{"version":3,"sources":["../src/lib/copilotkit-runtime.ts"],"sourcesContent":["/**\n * Handles requests from frontend, provides function calling and various LLM backends.\n *\n * <img\n *   referrerPolicy=\"no-referrer-when-downgrade\"\n *   src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n *\n * <RequestExample>\n *   ```jsx CopilotRuntime Example\n *   import {\n *     CopilotRuntime,\n *     OpenAIAdapter\n *   } from \"@copilotkit/backend\";\n *\n *   export async function POST(req: Request) {\n *     const copilotKit = new CopilotRuntime();\n *     return copilotKit.response(req, new OpenAIAdapter());\n *   }\n *\n * ```\n * </RequestExample>\n *\n * This class is the main entry point for the runtime. It handles requests from the frontend, provides function calling and various LLM backends.\n *\n * For example, to use OpenAI as a backend (check the [OpenAI Adapter](./OpenAIAdapter) docs for more info):\n * ```typescript\n * const copilotKit = new CopilotRuntime();\n * return copilotKit.response(req, new OpenAIAdapter());\n * ```\n *\n * Currently we support:\n *\n * - [OpenAI](./OpenAIAdapter)\n * - [LangChain](./LangChainAdapter)\n * - [OpenAI Assistant API](./OpenAIAssistantAdapter)\n * - [Google Gemini](./GoogleGenerativeAIAdapter)\n *\n * ## Server Side Actions\n *\n * CopilotKit supports actions that can be executed on the server side. You can define server side actions by passing the `actions` parameter:\n *\n * ```typescript\n * const copilotKit = new CopilotRuntime({\n *   actions: [\n *     {\n *       name: \"sayHello\",\n *       description: \"Says hello to someone.\",\n *       argumentAnnotations: [\n *         {\n *           name: \"arg\",\n *           type: \"string\",\n *           description: \"The name of the person to say hello to.\",\n *           required: true,\n *         },\n *       ],\n *       implementation: async (arg) => {\n *         console.log(\"Hello from the server\", arg, \"!\");\n *       },\n *     },\n *   ],\n * });\n * ```\n *\n * Server side actions can also return a result which becomes part of the message history.\n *\n * This is useful because it gives the LLM context about what happened on the server side. In addition,\n * it can be used to look up information from a vector or relational database and other sources.\n *\n * In addition to that, server side actions can also come from LangChain, including support for streaming responses.\n *\n * Returned results can be of the following type:\n *\n * - anything serializable to JSON\n * - `string`\n * - LangChain types:\n *   - `IterableReadableStream`\n *   - `BaseMessageChunk`\n *   - `AIMessage`\n *\n * ## LangServe\n *\n * The backend also supports LangServe, enabling you to connect to existing chains, for example python based chains.\n * Use the `langserve` parameter to specify URLs for LangServe.\n *\n * ```typescript\n * const copilotKit = new CopilotRuntime({\n *   langserve: [\n *     {\n *       chainUrl: \"http://my-langserve.chain\",\n *       name: \"performResearch\",\n *       description: \"Performs research on a given topic.\",\n *     },\n *   ],\n * });\n * ```\n *\n * When left out, arguments are automatically inferred from the schema provided by LangServe.\n */\n\nimport {\n  Action,\n  ToolDefinition,\n  EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n  actionToChatCompletionFunction,\n  Parameter,\n  AnnotatedFunction,\n  annotatedFunctionToAction,\n  COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n  CopilotCloudConfig,\n} from \"@copilotkit/shared\";\nimport {\n  SingleChunkReadableStream,\n  copilotkitStreamInterceptor,\n  remoteChainToAction,\n} from \"../utils\";\nimport { RemoteChain, CopilotKitServiceAdapter } from \"../types\";\nimport { CopilotCloud, RemoteCopilotCloud } from \"./copilot-cloud\";\n\ninterface CopilotRuntimeResult {\n  stream: ReadableStream;\n  headers?: Record<string, string>;\n}\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {\n  /*\n   * A list of server side actions that can be executed.\n   */\n  actions?: Action<T>[];\n\n  /*\n   * An array of LangServer URLs.\n   */\n  langserve?: RemoteChain[];\n\n  debug?: boolean;\n  copilotCloud?: CopilotCloud;\n}\n\ninterface CopilotDeprecatedRuntimeConstructorParams<T extends Parameter[] | [] = []> {\n  actions?: AnnotatedFunction<any>[];\n  langserve?: RemoteChain[];\n  debug?: boolean;\n  copilotCloud?: CopilotCloud;\n}\n\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n  private actions: Action<any>[] = [];\n  private langserve: Promise<Action<any>>[] = [];\n  private debug: boolean = false;\n  private copilotCloud: CopilotCloud;\n\n  constructor(params?: CopilotRuntimeConstructorParams<T>);\n  // @deprecated use Action<T> instead of AnnotatedFunction<T>\n  constructor(params?: CopilotDeprecatedRuntimeConstructorParams<T>);\n  constructor(\n    params?: CopilotRuntimeConstructorParams<T> | CopilotDeprecatedRuntimeConstructorParams<T>,\n  ) {\n    for (const action of params?.actions || []) {\n      if (\"argumentAnnotations\" in action) {\n        this.actions.push(annotatedFunctionToAction(action));\n      } else {\n        this.actions.push(action);\n      }\n    }\n    for (const chain of params?.langserve || []) {\n      this.langserve.push(remoteChainToAction(chain));\n    }\n    this.debug = params?.debug || false;\n    this.copilotCloud = params?.copilotCloud || new RemoteCopilotCloud();\n  }\n\n  addAction<const T extends Parameter[] | [] = []>(action: Action<T>): void;\n  /** @deprecated Use addAction with Action<T> instead. */\n  addAction(action: AnnotatedFunction<any>): void;\n  addAction<const T extends Parameter[] | [] = []>(\n    action: Action<T> | AnnotatedFunction<any>,\n  ): void {\n    this.removeAction(action.name);\n    if (\"argumentAnnotations\" in action) {\n      this.actions.push(annotatedFunctionToAction(action));\n    } else {\n      this.actions.push(action);\n    }\n  }\n\n  removeAction(actionName: string): void {\n    this.actions = this.actions.filter((f) => f.name !== actionName);\n  }\n\n  removeBackendOnlyProps(forwardedProps: any): void {\n    // Get keys backendOnlyPropsKeys in order to remove them from the forwardedProps\n    const backendOnlyPropsKeys = forwardedProps[EXCLUDE_FROM_FORWARD_PROPS_KEYS];\n    if (Array.isArray(backendOnlyPropsKeys)) {\n      backendOnlyPropsKeys.forEach((key) => {\n        const success = Reflect.deleteProperty(forwardedProps, key);\n        if (!success) {\n          console.error(`Failed to delete property ${key}`);\n        }\n      });\n      // After deleting individual backend-only properties, delete the EXCLUDE_FROM_FORWARD_PROPS_KEYS property itself from forwardedProps\n      const success = Reflect.deleteProperty(forwardedProps, EXCLUDE_FROM_FORWARD_PROPS_KEYS);\n      if (!success) {\n        console.error(`Failed to delete EXCLUDE_FROM_FORWARD_PROPS_KEYS`);\n      }\n    } else if (backendOnlyPropsKeys) {\n      console.error(\"backendOnlyPropsKeys is not an array\");\n    }\n  }\n\n  private async getResponse(\n    forwardedProps: any,\n    serviceAdapter: CopilotKitServiceAdapter,\n    publicApiKey?: string,\n  ): Promise<CopilotRuntimeResult> {\n    this.removeBackendOnlyProps(forwardedProps);\n\n    // In case Copilot Cloud is configured remove it from the forwardedProps\n    const cloud: CopilotCloudConfig = forwardedProps.cloud;\n    delete forwardedProps.cloud;\n\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 serversideTools: Action<any>[] = [...this.actions, ...langserveFunctions];\n    const mergedTools = flattenToolCallsNoDuplicates([\n      ...serversideTools.map(actionToChatCompletionFunction),\n      ...(forwardedProps.tools || []),\n    ]);\n\n    try {\n      const result = await serviceAdapter.getResponse({\n        ...forwardedProps,\n        tools: mergedTools,\n      });\n\n      if (publicApiKey !== undefined) {\n        // wait for the cloud log chat to finish before streaming back the response\n        try {\n          const checkGuardrailsInputResult = await this.copilotCloud.checkGuardrailsInput({\n            cloud,\n            publicApiKey,\n            messages: forwardedProps.messages || [],\n          });\n\n          if (checkGuardrailsInputResult.status === \"denied\") {\n            // the chat was denied. instead of streaming back the response,\n            // we let the client know...\n            return {\n              stream: new SingleChunkReadableStream(checkGuardrailsInputResult.reason),\n              headers: result.headers,\n            };\n          }\n        } catch (error) {\n          console.error(\"Error checking guardrails:\", error);\n        }\n      }\n      const stream = copilotkitStreamInterceptor(result.stream, serversideTools, this.debug);\n      return { stream, headers: result.headers };\n    } catch (error) {\n      console.error(\"Error getting response:\", error);\n      throw error;\n    }\n  }\n\n  /**\n   * Returns a `Response` object for streaming back the result to the client\n   *\n   * @param req The HTTP request\n   * @param serviceAdapter The adapter to use for the response.\n   */\n  async response(req: Request, serviceAdapter: CopilotKitServiceAdapter): Promise<Response> {\n    const publicApiKey = req.headers.get(COPILOT_CLOUD_PUBLIC_API_KEY_HEADER) || undefined;\n    try {\n      const forwardedProps = await req.json();\n      const response = await this.getResponse(forwardedProps, serviceAdapter, publicApiKey);\n      return new Response(response.stream, { headers: response.headers });\n    } catch (error: any) {\n      return new Response(error, { status: error.status });\n    }\n  }\n\n  /**\n   * Streams messages back to the client using the HTTP response object. Use with express,\nor Node.js HTTP server.\n    *\n    * @param req The HTTP request\n    * @param res The HTTP response\n    * @param serviceAdapter The adapter to use for the response.\n    * @param headers Additional headers to send with the response.\n    */\n  async streamHttpServerResponse(\n    req: any,\n    res: any,\n    serviceAdapter: CopilotKitServiceAdapter,\n    headers?: Record<string, string>,\n  ) {\n    const bodyParser = new Promise<any>((resolve, reject) => {\n      if (\"body\" in req) {\n        resolve(req.body);\n        return;\n      }\n      let body = \"\";\n      req.on(\"data\", (chunk: any) => (body += chunk.toString()));\n      req.on(\"end\", () => {\n        try {\n          resolve(JSON.parse(body));\n        } catch (error) {\n          reject(error);\n        }\n      });\n    });\n    const forwardedProps = await bodyParser;\n    const publicApiKey =\n      (req.header\n        ? // use header() in express\n          req.header(COPILOT_CLOUD_PUBLIC_API_KEY_HEADER)\n        : // use headers in node http\n          req.headers[COPILOT_CLOUD_PUBLIC_API_KEY_HEADER.toLowerCase()]) || undefined;\n    const response = await this.getResponse(forwardedProps, serviceAdapter, publicApiKey);\n    const mergedHeaders = { ...headers, ...response.headers };\n    res.writeHead(200, mergedHeaders);\n    const stream = response.stream;\n    const reader = stream.getReader();\n\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) {\n        res.end();\n        break;\n      } else {\n        res.write(new TextDecoder().decode(value));\n      }\n    }\n  }\n}\n\nexport function flattenToolCallsNoDuplicates(toolsByPriority: ToolDefinition[]): ToolDefinition[] {\n  let allTools: ToolDefinition[] = [];\n  const allToolNames: string[] = [];\n  for (const tool of toolsByPriority) {\n    if (!allToolNames.includes(tool.function.name)) {\n      allTools.push(tool);\n      allToolNames.push(tool.function.name);\n    }\n  }\n  return allTools;\n}\n\n/**\n * @deprecated use CopilotRuntime instead\n */\nexport class CopilotBackend extends CopilotRuntime {}\n"],"mappings":";;;;;;;;;;;;AAoGA;AAAA,EAGE;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,OAEK;AAoCA,IAAM,iBAAN,MAA4D;AAAA,EASjE,YACE,QACA;AAVF,SAAQ,UAAyB,CAAC;AAClC,SAAQ,YAAoC,CAAC;AAC7C,SAAQ,QAAiB;AASvB,eAAW,WAAU,iCAAQ,YAAW,CAAC,GAAG;AAC1C,UAAI,yBAAyB,QAAQ;AACnC,aAAK,QAAQ,KAAK,0BAA0B,MAAM,CAAC;AAAA,MACrD,OAAO;AACL,aAAK,QAAQ,KAAK,MAAM;AAAA,MAC1B;AAAA,IACF;AACA,eAAW,UAAS,iCAAQ,cAAa,CAAC,GAAG;AAC3C,WAAK,UAAU,KAAK,oBAAoB,KAAK,CAAC;AAAA,IAChD;AACA,SAAK,SAAQ,iCAAQ,UAAS;AAC9B,SAAK,gBAAe,iCAAQ,iBAAgB,IAAI,mBAAmB;AAAA,EACrE;AAAA,EAKA,UACE,QACM;AACN,SAAK,aAAa,OAAO,IAAI;AAC7B,QAAI,yBAAyB,QAAQ;AACnC,WAAK,QAAQ,KAAK,0BAA0B,MAAM,CAAC;AAAA,IACrD,OAAO;AACL,WAAK,QAAQ,KAAK,MAAM;AAAA,IAC1B;AAAA,EACF;AAAA,EAEA,aAAa,YAA0B;AACrC,SAAK,UAAU,KAAK,QAAQ,OAAO,CAAC,MAAM,EAAE,SAAS,UAAU;AAAA,EACjE;AAAA,EAEA,uBAAuB,gBAA2B;AAEhD,UAAM,uBAAuB,eAAe,+BAA+B;AAC3E,QAAI,MAAM,QAAQ,oBAAoB,GAAG;AACvC,2BAAqB,QAAQ,CAAC,QAAQ;AACpC,cAAMA,WAAU,QAAQ,eAAe,gBAAgB,GAAG;AAC1D,YAAI,CAACA,UAAS;A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