AI-NEWS · 2024年 10月 26日

用 AI 反向代码案例:揭秘 OpenAI Canvas 如何根据用户操作拼接生成 Prompt

The provided code snippet outlines a function handleUserOperation and its related functions in the context of a text document editor system, where users can perform various actions on documents such as editing or commenting. The system aims to generate prompts for an AI service (like ChatGPT) based on user selections within the text documents.

Here's a breakdown of the key components:

  1. Enums:

    • UserActionType: Defines different types of user actions, such as ASK, EDIT, COMMENT, and CREATETEXTDOC.
    • UserMessageType: Describes the type of message being sent to or from the AI service.
    • SelectionType: Categorizes how text is selected (ENTIREDOCUMENT, SELECTEDTEXT, SURROUNDINGCONTEXT).
    • TextdocType: Specifies types of documents, with an example given as DOCUMENT.
  2. Interfaces:

    • SourceRange: Represents a range within the document content using start and end positions.
    • TextdocVersion: Holds metadata about the text document version.
    • AcceleratorMetadata: Metadata for accelerators that might be used to speed up certain operations.
    • SelectionMetadata: Contains details on how text is selected.
  3. Functions:

    • handleUserOperation: Main function that processes user requests, extracting relevant information from a text document and generating appropriate prompts based on the selection type (entire document, selected text, or surrounding context).
    • generatePrompt: A helper function called by handleUserOperation to generate specific prompts for different actions.
    • extractSurroundingContext: Extracts context around a given range in the document.
    • sendPromptRequest: Sends the generated prompt to an AI service.
  4. Flow of Functions:

    • The flow starts with handleUserOperation, which extracts the selected text and surrounding context based on the provided source range.
    • It then calls generatePrompt to create a custom prompt for the given action and selection type.
    • Finally, it sends this generated prompt to an external AI service via sendPromptRequest.
  5. Additional Instructions:

    • Functions like additionalInstructions and generateUpdateInstructions provide rules on how text should be modified when updating based on the document type (e.g., fully rewriting sections if certain conditions are met).
  6. Diagram Explanation:

    • The diagram illustrates that handleUserOperation is responsible for orchestrating interactions between generating prompts and sending requests to an external AI service.
    • It includes a breakdown of how source ranges, selected text, and surrounding contexts are managed.

This system provides a structured approach to handling user interactions with documents and leveraging AI services for tasks such as editing or commenting.

Source:https://baoyu.io/blog/ai/reverse-engineering-openai-canvas-prompt-generation