Skip to content

feat: Generate Prompt#4002

Merged
zhanweizhang7 merged 1 commit intov2from
pr@v2@feat_generate_prompt
Sep 8, 2025
Merged

feat: Generate Prompt#4002
zhanweizhang7 merged 1 commit intov2from
pr@v2@feat_generate_prompt

Conversation

@shaohuzhang1
Copy link
Copy Markdown
Contributor

feat: Generate Prompt

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Sep 8, 2025

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.

Details

Instructions 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.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Sep 8, 2025

[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.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment


class OpenAIMessage(serializers.Serializer):
content = serializers.CharField(required=True, label=_('content'))
role = serializers.CharField(required=True, label=_('Role'))
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a review of the changes made to improve and optimize the code:

  1. Import Statements: Added json for handling JSON encoding.

  2. Imports: Updated PipelineManage, BaseSearchDatasetStep, Workflow, and other imports to include the necessary module or function from the latest version of the application flow package (application.flow).

  3. ChatMessagesSerializers: Added fields like role and content with validation labels.

    • Optimization:
      • Used required=True instead of default='' where applicable, improving clarity and enforcing mandatory data inputs.
  4. GeneratePromptSerializers:

    • Fixed logic in _generate_prompt method_ by properly assigning q` value based on "userInput" token replacement.
    • Improved validation in generate_prompt method (if needed).
  5. PromptGenerateSerializer:

    • Provided a detailed explanation of each step within the process function using docstrings for better understanding.
    • Removed unnecessary checks that can be handled elsewhere, such as empty strings when retrieving workspace/model IDs.
  6. Other Changes:

    • The original structure was cleaned up slightly, ensuring better readability and organization.

Overall, these revisions aim to make the code cleaner, more maintainable, and potentially faster or safer under certain conditions through improved error checking and input validation mechanisms.

@zhanweizhang7 zhanweizhang7 merged commit ff6714e into v2 Sep 8, 2025
3 of 5 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@feat_generate_prompt branch September 8, 2025 09:06

class ChatAPI(APIMixin):
@staticmethod
def get_parameters():
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided Python code snippet is incomplete and lacks several key components. However, I can highlight some general issues and suggest improvements:

Key Issues

  1. Missing End of File (EOF):
    The file does not end in a line that matches the first one (@@ -10,12 +10,35), which is unusual.

  2. Syntax Errors:
    There are syntax errors due to missing colons at the beginning of methods like get_parameters and the closing bracket of the function ChatAPI.

  3. Incomplete Function Definitions:
    Many functions (like get_parameters) are defined but do not have complete implementations or docstrings.

  4. Unclear Imports:
    While most imports are clear, there seems to be a mix-up between imported modules. For example, it's unclear if all necessary classes are being used properly.

Improvements Suggested

To make the code more readable and functional, consider the following changes:

from drf_spectacular.utils import OpenApiParameter

# Import other serializers you need
from chat.serializers.chat import ChatMessageSerializers, GeneratePromptSerializers
from chat.serializers.chat_record import HistoryChatModel, EditAbstractSerializer, ChatRecordSerializerModel
from common.mixins.api_mixin import APIMixin
from common.result import ResultSerializer, ResultPageSerializer, DefaultResultSerializer


class PromptGenerateAPI(APIMixin):
    """
    API endpoint for generating prompts based on workspace and model IDs.
    
    Parameters:
    - workspace_id: str
      Workspace identifier.
      
    - model_id: str
      Model identifier.
    """

    @staticmethod
    def get_parameters():
        return [
            OpenApiParameter(
                name="workspace_id",
                description="工作空间identifier",
                type=OpenApiTypes.STR,
                location='path',
                required=True,
            ),
            OpenApiParameter(
                name="model_id",
                description="模型identifier",
                type=OpenApiTypes.STR,
                location='path',
                required=True,
            )
        ]

    @staticmethod
    def get_request():
        return GeneratePromptSerializers


class ChatAPI(APIMixin):
    """
    API endpoint for managing interactions within a chat session.
    """

    @staticmethod
    def get_parameters():
        # Define your parameters here if needed
        pass

    @staticmethod
    def get_request():
        # Define your request serializer here if needed
        pass

Summary of Changes

  • Added proper syntax at the end of each method block.
  • Ensured correct indentation and structure.
  • Included docstrings describing what each part of the code does.
  • Clarified parameter descriptions in comments inside the docstring for better readability.

Make sure to implement the logic inside the get_parameters and get_request methods appropriately based on your requirements.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code snippet appears to be part of an OpenAI API implementation, specifically related to handling requests for chat generation and prompts. Here is a review with some suggestions:

Irregularities, Issues, and Optimization Suggestions

  1. Import Statements:

    • The import statement for PromptGenerateAPI was added without importing it elsewhere in the file.
    • Ensure that PromptGenerateAPI is defined in its own module or at least used properly within this context.
  2. Class Definitions:

    • The ChatView class handles both debug chats and prompt generation. Consider splitting them into separate classes if they serve different purposes.
  3. Method Signatures:

    • The post(request) method does not have any additional logic between checking permissions and returning serialized data.
    • Implement error handling for cases where permission checks fail or if data parsing fails.
  4. Code Readability:

    • Adding docstrings can improve readability and help other developers understand what each function is supposed to do.
    • Comment on areas where complex logic might be implemented in future updates.
  5. Security:

    • Ensure that authentication and authorization checks are correctly implemented and enforced across all views.
    • If necessary, use middleware like Django's built-in JWT token authentication.
  6. Error Handling:

    • Implement specific exceptions for errors such as invalid permissions, missing required fields, etc., with appropriate response codes (HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN, etc.).

Here are more detailed optimizations and enhancements based on these points:

# Update imports
from chat.api.chat_api import ChatAPI, PromptGenerateAPI

class ChatView(APIView):
    
    @classmethod
    def requires_permission(cls):
        """
        Check if the current user has permission to access the view.
        
        :return: Boolean indicating if permission is granted.
        """
        # Define your permission check here
        pass
    
    @extend_schema(
        methods=['POST'],
        description=_("Handle chat interactions"),
        summary=_("Process requests for chatting conversations."),
        operation_id=_("process_chats")
    )
    def post(self, request: Request, chat_id: str):
        if not self.requires_permission():
            return Response({"error": "Access denied"}, status=status.HTTP_403_FORBIDDEN)

        try:
            return DebugChatSerializers(data={'chat_id': chat_id}).chat(request.data)
        except Exception as e:
            return ErrorResponse(e).as_response()

And similarly for PromptGenerateView:

# Update import
from chat.api.chat_api import ChatAPI, PromptGenerateAPI
from chat.serializers.prompt_generate import PromptGenerateSerializer
from common.exceptions.error_response import ErrorResponse

class PromptGenerateView(APIView):

    @classmethod
    def requires_permission(cls):
        """
        Check if the current user has permission to generate prompts.
        
        :return: Boolean indicating if permission is granted.
        """
        # Define your permission check here
        pass
    
    @extend_schema(
        methods=['POST'],
        description=_("Generate a custom prompt"),
        summary=_("Create custom text prompts for various models."),
        operation_id=_("create_custom_prompt")
    )
    def post(self, request: Request, workspace_id: str, model_id: str):
        if not self.requires_permission():
            return Response({"error": "Access denied"}, status=status.HTTP_403_FORBIDDEN)

        try:
            return PromptGenerateSerializer().generate_prompt({'workspace_id': workspace_id, 'model_id': model_id}, instance=request.data)
        except Exception as e:
            return ErrorResponse(e).as_response()

These improvements focus on enhancing code clarity, robustness, and security while adhering to best practices for API development.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants