@librechat/agents 3.0.49 → 3.0.50
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/dist/cjs/llm/openrouter/index.cjs +10 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/stream.cjs +22 -16
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +10 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/stream.mjs +22 -16
- package/dist/esm/stream.mjs.map +1 -1
- package/package.json +6 -2
- package/src/llm/openrouter/index.ts +11 -1
- package/src/stream.ts +21 -20
- package/src/utils/llmConfig.ts +3 -1
|
@@ -67,6 +67,8 @@ class ChatOpenRouter extends index.ChatOpenAI {
|
|
|
67
67
|
// Accumulate reasoning_details from each delta
|
|
68
68
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
69
69
|
const deltaAny = delta;
|
|
70
|
+
// Extract current chunk's reasoning text for streaming (before accumulation)
|
|
71
|
+
let currentChunkReasoningText = '';
|
|
70
72
|
if (deltaAny.reasoning_details != null &&
|
|
71
73
|
Array.isArray(deltaAny.reasoning_details)) {
|
|
72
74
|
for (const detail of deltaAny.reasoning_details) {
|
|
@@ -81,7 +83,9 @@ class ChatOpenRouter extends index.ChatOpenAI {
|
|
|
81
83
|
});
|
|
82
84
|
}
|
|
83
85
|
else if (detail.type === 'reasoning.text') {
|
|
84
|
-
//
|
|
86
|
+
// Extract current chunk's text for streaming
|
|
87
|
+
currentChunkReasoningText += detail.text || '';
|
|
88
|
+
// For text reasoning, accumulate text by index for final message
|
|
85
89
|
const idx = detail.index ?? 0;
|
|
86
90
|
const existing = reasoningTextByIndex.get(idx);
|
|
87
91
|
if (existing) {
|
|
@@ -100,6 +104,11 @@ class ChatOpenRouter extends index.ChatOpenAI {
|
|
|
100
104
|
}
|
|
101
105
|
}
|
|
102
106
|
const chunk = this._convertOpenAIDeltaToBaseMessageChunk(delta, data, defaultRole);
|
|
107
|
+
// For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),
|
|
108
|
+
// set the current chunk's reasoning text to additional_kwargs.reasoning for streaming
|
|
109
|
+
if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {
|
|
110
|
+
chunk.additional_kwargs.reasoning = currentChunkReasoningText;
|
|
111
|
+
}
|
|
103
112
|
// IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent
|
|
104
113
|
// LangChain's chunk concatenation from corrupting the array
|
|
105
114
|
// Check if this is the final chunk (has finish_reason)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../../../src/llm/openrouter/index.ts"],"sourcesContent":["import { ChatOpenAI } from '@/llm/openai';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport { AIMessageChunk as AIMessageChunkClass } from '@langchain/core/messages';\nimport type {\n FunctionMessageChunk,\n SystemMessageChunk,\n HumanMessageChunk,\n ToolMessageChunk,\n ChatMessageChunk,\n AIMessageChunk,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type {\n ChatOpenAICallOptions,\n OpenAIChatInput,\n OpenAIClient,\n} from '@langchain/openai';\nimport { _convertMessagesToOpenAIParams } from '@/llm/openai/utils';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\nexport interface ChatOpenRouterCallOptions extends ChatOpenAICallOptions {\n include_reasoning?: boolean;\n modelKwargs?: OpenAIChatInput['modelKwargs'];\n}\nexport class ChatOpenRouter extends ChatOpenAI {\n constructor(_fields: Partial<ChatOpenRouterCallOptions>) {\n const { include_reasoning, modelKwargs = {}, ...fields } = _fields;\n super({\n ...fields,\n modelKwargs: {\n ...modelKwargs,\n include_reasoning,\n },\n });\n }\n static lc_name(): 'LibreChatOpenRouter' {\n return 'LibreChatOpenRouter';\n }\n protected override _convertOpenAIDeltaToBaseMessageChunk(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>,\n rawResponse: OpenAIClient.ChatCompletionChunk,\n defaultRole?:\n | 'function'\n | 'user'\n | 'system'\n | 'developer'\n | 'assistant'\n | 'tool'\n ):\n | AIMessageChunk\n | HumanMessageChunk\n | SystemMessageChunk\n | FunctionMessageChunk\n | ToolMessageChunk\n | ChatMessageChunk {\n const messageChunk = super._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n rawResponse,\n defaultRole\n );\n if (delta.reasoning != null) {\n messageChunk.additional_kwargs.reasoning = delta.reasoning;\n }\n if (delta.reasoning_details != null) {\n messageChunk.additional_kwargs.reasoning_details =\n delta.reasoning_details;\n }\n return messageChunk;\n }\n\n async *_streamResponseChunks2(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const messagesMapped: OpenAICompletionParam[] =\n _convertMessagesToOpenAIParams(messages, this.model, {\n includeReasoningDetails: true,\n convertReasoningDetailsToContent: true,\n });\n\n const params = {\n ...this.invocationParams(options, {\n streaming: true,\n }),\n messages: messagesMapped,\n stream: true as const,\n };\n let defaultRole: OpenAIRoleEnum | undefined;\n\n const streamIterable = await this.completionWithRetry(params, options);\n let usage: OpenAIClient.Completions.CompletionUsage | undefined;\n\n // Store reasoning_details keyed by unique identifier to prevent incorrect merging\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningTextByIndex: Map<number, Record<string, any>> = new Map();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningEncryptedById: Map<string, Record<string, any>> = new Map();\n\n for await (const data of streamIterable) {\n const choice = data.choices[0] as\n | Partial<OpenAIClient.Chat.Completions.ChatCompletionChunk.Choice>\n | undefined;\n if (data.usage) {\n usage = data.usage;\n }\n if (!choice) {\n continue;\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n // Accumulate reasoning_details from each delta\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const deltaAny = delta as Record<string, any>;\n if (\n deltaAny.reasoning_details != null &&\n Array.isArray(deltaAny.reasoning_details)\n ) {\n for (const detail of deltaAny.reasoning_details) {\n // For encrypted reasoning (thought signatures), store by ID - MUST be separate\n if (detail.type === 'reasoning.encrypted' && detail.id) {\n reasoningEncryptedById.set(detail.id, {\n type: detail.type,\n id: detail.id,\n data: detail.data,\n format: detail.format,\n index: detail.index,\n });\n } else if (detail.type === 'reasoning.text') {\n // For text reasoning, accumulate text by index\n const idx = detail.index ?? 0;\n const existing = reasoningTextByIndex.get(idx);\n if (existing) {\n // Only append text, keep other fields from first entry\n existing.text = (existing.text || '') + (detail.text || '');\n } else {\n reasoningTextByIndex.set(idx, {\n type: detail.type,\n text: detail.text || '',\n format: detail.format,\n index: idx,\n });\n }\n }\n }\n }\n\n const chunk = this._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n data,\n defaultRole\n );\n\n // IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent\n // LangChain's chunk concatenation from corrupting the array\n // Check if this is the final chunk (has finish_reason)\n if (choice.finish_reason != null) {\n // Build properly structured reasoning_details array\n // Text entries first (but we only need the encrypted ones for thought signatures)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalReasoningDetails: Record<string, any>[] = [\n ...reasoningTextByIndex.values(),\n ...reasoningEncryptedById.values(),\n ];\n\n if (finalReasoningDetails.length > 0) {\n chunk.additional_kwargs.reasoning_details = finalReasoningDetails;\n }\n } else {\n // Clear reasoning_details from intermediate chunks to prevent concatenation issues\n delete chunk.additional_kwargs.reasoning_details;\n }\n\n defaultRole = delta.role ?? defaultRole;\n const newTokenIndices = {\n prompt: options.promptIndex ?? 0,\n completion: choice.index ?? 0,\n };\n if (typeof chunk.content !== 'string') {\n // eslint-disable-next-line no-console\n console.log(\n '[WARNING]: Received non-string content from OpenAI. This is currently not supported.'\n );\n continue;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const generationInfo: Record<string, any> = { ...newTokenIndices };\n if (choice.finish_reason != null) {\n generationInfo.finish_reason = choice.finish_reason;\n generationInfo.system_fingerprint = data.system_fingerprint;\n generationInfo.model_name = data.model;\n generationInfo.service_tier = data.service_tier;\n }\n if (this.logprobs == true) {\n generationInfo.logprobs = choice.logprobs;\n }\n const generationChunk = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n generationInfo,\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n await runManager?.handleLLMNewToken(\n generationChunk.text || '',\n newTokenIndices,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n if (usage) {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunkClass({\n content: '',\n response_metadata: {\n usage: { ...usage },\n },\n usage_metadata: {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n total_tokens: usage.total_tokens,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n },\n }),\n text: '',\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n }\n if (options.signal?.aborted === true) {\n throw new Error('AbortError');\n }\n }\n}\n"],"names":["ChatOpenAI","messages","_convertMessagesToOpenAIParams","ChatGenerationChunk","AIMessageChunkClass"],"mappings":";;;;;;;AAmCM,MAAO,cAAe,SAAQA,gBAAU,CAAA;AAC5C,IAAA,WAAA,CAAY,OAA2C,EAAA;AACrD,QAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO;AAClE,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,WAAW,EAAE;AACX,gBAAA,GAAG,WAAW;gBACd,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;;AAEJ,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,qBAAqB;;IAEX,qCAAqC;;IAEtD,KAA0B,EAC1B,WAA6C,EAC7C,WAMU,EAAA;AAQV,QAAA,MAAM,YAAY,GAAG,KAAK,CAAC,qCAAqC,CAC9D,KAAK,EACL,WAAW,EACX,WAAW,CACZ;AACD,QAAA,IAAI,KAAK,CAAC,SAAS,IAAI,IAAI,EAAE;YAC3B,YAAY,CAAC,iBAAiB,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS;;AAE5D,QAAA,IAAI,KAAK,CAAC,iBAAiB,IAAI,IAAI,EAAE;YACnC,YAAY,CAAC,iBAAiB,CAAC,iBAAiB;gBAC9C,KAAK,CAAC,iBAAiB;;AAE3B,QAAA,OAAO,YAAY;;IAGrB,OAAO,sBAAsB,CAC3BC,UAAuB,EACvB,OAAkC,EAClC,UAAqC,EAAA;QAErC,MAAM,cAAc,GAClBC,sCAA8B,CAACD,UAAQ,EAAE,IAAI,CAAC,KAAK,EAAE;AACnD,YAAA,uBAAuB,EAAE,IAAI;AAC7B,YAAA,gCAAgC,EAAE,IAAI;AACvC,SAAA,CAAC;AAEJ,QAAA,MAAM,MAAM,GAAG;AACb,YAAA,GAAG,IAAI,CAAC,gBAAgB,CA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IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACjC,gBAAA,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,KACxB,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAC3C;;;QAGL,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE;AACpC,YAAA,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC;;;AAGlC;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../../../src/llm/openrouter/index.ts"],"sourcesContent":["import { ChatOpenAI } from '@/llm/openai';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport { AIMessageChunk as AIMessageChunkClass } from '@langchain/core/messages';\nimport type {\n FunctionMessageChunk,\n SystemMessageChunk,\n HumanMessageChunk,\n ToolMessageChunk,\n ChatMessageChunk,\n AIMessageChunk,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type {\n ChatOpenAICallOptions,\n OpenAIChatInput,\n OpenAIClient,\n} from '@langchain/openai';\nimport { _convertMessagesToOpenAIParams } from '@/llm/openai/utils';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\nexport interface ChatOpenRouterCallOptions extends ChatOpenAICallOptions {\n include_reasoning?: boolean;\n modelKwargs?: OpenAIChatInput['modelKwargs'];\n}\nexport class ChatOpenRouter extends ChatOpenAI {\n constructor(_fields: Partial<ChatOpenRouterCallOptions>) {\n const { include_reasoning, modelKwargs = {}, ...fields } = _fields;\n super({\n ...fields,\n modelKwargs: {\n ...modelKwargs,\n include_reasoning,\n },\n });\n }\n static lc_name(): 'LibreChatOpenRouter' {\n return 'LibreChatOpenRouter';\n }\n protected override _convertOpenAIDeltaToBaseMessageChunk(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>,\n rawResponse: OpenAIClient.ChatCompletionChunk,\n defaultRole?:\n | 'function'\n | 'user'\n | 'system'\n | 'developer'\n | 'assistant'\n | 'tool'\n ):\n | AIMessageChunk\n | HumanMessageChunk\n | SystemMessageChunk\n | FunctionMessageChunk\n | ToolMessageChunk\n | ChatMessageChunk {\n const messageChunk = super._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n rawResponse,\n defaultRole\n );\n if (delta.reasoning != null) {\n messageChunk.additional_kwargs.reasoning = delta.reasoning;\n }\n if (delta.reasoning_details != null) {\n messageChunk.additional_kwargs.reasoning_details =\n delta.reasoning_details;\n }\n return messageChunk;\n }\n\n async *_streamResponseChunks2(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const messagesMapped: OpenAICompletionParam[] =\n _convertMessagesToOpenAIParams(messages, this.model, {\n includeReasoningDetails: true,\n convertReasoningDetailsToContent: true,\n });\n\n const params = {\n ...this.invocationParams(options, {\n streaming: true,\n }),\n messages: messagesMapped,\n stream: true as const,\n };\n let defaultRole: OpenAIRoleEnum | undefined;\n\n const streamIterable = await this.completionWithRetry(params, options);\n let usage: OpenAIClient.Completions.CompletionUsage | undefined;\n\n // Store reasoning_details keyed by unique identifier to prevent incorrect merging\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningTextByIndex: Map<number, Record<string, any>> = new Map();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningEncryptedById: Map<string, Record<string, any>> = new Map();\n\n for await (const data of streamIterable) {\n const choice = data.choices[0] as\n | Partial<OpenAIClient.Chat.Completions.ChatCompletionChunk.Choice>\n | undefined;\n if (data.usage) {\n usage = data.usage;\n }\n if (!choice) {\n continue;\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n // Accumulate reasoning_details from each delta\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const deltaAny = delta as Record<string, any>;\n // Extract current chunk's reasoning text for streaming (before accumulation)\n let currentChunkReasoningText = '';\n if (\n deltaAny.reasoning_details != null &&\n Array.isArray(deltaAny.reasoning_details)\n ) {\n for (const detail of deltaAny.reasoning_details) {\n // For encrypted reasoning (thought signatures), store by ID - MUST be separate\n if (detail.type === 'reasoning.encrypted' && detail.id) {\n reasoningEncryptedById.set(detail.id, {\n type: detail.type,\n id: detail.id,\n data: detail.data,\n format: detail.format,\n index: detail.index,\n });\n } else if (detail.type === 'reasoning.text') {\n // Extract current chunk's text for streaming\n currentChunkReasoningText += detail.text || '';\n // For text reasoning, accumulate text by index for final message\n const idx = detail.index ?? 0;\n const existing = reasoningTextByIndex.get(idx);\n if (existing) {\n // Only append text, keep other fields from first entry\n existing.text = (existing.text || '') + (detail.text || '');\n } else {\n reasoningTextByIndex.set(idx, {\n type: detail.type,\n text: detail.text || '',\n format: detail.format,\n index: idx,\n });\n }\n }\n }\n }\n\n const chunk = this._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n data,\n defaultRole\n );\n\n // For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),\n // set the current chunk's reasoning text to additional_kwargs.reasoning for streaming\n if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {\n chunk.additional_kwargs.reasoning = currentChunkReasoningText;\n }\n\n // IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent\n // LangChain's chunk concatenation from corrupting the array\n // Check if this is the final chunk (has finish_reason)\n if (choice.finish_reason != null) {\n // Build properly structured reasoning_details array\n // Text entries first (but we only need the encrypted ones for thought signatures)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalReasoningDetails: Record<string, any>[] = [\n ...reasoningTextByIndex.values(),\n ...reasoningEncryptedById.values(),\n ];\n\n if (finalReasoningDetails.length > 0) {\n chunk.additional_kwargs.reasoning_details = finalReasoningDetails;\n }\n } else {\n // Clear reasoning_details from intermediate chunks to prevent concatenation issues\n delete chunk.additional_kwargs.reasoning_details;\n }\n\n defaultRole = delta.role ?? defaultRole;\n const newTokenIndices = {\n prompt: options.promptIndex ?? 0,\n completion: choice.index ?? 0,\n };\n if (typeof chunk.content !== 'string') {\n // eslint-disable-next-line no-console\n console.log(\n '[WARNING]: Received non-string content from OpenAI. This is currently not supported.'\n );\n continue;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const generationInfo: Record<string, any> = { ...newTokenIndices };\n if (choice.finish_reason != null) {\n generationInfo.finish_reason = choice.finish_reason;\n generationInfo.system_fingerprint = data.system_fingerprint;\n generationInfo.model_name = data.model;\n generationInfo.service_tier = data.service_tier;\n }\n if (this.logprobs == true) {\n generationInfo.logprobs = choice.logprobs;\n }\n const generationChunk = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n generationInfo,\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n await runManager?.handleLLMNewToken(\n generationChunk.text || '',\n newTokenIndices,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n if (usage) {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunkClass({\n content: '',\n response_metadata: {\n usage: { ...usage },\n },\n usage_metadata: {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n total_tokens: usage.total_tokens,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n },\n }),\n text: '',\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n }\n if (options.signal?.aborted === true) {\n throw new Error('AbortError');\n }\n }\n}\n"],"names":["ChatOpenAI","messages","_convertMessagesToOpenAIParams","ChatGenerationChunk","AIMessageChunkClass"],"mappings":";;;;;;;AAmCM,MAAO,cAAe,SAAQA,gBAAU,CAAA;AAC5C,IAAA,WAAA,CAAY,OAA2C,EAAA;AACrD,QAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO;AAClE,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,WAAW,EAAE;AACX,gBAAA,GAAG,WAAW;gBACd,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;;AAEJ,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,qBAAqB;;IAEX,qCAAqC;;IAEtD,KAA0B,EAC1B,WAA6C,EAC7C,WAMU,EAAA;AAQV,QAAA,MAAM,YAAY,GAAG,KAAK,CAAC,qCAAqC,CAC9D,KAAK,EACL,WAAW,EACX,WAAW,CACZ;AACD,QAAA,IAAI,KAAK,CAAC,SAAS,IAAI,IAAI,EAAE;YAC3B,YAAY,CAAC,iBAAiB,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS;;AAE5D,QAAA,IAAI,KAAK,CAAC,iBAAiB,IAAI,IAAI,EAAE;YACnC,YAAY,CAAC,iBAAiB,CAAC,iBAAiB;gBAC9C,KAAK,CAAC,iBAAiB;;AAE3B,QAAA,OAAO,YAAY;;IAGrB,OAAO,sBAAsB,CAC3BC,UAAuB,EACvB,OAAkC,EAClC,UAAqC,EAAA;QAErC,MAAM,cAAc,GAClBC,sCAA8B,CAACD,UAAQ,EAAE,IAAI,CAAC,KAAK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AAE,KAAK,CAAC,YAAY;wBAChC,IAAI,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI;AAC/C,4BAAA,mBAAmB,EAAE,iBAAiB;yBACvC,CAAC;wBACF,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI;AAChD,4BAAA,oBAAoB,EAAE,kBAAkB;yBACzC,CAAC;AACH,qBAAA;iBACF,CAAC;AACF,gBAAA,IAAI,EAAE,EAAE;AACT,aAAA,CAAC;AACF,YAAA,MAAM,eAAe;AACrB,YAAA,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACjC,gBAAA,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,KACxB,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAC3C;;;QAGL,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE;AACpC,YAAA,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC;;;AAGlC;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -59,19 +59,22 @@ function getChunkContent({ chunk, provider, reasoningKey, }) {
|
|
|
59
59
|
(chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
|
|
60
60
|
return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
|
|
61
61
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
62
|
+
/**
|
|
63
|
+
* For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).
|
|
64
|
+
* NOTE: We intentionally do NOT extract text from reasoning_details here.
|
|
65
|
+
* The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),
|
|
66
|
+
* but individual reasoning tokens are already streamed via additional_kwargs.reasoning.
|
|
67
|
+
* Extracting from reasoning_details would cause duplication.
|
|
68
|
+
* The reasoning_details is only used for:
|
|
69
|
+
* 1. Detecting reasoning mode in handleReasoning()
|
|
70
|
+
* 2. Final message storage (for thought signatures)
|
|
71
|
+
*/
|
|
72
|
+
if (provider === _enum.Providers.OPENROUTER) {
|
|
73
|
+
const reasoning = chunk?.additional_kwargs?.reasoning;
|
|
74
|
+
if (reasoning != null && reasoning !== '') {
|
|
75
|
+
return reasoning;
|
|
76
|
+
}
|
|
77
|
+
return chunk?.content;
|
|
75
78
|
}
|
|
76
79
|
return ((chunk?.additional_kwargs?.[reasoningKey] ?? '') ||
|
|
77
80
|
chunk?.content);
|
|
@@ -274,9 +277,12 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
274
277
|
reasoning_content = 'valid';
|
|
275
278
|
}
|
|
276
279
|
else if (agentContext.provider === _enum.Providers.OPENROUTER &&
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
+
// Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)
|
|
281
|
+
((chunk.additional_kwargs?.reasoning_details != null &&
|
|
282
|
+
Array.isArray(chunk.additional_kwargs.reasoning_details) &&
|
|
283
|
+
chunk.additional_kwargs.reasoning_details.length > 0) ||
|
|
284
|
+
(typeof chunk.additional_kwargs?.reasoning === 'string' &&
|
|
285
|
+
chunk.additional_kwargs.reasoning !== ''))) {
|
|
280
286
|
reasoning_content = 'valid';
|
|
281
287
|
}
|
|
282
288
|
if (reasoning_content != null &&
|
package/dist/cjs/stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n if (\n provider === Providers.OPENROUTER &&\n chunk?.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details)\n ) {\n // Extract text from reasoning_details array (for Gemini, DeepSeek, etc.)\n const textEntries = chunk.additional_kwargs.reasoning_details\n .filter(\n (detail) =>\n detail.type === 'reasoning.text' &&\n detail.text != null &&\n detail.text !== ''\n )\n .map((detail) => detail.text)\n .join('');\n if (textEntries) {\n return textEntries;\n }\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["Providers","handleServerToolResult","handleToolCalls","handleToolCallChunks","getMessageId","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,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O,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)\n ((chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0) ||\n (typeof chunk.additional_kwargs?.reasoning === 'string' &&\n chunk.additional_kwargs.reasoning !== ''))\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["Providers","handleServerToolResult","handleToolCalls","handleToolCallChunks","getMessageId","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,QAAA,IAAI,QAAQ,KAAK,EAAE,EAAE;;AAEnB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;YACvC;;;AAIF,QAAA,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,EAAE,QAAQ,CAAC;AAC5D,QAAA,cAAc,CAAC,IAAI,CAAC,YAAY,CAAC;;AAGjC,QAAA,QAAQ,GAAG,QAAQ,GAAG,CAAC,CAAC;;IAG1B,OAAO;AACL,QAAA,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE;QACvB,QAAQ,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC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Y,CAAC,KAAK,CAAC,UAAU,EAC7B;gBACA,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,aAAa,KAAI;oBACtD,MAAM,UAAU,GAAG,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;AAErD,oBAAA,MAAM,WAAW,GAA4B;wBAC3C,IAAI,EAAEC,kBAAY,CAAC,SAAS;AAC5B,wBAAA,SAAS,EAAE;AACT,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;4BAC9B,IAAI,EAAE,aAAa,CAAC,IAAI;AACxB,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAKE,iBAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;;"}
|
|
@@ -65,6 +65,8 @@ class ChatOpenRouter extends ChatOpenAI {
|
|
|
65
65
|
// Accumulate reasoning_details from each delta
|
|
66
66
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
67
67
|
const deltaAny = delta;
|
|
68
|
+
// Extract current chunk's reasoning text for streaming (before accumulation)
|
|
69
|
+
let currentChunkReasoningText = '';
|
|
68
70
|
if (deltaAny.reasoning_details != null &&
|
|
69
71
|
Array.isArray(deltaAny.reasoning_details)) {
|
|
70
72
|
for (const detail of deltaAny.reasoning_details) {
|
|
@@ -79,7 +81,9 @@ class ChatOpenRouter extends ChatOpenAI {
|
|
|
79
81
|
});
|
|
80
82
|
}
|
|
81
83
|
else if (detail.type === 'reasoning.text') {
|
|
82
|
-
//
|
|
84
|
+
// Extract current chunk's text for streaming
|
|
85
|
+
currentChunkReasoningText += detail.text || '';
|
|
86
|
+
// For text reasoning, accumulate text by index for final message
|
|
83
87
|
const idx = detail.index ?? 0;
|
|
84
88
|
const existing = reasoningTextByIndex.get(idx);
|
|
85
89
|
if (existing) {
|
|
@@ -98,6 +102,11 @@ class ChatOpenRouter extends ChatOpenAI {
|
|
|
98
102
|
}
|
|
99
103
|
}
|
|
100
104
|
const chunk = this._convertOpenAIDeltaToBaseMessageChunk(delta, data, defaultRole);
|
|
105
|
+
// For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),
|
|
106
|
+
// set the current chunk's reasoning text to additional_kwargs.reasoning for streaming
|
|
107
|
+
if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {
|
|
108
|
+
chunk.additional_kwargs.reasoning = currentChunkReasoningText;
|
|
109
|
+
}
|
|
101
110
|
// IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent
|
|
102
111
|
// LangChain's chunk concatenation from corrupting the array
|
|
103
112
|
// Check if this is the final chunk (has finish_reason)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/llm/openrouter/index.ts"],"sourcesContent":["import { ChatOpenAI } from '@/llm/openai';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport { AIMessageChunk as AIMessageChunkClass } from '@langchain/core/messages';\nimport type {\n FunctionMessageChunk,\n SystemMessageChunk,\n HumanMessageChunk,\n ToolMessageChunk,\n ChatMessageChunk,\n AIMessageChunk,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type {\n ChatOpenAICallOptions,\n OpenAIChatInput,\n OpenAIClient,\n} from '@langchain/openai';\nimport { _convertMessagesToOpenAIParams } from '@/llm/openai/utils';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\nexport interface ChatOpenRouterCallOptions extends ChatOpenAICallOptions {\n include_reasoning?: boolean;\n modelKwargs?: OpenAIChatInput['modelKwargs'];\n}\nexport class ChatOpenRouter extends ChatOpenAI {\n constructor(_fields: Partial<ChatOpenRouterCallOptions>) {\n const { include_reasoning, modelKwargs = {}, ...fields } = _fields;\n super({\n ...fields,\n modelKwargs: {\n ...modelKwargs,\n include_reasoning,\n },\n });\n }\n static lc_name(): 'LibreChatOpenRouter' {\n return 'LibreChatOpenRouter';\n }\n protected override _convertOpenAIDeltaToBaseMessageChunk(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>,\n rawResponse: OpenAIClient.ChatCompletionChunk,\n defaultRole?:\n | 'function'\n | 'user'\n | 'system'\n | 'developer'\n | 'assistant'\n | 'tool'\n ):\n | AIMessageChunk\n | HumanMessageChunk\n | SystemMessageChunk\n | FunctionMessageChunk\n | ToolMessageChunk\n | ChatMessageChunk {\n const messageChunk = super._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n rawResponse,\n defaultRole\n );\n if (delta.reasoning != null) {\n messageChunk.additional_kwargs.reasoning = delta.reasoning;\n }\n if (delta.reasoning_details != null) {\n messageChunk.additional_kwargs.reasoning_details =\n delta.reasoning_details;\n }\n return messageChunk;\n }\n\n async *_streamResponseChunks2(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const messagesMapped: OpenAICompletionParam[] =\n _convertMessagesToOpenAIParams(messages, this.model, {\n includeReasoningDetails: true,\n convertReasoningDetailsToContent: true,\n });\n\n const params = {\n ...this.invocationParams(options, {\n streaming: true,\n }),\n messages: messagesMapped,\n stream: true as const,\n };\n let defaultRole: OpenAIRoleEnum | undefined;\n\n const streamIterable = await this.completionWithRetry(params, options);\n let usage: OpenAIClient.Completions.CompletionUsage | undefined;\n\n // Store reasoning_details keyed by unique identifier to prevent incorrect merging\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningTextByIndex: Map<number, Record<string, any>> = new Map();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningEncryptedById: Map<string, Record<string, any>> = new Map();\n\n for await (const data of streamIterable) {\n const choice = data.choices[0] as\n | Partial<OpenAIClient.Chat.Completions.ChatCompletionChunk.Choice>\n | undefined;\n if (data.usage) {\n usage = data.usage;\n }\n if (!choice) {\n continue;\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n // Accumulate reasoning_details from each delta\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const deltaAny = delta as Record<string, any>;\n if (\n deltaAny.reasoning_details != null &&\n Array.isArray(deltaAny.reasoning_details)\n ) {\n for (const detail of deltaAny.reasoning_details) {\n // For encrypted reasoning (thought signatures), store by ID - MUST be separate\n if (detail.type === 'reasoning.encrypted' && detail.id) {\n reasoningEncryptedById.set(detail.id, {\n type: detail.type,\n id: detail.id,\n data: detail.data,\n format: detail.format,\n index: detail.index,\n });\n } else if (detail.type === 'reasoning.text') {\n // For text reasoning, accumulate text by index\n const idx = detail.index ?? 0;\n const existing = reasoningTextByIndex.get(idx);\n if (existing) {\n // Only append text, keep other fields from first entry\n existing.text = (existing.text || '') + (detail.text || '');\n } else {\n reasoningTextByIndex.set(idx, {\n type: detail.type,\n text: detail.text || '',\n format: detail.format,\n index: idx,\n });\n }\n }\n }\n }\n\n const chunk = this._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n data,\n defaultRole\n );\n\n // IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent\n // LangChain's chunk concatenation from corrupting the array\n // Check if this is the final chunk (has finish_reason)\n if (choice.finish_reason != null) {\n // Build properly structured reasoning_details array\n // Text entries first (but we only need the encrypted ones for thought signatures)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalReasoningDetails: Record<string, any>[] = [\n ...reasoningTextByIndex.values(),\n ...reasoningEncryptedById.values(),\n ];\n\n if (finalReasoningDetails.length > 0) {\n chunk.additional_kwargs.reasoning_details = finalReasoningDetails;\n }\n } else {\n // Clear reasoning_details from intermediate chunks to prevent concatenation issues\n delete chunk.additional_kwargs.reasoning_details;\n }\n\n defaultRole = delta.role ?? defaultRole;\n const newTokenIndices = {\n prompt: options.promptIndex ?? 0,\n completion: choice.index ?? 0,\n };\n if (typeof chunk.content !== 'string') {\n // eslint-disable-next-line no-console\n console.log(\n '[WARNING]: Received non-string content from OpenAI. This is currently not supported.'\n );\n continue;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const generationInfo: Record<string, any> = { ...newTokenIndices };\n if (choice.finish_reason != null) {\n generationInfo.finish_reason = choice.finish_reason;\n generationInfo.system_fingerprint = data.system_fingerprint;\n generationInfo.model_name = data.model;\n generationInfo.service_tier = data.service_tier;\n }\n if (this.logprobs == true) {\n generationInfo.logprobs = choice.logprobs;\n }\n const generationChunk = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n generationInfo,\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n await runManager?.handleLLMNewToken(\n generationChunk.text || '',\n newTokenIndices,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n if (usage) {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunkClass({\n content: '',\n response_metadata: {\n usage: { ...usage },\n },\n usage_metadata: {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n total_tokens: usage.total_tokens,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n },\n }),\n text: '',\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n }\n if (options.signal?.aborted === true) {\n throw new Error('AbortError');\n }\n }\n}\n"],"names":["AIMessageChunkClass"],"mappings":";;;;;AAmCM,MAAO,cAAe,SAAQ,UAAU,CAAA;AAC5C,IAAA,WAAA,CAAY,OAA2C,EAAA;AACrD,QAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO;AAClE,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,WAAW,EAAE;AACX,gBAAA,GAAG,WAAW;gBACd,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;;AAEJ,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,qBAAqB;;IAEX,qCAAqC;;IAEtD,KAA0B,EAC1B,WAA6C,EAC7C,WAMU,EAAA;AAQV,QAAA,MAAM,YAAY,GAAG,KAAK,CAAC,qCAAqC,CAC9D,KAAK,EACL,WA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oBAAA,iBAAiB,EAAE;AACjB,wBAAA,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE;AACpB,qBAAA;AACD,oBAAA,cAAc,EAAE;wBACd,YAAY,EAAE,KAAK,CAAC,aAAa;wBACjC,aAAa,EAAE,KAAK,CAAC,iBAAiB;wBACtC,YAAY,EAAE,KAAK,CAAC,YAAY;wBAChC,IAAI,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI;AAC/C,4BAAA,mBAAmB,EAAE,iBAAiB;yBACvC,CAAC;wBACF,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI;AAChD,4BAAA,oBAAoB,EAAE,kBAAkB;yBACzC,CAAC;AACH,qBAAA;iBACF,CAAC;AACF,gBAAA,IAAI,EAAE,EAAE;AACT,aAAA,CAAC;AACF,YAAA,MAAM,eAAe;AACrB,YAAA,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACjC,gBAAA,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,KACxB,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAC3C;;;QAGL,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE;AACpC,YAAA,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC;;;AAGlC;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/llm/openrouter/index.ts"],"sourcesContent":["import { ChatOpenAI } from '@/llm/openai';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport { AIMessageChunk as AIMessageChunkClass } from '@langchain/core/messages';\nimport type {\n FunctionMessageChunk,\n SystemMessageChunk,\n HumanMessageChunk,\n ToolMessageChunk,\n ChatMessageChunk,\n AIMessageChunk,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type {\n ChatOpenAICallOptions,\n OpenAIChatInput,\n OpenAIClient,\n} from '@langchain/openai';\nimport { _convertMessagesToOpenAIParams } from '@/llm/openai/utils';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\nexport interface ChatOpenRouterCallOptions extends ChatOpenAICallOptions {\n include_reasoning?: boolean;\n modelKwargs?: OpenAIChatInput['modelKwargs'];\n}\nexport class ChatOpenRouter extends ChatOpenAI {\n constructor(_fields: Partial<ChatOpenRouterCallOptions>) {\n const { include_reasoning, modelKwargs = {}, ...fields } = _fields;\n super({\n ...fields,\n modelKwargs: {\n ...modelKwargs,\n include_reasoning,\n },\n });\n }\n static lc_name(): 'LibreChatOpenRouter' {\n return 'LibreChatOpenRouter';\n }\n protected override _convertOpenAIDeltaToBaseMessageChunk(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>,\n rawResponse: OpenAIClient.ChatCompletionChunk,\n defaultRole?:\n | 'function'\n | 'user'\n | 'system'\n | 'developer'\n | 'assistant'\n | 'tool'\n ):\n | AIMessageChunk\n | HumanMessageChunk\n | SystemMessageChunk\n | FunctionMessageChunk\n | ToolMessageChunk\n | ChatMessageChunk {\n const messageChunk = super._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n rawResponse,\n defaultRole\n );\n if (delta.reasoning != null) {\n messageChunk.additional_kwargs.reasoning = delta.reasoning;\n }\n if (delta.reasoning_details != null) {\n messageChunk.additional_kwargs.reasoning_details =\n delta.reasoning_details;\n }\n return messageChunk;\n }\n\n async *_streamResponseChunks2(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const messagesMapped: OpenAICompletionParam[] =\n _convertMessagesToOpenAIParams(messages, this.model, {\n includeReasoningDetails: true,\n convertReasoningDetailsToContent: true,\n });\n\n const params = {\n ...this.invocationParams(options, {\n streaming: true,\n }),\n messages: messagesMapped,\n stream: true as const,\n };\n let defaultRole: OpenAIRoleEnum | undefined;\n\n const streamIterable = await this.completionWithRetry(params, options);\n let usage: OpenAIClient.Completions.CompletionUsage | undefined;\n\n // Store reasoning_details keyed by unique identifier to prevent incorrect merging\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningTextByIndex: Map<number, Record<string, any>> = new Map();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningEncryptedById: Map<string, Record<string, any>> = new Map();\n\n for await (const data of streamIterable) {\n const choice = data.choices[0] as\n | Partial<OpenAIClient.Chat.Completions.ChatCompletionChunk.Choice>\n | undefined;\n if (data.usage) {\n usage = data.usage;\n }\n if (!choice) {\n continue;\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n // Accumulate reasoning_details from each delta\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const deltaAny = delta as Record<string, any>;\n // Extract current chunk's reasoning text for streaming (before accumulation)\n let currentChunkReasoningText = '';\n if (\n deltaAny.reasoning_details != null &&\n Array.isArray(deltaAny.reasoning_details)\n ) {\n for (const detail of deltaAny.reasoning_details) {\n // For encrypted reasoning (thought signatures), store by ID - MUST be separate\n if (detail.type === 'reasoning.encrypted' && detail.id) {\n reasoningEncryptedById.set(detail.id, {\n type: detail.type,\n id: detail.id,\n data: detail.data,\n format: detail.format,\n index: detail.index,\n });\n } else if (detail.type === 'reasoning.text') {\n // Extract current chunk's text for streaming\n currentChunkReasoningText += detail.text || '';\n // For text reasoning, accumulate text by index for final message\n const idx = detail.index ?? 0;\n const existing = reasoningTextByIndex.get(idx);\n if (existing) {\n // Only append text, keep other fields from first entry\n existing.text = (existing.text || '') + (detail.text || '');\n } else {\n reasoningTextByIndex.set(idx, {\n type: detail.type,\n text: detail.text || '',\n format: detail.format,\n index: idx,\n });\n }\n }\n }\n }\n\n const chunk = this._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n data,\n defaultRole\n );\n\n // For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),\n // set the current chunk's reasoning text to additional_kwargs.reasoning for streaming\n if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {\n chunk.additional_kwargs.reasoning = currentChunkReasoningText;\n }\n\n // IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent\n // LangChain's chunk concatenation from corrupting the array\n // Check if this is the final chunk (has finish_reason)\n if (choice.finish_reason != null) {\n // Build properly structured reasoning_details array\n // Text entries first (but we only need the encrypted ones for thought signatures)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalReasoningDetails: Record<string, any>[] = [\n ...reasoningTextByIndex.values(),\n ...reasoningEncryptedById.values(),\n ];\n\n if (finalReasoningDetails.length > 0) {\n chunk.additional_kwargs.reasoning_details = finalReasoningDetails;\n }\n } else {\n // Clear reasoning_details from intermediate chunks to prevent concatenation issues\n delete chunk.additional_kwargs.reasoning_details;\n }\n\n defaultRole = delta.role ?? defaultRole;\n const newTokenIndices = {\n prompt: options.promptIndex ?? 0,\n completion: choice.index ?? 0,\n };\n if (typeof chunk.content !== 'string') {\n // eslint-disable-next-line no-console\n console.log(\n '[WARNING]: Received non-string content from OpenAI. This is currently not supported.'\n );\n continue;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const generationInfo: Record<string, any> = { ...newTokenIndices };\n if (choice.finish_reason != null) {\n generationInfo.finish_reason = choice.finish_reason;\n generationInfo.system_fingerprint = data.system_fingerprint;\n generationInfo.model_name = data.model;\n generationInfo.service_tier = data.service_tier;\n }\n if (this.logprobs == true) {\n generationInfo.logprobs = choice.logprobs;\n }\n const generationChunk = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n generationInfo,\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n await runManager?.handleLLMNewToken(\n generationChunk.text || '',\n newTokenIndices,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n if (usage) {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunkClass({\n content: '',\n response_metadata: {\n usage: { ...usage },\n },\n usage_metadata: {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n total_tokens: usage.total_tokens,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n },\n }),\n text: '',\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n }\n if (options.signal?.aborted === true) {\n throw new Error('AbortError');\n }\n }\n}\n"],"names":["AIMessageChunkClass"],"mappings":";;;;;AAmCM,MAAO,cAAe,SAAQ,UAAU,CAAA;AAC5C,IAAA,WAAA,CAAY,OAA2C,EAAA;AACrD,QAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO;AAClE,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,WAAW,EAAE;AACX,gBAAA,GAAG,WAAW;gBACd,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;;AAEJ,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,qBAAqB;;IAEX,qCAAqC;;IAEtD,KAA0B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ANGED
|
@@ -57,19 +57,22 @@ function getChunkContent({ chunk, provider, reasoningKey, }) {
|
|
|
57
57
|
(chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
|
|
58
58
|
return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
|
|
59
59
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
60
|
+
/**
|
|
61
|
+
* For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).
|
|
62
|
+
* NOTE: We intentionally do NOT extract text from reasoning_details here.
|
|
63
|
+
* The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),
|
|
64
|
+
* but individual reasoning tokens are already streamed via additional_kwargs.reasoning.
|
|
65
|
+
* Extracting from reasoning_details would cause duplication.
|
|
66
|
+
* The reasoning_details is only used for:
|
|
67
|
+
* 1. Detecting reasoning mode in handleReasoning()
|
|
68
|
+
* 2. Final message storage (for thought signatures)
|
|
69
|
+
*/
|
|
70
|
+
if (provider === Providers.OPENROUTER) {
|
|
71
|
+
const reasoning = chunk?.additional_kwargs?.reasoning;
|
|
72
|
+
if (reasoning != null && reasoning !== '') {
|
|
73
|
+
return reasoning;
|
|
74
|
+
}
|
|
75
|
+
return chunk?.content;
|
|
73
76
|
}
|
|
74
77
|
return ((chunk?.additional_kwargs?.[reasoningKey] ?? '') ||
|
|
75
78
|
chunk?.content);
|
|
@@ -272,9 +275,12 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
272
275
|
reasoning_content = 'valid';
|
|
273
276
|
}
|
|
274
277
|
else if (agentContext.provider === Providers.OPENROUTER &&
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
+
// Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)
|
|
279
|
+
((chunk.additional_kwargs?.reasoning_details != null &&
|
|
280
|
+
Array.isArray(chunk.additional_kwargs.reasoning_details) &&
|
|
281
|
+
chunk.additional_kwargs.reasoning_details.length > 0) ||
|
|
282
|
+
(typeof chunk.additional_kwargs?.reasoning === 'string' &&
|
|
283
|
+
chunk.additional_kwargs.reasoning !== ''))) {
|
|
278
284
|
reasoning_content = 'valid';
|
|
279
285
|
}
|
|
280
286
|
if (reasoning_content != null &&
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n if (\n provider === Providers.OPENROUTER &&\n chunk?.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details)\n ) {\n // Extract text from reasoning_details array (for Gemini, DeepSeek, etc.)\n const textEntries = chunk.additional_kwargs.reasoning_details\n .filter(\n (detail) =>\n detail.type === 'reasoning.text' &&\n detail.text != null &&\n detail.text !== ''\n )\n .map((detail) => detail.text)\n .join('');\n if (textEntries) {\n return textEntries;\n }\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cA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,CAAC,IAAI;AACxB,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)\n ((chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0) ||\n (typeof chunk.additional_kwargs?.reasoning === 'string' &&\n chunk.additional_kwargs.reasoning !== ''))\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,QAAA,IAAI,QAAQ,KAAK,EAAE,EAAE;;AAEnB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;YACvC;;;AAIF,QAAA,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,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package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@librechat/agents",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.50",
|
|
4
4
|
"main": "./dist/cjs/main.cjs",
|
|
5
5
|
"module": "./dist/esm/main.mjs",
|
|
6
6
|
"types": "./dist/types/index.d.ts",
|
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
},
|
|
14
14
|
"type": "module",
|
|
15
15
|
"description": "",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/danny-avila/agents"
|
|
19
|
+
},
|
|
16
20
|
"author": "Danny Avila",
|
|
17
21
|
"license": "MIT",
|
|
18
22
|
"licenses": [
|
|
@@ -47,7 +51,7 @@
|
|
|
47
51
|
"image": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/image.ts --provider 'google' --name 'Jo' --location 'New York, NY'",
|
|
48
52
|
"code_exec_files": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_files.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
|
|
49
53
|
"code_exec_simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_simple.ts --provider 'google' --name 'Jo' --location 'New York, NY'",
|
|
50
|
-
"simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider '
|
|
54
|
+
"simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'openrouter' --name 'Jo' --location 'New York, NY'",
|
|
51
55
|
"caching": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/caching.ts --name 'Jo' --location 'New York, NY'",
|
|
52
56
|
"thinking": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/thinking.ts --name 'Jo' --location 'New York, NY'",
|
|
53
57
|
"memory": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/memory.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
|
|
@@ -128,6 +128,8 @@ export class ChatOpenRouter extends ChatOpenAI {
|
|
|
128
128
|
// Accumulate reasoning_details from each delta
|
|
129
129
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
130
130
|
const deltaAny = delta as Record<string, any>;
|
|
131
|
+
// Extract current chunk's reasoning text for streaming (before accumulation)
|
|
132
|
+
let currentChunkReasoningText = '';
|
|
131
133
|
if (
|
|
132
134
|
deltaAny.reasoning_details != null &&
|
|
133
135
|
Array.isArray(deltaAny.reasoning_details)
|
|
@@ -143,7 +145,9 @@ export class ChatOpenRouter extends ChatOpenAI {
|
|
|
143
145
|
index: detail.index,
|
|
144
146
|
});
|
|
145
147
|
} else if (detail.type === 'reasoning.text') {
|
|
146
|
-
//
|
|
148
|
+
// Extract current chunk's text for streaming
|
|
149
|
+
currentChunkReasoningText += detail.text || '';
|
|
150
|
+
// For text reasoning, accumulate text by index for final message
|
|
147
151
|
const idx = detail.index ?? 0;
|
|
148
152
|
const existing = reasoningTextByIndex.get(idx);
|
|
149
153
|
if (existing) {
|
|
@@ -167,6 +171,12 @@ export class ChatOpenRouter extends ChatOpenAI {
|
|
|
167
171
|
defaultRole
|
|
168
172
|
);
|
|
169
173
|
|
|
174
|
+
// For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),
|
|
175
|
+
// set the current chunk's reasoning text to additional_kwargs.reasoning for streaming
|
|
176
|
+
if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {
|
|
177
|
+
chunk.additional_kwargs.reasoning = currentChunkReasoningText;
|
|
178
|
+
}
|
|
179
|
+
|
|
170
180
|
// IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent
|
|
171
181
|
// LangChain's chunk concatenation from corrupting the array
|
|
172
182
|
// Check if this is the final chunk (has finish_reason)
|
package/src/stream.ts
CHANGED
|
@@ -107,24 +107,22 @@ export function getChunkContent({
|
|
|
107
107
|
| undefined
|
|
108
108
|
)?.summary?.[0]?.text;
|
|
109
109
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
.join('');
|
|
125
|
-
if (textEntries) {
|
|
126
|
-
return textEntries;
|
|
110
|
+
/**
|
|
111
|
+
* For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).
|
|
112
|
+
* NOTE: We intentionally do NOT extract text from reasoning_details here.
|
|
113
|
+
* The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),
|
|
114
|
+
* but individual reasoning tokens are already streamed via additional_kwargs.reasoning.
|
|
115
|
+
* Extracting from reasoning_details would cause duplication.
|
|
116
|
+
* The reasoning_details is only used for:
|
|
117
|
+
* 1. Detecting reasoning mode in handleReasoning()
|
|
118
|
+
* 2. Final message storage (for thought signatures)
|
|
119
|
+
*/
|
|
120
|
+
if (provider === Providers.OPENROUTER) {
|
|
121
|
+
const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;
|
|
122
|
+
if (reasoning != null && reasoning !== '') {
|
|
123
|
+
return reasoning;
|
|
127
124
|
}
|
|
125
|
+
return chunk?.content;
|
|
128
126
|
}
|
|
129
127
|
return (
|
|
130
128
|
((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||
|
|
@@ -376,9 +374,12 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
376
374
|
reasoning_content = 'valid';
|
|
377
375
|
} else if (
|
|
378
376
|
agentContext.provider === Providers.OPENROUTER &&
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
377
|
+
// Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)
|
|
378
|
+
((chunk.additional_kwargs?.reasoning_details != null &&
|
|
379
|
+
Array.isArray(chunk.additional_kwargs.reasoning_details) &&
|
|
380
|
+
chunk.additional_kwargs.reasoning_details.length > 0) ||
|
|
381
|
+
(typeof chunk.additional_kwargs?.reasoning === 'string' &&
|
|
382
|
+
chunk.additional_kwargs.reasoning !== ''))
|
|
382
383
|
) {
|
|
383
384
|
reasoning_content = 'valid';
|
|
384
385
|
}
|
package/src/utils/llmConfig.ts
CHANGED
|
@@ -56,7 +56,9 @@ export const llmConfigs: Record<string, t.LLMConfig | undefined> = {
|
|
|
56
56
|
provider: Providers.OPENROUTER,
|
|
57
57
|
streaming: true,
|
|
58
58
|
streamUsage: true,
|
|
59
|
-
model: 'anthropic/claude-sonnet-4',
|
|
59
|
+
// model: 'anthropic/claude-sonnet-4',
|
|
60
|
+
// model: 'moonshotai/kimi-k2-thinking',
|
|
61
|
+
model: 'google/gemini-3-pro-preview',
|
|
60
62
|
apiKey: process.env.OPENROUTER_API_KEY,
|
|
61
63
|
configuration: {
|
|
62
64
|
baseURL: process.env.OPENROUTER_BASE_URL,
|