{"version":3,"sources":["../src/lib/langchain-adapter.ts"],"sourcesContent":["/**\n * CopilotKit Adapter for LangChain\n *\n * Use this adapter to use LangChain as a backend.\n *\n * ```typescript\n * return copilotKit.response(\n *   req,\n *   new LangChainAdapter(async (forwardedProps) => {\n *     const model = new ChatOpenAI({ modelName: \"gpt-4o\" });\n *     return model.stream(forwardedProps.messages, {\n *       tools: forwardedProps.tools,\n *     });\n *   })\n * );\n * ```\n * The async handler function can return:\n *\n * - a simple `string` response\n * - a LangChain stream `IterableReadableStream`\n * - a LangChain `BaseMessageChunk` object\n * - a LangChain `AIMessage` object\n */\n\nimport { ChatCompletionChunk } from \"@copilotkit/shared\";\nimport {\n  AIMessage,\n  BaseMessage,\n  BaseMessageChunk,\n  FunctionMessage,\n  HumanMessage,\n  SystemMessage,\n  ToolMessage,\n} from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport { CopilotKitServiceAdapter } from \"../types\";\nimport { writeChatCompletionChunk, writeChatCompletionEnd } from \"../utils\";\nimport { CopilotKitResponse } from \"../types/service-adapter\";\nimport { SingleChunkReadableStream } from \"../utils\";\n\nexport type LangChainMessageStream = IterableReadableStream<BaseMessageChunk>;\nexport type LangChainReturnType = LangChainMessageStream | BaseMessageChunk | string | AIMessage;\n\nexport class LangChainAdapter implements CopilotKitServiceAdapter {\n  /**\n   * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.\n   */\n  constructor(private chainFn: (forwardedProps: any) => Promise<LangChainReturnType>) {}\n\n  async getResponse(forwardedProps: any): Promise<CopilotKitResponse> {\n    forwardedProps = this.transformProps(forwardedProps);\n\n    const result = await this.chainFn(forwardedProps);\n\n    // We support several types of return values from LangChain functions:\n\n    // 1. string\n    // Just send one chunk with the string as the content.\n    if (typeof result === \"string\") {\n      return {\n        stream: new SingleChunkReadableStream(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 (\"content\" in result && typeof result.content === \"string\") {\n      return {\n        stream: new SingleChunkReadableStream(result.content, result.additional_kwargs?.tool_calls),\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 (\"lc_kwargs\" in result) {\n      return {\n        stream: new SingleChunkReadableStream(\n          result.lc_kwargs?.content,\n          result.lc_kwargs?.tool_calls,\n        ),\n      };\n    }\n\n    // 4. IterableReadableStream\n    // Stream the result of the LangChain function.\n    else if (\"getReader\" in result) {\n      return {\n        stream: this.streamResult(result),\n      };\n    }\n\n    // TODO write function call result!\n\n    console.error(\"Invalid return type from LangChain function.\");\n    throw new Error(\"Invalid return type from LangChain function.\");\n  }\n\n  /**\n   * Transforms the props that are forwarded to the LangChain function.\n   * Currently this just transforms the messages to the format that LangChain expects.\n   *\n   * @param forwardedProps\n   * @returns {any}\n   */\n  private transformProps(forwardedProps: any) {\n    const forwardedPropsCopy = Object.assign({}, forwardedProps);\n\n    // map messages to langchain format\n    if (forwardedProps.messages && Array.isArray(forwardedProps.messages)) {\n      const newMessages: BaseMessage[] = [];\n\n      for (const message of forwardedProps.messages) {\n        if (message.role === \"user\") {\n          newMessages.push(new HumanMessage(message.content));\n        } else if (message.role === \"assistant\") {\n          if (message.function_call) {\n            newMessages.push(\n              new AIMessage({\n                content: \"\",\n                tool_calls: [\n                  {\n                    id: message.function_call.name + \"-\" + forwardedProps.messages.indexOf(message),\n                    args: JSON.parse(message.function_call.arguments),\n                    name: message.function_call.name,\n                  },\n                ],\n              }),\n            );\n          } else {\n            newMessages.push(new AIMessage(message.content));\n          }\n        } else if (message.role === \"system\") {\n          newMessages.push(new SystemMessage(message.content));\n        } else if (message.role == \"function\") {\n          // An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'\n          newMessages.push(\n            new ToolMessage({\n              content: message.content,\n              tool_call_id: message.name + \"-\" + (forwardedProps.messages.indexOf(message) - 1),\n            }),\n          );\n        }\n      }\n      forwardedPropsCopy.messages = newMessages;\n    }\n\n    return forwardedPropsCopy;\n  }\n\n  /**\n   * Reads from the LangChainMessageStream and converts the output to a ReadableStream.\n   *\n   * @param streamedChain\n   * @returns ReadableStream\n   */\n  streamResult(streamedChain: LangChainMessageStream): ReadableStream<any> {\n    let reader = streamedChain.getReader();\n\n    async function cleanup(controller?: ReadableStreamDefaultController<BaseMessageChunk>) {\n      if (controller) {\n        try {\n          controller.close();\n        } catch (_) {}\n      }\n      if (reader) {\n        try {\n          await reader.cancel();\n        } catch (_) {}\n      }\n    }\n\n    return new ReadableStream<any>({\n      async pull(controller) {\n        while (true) {\n          try {\n            const { done, value } = await reader.read();\n\n            if (done) {\n              writeChatCompletionEnd(controller);\n              await cleanup(controller);\n              return;\n            }\n\n            const toolCalls = value.lc_kwargs?.additional_kwargs?.tool_calls;\n            const content = value?.lc_kwargs?.content;\n            const chunk: ChatCompletionChunk = {\n              choices: [\n                {\n                  delta: {\n                    role: \"assistant\",\n                    content: content,\n                    ...(toolCalls ? { tool_calls: toolCalls } : {}),\n                  },\n                },\n              ],\n            };\n            writeChatCompletionChunk(controller, chunk);\n          } catch (error) {\n            controller.error(error);\n            await cleanup(controller);\n            return;\n          }\n        }\n      },\n      cancel() {\n        cleanup();\n      },\n    });\n  }\n}\n"],"mappings":";;;;;;;;;AAyBA;AAAA,EACE;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUA,IAAM,mBAAN,MAA2D;AAAA;AAAA;AAAA;AAAA,EAIhE,YAAoB,SAAgE;AAAhE;AAAA,EAAiE;AAAA,EAErF,MAAM,YAAY,gBAAkD;AAjDtE;AAkDI,qBAAiB,KAAK,eAAe,cAAc;AAEnD,UAAM,SAAS,MAAM,KAAK,QAAQ,cAAc;AAMhD,QAAI,OAAO,WAAW,UAAU;AAC9B,aAAO;AAAA,QACL,QAAQ,IAAI,0BAA0B,MAAM;AAAA,MAC9C;AAAA,IACF,WAIS,aAAa,UAAU,OAAO,OAAO,YAAY,UAAU;AAClE,aAAO;AAAA,QACL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