@librechat/agents 3.1.99 → 3.2.1
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/graphs/Graph.cjs +154 -67
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/langfuse.cjs +9 -1
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +93 -7
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/stream.cjs +10 -8
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +155 -68
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/langfuse.mjs +9 -1
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +94 -8
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/stream.mjs +10 -8
- package/dist/esm/stream.mjs.map +1 -1
- package/package.json +1 -1
- package/src/graphs/Graph.ts +246 -104
- package/src/graphs/__tests__/Graph.reasoning.test.ts +747 -0
- package/src/langfuse.ts +13 -4
- package/src/messages/core.ts +126 -11
- package/src/messages/formatAgentMessages.test.ts +122 -0
- package/src/specs/deepseek.simple.test.ts +8 -3
- package/src/specs/langfuse-callbacks.test.ts +2 -1
- package/src/specs/langfuse-config.test.ts +23 -0
- package/src/specs/moonshot.simple.test.ts +8 -3
- package/src/splitStream.test.ts +64 -0
- package/src/stream.ts +12 -10
package/dist/esm/langfuse.mjs
CHANGED
|
@@ -3,6 +3,13 @@ import { CallbackHandler } from '@langfuse/langchain';
|
|
|
3
3
|
import { isPresent } from './utils/misc.mjs';
|
|
4
4
|
|
|
5
5
|
const TRACE_METADATA_MAX_LENGTH = 200;
|
|
6
|
+
const LANGFUSE_FORCE_FLUSH_ON_DISPOSE = 'LANGFUSE_FORCE_FLUSH_ON_DISPOSE';
|
|
7
|
+
function parseBooleanEnv(value) {
|
|
8
|
+
if (value == null) {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());
|
|
12
|
+
}
|
|
6
13
|
function hasLangfuseConfigCredentials(langfuse) {
|
|
7
14
|
return (langfuse != null &&
|
|
8
15
|
isPresent(langfuse.publicKey) &&
|
|
@@ -68,7 +75,8 @@ function isLangfuseCallbackHandler(value) {
|
|
|
68
75
|
return value instanceof CallbackHandler;
|
|
69
76
|
}
|
|
70
77
|
async function disposeLangfuseHandler(value) {
|
|
71
|
-
if (value == null
|
|
78
|
+
if (value == null ||
|
|
79
|
+
!parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE])) {
|
|
72
80
|
return;
|
|
73
81
|
}
|
|
74
82
|
const provider = getLangfuseTracerProvider();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"langfuse.mjs","sources":["../../src/langfuse.ts"],"sourcesContent":["import { getLangfuseTracerProvider } from '@langfuse/tracing';\nimport { CallbackHandler } from '@langfuse/langchain';\nimport type * as t from '@/types';\nimport { isPresent } from '@/utils/misc';\n\nconst TRACE_METADATA_MAX_LENGTH = 200;\n\nexport type LangfuseTraceMetadata = Record<string, string>;\n\ntype LangfuseHandlerParams = {\n userId?: string;\n sessionId?: string;\n traceMetadata?: LangfuseTraceMetadata;\n tags?: string[];\n};\n\ntype AgentLangfuseHandlerParams = LangfuseHandlerParams & {\n langfuse?: t.LangfuseConfig;\n};\n\ntype FlushableTracerProvider = {\n forceFlush?: () => Promise<void> | void;\n};\n\nfunction hasLangfuseTracingConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.toolNodeTracing != null || langfuse?.toolOutputTracing != null\n );\n}\n\nexport function hasLangfuseConfigCredentials(\n langfuse?: t.LangfuseConfig\n): langfuse is t.LangfuseConfig & {\n publicKey: string;\n secretKey: string;\n} {\n return (\n langfuse != null &&\n isPresent(langfuse.publicKey) &&\n isPresent(langfuse.secretKey)\n );\n}\n\nfunction hasLangfuseConfigBaseUrl(langfuse?: t.LangfuseConfig): boolean {\n return isPresent(langfuse?.baseUrl);\n}\n\nexport function isExplicitLangfuseConfig(
|
|
1
|
+
{"version":3,"file":"langfuse.mjs","sources":["../../src/langfuse.ts"],"sourcesContent":["import { getLangfuseTracerProvider } from '@langfuse/tracing';\nimport { CallbackHandler } from '@langfuse/langchain';\nimport type * as t from '@/types';\nimport { isPresent } from '@/utils/misc';\n\nconst TRACE_METADATA_MAX_LENGTH = 200;\nconst LANGFUSE_FORCE_FLUSH_ON_DISPOSE = 'LANGFUSE_FORCE_FLUSH_ON_DISPOSE';\n\nexport type LangfuseTraceMetadata = Record<string, string>;\n\ntype LangfuseHandlerParams = {\n userId?: string;\n sessionId?: string;\n traceMetadata?: LangfuseTraceMetadata;\n tags?: string[];\n};\n\ntype AgentLangfuseHandlerParams = LangfuseHandlerParams & {\n langfuse?: t.LangfuseConfig;\n};\n\ntype FlushableTracerProvider = {\n forceFlush?: () => Promise<void> | void;\n};\n\nfunction parseBooleanEnv(value?: string): boolean {\n if (value == null) {\n return false;\n }\n return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());\n}\n\nfunction hasLangfuseTracingConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.toolNodeTracing != null || langfuse?.toolOutputTracing != null\n );\n}\n\nexport function hasLangfuseConfigCredentials(\n langfuse?: t.LangfuseConfig\n): langfuse is t.LangfuseConfig & {\n publicKey: string;\n secretKey: string;\n} {\n return (\n langfuse != null &&\n isPresent(langfuse.publicKey) &&\n isPresent(langfuse.secretKey)\n );\n}\n\nfunction hasLangfuseConfigBaseUrl(langfuse?: t.LangfuseConfig): boolean {\n return isPresent(langfuse?.baseUrl);\n}\n\nexport function isExplicitLangfuseConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.enabled != null ||\n isPresent(langfuse?.publicKey) ||\n isPresent(langfuse?.secretKey) ||\n isPresent(langfuse?.baseUrl) ||\n hasLangfuseTracingConfig(langfuse)\n );\n}\n\nfunction createTraceMetadata(\n metadata: Record<string, unknown>\n): LangfuseTraceMetadata {\n const traceMetadata: LangfuseTraceMetadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (value == null) {\n continue;\n }\n const stringValue = typeof value === 'string' ? value : String(value);\n if (\n stringValue.trim() === '' ||\n stringValue.length > TRACE_METADATA_MAX_LENGTH\n ) {\n continue;\n }\n traceMetadata[key] = stringValue;\n }\n return traceMetadata;\n}\n\nexport function createLangfuseTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n}: {\n messageId?: unknown;\n parentMessageId?: unknown;\n agentId?: unknown;\n agentName?: unknown;\n}): LangfuseTraceMetadata {\n return createTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n });\n}\n\nexport function getLangfuseTraceName(\n traceMetadata?: LangfuseTraceMetadata,\n fallback: string = 'LibreChat Agent'\n): string {\n const agentName = traceMetadata?.agentName;\n return isPresent(agentName) ? `${fallback}: ${agentName}` : fallback;\n}\n\nexport function hasLangfuseEnvConfig(): boolean {\n return hasLangfuseEnvCredentials();\n}\n\nexport function hasLangfuseEnvCredentials(): boolean {\n return (\n isPresent(process.env.LANGFUSE_SECRET_KEY) &&\n isPresent(process.env.LANGFUSE_PUBLIC_KEY)\n );\n}\n\nexport function shouldCreateLangfuseHandler(\n langfuse?: t.LangfuseConfig\n): boolean {\n if (langfuse?.enabled === false) {\n return false;\n }\n return (\n hasLangfuseEnvConfig() ||\n hasLangfuseConfigCredentials(langfuse) ||\n (hasLangfuseConfigBaseUrl(langfuse) && hasLangfuseEnvCredentials())\n );\n}\n\nexport function createLegacyLangfuseHandler(\n params: LangfuseHandlerParams\n): CallbackHandler {\n return new CallbackHandler(params);\n}\n\nexport function createLangfuseHandler({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n tags,\n}: AgentLangfuseHandlerParams): CallbackHandler | undefined {\n if (!shouldCreateLangfuseHandler(langfuse)) {\n return undefined;\n }\n return new CallbackHandler({\n userId,\n sessionId,\n traceMetadata,\n tags,\n });\n}\n\nexport function hasExplicitLangfuseConfig(\n contexts: Iterable<{ langfuse?: t.LangfuseConfig }>\n): boolean {\n for (const context of contexts) {\n if (isExplicitLangfuseConfig(context.langfuse)) {\n return true;\n }\n }\n return false;\n}\n\nexport function isLangfuseCallbackHandler(value: unknown): boolean {\n return value instanceof CallbackHandler;\n}\n\nexport async function disposeLangfuseHandler(value: unknown): Promise<void> {\n if (\n value == null ||\n !parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE])\n ) {\n return;\n }\n const provider = getLangfuseTracerProvider() as FlushableTracerProvider;\n await provider.forceFlush?.();\n}\n"],"names":[],"mappings":";;;;AAKA,MAAM,yBAAyB,GAAG,GAAG;AACrC,MAAM,+BAA+B,GAAG,iCAAiC;AAmBzE,SAAS,eAAe,CAAC,KAAc,EAAA;AACrC,IAAA,IAAI,KAAK,IAAI,IAAI,EAAE;AACjB,QAAA,OAAO,KAAK;IACd;IACA,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACxE;AAQM,SAAU,4BAA4B,CAC1C,QAA2B,EAAA;IAK3B,QACE,QAAQ,IAAI,IAAI;AAChB,QAAA,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC;AAC7B,QAAA,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC;AAEjC;AAEA,SAAS,wBAAwB,CAAC,QAA2B,EAAA;AAC3D,IAAA,OAAO,SAAS,CAAC,QAAQ,EAAE,OAAO,CAAC;AACrC;AAYA,SAAS,mBAAmB,CAC1B,QAAiC,EAAA;IAEjC,MAAM,aAAa,GAA0B,EAAE;AAC/C,IAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;AACnD,QAAA,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QAAQ,EACR,MAAM,EACN,SAAS,EACT,aAAa,EACb,IAAI,GACuB,EAAA;AAC3B,IAAA,IAAI,CAAC,2BAA2B,CAAC,QAAQ,CAAC,EAAE;AAC1C,QAAA,OAAO,SAAS;IAClB;IACA,OAAO,IAAI,eAAe,CAAC;QACzB,MAAM;QACN,SAAS;QACT,aAAa;QACb,IAAI;AACL,KAAA,CAAC;AACJ;AAaM,SAAU,yBAAyB,CAAC,KAAc,EAAA;IACtD,OAAO,KAAK,YAAY,eAAe;AACzC;AAEO,eAAe,sBAAsB,CAAC,KAAc,EAAA;IACzD,IACE,KAAK,IAAI,IAAI;QACb,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC,EAC9D;QACA;IACF;AACA,IAAA,MAAM,QAAQ,GAAG,yBAAyB,EAA6B;AACvE,IAAA,MAAM,QAAQ,CAAC,UAAU,IAAI;AAC/B;;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ToolMessage, AIMessageChunk, AIMessage, HumanMessage } from '@langchain/core/messages';
|
|
2
|
-
import { Providers } from '../common/enum.mjs';
|
|
2
|
+
import { Providers, ContentTypes } from '../common/enum.mjs';
|
|
3
3
|
import { toLangChainContent } from './langchain.mjs';
|
|
4
4
|
|
|
5
5
|
// src/messages.ts
|
|
@@ -92,6 +92,57 @@ function reduceBlocks(blocks) {
|
|
|
92
92
|
}
|
|
93
93
|
return reduced;
|
|
94
94
|
}
|
|
95
|
+
function getReasoningText(value) {
|
|
96
|
+
if (typeof value === 'string') {
|
|
97
|
+
return value !== '' ? value : undefined;
|
|
98
|
+
}
|
|
99
|
+
const summaryText = value?.summary
|
|
100
|
+
?.map((summary) => summary.text ?? '')
|
|
101
|
+
.filter((text) => text !== '')
|
|
102
|
+
.join('');
|
|
103
|
+
return summaryText != null && summaryText !== '' ? summaryText : undefined;
|
|
104
|
+
}
|
|
105
|
+
function getReasoningDetailsText(value) {
|
|
106
|
+
if (!Array.isArray(value)) {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
const reasoningText = value
|
|
110
|
+
.filter((detail) => detail.type === 'reasoning.text')
|
|
111
|
+
.map((detail) => detail.text ?? '')
|
|
112
|
+
.filter((text) => text !== '')
|
|
113
|
+
.join('');
|
|
114
|
+
return reasoningText !== '' ? reasoningText : undefined;
|
|
115
|
+
}
|
|
116
|
+
function getAdditionalReasoningContent(message) {
|
|
117
|
+
const additionalKwargs = message.additional_kwargs;
|
|
118
|
+
if (additionalKwargs == null) {
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
const reasoningContent = getReasoningText(additionalKwargs.reasoning_content);
|
|
122
|
+
if (reasoningContent != null) {
|
|
123
|
+
return reasoningContent;
|
|
124
|
+
}
|
|
125
|
+
const reasoning = getReasoningText(additionalKwargs.reasoning);
|
|
126
|
+
if (reasoning != null) {
|
|
127
|
+
return reasoning;
|
|
128
|
+
}
|
|
129
|
+
return getReasoningDetailsText(additionalKwargs.reasoning_details);
|
|
130
|
+
}
|
|
131
|
+
function hasReasoningContent(content) {
|
|
132
|
+
if (!Array.isArray(content)) {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
return content.some((item) => {
|
|
136
|
+
if (typeof item !== 'object' || !('type' in item)) {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
return (item.type === ContentTypes.THINK ||
|
|
140
|
+
item.type === ContentTypes.THINKING ||
|
|
141
|
+
item.type === ContentTypes.REASONING ||
|
|
142
|
+
item.type === ContentTypes.REASONING_CONTENT ||
|
|
143
|
+
item.type === 'redacted_thinking');
|
|
144
|
+
});
|
|
145
|
+
}
|
|
95
146
|
function modifyDeltaProperties(provider, obj) {
|
|
96
147
|
if (!obj || typeof obj !== 'object')
|
|
97
148
|
return obj;
|
|
@@ -207,23 +258,50 @@ function formatAnthropicMessage(message) {
|
|
|
207
258
|
}
|
|
208
259
|
function convertMessagesToContent(messages) {
|
|
209
260
|
const processedContent = [];
|
|
261
|
+
const addToolCallBoundary = () => {
|
|
262
|
+
processedContent.push({ type: ContentTypes.TEXT, text: '' });
|
|
263
|
+
return processedContent.length - 1;
|
|
264
|
+
};
|
|
210
265
|
const addContentPart = (message) => {
|
|
211
266
|
const content = message?.lc_kwargs.content != null
|
|
212
267
|
? message.lc_kwargs.content
|
|
213
268
|
: message?.content;
|
|
214
269
|
if (content === undefined) {
|
|
215
|
-
return;
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
const reasoningContent = message?._getType() === 'ai' && !hasReasoningContent(content)
|
|
273
|
+
? getAdditionalReasoningContent(message)
|
|
274
|
+
: undefined;
|
|
275
|
+
if (reasoningContent != null) {
|
|
276
|
+
processedContent.push({
|
|
277
|
+
type: ContentTypes.THINK,
|
|
278
|
+
think: reasoningContent,
|
|
279
|
+
});
|
|
216
280
|
}
|
|
217
281
|
if (typeof content === 'string') {
|
|
282
|
+
if (content === '') {
|
|
283
|
+
return undefined;
|
|
284
|
+
}
|
|
218
285
|
processedContent.push({
|
|
219
|
-
type:
|
|
286
|
+
type: ContentTypes.TEXT,
|
|
220
287
|
text: content,
|
|
221
288
|
});
|
|
289
|
+
return processedContent.length - 1;
|
|
222
290
|
}
|
|
223
291
|
else if (Array.isArray(content)) {
|
|
224
|
-
|
|
225
|
-
|
|
292
|
+
let textContentIndex;
|
|
293
|
+
for (const item of content) {
|
|
294
|
+
if (item == null || item.type === 'tool_use') {
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
processedContent.push(item);
|
|
298
|
+
if (item.type === ContentTypes.TEXT) {
|
|
299
|
+
textContentIndex = processedContent.length - 1;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return textContentIndex;
|
|
226
303
|
}
|
|
304
|
+
return undefined;
|
|
227
305
|
};
|
|
228
306
|
let currentAIMessageIndex = -1;
|
|
229
307
|
const toolCallMap = new Map();
|
|
@@ -239,8 +317,8 @@ function convertMessagesToContent(messages) {
|
|
|
239
317
|
}
|
|
240
318
|
toolCallMap.set(tool_call.id, tool_call);
|
|
241
319
|
}
|
|
242
|
-
|
|
243
|
-
|
|
320
|
+
currentAIMessageIndex =
|
|
321
|
+
addContentPart(message) ?? addToolCallBoundary();
|
|
244
322
|
continue;
|
|
245
323
|
}
|
|
246
324
|
else if (messageType === 'tool' &&
|
|
@@ -269,6 +347,9 @@ function convertMessagesToContent(messages) {
|
|
|
269
347
|
}
|
|
270
348
|
return processedContent;
|
|
271
349
|
}
|
|
350
|
+
function stringifyToolMessageContent(content) {
|
|
351
|
+
return content == null ? '' : String(content);
|
|
352
|
+
}
|
|
272
353
|
function formatAnthropicArtifactContent(messages) {
|
|
273
354
|
const lastMessage = messages[messages.length - 1];
|
|
274
355
|
if (!(lastMessage instanceof ToolMessage))
|
|
@@ -298,7 +379,12 @@ function formatAnthropicArtifactContent(messages) {
|
|
|
298
379
|
Array.isArray(msg.artifact?.content)) {
|
|
299
380
|
const base = Array.isArray(msg.content)
|
|
300
381
|
? msg.content
|
|
301
|
-
: [
|
|
382
|
+
: [
|
|
383
|
+
{
|
|
384
|
+
type: ContentTypes.TEXT,
|
|
385
|
+
text: stringifyToolMessageContent(msg.content),
|
|
386
|
+
},
|
|
387
|
+
];
|
|
302
388
|
msg.content = base.concat(msg.artifact.content);
|
|
303
389
|
}
|
|
304
390
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.mjs","sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n HumanMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { Providers } from '@/common';\nimport { toLangChainContent } from './langchain';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY,\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [\n ..._allowedTypes,\n 'thinking',\n 'redacted_thinking',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content,\n}: {\n provider: Providers;\n messageType: string;\n content: t.ExtendedMessageContent[];\n}): (t.ExtendedMessageContent | null)[] => {\n const allowedTypes =\n allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map((item: t.ExtendedMessageContent | null) => {\n if (\n item &&\n typeof item === 'object' &&\n 'type' in item &&\n item.type != null &&\n item.type\n ) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (\n messageType === 'ai' &&\n newType === 'tool_use' &&\n 'input' in item &&\n item.input === ''\n ) {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock =\n | Partial<t.BedrockReasoningContentText>\n | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1] as ContentBlock | undefined;\n\n // Merge consecutive 'reasoning_content'\n if (\n block.type === 'reasoning_content' &&\n lastBlock?.type === 'reasoning_content'\n ) {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).text =\n (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (\n block.reasoningText?.signature != null &&\n block.reasoningText.signature\n ) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nexport function modifyDeltaProperties(\n provider: Providers,\n obj?: AIMessageChunk\n): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = (obj as Partial<AIMessageChunk>)._getType\n ? obj._getType()\n : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n reduceBlocks(obj.content as ContentBlock[])\n );\n }\n if (Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n modifyContent({\n provider,\n messageType,\n content: obj.content as t.ExtendedMessageContent[],\n }) as t.MessageContentComplex[]\n );\n }\n if (\n (obj as Partial<AIMessageChunk>).lc_kwargs &&\n Array.isArray(obj.lc_kwargs.content)\n ) {\n if (provider === Providers.BEDROCK) {\n obj.lc_kwargs.content = reduceBlocks(\n obj.lc_kwargs.content as ContentBlock[]\n );\n }\n obj.lc_kwargs.content = modifyContent({\n provider,\n messageType,\n content: obj.lc_kwargs.content,\n });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: toLangChainContent(message.content) });\n }\n\n const toolCallMap = new Map(message.tool_calls.map((tc) => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>(\n (acc, item) => {\n if (typeof item === 'object') {\n const extendedItem = item as t.ExtendedMessageContent;\n if (\n extendedItem.type === 'text' &&\n extendedItem.text != null &&\n extendedItem.text\n ) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (\n extendedItem.type === 'tool_use' &&\n extendedItem.id != null &&\n extendedItem.id\n ) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } else if (\n 'input' in extendedItem &&\n extendedItem.input != null &&\n extendedItem.input\n ) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(\n (tc) => tc.args.input === parsedInput.input\n );\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n },\n []\n );\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args,\n },\n })\n );\n\n return new AIMessage({\n content: toLangChainContent(formattedContent),\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n },\n });\n}\n\nexport function convertMessagesToContent(\n messages: BaseMessage[]\n): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content =\n message?.lc_kwargs.content != null\n ? message.lc_kwargs.content\n : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content,\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(\n (item) => item != null && item.type !== 'tool_use'\n );\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (\n messageType === 'ai' &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (tool_call.id == null || !tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (\n messageType === 'tool' &&\n (message as ToolMessage).tool_call_id\n ) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n if (currentAIMessageIndex === -1) {\n processedContent.push({ type: 'text', text: '' });\n currentAIMessageIndex = processedContent.length - 1;\n }\n const contentPart = processedContent[currentAIMessageIndex];\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Build tool call ID set and merge artifact content in a single forward pass.\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIdSet = new Set<string>();\n if (message.tool_calls) {\n for (const tc of message.tool_calls) {\n if (tc.id != null) {\n toolCallIdSet.add(tc.id);\n }\n }\n }\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (\n msg instanceof ToolMessage &&\n toolCallIdSet.has(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content)\n ) {\n const base = Array.isArray(msg.content)\n ? msg.content\n : [{ type: 'text' as const, text: String(msg.content ?? '') }];\n msg.content = base.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessageY.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Single pass: collect relevant tool messages with artifacts and aggregate\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (\n !(msg instanceof ToolMessage) ||\n !Array.isArray(msg.artifact?.content)\n ) {\n continue;\n }\n let currentContent = msg.content;\n if (!Array.isArray(currentContent)) {\n currentContent = [{ type: 'text', text: msg.content }];\n }\n aggregatedContent.push(...(currentContent as t.MessageContentComplex[]));\n msg.content =\n 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n }\n\n if (aggregatedContent.length > 0) {\n messages.push(\n new HumanMessage({ content: toLangChainContent(aggregatedContent) })\n );\n }\n}\n\nexport function findLastIndex<T>(\n array: T[],\n predicate: (value: T) => boolean\n): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n"],"names":[],"mappings":";;;;AAAA;AAaM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,GAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CAAC,CAAC;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO;CACvB;AAEC,IAAA,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC;AAClC;AAEA,MAAM,aAAa,GAAG,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,CAAC;AACtE,MAAM,sBAAsB,GAA6B;AACvD,IAAA,OAAO,EAAE,aAAa;AACtB,IAAA,CAAC,SAAS,CAAC,SAAS,GAAG;AACrB,QAAA,GAAG,aAAa;QAChB,UAAU;QACV,mBAAmB;QACnB,iBAAiB;QACjB,wBAAwB;QACxB,mBAAmB;AACpB,KAAA;IACD,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,GAAG,aAAa,EAAE,mBAAmB,CAAC;AAC5D,IAAA,CAAC,SAAS,CAAC,MAAM,GAAG,aAAa;CAClC;AAED,MAAM,aAAa,GAAG,CAAC,EACrB,QAAQ,EACR,WAAW,EACX,OAAO,GAKR,KAAyC;IACxC,MAAM,YAAY,GAChB,sBAAsB,CAAC,QAAQ,CAAC,IAAI,sBAAsB,CAAC,OAAO;AACpE,IAAA,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,IAAqC,KAAI;AAC3D,QAAA,IACE,IAAI;YACJ,OAAO,IAAI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B,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC;IACjD;AAEA,IAAA,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;AAChC,QAAA,QAAQ,CAAC,IAAI,CACX,IAAI,YAAY,CAAC,EAAE,OAAO,EAAE,kBAAkB,CAAC,iBAAiB,CAAC,EAAE,CAAC,CACrE;IACH;AACF;AAEM,SAAU,aAAa,CAC3B,KAAU,EACV,SAAgC,EAAA;AAEhC,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;QACV;IACF;IACA,OAAO,EAAE;AACX;;;;"}
|
|
1
|
+
{"version":3,"file":"core.mjs","sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n HumanMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { ContentTypes, Providers } from '@/common';\nimport { toLangChainContent } from './langchain';\n\ntype ReasoningSummary = { summary?: Array<{ text?: string }> };\ntype ReasoningDetail = { type?: string; text?: string };\ntype ReasoningAdditionalKwargs = {\n reasoning_content?: string | Partial<ReasoningSummary> | null;\n reasoning?: string | Partial<ReasoningSummary> | null;\n reasoning_details?: ReasoningDetail[] | null;\n};\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY,\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [\n ..._allowedTypes,\n 'thinking',\n 'redacted_thinking',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content,\n}: {\n provider: Providers;\n messageType: string;\n content: t.ExtendedMessageContent[];\n}): (t.ExtendedMessageContent | null)[] => {\n const allowedTypes =\n allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map((item: t.ExtendedMessageContent | null) => {\n if (\n item &&\n typeof item === 'object' &&\n 'type' in item &&\n item.type != null &&\n item.type\n ) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (\n messageType === 'ai' &&\n newType === 'tool_use' &&\n 'input' in item &&\n item.input === ''\n ) {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock =\n | Partial<t.BedrockReasoningContentText>\n | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1] as ContentBlock | undefined;\n\n // Merge consecutive 'reasoning_content'\n if (\n block.type === 'reasoning_content' &&\n lastBlock?.type === 'reasoning_content'\n ) {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).text =\n (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (\n block.reasoningText?.signature != null &&\n block.reasoningText.signature\n ) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nfunction getReasoningText(\n value: string | Partial<ReasoningSummary> | null | undefined\n): string | undefined {\n if (typeof value === 'string') {\n return value !== '' ? value : undefined;\n }\n const summaryText = value?.summary\n ?.map((summary) => summary.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return summaryText != null && summaryText !== '' ? summaryText : undefined;\n}\n\nfunction getReasoningDetailsText(\n value: ReasoningDetail[] | null | undefined\n): string | undefined {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const reasoningText = value\n .filter((detail) => detail.type === 'reasoning.text')\n .map((detail) => detail.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return reasoningText !== '' ? reasoningText : undefined;\n}\n\nfunction getAdditionalReasoningContent(\n message: BaseMessage\n): string | undefined {\n const additionalKwargs =\n message.additional_kwargs as ReasoningAdditionalKwargs | undefined;\n if (additionalKwargs == null) {\n return undefined;\n }\n\n const reasoningContent = getReasoningText(\n additionalKwargs.reasoning_content\n );\n if (reasoningContent != null) {\n return reasoningContent;\n }\n\n const reasoning = getReasoningText(additionalKwargs.reasoning);\n if (reasoning != null) {\n return reasoning;\n }\n\n return getReasoningDetailsText(additionalKwargs.reasoning_details);\n}\n\nfunction hasReasoningContent(content: BaseMessage['content']): boolean {\n if (!Array.isArray(content)) {\n return false;\n }\n return content.some((item) => {\n if (typeof item !== 'object' || !('type' in item)) {\n return false;\n }\n return (\n item.type === ContentTypes.THINK ||\n item.type === ContentTypes.THINKING ||\n item.type === ContentTypes.REASONING ||\n item.type === ContentTypes.REASONING_CONTENT ||\n item.type === 'redacted_thinking'\n );\n });\n}\n\nexport function modifyDeltaProperties(\n provider: Providers,\n obj?: AIMessageChunk\n): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = (obj as Partial<AIMessageChunk>)._getType\n ? obj._getType()\n : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n reduceBlocks(obj.content as ContentBlock[])\n );\n }\n if (Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n modifyContent({\n provider,\n messageType,\n content: obj.content as t.ExtendedMessageContent[],\n }) as t.MessageContentComplex[]\n );\n }\n if (\n (obj as Partial<AIMessageChunk>).lc_kwargs &&\n Array.isArray(obj.lc_kwargs.content)\n ) {\n if (provider === Providers.BEDROCK) {\n obj.lc_kwargs.content = reduceBlocks(\n obj.lc_kwargs.content as ContentBlock[]\n );\n }\n obj.lc_kwargs.content = modifyContent({\n provider,\n messageType,\n content: obj.lc_kwargs.content,\n });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: toLangChainContent(message.content) });\n }\n\n const toolCallMap = new Map(message.tool_calls.map((tc) => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>(\n (acc, item) => {\n if (typeof item === 'object') {\n const extendedItem = item as t.ExtendedMessageContent;\n if (\n extendedItem.type === 'text' &&\n extendedItem.text != null &&\n extendedItem.text\n ) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (\n extendedItem.type === 'tool_use' &&\n extendedItem.id != null &&\n extendedItem.id\n ) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } else if (\n 'input' in extendedItem &&\n extendedItem.input != null &&\n extendedItem.input\n ) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(\n (tc) => tc.args.input === parsedInput.input\n );\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n },\n []\n );\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args,\n },\n })\n );\n\n return new AIMessage({\n content: toLangChainContent(formattedContent),\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n },\n });\n}\n\nexport function convertMessagesToContent(\n messages: BaseMessage[]\n): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addToolCallBoundary = (): number => {\n processedContent.push({ type: ContentTypes.TEXT, text: '' });\n return processedContent.length - 1;\n };\n\n const addContentPart = (message: BaseMessage | null): number | undefined => {\n const content =\n message?.lc_kwargs.content != null\n ? message.lc_kwargs.content\n : message?.content;\n if (content === undefined) {\n return undefined;\n }\n const reasoningContent =\n message?._getType() === 'ai' && !hasReasoningContent(content)\n ? getAdditionalReasoningContent(message)\n : undefined;\n if (reasoningContent != null) {\n processedContent.push({\n type: ContentTypes.THINK,\n think: reasoningContent,\n });\n }\n if (typeof content === 'string') {\n if (content === '') {\n return undefined;\n }\n processedContent.push({\n type: ContentTypes.TEXT,\n text: content,\n });\n return processedContent.length - 1;\n } else if (Array.isArray(content)) {\n let textContentIndex: number | undefined;\n for (const item of content) {\n if (item == null || item.type === 'tool_use') {\n continue;\n }\n processedContent.push(item);\n if (item.type === ContentTypes.TEXT) {\n textContentIndex = processedContent.length - 1;\n }\n }\n return textContentIndex;\n }\n return undefined;\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (\n messageType === 'ai' &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (tool_call.id == null || !tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n currentAIMessageIndex =\n addContentPart(message) ?? addToolCallBoundary();\n continue;\n } else if (\n messageType === 'tool' &&\n (message as ToolMessage).tool_call_id\n ) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n if (currentAIMessageIndex === -1) {\n processedContent.push({ type: 'text', text: '' });\n currentAIMessageIndex = processedContent.length - 1;\n }\n const contentPart = processedContent[currentAIMessageIndex];\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nfunction stringifyToolMessageContent(\n content: ToolMessage['content'] | null | undefined\n): string {\n return content == null ? '' : String(content);\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Build tool call ID set and merge artifact content in a single forward pass.\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIdSet = new Set<string>();\n if (message.tool_calls) {\n for (const tc of message.tool_calls) {\n if (tc.id != null) {\n toolCallIdSet.add(tc.id);\n }\n }\n }\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (\n msg instanceof ToolMessage &&\n toolCallIdSet.has(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content)\n ) {\n const base = Array.isArray(msg.content)\n ? msg.content\n : [\n {\n type: ContentTypes.TEXT,\n text: stringifyToolMessageContent(msg.content),\n },\n ];\n msg.content = base.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessageY.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Single pass: collect relevant tool messages with artifacts and aggregate\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (\n !(msg instanceof ToolMessage) ||\n !Array.isArray(msg.artifact?.content)\n ) {\n continue;\n }\n let currentContent = msg.content;\n if (!Array.isArray(currentContent)) {\n currentContent = [{ type: 'text', text: msg.content }];\n }\n aggregatedContent.push(...(currentContent as t.MessageContentComplex[]));\n msg.content =\n 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n }\n\n if (aggregatedContent.length > 0) {\n messages.push(\n new HumanMessage({ content: toLangChainContent(aggregatedContent) })\n );\n }\n}\n\nexport function findLastIndex<T>(\n array: T[],\n predicate: (value: T) => boolean\n): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n"],"names":[],"mappings":";;;;AAAA;AAqBM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,GAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CAAC,CAAC;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO;CACvB;AAEC,IAAA,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC;AAClC;AAEA,MAAM,aAAa,GAAG,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,CAAC;AACtE,MAAM,sBAAsB,GAA6B;AACvD,IAAA,OAAO,EAAE,aAAa;AACtB,IAAA,CAAC,SAAS,CAAC,SAAS,GAAG;AACrB,QAAA,GAAG,aAAa;QAChB,UAAU;QACV,mBAAmB;QACnB,iBAAiB;QACjB,wBAAwB;QACxB,mBAAmB;AACpB,KAAA;IACD,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,GAAG,aAAa,EAAE,mBAAmB,CAAC;AAC5D,IAAA,CAAC,SAAS,CAAC,MAAM,GAAG,aAAa;CAClC;AAED,MAAM,aAAa,GAAG,CAAC,EACrB,QAAQ,EACR,WAAW,EACX,OAAO,GAKR,KAAyC;IACxC,MAAM,YAAY,GAChB,sBAAsB,CAAC,QAAQ,CAAC,IAAI,sBAAsB,CAAC,OAAO;AACpE,IAAA,OA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 +917,12 @@ function createContentAggregator() {
|
|
|
917
917
|
const toolCallIdMap = new Map();
|
|
918
918
|
// Track agentId and groupId for each content index (applied to content parts)
|
|
919
919
|
const contentMetaMap = new Map();
|
|
920
|
+
const getFirstContentPart = (content) => {
|
|
921
|
+
if (content == null) {
|
|
922
|
+
return undefined;
|
|
923
|
+
}
|
|
924
|
+
return Array.isArray(content) ? content[0] : content;
|
|
925
|
+
};
|
|
920
926
|
const updateContent = (index, contentPart, finalUpdate = false) => {
|
|
921
927
|
if (!contentPart) {
|
|
922
928
|
console.warn('No content part found in \'updateContent\'');
|
|
@@ -1124,10 +1130,8 @@ function createContentAggregator() {
|
|
|
1124
1130
|
console.warn('No run step or runId found for message delta event');
|
|
1125
1131
|
return;
|
|
1126
1132
|
}
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
? messageDelta.delta.content[0]
|
|
1130
|
-
: messageDelta.delta.content;
|
|
1133
|
+
const contentPart = getFirstContentPart(messageDelta.delta.content);
|
|
1134
|
+
if (contentPart != null) {
|
|
1131
1135
|
updateContent(runStep.index, contentPart);
|
|
1132
1136
|
}
|
|
1133
1137
|
}
|
|
@@ -1146,10 +1150,8 @@ function createContentAggregator() {
|
|
|
1146
1150
|
console.warn('No run step or runId found for reasoning delta event');
|
|
1147
1151
|
return;
|
|
1148
1152
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
? reasoningDelta.delta.content[0]
|
|
1152
|
-
: reasoningDelta.delta.content;
|
|
1153
|
+
const contentPart = getFirstContentPart(reasoningDelta.delta.content);
|
|
1154
|
+
if (contentPart != null) {
|
|
1153
1155
|
updateContent(runStep.index, contentPart);
|
|
1154
1156
|
}
|
|
1155
1157
|
}
|