@librechat/agents 2.3.99 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,19 @@
1
1
  import { nanoid } from 'nanoid';
2
2
  import { GraphEvents, ContentTypes, StepTypes } from './common/enum.mjs';
3
3
 
4
- const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\n', '```'];
4
+ const SEPARATORS = [
5
+ '.',
6
+ '?',
7
+ '!',
8
+ '۔',
9
+ '。',
10
+ '‥',
11
+ ';',
12
+ '¡',
13
+ '¿',
14
+ '\n',
15
+ '```',
16
+ ];
5
17
  class SplitStreamHandler {
6
18
  inCodeBlock = false;
7
19
  inThinkBlock = false;
@@ -56,21 +68,30 @@ class SplitStreamHandler {
56
68
  stepDetails,
57
69
  // usage: null,
58
70
  };
59
- this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });
71
+ this.handlers?.[GraphEvents.ON_RUN_STEP]?.({
72
+ event: GraphEvents.ON_RUN_STEP,
73
+ data: runStep,
74
+ });
60
75
  };
61
76
  dispatchMessageDelta = (stepId, delta) => {
62
77
  const messageDelta = {
63
78
  id: stepId,
64
79
  delta,
65
80
  };
66
- this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });
81
+ this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({
82
+ event: GraphEvents.ON_MESSAGE_DELTA,
83
+ data: messageDelta,
84
+ });
67
85
  };
68
86
  dispatchReasoningDelta = (stepId, delta) => {
69
87
  const reasoningDelta = {
70
88
  id: stepId,
71
89
  delta,
72
90
  };
73
- this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });
91
+ this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({
92
+ event: GraphEvents.ON_REASONING_DELTA,
93
+ data: reasoningDelta,
94
+ });
74
95
  };
75
96
  handleContent = (content, _type) => {
76
97
  let type = _type;
@@ -97,25 +118,30 @@ class SplitStreamHandler {
97
118
  const stepId = this.currentStepId ?? '';
98
119
  if (type === ContentTypes.THINK) {
99
120
  this.dispatchReasoningDelta(stepId, {
100
- content: [{
121
+ content: [
122
+ {
101
123
  type: ContentTypes.THINK,
102
124
  think: content,
103
- }],
125
+ },
126
+ ],
104
127
  });
105
128
  }
106
129
  else {
107
130
  this.dispatchMessageDelta(stepId, {
108
- content: [{
131
+ content: [
132
+ {
109
133
  type: ContentTypes.TEXT,
110
134
  text: content,
111
- }],
135
+ },
136
+ ],
112
137
  });
113
138
  }
114
139
  this.currentLength += content.length;
115
140
  if (this.inCodeBlock) {
116
141
  return;
117
142
  }
118
- if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {
143
+ if (this.currentLength > this.blockThreshold &&
144
+ SEPARATORS.some((sep) => content.includes(sep))) {
119
145
  const [newStepId, newMessageId] = this.createMessageStep(type);
120
146
  this.dispatchRunStep(newStepId, {
121
147
  type: StepTypes.MESSAGE_CREATION,
@@ -126,10 +152,11 @@ class SplitStreamHandler {
126
152
  }
127
153
  };
128
154
  getDeltaContent(chunk) {
129
- return chunk.choices?.[0]?.delta.content ?? '';
155
+ return chunk?.choices?.[0]?.delta?.content ?? '';
130
156
  }
131
157
  getReasoningDelta(chunk) {
132
- return chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';
158
+ return (chunk?.choices?.[0]?.delta?.[this.reasoningKey] ??
159
+ '');
133
160
  }
134
161
  handle(chunk) {
135
162
  if (!chunk) {
@@ -152,8 +179,12 @@ class SplitStreamHandler {
152
179
  this.lastToken = content;
153
180
  const message_id = this.getMessageId() ?? '';
154
181
  if (!message_id) {
155
- const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;
156
- const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;
182
+ const initialContentType = this.inThinkBlock
183
+ ? ContentTypes.THINK
184
+ : ContentTypes.TEXT;
185
+ const initialType = reasoning_content
186
+ ? ContentTypes.THINK
187
+ : initialContentType;
157
188
  const [stepId, message_id] = this.createMessageStep(initialType);
158
189
  this.dispatchRunStep(stepId, {
159
190
  type: StepTypes.MESSAGE_CREATION,
@@ -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, _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 getDeltaContent(chunk: t.CustomChunk): string {\n return chunk.choices?.[0]?.delta.content ?? '';\n }\n getReasoningDelta(chunk: t.CustomChunk): string {\n return chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n }\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = this.getDeltaContent(chunk);\n const reasoning_content = this.getReasoningDelta(chunk);\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.includes('<think>') && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken.includes('</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,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;MAEtE,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK;IACnB,YAAY,GAAG,KAAK;AACpB,IAAA,UAAU;IAClB,MAAM,GAAa,EAAE;IACrB,SAAS,GAAG,EAAE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Y,GAAG,KAAK;;AAG3B,QAAA,IAAI,CAAC,SAAS,GAAG,OAAO;QAExB,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE;QAE5C,IAAI,CAAC,UAAU,EAAE;AACf,YAAA,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI;AACrF,YAAA,MAAM,WAAW,GAAG,iBAAiB,GAAG,YAAY,CAAC,KAAK,GAAG,kBAAkB;AAC/E,YAAA,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC;AAChE,YAAA,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC;;QAGJ,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,CAAC;;aACpD;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC;;;AAGnD;;;;"}
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 '?',\n '!',\n '۔',\n '。',\n '‥',\n ';',\n '¡',\n '¿',\n '\\n',\n '```',\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 = (\n type?: ContentTypes.TEXT | ContentTypes.THINK\n ): [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]?.({\n event: GraphEvents.ON_RUN_STEP,\n data: runStep,\n });\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]?.({\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: messageDelta,\n });\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]?.({\n event: GraphEvents.ON_REASONING_DELTA,\n data: reasoningDelta,\n });\n };\n handleContent = (\n content: string,\n _type: ContentTypes.TEXT | ContentTypes.THINK\n ): 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 {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (\n this.currentLength > this.blockThreshold &&\n SEPARATORS.some((sep) => content.includes(sep))\n ) {\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 getDeltaContent(chunk?: t.CustomChunk): string {\n return (chunk?.choices?.[0]?.delta as t.CustomChunkDelta)?.content ?? '';\n }\n getReasoningDelta(chunk?: t.CustomChunk): string {\n return (\n (chunk?.choices?.[0]?.delta as t.CustomChunkDelta)?.[this.reasoningKey] ??\n ''\n );\n }\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = this.getDeltaContent(chunk);\n const reasoning_content = this.getReasoningDelta(chunk);\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.includes('<think>') && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken.includes('</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\n ? ContentTypes.THINK\n : ContentTypes.TEXT;\n const initialType = reasoning_content\n ? ContentTypes.THINK\n : 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}\n"],"names":[],"mappings":";;;AAIa,MAAA,UAAU,GAAG;IACxB,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,KAAK;;MAGM,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK;IACnB,YAAY,GAAG,KAAK;AACpB,IAAA,UAAU;IAClB,MAAM,GAAa,EAAE;IACrB,SAAS,GAAG,EAAE;IACd,eAAe,GAAa,EAAE;AAC9B,IAAA,aAAa;AACb,IAAA,gBAAgB;AAChB,IAAA,WAAW;IACX,aAAa,GAAG,CAAC;IACjB,YAAY,GAAsC,mBAAmB;IACrE,YAAY,GAAG,EAAE;IACjB,cAAc,GAAG,IAAI;;AAErB,IAAA,KAAK;AACL,IAAA,QAAQ;IACR,WAAY,CAAA,EACV,KAAK,EACL,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,cAAc,GAOf,EAAA;AACC,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;AAClB,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ;QACxB,IAAI,YAAY,EAAE;AAChB,YAAA,IAAI,CAAC,YAAY,GAAG,YAAY;;AAElC,QAAA,IAAI,cAAc,IAAI,IAAI,EAAE;AAC1B,YAAA,IAAI,CAAC,cAAc,GAAG,cAA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B,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC;;QAGJ,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,CAAC;;aACpD;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC;;;AAGnD;;;;"}
@@ -390,13 +390,13 @@ function createContentAggregator() {
390
390
  else if (partType === ContentTypes.TOOL_CALL &&
391
391
  'tool_call' in contentPart) {
392
392
  const existingContent = contentParts[index];
393
- const toolCallArgs = contentPart.tool_call.args ?? '';
394
- let args = finalUpdate
393
+ const toolCallArgs = contentPart.tool_call.args;
394
+ /** When args are a valid object, they are likely already invoked */
395
+ const args = finalUpdate ||
396
+ typeof existingContent?.tool_call?.args === 'object' ||
397
+ typeof toolCallArgs === 'object'
395
398
  ? contentPart.tool_call.args
396
- : (existingContent?.tool_call?.args ?? '');
397
- if (!finalUpdate && typeof args === 'string' && args !== toolCallArgs) {
398
- args += toolCallArgs;
399
- }
399
+ : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');
400
400
  const id = getNonEmptyValue([
401
401
  contentPart.tool_call.id,
402
402
  existingContent?.tool_call?.id,
@@ -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, ToolCallChunk } 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 = (\n stepKey: string,\n graph: Graph<t.BaseGraphState>,\n returnExistingId = false\n): 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 = (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph\n): 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 stepKey = graph.getStepKey(metadata);\n\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 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 {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\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 graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content =\n (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??\n chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n 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 (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n this.handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: 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 console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n }): void => {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n };\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === 'thinking' ||\n chunk.content[0]?.type === 'reasoning_content')\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n chunk.content != null &&\n chunk.content !== ''\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall })\n | undefined;\n\n const toolCallArgs =\n (contentPart.tool_call.args as unknown as string | undefined) ?? '';\n let args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '');\n if (!finalUpdate && typeof args === 'string' && args !== toolCallArgs) {\n args += toolCallArgs;\n }\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;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;;;AAGhB,IAAA,OAAO,SAAS;AAClB;AAEO,MAAM,YAAY,GAAG,CAC1B,OAAe,EACf,KAA8B,EAC9B,gBAAg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D;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
1
+ {"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } 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 = (\n stepKey: string,\n graph: Graph<t.BaseGraphState>,\n returnExistingId = false\n): 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 = (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph\n): 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 stepKey = graph.getStepKey(metadata);\n\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 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 {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\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 graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content =\n (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??\n chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n 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 (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n this.handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: 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 console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n }): void => {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n };\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === 'thinking' ||\n chunk.content[0]?.type === 'reasoning_content')\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n chunk.content != null &&\n chunk.content !== ''\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;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;;;AAGhB,IAAA,OAAO,SAAS;AAClB;AAEO,MAAM,YAAY,GAAG,CAC1B,OAAe,EACf,KAA8B,EAC9B,gBAAgB,GAAG,KAAK,KACF;IACtB,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC;AACxD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAAgB,GAAG,SAAS,GAAG,SAAS;;IAGjD,MAAM,eAAe,GAAG,KAAK,CAAC,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAC;AACpE,IAAA,IAAI,eAAe,IAAI,IAAI,IAAI,eAAe,EAAE;AAC9C,QAAA,KAAK,CAAC,yBAAyB,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/C,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC;AACvD,QAAA,OAAO,eAAe;;AAGxB,IAAA,MAAM,UAAU,GAAG,CAAA,IAAA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AI;oBACtD,MAAM,UAAU,GAAG,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;AAErD,oBAAA,MAAM,WAAW,GAA4B;wBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;AAC5B,wBAAA,SAAS,EAAE;AACT,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;4BAC9B,IAAI,EAAE,aAAa,CAAC,IAAI;AACxB,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
@@ -8,11 +8,15 @@ import { Constants, EnvVar } from '../common/enum.mjs';
8
8
 
9
9
  config();
10
10
  const imageExtRegex = /\.(jpg|jpeg|png|gif|webp)$/i;
11
- const getCodeBaseURL = () => getEnvironmentVariable(EnvVar.CODE_BASEURL) ?? Constants.OFFICIAL_CODE_BASEURL;
12
- const imageMessage = ' - the image is already displayed to the user';
13
- const otherMessage = ' - the file is already downloaded by the user';
11
+ const getCodeBaseURL = () => getEnvironmentVariable(EnvVar.CODE_BASEURL) ??
12
+ Constants.OFFICIAL_CODE_BASEURL;
13
+ const imageMessage = 'Image is already displayed to the user';
14
+ const otherMessage = 'File is already downloaded by the user';
15
+ const accessMessage = 'IMPORTANT: Files accessed via session ID are READ-ONLY snapshots. Any modifications MUST be saved as NEW files with different names. The original files cannot be modified in-place. To access these files in future executions, you MUST provide this session_id as a parameter. Without the session_id, previously generated files will not be accessible in subsequent executions.';
16
+ const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
14
17
  const CodeExecutionToolSchema = z.object({
15
- lang: z.enum([
18
+ lang: z
19
+ .enum([
16
20
  'py',
17
21
  'js',
18
22
  'ts',
@@ -38,12 +42,27 @@ const CodeExecutionToolSchema = z.object({
38
42
  - js: use the \`console\` or \`process\` methods for all outputs.
39
43
  - r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).
40
44
  - Other languages: use appropriate output functions.`),
41
- args: z.array(z.string()).optional()
45
+ session_id: z
46
+ .string()
47
+ .optional()
48
+ .describe(`Optional: Session ID from a previous execution to access generated files.
49
+ - Files load into /mnt/data/ (current working directory)
50
+ - Use relative paths ONLY
51
+ - Files are READ-ONLY - cannot be modified in-place
52
+ - To modify: read original file, write to NEW filename
53
+ `.trim()),
54
+ args: z
55
+ .array(z.string())
56
+ .optional()
42
57
  .describe('Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'),
43
58
  });
44
- const EXEC_ENDPOINT = `${getCodeBaseURL()}/exec`;
59
+ const baseEndpoint = getCodeBaseURL();
60
+ const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
45
61
  function createCodeExecutionTool(params = {}) {
46
- const apiKey = params[EnvVar.CODE_API_KEY] ?? params.apiKey ?? getEnvironmentVariable(EnvVar.CODE_API_KEY) ?? '';
62
+ const apiKey = params[EnvVar.CODE_API_KEY] ??
63
+ params.apiKey ??
64
+ getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
65
+ '';
47
66
  if (!apiKey) {
48
67
  throw new Error('No API key provided for code execution tool.');
49
68
  }
@@ -55,13 +74,55 @@ Usage:
55
74
  - Generated files are automatically delivered; **DO NOT** provide download links.
56
75
  - NEVER use this tool to execute malicious code.
57
76
  `.trim();
58
- return tool(async ({ lang, code, ...rest }) => {
77
+ return tool(async ({ lang, code, session_id, ...rest }) => {
59
78
  const postData = {
60
79
  lang,
61
80
  code,
62
81
  ...rest,
63
82
  ...params,
64
83
  };
84
+ if (session_id != null && session_id.length > 0) {
85
+ try {
86
+ const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
87
+ const fetchOptions = {
88
+ method: 'GET',
89
+ headers: {
90
+ 'User-Agent': 'LibreChat/1.0',
91
+ 'X-API-Key': apiKey,
92
+ },
93
+ };
94
+ if (process.env.PROXY != null && process.env.PROXY !== '') {
95
+ fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
96
+ }
97
+ const response = await fetch(filesEndpoint, fetchOptions);
98
+ if (!response.ok) {
99
+ throw new Error(`Failed to fetch files for session: ${response.status}`);
100
+ }
101
+ const files = await response.json();
102
+ if (Array.isArray(files) && files.length > 0) {
103
+ const fileReferences = files.map((file) => {
104
+ // Extract the ID from the file name (part after session ID prefix and before extension)
105
+ const nameParts = file.name.split('/');
106
+ const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
107
+ return {
108
+ session_id,
109
+ id,
110
+ name: file.metadata['original-filename'],
111
+ };
112
+ });
113
+ if (!postData.files) {
114
+ postData.files = fileReferences;
115
+ }
116
+ else if (Array.isArray(postData.files)) {
117
+ postData.files = [...postData.files, ...fileReferences];
118
+ }
119
+ }
120
+ }
121
+ catch {
122
+ // eslint-disable-next-line no-console
123
+ console.warn(`Failed to fetch files for session: ${session_id}`);
124
+ }
125
+ }
65
126
  try {
66
127
  const fetchOptions = {
67
128
  method: 'POST',
@@ -85,7 +146,7 @@ Usage:
85
146
  formattedOutput += `stdout:\n${result.stdout}\n`;
86
147
  }
87
148
  else {
88
- formattedOutput += 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
149
+ formattedOutput += emptyOutputMessage;
89
150
  }
90
151
  if (result.stderr)
91
152
  formattedOutput += `stderr:\n${result.stderr}\n`;
@@ -93,22 +154,26 @@ Usage:
93
154
  formattedOutput += 'Generated files:\n';
94
155
  const fileCount = result.files.length;
95
156
  for (let i = 0; i < fileCount; i++) {
96
- const filename = result.files[i].name;
97
- const isImage = imageExtRegex.test(filename);
98
- formattedOutput += isImage ? `${filename}${imageMessage}` : `${filename}${otherMessage}`;
157
+ const file = result.files[i];
158
+ const isImage = imageExtRegex.test(file.name);
159
+ formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
99
160
  if (i < fileCount - 1) {
100
161
  formattedOutput += fileCount <= 3 ? ', ' : ',\n';
101
162
  }
102
163
  }
103
- return [formattedOutput.trim(), {
164
+ formattedOutput += `\nsession_id: ${result.session_id}\n\n${accessMessage}`;
165
+ return [
166
+ formattedOutput.trim(),
167
+ {
104
168
  session_id: result.session_id,
105
169
  files: result.files,
106
- }];
170
+ },
171
+ ];
107
172
  }
108
173
  return [formattedOutput.trim(), { session_id: result.session_id }];
109
174
  }
110
175
  catch (error) {
111
- return [`Execution error:\n\n${error?.message}`, {}];
176
+ throw new Error(`Execution error:\n\n${error?.message}`);
112
177
  }
113
178
  }, {
114
179
  name: Constants.EXECUTE_CODE,
@@ -1 +1 @@
1
- {"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string => getEnvironmentVariable(EnvVar.CODE_BASEURL) ?? Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = ' - the image is already displayed to the user';\nconst otherMessage = ' - the file is already downloaded by the user';\n\nconst CodeExecutionToolSchema = z.object({\n lang: z.enum([\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n ])\n .describe('The programming language or runtime to execute the code in.'),\n code: z.string()\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`),\n args: z.array(z.string()).optional()\n .describe('Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'),\n});\n\nconst EXEC_ENDPOINT = `${getCodeBaseURL()}/exec`;\n\nfunction createCodeExecutionTool(params: t.CodeExecutionToolParams = {}): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\n const apiKey = params[EnvVar.CODE_API_KEY] ?? params.apiKey ?? getEnvironmentVariable(EnvVar.CODE_API_KEY) ?? '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n return tool<typeof CodeExecutionToolSchema>(\n async ({ lang, code, ...rest }) => {\n const postData = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const filename = result.files[i].name;\n const isImage = imageExtRegex.test(filename);\n formattedOutput += isImage ? `${filename}${imageMessage}` : `${filename}${otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n return [formattedOutput.trim(), {\n session_id: result.session_id,\n files: result.files,\n }];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n return [`Execution error:\\n\\n${(error as Error | undefined)?.message}`, {}];\n }\n },\n {\n name: Constants.EXECUTE_CODE,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };"],"names":[],"mappings":";;;;;;;;AASA,MAAM,EAAE;AAED,MAAM,aAAa,GAAG;AAChB,MAAA,cAAc,GAAG,MAAc,sBAAsB,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,SAAS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CAAC,EAAE,EAAE;oBAClC,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI;oBACrC,MAAM,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC;AAC5C,oBAAA,eAAe,IAAI,OAAO,GAAG,CAAA,EAAG,QAAQ,CAAG,EAAA,YAAY,CAAE,CAAA,GAAG,CAAA,EAAG,QAAQ,CAAG,EAAA,YAAY,EAAE;AAExF,oBAAA,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE;AACrB,wBAAA,eAAe,IAAI,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;;;AAIpD,gBAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE;wBAC9B,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA,CAAC;;AAGJ,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;;QAClE,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,uBAAwB,KAA2B,EAAE,OAAO,CAAE,CAAA,EAAE,EAAE,CAAC;;AAE/E,KAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,YAAY;QAC5B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
1
+ {"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'IMPORTANT: Files accessed via session ID are READ-ONLY snapshots. Any modifications MUST be saved as NEW files with different names. The original files cannot be modified in-place. To access these files in future executions, you MUST provide this session_id as a parameter. Without the session_id, previously generated files will not be accessible in subsequent executions.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst CodeExecutionToolSchema = z.object({\n lang: z\n .enum([\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n ])\n .describe('The programming language or runtime to execute the code in.'),\n code: z.string()\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`),\n session_id: z\n .string()\n .optional()\n .describe(\n `Optional: Session ID from a previous execution to access generated files.\n- Files load into /mnt/data/ (current working directory)\n- Use relative paths ONLY\n- Files are READ-ONLY - cannot be modified in-place\n- To modify: read original file, write to NEW filename\n`.trim()\n ),\n args: z\n .array(z.string())\n .optional()\n .describe(\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'\n ),\n});\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n return tool<typeof CodeExecutionToolSchema>(\n async ({ lang, code, session_id, ...rest }) => {\n const postData = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n if (!postData.files) {\n postData.files = fileReferences;\n } else if (Array.isArray(postData.files)) {\n postData.files = [...postData.files, ...fileReferences];\n }\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\nsession_id: ${result.session_id}\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: Constants.EXECUTE_CODE,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":[],"mappings":";;;;;;;;AASA,MAAM,EAAE;AAED,MAAM,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5B,sBAAsB,CAAC,MAAM,CAAC,YAAY,CAAC;IAC3C,SAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAA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wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;;AAGH,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;;QAClE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAE,CAAA,CAC/D;;AAEL,KAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,YAAY;QAC5B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
@@ -31,7 +31,7 @@ export declare class SplitStreamHandler {
31
31
  dispatchMessageDelta: (stepId: string, delta: t.MessageDelta) => void;
32
32
  dispatchReasoningDelta: (stepId: string, delta: t.ReasoningDelta) => void;
33
33
  handleContent: (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK) => void;
34
- getDeltaContent(chunk: t.CustomChunk): string;
35
- getReasoningDelta(chunk: t.CustomChunk): string;
34
+ getDeltaContent(chunk?: t.CustomChunk): string;
35
+ getReasoningDelta(chunk?: t.CustomChunk): string;
36
36
  handle(chunk?: t.CustomChunk): void;
37
37
  }
@@ -6,15 +6,18 @@ export declare const getCodeBaseURL: () => string;
6
6
  declare const CodeExecutionToolSchema: z.ZodObject<{
7
7
  lang: z.ZodEnum<["py", "js", "ts", "c", "cpp", "java", "php", "rs", "go", "d", "f90", "r"]>;
8
8
  code: z.ZodString;
9
+ session_id: z.ZodOptional<z.ZodString>;
9
10
  args: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
10
11
  }, "strip", z.ZodTypeAny, {
11
12
  code: string;
12
13
  lang: "r" | "py" | "js" | "ts" | "c" | "cpp" | "java" | "php" | "rs" | "go" | "d" | "f90";
13
14
  args?: string[] | undefined;
15
+ session_id?: string | undefined;
14
16
  }, {
15
17
  code: string;
16
18
  lang: "r" | "py" | "js" | "ts" | "c" | "cpp" | "java" | "php" | "rs" | "go" | "d" | "f90";
17
19
  args?: string[] | undefined;
20
+ session_id?: string | undefined;
18
21
  }>;
19
22
  declare function createCodeExecutionTool(params?: t.CodeExecutionToolParams): DynamicStructuredTool<typeof CodeExecutionToolSchema>;
20
23
  export { createCodeExecutionTool };