UNPKG

@copilotkit/react-core

Version:

<div align="center"> <a href="https://copilotkit.ai" target="_blank"> <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/banner.png" alt="CopilotKit Logo"> </a>

1 lines 8.46 kB
{"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n ...(this.forwardedParameters ?? {}),\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;;;;;;AAgDA;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AA8BA,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBAAwB,OAAO,0BAA0B;AAC9D,SAAK,sBAAsB,OAAO;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AA5GpE;AA6GI,YAAM,UAAU,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,OAAO,IAAI,CAAC;AAGnF,iBAAW,MAAM,KAAK,SAAS;AAC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