{"version":3,"sources":["../src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx"],"sourcesContent":["import { AI_CLOUD_PUBLIC_API_KEY_HEADER } from \"@vn-sdk/shared\";\nimport { useAiContext } from \"@vn-sdk/react-core\";\nimport { useCallback } from \"react\";\nimport {\n  AiRuntimeClient,\n  Message,\n  Role,\n  TextMessage,\n  convertGqlOutputToMessages,\n  convertMessagesToGqlInput,\n  filterAgentStateMessages,\n  AiRequestType,\n} from \"@vn-sdk/runtime-client-gql\";\nimport { retry } from \"../../lib/retry\";\nimport {\n  EditingEditorState,\n  Generator_InsertionOrEditingSuggestion,\n} from \"../../types/base/autosuggestions-bare-function\";\nimport { InsertionsApiConfig } from \"../../types/autosuggestions-config/insertions-api-config\";\nimport { EditingApiConfig } from \"../../types/autosuggestions-config/editing-api-config\";\nimport { DocumentPointer } from \"@vn-sdk/react-core\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardInsertionOrEditingFunction(\n  textareaPurpose: string,\n  contextCategories: string[],\n  insertionApiConfig: InsertionsApiConfig,\n  editingApiConfig: EditingApiConfig,\n): Generator_InsertionOrEditingSuggestion {\n  const { getContextString, aiApiConfig, runtimeClient } = useAiContext();\n  const headers = {\n    ...(aiApiConfig.publicApiKey\n      ? { [AI_CLOUD_PUBLIC_API_KEY_HEADER]: aiApiConfig.publicApiKey }\n      : {}),\n  };\n\n  async function runtimeClientResponseToStringStream(\n    responsePromise: ReturnType<typeof runtimeClient.generateCopilotResponse>,\n  ) {\n    const messagesStream = runtimeClient.asStream(responsePromise);\n\n    return new ReadableStream({\n      async start(controller) {\n        const reader = messagesStream.getReader();\n        let sentContent = \"\";\n\n        while (true) {\n          const { done, value } = await reader.read();\n          if (done) {\n            break;\n          }\n\n          const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n          let newContent = \"\";\n\n          for (const message of messages) {\n            if (message.isTextMessage()) {\n              newContent += message.content;\n            }\n          }\n          if (newContent) {\n            const contentToSend = newContent.slice(sentContent.length);\n            controller.enqueue(contentToSend);\n            sentContent += contentToSend;\n          }\n        }\n        controller.close();\n      },\n    });\n  }\n\n  const insertionFunction = useCallback(\n    async (\n      editorState: EditingEditorState,\n      insertionPrompt: string,\n      documents: DocumentPointer[],\n      abortSignal: AbortSignal,\n    ) => {\n      const res = await retry(async () => {\n        const messages: Message[] = [\n          new TextMessage({\n            role: Role.System,\n            content: insertionApiConfig.makeSystemPrompt(\n              textareaPurpose,\n              getContextString(documents, contextCategories),\n            ),\n          }),\n          ...insertionApiConfig.fewShotMessages,\n          new TextMessage({\n            role: Role.User,\n            content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n          }),\n          new TextMessage({\n            role: Role.User,\n            content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n          }),\n          new TextMessage({\n            role: Role.User,\n            content: `<InsertionPrompt>${insertionPrompt}</InsertionPrompt>`,\n          }),\n        ];\n\n        return runtimeClientResponseToStringStream(\n          runtimeClient.generateCopilotResponse({\n            data: {\n              frontend: {\n                actions: [],\n                url: window.location.href,\n              },\n              messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n              metadata: {\n                requestType: AiRequestType.TextareaCompletion,\n              },\n            },\n            properties: aiApiConfig.properties,\n            signal: abortSignal,\n          }),\n        );\n      });\n\n      return res;\n    },\n    [insertionApiConfig, getContextString, contextCategories, textareaPurpose],\n  );\n\n  const editingFunction = useCallback(\n    async (\n      editorState: EditingEditorState,\n      editingPrompt: string,\n      documents: DocumentPointer[],\n      abortSignal: AbortSignal,\n    ) => {\n      const res = await retry(async () => {\n        const messages: Message[] = [\n          new TextMessage({\n            role: Role.System,\n            content: editingApiConfig.makeSystemPrompt(\n              textareaPurpose,\n              getContextString(documents, contextCategories),\n            ),\n          }),\n          ...editingApiConfig.fewShotMessages,\n          new TextMessage({\n            role: Role.User,\n            content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n          }),\n          new TextMessage({\n            role: Role.User,\n            content: `<TextToEdit>${editorState.selectedText}</TextToEdit>`,\n          }),\n          new TextMessage({\n            role: Role.User,\n            content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n          }),\n          new TextMessage({\n            role: Role.User,\n            content: `<EditingPrompt>${editingPrompt}</EditingPrompt>`,\n          }),\n        ];\n\n        return runtimeClientResponseToStringStream(\n          runtimeClient.generateCopilotResponse({\n            data: {\n              frontend: {\n                actions: [],\n                url: window.location.href,\n              },\n              messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n              metadata: {\n                requestType: AiRequestType.TextareaCompletion,\n              },\n            },\n            properties: aiApiConfig.properties,\n            signal: abortSignal,\n          }),\n        );\n      });\n\n      return res;\n    },\n    [editingApiConfig, getContextString, contextCategories, textareaPurpose],\n  );\n\n  const insertionOrEditingFunction = useCallback(\n    async (\n      editorState: EditingEditorState,\n      insertionPrompt: string,\n      documents: DocumentPointer[],\n      abortSignal: AbortSignal,\n    ) => {\n      if (editorState.selectedText === \"\") {\n        return await insertionFunction(editorState, insertionPrompt, documents, abortSignal);\n      } else {\n        return await editingFunction(editorState, insertionPrompt, documents, abortSignal);\n      }\n    },\n    [insertionFunction, editingFunction],\n  );\n\n  return insertionOrEditingFunction;\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,sCAAsC;AAC/C,S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