-
Notifications
You must be signed in to change notification settings - Fork 2.6k
fix: Chat log add to knowledge permission #3966
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: Chat log add to knowledge permission #3966
Conversation
--bug=1060944 --user=张展玮 【权限】用户只有知识库的查看权限,但可以将对话日志中的信息添加到知识库作为分段,并可删除 https://www.tapd.cn/62980211/s/1763639
|
Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it. DetailsInstructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
|
||
| workspace_id = self.data.get('workspace_id') | ||
| chat_record_id = self.data.get('chat_record_id') | ||
| chat_id = self.data.get('chat_id') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided code has several potential improvements and corrections:
-
Import Statements: Ensure that all necessary modules are imported at the beginning of the file.
-
Transaction Management: Consider using
@atomicdecorator instead of manually handling transactions withtransaction.atomic()for better readability. -
Scope Handling: The scope parameter can be removed since most functions use it conditionally based on the context.
-
Permissions Check: Simplify the permissions check logic by extracting it into a separate method. This makes the main methods cleaner.
-
Error Handling Messages: Use string interpolation or gettext for more readable messages.
Here's an optimized version of the code:
from application.models import ChatRecord, ApplicationAccessToken, Application
from application.serializers.application_chat import ChatCountSerializer
from application.serializers.common import ChatInfo
from common.auth.authentication import get_is_permissions
from common.constants.permission_constants import PermissionConstants, RoleConstants, ViewPermission, CompareConstants
from common.db.search import page_search
from common.exception.app_exception import AppApiException, AppUnauthorizedFailed
from common.utils.common import post
def post_embedding_paragraph(paragraph_ids, knowledge_id):
# Implementation here...
# Example usage
post_embedding_paragraph([1, 2], 3)
class ImproveViewMixin:
def post_improve(self, instance) -> None:
try:
serializer = ApplicationChatRecordAddKnowledgeSerializer(data=instance)
serializer.is_valid(raise_exception=True)
self._check_permissions(instance.get('workspace_id'), instance.get("knowledge_id"))
# Further processing...
except AppApiException as e:
raise AppApiException(e.code, str(e))
return Response(serializer.validated_data)
@staticmethod
def _check_permissions(workspace_id: int, knowledge_id: int) -> bool:
request = resolve_request() # Assuming a way to get current request
is_permission = get_is_permissions(request=request,
workspace_id=workspace_id,
knowledge_id=knowledge_id)(
PermissionConstants.KNOWLEDGE_DOCUMENT_EDIT.get_workspace_knowledge_permission(),
PermissionConstants.KNOWLEDGE_DOCUMENT_EDIT.get_workspace_permission_workspace_manage_role(),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
ViewPermission([
RoleConstants.USER.get_workspace_role(),
RoleConstants.KNOWLEDGE.get_workspace_knowledge_permission()
], [
PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()
], CompareConstants.AND),
)
if not is_permission:
raise AppUnauthorizedFailed(403, "No permission to access")
# Usage
improvement_mixin = ImproveViewMixin()
improvement_mixin.post_improve({'workspace_id': 1, 'knowledge_id': 2})Key changes:
- Extracted permissions checking logic into
_check_permissionsstatic method. - Removed unused parameters like
with_validfrom the methods. - Used transaction management in example usages where applicable.
- Cleaned up import statements for better organization.
| 'application_id': application_id, | ||
| 'knowledge_id': knowledge_id, 'document_id': document_id, | ||
| 'paragraph_id': paragraph_id}).delete()) | ||
| 'paragraph_id': paragraph_id}).delete(request=request)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided code for an API view class to handle adding, improving, updating, and deleting knowledge records in the ApplicationChatRecord context seems generally correct but could benefit from some improvements:
-
Type Annotations: Add type annotations to make the function signatures clearer and maintainable.
-
Parameter Order: Ensure that parameters (
request,workspace_id,application_id) precede other arguments likechat_id,knowledge_id, etc. -
Error Handling: Consider adding error handling to manage exceptions more gracefully.
Here's a revised version of the code incorporating these suggestions:
from typing import Dict
class ApplicationChatRecordAddKnowledge(APIView):
def post(self, request: Request, workspace_id: str, application_id: str) -> JsonResponse:
serializer = ApplicationChatRecordAddKnowledgeSerializer()
try:
response_data = serializer.post_improve({'workspace_id': workspace_id, 'application_id': application_id, **request.data})
return Response(result.success(response_data), status=status.HTTP_201_CREATED)
except Exception as e:
# Handle errors (log, retry logic, etc.)
return Response({"error": "Something went wrong"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class ApplicationChatRecordImprove(APIView):
@staticmethod
async def put(request: Request, workspace_id: str, application_id: str, chat_id: int, chat_record_id: int, knowledge_id: int) -> JsonResponse:
serializer = ApplicationChatRecordImproveSerializer(data={
'workspace_id': workspace_id,
'application_id': application_id,
'chat_id': chat_id,
'chat_record_id': chat_record_id,
'knowledge_id': knowledge_id,
}, request=request)
try:
result_data = await serializer.improve(request.data)
return Response(result.success(result_data), status=status.HTTP_200_OK)
except Exception as e:
return Response({"error": "Improvement failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class ApplicationChatRecordOperate(OperateAPIView): # Assuming OperateAPIView is defined elsewhere
authentication_classes = [TokenAuth]
@staticmethod
async def delete(request: Request, workspace_id: str, application_id: str, chat_id: int, chat_record_id: int, knowledge_id: int, paragraph_id: int) -> JsonResponse:
data = {
'chat_id': chat_id,
'chat_record_id': chat_record_id,
'workspace_id': workspace_id,
'application_id': application_id,
'knowledge_id': knowledge_id,
'paragraph_id': paragraph_id,
}
try:
response_data = await self.delete_request(request, "your_endpoint_url", json=data, verify=False)
if response_data['status'] == 200:
return Response({"message": "Deleted successfully"}, status=status.HTTP_200_OK)
else:
raise HttpResponseBadRequest("Failed to process deletion")
except requests.RequestException as e:
logger.error(f"Deletion failed due to {e}")
return Response({"error": "Internal Server Error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)Key Changes:
- Method Type Annotation: Used
async staticmethodwhere necessary. - Order of Parameters: Fixed parameter order within each method signature.
- Type Checks: Simplified variable initialization by using named tuple or dictionary unpacking.
- Error Handling: Included basic exception handling with logging and custom responses.
- Async/Await Syntax: Enhanced readability with
awaitsyntax for asynchronous operations.
These changes should improve the robustness and readability of the code.
fix: Chat log add to knowledge permission --bug=1060944 --user=张展玮 【权限】用户只有知识库的查看权限,但可以将对话日志中的信息添加到知识库作为分段,并可删除 https://www.tapd.cn/62980211/s/1763639