{"version":3,"sources":["../src/utils/stream.ts"],"sourcesContent":["import {\n  Action,\n  parseChatCompletion,\n  ToolCallPayload,\n  ChatCompletionChunk,\n} from \"@copilotkit/shared\";\nimport {\n  writeChatCompletionChunk,\n  writeChatCompletionContent,\n  writeChatCompletionEnd,\n  writeChatCompletionResult,\n} from \"./openai\";\n\n/**\n * Execute a function call and write the result to the stream.\n * TODO: should this return a stream to get process other function calls?\n */\nasync function executeFunctionCall(\n  controller: ReadableStreamDefaultController<any>,\n  action: Action<any>,\n  functionCallArguments: string,\n): Promise<void> {\n  // Prepare arguments for function calling\n  let args: Record<string, any>[] = [];\n  if (functionCallArguments) {\n    args = JSON.parse(functionCallArguments);\n  }\n\n  // call the function\n  const result = await action.handler(args);\n\n  // We support several types of return values from functions:\n\n  // 1. string\n  // Just send the result as the content of the chunk.\n  if (result && typeof result === \"string\") {\n    writeChatCompletionResult(controller, action.name, result);\n  }\n\n  // 2. AIMessage\n  // Send the content and function call of the AIMessage as the content of the chunk.\n  else if (result && \"content\" in result && typeof result.content === \"string\") {\n    writeChatCompletionContent(controller, result.content, result.additional_kwargs?.tool_calls);\n  }\n\n  // 3. BaseMessageChunk\n  // Send the content and function call of the AIMessage as the content of the chunk.\n  else if (result && \"lc_kwargs\" in result) {\n    writeChatCompletionContent(controller, result.lc_kwargs?.content, result.lc_kwargs?.tool_calls);\n  }\n\n  // 4. IterableReadableStream\n  // Stream the result of the LangChain function.\n  else if (result && \"getReader\" in result) {\n    let reader = result.getReader();\n    while (true) {\n      try {\n        const { done, value } = await reader.read();\n\n        if (done) {\n          break;\n        }\n\n        writeChatCompletionContent(\n          controller,\n          value?.lc_kwargs?.content,\n          value.lc_kwargs?.additional_kwargs?.tool_calls,\n        );\n      } catch (error) {\n        console.error(\"Error reading from stream\", error);\n        break;\n      }\n    }\n  }\n\n  // 5. Any other type, return JSON result\n  else {\n    writeChatCompletionResult(controller, action.name, result);\n  }\n}\n\n/**\n * This function intercepts the stream from the chat completion and processes it according to the defined actions.\n * It decodes the stream, executes any server-side functions as specified in the actions, and forwards the rest to the client.\n *\n * @param stream - The incoming ReadableStream of Uint8Array from the chat completion.\n * @param actions - An array of Action objects that define server-side functions to be executed.\n * @param debug - A boolean flag to enable debug logging.\n * @returns A new ReadableStream that is the result of processing the incoming stream.\n */\nexport function copilotkitStreamInterceptor(\n  stream: ReadableStream<Uint8Array>,\n  actions: Action<any>[],\n  debug: boolean = false,\n): ReadableStream {\n  const functionsByName = actions.reduce(\n    (acc, fn) => {\n      acc[fn.name] = fn;\n      return acc;\n    },\n    {} as Record<string, Action<any>>,\n  );\n\n  const decodedStream = parseChatCompletion(stream);\n  const reader = decodedStream.getReader();\n\n  async function cleanup(controller?: ReadableStreamDefaultController<any>) {\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  // Keep track of current state as we process the stream\n\n  // Loop Invariant:\n  // Either we are in the middle of a function call that should be executed on the backend = TRUE\n  // or we are in the middle of processing a chunk that should be forwarded to the client = FALSE\n  let executeThisFunctionCall = false;\n\n  let functionCallName = \"\";\n  let functionCallArguments = \"\";\n\n  let currentFnIndex: number | null = null;\n\n  const flushFunctionCall = async (\n    controller: ReadableStreamDefaultController<any>,\n  ): Promise<void> => {\n    const action = functionsByName[functionCallName];\n    await executeFunctionCall(controller, action, functionCallArguments);\n\n    executeThisFunctionCall = false;\n    functionCallName = \"\";\n    functionCallArguments = \"\";\n  };\n\n  return new ReadableStream({\n    async pull(controller) {\n      while (true) {\n        try {\n          const { done, value } = await reader.read();\n\n          if (done) {\n            if (debug) {\n              console.log(\"data: [DONE]\\n\\n\");\n            }\n            if (executeThisFunctionCall) {\n              // We are at the end of the stream and still have a function call to execute\n              await flushFunctionCall(controller);\n            }\n            writeChatCompletionEnd(controller);\n            await cleanup(controller);\n            return;\n          } // done == true (terminal case)\n\n          // Azure\n          if (value.choices.length == 0 || !value.choices[0].delta) {\n            continue;\n          }\n\n          if (debug) {\n            console.log(\"data: \" + JSON.stringify(value) + \"\\n\\n\");\n          }\n\n          type Mode = { type: \"function\"; toolCall: ToolCallPayload } | { type: \"message\" };\n\n          let mode: Mode;\n          const maybeToolCall = value.choices[0].delta.tool_calls?.[0];\n          if (maybeToolCall) {\n            mode = { type: \"function\", toolCall: maybeToolCall };\n          } else {\n            mode = { type: \"message\" };\n          }\n\n          const nextChunkIndex = mode.type === \"function\" ? mode.toolCall.index : null;\n          // If We are in the middle of a function call and got a non function call chunk\n          // or a different function call\n          // => execute the function call first\n          if (\n            executeThisFunctionCall &&\n            (mode.type != \"function\" || nextChunkIndex != currentFnIndex)\n          ) {\n            await flushFunctionCall(controller);\n          }\n          currentFnIndex = nextChunkIndex;\n\n          // if we get a message, emit the content and continue;\n          if (mode.type === \"message\") {\n            if (value.choices[0].delta.content) {\n              writeChatCompletionChunk(controller, value);\n            }\n            continue;\n          }\n\n          // if we get a function call, emit it only if we don't execute it server side\n          else if (mode.type === \"function\") {\n            // Set the function name if present\n            const maybeFunctionName = mode.toolCall.function.name;\n            if (maybeFunctionName) {\n              functionCallName = maybeFunctionName;\n            }\n            // If we have argument streamed back, add them to the function call arguments\n            const maybeArguments = mode.toolCall.function.arguments;\n            if (mode.toolCall.function.arguments) {\n              functionCallArguments += maybeArguments;\n            }\n            if (!executeThisFunctionCall) {\n              // Decide if we should execute the function call server side\n              if (functionCallName in functionsByName) {\n                executeThisFunctionCall = true;\n              }\n            }\n            mode.toolCall.function.scope = executeThisFunctionCall ? \"server\" : \"client\";\n            writeChatCompletionChunk(controller, value);\n            continue;\n          }\n        } catch (error) {\n          controller.error(error);\n          return;\n        }\n      }\n    },\n    cancel() {\n      reader.cancel();\n    },\n  });\n}\n\n/**\n * A ReadableStream that only emits a single chunk.\n */\nexport class SingleChunkReadableStream extends ReadableStream<any> {\n  constructor(content: string = \"\", toolCalls?: any) {\n    super({\n      start(controller) {\n        const chunk: ChatCompletionChunk = {\n          choices: [\n            {\n              delta: {\n                role: \"assistant\",\n                content,\n                ...(toolCalls ? { tool_calls: toolCalls } : {}),\n              },\n            },\n          ],\n        };\n        writeChatCompletionChunk(controller, chunk);\n        writeChatCompletionEnd(controller);\n\n        controller.close();\n      },\n      cancel() {},\n    });\n  }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EAEE;AAAA,OAGK;AAYP,eAAe,oBACb,YACA,QACA,uBACe;AArBjB;AAuBE,MAAI,OAA8B,CAAC;AACnC,MAAI,uBAAuB;AACzB,WAAO,KAAK,MAAM,qBAAqB;AAAA,EACzC;AAGA,QAAM,SAAS,MAAM,OAAO,QAAQ,IAAI;AAMxC,MAAI,UAAU,OAAO,WAAW,UAAU;AACxC,8BAA0B,YAAY,OAAO,MAAM,MAAM;AAAA,EAC3D,WAIS,UAAU,aAAa,UAAU,OAAO,OAAO,YAAY,UAAU;AAC5E,+BAA2B,YAAY,OAAO,UAAS,YAAO,sBAAP,mBAA0B,UAAU;AAAA,EAC7F,WAIS,UAAU,eAAe,QAAQ;AACxC,+BAA2B,aAAY,YAAO,cAAP,mBAAkB,UAAS,YAAO,cAAP,mBAAkB,UAAU;AAAA,EAChG,WAIS,UAAU,eAAe,QAAQ;AACxC,QAAI,SAAS,OAAO,UAAU;AAC9B,WAAO,MAAM;AACX,UAAI;AACF,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,YAAI,MAAM;AACR;AAAA,QACF;AAEA;AAAA,UACE;AAAA,WACA,oCAAO,cAAP,mBAAkB;AAAA,WAClB,iBAAM,cAAN,mBAAiB,sBAAjB,mBAAoC;AAAA,QACtC;AAAA,MACF,SAAS,OAAP;AACA,gBAAQ,MAAM,6BAA6B,KAAK;AAChD;AAAA,MACF;AAAA,IACF;AAAA,EACF,OAGK;AACH,8BAA0B,YAAY,OAAO,MAAM,MAAM;AAAA,EAC3D;AACF;AAWO,SAAS,4BACd,QACA,SACA,QAAiB,OACD;AAChB,QAAM,kBAAkB,QAAQ;A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