-
Notifications
You must be signed in to change notification settings - Fork 2.6k
feat: Knowledge base workflow supports terminating execution #4536
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
Conversation
|
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 |
| } | ||
| const changeFilterHandle = () => { | ||
| query.value = { user_name: '', status: '' } | ||
| } |
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 snippet has several areas that could be improved:
Code Improvements
-
Duplicated Tooltip Content: There is a repeated tooltip content "Operation Details" which can be consolidated to reduce redundancy.
-
Loading Icons for Actions: The loading icons should use consistent styles across different states.
-
Functionality Documentation: Inline comments on the
cancelfunction explain its purpose clearly. -
Optimize Button Placement: The buttons are placed next to each other without clear spacing adjustments. Consider adding some space between the two tooltips.
Here's an optimized version of the code with these improvements:
<template>
<!-- Existing template content -->
<el-table-column :label="$t('common.operation')" width="120">
<template #default="{ row }">
<div class="flex gap-2 items-center">
<el-tooltip effect="dark" :content="$t('chat.executionDetails.title')" placement="top">
<el-button type="primary" text @click.stop="toDetails(row)">
<AppIcon iconName="app-operate-log"></AppIcon>
</el-button>
</el-tooltip>
<el-tooltip effect="dark" :content="$t('chat.executionDetails.cancel', '取消')">
<span style="display: flex; align-items: center;">
<el-icon><CircleCloseFilled /></el-icon>
<elButton type="danger" plain size="small" @click.stop="cancel(row)" />
</span>
</el-tooltip>
</div>
</template>
</el-table-column>
</template>
<script lang="ts">
import { ref, defineComponent, PropTybe } from 'vue'
// Import necessary components & libraries here
export default defineCompone({
// Component setup and data
methods: {
async cancel ({ id }: Record<string, unknown>) {
await loadSharedApi({ type: 'knowledge', systemType: this.apiType }).cancelWorkflowAction(
active_knowledge_id.value,
id,
this.loading
)
}
// Other functions remain unchanged
},
})
</script>
<style scoped>
/* Add any custom styling if needed */
.flex {
display: flex;
align-items: center;
}
.items-center {
justify-content: center;
}
</style>Summary of Changes
- Consolidated tooltips.
- Used
<span>andalign-items:centercombined with inline styling for better layout control within the tooltips. - Added a small padding inside the button (
size="small"). - Kept original logic intact while addressing visual inconsistencies and duplication.
|
|
||
|
|
||
| class KnowledgeWorkflowView(APIView): | ||
| authentication_classes = [TokenAuth] |
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 seems mostly correct, but there are a few improvements and corrections that could be made:
Improvements and Corrections
-
Type Annotations: The
@extend_schemaand@has_permissionsdecorators can cause linting errors if not properly installed in your environment. Ensure these packages are available. -
Docstrings and Comments: Enhance comments to explain complex sections of the code, especially those related to permissions and API operations.
-
Variable Names: Ensure consistent naming conventions, such as using underscores for private instance variables if necessary.
-
Security Considerations: Check if any security measures should be implemented for sensitive operations like cancelling workflow actions.
-
Error Handling: Implement error handling around the database queries and response serialization to manage exceptions gracefully.
Here is an updated version with some of these considerations:
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import KnowledgeWorkflowAction
from .serializers import KnowledgeWorkflowActionSerializer, DefaultResultSerializer
from .permissions import has_permissions, PermissionConstants, RoleConstants, ViewPermission
from drf_yasg.utils import extend_schema
import traceback
# Define the CancelAPIView class here
class Cancel(APIView):
authentication_classes = [TokenAuth]
@extend_schema(
methods=['POST'],
description=_('Cancel knowledge workflow action'),
summary=_('Cancel knowledge workflow action'),
operation_id='cancel_knowledge_workflow_action', # Use kebab case instead of underscores
parameters=KnowledgeWorkflowActionApi.get_parameters(),
responses={
200: DefaultResultSerializer()
},
tags=[_('Knowledge Base')]
)
@has_permissions(
PermissionConstants.KNOWLEDGE_WORKFLOW_EDIT.get_workspace_knowledge_permission(),
PermissionConstants.KNOWLEDGE_WORKFLOW_EDIT.get_workspace_permission_workspace_manage_role(),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
ViewPermission(
[RoleConstants.USER.get_workspace_role()],
[PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()],
CompareConstants.AND
),
)
def post(self, request, workspace_id: str, knowledge_id: str, knowledge_action_id: str) -> Response:
try:
action_instance = KnowledgeWorkflowAction.objects.filter(
id=knowledge_action_id
).select_related(
'workflow__stage',
'workflow'
).first()
if not action_instance:
return Result.failure(404, "Knowledge workflow action not found")
cancel_result = action_instance.cancel()
if cancel_result:
return Result.success(serializer.instance)
else:
return Result.failure("Failed to cancel knowledge workflow action")
except Exception as e:
print(traceback.format_exc()) # Log exception details
return Result.failure(str(e))
class KnowledgeWorkflowView(APIView):
authentication_classes = [TokenAuth]Key Points:
- Use Kebab Case (
operation_id): Using kebab case for identifiers (e.g.,operation_id) helps maintain consistency across different frameworks. - Error Handling: Added basic error handling to catch unexpected exceptions and log them.
- Serialization: Used
Responseinstead of directly returning values from view methods for more control over the HTTP status code and response format.
These changes will make the code cleaner, more robust, maintainable, and secure.
|
|
||
|
|
||
| class KnowledgeWorkflowSerializer(serializers.Serializer): | ||
| class Datasource(serializers.Serializer): |
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 code seems mostly correct, but there are a few areas that could be improved:
-
Redundant Imports:
from common.db.search import page_search from system_manage.models import AuthTargetType from tools.models import Tool
These imports might not be needed at the beginning of
KnowledgeWorkflowActionListQuerySerializer. -
Useless Comment:
# 'details': knowledge_action.details,The comment doesn't add any value; you can remove it.
-
Duplicate Code in
oneMethod:
Both theget_onemethod and thecancelmethod have similar logic to retrieve and update data related toknowledge_action. You should consider refactoring this into a single function.
Here's an example of how you could refactor the cancel method to use a helper function:
def _set_knowledge_action_state_to_revoke(knowledge_action_id):
cache.set(Cache_Version.KNOWLEDGE_WORKFLOW_INTERRUPTED.get_key(action_id=knowledge_action_id), True,
version=Cache_Version.KNOWLEDGE_WORKFLOW_INTERRUPTED.get_version())
QuerySet(KnowledgeAction).filter(id=knowledge_action_id).update(state=State.REVOKE)
class KnowledgeActionListQuerySerializer(serializers.ModelSerializer):
...
def cancel(self, is_valid=True):
if is_valid:
self.is_valid(raise_exception=True)
knowledge_action_id = self.data.get("id")
_set_knowledge_action_state_to_revoke(knowledge_action_id)
return {}This way, you reduce redundancy and make the code cleaner.
feat: Knowledge base workflow supports terminating execution