@librechat/agents 1.9.96 → 1.9.98
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/main.cjs +1 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/splitStream.cjs +8 -11
- package/dist/cjs/splitStream.cjs.map +1 -1
- package/dist/cjs/stream.cjs +1 -0
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/main.mjs +1 -1
- package/dist/esm/splitStream.mjs +8 -11
- package/dist/esm/splitStream.mjs.map +1 -1
- package/dist/esm/stream.mjs +1 -1
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/types/splitStream.d.ts +1 -1
- package/dist/types/stream.d.ts +1 -0
- package/dist/types/types/stream.d.ts +5 -1
- package/package.json +1 -1
- package/src/splitStream.test.ts +91 -0
- package/src/splitStream.ts +9 -14
- package/src/stream.ts +1 -1
- package/src/types/stream.ts +6 -1
package/dist/cjs/main.cjs
CHANGED
|
@@ -17,6 +17,7 @@ var run$1 = require('./utils/run.cjs');
|
|
|
17
17
|
exports.Run = run.Run;
|
|
18
18
|
exports.ChatModelStreamHandler = stream.ChatModelStreamHandler;
|
|
19
19
|
exports.createContentAggregator = stream.createContentAggregator;
|
|
20
|
+
exports.getMessageId = stream.getMessageId;
|
|
20
21
|
exports.handleToolCalls = stream.handleToolCalls;
|
|
21
22
|
exports.SEPARATORS = splitStream.SEPARATORS;
|
|
22
23
|
exports.SplitStreamHandler = splitStream.SplitStreamHandler;
|
package/dist/cjs/main.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/cjs/splitStream.cjs
CHANGED
|
@@ -74,7 +74,7 @@ class SplitStreamHandler {
|
|
|
74
74
|
};
|
|
75
75
|
this.handlers?.[_enum.GraphEvents.ON_REASONING_DELTA]?.({ event: _enum.GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });
|
|
76
76
|
};
|
|
77
|
-
handleContent = (content,
|
|
77
|
+
handleContent = (content, _type) => {
|
|
78
78
|
let type = _type;
|
|
79
79
|
if (this.inThinkBlock && type === _enum.ContentTypes.TEXT) {
|
|
80
80
|
type = _enum.ContentTypes.THINK;
|
|
@@ -96,10 +96,7 @@ class SplitStreamHandler {
|
|
|
96
96
|
},
|
|
97
97
|
});
|
|
98
98
|
}
|
|
99
|
-
|
|
100
|
-
this.inCodeBlock = !this.inCodeBlock;
|
|
101
|
-
}
|
|
102
|
-
this.currentLength += content.length;
|
|
99
|
+
const stepId = this.currentStepId ?? '';
|
|
103
100
|
if (type === _enum.ContentTypes.THINK) {
|
|
104
101
|
this.dispatchReasoningDelta(stepId, {
|
|
105
102
|
content: [{
|
|
@@ -116,6 +113,7 @@ class SplitStreamHandler {
|
|
|
116
113
|
}],
|
|
117
114
|
});
|
|
118
115
|
}
|
|
116
|
+
this.currentLength += content.length;
|
|
119
117
|
if (this.inCodeBlock) {
|
|
120
118
|
return;
|
|
121
119
|
}
|
|
@@ -138,6 +136,9 @@ class SplitStreamHandler {
|
|
|
138
136
|
if (!content.length && !reasoning_content.length) {
|
|
139
137
|
return;
|
|
140
138
|
}
|
|
139
|
+
if (content.includes('```')) {
|
|
140
|
+
this.inCodeBlock = !this.inCodeBlock;
|
|
141
|
+
}
|
|
141
142
|
if (content === '<think>' && !this.inCodeBlock) {
|
|
142
143
|
this.inThinkBlock = true;
|
|
143
144
|
}
|
|
@@ -157,15 +158,11 @@ class SplitStreamHandler {
|
|
|
157
158
|
},
|
|
158
159
|
});
|
|
159
160
|
}
|
|
160
|
-
const stepId = this.currentStepId ?? '';
|
|
161
|
-
if (!stepId) {
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
161
|
if (reasoning_content) {
|
|
165
|
-
this.handleContent(reasoning_content,
|
|
162
|
+
this.handleContent(reasoning_content, _enum.ContentTypes.THINK);
|
|
166
163
|
}
|
|
167
164
|
else {
|
|
168
|
-
this.handleContent(content,
|
|
165
|
+
this.handleContent(content, _enum.ContentTypes.TEXT);
|
|
169
166
|
}
|
|
170
167
|
}
|
|
171
168
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitStream.cjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string,\n accumulate?: boolean,\n handlers: t.SplitStreamHandlers\n blockThreshold?: number,\n reasoningKey?: 'reasoning_content' | 'reasoning',\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (type?: ContentTypes.TEXT | ContentTypes.THINK): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });\n };\n handleContent = (content: string, stepId: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n this.currentLength += content.length;\n\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n }\n\n if (this.inCodeBlock) {\n return;\n }\n\n if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = chunk.choices?.[0]?.delta.content ?? '';\n const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content === '<think>' && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken === '</think>' && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;\n const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (!stepId) {\n return;\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, stepId, ContentTypes.THINK);\n } else {\n this.handleContent(content, stepId, ContentTypes.TEXT);\n }\n }\n}"],"names":["nanoid","GraphEvents","ContentTypes","StepTypes"],"mappings":";;;;;AAIa,MAAA,UAAU,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE;MAExE,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK,CAAC;IACpB,YAAY,GAAG,KAA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
+
{"version":3,"file":"splitStream.cjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string,\n accumulate?: boolean,\n handlers: t.SplitStreamHandlers\n blockThreshold?: number,\n reasoningKey?: 'reasoning_content' | 'reasoning',\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (type?: ContentTypes.TEXT | ContentTypes.THINK): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });\n };\n handleContent = (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = chunk.choices?.[0]?.delta.content ?? '';\n const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n if (content === '<think>' && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken === '</think>' && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;\n const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, ContentTypes.THINK);\n } else {\n this.handleContent(content, ContentTypes.TEXT);\n }\n }\n}"],"names":["nanoid","GraphEvents","ContentTypes","StepTypes"],"mappings":";;;;;AAIa,MAAA,UAAU,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE;MAExE,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK,CAAC;IACpB,YAAY,GAAG,KAAK,CAAC;AACrB,IAAA,UAAU,CAAU;IAC5B,MAAM,GAAa,EAAE,CAAC;IACtB,SAAS,GAAG,EAAE,CAAC;IACf,eAAe,GAAa,EAAE,CAAC;AAC/B,IAAA,aAAa,CAAU;AACvB,IAAA,gBAAgB,CAAU;AAC1B,IAAA,WAAW,CAA0C;IACrD,aAAa,GAAG,CAAC,CAAC;IAClB,YAAY,GAAsC,mBAAmB,CAAC;IACtE,YAAY,GAAG,CAAC,CAAC,CAAC;IAClB,cAAc,GAAG,IAAI,CAAC;;AAEtB,IAAA,KAA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C,SAAS,GAAG,OAAO,CAAC;QAEzB,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE,CAAC;QAE7C,IAAI,CAAC,UAAU,EAAE;AACf,YAAA,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,GAAGD,kBAAY,CAAC,KAAK,GAAGA,kBAAY,CAAC,IAAI,CAAC;AACtF,YAAA,MAAM,WAAW,GAAG,iBAAiB,GAAGA,kBAAY,CAAC,KAAK,GAAG,kBAAkB,CAAC;AAChF,YAAA,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC;AACjE,YAAA,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAEC,eAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC,CAAC;SACJ;QAED,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAED,kBAAY,CAAC,KAAK,CAAC,CAAC;SAC3D;aAAM;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAEA,kBAAY,CAAC,IAAI,CAAC,CAAC;SAChD;KACF;AACF;;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -348,5 +348,6 @@ function createContentAggregator() {
|
|
|
348
348
|
|
|
349
349
|
exports.ChatModelStreamHandler = ChatModelStreamHandler;
|
|
350
350
|
exports.createContentAggregator = createContentAggregator;
|
|
351
|
+
exports.getMessageId = getMessageId;
|
|
351
352
|
exports.handleToolCalls = handleToolCalls;
|
|
352
353
|
//# sourceMappingURL=stream.cjs.map
|
package/dist/cjs/stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\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\nconst getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\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 (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): 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 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 (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\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 = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\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 (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\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 (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 message 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\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 name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\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('No run step or runId found for completed tool call event');\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\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["nanoid","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK,CAAC;SACd;KACF;AACD,IAAA,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IACrH,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACzD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAA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CAAC;aACJ;SACF;AAAM,aAAA,IAAI,KAAK,KAAKE,iBAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C,CAAC;AAEjE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YAE9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;gBACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\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 const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\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 (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): 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 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 (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\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 = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\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 (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\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 (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 message 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\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 name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\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('No run step or runId found for completed tool call event');\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\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["nanoid","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK,CAAC;SACd;KACF;AACD,IAAA,OAAO,SAAS,CAAC;AACnB,CAAC;AAEM,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACzD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAAgB,GAAG,SAAS,GAAG,SAAS,CAAC;KACjD;IAED,MAAM,eAAe,GAAG,KAAK,CAAC,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACrE,IAAA,IAAI,eAAe,IAAI,IAAI,IAAI,eAAe,EAAE;AAC9C,QAAA,KAAK,CAAC,yBAAyB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAChD,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AACxD,QAAA,OAAO,eAAe,CAAC;KACxB;AAED,IAAA,MAAM,UAAU,GAAG,CAAA,IAAA,EAAOA,aAAM,EAAE,EAAE,CAAC;IACrC,KAAK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gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;;;;"}
|
package/dist/esm/main.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { Run } from './run.mjs';
|
|
2
|
-
export { ChatModelStreamHandler, createContentAggregator, handleToolCalls } from './stream.mjs';
|
|
2
|
+
export { ChatModelStreamHandler, createContentAggregator, getMessageId, handleToolCalls } from './stream.mjs';
|
|
3
3
|
export { SEPARATORS, SplitStreamHandler } from './splitStream.mjs';
|
|
4
4
|
export { HandlerRegistry, LLMStreamHandler, ModelEndHandler, TestChatStreamHandler, TestLLMStreamHandler, ToolEndHandler, createMetadataAggregator } from './events.mjs';
|
|
5
5
|
export { convertMessagesToContent, findLastIndex, formatAnthropicArtifactContent, formatAnthropicMessage, formatOpenAIArtifactContent, getConverseOverrideMessage, modifyDeltaProperties } from './messages.mjs';
|
package/dist/esm/splitStream.mjs
CHANGED
|
@@ -72,7 +72,7 @@ class SplitStreamHandler {
|
|
|
72
72
|
};
|
|
73
73
|
this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });
|
|
74
74
|
};
|
|
75
|
-
handleContent = (content,
|
|
75
|
+
handleContent = (content, _type) => {
|
|
76
76
|
let type = _type;
|
|
77
77
|
if (this.inThinkBlock && type === ContentTypes.TEXT) {
|
|
78
78
|
type = ContentTypes.THINK;
|
|
@@ -94,10 +94,7 @@ class SplitStreamHandler {
|
|
|
94
94
|
},
|
|
95
95
|
});
|
|
96
96
|
}
|
|
97
|
-
|
|
98
|
-
this.inCodeBlock = !this.inCodeBlock;
|
|
99
|
-
}
|
|
100
|
-
this.currentLength += content.length;
|
|
97
|
+
const stepId = this.currentStepId ?? '';
|
|
101
98
|
if (type === ContentTypes.THINK) {
|
|
102
99
|
this.dispatchReasoningDelta(stepId, {
|
|
103
100
|
content: [{
|
|
@@ -114,6 +111,7 @@ class SplitStreamHandler {
|
|
|
114
111
|
}],
|
|
115
112
|
});
|
|
116
113
|
}
|
|
114
|
+
this.currentLength += content.length;
|
|
117
115
|
if (this.inCodeBlock) {
|
|
118
116
|
return;
|
|
119
117
|
}
|
|
@@ -136,6 +134,9 @@ class SplitStreamHandler {
|
|
|
136
134
|
if (!content.length && !reasoning_content.length) {
|
|
137
135
|
return;
|
|
138
136
|
}
|
|
137
|
+
if (content.includes('```')) {
|
|
138
|
+
this.inCodeBlock = !this.inCodeBlock;
|
|
139
|
+
}
|
|
139
140
|
if (content === '<think>' && !this.inCodeBlock) {
|
|
140
141
|
this.inThinkBlock = true;
|
|
141
142
|
}
|
|
@@ -155,15 +156,11 @@ class SplitStreamHandler {
|
|
|
155
156
|
},
|
|
156
157
|
});
|
|
157
158
|
}
|
|
158
|
-
const stepId = this.currentStepId ?? '';
|
|
159
|
-
if (!stepId) {
|
|
160
|
-
return;
|
|
161
|
-
}
|
|
162
159
|
if (reasoning_content) {
|
|
163
|
-
this.handleContent(reasoning_content,
|
|
160
|
+
this.handleContent(reasoning_content, ContentTypes.THINK);
|
|
164
161
|
}
|
|
165
162
|
else {
|
|
166
|
-
this.handleContent(content,
|
|
163
|
+
this.handleContent(content, ContentTypes.TEXT);
|
|
167
164
|
}
|
|
168
165
|
}
|
|
169
166
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitStream.mjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string,\n accumulate?: boolean,\n handlers: t.SplitStreamHandlers\n blockThreshold?: number,\n reasoningKey?: 'reasoning_content' | 'reasoning',\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (type?: ContentTypes.TEXT | ContentTypes.THINK): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });\n };\n handleContent = (content: string, stepId: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n this.currentLength += content.length;\n\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n }\n\n if (this.inCodeBlock) {\n return;\n }\n\n if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = chunk.choices?.[0]?.delta.content ?? '';\n const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content === '<think>' && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken === '</think>' && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;\n const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (!stepId) {\n return;\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, stepId, ContentTypes.THINK);\n } else {\n this.handleContent(content, stepId, ContentTypes.TEXT);\n }\n }\n}"],"names":[],"mappings":";;;AAIa,MAAA,UAAU,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE;MAExE,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK,CAAC;IACpB,YAAY,GAAG,KAAK,CAAC;AACrB,IAAA,UAAU,CAAU;IAC5B,MAAM,GAAa,EAAE,CAAC;IACtB,SAAS,GAAG,EAAE,CAAC;IACf,eAAe,GAAa,EAAE,CAAC;AAC/B,IAAA,aAAa,CAAU;AACvB,IAAA,gBAAgB,CAAU;AAC1B,IAAA,WAAW,CAA0C;IACrD,aAAa,GAAG,CAAC,CAAC;IAClB,YAAY,GAAsC,mBAAmB,CAAC;IACtE,YAAY,GAAG,CAAC,CAAC,CAAC;IAClB,cAAc,GAAG,IAAI,CAAC;;AAEtB,IAAA,KAAK,CAAS;AACd,IAAA,QAAQ,CAAyB;IACjC,WAAY,CAAA,EACV,KAAK,EACL,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,cAAc,GAOb,EAAA;AACD,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACnB,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI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A,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC;AACjE,YAAA,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC,CAAC;SACJ;AAED,QAAA,MAAM,MAAM,GAAG,IAAI,CAAC,aAAa,IAAI,EAAE,CAAC;QACxC,IAAI,CAAC,MAAM,EAAE;YACX,OAAO;SACR;QAED,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,MAAM,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC;SACnE;aAAM;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;SACxD;KACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"splitStream.mjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string,\n accumulate?: boolean,\n handlers: t.SplitStreamHandlers\n blockThreshold?: number,\n reasoningKey?: 'reasoning_content' | 'reasoning',\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (type?: ContentTypes.TEXT | ContentTypes.THINK): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });\n };\n handleContent = (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = chunk.choices?.[0]?.delta.content ?? '';\n const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n if (content === '<think>' && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken === '</think>' && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;\n const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, ContentTypes.THINK);\n } else {\n this.handleContent(content, ContentTypes.TEXT);\n }\n }\n}"],"names":[],"mappings":";;;AAIa,M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aAAM;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;SAChD;KACF;AACF;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -344,5 +344,5 @@ function createContentAggregator() {
|
|
|
344
344
|
return { contentParts, aggregateContent, stepMap };
|
|
345
345
|
}
|
|
346
346
|
|
|
347
|
-
export { ChatModelStreamHandler, createContentAggregator, handleToolCalls };
|
|
347
|
+
export { ChatModelStreamHandler, createContentAggregator, getMessageId, handleToolCalls };
|
|
348
348
|
//# sourceMappingURL=stream.mjs.map
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\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\nconst getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\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 (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): 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 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 (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\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 = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\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 (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\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 (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 message 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\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 name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\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('No run step or runId found for completed tool call event');\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\n return { contentParts, aggregateContent, stepMap };\n}\n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,oBAAA,MAAM,UAAU,GAAG,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;AAE5D,oBAAA,MAAM,WAAW,GAA4B;wBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;AAC5B,wBAAA,SAAS,EAAE;AACT,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;AAC9B,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;AAC9B,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF,CAAC;AAEF,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC5C,iBAAC,CAAC,CAAC;aACJ;SACF;AAAM,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C,CAAC;AAEjE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YAE9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;gBACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\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 const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\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 (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): 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 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 (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\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 = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\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 (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\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 (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 message 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\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 name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\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('No run step or runId found for completed tool call event');\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\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK,CAAC;SACd;KACF;AACD,IAAA,OAAO,SAAS,CAAC;AACnB,CAAC;AAEM,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACzD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAAgB,GAAG,SAAS,GAAG,SAAS,CAAC;KACjD;I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AAE,MAAM,EAAE,GAAG,IAA6C,CAAC;AAEjE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YAE9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;gBACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;"}
|
|
@@ -30,6 +30,6 @@ export declare class SplitStreamHandler {
|
|
|
30
30
|
dispatchRunStep: (stepId: string, stepDetails: t.StepDetails) => void;
|
|
31
31
|
dispatchMessageDelta: (stepId: string, delta: t.MessageDelta) => void;
|
|
32
32
|
dispatchReasoningDelta: (stepId: string, delta: t.ReasoningDelta) => void;
|
|
33
|
-
handleContent: (content: string,
|
|
33
|
+
handleContent: (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK) => void;
|
|
34
34
|
handle(chunk?: t.CustomChunk): void;
|
|
35
35
|
}
|
package/dist/types/stream.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { ToolCall } from '@langchain/core/messages/tool';
|
|
|
2
2
|
import type { Graph } from '@/graphs';
|
|
3
3
|
import type * as t from '@/types';
|
|
4
4
|
import { GraphEvents } from '@/common';
|
|
5
|
+
export declare const getMessageId: (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId?: boolean) => string | undefined;
|
|
5
6
|
export declare const handleToolCalls: (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph) => void;
|
|
6
7
|
export declare class ChatModelStreamHandler implements t.EventHandler {
|
|
7
8
|
handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void;
|
|
@@ -173,7 +173,11 @@ export type ReasoningDeltaUpdate = {
|
|
|
173
173
|
think: string;
|
|
174
174
|
};
|
|
175
175
|
export type ContentType = 'text' | 'image_url' | 'tool_call' | 'think' | string;
|
|
176
|
-
export type
|
|
176
|
+
export type ReasoningContentText = {
|
|
177
|
+
type: ContentTypes.THINK;
|
|
178
|
+
think: string;
|
|
179
|
+
};
|
|
180
|
+
export type MessageContentComplex = (ReasoningContentText | MessageContentText | MessageContentImageUrl | (Record<string, any> & {
|
|
177
181
|
type?: 'text' | 'image_url' | 'think' | string;
|
|
178
182
|
}) | (Record<string, any> & {
|
|
179
183
|
type?: never;
|
package/package.json
CHANGED
package/src/splitStream.test.ts
CHANGED
|
@@ -536,4 +536,95 @@ describe('SplitStreamHandler', () => {
|
|
|
536
536
|
// Verify no reasoning events were generated
|
|
537
537
|
expect(reasoningDeltaEvents.length).toBe(0);
|
|
538
538
|
});
|
|
539
|
+
|
|
540
|
+
it('should properly split content with think tags while maintaining context', async () => {
|
|
541
|
+
const runId = nanoid();
|
|
542
|
+
const messageDeltaEvents: t.MessageDeltaEvent[] = [];
|
|
543
|
+
const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
|
|
544
|
+
const runStepEvents: t.RunStep[] = [];
|
|
545
|
+
const { contentParts, aggregateContent } = createContentAggregator();
|
|
546
|
+
|
|
547
|
+
const streamHandler = new SplitStreamHandler({
|
|
548
|
+
runId,
|
|
549
|
+
blockThreshold: 20, // Small threshold to force splits
|
|
550
|
+
handlers: {
|
|
551
|
+
[GraphEvents.ON_MESSAGE_DELTA]: (event): void => {
|
|
552
|
+
messageDeltaEvents.push(event.data);
|
|
553
|
+
aggregateContent(event);
|
|
554
|
+
},
|
|
555
|
+
[GraphEvents.ON_REASONING_DELTA]: (event): void => {
|
|
556
|
+
reasoningDeltaEvents.push(event.data);
|
|
557
|
+
aggregateContent(event);
|
|
558
|
+
},
|
|
559
|
+
[GraphEvents.ON_RUN_STEP]: (event): void => {
|
|
560
|
+
runStepEvents.push(event.data);
|
|
561
|
+
aggregateContent(event);
|
|
562
|
+
},
|
|
563
|
+
},
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
const content = 'Here\'s some regular text. <think>Now I\'m thinking deeply about something important. This is a long thought that should be split into multiple parts. We want to ensure the splitting works correctly.</think> Back to regular text after thinking.';
|
|
567
|
+
|
|
568
|
+
const stream = createMockStream({
|
|
569
|
+
text: content,
|
|
570
|
+
streamRate: 5,
|
|
571
|
+
})();
|
|
572
|
+
|
|
573
|
+
for await (const chunk of stream) {
|
|
574
|
+
streamHandler.handle(chunk);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// Verify that multiple message blocks were created
|
|
578
|
+
expect(runStepEvents.length).toBeGreaterThan(2);
|
|
579
|
+
|
|
580
|
+
// Check that content before <think> was handled as regular text
|
|
581
|
+
expect(messageDeltaEvents.some(event =>
|
|
582
|
+
(event.delta.content?.[0] as t.MessageDeltaUpdate | undefined)?.text.includes('regular')
|
|
583
|
+
)).toBe(true);
|
|
584
|
+
|
|
585
|
+
// Verify that reasoning content was split into multiple parts
|
|
586
|
+
const reasoningParts = reasoningDeltaEvents
|
|
587
|
+
.map(event => (event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined)?.think)
|
|
588
|
+
.filter(Boolean);
|
|
589
|
+
expect(reasoningParts.length).toBeGreaterThan(1);
|
|
590
|
+
|
|
591
|
+
// Verify that the complete reasoning content is preserved when joined
|
|
592
|
+
const fullReasoningContent = reasoningParts.join('');
|
|
593
|
+
expect(fullReasoningContent).toContain('thinking');
|
|
594
|
+
expect(fullReasoningContent).toContain('should');
|
|
595
|
+
expect(fullReasoningContent).toContain('be');
|
|
596
|
+
expect(fullReasoningContent).toContain('split');
|
|
597
|
+
|
|
598
|
+
// Check that each reasoning part maintains proper think context
|
|
599
|
+
let seenThinkOpen = false;
|
|
600
|
+
let seenThinkClose = false;
|
|
601
|
+
reasoningParts.forEach(part => {
|
|
602
|
+
if (part == null) return;
|
|
603
|
+
if (part.includes('<think>')) {
|
|
604
|
+
seenThinkOpen = true;
|
|
605
|
+
}
|
|
606
|
+
if (part.includes('</think>')) {
|
|
607
|
+
seenThinkClose = true;
|
|
608
|
+
}
|
|
609
|
+
// Middle parts should be handled as reasoning even without explicit think tags
|
|
610
|
+
if (!part.includes('<think>') && !part.includes('</think>')) {
|
|
611
|
+
expect(reasoningDeltaEvents.some(event =>
|
|
612
|
+
(event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined)?.think === part
|
|
613
|
+
)).toBe(true);
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
expect(seenThinkOpen).toBe(true);
|
|
617
|
+
expect(seenThinkClose).toBe(true);
|
|
618
|
+
|
|
619
|
+
// Check that content after </think> was handled as regular text
|
|
620
|
+
expect(messageDeltaEvents.some(event =>
|
|
621
|
+
(event.delta.content?.[0] as t.MessageDeltaUpdate | undefined)?.text.includes('Back')
|
|
622
|
+
)).toBe(true);
|
|
623
|
+
|
|
624
|
+
const thinkingBlocks = contentParts.filter(part =>
|
|
625
|
+
part?.type === ContentTypes.THINK
|
|
626
|
+
);
|
|
627
|
+
expect(thinkingBlocks.length).toEqual(4);
|
|
628
|
+
expect((thinkingBlocks[0] as t.ReasoningContentText).think.startsWith('<think>')).toBeTruthy();
|
|
629
|
+
});
|
|
539
630
|
});
|
package/src/splitStream.ts
CHANGED
|
@@ -86,7 +86,7 @@ export class SplitStreamHandler {
|
|
|
86
86
|
};
|
|
87
87
|
this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });
|
|
88
88
|
};
|
|
89
|
-
handleContent = (content: string,
|
|
89
|
+
handleContent = (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {
|
|
90
90
|
let type = _type;
|
|
91
91
|
if (this.inThinkBlock && type === ContentTypes.TEXT) {
|
|
92
92
|
type = ContentTypes.THINK;
|
|
@@ -109,12 +109,7 @@ export class SplitStreamHandler {
|
|
|
109
109
|
});
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
|
|
113
|
-
this.inCodeBlock = !this.inCodeBlock;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
this.currentLength += content.length;
|
|
117
|
-
|
|
112
|
+
const stepId = this.currentStepId ?? '';
|
|
118
113
|
if (type === ContentTypes.THINK) {
|
|
119
114
|
this.dispatchReasoningDelta(stepId, {
|
|
120
115
|
content: [{
|
|
@@ -131,6 +126,7 @@ export class SplitStreamHandler {
|
|
|
131
126
|
});
|
|
132
127
|
}
|
|
133
128
|
|
|
129
|
+
this.currentLength += content.length;
|
|
134
130
|
if (this.inCodeBlock) {
|
|
135
131
|
return;
|
|
136
132
|
}
|
|
@@ -157,6 +153,10 @@ export class SplitStreamHandler {
|
|
|
157
153
|
return;
|
|
158
154
|
}
|
|
159
155
|
|
|
156
|
+
if (content.includes('```')) {
|
|
157
|
+
this.inCodeBlock = !this.inCodeBlock;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
160
|
if (content === '<think>' && !this.inCodeBlock) {
|
|
161
161
|
this.inThinkBlock = true;
|
|
162
162
|
} else if (this.lastToken === '</think>' && !this.inCodeBlock) {
|
|
@@ -179,15 +179,10 @@ export class SplitStreamHandler {
|
|
|
179
179
|
});
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
const stepId = this.currentStepId ?? '';
|
|
183
|
-
if (!stepId) {
|
|
184
|
-
return;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
182
|
if (reasoning_content) {
|
|
188
|
-
this.handleContent(reasoning_content,
|
|
183
|
+
this.handleContent(reasoning_content, ContentTypes.THINK);
|
|
189
184
|
} else {
|
|
190
|
-
this.handleContent(content,
|
|
185
|
+
this.handleContent(content, ContentTypes.TEXT);
|
|
191
186
|
}
|
|
192
187
|
}
|
|
193
188
|
}
|
package/src/stream.ts
CHANGED
|
@@ -15,7 +15,7 @@ function getNonEmptyValue(possibleValues: string[]): string | undefined {
|
|
|
15
15
|
return undefined;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {
|
|
18
|
+
export const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {
|
|
19
19
|
const messageId = graph.messageIdsByStepKey.get(stepKey);
|
|
20
20
|
if (messageId != null && messageId) {
|
|
21
21
|
return returnExistingId ? messageId : undefined;
|
package/src/types/stream.ts
CHANGED
|
@@ -210,8 +210,13 @@ export type ReasoningDeltaUpdate = { type: ContentTypes.THINK; think: string; };
|
|
|
210
210
|
|
|
211
211
|
export type ContentType = 'text' | 'image_url' | 'tool_call' | 'think' | string;
|
|
212
212
|
|
|
213
|
+
export type ReasoningContentText = {
|
|
214
|
+
type: ContentTypes.THINK;
|
|
215
|
+
think: string;
|
|
216
|
+
};
|
|
217
|
+
|
|
213
218
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
214
|
-
export type MessageContentComplex = (MessageContentText | MessageContentImageUrl | (Record<string, any> & {
|
|
219
|
+
export type MessageContentComplex = (ReasoningContentText | MessageContentText | MessageContentImageUrl | (Record<string, any> & {
|
|
215
220
|
type?: 'text' | 'image_url' | 'think' | string;
|
|
216
221
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
217
222
|
}) | (Record<string, any> & {
|