@copilotkit/runtime 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/{chunk-NJUL6GAV.mjs → chunk-6PAC74F2.mjs} +2 -2
- package/dist/{chunk-BOAAK6EY.mjs → chunk-74B76SMO.mjs} +2 -2
- package/dist/{chunk-YJAUWNAJ.mjs → chunk-MKV3LEJ6.mjs} +2 -2
- package/dist/{chunk-YJAUWNAJ.mjs.map → chunk-MKV3LEJ6.mjs.map} +1 -1
- package/dist/{chunk-AMCK7MAH.mjs → chunk-NPCP4YZB.mjs} +2 -2
- package/dist/{chunk-RO5NLPB3.mjs → chunk-RDEOIOQR.mjs} +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +5 -5
- package/dist/lib/index.js +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +5 -5
- package/dist/lib/integrations/index.js +1 -1
- package/dist/lib/integrations/index.js.map +1 -1
- package/dist/lib/integrations/index.mjs +4 -4
- package/dist/lib/integrations/nest/index.js +1 -1
- package/dist/lib/integrations/nest/index.js.map +1 -1
- package/dist/lib/integrations/nest/index.mjs +2 -2
- package/dist/lib/integrations/node-express/index.js +1 -1
- package/dist/lib/integrations/node-express/index.js.map +1 -1
- package/dist/lib/integrations/node-express/index.mjs +2 -2
- package/dist/lib/integrations/node-http/index.js +1 -1
- package/dist/lib/integrations/node-http/index.js.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs +1 -1
- package/package.json +2 -2
- /package/dist/{chunk-NJUL6GAV.mjs.map → chunk-6PAC74F2.mjs.map} +0 -0
- /package/dist/{chunk-BOAAK6EY.mjs.map → chunk-74B76SMO.mjs.map} +0 -0
- /package/dist/{chunk-AMCK7MAH.mjs.map → chunk-NPCP4YZB.mjs.map} +0 -0
- /package/dist/{chunk-RO5NLPB3.mjs.map → chunk-RDEOIOQR.mjs.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../src/index.ts","../src/lib/copilot-runtime.ts","../src/service-adapters/openai/openai-adapter.ts","../src/graphql/types/base/index.ts","../src/graphql/types/converted/index.ts","../src/service-adapters/openai/utils.ts","../src/service-adapters/openai/openai-assistant-adapter.ts","../src/service-adapters/google/google-genai-adapter.ts","../src/service-adapters/google/utils.ts","../src/service-adapters/langchain/utils.ts","../src/service-adapters/langchain/langchain-adapter.ts","../src/service-adapters/langchain/langserve.ts","../src/service-adapters/unify/unify-adapter.ts","../src/service-adapters/groq/groq-adapter.ts","../src/service-adapters/events.ts","../src/service-adapters/conversion.ts","../src/lib/integrations/shared.ts","../src/graphql/resolvers/copilot.resolver.ts","../src/graphql/inputs/generate-copilot-response.input.ts","../src/graphql/inputs/message.input.ts","../src/graphql/types/enums.ts","../src/graphql/inputs/frontend.input.ts","../src/graphql/inputs/action.input.ts","../src/graphql/inputs/cloud.input.ts","../src/graphql/inputs/cloud-guardrails.input.ts","../src/graphql/inputs/forwarded-parameters.input.ts","../src/graphql/types/copilot-response.type.ts","../src/graphql/types/message-status.type.ts","../src/graphql/types/response-status.type.ts","../src/utils/failed-response-status-reasons.ts","../src/lib/telemetry-client.ts","../src/lib/logger.ts","../src/lib/integrations/nextjs/app-router.ts","../src/lib/integrations/nextjs/pages-router.ts","../src/lib/integrations/node-http/index.ts","../src/lib/integrations/node-express/index.ts","../src/lib/integrations/nest/index.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/runtime\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.1.1\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"dev\": \"tsup --watch --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__\",\n \"generate-graphql-schema\": \"rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts\"\n },\n \"devDependencies\": {\n \"@swc/core\": \"1.5.28\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jest\": \"^29.5.4\",\n \"@types/node\": \"^18.11.17\",\n \"@whatwg-node/server\": \"^0.9.34\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"nodemon\": \"^3.1.3\",\n \"ts-jest\": \"^29.1.1\",\n \"ts-node\": \"^10.9.2\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\"\n },\n \"dependencies\": {\n \"@copilotkit/shared\": \"workspace:*\",\n \"@google/generative-ai\": \"^0.11.2\",\n \"@graphql-yoga/plugin-defer-stream\": \"^3.3.1\",\n \"@langchain/community\": \"^0.0.53\",\n \"@langchain/core\": \"^0.1.61\",\n \"@langchain/openai\": \"^0.0.28\",\n \"class-transformer\": \"^0.5.1\",\n \"express\": \"^4.19.2\",\n \"graphql\": \"^16.8.1\",\n \"graphql-scalars\": \"^1.23.0\",\n \"graphql-yoga\": \"^5.3.1\",\n \"groq-sdk\": \"^0.5.0\",\n \"langchain\": \"^0.1.36\",\n \"openai\": \"^4.50.0\",\n \"pino\": \"^9.2.0\",\n \"pino-pretty\": \"^11.2.1\",\n \"reflect-metadata\": \"^0.2.2\",\n \"rxjs\": \"^7.8.1\",\n \"type-graphql\": \"2.0.0-rc.1\",\n \"zod\": \"^3.23.3\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import \"reflect-metadata\";\nexport * from \"./lib\";\nexport * from \"./utils\";\n","/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport { Action, actionParametersToJsonSchema, Parameter } from \"@copilotkit/shared\";\nimport { RemoteChain, RemoteChainParameters, CopilotServiceAdapter } from \"../service-adapters\";\nimport { MessageInput } from \"../graphql/inputs/message.input\";\nimport { ActionInput } from \"../graphql/inputs/action.input\";\nimport { RuntimeEventSource } from \"../service-adapters/events\";\nimport { convertGqlInputToMessages } from \"../service-adapters/conversion\";\nimport { Message } from \"../graphql/types/converted\";\nimport { ForwardedParametersInput } from \"../graphql/inputs/forwarded-parameters.input\";\n\ninterface CopilotRuntimeRequest {\n serviceAdapter: CopilotServiceAdapter;\n messages: MessageInput[];\n actions: ActionInput[];\n outputMessagesPromise: Promise<Message[]>;\n properties: any;\n threadId?: string;\n runId?: string;\n publicApiKey?: string;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface CopilotRuntimeResponse {\n threadId: string;\n runId?: string;\n eventSource: RuntimeEventSource;\n actions: Action<any>[];\n}\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n}\n\ntype OnBeforeRequestHandler = (options: OnBeforeRequestOptions) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n}\n\ntype OnAfterRequestHandler = (options: OnAfterRequestOptions) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed.\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n}\n\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n public actions: ActionsConfiguration<T>;\n private langserve: Promise<Action<any>>[] = [];\n private onBeforeRequest?: OnBeforeRequestHandler;\n private onAfterRequest?: OnAfterRequestHandler;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n this.actions = params?.actions || [];\n\n for (const chain of params?.langserve || []) {\n const remoteChain = new RemoteChain(chain);\n this.langserve.push(remoteChain.toAction());\n }\n\n this.onBeforeRequest = params?.middleware?.onBeforeRequest;\n this.onAfterRequest = params?.middleware?.onAfterRequest;\n }\n\n async process(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {\n const {\n serviceAdapter,\n messages,\n actions: clientSideActionsInput,\n threadId,\n runId,\n properties,\n outputMessagesPromise,\n forwardedParameters,\n } = request;\n const langserveFunctions: Action<any>[] = [];\n\n for (const chainPromise of this.langserve) {\n try {\n const chain = await chainPromise;\n langserveFunctions.push(chain);\n } catch (error) {\n console.error(\"Error loading langserve chain:\", error);\n }\n }\n\n const configuredActions =\n typeof this.actions === \"function\" ? this.actions({ properties }) : this.actions;\n\n const actions = [...configuredActions, ...langserveFunctions];\n\n const serverSideActionsInput: ActionInput[] = actions.map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const actionInputs = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...clientSideActionsInput,\n ]);\n const inputMessages = convertGqlInputToMessages(messages);\n\n await this.onBeforeRequest?.({\n threadId,\n runId,\n inputMessages,\n properties,\n });\n\n try {\n const eventSource = new RuntimeEventSource();\n\n const result = await serviceAdapter.process({\n messages: inputMessages,\n actions: actionInputs,\n threadId,\n runId,\n eventSource,\n forwardedParameters,\n });\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId: result.threadId,\n runId: result.runId,\n inputMessages,\n outputMessages,\n properties,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId: result.threadId,\n runId: result.runId,\n eventSource,\n actions: actions,\n };\n } catch (error) {\n console.error(\"Error getting response:\", error);\n throw error;\n }\n }\n}\n\nexport function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {\n let allTools: ActionInput[] = [];\n const allToolNames: string[] = [];\n for (const tool of toolsByPriority) {\n if (!allToolNames.includes(tool.name)) {\n allTools.push(tool);\n allToolNames.push(tool.name);\n }\n }\n return allTools;\n}\n","/**\n * Copilot Runtime adapter for OpenAI.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, OpenAIAdapter } from \"@copilotkit/runtime\";\n * import OpenAI from \"openai\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const openai = new OpenAI({\n * organization: \"<your-organization-id>\", // optional\n * apiKey: \"<your-api-key>\",\n * });\n *\n * const serviceAdapter = new OpenAIAdapter({ openai });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport OpenAI from \"openai\";\nimport {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToOpenAITool,\n convertMessageToOpenAIMessage,\n limitMessagesToTokenCount,\n} from \"./utils\";\nimport { randomId } from \"@copilotkit/shared\";\n\nconst DEFAULT_MODEL = \"gpt-4o\";\n\nexport interface OpenAIAdapterParams {\n /**\n * An optional OpenAI instance to use. If not provided, a new instance will be\n * created.\n */\n openai?: OpenAI;\n\n /**\n * The model to use.\n */\n model?: string;\n}\n\nexport class OpenAIAdapter implements CopilotServiceAdapter {\n private model: string = DEFAULT_MODEL;\n\n private _openai: OpenAI;\n public get openai(): OpenAI {\n return this._openai;\n }\n\n constructor(params?: OpenAIAdapterParams) {\n this._openai = params?.openai || new OpenAI({});\n if (params?.model) {\n this.model = params.model;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const {\n threadId,\n model = this.model,\n messages,\n actions,\n eventSource,\n forwardedParameters,\n } = request;\n const tools = actions.map(convertActionInputToOpenAITool);\n\n let openaiMessages = messages.map(convertMessageToOpenAIMessage);\n openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);\n\n let toolChoice: any = forwardedParameters?.toolChoice;\n if (forwardedParameters?.toolChoice === \"function\") {\n toolChoice = {\n type: \"function\",\n function: { name: forwardedParameters.toolChoiceFunctionName },\n };\n }\n\n const stream = this.openai.beta.chat.completions.stream({\n model: model,\n stream: true,\n messages: openaiMessages,\n ...(tools.length > 0 && { tools }),\n ...(forwardedParameters?.maxTokens && { max_tokens: forwardedParameters.maxTokens }),\n ...(forwardedParameters?.stop && { stop: forwardedParameters.stop }),\n ...(toolChoice && { tool_choice: toolChoice }),\n });\n\n eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n for await (const chunk of stream) {\n const toolCall = chunk.choices[0].delta.tool_calls?.[0];\n const content = chunk.choices[0].delta.content;\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCall?.id is defined, it means a new tool call starts.\n if (mode === \"message\" && toolCall?.id) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (toolCall === undefined || toolCall?.id)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (toolCall?.id) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCall!.id, toolCall!.function!.name);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(chunk.id);\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCall?.function?.arguments) {\n eventStream$.sendActionExecutionArgs(toolCall.function.arguments);\n }\n }\n\n // send the end events\n if (mode === \"message\") {\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd();\n }\n\n eventStream$.complete();\n });\n\n return {\n threadId: threadId || randomId(),\n };\n }\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessage {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import {\n ActionExecutionMessageInput,\n ResultMessageInput,\n TextMessageInput,\n} from \"../../inputs/message.input\";\nimport { BaseMessage } from \"../base\";\nimport { ActionExecutionScope, MessageRole } from \"../enums\";\n\nexport class TextMessage extends BaseMessage implements TextMessageInput {\n content: string;\n role: MessageRole;\n}\n\nexport type Message = BaseMessage;\n\nexport class ActionExecutionMessage\n extends BaseMessage\n implements Omit<ActionExecutionMessageInput, \"arguments\">\n{\n name: string;\n arguments: Record<string, any>;\n scope: ActionExecutionScope;\n}\n\nexport class ResultMessage extends BaseMessage implements ResultMessageInput {\n actionExecutionId: string;\n actionName: string;\n result: string;\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { ChatCompletionMessageParam, ChatCompletionTool } from \"openai/resources\";\n\nexport function limitMessagesToTokenCount(\n messages: any[],\n tools: any[],\n model: string,\n maxTokens?: number,\n): any[] {\n maxTokens ||= maxTokensForOpenAIModel(model);\n\n const result: any[] = [];\n const toolsNumTokens = countToolsTokens(model, tools);\n if (toolsNumTokens > maxTokens) {\n throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);\n }\n maxTokens -= toolsNumTokens;\n\n for (const message of messages) {\n if (message.role === \"system\") {\n const numTokens = countMessageTokens(model, message);\n maxTokens -= numTokens;\n\n if (maxTokens < 0) {\n throw new Error(\"Not enough tokens for system message.\");\n }\n }\n }\n\n let cutoff: boolean = false;\n\n const reversedMessages = [...messages].reverse();\n for (const message of reversedMessages) {\n if (message.role === \"system\") {\n result.unshift(message);\n continue;\n } else if (cutoff) {\n continue;\n }\n let numTokens = countMessageTokens(model, message);\n if (maxTokens < numTokens) {\n cutoff = true;\n continue;\n }\n result.unshift(message);\n maxTokens -= numTokens;\n }\n\n return result;\n}\n\nexport function maxTokensForOpenAIModel(model: string): number {\n return maxTokensByModel[model] || DEFAULT_MAX_TOKENS;\n}\n\nconst DEFAULT_MAX_TOKENS = 128000;\n\nconst maxTokensByModel: { [key: string]: number } = {\n // GPT-4\n \"gpt-4o\": 128000,\n \"gpt-4o-2024-05-13\": 128000,\n \"gpt-4-turbo\": 128000,\n \"gpt-4-turbo-2024-04-09\": 128000,\n \"gpt-4-0125-preview\": 128000,\n \"gpt-4-turbo-preview\": 128000,\n \"gpt-4-1106-preview\": 128000,\n \"gpt-4-vision-preview\": 128000,\n \"gpt-4-1106-vision-preview\": 128000,\n \"gpt-4-32k\": 32768,\n \"gpt-4-32k-0613\": 32768,\n \"gpt-4-32k-0314\": 32768,\n \"gpt-4\": 8192,\n \"gpt-4-0613\": 8192,\n \"gpt-4-0314\": 8192,\n\n // GPT-3.5\n \"gpt-3.5-turbo-0125\": 16385,\n \"gpt-3.5-turbo\": 16385,\n \"gpt-3.5-turbo-1106\": 16385,\n \"gpt-3.5-turbo-instruct\": 4096,\n \"gpt-3.5-turbo-16k\": 16385,\n \"gpt-3.5-turbo-0613\": 4096,\n \"gpt-3.5-turbo-16k-0613\": 16385,\n \"gpt-3.5-turbo-0301\": 4097,\n};\n\nfunction countToolsTokens(model: string, tools: any[]): number {\n if (tools.length === 0) {\n return 0;\n }\n const json = JSON.stringify(tools);\n return countTokens(model, json);\n}\n\nfunction countMessageTokens(model: string, message: any): number {\n return countTokens(model, message.content || \"\");\n}\n\nfunction countTokens(model: string, text: string): number {\n return text.length / 3;\n}\n\nexport function convertActionInputToOpenAITool(action: ActionInput): ChatCompletionTool {\n return {\n type: \"function\",\n function: {\n name: action.name,\n description: action.description,\n parameters: JSON.parse(action.jsonSchema),\n },\n };\n}\n\nexport function convertMessageToOpenAIMessage(message: Message): ChatCompletionMessageParam {\n if (message instanceof TextMessage) {\n return {\n role: message.role,\n content: message.content,\n };\n } else if (message instanceof ActionExecutionMessage) {\n return {\n role: \"assistant\",\n tool_calls: [\n {\n id: message.id,\n type: \"function\",\n function: {\n name: message.name,\n arguments: JSON.stringify(message.arguments),\n },\n },\n ],\n };\n } else if (message instanceof ResultMessage) {\n return {\n role: \"tool\",\n content: message.result,\n tool_call_id: message.actionExecutionId,\n };\n }\n}\n\nexport function convertSystemMessageToAssistantAPI(message: ChatCompletionMessageParam) {\n return {\n ...message,\n ...(message.role === \"system\" && {\n role: \"assistant\",\n content: \"THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: \" + message.content,\n }),\n };\n}\n","/**\n * Copilot Runtime adapter for the OpenAI Assistant API.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, OpenAIAssistantAdapter } from \"@copilotkit/runtime\";\n * import OpenAI from \"openai\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const openai = new OpenAI({\n * organization: \"<your-organization-id>\",\n * apiKey: \"<your-api-key>\",\n * });\n *\n * const serviceAdapter = new OpenAIAssistantAdapter({\n * openai,\n * assistantId: \"<your-assistant-id>\",\n * codeInterpreterEnabled: true,\n * fileSearchEnabled: true,\n * });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport OpenAI from \"openai\";\nimport {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport { Message, ResultMessage, TextMessage } from \"../../graphql/types/converted\";\nimport {\n convertActionInputToOpenAITool,\n convertMessageToOpenAIMessage,\n convertSystemMessageToAssistantAPI,\n} from \"./utils\";\nimport { RunSubmitToolOutputsStreamParams } from \"openai/resources/beta/threads/runs/runs\";\nimport { AssistantStream } from \"openai/lib/AssistantStream\";\nimport { RuntimeEventSource } from \"../events\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { AssistantStreamEvent, AssistantTool } from \"openai/resources/beta/assistants\";\nimport { ForwardedParametersInput } from \"../../graphql/inputs/forwarded-parameters.input\";\n\nexport interface OpenAIAssistantAdapterParams {\n /**\n * The ID of the assistant to use.\n */\n assistantId: string;\n\n /**\n * An optional OpenAI instance to use. If not provided, a new instance will be created.\n */\n openai?: OpenAI;\n\n /**\n * Whether to enable code interpretation.\n * @default true\n */\n codeInterpreterEnabled?: boolean;\n\n /**\n * Whether to enable file search.\n * @default true\n */\n fileSearchEnabled?: boolean;\n}\n\nexport class OpenAIAssistantAdapter implements CopilotServiceAdapter {\n private openai: OpenAI;\n private codeInterpreterEnabled: boolean;\n private assistantId: string;\n private fileSearchEnabled: boolean;\n\n constructor(params: OpenAIAssistantAdapterParams) {\n this.openai = params.openai || new OpenAI({});\n this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;\n this.fileSearchEnabled = params.fileSearchEnabled === false || true;\n this.assistantId = params.assistantId;\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource, runId, forwardedParameters } = request;\n // if we don't have a threadId, create a new thread\n let threadId = request.threadId || (await this.openai.beta.threads.create()).id;\n\n const lastMessage = messages.at(-1);\n\n let nextRunId: string | undefined = undefined;\n\n // submit function outputs\n if (lastMessage instanceof ResultMessage && runId) {\n nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);\n }\n // submit user message\n else if (lastMessage instanceof TextMessage) {\n nextRunId = await this.submitUserMessage(\n threadId,\n messages,\n actions,\n eventSource,\n forwardedParameters,\n );\n }\n // unsupported message\n else {\n throw new Error(\"No actionable message found in the messages\");\n }\n\n return {\n threadId,\n runId: nextRunId,\n };\n }\n\n private async submitToolOutputs(\n threadId: string,\n runId: string,\n messages: Message[],\n eventSource: RuntimeEventSource,\n ) {\n let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);\n if (!run.required_action) {\n throw new Error(\"No tool outputs required\");\n }\n\n // get the required tool call ids\n const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map(\n (toolCall) => toolCall.id,\n );\n\n // search for these tool calls\n const resultMessages = messages.filter(\n (message) =>\n message instanceof ResultMessage && toolCallsIds.includes(message.actionExecutionId),\n ) as ResultMessage[];\n\n if (toolCallsIds.length != resultMessages.length) {\n throw new Error(\"Number of function results does not match the number of tool calls\");\n }\n\n // submit the tool outputs\n const toolOutputs: RunSubmitToolOutputsStreamParams.ToolOutput[] = resultMessages.map(\n (message) => {\n return {\n tool_call_id: message.actionExecutionId,\n output: message.result,\n };\n },\n );\n\n const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {\n tool_outputs: toolOutputs,\n });\n\n await this.streamResponse(stream, eventSource);\n return runId;\n }\n\n private async submitUserMessage(\n threadId: string,\n messages: Message[],\n actions: ActionInput[],\n eventSource: RuntimeEventSource,\n forwardedParameters: ForwardedParametersInput,\n ) {\n messages = [...messages];\n\n // get the instruction message\n const instructionsMessage = messages.shift();\n const instructions =\n instructionsMessage instanceof TextMessage ? instructionsMessage.content : \"\";\n\n // get the latest user message\n const userMessage = messages\n .map(convertMessageToOpenAIMessage)\n .map(convertSystemMessageToAssistantAPI)\n .at(-1);\n\n if (userMessage.role !== \"user\") {\n throw new Error(\"No user message found\");\n }\n\n // create a new message on the thread\n await this.openai.beta.threads.messages.create(threadId, {\n role: \"user\",\n content: userMessage.content,\n });\n\n const openaiTools = actions.map(convertActionInputToOpenAITool);\n\n const tools = [\n ...openaiTools,\n ...(this.codeInterpreterEnabled ? [{ type: \"code_interpreter\" } as AssistantTool] : []),\n ...(this.fileSearchEnabled ? [{ type: \"file_search\" } as AssistantTool] : []),\n ];\n\n // run the thread\n let stream = this.openai.beta.threads.runs.stream(threadId, {\n assistant_id: this.assistantId,\n instructions,\n tools: tools,\n ...(forwardedParameters?.maxTokens && {\n max_completion_tokens: forwardedParameters.maxTokens,\n }),\n });\n\n await this.streamResponse(stream, eventSource);\n\n return getRunIdFromStream(stream);\n }\n\n private async streamResponse(stream: AssistantStream, eventSource: RuntimeEventSource) {\n eventSource.stream(async (eventStream$) => {\n let inFunctionCall = false;\n\n for await (const chunk of stream) {\n switch (chunk.event) {\n case \"thread.message.created\":\n if (inFunctionCall) {\n eventStream$.sendActionExecutionEnd();\n }\n eventStream$.sendTextMessageStart(chunk.data.id);\n break;\n case \"thread.message.delta\":\n if (chunk.data.delta.content?.[0].type === \"text\") {\n eventStream$.sendTextMessageContent(chunk.data.delta.content?.[0].text.value);\n }\n break;\n case \"thread.message.completed\":\n eventStream$.sendTextMessageEnd();\n break;\n case \"thread.run.step.delta\":\n let toolCallId: string | undefined;\n let toolCallName: string | undefined;\n let toolCallArgs: string | undefined;\n if (\n chunk.data.delta.step_details.type === \"tool_calls\" &&\n chunk.data.delta.step_details.tool_calls?.[0].type === \"function\"\n ) {\n toolCallId = chunk.data.delta.step_details.tool_calls?.[0].id;\n toolCallName = chunk.data.delta.step_details.tool_calls?.[0].function.name;\n toolCallArgs = chunk.data.delta.step_details.tool_calls?.[0].function.arguments;\n }\n\n if (toolCallName && toolCallId) {\n if (inFunctionCall) {\n eventStream$.sendActionExecutionEnd();\n }\n inFunctionCall = true;\n eventStream$.sendActionExecutionStart(toolCallId, toolCallName);\n } else if (toolCallArgs) {\n eventStream$.sendActionExecutionArgs(toolCallArgs);\n }\n break;\n }\n }\n if (inFunctionCall) {\n eventStream$.sendActionExecutionEnd();\n }\n eventStream$.complete();\n });\n }\n}\n\nfunction getRunIdFromStream(stream: AssistantStream): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let runIdGetter = (event: AssistantStreamEvent) => {\n if (event.event === \"thread.run.created\") {\n const runId = event.data.id;\n stream.off(\"event\", runIdGetter);\n resolve(runId);\n }\n };\n stream.on(\"event\", runIdGetter);\n });\n}\n","/**\n * Copilot Runtime adapter for Google Generative AI (e.g. Gemini).\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, GoogleGenerativeAIAdapter } from \"@copilotkit/runtime\";\n * const { GoogleGenerativeAI } = require(\"@google/generative-ai\");\n *\n * const genAI = new GoogleGenerativeAI(process.env[\"GOOGLE_API_KEY\"]);\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const model = genAI.getGenerativeModel({\n * model: \"gemini-pro\"\n * });\n *\n * const serviceAdapter = new GoogleGenerativeAIAdapter({ model });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport { CopilotServiceAdapter } from \"../service-adapter\";\nimport {\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport { GenerativeModel, GoogleGenerativeAI } from \"@google/generative-ai\";\nimport { TextMessage } from \"../../graphql/types/converted\";\nimport { convertMessageToGoogleGenAIMessage, transformActionToGoogleGenAITool } from \"./utils\";\nimport { randomId } from \"@copilotkit/shared\";\n\ninterface GoogleGenerativeAIAdapterOptions {\n /**\n * A custom Google Generative AI model to use.\n */\n model?: GenerativeModel;\n}\n\nexport class GoogleGenerativeAIAdapter implements CopilotServiceAdapter {\n private model: GenerativeModel;\n\n constructor(options?: GoogleGenerativeAIAdapterOptions) {\n if (options?.model) {\n this.model = options.model;\n } else {\n const genAI = new GoogleGenerativeAI(process.env[\"GOOGLE_API_KEY\"]!);\n this.model = genAI.getGenerativeModel({ model: \"gemini-pro\" });\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource } = request;\n\n // get the history (everything except the first and last message)\n const history = messages.slice(1, -1).map(convertMessageToGoogleGenAIMessage);\n\n // get the current message (the last message)\n const currentMessage = convertMessageToGoogleGenAIMessage(messages.at(-1));\n if (!currentMessage) {\n throw new Error(\"No current message\");\n }\n\n let systemMessage: string;\n const firstMessage = messages.at(0);\n if (firstMessage instanceof TextMessage && firstMessage.role === \"system\") {\n systemMessage = firstMessage.content.trim();\n } else {\n throw new Error(\"First message is not a system message\");\n }\n\n const tools = actions.map(transformActionToGoogleGenAITool);\n\n const isFirstGenGeminiPro =\n this.model.model === \"gemini-pro\" || this.model.model === \"models/gemini-pro\";\n\n const chat = this.model.startChat({\n history: [\n ...history,\n // gemini-pro does not support system instructions, so we need to add them to the history\n ...(isFirstGenGeminiPro ? [{ role: \"user\", parts: [{ text: systemMessage }] }] : []),\n ],\n // only gemini-1.5-pro-latest and later supports setting system instructions\n ...(isFirstGenGeminiPro\n ? {}\n : { systemInstruction: { role: \"user\", parts: [{ text: systemMessage }] } }),\n tools,\n });\n\n const result = await chat.sendMessageStream(currentMessage.parts);\n\n eventSource.stream(async (eventStream$) => {\n let isTextMessage = false;\n for await (const chunk of result.stream) {\n const chunkText = chunk.text();\n if (chunkText === \"\") {\n continue;\n }\n if (!isTextMessage) {\n isTextMessage = true;\n eventStream$.sendTextMessageStart(randomId());\n }\n eventStream$.sendTextMessageContent(chunkText);\n }\n if (isTextMessage) {\n eventStream$.sendTextMessageEnd();\n }\n\n let calls = (await result.response).functionCalls();\n if (calls) {\n for (let call of calls) {\n eventStream$.sendActionExecution(\n randomId(),\n call.name,\n JSON.stringify(replaceNewlinesInObject(call.args)),\n );\n }\n }\n eventStream$.complete();\n });\n\n return {\n threadId: request.threadId || randomId(),\n };\n }\n}\n\nfunction replaceNewlinesInObject(obj: any): any {\n if (typeof obj === \"string\") {\n return obj.replace(/\\\\\\\\n/g, \"\\n\");\n } else if (Array.isArray(obj)) {\n return obj.map(replaceNewlinesInObject);\n } else if (typeof obj === \"object\" && obj !== null) {\n const newObj: any = {};\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n newObj[key] = replaceNewlinesInObject(obj[key]);\n }\n }\n return newObj;\n }\n return obj;\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport { Tool } from \"@google/generative-ai\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\n\nexport function convertMessageToGoogleGenAIMessage(message: Message) {\n if (message instanceof TextMessage) {\n const role = {\n user: \"user\",\n assistant: \"model\",\n system: \"user\",\n }[message.role];\n\n const text =\n message.role === \"system\"\n ? \"THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: \" + message.content\n : message.content;\n\n return {\n role,\n parts: [{ text }],\n };\n } else if (message instanceof ActionExecutionMessage) {\n return {\n role: \"model\",\n parts: [\n {\n functionCall: {\n name: message.name,\n args: message.arguments,\n },\n },\n ],\n };\n } else if (message instanceof ResultMessage) {\n return {\n role: \"function\",\n parts: [\n {\n functionResponse: {\n name: message.actionName,\n response: {\n name: message.actionName,\n content: tryParseJson(message.result),\n },\n },\n },\n ],\n };\n }\n}\n\nexport function transformActionToGoogleGenAITool(action: ActionInput): Tool {\n const name = action.name;\n const description = action.description;\n const parameters = JSON.parse(action.jsonSchema);\n\n const transformProperties = (props: any) => {\n for (const key in props) {\n if (props[key].type) {\n props[key].type = props[key].type.toUpperCase();\n }\n if (props[key].properties) {\n transformProperties(props[key].properties);\n }\n }\n };\n transformProperties(parameters);\n\n return {\n functionDeclarations: [\n {\n name,\n description,\n parameters,\n },\n ],\n };\n}\n\nfunction tryParseJson(str?: string) {\n if (!str) {\n return \"\";\n }\n try {\n return JSON.parse(str);\n } catch (e) {\n return str;\n }\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { LangChainReturnType } from \"./types\";\nimport { RuntimeEventSubject } from \"../events\";\nimport { randomId } from \"@copilotkit/shared\";\n\nexport function convertMessageToLangChainMessage(message: Message): BaseMessage {\n if (message instanceof TextMessage) {\n if (message.role == \"user\") {\n return new HumanMessage(message.content);\n } else if (message.role == \"assistant\") {\n return new AIMessage(message.content);\n } else if (message.role === \"system\") {\n return new SystemMessage(message.content);\n }\n } else if (message instanceof ActionExecutionMessage) {\n return new AIMessage({\n content: \"\",\n tool_calls: [\n {\n id: message.id,\n args: message.arguments,\n name: message.name,\n },\n ],\n });\n } else if (message instanceof ResultMessage) {\n return new ToolMessage({\n content: message.result,\n tool_call_id: message.actionExecutionId,\n });\n }\n}\n\nexport function convertJsonSchemaToZodSchema(jsonSchema: any, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n let schema = z.object(spec);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"array\") {\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, false);\n let schema = z.array(itemSchema);\n return !required ? schema.optional() : schema;\n }\n}\n\nexport function convertActionInputToLangChainTool(actionInput: ActionInput): any {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(\n JSON.parse(actionInput.jsonSchema),\n true,\n ) as z.ZodObject<any>,\n func: async () => {\n return \"\";\n },\n });\n}\n\ninterface StreamLangChainResponseParams {\n result: LangChainReturnType;\n eventStream$: RuntimeEventSubject;\n actionExecution?: {\n id: string;\n name: string;\n };\n}\n\nfunction getConstructorName(object: any): string {\n if (object && typeof object === \"object\" && object.constructor && object.constructor.name) {\n return object.constructor.name;\n }\n return \"\";\n}\n\nfunction isAIMessage(message: any): message is AIMessage {\n return getConstructorName(message) === \"AIMessage\";\n}\n\nfunction isAIMessageChunk(message: any): message is AIMessageChunk {\n return getConstructorName(message) === \"AIMessageChunk\";\n}\n\nfunction isBaseMessageChunk(message: any): message is BaseMessageChunk {\n return getConstructorName(message) === \"BaseMessageChunk\";\n}\n\nfunction maybeSendActionExecutionResultIsMessage(\n eventStream$: RuntimeEventSubject,\n actionExecution?: { id: string; name: string },\n) {\n // language models need a result after the function call\n // we simply let them know that we are sending a message\n if (actionExecution) {\n eventStream$.sendActionExecutionResult(\n actionExecution.id,\n actionExecution.name,\n \"Sending a message\",\n );\n }\n}\n\nexport async function streamLangChainResponse({\n result,\n eventStream$,\n actionExecution,\n}: StreamLangChainResponseParams) {\n // We support several types of return values from LangChain functions:\n\n // 1. string\n\n if (typeof result === \"string\") {\n if (!actionExecution) {\n // Just send one chunk with the string as the content.\n eventStream$.sendTextMessage(randomId(), result);\n } else {\n // Send as a result\n eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);\n }\n }\n\n // 2. AIMessage\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isAIMessage(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n for (const toolCall of result.tool_calls) {\n eventStream$.sendActionExecution(\n toolCall.id || randomId(),\n toolCall.name,\n JSON.stringify(toolCall.args),\n );\n }\n }\n\n // 3. BaseMessageChunk\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isBaseMessageChunk(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.lc_kwargs?.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n if (result.lc_kwargs?.tool_calls) {\n for (const toolCall of result.lc_kwargs?.tool_calls) {\n eventStream$.sendActionExecution(\n toolCall.id || randomId(),\n toolCall.name,\n JSON.stringify(toolCall.args),\n );\n }\n }\n }\n\n // 4. IterableReadableStream\n // Stream the result of the LangChain function.\n else if (result && \"getReader\" in result) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n let reader = result.getReader();\n\n let mode: \"function\" | \"message\" | null = null;\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n let toolCallName: string | undefined = undefined;\n let toolCallId: string | undefined = undefined;\n let toolCallArgs: string | undefined = undefined;\n let hasToolCall: boolean = false;\n let content = value?.content as string;\n\n if (isAIMessageChunk(value)) {\n let chunk = value.tool_call_chunks?.[0];\n toolCallName = chunk?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.args;\n hasToolCall = chunk != undefined;\n } else if (isBaseMessageChunk(value)) {\n let chunk = value.additional_kwargs?.tool_calls?.[0];\n toolCallName = chunk?.function?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.function?.arguments;\n hasToolCall = chunk?.function != undefined;\n }\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCallName is defined, it means a new tool call starts.\n if (mode === \"message\" && (toolCallId || done)) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (!hasToolCall || done)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n if (done) {\n break;\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (hasToolCall) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCallId, toolCallName);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(randomId());\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCallArgs) {\n eventStream$.sendActionExecutionArgs(toolCallArgs);\n }\n } catch (error) {\n console.error(\"Error reading from stream\", error);\n break;\n }\n }\n } else if (actionExecution) {\n eventStream$.sendActionExecutionResult(\n actionExecution.id,\n actionExecution.name,\n encodeResult(result),\n );\n }\n\n // unsupported type\n else {\n throw new Error(\"Invalid return type from LangChain function.\");\n }\n\n eventStream$.complete();\n}\n\nfunction encodeResult(result: any): string {\n if (result === undefined) {\n return \"\";\n } else if (typeof result === \"string\") {\n return result;\n } else {\n return JSON.stringify(result);\n }\n}\n","/**\n * Copilot Runtime adapter for LangChain.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, LangChainAdapter } from \"@copilotkit/runtime\";\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * apiKey: \"<your-api-key>\",\n * });\n *\n * const serviceAdapter = new LangChainAdapter({\n * chainFn: async ({ messages, tools }) => {\n * return model.stream(messages, { tools });\n * }\n * });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n *\n * The asynchronous handler function (`chainFn`) can return any of the following:\n *\n * - A simple `string` response\n * - A LangChain stream (`IterableReadableStream`)\n * - A LangChain `BaseMessageChunk` object\n * - A LangChain `AIMessage` object\n */\n\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { CopilotServiceAdapter } from \"../service-adapter\";\nimport {\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToLangChainTool,\n convertMessageToLangChainMessage,\n streamLangChainResponse,\n} from \"./utils\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { LangChainReturnType } from \"./types\";\nimport { randomId } from \"@copilotkit/shared\";\n\ninterface ChainFnParameters {\n model: string;\n messages: BaseMessage[];\n tools: DynamicStructuredTool[];\n threadId?: string;\n runId?: string;\n}\n\ninterface LangChainAdapterOptions {\n /**\n * A function that uses the LangChain API to generate a response.\n */\n chainFn: (parameters: ChainFnParameters) => Promise<LangChainReturnType>;\n}\n\nexport class LangChainAdapter implements CopilotServiceAdapter {\n /**\n * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.\n */\n constructor(private options: LangChainAdapterOptions) {}\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { eventSource, model, actions, messages, threadId, runId } = request;\n const result = await this.options.chainFn({\n messages: messages.map(convertMessageToLangChainMessage),\n tools: actions.map(convertActionInputToLangChainTool),\n model,\n threadId,\n runId,\n });\n\n eventSource.stream(async (eventStream$) => {\n await streamLangChainResponse({\n result,\n eventStream$,\n });\n });\n\n return {\n threadId: threadId || randomId(),\n };\n }\n}\n","import { Parameter, Action } from \"@copilotkit/shared\";\nimport { RemoteRunnable } from \"langchain/runnables/remote\";\n\nexport interface RemoteChainParameters {\n name: string;\n description: string;\n chainUrl: string;\n parameters?: Parameter[];\n parameterType?: \"single\" | \"multi\";\n}\n\nexport class RemoteChain {\n name: string;\n description: string;\n chainUrl: string;\n parameters?: Parameter[];\n parameterType: \"single\" | \"multi\";\n\n constructor(options: RemoteChainParameters) {\n this.name = options.name;\n this.description = options.description;\n this.chainUrl = options.chainUrl;\n this.parameters = options.parameters;\n this.parameterType = options.parameterType || \"multi\";\n }\n\n async toAction(): Promise<Action<any>> {\n if (!this.parameters) {\n await this.inferLangServeParameters();\n }\n\n return {\n name: this.name,\n description: this.description,\n parameters: this.parameters!,\n handler: async (args: any) => {\n const runnable = new RemoteRunnable({ url: this.chainUrl });\n let input: any;\n if (this.parameterType === \"single\") {\n input = args[Object.keys(args)[0]];\n } else {\n input = args;\n }\n return await runnable.invoke(input);\n },\n };\n }\n\n async inferLangServeParameters() {\n const supportedTypes = [\"string\", \"number\", \"boolean\"];\n\n let schemaUrl = this.chainUrl.replace(/\\/+$/, \"\") + \"/input_schema\";\n let schema = await fetch(schemaUrl)\n .then((res) => res.json())\n .catch(() => {\n throw new Error(\"Failed to fetch langserve schema at \" + schemaUrl);\n });\n // for now, don't use json schema, just do a simple conversion\n\n if (supportedTypes.includes(schema.type)) {\n this.parameterType = \"single\";\n this.parameters = [\n {\n name: \"input\",\n type: schema.type,\n description: \"The input to the chain\",\n },\n ];\n } else if (schema.type === \"object\") {\n this.parameterType = \"multi\";\n this.parameters = Object.keys(schema.properties).map((key) => {\n let property = schema.properties[key];\n if (!supportedTypes.includes(property.type)) {\n throw new Error(\"Unsupported schema type\");\n }\n return {\n name: key,\n type: property.type,\n description: property.description || \"\",\n required: schema.required?.includes(key) || false,\n };\n });\n } else {\n throw new Error(\"Unsupported schema type\");\n }\n }\n}\n","/**\n * CopilotKit Adapter for Unify\n *\n * <RequestExample>\n * ```jsx CopilotRuntime Example\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new UnifyAdapter());\n * ```\n * </RequestExample>\n *\n * You can easily set the model to use by passing it to the constructor.\n * ```jsx\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(\n * req,\n * new UnifyAdapter({ model: \"llama-3-8b-chat@fireworks-ai\" }),\n * );\n * ```\n */\nimport { TextMessage } from \"../../graphql/types/converted\";\nimport {\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n CopilotServiceAdapter,\n} from \"../service-adapter\";\nimport OpenAI from \"openai\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { convertActionInputToOpenAITool, convertMessageToOpenAIMessage } from \"../openai/utils\";\n\nexport interface UnifyAdapterParams {\n apiKey?: string;\n model: string;\n}\n\nexport class UnifyAdapter implements CopilotServiceAdapter {\n private apiKey: string;\n private model: string;\n private start: boolean;\n\n constructor(options?: UnifyAdapterParams) {\n if (options?.apiKey) {\n this.apiKey = options.apiKey;\n } else {\n this.apiKey = \"UNIFY_API_KEY\";\n }\n this.model = options?.model;\n this.start = true;\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const tools = request.actions.map(convertActionInputToOpenAITool);\n const openai = new OpenAI({\n apiKey: this.apiKey,\n baseURL: \"https://api.unify.ai/v0/\",\n });\n\n const messages = request.messages.map(convertMessageToOpenAIMessage);\n\n const stream = await openai.chat.completions.create({\n model: this.model,\n messages: messages,\n stream: true,\n ...(tools.length > 0 && { tools }),\n });\n\n let model = null;\n request.eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n for await (const chunk of stream) {\n if (this.start) {\n model = chunk.model;\n eventStream$.sendTextMessageStart(randomId());\n eventStream$.sendTextMessageContent(`Model used: ${model}\\n`);\n eventStream$.sendTextMessageEnd();\n this.start = false;\n }\n const toolCall = chunk.choices[0].delta.tool_calls?.[0];\n const content = chunk.choices[0].delta.content;\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCall?.id is defined, it means a new tool call starts.\n if (mode === \"message\" && toolCall?.id) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (toolCall === undefined || toolCall?.id)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (toolCall?.id) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCall!.id, toolCall!.function!.name);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(chunk.id);\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCall?.function?.arguments) {\n eventStream$.sendActionExecutionArgs(toolCall.function.arguments);\n }\n }\n\n // send the end events\n if (mode === \"message\") {\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd();\n }\n\n eventStream$.complete();\n });\n\n return {\n threadId: request.threadId || randomId(),\n };\n }\n}\n","/**\n * Copilot Runtime adapter for OpenAI.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, GroqAdapter } from \"@copilotkit/runtime\";\n * import { Groq } from \"groq-sdk\";\n *\n * const groq = new Groq({ apiKey: process.env[\"GROQ_API_KEY\"] });\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const serviceAdapter = new GroqAdapter({ groq, model: \"<model-name>\" });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport { Groq } from \"groq-sdk\";\nimport {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToOpenAITool,\n convertMessageToOpenAIMessage,\n limitMessagesToTokenCount,\n} from \"../openai/utils\";\nimport { randomId } from \"@copilotkit/shared\";\n\nconst DEFAULT_MODEL = \"llama3-groq-70b-8192-tool-use-preview\";\n\nexport interface GroqAdapterParams {\n /**\n * An optional Groq instance to use.\n */\n groq?: Groq;\n\n /**\n * The model to use.\n */\n model?: string;\n}\n\nexport class GroqAdapter implements CopilotServiceAdapter {\n private model: string = DEFAULT_MODEL;\n\n private _groq: Groq;\n public get groq(): Groq {\n return this._groq;\n }\n\n constructor(params?: GroqAdapterParams) {\n this._groq = params?.groq || new Groq({});\n if (params?.model) {\n this.model = params.model;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const {\n threadId,\n model = this.model,\n messages,\n actions,\n eventSource,\n forwardedParameters,\n } = request;\n const tools = actions.map(convertActionInputToOpenAITool);\n\n let openaiMessages = messages.map(convertMessageToOpenAIMessage);\n openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);\n\n let toolChoice: any = forwardedParameters?.toolChoice;\n if (forwardedParameters?.toolChoice === \"function\") {\n toolChoice = {\n type: \"function\",\n function: { name: forwardedParameters.toolChoiceFunctionName },\n };\n }\n const stream = await this.groq.chat.completions.create({\n model: model,\n stream: true,\n messages: openaiMessages,\n ...(tools.length > 0 && { tools }),\n ...(forwardedParameters?.maxTokens && {\n max_tokens: forwardedParameters.maxTokens,\n }),\n ...(forwardedParameters?.stop && { stop: forwardedParameters.stop }),\n ...(toolChoice && { tool_choice: toolChoice }),\n });\n\n eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n for await (const chunk of stream) {\n const toolCall = chunk.choices[0].delta.tool_calls?.[0];\n const content = chunk.choices[0].delta.content;\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCall?.id is defined, it means a new tool call starts.\n if (mode === \"message\" && toolCall?.id) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (toolCall === undefined || toolCall?.id)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (toolCall?.id) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCall!.id, toolCall!.function!.name);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(chunk.id);\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCall?.function?.arguments) {\n eventStream$.sendActionExecutionArgs(toolCall.function.arguments);\n }\n }\n\n // send the end events\n if (mode === \"message\") {\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd();\n }\n\n eventStream$.complete();\n });\n\n return {\n threadId: threadId || randomId(),\n };\n }\n}\n","import { Action } from \"@copilotkit/shared\";\nimport { of, concat, map, scan, concatMap, ReplaySubject, Subject, firstValueFrom } from \"rxjs\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n}\n\ntype FunctionCallScope = \"client\" | \"server\";\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n scope?: FunctionCallScope;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n };\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart(messageId: string) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId });\n }\n\n sendTextMessageContent(content: string) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content });\n }\n\n sendTextMessageEnd() {\n this.next({ type: RuntimeEventTypes.TextMessageEnd });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart(messageId);\n this.sendTextMessageContent(content);\n this.sendTextMessageEnd();\n }\n\n sendActionExecutionStart(actionExecutionId: string, actionName: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n });\n }\n\n sendActionExecutionArgs(args: string) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args });\n }\n\n sendActionExecutionEnd() {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd });\n }\n\n sendActionExecution(actionExecutionId: string, toolName: string, args: string) {\n this.sendActionExecutionStart(actionExecutionId, toolName);\n this.sendActionExecutionArgs(args);\n this.sendActionExecutionEnd();\n }\n\n sendActionExecutionResult(actionExecutionId: string, actionName: string, result: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n process({\n serversideActions,\n guardrailsResult$,\n }: {\n serversideActions: Action<any>[];\n guardrailsResult$?: Subject<GuardrailsResult>;\n }) {\n this.callback(this.eventStream$).catch((error) => {\n console.error(\"Error in event source callback\", error);\n });\n return this.eventStream$.pipe(\n // mark tools for server side execution\n map((event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n event.scope = serversideActions.find((action) => action.name === event.actionName)\n ? \"server\"\n : \"client\";\n }\n return event;\n }),\n // track state\n scan(\n (acc, event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide = event.scope === \"server\";\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serversideActions.find((action) => action.name === event.actionName);\n }\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n guardrailsResult$ ? guardrailsResult$ : null,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionId,\n ).catch((error) => {\n console.error(error);\n });\n return concat(of(eventWithState.event!), toolCallEventStream$);\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n guardrailsResult$: Subject<GuardrailsResult> | null,\n action: Action<any>,\n actionArguments: string,\n actionExecutionId: string,\n) {\n if (guardrailsResult$) {\n const { status } = await firstValueFrom(guardrailsResult$);\n\n if (status === \"denied\") {\n eventStream$.complete();\n return;\n }\n }\n\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n args = JSON.parse(actionArguments);\n }\n\n // call the function\n const result = await action.handler(args);\n\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n },\n });\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../graphql/types/converted\";\nimport { MessageInput } from \"../graphql/inputs/message.input\";\nimport { plainToInstance } from \"class-transformer\";\n\nexport function convertGqlInputToMessages(inputMessages: MessageInput[]): Message[] {\n const messages: Message[] = [];\n\n for (const message of inputMessages) {\n if (message.textMessage) {\n messages.push(\n plainToInstance(TextMessage, {\n id: message.id,\n createdAt: message.createdAt,\n role: message.textMessage.role,\n content: message.textMessage.content,\n }),\n );\n } else if (message.actionExecutionMessage) {\n messages.push(\n plainToInstance(ActionExecutionMessage, {\n id: message.id,\n createdAt: message.createdAt,\n name: message.actionExecutionMessage.name,\n arguments: JSON.parse(message.actionExecutionMessage.arguments),\n scope: message.actionExecutionMessage.scope,\n }),\n );\n } else if (message.resultMessage) {\n messages.push(\n plainToInstance(ResultMessage, {\n id: message.id,\n createdAt: message.createdAt,\n actionExecutionId: message.resultMessage.actionExecutionId,\n actionName: message.resultMessage.actionName,\n result: message.resultMessage.result,\n }),\n );\n }\n }\n\n return messages;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\nimport telemetry from \"../telemetry-client\";\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n\n const contextLogger = createLogger({ level: logLevel });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter.constructor.name,\n },\n });\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream()],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport { MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport { RuntimeEvent, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport { ActionExecutionMessage, Message, ResultMessage, TextMessage } from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n console.log(\"invokeGuardrails.baseUrl\", baseUrl);\n\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Mutation(() => CopilotResponse)\n async generateCopilotResponse(\n @Ctx() ctx: GraphQLContext,\n @Arg(\"data\") data: GenerateCopilotResponseInput,\n @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n properties?: CopilotRequestContextProperties,\n ) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": data.cloud?.guardrails !== undefined,\n requestType: data.metadata.requestType,\n });\n\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n const key = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (key) {\n logger.debug(\"Public API key found in headers\");\n copilotCloudPublicApiKey = key;\n } else {\n logger.error(\"Public API key not found in headers\");\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.cloud?.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n logger.debug(\"Processing\");\n const {\n eventSource,\n threadId = randomId(),\n runId,\n actions,\n } = await copilotRuntime.process({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions,\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: undefined,\n properties: ctx.properties || {},\n outputMessagesPromise,\n forwardedParameters: data.forwardedParameters,\n });\n\n logger.debug(\"Event source created, creating response\");\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: randomId(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n // run and process the event stream\n const eventStream = eventSource\n .process({\n serversideActions: actions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n })\n .pipe(\n // shareReplay() ensures that later subscribers will see the whole stream instead of\n // just the events that were emitted after the subscriber was added.\n shareReplay(),\n finalize(() => {\n logger.debug(\"Event stream finalized\");\n }),\n );\n\n logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\n ////////////////////////////////\n // TextMessageStart\n ////////////////////////////////\n case RuntimeEventTypes.TextMessageStart:\n // create a sub stream that contains the message content\n const textMessageContentStream = eventStream.pipe(\n // skip until this message start event\n skipWhile((e) => e !== event),\n // take until the message end event\n takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = randomId();\n\n // push the new message\n pushMessage({\n id: messageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e) => e !== event),\n takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: randomId(),\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: randomId(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in event stream\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\nimport { CopilotRequestType } from \"../types/enums\";\nimport { ForwardedParametersInput } from \"./forwarded-parameters.input\";\n\n@InputType()\nexport class GenerateCopilotResponseMetadataInput {\n @Field(() => CopilotRequestType, { nullable: true })\n requestType: CopilotRequestType;\n}\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => GenerateCopilotResponseMetadataInput, { nullable: false })\n metadata: GenerateCopilotResponseMetadataInput;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n\n @Field(() => ForwardedParametersInput, { nullable: true })\n forwardedParameters?: ForwardedParametersInput;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"../types/enums\";\nimport { BaseMessage } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessage {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n}\n\nexport enum ActionExecutionScope {\n server = \"server\",\n client = \"client\",\n}\n\nexport enum CopilotRequestType {\n Chat = \"Chat\",\n Task = \"Task\",\n TextareaCompletion = \"TextareaCompletion\",\n TextareaPopover = \"TextareaPopover\",\n Suggestion = \"Suggestion\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(ActionExecutionScope, {\n name: \"ActionExecutionScope\",\n description: \"The scope of the action\",\n});\n\nregisterEnumType(CopilotRequestType, {\n name: \"CopilotRequestType\",\n description: \"The type of Copilot request\",\n});\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: false })\n inputValidationRules: GuardrailsRuleInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ForwardedParametersInput {\n @Field(() => String, { nullable: true })\n model?: string;\n\n @Field(() => Number, { nullable: true })\n maxTokens?: number;\n\n @Field(() => [String], { nullable: true })\n stop?: string[];\n\n @Field(() => String, { nullable: true })\n toolChoice?: String;\n\n @Field(() => String, { nullable: true })\n toolChoiceFunctionName?: string;\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n }\n return undefined;\n },\n})\nabstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n\n @Field(() => [String])\n arguments: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { GraphQLJSON } from \"graphql-scalars\";\nimport { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\nexport enum FailedResponseStatusReason {\n GUARDRAILS_VALIDATION_FAILED = \"GUARDRAILS_VALIDATION_FAILED\",\n MESSAGE_STREAM_INTERRUPTED = \"MESSAGE_STREAM_INTERRUPTED\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nregisterEnumType(FailedResponseStatusReason, {\n name: \"FailedResponseStatusReason\",\n});\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => FailedResponseStatusReason)\n reason: FailedResponseStatusReason;\n\n @Field(() => GraphQLJSON, { nullable: true })\n details?: Record<string, any> = null;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import {\n FailedResponseStatus,\n FailedResponseStatusReason,\n} from \"../graphql/types/response-status.type\";\n\nexport class GuardrailsValidationFailureResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;\n declare details: {\n guardrailsReason: string;\n };\n\n constructor({ guardrailsReason }) {\n super();\n this.details = {\n guardrailsReason,\n };\n }\n}\n\nexport class MessageStreamInterruptedResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;\n declare details: {\n messageId: string;\n description: string;\n };\n\n constructor({ messageId }: { messageId: string }) {\n super();\n this.details = {\n messageId,\n description: \"Check the message for mode details\",\n };\n }\n}\n\nexport class UnknownErrorResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.UNKNOWN_ERROR;\n declare details: {\n description?: string;\n };\n\n constructor({ description }: { description?: string }) {\n super();\n this.details = {\n description,\n };\n }\n}\n","import { TelemetryClient } from \"@copilotkit/shared\";\nconst packageJson = require(\"../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport default telemetryClient;\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n fetchAPI: { Response: globalThis.Response },\n });\n\n return {\n handleRequest: yoga,\n GET: yoga as any,\n POST: yoga as any,\n OPTIONS: yoga as any,\n };\n}\n","import { YogaServerInstance, createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, GraphQLContext, getCommonConfig } from \"../shared\";\nimport telemetry from \"../../telemetry-client\";\n\nexport const config = {\n api: {\n bodyParser: false,\n },\n};\n\nexport type CopilotRuntimeServerInstance<T> = YogaServerInstance<T, Partial<GraphQLContext>>;\n\n// This import is needed to fix the type error\n// Fix is currently in TypeScript 5.5 beta, waiting for stable version\n// https://github.com/microsoft/TypeScript/issues/42873#issuecomment-2066874644\nexport type {} from \"@whatwg-node/server\";\n\nexport function copilotRuntimeNextJSPagesRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n): CopilotRuntimeServerInstance<GraphQLContext> {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-pages-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS Pages Router endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0BAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,UAAY;AAAA,MACZ,YAAc;AAAA,QACZ,M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AAQ,gCAAgC,CAAC,CAAA;AAEnD,QAAMC,UAAST,aAAaU;AAC5BD,EAAAA,QAAOE,MAAM,uCAAA;AAEb,QAAMC,WAAOC,iCAAW;IACtB,GAAGb;IACHc,iBAAiBf,QAAQgB;EAC3B,CAAA;AAEA,SAAOH;AACT;AA5BgBd;;;ACjBhB,IAAAkB,uBAA2B;AAIpB,SAASC,+BAA+BC,SAA0C;AAJzF;AAKE,QAAMC,eAAeC,gBAAgBF,OAAAA;AAErCG,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEA,OAAIN,aAAQO,eAARP,mBAAoBQ,aAAa;AACnCL,6BAAUC,oBAAoB;MAC5BI,aAAaR,QAAQO,WAAWC;IAClC,CAAA;EACF;AAEAL,2BAAUM,QAAQ,gCAAgC,CAAC,CAAA;AAEnD,QAAMC,UAAST,aAAaU;AAC5BD,EAAAA,QAAOE,MAAM,6BAAA;AAEb,QAAMC,WAAOC,iCAAW;IACtB,GAAGb;IACHc,iBAAiBf,QAAQgB;EAC3B,CAAA;AAEA,SAAOH;AACT;AA1BgBd;;;ACAT,SAASkB,kCAAkCC,SAA0C;AAC1FC,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEAH,2BAAUI,QAAQ,gCAAgC,CAAC,CAAA;AACnD,SAAOC,+BAA+BN,OAAAA;AACxC;AATgBD;;;ACAT,SAASQ,2BAA2BC,SAA0C;AACnFC,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEAH,2BAAUI,QAAQ,gCAAgC,CAAC,CAAA;AACnD,SAAOC,+BAA+BN,OAAAA;AACxC;AATgBD;","names":["module","import_shared","BaseMessage","id","createdAt","Field","String","Date","InputType","TextMessage","BaseMessage","content","role","ActionExecutionMessage","name","arguments","scope","ResultMessage","actionExecutionId","actionName","result","limitMessagesToTokenCount","messages","tools","model","maxTokens","maxTokensForOpenAIModel","result","toolsNumTokens","countToolsTokens","Error","message","role","numTokens","countMessageTokens","cutoff","reversedMessages","reverse","unshift","maxTokensByModel","DEFAULT_MAX_TOKENS","length","json","JSON","stringify","countTokens","content","text","convertActionInputToOpenAITool","action","type","function","name","description","parameters","parse","jsonSchema","convertMessageToOpenAIMessage","TextMessage","ActionExecutionMessage","tool_calls","id","arguments","ResultMessage","tool_call_id","actionExecutionId","convertSystemMessageToAssistantAPI","DEFAULT_MODEL","OpenAIAdapter","model","_openai","openai","constructor","params","OpenAI","process","request","threadId","messages","actions","eventSource","forwardedParameters","tools","map","convertActionInputToOpenAITool","openaiMessages","convertMessageToOpenAIMessage","limitMessagesToTokenCount","toolChoice","type","function","name","toolChoiceFunctionName","stream","beta","chat","completions","length","maxTokens","max_tokens","stop","tool_choice","eventStream$","mode","chunk","toolCall","choices","delta","tool_calls","content","id","sendTextMessageEnd","undefined","sendActionExecutionEnd","sendActionExecutionStart","sendTextMessageStart","sendTextMessageContent","arguments","sendActionExecutionArgs","complete","randomId","import_openai","OpenAIAssistantAdapter","openai","codeInterpreterEnabled","assistantId","fileSearchEnabled","constructor","params","OpenAI","process","request","messages","actions","eventSource","runId","forwardedParameters","threadId","beta","threads","create","id","lastMessage","at","nextRunId","undefined","ResultMessage","submitToolOutputs","TextMessage","submitUserMessage","Error","run","runs","retrieve","required_action","toolCallsIds","submit_tool_outputs","tool_calls","map","toolCall","resultMessages","filter","message","includes","actionExecutionId","length","toolOutputs","tool_call_id","output","result","stream","submitToolOutputsStream","tool_outputs","streamResponse","instructionsMessage","shift","instructions","content","userMessage","convertMessageToOpenAIMessage","convertSystemMessageToAssistantAPI","role","openaiTools","convertActionInputToOpenAITool","tools","type","assistant_id","maxTokens","max_completion_tokens","getRunIdFromStream","eventStream$","inFunctionCall","chunk","event","sendActionExecutionEnd","sendTextMessageStart","data","delta","sendTextMessageContent","text","value","sendTextMessageEnd","toolCallId","toolCallName","toolCallArgs","step_details","function","name","arguments","sendActionExecutionStart","sendActionExecutionArgs","complete","Promise","resolve","reject","runIdGetter","off","on","convertMessageToGoogleGenAIMessage","message","TextMessage","role","user","assistant","system","text","content","parts","ActionExecutionMessage","functionCall","name","args","arguments","ResultMessage","functionResponse","actionName","response","tryParseJson","result","transformActionToGoogleGenAITool","action","description","parameters","JSON","parse","jsonSchema","transformProperties","props","key","type","toUpperCase","properties","functionDeclarations","str","e","import_shared","GoogleGenerativeAIAdapter","model","constructor","options","genAI","GoogleGenerativeAI","process","env","getGenerativeModel","request","messages","actions","eventSource","history","slice","map","convertMessageToGoogleGenAIMessage","currentMessage","at","Error","systemMessage","firstMessage","TextMessage","role","content","trim","tools","transformActionToGoogleGenAITool","isFirstGenGeminiPro","chat","startChat","parts","text","systemInstruction","result","sendMessageStream","stream","eventStream$","isTextMessage","chunk","chunkText","sendTextMessageStart","randomId","sendTextMessageContent","sendTextMessageEnd","calls","response","functionCalls","call","sendActionExecution","name","JSON","stringify","replaceNewlinesInObject","args","complete","threadId","obj","replace","Array","isArray","newObj","key","hasOwnProperty","import_shared","convertMessageToLangChainMessage","message","TextMessage","role","HumanMessage","content","AIMessage","SystemMessage","ActionExecutionMessage","tool_calls","id","args","arguments","name","ResultMessage","ToolMessage","result","tool_call_id","actionExecutionId","convertJsonSchemaToZodSchema","jsonSchema","required","type","spec","key","value","Object","entries","properties","includes","schema","z","object","optional","string","describe","description","number","boolean","itemSchema","items","array","convertActionInputToLangChainTool","actionInput","DynamicStructuredTool","JSON","parse","func","getConstructorName","constructor","isAIMessage","isAIMessageChunk","isBaseMessageChunk","maybeSendActionExecutionResultIsMessage","eventStream$","actionExecution","sendActionExecutionResult","streamLangChainResponse","sendTextMessage","randomId","toolCall","sendActionExecution","stringify","lc_kwargs","reader","getReader","mode","done","read","toolCallName","undefined","toolCallId","toolCallArgs","hasToolCall","chunk","tool_call_chunks","additional_kwargs","function","sendTextMessageEnd","sendActionExecutionEnd","sendActionExecutionStart","sendTextMessageStart","sendTextMessageContent","sendActionExecutionArgs","error","console","encodeResult","Error","complete","import_shared","LangChainAdapter","constructor","options","process","request","eventSource","model","actions","messages","threadId","runId","result","chainFn","map","convertMessageToLangChainMessage","tools","convertActionInputToLangChainTool","stream","eventStream$","streamLangChainResponse","randomId","RemoteChain","name","description","chainUrl","parameters","parameterType","constructor","options","toAction","inferLangServeParameters","handler","args","runnable","RemoteRunnable","url","input","Object","keys","invoke","supportedTypes","schemaUrl","replace","schema","fetch","then","res","json","catch","Error","includes","type","properties","map","key","property","required","import_openai","import_shared","UnifyAdapter","apiKey","model","start","constructor","options","process","request","tools","actions","map","convertActionInputToOpenAITool","openai","OpenAI","baseURL","messages","convertMessageToOpenAIMessage","stream","chat","completions","create","length","eventSource","eventStream$","mode","chunk","sendTextMessageStart","randomId","sendTextMessageContent","sendTextMessageEnd","toolCall","choices","delta","tool_calls","content","id","undefined","sendActionExecutionEnd","sendActionExecutionStart","function","name","arguments","sendActionExecutionArgs","complete","threadId","import_shared","DEFAULT_MODEL","GroqAdapter","model","_groq","groq","constructor","params","Groq","process","request","threadId","messages","actions","eventSource","forwardedParameters","tools","map","convertActionInputToOpenAITool","openaiMessages","convertMessageToOpenAIMessage","limitMessagesToTokenCount","toolChoice","type","function","name","toolChoiceFunctionName","stream","chat","completions","create","length","maxTokens","max_tokens","stop","tool_choice","eventStream$","mode","chunk","toolCall","choices","delta","tool_calls","content","id","sendTextMessageEnd","undefined","sendActionExecutionEnd","sendActionExecutionStart","sendTextMessageStart","sendTextMessageContent","arguments","sendActionExecutionArgs","complete","randomId","RuntimeEventTypes","RuntimeEventSubject","ReplaySubject","constructor","sendTextMessageStart","messageId","next","type","sendTextMessageContent","content","sendTextMessageEnd","sendTextMessage","sendActionExecutionStart","actionExecutionId","actionName","sendActionExecutionArgs","args","sendActionExecutionEnd","sendActionExecution","toolName","sendActionExecutionResult","result","RuntimeEventSource","eventStream$","callback","stream","process","serversideActions","guardrailsResult$","catch","error","console","pipe","map","event","scope","find","action","name","scan","acc","callActionServerSide","concatMap","eventWithState","toolCallEventStream$","executeAction","concat","of","actionArguments","status","firstValueFrom","complete","JSON","parse","handler","streamLangChainResponse","actionExecution","id","convertGqlInputToMessages","inputMessages","messages","message","textMessage","push","plainToInstance","TextMessage","id","createdAt","role","content","actionExecutionMessage","ActionExecutionMessage","name","arguments","JSON","parse","scope","resultMessage","ResultMessage","actionExecutionId","actionName","result","CopilotRuntime","actions","langserve","onBeforeRequest","onAfterRequest","constructor","params","chain","remoteChain","RemoteChain","push","toAction","middleware","process","request","serviceAdapter","messages","clientSideActionsInput","threadId","runId","properties","outputMessagesPromise","forwardedParameters","langserveFunctions","chainPromise","error","console","configuredActions","serverSideActionsInput","map","action","name","description","jsonSchema","JSON","stringify","actionParametersToJsonSchema","parameters","actionInputs","flattenToolCallsNoDuplicates","inputMessages","convertGqlInputToMessages","eventSource","RuntimeEventSource","result","then","outputMessages","_a","catch","_error","toolsByPriority","allTools","allToolNames","tool","includes","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","import_type_graphql","MessageRole","ActionExecutionScope","CopilotRequestType","registerEnumType","name","description","MessageInput","BaseMessage","textMessage","actionExecutionMessage","resultMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","InputType","content","role","String","MessageRole","name","arguments","scope","ActionExecutionScope","actionExecutionId","actionName","result","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","Field","String","InputType","FrontendInput","toDeprecate_fullContext","actions","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","import_type_graphql","ForwardedParametersInput","model","maxTokens","stop","toolChoice","toolChoiceFunctionName","Field","String","nullable","Number","InputType","GenerateCopilotResponseMetadataInput","requestType","Field","CopilotRequestType","nullable","InputType","GenerateCopilotResponseInput","metadata","threadId","runId","messages","frontend","cloud","forwardedParameters","String","MessageInput","FrontendInput","CloudInput","ForwardedParametersInput","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","FailedResponseStatusReason","reason","details","GraphQLJSON","nullable","ResponseStatusUnion","createUnionType","types","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","undefined","role","content","MessageRole","ObjectType","implements","name","scope","arguments","ActionExecutionScope","actionExecutionId","actionName","result","CopilotResponse","threadId","runId","messages","ResponseStatusUnion","nullable","import_graphql_scalars","import_class_transformer","GuardrailsValidationFailureResponse","FailedResponseStatus","reason","FailedResponseStatusReason","GUARDRAILS_VALIDATION_FAILED","constructor","guardrailsReason","details","MessageStreamInterruptedResponse","MESSAGE_STREAM_INTERRUPTED","messageId","description","UnknownErrorResponse","UNKNOWN_ERROR","import_shared","packageJson","require","telemetryClient","TelemetryClient","packageName","name","packageVersion","version","import_shared","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","console","log","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","generateCopilotResponse","ctx","properties","telemetry","capture","requestType","metadata","logger","child","component","debug","copilotRuntime","_copilotkit","runtime","serviceAdapter","copilotCloudBaseUrl","key","request","get","error","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","eventSource","threadId","randomId","runId","actions","frontend","publicApiKey","forwardedParameters","response","status","firstValueFrom","Repeater","pushMessage","stopStreamingMessages","result","next","GuardrailsValidationFailureResponse","guardrailsReason","reason","plainToInstance","TextMessage","id","createdAt","Date","err","UnknownErrorResponse","description","eventStreamSubscription","eventStream","serversideActions","pipe","shareReplay","finalize","subscribe","event","type","RuntimeEventTypes","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","streamingTextStatus","Subject","messageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","unsubscribe","TextMessageContent","push","complete","SuccessMessageStatus","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","streamingArgumentsStatus","actionExecutionId","name","actionName","scope","arguments","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","ActionExecutionArgs","args","ActionExecutionMessage","ActionExecutionResult","ResultMessage","SuccessResponseStatus","Query","String","Mutation","CopilotResponse","Ctx","Arg","GraphQLJSONObject","nullable","Resolver","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","logger","createLogger","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","cloud","telemetry","setCloudConfiguration","publicApiKey","baseUrl","setGlobalProperties","runtime","serviceAdapter","constructor","name","logging","plugins","useDeferStream","context","import_graphql_yoga","copilotRuntimeNextJSAppRouterEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","fetchAPI","Response","globalThis","handleRequest","GET","POST","OPTIONS","import_graphql_yoga","config","api","bodyParser","copilotRuntimeNextJSPagesRouterEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","import_graphql_yoga","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","copilotRuntimeNodeExpressEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","copilotRuntimeNodeHttpEndpoint","copilotRuntimeNestEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","copilotRuntimeNodeHttpEndpoint"]}
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/index.ts","../src/lib/copilot-runtime.ts","../src/service-adapters/openai/openai-adapter.ts","../src/graphql/types/base/index.ts","../src/graphql/types/converted/index.ts","../src/service-adapters/openai/utils.ts","../src/service-adapters/openai/openai-assistant-adapter.ts","../src/service-adapters/google/google-genai-adapter.ts","../src/service-adapters/google/utils.ts","../src/service-adapters/langchain/utils.ts","../src/service-adapters/langchain/langchain-adapter.ts","../src/service-adapters/langchain/langserve.ts","../src/service-adapters/unify/unify-adapter.ts","../src/service-adapters/groq/groq-adapter.ts","../src/service-adapters/events.ts","../src/service-adapters/conversion.ts","../src/lib/integrations/shared.ts","../src/graphql/resolvers/copilot.resolver.ts","../src/graphql/inputs/generate-copilot-response.input.ts","../src/graphql/inputs/message.input.ts","../src/graphql/types/enums.ts","../src/graphql/inputs/frontend.input.ts","../src/graphql/inputs/action.input.ts","../src/graphql/inputs/cloud.input.ts","../src/graphql/inputs/cloud-guardrails.input.ts","../src/graphql/inputs/forwarded-parameters.input.ts","../src/graphql/types/copilot-response.type.ts","../src/graphql/types/message-status.type.ts","../src/graphql/types/response-status.type.ts","../src/utils/failed-response-status-reasons.ts","../src/lib/telemetry-client.ts","../src/lib/logger.ts","../src/lib/integrations/nextjs/app-router.ts","../src/lib/integrations/nextjs/pages-router.ts","../src/lib/integrations/node-http/index.ts","../src/lib/integrations/node-express/index.ts","../src/lib/integrations/nest/index.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/runtime\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.1.2\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"dev\": \"tsup --watch --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__\",\n \"generate-graphql-schema\": \"rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts\"\n },\n \"devDependencies\": {\n \"@swc/core\": \"1.5.28\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jest\": \"^29.5.4\",\n \"@types/node\": \"^18.11.17\",\n \"@whatwg-node/server\": \"^0.9.34\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"nodemon\": \"^3.1.3\",\n \"ts-jest\": \"^29.1.1\",\n \"ts-node\": \"^10.9.2\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\"\n },\n \"dependencies\": {\n \"@copilotkit/shared\": \"workspace:*\",\n \"@google/generative-ai\": \"^0.11.2\",\n \"@graphql-yoga/plugin-defer-stream\": \"^3.3.1\",\n \"@langchain/community\": \"^0.0.53\",\n \"@langchain/core\": \"^0.1.61\",\n \"@langchain/openai\": \"^0.0.28\",\n \"class-transformer\": \"^0.5.1\",\n \"express\": \"^4.19.2\",\n \"graphql\": \"^16.8.1\",\n \"graphql-scalars\": \"^1.23.0\",\n \"graphql-yoga\": \"^5.3.1\",\n \"groq-sdk\": \"^0.5.0\",\n \"langchain\": \"^0.1.36\",\n \"openai\": \"^4.50.0\",\n \"pino\": \"^9.2.0\",\n \"pino-pretty\": \"^11.2.1\",\n \"reflect-metadata\": \"^0.2.2\",\n \"rxjs\": \"^7.8.1\",\n \"type-graphql\": \"2.0.0-rc.1\",\n \"zod\": \"^3.23.3\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import \"reflect-metadata\";\nexport * from \"./lib\";\nexport * from \"./utils\";\n","/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport { Action, actionParametersToJsonSchema, Parameter } from \"@copilotkit/shared\";\nimport { RemoteChain, RemoteChainParameters, CopilotServiceAdapter } from \"../service-adapters\";\nimport { MessageInput } from \"../graphql/inputs/message.input\";\nimport { ActionInput } from \"../graphql/inputs/action.input\";\nimport { RuntimeEventSource } from \"../service-adapters/events\";\nimport { convertGqlInputToMessages } from \"../service-adapters/conversion\";\nimport { Message } from \"../graphql/types/converted\";\nimport { ForwardedParametersInput } from \"../graphql/inputs/forwarded-parameters.input\";\n\ninterface CopilotRuntimeRequest {\n serviceAdapter: CopilotServiceAdapter;\n messages: MessageInput[];\n actions: ActionInput[];\n outputMessagesPromise: Promise<Message[]>;\n properties: any;\n threadId?: string;\n runId?: string;\n publicApiKey?: string;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface CopilotRuntimeResponse {\n threadId: string;\n runId?: string;\n eventSource: RuntimeEventSource;\n actions: Action<any>[];\n}\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n}\n\ntype OnBeforeRequestHandler = (options: OnBeforeRequestOptions) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n}\n\ntype OnAfterRequestHandler = (options: OnAfterRequestOptions) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed.\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n}\n\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n public actions: ActionsConfiguration<T>;\n private langserve: Promise<Action<any>>[] = [];\n private onBeforeRequest?: OnBeforeRequestHandler;\n private onAfterRequest?: OnAfterRequestHandler;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n this.actions = params?.actions || [];\n\n for (const chain of params?.langserve || []) {\n const remoteChain = new RemoteChain(chain);\n this.langserve.push(remoteChain.toAction());\n }\n\n this.onBeforeRequest = params?.middleware?.onBeforeRequest;\n this.onAfterRequest = params?.middleware?.onAfterRequest;\n }\n\n async process(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {\n const {\n serviceAdapter,\n messages,\n actions: clientSideActionsInput,\n threadId,\n runId,\n properties,\n outputMessagesPromise,\n forwardedParameters,\n } = request;\n const langserveFunctions: Action<any>[] = [];\n\n for (const chainPromise of this.langserve) {\n try {\n const chain = await chainPromise;\n langserveFunctions.push(chain);\n } catch (error) {\n console.error(\"Error loading langserve chain:\", error);\n }\n }\n\n const configuredActions =\n typeof this.actions === \"function\" ? this.actions({ properties }) : this.actions;\n\n const actions = [...configuredActions, ...langserveFunctions];\n\n const serverSideActionsInput: ActionInput[] = actions.map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const actionInputs = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...clientSideActionsInput,\n ]);\n const inputMessages = convertGqlInputToMessages(messages);\n\n await this.onBeforeRequest?.({\n threadId,\n runId,\n inputMessages,\n properties,\n });\n\n try {\n const eventSource = new RuntimeEventSource();\n\n const result = await serviceAdapter.process({\n messages: inputMessages,\n actions: actionInputs,\n threadId,\n runId,\n eventSource,\n forwardedParameters,\n });\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId: result.threadId,\n runId: result.runId,\n inputMessages,\n outputMessages,\n properties,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId: result.threadId,\n runId: result.runId,\n eventSource,\n actions: actions,\n };\n } catch (error) {\n console.error(\"Error getting response:\", error);\n throw error;\n }\n }\n}\n\nexport function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {\n let allTools: ActionInput[] = [];\n const allToolNames: string[] = [];\n for (const tool of toolsByPriority) {\n if (!allToolNames.includes(tool.name)) {\n allTools.push(tool);\n allToolNames.push(tool.name);\n }\n }\n return allTools;\n}\n","/**\n * Copilot Runtime adapter for OpenAI.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, OpenAIAdapter } from \"@copilotkit/runtime\";\n * import OpenAI from \"openai\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const openai = new OpenAI({\n * organization: \"<your-organization-id>\", // optional\n * apiKey: \"<your-api-key>\",\n * });\n *\n * const serviceAdapter = new OpenAIAdapter({ openai });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport OpenAI from \"openai\";\nimport {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToOpenAITool,\n convertMessageToOpenAIMessage,\n limitMessagesToTokenCount,\n} from \"./utils\";\nimport { randomId } from \"@copilotkit/shared\";\n\nconst DEFAULT_MODEL = \"gpt-4o\";\n\nexport interface OpenAIAdapterParams {\n /**\n * An optional OpenAI instance to use. If not provided, a new instance will be\n * created.\n */\n openai?: OpenAI;\n\n /**\n * The model to use.\n */\n model?: string;\n}\n\nexport class OpenAIAdapter implements CopilotServiceAdapter {\n private model: string = DEFAULT_MODEL;\n\n private _openai: OpenAI;\n public get openai(): OpenAI {\n return this._openai;\n }\n\n constructor(params?: OpenAIAdapterParams) {\n this._openai = params?.openai || new OpenAI({});\n if (params?.model) {\n this.model = params.model;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const {\n threadId,\n model = this.model,\n messages,\n actions,\n eventSource,\n forwardedParameters,\n } = request;\n const tools = actions.map(convertActionInputToOpenAITool);\n\n let openaiMessages = messages.map(convertMessageToOpenAIMessage);\n openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);\n\n let toolChoice: any = forwardedParameters?.toolChoice;\n if (forwardedParameters?.toolChoice === \"function\") {\n toolChoice = {\n type: \"function\",\n function: { name: forwardedParameters.toolChoiceFunctionName },\n };\n }\n\n const stream = this.openai.beta.chat.completions.stream({\n model: model,\n stream: true,\n messages: openaiMessages,\n ...(tools.length > 0 && { tools }),\n ...(forwardedParameters?.maxTokens && { max_tokens: forwardedParameters.maxTokens }),\n ...(forwardedParameters?.stop && { stop: forwardedParameters.stop }),\n ...(toolChoice && { tool_choice: toolChoice }),\n });\n\n eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n for await (const chunk of stream) {\n const toolCall = chunk.choices[0].delta.tool_calls?.[0];\n const content = chunk.choices[0].delta.content;\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCall?.id is defined, it means a new tool call starts.\n if (mode === \"message\" && toolCall?.id) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (toolCall === undefined || toolCall?.id)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (toolCall?.id) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCall!.id, toolCall!.function!.name);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(chunk.id);\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCall?.function?.arguments) {\n eventStream$.sendActionExecutionArgs(toolCall.function.arguments);\n }\n }\n\n // send the end events\n if (mode === \"message\") {\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd();\n }\n\n eventStream$.complete();\n });\n\n return {\n threadId: threadId || randomId(),\n };\n }\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessage {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import {\n ActionExecutionMessageInput,\n ResultMessageInput,\n TextMessageInput,\n} from \"../../inputs/message.input\";\nimport { BaseMessage } from \"../base\";\nimport { ActionExecutionScope, MessageRole } from \"../enums\";\n\nexport class TextMessage extends BaseMessage implements TextMessageInput {\n content: string;\n role: MessageRole;\n}\n\nexport type Message = BaseMessage;\n\nexport class ActionExecutionMessage\n extends BaseMessage\n implements Omit<ActionExecutionMessageInput, \"arguments\">\n{\n name: string;\n arguments: Record<string, any>;\n scope: ActionExecutionScope;\n}\n\nexport class ResultMessage extends BaseMessage implements ResultMessageInput {\n actionExecutionId: string;\n actionName: string;\n result: string;\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { ChatCompletionMessageParam, ChatCompletionTool } from \"openai/resources\";\n\nexport function limitMessagesToTokenCount(\n messages: any[],\n tools: any[],\n model: string,\n maxTokens?: number,\n): any[] {\n maxTokens ||= maxTokensForOpenAIModel(model);\n\n const result: any[] = [];\n const toolsNumTokens = countToolsTokens(model, tools);\n if (toolsNumTokens > maxTokens) {\n throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);\n }\n maxTokens -= toolsNumTokens;\n\n for (const message of messages) {\n if (message.role === \"system\") {\n const numTokens = countMessageTokens(model, message);\n maxTokens -= numTokens;\n\n if (maxTokens < 0) {\n throw new Error(\"Not enough tokens for system message.\");\n }\n }\n }\n\n let cutoff: boolean = false;\n\n const reversedMessages = [...messages].reverse();\n for (const message of reversedMessages) {\n if (message.role === \"system\") {\n result.unshift(message);\n continue;\n } else if (cutoff) {\n continue;\n }\n let numTokens = countMessageTokens(model, message);\n if (maxTokens < numTokens) {\n cutoff = true;\n continue;\n }\n result.unshift(message);\n maxTokens -= numTokens;\n }\n\n return result;\n}\n\nexport function maxTokensForOpenAIModel(model: string): number {\n return maxTokensByModel[model] || DEFAULT_MAX_TOKENS;\n}\n\nconst DEFAULT_MAX_TOKENS = 128000;\n\nconst maxTokensByModel: { [key: string]: number } = {\n // GPT-4\n \"gpt-4o\": 128000,\n \"gpt-4o-2024-05-13\": 128000,\n \"gpt-4-turbo\": 128000,\n \"gpt-4-turbo-2024-04-09\": 128000,\n \"gpt-4-0125-preview\": 128000,\n \"gpt-4-turbo-preview\": 128000,\n \"gpt-4-1106-preview\": 128000,\n \"gpt-4-vision-preview\": 128000,\n \"gpt-4-1106-vision-preview\": 128000,\n \"gpt-4-32k\": 32768,\n \"gpt-4-32k-0613\": 32768,\n \"gpt-4-32k-0314\": 32768,\n \"gpt-4\": 8192,\n \"gpt-4-0613\": 8192,\n \"gpt-4-0314\": 8192,\n\n // GPT-3.5\n \"gpt-3.5-turbo-0125\": 16385,\n \"gpt-3.5-turbo\": 16385,\n \"gpt-3.5-turbo-1106\": 16385,\n \"gpt-3.5-turbo-instruct\": 4096,\n \"gpt-3.5-turbo-16k\": 16385,\n \"gpt-3.5-turbo-0613\": 4096,\n \"gpt-3.5-turbo-16k-0613\": 16385,\n \"gpt-3.5-turbo-0301\": 4097,\n};\n\nfunction countToolsTokens(model: string, tools: any[]): number {\n if (tools.length === 0) {\n return 0;\n }\n const json = JSON.stringify(tools);\n return countTokens(model, json);\n}\n\nfunction countMessageTokens(model: string, message: any): number {\n return countTokens(model, message.content || \"\");\n}\n\nfunction countTokens(model: string, text: string): number {\n return text.length / 3;\n}\n\nexport function convertActionInputToOpenAITool(action: ActionInput): ChatCompletionTool {\n return {\n type: \"function\",\n function: {\n name: action.name,\n description: action.description,\n parameters: JSON.parse(action.jsonSchema),\n },\n };\n}\n\nexport function convertMessageToOpenAIMessage(message: Message): ChatCompletionMessageParam {\n if (message instanceof TextMessage) {\n return {\n role: message.role,\n content: message.content,\n };\n } else if (message instanceof ActionExecutionMessage) {\n return {\n role: \"assistant\",\n tool_calls: [\n {\n id: message.id,\n type: \"function\",\n function: {\n name: message.name,\n arguments: JSON.stringify(message.arguments),\n },\n },\n ],\n };\n } else if (message instanceof ResultMessage) {\n return {\n role: \"tool\",\n content: message.result,\n tool_call_id: message.actionExecutionId,\n };\n }\n}\n\nexport function convertSystemMessageToAssistantAPI(message: ChatCompletionMessageParam) {\n return {\n ...message,\n ...(message.role === \"system\" && {\n role: \"assistant\",\n content: \"THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: \" + message.content,\n }),\n };\n}\n","/**\n * Copilot Runtime adapter for the OpenAI Assistant API.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, OpenAIAssistantAdapter } from \"@copilotkit/runtime\";\n * import OpenAI from \"openai\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const openai = new OpenAI({\n * organization: \"<your-organization-id>\",\n * apiKey: \"<your-api-key>\",\n * });\n *\n * const serviceAdapter = new OpenAIAssistantAdapter({\n * openai,\n * assistantId: \"<your-assistant-id>\",\n * codeInterpreterEnabled: true,\n * fileSearchEnabled: true,\n * });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport OpenAI from \"openai\";\nimport {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport { Message, ResultMessage, TextMessage } from \"../../graphql/types/converted\";\nimport {\n convertActionInputToOpenAITool,\n convertMessageToOpenAIMessage,\n convertSystemMessageToAssistantAPI,\n} from \"./utils\";\nimport { RunSubmitToolOutputsStreamParams } from \"openai/resources/beta/threads/runs/runs\";\nimport { AssistantStream } from \"openai/lib/AssistantStream\";\nimport { RuntimeEventSource } from \"../events\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { AssistantStreamEvent, AssistantTool } from \"openai/resources/beta/assistants\";\nimport { ForwardedParametersInput } from \"../../graphql/inputs/forwarded-parameters.input\";\n\nexport interface OpenAIAssistantAdapterParams {\n /**\n * The ID of the assistant to use.\n */\n assistantId: string;\n\n /**\n * An optional OpenAI instance to use. If not provided, a new instance will be created.\n */\n openai?: OpenAI;\n\n /**\n * Whether to enable code interpretation.\n * @default true\n */\n codeInterpreterEnabled?: boolean;\n\n /**\n * Whether to enable file search.\n * @default true\n */\n fileSearchEnabled?: boolean;\n}\n\nexport class OpenAIAssistantAdapter implements CopilotServiceAdapter {\n private openai: OpenAI;\n private codeInterpreterEnabled: boolean;\n private assistantId: string;\n private fileSearchEnabled: boolean;\n\n constructor(params: OpenAIAssistantAdapterParams) {\n this.openai = params.openai || new OpenAI({});\n this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;\n this.fileSearchEnabled = params.fileSearchEnabled === false || true;\n this.assistantId = params.assistantId;\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource, runId, forwardedParameters } = request;\n // if we don't have a threadId, create a new thread\n let threadId = request.threadId || (await this.openai.beta.threads.create()).id;\n\n const lastMessage = messages.at(-1);\n\n let nextRunId: string | undefined = undefined;\n\n // submit function outputs\n if (lastMessage instanceof ResultMessage && runId) {\n nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);\n }\n // submit user message\n else if (lastMessage instanceof TextMessage) {\n nextRunId = await this.submitUserMessage(\n threadId,\n messages,\n actions,\n eventSource,\n forwardedParameters,\n );\n }\n // unsupported message\n else {\n throw new Error(\"No actionable message found in the messages\");\n }\n\n return {\n threadId,\n runId: nextRunId,\n };\n }\n\n private async submitToolOutputs(\n threadId: string,\n runId: string,\n messages: Message[],\n eventSource: RuntimeEventSource,\n ) {\n let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);\n if (!run.required_action) {\n throw new Error(\"No tool outputs required\");\n }\n\n // get the required tool call ids\n const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map(\n (toolCall) => toolCall.id,\n );\n\n // search for these tool calls\n const resultMessages = messages.filter(\n (message) =>\n message instanceof ResultMessage && toolCallsIds.includes(message.actionExecutionId),\n ) as ResultMessage[];\n\n if (toolCallsIds.length != resultMessages.length) {\n throw new Error(\"Number of function results does not match the number of tool calls\");\n }\n\n // submit the tool outputs\n const toolOutputs: RunSubmitToolOutputsStreamParams.ToolOutput[] = resultMessages.map(\n (message) => {\n return {\n tool_call_id: message.actionExecutionId,\n output: message.result,\n };\n },\n );\n\n const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {\n tool_outputs: toolOutputs,\n });\n\n await this.streamResponse(stream, eventSource);\n return runId;\n }\n\n private async submitUserMessage(\n threadId: string,\n messages: Message[],\n actions: ActionInput[],\n eventSource: RuntimeEventSource,\n forwardedParameters: ForwardedParametersInput,\n ) {\n messages = [...messages];\n\n // get the instruction message\n const instructionsMessage = messages.shift();\n const instructions =\n instructionsMessage instanceof TextMessage ? instructionsMessage.content : \"\";\n\n // get the latest user message\n const userMessage = messages\n .map(convertMessageToOpenAIMessage)\n .map(convertSystemMessageToAssistantAPI)\n .at(-1);\n\n if (userMessage.role !== \"user\") {\n throw new Error(\"No user message found\");\n }\n\n // create a new message on the thread\n await this.openai.beta.threads.messages.create(threadId, {\n role: \"user\",\n content: userMessage.content,\n });\n\n const openaiTools = actions.map(convertActionInputToOpenAITool);\n\n const tools = [\n ...openaiTools,\n ...(this.codeInterpreterEnabled ? [{ type: \"code_interpreter\" } as AssistantTool] : []),\n ...(this.fileSearchEnabled ? [{ type: \"file_search\" } as AssistantTool] : []),\n ];\n\n // run the thread\n let stream = this.openai.beta.threads.runs.stream(threadId, {\n assistant_id: this.assistantId,\n instructions,\n tools: tools,\n ...(forwardedParameters?.maxTokens && {\n max_completion_tokens: forwardedParameters.maxTokens,\n }),\n });\n\n await this.streamResponse(stream, eventSource);\n\n return getRunIdFromStream(stream);\n }\n\n private async streamResponse(stream: AssistantStream, eventSource: RuntimeEventSource) {\n eventSource.stream(async (eventStream$) => {\n let inFunctionCall = false;\n\n for await (const chunk of stream) {\n switch (chunk.event) {\n case \"thread.message.created\":\n if (inFunctionCall) {\n eventStream$.sendActionExecutionEnd();\n }\n eventStream$.sendTextMessageStart(chunk.data.id);\n break;\n case \"thread.message.delta\":\n if (chunk.data.delta.content?.[0].type === \"text\") {\n eventStream$.sendTextMessageContent(chunk.data.delta.content?.[0].text.value);\n }\n break;\n case \"thread.message.completed\":\n eventStream$.sendTextMessageEnd();\n break;\n case \"thread.run.step.delta\":\n let toolCallId: string | undefined;\n let toolCallName: string | undefined;\n let toolCallArgs: string | undefined;\n if (\n chunk.data.delta.step_details.type === \"tool_calls\" &&\n chunk.data.delta.step_details.tool_calls?.[0].type === \"function\"\n ) {\n toolCallId = chunk.data.delta.step_details.tool_calls?.[0].id;\n toolCallName = chunk.data.delta.step_details.tool_calls?.[0].function.name;\n toolCallArgs = chunk.data.delta.step_details.tool_calls?.[0].function.arguments;\n }\n\n if (toolCallName && toolCallId) {\n if (inFunctionCall) {\n eventStream$.sendActionExecutionEnd();\n }\n inFunctionCall = true;\n eventStream$.sendActionExecutionStart(toolCallId, toolCallName);\n } else if (toolCallArgs) {\n eventStream$.sendActionExecutionArgs(toolCallArgs);\n }\n break;\n }\n }\n if (inFunctionCall) {\n eventStream$.sendActionExecutionEnd();\n }\n eventStream$.complete();\n });\n }\n}\n\nfunction getRunIdFromStream(stream: AssistantStream): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let runIdGetter = (event: AssistantStreamEvent) => {\n if (event.event === \"thread.run.created\") {\n const runId = event.data.id;\n stream.off(\"event\", runIdGetter);\n resolve(runId);\n }\n };\n stream.on(\"event\", runIdGetter);\n });\n}\n","/**\n * Copilot Runtime adapter for Google Generative AI (e.g. Gemini).\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, GoogleGenerativeAIAdapter } from \"@copilotkit/runtime\";\n * const { GoogleGenerativeAI } = require(\"@google/generative-ai\");\n *\n * const genAI = new GoogleGenerativeAI(process.env[\"GOOGLE_API_KEY\"]);\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const model = genAI.getGenerativeModel({\n * model: \"gemini-pro\"\n * });\n *\n * const serviceAdapter = new GoogleGenerativeAIAdapter({ model });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport { CopilotServiceAdapter } from \"../service-adapter\";\nimport {\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport { GenerativeModel, GoogleGenerativeAI } from \"@google/generative-ai\";\nimport { TextMessage } from \"../../graphql/types/converted\";\nimport { convertMessageToGoogleGenAIMessage, transformActionToGoogleGenAITool } from \"./utils\";\nimport { randomId } from \"@copilotkit/shared\";\n\ninterface GoogleGenerativeAIAdapterOptions {\n /**\n * A custom Google Generative AI model to use.\n */\n model?: GenerativeModel;\n}\n\nexport class GoogleGenerativeAIAdapter implements CopilotServiceAdapter {\n private model: GenerativeModel;\n\n constructor(options?: GoogleGenerativeAIAdapterOptions) {\n if (options?.model) {\n this.model = options.model;\n } else {\n const genAI = new GoogleGenerativeAI(process.env[\"GOOGLE_API_KEY\"]!);\n this.model = genAI.getGenerativeModel({ model: \"gemini-pro\" });\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { messages, actions, eventSource } = request;\n\n // get the history (everything except the first and last message)\n const history = messages.slice(1, -1).map(convertMessageToGoogleGenAIMessage);\n\n // get the current message (the last message)\n const currentMessage = convertMessageToGoogleGenAIMessage(messages.at(-1));\n if (!currentMessage) {\n throw new Error(\"No current message\");\n }\n\n let systemMessage: string;\n const firstMessage = messages.at(0);\n if (firstMessage instanceof TextMessage && firstMessage.role === \"system\") {\n systemMessage = firstMessage.content.trim();\n } else {\n throw new Error(\"First message is not a system message\");\n }\n\n const tools = actions.map(transformActionToGoogleGenAITool);\n\n const isFirstGenGeminiPro =\n this.model.model === \"gemini-pro\" || this.model.model === \"models/gemini-pro\";\n\n const chat = this.model.startChat({\n history: [\n ...history,\n // gemini-pro does not support system instructions, so we need to add them to the history\n ...(isFirstGenGeminiPro ? [{ role: \"user\", parts: [{ text: systemMessage }] }] : []),\n ],\n // only gemini-1.5-pro-latest and later supports setting system instructions\n ...(isFirstGenGeminiPro\n ? {}\n : { systemInstruction: { role: \"user\", parts: [{ text: systemMessage }] } }),\n tools,\n });\n\n const result = await chat.sendMessageStream(currentMessage.parts);\n\n eventSource.stream(async (eventStream$) => {\n let isTextMessage = false;\n for await (const chunk of result.stream) {\n const chunkText = chunk.text();\n if (chunkText === \"\") {\n continue;\n }\n if (!isTextMessage) {\n isTextMessage = true;\n eventStream$.sendTextMessageStart(randomId());\n }\n eventStream$.sendTextMessageContent(chunkText);\n }\n if (isTextMessage) {\n eventStream$.sendTextMessageEnd();\n }\n\n let calls = (await result.response).functionCalls();\n if (calls) {\n for (let call of calls) {\n eventStream$.sendActionExecution(\n randomId(),\n call.name,\n JSON.stringify(replaceNewlinesInObject(call.args)),\n );\n }\n }\n eventStream$.complete();\n });\n\n return {\n threadId: request.threadId || randomId(),\n };\n }\n}\n\nfunction replaceNewlinesInObject(obj: any): any {\n if (typeof obj === \"string\") {\n return obj.replace(/\\\\\\\\n/g, \"\\n\");\n } else if (Array.isArray(obj)) {\n return obj.map(replaceNewlinesInObject);\n } else if (typeof obj === \"object\" && obj !== null) {\n const newObj: any = {};\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n newObj[key] = replaceNewlinesInObject(obj[key]);\n }\n }\n return newObj;\n }\n return obj;\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport { Tool } from \"@google/generative-ai\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\n\nexport function convertMessageToGoogleGenAIMessage(message: Message) {\n if (message instanceof TextMessage) {\n const role = {\n user: \"user\",\n assistant: \"model\",\n system: \"user\",\n }[message.role];\n\n const text =\n message.role === \"system\"\n ? \"THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: \" + message.content\n : message.content;\n\n return {\n role,\n parts: [{ text }],\n };\n } else if (message instanceof ActionExecutionMessage) {\n return {\n role: \"model\",\n parts: [\n {\n functionCall: {\n name: message.name,\n args: message.arguments,\n },\n },\n ],\n };\n } else if (message instanceof ResultMessage) {\n return {\n role: \"function\",\n parts: [\n {\n functionResponse: {\n name: message.actionName,\n response: {\n name: message.actionName,\n content: tryParseJson(message.result),\n },\n },\n },\n ],\n };\n }\n}\n\nexport function transformActionToGoogleGenAITool(action: ActionInput): Tool {\n const name = action.name;\n const description = action.description;\n const parameters = JSON.parse(action.jsonSchema);\n\n const transformProperties = (props: any) => {\n for (const key in props) {\n if (props[key].type) {\n props[key].type = props[key].type.toUpperCase();\n }\n if (props[key].properties) {\n transformProperties(props[key].properties);\n }\n }\n };\n transformProperties(parameters);\n\n return {\n functionDeclarations: [\n {\n name,\n description,\n parameters,\n },\n ],\n };\n}\n\nfunction tryParseJson(str?: string) {\n if (!str) {\n return \"\";\n }\n try {\n return JSON.parse(str);\n } catch (e) {\n return str;\n }\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { LangChainReturnType } from \"./types\";\nimport { RuntimeEventSubject } from \"../events\";\nimport { randomId } from \"@copilotkit/shared\";\n\nexport function convertMessageToLangChainMessage(message: Message): BaseMessage {\n if (message instanceof TextMessage) {\n if (message.role == \"user\") {\n return new HumanMessage(message.content);\n } else if (message.role == \"assistant\") {\n return new AIMessage(message.content);\n } else if (message.role === \"system\") {\n return new SystemMessage(message.content);\n }\n } else if (message instanceof ActionExecutionMessage) {\n return new AIMessage({\n content: \"\",\n tool_calls: [\n {\n id: message.id,\n args: message.arguments,\n name: message.name,\n },\n ],\n });\n } else if (message instanceof ResultMessage) {\n return new ToolMessage({\n content: message.result,\n tool_call_id: message.actionExecutionId,\n });\n }\n}\n\nexport function convertJsonSchemaToZodSchema(jsonSchema: any, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n let schema = z.object(spec);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description);\n return !required ? schema.optional() : schema;\n } else if (jsonSchema.type === \"array\") {\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, false);\n let schema = z.array(itemSchema);\n return !required ? schema.optional() : schema;\n }\n}\n\nexport function convertActionInputToLangChainTool(actionInput: ActionInput): any {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(\n JSON.parse(actionInput.jsonSchema),\n true,\n ) as z.ZodObject<any>,\n func: async () => {\n return \"\";\n },\n });\n}\n\ninterface StreamLangChainResponseParams {\n result: LangChainReturnType;\n eventStream$: RuntimeEventSubject;\n actionExecution?: {\n id: string;\n name: string;\n };\n}\n\nfunction getConstructorName(object: any): string {\n if (object && typeof object === \"object\" && object.constructor && object.constructor.name) {\n return object.constructor.name;\n }\n return \"\";\n}\n\nfunction isAIMessage(message: any): message is AIMessage {\n return getConstructorName(message) === \"AIMessage\";\n}\n\nfunction isAIMessageChunk(message: any): message is AIMessageChunk {\n return getConstructorName(message) === \"AIMessageChunk\";\n}\n\nfunction isBaseMessageChunk(message: any): message is BaseMessageChunk {\n return getConstructorName(message) === \"BaseMessageChunk\";\n}\n\nfunction maybeSendActionExecutionResultIsMessage(\n eventStream$: RuntimeEventSubject,\n actionExecution?: { id: string; name: string },\n) {\n // language models need a result after the function call\n // we simply let them know that we are sending a message\n if (actionExecution) {\n eventStream$.sendActionExecutionResult(\n actionExecution.id,\n actionExecution.name,\n \"Sending a message\",\n );\n }\n}\n\nexport async function streamLangChainResponse({\n result,\n eventStream$,\n actionExecution,\n}: StreamLangChainResponseParams) {\n // We support several types of return values from LangChain functions:\n\n // 1. string\n\n if (typeof result === \"string\") {\n if (!actionExecution) {\n // Just send one chunk with the string as the content.\n eventStream$.sendTextMessage(randomId(), result);\n } else {\n // Send as a result\n eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);\n }\n }\n\n // 2. AIMessage\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isAIMessage(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n for (const toolCall of result.tool_calls) {\n eventStream$.sendActionExecution(\n toolCall.id || randomId(),\n toolCall.name,\n JSON.stringify(toolCall.args),\n );\n }\n }\n\n // 3. BaseMessageChunk\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isBaseMessageChunk(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.lc_kwargs?.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n if (result.lc_kwargs?.tool_calls) {\n for (const toolCall of result.lc_kwargs?.tool_calls) {\n eventStream$.sendActionExecution(\n toolCall.id || randomId(),\n toolCall.name,\n JSON.stringify(toolCall.args),\n );\n }\n }\n }\n\n // 4. IterableReadableStream\n // Stream the result of the LangChain function.\n else if (result && \"getReader\" in result) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n let reader = result.getReader();\n\n let mode: \"function\" | \"message\" | null = null;\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n let toolCallName: string | undefined = undefined;\n let toolCallId: string | undefined = undefined;\n let toolCallArgs: string | undefined = undefined;\n let hasToolCall: boolean = false;\n let content = value?.content as string;\n\n if (isAIMessageChunk(value)) {\n let chunk = value.tool_call_chunks?.[0];\n toolCallName = chunk?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.args;\n hasToolCall = chunk != undefined;\n } else if (isBaseMessageChunk(value)) {\n let chunk = value.additional_kwargs?.tool_calls?.[0];\n toolCallName = chunk?.function?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.function?.arguments;\n hasToolCall = chunk?.function != undefined;\n }\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCallName is defined, it means a new tool call starts.\n if (mode === \"message\" && (toolCallId || done)) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (!hasToolCall || done)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n if (done) {\n break;\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (hasToolCall) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCallId, toolCallName);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(randomId());\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCallArgs) {\n eventStream$.sendActionExecutionArgs(toolCallArgs);\n }\n } catch (error) {\n console.error(\"Error reading from stream\", error);\n break;\n }\n }\n } else if (actionExecution) {\n eventStream$.sendActionExecutionResult(\n actionExecution.id,\n actionExecution.name,\n encodeResult(result),\n );\n }\n\n // unsupported type\n else {\n throw new Error(\"Invalid return type from LangChain function.\");\n }\n\n eventStream$.complete();\n}\n\nfunction encodeResult(result: any): string {\n if (result === undefined) {\n return \"\";\n } else if (typeof result === \"string\") {\n return result;\n } else {\n return JSON.stringify(result);\n }\n}\n","/**\n * Copilot Runtime adapter for LangChain.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, LangChainAdapter } from \"@copilotkit/runtime\";\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * apiKey: \"<your-api-key>\",\n * });\n *\n * const serviceAdapter = new LangChainAdapter({\n * chainFn: async ({ messages, tools }) => {\n * return model.stream(messages, { tools });\n * }\n * });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n *\n * The asynchronous handler function (`chainFn`) can return any of the following:\n *\n * - A simple `string` response\n * - A LangChain stream (`IterableReadableStream`)\n * - A LangChain `BaseMessageChunk` object\n * - A LangChain `AIMessage` object\n */\n\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { CopilotServiceAdapter } from \"../service-adapter\";\nimport {\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToLangChainTool,\n convertMessageToLangChainMessage,\n streamLangChainResponse,\n} from \"./utils\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { LangChainReturnType } from \"./types\";\nimport { randomId } from \"@copilotkit/shared\";\n\ninterface ChainFnParameters {\n model: string;\n messages: BaseMessage[];\n tools: DynamicStructuredTool[];\n threadId?: string;\n runId?: string;\n}\n\ninterface LangChainAdapterOptions {\n /**\n * A function that uses the LangChain API to generate a response.\n */\n chainFn: (parameters: ChainFnParameters) => Promise<LangChainReturnType>;\n}\n\nexport class LangChainAdapter implements CopilotServiceAdapter {\n /**\n * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.\n */\n constructor(private options: LangChainAdapterOptions) {}\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const { eventSource, model, actions, messages, threadId, runId } = request;\n const result = await this.options.chainFn({\n messages: messages.map(convertMessageToLangChainMessage),\n tools: actions.map(convertActionInputToLangChainTool),\n model,\n threadId,\n runId,\n });\n\n eventSource.stream(async (eventStream$) => {\n await streamLangChainResponse({\n result,\n eventStream$,\n });\n });\n\n return {\n threadId: threadId || randomId(),\n };\n }\n}\n","import { Parameter, Action } from \"@copilotkit/shared\";\nimport { RemoteRunnable } from \"langchain/runnables/remote\";\n\nexport interface RemoteChainParameters {\n name: string;\n description: string;\n chainUrl: string;\n parameters?: Parameter[];\n parameterType?: \"single\" | \"multi\";\n}\n\nexport class RemoteChain {\n name: string;\n description: string;\n chainUrl: string;\n parameters?: Parameter[];\n parameterType: \"single\" | \"multi\";\n\n constructor(options: RemoteChainParameters) {\n this.name = options.name;\n this.description = options.description;\n this.chainUrl = options.chainUrl;\n this.parameters = options.parameters;\n this.parameterType = options.parameterType || \"multi\";\n }\n\n async toAction(): Promise<Action<any>> {\n if (!this.parameters) {\n await this.inferLangServeParameters();\n }\n\n return {\n name: this.name,\n description: this.description,\n parameters: this.parameters!,\n handler: async (args: any) => {\n const runnable = new RemoteRunnable({ url: this.chainUrl });\n let input: any;\n if (this.parameterType === \"single\") {\n input = args[Object.keys(args)[0]];\n } else {\n input = args;\n }\n return await runnable.invoke(input);\n },\n };\n }\n\n async inferLangServeParameters() {\n const supportedTypes = [\"string\", \"number\", \"boolean\"];\n\n let schemaUrl = this.chainUrl.replace(/\\/+$/, \"\") + \"/input_schema\";\n let schema = await fetch(schemaUrl)\n .then((res) => res.json())\n .catch(() => {\n throw new Error(\"Failed to fetch langserve schema at \" + schemaUrl);\n });\n // for now, don't use json schema, just do a simple conversion\n\n if (supportedTypes.includes(schema.type)) {\n this.parameterType = \"single\";\n this.parameters = [\n {\n name: \"input\",\n type: schema.type,\n description: \"The input to the chain\",\n },\n ];\n } else if (schema.type === \"object\") {\n this.parameterType = \"multi\";\n this.parameters = Object.keys(schema.properties).map((key) => {\n let property = schema.properties[key];\n if (!supportedTypes.includes(property.type)) {\n throw new Error(\"Unsupported schema type\");\n }\n return {\n name: key,\n type: property.type,\n description: property.description || \"\",\n required: schema.required?.includes(key) || false,\n };\n });\n } else {\n throw new Error(\"Unsupported schema type\");\n }\n }\n}\n","/**\n * CopilotKit Adapter for Unify\n *\n * <RequestExample>\n * ```jsx CopilotRuntime Example\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new UnifyAdapter());\n * ```\n * </RequestExample>\n *\n * You can easily set the model to use by passing it to the constructor.\n * ```jsx\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(\n * req,\n * new UnifyAdapter({ model: \"llama-3-8b-chat@fireworks-ai\" }),\n * );\n * ```\n */\nimport { TextMessage } from \"../../graphql/types/converted\";\nimport {\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n CopilotServiceAdapter,\n} from \"../service-adapter\";\nimport OpenAI from \"openai\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { convertActionInputToOpenAITool, convertMessageToOpenAIMessage } from \"../openai/utils\";\n\nexport interface UnifyAdapterParams {\n apiKey?: string;\n model: string;\n}\n\nexport class UnifyAdapter implements CopilotServiceAdapter {\n private apiKey: string;\n private model: string;\n private start: boolean;\n\n constructor(options?: UnifyAdapterParams) {\n if (options?.apiKey) {\n this.apiKey = options.apiKey;\n } else {\n this.apiKey = \"UNIFY_API_KEY\";\n }\n this.model = options?.model;\n this.start = true;\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const tools = request.actions.map(convertActionInputToOpenAITool);\n const openai = new OpenAI({\n apiKey: this.apiKey,\n baseURL: \"https://api.unify.ai/v0/\",\n });\n\n const messages = request.messages.map(convertMessageToOpenAIMessage);\n\n const stream = await openai.chat.completions.create({\n model: this.model,\n messages: messages,\n stream: true,\n ...(tools.length > 0 && { tools }),\n });\n\n let model = null;\n request.eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n for await (const chunk of stream) {\n if (this.start) {\n model = chunk.model;\n eventStream$.sendTextMessageStart(randomId());\n eventStream$.sendTextMessageContent(`Model used: ${model}\\n`);\n eventStream$.sendTextMessageEnd();\n this.start = false;\n }\n const toolCall = chunk.choices[0].delta.tool_calls?.[0];\n const content = chunk.choices[0].delta.content;\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCall?.id is defined, it means a new tool call starts.\n if (mode === \"message\" && toolCall?.id) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (toolCall === undefined || toolCall?.id)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (toolCall?.id) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCall!.id, toolCall!.function!.name);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(chunk.id);\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCall?.function?.arguments) {\n eventStream$.sendActionExecutionArgs(toolCall.function.arguments);\n }\n }\n\n // send the end events\n if (mode === \"message\") {\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd();\n }\n\n eventStream$.complete();\n });\n\n return {\n threadId: request.threadId || randomId(),\n };\n }\n}\n","/**\n * Copilot Runtime adapter for OpenAI.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, GroqAdapter } from \"@copilotkit/runtime\";\n * import { Groq } from \"groq-sdk\";\n *\n * const groq = new Groq({ apiKey: process.env[\"GROQ_API_KEY\"] });\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const serviceAdapter = new GroqAdapter({ groq, model: \"<model-name>\" });\n *\n * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter);\n * ```\n */\nimport { Groq } from \"groq-sdk\";\nimport {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToOpenAITool,\n convertMessageToOpenAIMessage,\n limitMessagesToTokenCount,\n} from \"../openai/utils\";\nimport { randomId } from \"@copilotkit/shared\";\n\nconst DEFAULT_MODEL = \"llama3-groq-70b-8192-tool-use-preview\";\n\nexport interface GroqAdapterParams {\n /**\n * An optional Groq instance to use.\n */\n groq?: Groq;\n\n /**\n * The model to use.\n */\n model?: string;\n}\n\nexport class GroqAdapter implements CopilotServiceAdapter {\n private model: string = DEFAULT_MODEL;\n\n private _groq: Groq;\n public get groq(): Groq {\n return this._groq;\n }\n\n constructor(params?: GroqAdapterParams) {\n this._groq = params?.groq || new Groq({});\n if (params?.model) {\n this.model = params.model;\n }\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const {\n threadId,\n model = this.model,\n messages,\n actions,\n eventSource,\n forwardedParameters,\n } = request;\n const tools = actions.map(convertActionInputToOpenAITool);\n\n let openaiMessages = messages.map(convertMessageToOpenAIMessage);\n openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);\n\n let toolChoice: any = forwardedParameters?.toolChoice;\n if (forwardedParameters?.toolChoice === \"function\") {\n toolChoice = {\n type: \"function\",\n function: { name: forwardedParameters.toolChoiceFunctionName },\n };\n }\n const stream = await this.groq.chat.completions.create({\n model: model,\n stream: true,\n messages: openaiMessages,\n ...(tools.length > 0 && { tools }),\n ...(forwardedParameters?.maxTokens && {\n max_tokens: forwardedParameters.maxTokens,\n }),\n ...(forwardedParameters?.stop && { stop: forwardedParameters.stop }),\n ...(toolChoice && { tool_choice: toolChoice }),\n });\n\n eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n for await (const chunk of stream) {\n const toolCall = chunk.choices[0].delta.tool_calls?.[0];\n const content = chunk.choices[0].delta.content;\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCall?.id is defined, it means a new tool call starts.\n if (mode === \"message\" && toolCall?.id) {\n mode = null;\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\" && (toolCall === undefined || toolCall?.id)) {\n mode = null;\n eventStream$.sendActionExecutionEnd();\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (toolCall?.id) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart(toolCall!.id, toolCall!.function!.name);\n } else if (content) {\n mode = \"message\";\n eventStream$.sendTextMessageStart(chunk.id);\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent(content);\n } else if (mode === \"function\" && toolCall?.function?.arguments) {\n eventStream$.sendActionExecutionArgs(toolCall.function.arguments);\n }\n }\n\n // send the end events\n if (mode === \"message\") {\n eventStream$.sendTextMessageEnd();\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd();\n }\n\n eventStream$.complete();\n });\n\n return {\n threadId: threadId || randomId(),\n };\n }\n}\n","import { Action } from \"@copilotkit/shared\";\nimport { of, concat, map, scan, concatMap, ReplaySubject, Subject, firstValueFrom } from \"rxjs\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n}\n\ntype FunctionCallScope = \"client\" | \"server\";\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n scope?: FunctionCallScope;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n };\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart(messageId: string) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId });\n }\n\n sendTextMessageContent(content: string) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content });\n }\n\n sendTextMessageEnd() {\n this.next({ type: RuntimeEventTypes.TextMessageEnd });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart(messageId);\n this.sendTextMessageContent(content);\n this.sendTextMessageEnd();\n }\n\n sendActionExecutionStart(actionExecutionId: string, actionName: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n });\n }\n\n sendActionExecutionArgs(args: string) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args });\n }\n\n sendActionExecutionEnd() {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd });\n }\n\n sendActionExecution(actionExecutionId: string, toolName: string, args: string) {\n this.sendActionExecutionStart(actionExecutionId, toolName);\n this.sendActionExecutionArgs(args);\n this.sendActionExecutionEnd();\n }\n\n sendActionExecutionResult(actionExecutionId: string, actionName: string, result: string) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n process({\n serversideActions,\n guardrailsResult$,\n }: {\n serversideActions: Action<any>[];\n guardrailsResult$?: Subject<GuardrailsResult>;\n }) {\n this.callback(this.eventStream$).catch((error) => {\n console.error(\"Error in event source callback\", error);\n });\n return this.eventStream$.pipe(\n // mark tools for server side execution\n map((event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n event.scope = serversideActions.find((action) => action.name === event.actionName)\n ? \"server\"\n : \"client\";\n }\n return event;\n }),\n // track state\n scan(\n (acc, event) => {\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide = event.scope === \"server\";\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serversideActions.find((action) => action.name === event.actionName);\n }\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n guardrailsResult$ ? guardrailsResult$ : null,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionId,\n ).catch((error) => {\n console.error(error);\n });\n return concat(of(eventWithState.event!), toolCallEventStream$);\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n guardrailsResult$: Subject<GuardrailsResult> | null,\n action: Action<any>,\n actionArguments: string,\n actionExecutionId: string,\n) {\n if (guardrailsResult$) {\n const { status } = await firstValueFrom(guardrailsResult$);\n\n if (status === \"denied\") {\n eventStream$.complete();\n return;\n }\n }\n\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n args = JSON.parse(actionArguments);\n }\n\n // call the function\n const result = await action.handler(args);\n\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n },\n });\n}\n","import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../graphql/types/converted\";\nimport { MessageInput } from \"../graphql/inputs/message.input\";\nimport { plainToInstance } from \"class-transformer\";\n\nexport function convertGqlInputToMessages(inputMessages: MessageInput[]): Message[] {\n const messages: Message[] = [];\n\n for (const message of inputMessages) {\n if (message.textMessage) {\n messages.push(\n plainToInstance(TextMessage, {\n id: message.id,\n createdAt: message.createdAt,\n role: message.textMessage.role,\n content: message.textMessage.content,\n }),\n );\n } else if (message.actionExecutionMessage) {\n messages.push(\n plainToInstance(ActionExecutionMessage, {\n id: message.id,\n createdAt: message.createdAt,\n name: message.actionExecutionMessage.name,\n arguments: JSON.parse(message.actionExecutionMessage.arguments),\n scope: message.actionExecutionMessage.scope,\n }),\n );\n } else if (message.resultMessage) {\n messages.push(\n plainToInstance(ResultMessage, {\n id: message.id,\n createdAt: message.createdAt,\n actionExecutionId: message.resultMessage.actionExecutionId,\n actionName: message.resultMessage.actionName,\n result: message.resultMessage.result,\n }),\n );\n }\n }\n\n return messages;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\nimport telemetry from \"../telemetry-client\";\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n\n const contextLogger = createLogger({ level: logLevel });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter.constructor.name,\n },\n });\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream()],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport { MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport { RuntimeEvent, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport { ActionExecutionMessage, Message, ResultMessage, TextMessage } from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n console.log(\"invokeGuardrails.baseUrl\", baseUrl);\n\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Mutation(() => CopilotResponse)\n async generateCopilotResponse(\n @Ctx() ctx: GraphQLContext,\n @Arg(\"data\") data: GenerateCopilotResponseInput,\n @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n properties?: CopilotRequestContextProperties,\n ) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": data.cloud?.guardrails !== undefined,\n requestType: data.metadata.requestType,\n });\n\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n const key = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (key) {\n logger.debug(\"Public API key found in headers\");\n copilotCloudPublicApiKey = key;\n } else {\n logger.error(\"Public API key not found in headers\");\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.cloud?.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n logger.debug(\"Processing\");\n const {\n eventSource,\n threadId = randomId(),\n runId,\n actions,\n } = await copilotRuntime.process({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions,\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: undefined,\n properties: ctx.properties || {},\n outputMessagesPromise,\n forwardedParameters: data.forwardedParameters,\n });\n\n logger.debug(\"Event source created, creating response\");\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: randomId(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n // run and process the event stream\n const eventStream = eventSource\n .process({\n serversideActions: actions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n })\n .pipe(\n // shareReplay() ensures that later subscribers will see the whole stream instead of\n // just the events that were emitted after the subscriber was added.\n shareReplay(),\n finalize(() => {\n logger.debug(\"Event stream finalized\");\n }),\n );\n\n logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\n ////////////////////////////////\n // TextMessageStart\n ////////////////////////////////\n case RuntimeEventTypes.TextMessageStart:\n // create a sub stream that contains the message content\n const textMessageContentStream = eventStream.pipe(\n // skip until this message start event\n skipWhile((e) => e !== event),\n // take until the message end event\n takeWhile((e) => e.type != RuntimeEventTypes.TextMessageEnd),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = randomId();\n\n // push the new message\n pushMessage({\n id: messageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e) => e !== event),\n takeWhile((e) => e.type != RuntimeEventTypes.ActionExecutionEnd),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n scope: event.scope!,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: randomId(),\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: randomId(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in event stream\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\nimport { CopilotRequestType } from \"../types/enums\";\nimport { ForwardedParametersInput } from \"./forwarded-parameters.input\";\n\n@InputType()\nexport class GenerateCopilotResponseMetadataInput {\n @Field(() => CopilotRequestType, { nullable: true })\n requestType: CopilotRequestType;\n}\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => GenerateCopilotResponseMetadataInput, { nullable: false })\n metadata: GenerateCopilotResponseMetadataInput;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n\n @Field(() => ForwardedParametersInput, { nullable: true })\n forwardedParameters?: ForwardedParametersInput;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"../types/enums\";\nimport { BaseMessage } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessage {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n}\n\nexport enum ActionExecutionScope {\n server = \"server\",\n client = \"client\",\n}\n\nexport enum CopilotRequestType {\n Chat = \"Chat\",\n Task = \"Task\",\n TextareaCompletion = \"TextareaCompletion\",\n TextareaPopover = \"TextareaPopover\",\n Suggestion = \"Suggestion\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(ActionExecutionScope, {\n name: \"ActionExecutionScope\",\n description: \"The scope of the action\",\n});\n\nregisterEnumType(CopilotRequestType, {\n name: \"CopilotRequestType\",\n description: \"The type of Copilot request\",\n});\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: false })\n inputValidationRules: GuardrailsRuleInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ForwardedParametersInput {\n @Field(() => String, { nullable: true })\n model?: string;\n\n @Field(() => Number, { nullable: true })\n maxTokens?: number;\n\n @Field(() => [String], { nullable: true })\n stop?: string[];\n\n @Field(() => String, { nullable: true })\n toolChoice?: String;\n\n @Field(() => String, { nullable: true })\n toolChoiceFunctionName?: string;\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole, ActionExecutionScope } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n }\n return undefined;\n },\n})\nabstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => ActionExecutionScope)\n scope: ActionExecutionScope;\n\n @Field(() => [String])\n arguments: string[];\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { GraphQLJSON } from \"graphql-scalars\";\nimport { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\nexport enum FailedResponseStatusReason {\n GUARDRAILS_VALIDATION_FAILED = \"GUARDRAILS_VALIDATION_FAILED\",\n MESSAGE_STREAM_INTERRUPTED = \"MESSAGE_STREAM_INTERRUPTED\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nregisterEnumType(FailedResponseStatusReason, {\n name: \"FailedResponseStatusReason\",\n});\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => FailedResponseStatusReason)\n reason: FailedResponseStatusReason;\n\n @Field(() => GraphQLJSON, { nullable: true })\n details?: Record<string, any> = null;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import {\n FailedResponseStatus,\n FailedResponseStatusReason,\n} from \"../graphql/types/response-status.type\";\n\nexport class GuardrailsValidationFailureResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;\n declare details: {\n guardrailsReason: string;\n };\n\n constructor({ guardrailsReason }) {\n super();\n this.details = {\n guardrailsReason,\n };\n }\n}\n\nexport class MessageStreamInterruptedResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;\n declare details: {\n messageId: string;\n description: string;\n };\n\n constructor({ messageId }: { messageId: string }) {\n super();\n this.details = {\n messageId,\n description: \"Check the message for mode details\",\n };\n }\n}\n\nexport class UnknownErrorResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.UNKNOWN_ERROR;\n declare details: {\n description?: string;\n };\n\n constructor({ description }: { description?: string }) {\n super();\n this.details = {\n description,\n };\n }\n}\n","import { TelemetryClient } from \"@copilotkit/shared\";\nconst packageJson = require(\"../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport default telemetryClient;\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n fetchAPI: { Response: globalThis.Response },\n });\n\n return {\n handleRequest: yoga,\n GET: yoga as any,\n POST: yoga as any,\n OPTIONS: yoga as any,\n };\n}\n","import { YogaServerInstance, createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, GraphQLContext, getCommonConfig } from \"../shared\";\nimport telemetry from \"../../telemetry-client\";\n\nexport const config = {\n api: {\n bodyParser: false,\n },\n};\n\nexport type CopilotRuntimeServerInstance<T> = YogaServerInstance<T, Partial<GraphQLContext>>;\n\n// This import is needed to fix the type error\n// Fix is currently in TypeScript 5.5 beta, waiting for stable version\n// https://github.com/microsoft/TypeScript/issues/42873#issuecomment-2066874644\nexport type {} from \"@whatwg-node/server\";\n\nexport function copilotRuntimeNextJSPagesRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n): CopilotRuntimeServerInstance<GraphQLContext> {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-pages-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS Pages Router endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n telemetry.capture(\"oss.runtime.instance_created\", {});\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0BAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,UAAY;AAAA,MACZ,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,eAAiB;AAAA,QACf,QAAU;AAAA,MACZ;AAAA,MACA,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,SAAW;AAAA,QACT,KAAK;AAAA,MACP;AAAA,MACA,OAAS;AAAA,MACT,SAAW;AAAA,MACX,SAAW;AAAA,QACT,OAAS;AAAA,QACT,KAAO;AAAA,QACP,MAAQ;AAAA,QACR,eAAe;AAAA,QACf,OAAS;AAAA,QACT,2BAA2B;AAAA,MAC7B;AAAA,MACA,iBAAmB;AAAA,QACjB,aAAa;AAAA,QACb,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf,eAAe;AAAA,QACf,uBAAuB;AAAA,QACvB,QAAU;AAAA,QACV,wBAAwB;AAAA,QACxB,MAAQ;AAAA,QACR,SAAW;AAAA,QACX,WAAW;AAAA,QACX,WAAW;AAAA,QACX,UAAY;AAAA,QACZ,MAAQ;AAAA,QACR,YAAc;AAAA,MAChB;AAAA,MACA,cAAgB;AAAA,QACd,sBAAsB;AAAA,QACtB,yBAAyB;AAAA,QACzB,qCAAqC;AAAA,QACrC,wBAAwB;AAAA,QACxB,mBAAmB;AAAA,QACnB,qBAAqB;AAAA,QACrB,qBAAqB;AAAA,QACrB,SAAW;AAAA,QACX,SAAW;AAAA,QACX,mBAAmB;AAAA,QACnB,gBAAgB;AAAA,QAChB,YA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2BAA2BC,SAA0C;AACnFC,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEAH,2BAAUI,QAAQ,gCAAgC,CAAC,CAAA;AACnD,SAAOC,+BAA+BN,OAAAA;AACxC;AATgBD;","names":["module","import_shared","BaseMessage","id","createdAt","Field","String","Date","InputType","TextMessage","BaseMessage","content","role","ActionExecutionMessage","name","arguments","scope","ResultMessage","actionExecutionId","actionName","result","limitMessagesToTokenCount","messages","tools","model","maxTokens","maxTokensForOpenAIModel","result","toolsNumTokens","countToolsTokens","Error","message","role","numTokens","countMessageTokens","cutoff","reversedMessages","reverse","unshift","maxTokensByModel","DEFAULT_MAX_TOKENS","length","json","JSON","stringify","countTokens","content","text","convertActionInputToOpenAITool","action","type","function","name","description","parameters","parse","jsonSchema","convertMessageToOpenAIMessage","TextMessage","ActionExecutionMessage","tool_calls","id","arguments","ResultMessage","tool_call_id","actionExecutionId","convertSystemMessageToAssistantAPI","DEFAULT_MODEL","OpenAIAdapter","model","_openai","openai","constructor","params","OpenAI","process","request","threadId","messages","actions","eventSource","forwardedParameters","tools","map","convertActionInputToOpenAITool","openaiMessages","convertMessageToOpenAIMessage","limitMessagesToTokenCount","toolChoice","type","function","name","toolChoiceFunctionName","stream","beta","chat","completions","length","maxTokens","max_tokens","stop","tool_choice","eventStream$","mode","chunk","toolCall","choices","delta","tool_calls","content","id","sendTextMessageEnd","undefined","sendActionExecutionEnd","sendActionExecutionStart","sendTextMessageStart","sendTextMessageContent","arguments","sendActionExecutionArgs","complete","randomId","import_openai","OpenAIAssistantAdapter","openai","codeInterpreterEnabled","assistantId","fileSearchEnabled","constructor","params","OpenAI","process","request","messages","actions","eventSource","runId","forwardedParameters","threadId","beta","threads","create","id","lastMessage","at","nextRunId","undefined","ResultMessage","submitToolOutputs","TextMessage","submitUserMessage","Error","run","runs","retrieve","required_action","toolCallsIds","submit_tool_outputs","tool_calls","map","toolCall","resultMessages","filter","message","includes","actionExecutionId","length","toolOutputs","tool_call_id","output","result","stream","submitToolOutputsStream","tool_outputs","streamResponse","instructionsMessage","shift","instructions","content","userMessage","convertMessageToOpenAIMessage","convertSystemMessageToAssistantAPI","role","openaiTools","convertActionInputToOpenAITool","tools","type","assistant_id","maxTokens","max_completion_tokens","getRunIdFromStream","eventStream$","inFunctionCall","chunk","event","sendActionExecutionEnd","sendTextMessageStart","data","delta","sendTextMessageContent","text","value","sendTextMessageEnd","toolCallId","toolCallName","toolCallArgs","step_details","function","name","arguments","sendActionExecutionStart","sendActionExecutionArgs","complete","Promise","resolve","reject","runIdGetter","off","on","convertMessageToGoogleGenAIMessage","message","TextMessage","role","user","assistant","system","text","content","parts","ActionExecutionMessage","functionCall","name","args","arguments","ResultMessage","functionResponse","actionName","response","tryParseJson","result","transformActionToGoogleGenAITool","action","description","parameters","JSON","parse","jsonSchema","transformProperties","props","key","type","toUpperCase","properties","functionDeclarations","str","e","import_shared","GoogleGenerativeAIAdapter","model","constructor","options","genAI","GoogleGenerativeAI","process","env","getGenerativeModel","request","messages","actions","eventSource","history","slice","map","convertMessageToGoogleGenAIMessage","currentMessage","at","Error","systemMessage","firstMessage","TextMessage","role","content","trim","tools","transformActionToGoogleGenAITool","isFirstGenGeminiPro","chat","startChat","parts","text","systemInstruction","result","sendMessageStream","stream","eventStream$","isTextMessage","chunk","chunkText","sendTextMessageStart","randomId","sendTextMessageContent","sendTextMessageEnd","calls","response","functionCalls","call","sendActionExecution","name","JSON","stringify","replaceNewlinesInObject","args","complete","threadId","obj","replace","Array","isArray","newObj","key","hasOwnProperty","import_shared","convertMessageToLangChainMessage","message","TextMessage","role","HumanMessage","content","AIMessage","SystemMessage","ActionExecutionMessage","tool_calls","id","args","arguments","name","ResultMessage","ToolMessage","result","tool_call_id","actionExecutionId","convertJsonSchemaToZodSchema","jsonSchema","required","type","spec","key","value","Object","entries","properties","includes","schema","z","object","optional","string","describe","description","number","boolean","itemSchema","items","array","convertActionInputToLangChainTool","actionInput","DynamicStructuredTool","JSON","parse","func","getConstructorName","constructor","isAIMessage","isAIMessageChunk","isBaseMessageChunk","maybeSendActionExecutionResultIsMessage","eventStream$","actionExecution","sendActionExecutionResult","streamLangChainResponse","sendTextMessage","randomId","toolCall","sendActionExecution","stringify","lc_kwargs","reader","getReader","mode","done","read","toolCallName","undefined","toolCallId","toolCallArgs","hasToolCall","chunk","tool_call_chunks","additional_kwargs","function","sendTextMessageEnd","sendActionExecutionEnd","sendActionExecutionStart","sendTextMessageStart","sendTextMessageContent","sendActionExecutionArgs","error","console","encodeResult","Error","complete","import_shared","LangChainAdapter","constructor","options","process","request","eventSource","model","actions","messages","threadId","runId","result","chainFn","map","convertMessageToLangChainMessage","tools","convertActionInputToLangChainTool","stream","eventStream$","streamLangChainResponse","randomId","RemoteChain","name","description","chainUrl","parameters","parameterType","constructor","options","toAction","inferLangServeParameters","handler","args","runnable","RemoteRunnable","url","input","Object","keys","invoke","supportedTypes","schemaUrl","replace","schema","fetch","then","res","json","catch","Error","includes","type","properties","map","key","property","required","import_openai","import_shared","UnifyAdapter","apiKey","model","start","constructor","options","process","request","tools","actions","map","convertActionInputToOpenAITool","openai","OpenAI","baseURL","messages","convertMessageToOpenAIMessage","stream","chat","completions","create","length","eventSource","eventStream$","mode","chunk","sendTextMessageStart","randomId","sendTextMessageContent","sendTextMessageEnd","toolCall","choices","delta","tool_calls","content","id","undefined","sendActionExecutionEnd","sendActionExecutionStart","function","name","arguments","sendActionExecutionArgs","complete","threadId","import_shared","DEFAULT_MODEL","GroqAdapter","model","_groq","groq","constructor","params","Groq","process","request","threadId","messages","actions","eventSource","forwardedParameters","tools","map","convertActionInputToOpenAITool","openaiMessages","convertMessageToOpenAIMessage","limitMessagesToTokenCount","toolChoice","type","function","name","toolChoiceFunctionName","stream","chat","completions","create","length","maxTokens","max_tokens","stop","tool_choice","eventStream$","mode","chunk","toolCall","choices","delta","tool_calls","content","id","sendTextMessageEnd","undefined","sendActionExecutionEnd","sendActionExecutionStart","sendTextMessageStart","sendTextMessageContent","arguments","sendActionExecutionArgs","complete","randomId","RuntimeEventTypes","RuntimeEventSubject","ReplaySubject","constructor","sendTextMessageStart","messageId","next","type","sendTextMessageContent","content","sendTextMessageEnd","sendTextMessage","sendActionExecutionStart","actionExecutionId","actionName","sendActionExecutionArgs","args","sendActionExecutionEnd","sendActionExecution","toolName","sendActionExecutionResult","result","RuntimeEventSource","eventStream$","callback","stream","process","serversideActions","guardrailsResult$","catch","error","console","pipe","map","event","scope","find","action","name","scan","acc","callActionServerSide","concatMap","eventWithState","toolCallEventStream$","executeAction","concat","of","actionArguments","status","firstValueFrom","complete","JSON","parse","handler","streamLangChainResponse","actionExecution","id","convertGqlInputToMessages","inputMessages","messages","message","textMessage","push","plainToInstance","TextMessage","id","createdAt","role","content","actionExecutionMessage","ActionExecutionMessage","name","arguments","JSON","parse","scope","resultMessage","ResultMessage","actionExecutionId","actionName","result","CopilotRuntime","actions","langserve","onBeforeRequest","onAfterRequest","constructor","params","chain","remoteChain","RemoteChain","push","toAction","middleware","process","request","serviceAdapter","messages","clientSideActionsInput","threadId","runId","properties","outputMessagesPromise","forwardedParameters","langserveFunctions","chainPromise","error","console","configuredActions","serverSideActionsInput","map","action","name","description","jsonSchema","JSON","stringify","actionParametersToJsonSchema","parameters","actionInputs","flattenToolCallsNoDuplicates","inputMessages","convertGqlInputToMessages","eventSource","RuntimeEventSource","result","then","outputMessages","_a","catch","_error","toolsByPriority","allTools","allToolNames","tool","includes","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","import_type_graphql","MessageRole","ActionExecutionScope","CopilotRequestType","registerEnumType","name","description","MessageInput","BaseMessage","textMessage","actionExecutionMessage","resultMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","InputType","content","role","String","MessageRole","name","arguments","scope","ActionExecutionScope","actionExecutionId","actionName","result","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","Field","String","InputType","FrontendInput","toDeprecate_fullContext","actions","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","import_type_graphql","ForwardedParametersInput","model","maxTokens","stop","toolChoice","toolChoiceFunctionName","Field","String","nullable","Number","InputType","GenerateCopilotResponseMetadataInput","requestType","Field","CopilotRequestType","nullable","InputType","GenerateCopilotResponseInput","metadata","threadId","runId","messages","frontend","cloud","forwardedParameters","String","MessageInput","FrontendInput","CloudInput","ForwardedParametersInput","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","FailedResponseStatusReason","reason","details","GraphQLJSON","nullable","ResponseStatusUnion","createUnionType","types","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","undefined","role","content","MessageRole","ObjectType","implements","name","scope","arguments","ActionExecutionScope","actionExecutionId","actionName","result","CopilotResponse","threadId","runId","messages","ResponseStatusUnion","nullable","import_graphql_scalars","import_class_transformer","GuardrailsValidationFailureResponse","FailedResponseStatus","reason","FailedResponseStatusReason","GUARDRAILS_VALIDATION_FAILED","constructor","guardrailsReason","details","MessageStreamInterruptedResponse","MESSAGE_STREAM_INTERRUPTED","messageId","description","UnknownErrorResponse","UNKNOWN_ERROR","import_shared","packageJson","require","telemetryClient","TelemetryClient","packageName","name","packageVersion","version","import_shared","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","console","log","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","generateCopilotResponse","ctx","properties","telemetry","capture","requestType","metadata","logger","child","component","debug","copilotRuntime","_copilotkit","runtime","serviceAdapter","copilotCloudBaseUrl","key","request","get","error","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","eventSource","threadId","randomId","runId","actions","frontend","publicApiKey","forwardedParameters","response","status","firstValueFrom","Repeater","pushMessage","stopStreamingMessages","result","next","GuardrailsValidationFailureResponse","guardrailsReason","reason","plainToInstance","TextMessage","id","createdAt","Date","err","UnknownErrorResponse","description","eventStreamSubscription","eventStream","serversideActions","pipe","shareReplay","finalize","subscribe","event","type","RuntimeEventTypes","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","streamingTextStatus","Subject","messageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","unsubscribe","TextMessageContent","push","complete","SuccessMessageStatus","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","streamingArgumentsStatus","actionExecutionId","name","actionName","scope","arguments","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","ActionExecutionArgs","args","ActionExecutionMessage","ActionExecutionResult","ResultMessage","SuccessResponseStatus","Query","String","Mutation","CopilotResponse","Ctx","Arg","GraphQLJSONObject","nullable","Resolver","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","logger","createLogger","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","cloud","telemetry","setCloudConfiguration","publicApiKey","baseUrl","setGlobalProperties","runtime","serviceAdapter","constructor","name","logging","plugins","useDeferStream","context","import_graphql_yoga","copilotRuntimeNextJSAppRouterEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","fetchAPI","Response","globalThis","handleRequest","GET","POST","OPTIONS","import_graphql_yoga","config","api","bodyParser","copilotRuntimeNextJSPagesRouterEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","import_graphql_yoga","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","copilotRuntimeNodeExpressEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","copilotRuntimeNodeHttpEndpoint","copilotRuntimeNestEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","copilotRuntimeNodeHttpEndpoint"]}
|