@librechat/agents 2.0.5 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +10 -0
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +34 -5
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/llm.cjs +1 -3
- package/dist/cjs/llm/anthropic/llm.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/fake.cjs +55 -0
- package/dist/cjs/llm/fake.cjs.map +1 -0
- package/dist/cjs/llm/providers.cjs +7 -5
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/cjs/llm/text.cjs.map +1 -1
- package/dist/cjs/messages.cjs.map +1 -1
- package/dist/cjs/run.cjs +3 -7
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/splitStream.cjs.map +1 -1
- package/dist/cjs/stream.cjs +93 -55
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +8 -2
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/graph.cjs.map +1 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/misc.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/cjs/utils/title.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +10 -0
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +35 -6
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/llm.mjs +1 -3
- package/dist/esm/llm/anthropic/llm.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/fake.mjs +52 -0
- package/dist/esm/llm/fake.mjs.map +1 -0
- package/dist/esm/llm/providers.mjs +8 -6
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/esm/llm/text.mjs.map +1 -1
- package/dist/esm/messages.mjs.map +1 -1
- package/dist/esm/run.mjs +3 -7
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/splitStream.mjs.map +1 -1
- package/dist/esm/stream.mjs +94 -56
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +9 -3
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/graph.mjs.map +1 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/misc.mjs.map +1 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/esm/utils/title.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +2 -1
- package/dist/types/events.d.ts +4 -1
- package/dist/types/graphs/Graph.d.ts +9 -13
- package/dist/types/llm/fake.d.ts +21 -0
- package/dist/types/specs/spec.utils.d.ts +1 -0
- package/dist/types/stream.d.ts +9 -13
- package/dist/types/types/graph.d.ts +16 -0
- package/dist/types/types/llm.d.ts +10 -5
- package/dist/types/types/run.d.ts +4 -12
- package/dist/types/types/stream.d.ts +12 -0
- package/package.json +15 -26
- package/src/common/enum.ts +1 -0
- package/src/events.ts +13 -1
- package/src/graphs/Graph.ts +43 -21
- package/src/llm/fake.ts +83 -0
- package/src/llm/providers.ts +7 -5
- package/src/run.ts +3 -7
- package/src/scripts/simple.ts +28 -14
- package/src/specs/anthropic.simple.test.ts +204 -0
- package/src/specs/openai.simple.test.ts +204 -0
- package/src/specs/reasoning.test.ts +165 -0
- package/src/specs/spec.utils.ts +3 -0
- package/src/stream.ts +100 -72
- package/src/tools/CodeExecutor.ts +8 -2
- package/src/types/graph.ts +18 -1
- package/src/types/llm.ts +10 -5
- package/src/types/run.ts +5 -13
- package/src/types/stream.ts +14 -1
- package/src/utils/llmConfig.ts +7 -1
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\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 graph.messageStepHasToolCalls.set(prevStepId, true);\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 graph.messageStepHasToolCalls.set(prevStepId, true);\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 /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of chunk.tool_call_chunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {\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 = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === chunk.tool_call_chunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\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: 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 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('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;IAED,MAAM,eAAe,GAAG,KAAK,CAAC,yB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AE,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,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, 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 = (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 graph.messageStepHasToolCalls.set(prevStepId, true);\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 graph.messageStepHasToolCalls.set(prevStepId, true);\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 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 = (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ?? chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\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 hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\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 this.handleToolCallChunks({ graph, stepKey, toolCallChunks: chunk.tool_call_chunks });\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 if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n }\n } else if (content.every((c) => c.type?.startsWith(ContentTypes.TEXT))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[],\n }): void => {\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 /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\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 (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {\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 = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\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 const reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined;\n if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (graph.tokenTypeSwitch === 'reasoning' && graph.currentTokenType !== ContentTypes.TEXT && chunk.content != null && chunk.content !== '') {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (chunk.content != null && typeof chunk.content === 'string' && chunk.content.includes('<think>')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (graph.lastToken != null && graph.lastToken.includes('</think>')) {\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 (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 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\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('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;;;AAGhB,IAAA,OAAO,SAAS;AAClB;AAEO,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,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E,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,CAAC,0DAA0D,CAAC;gBACxE;;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;;AAGnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { config } from 'dotenv';
|
|
3
|
+
import fetch from 'node-fetch';
|
|
4
|
+
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
3
5
|
import { tool } from '@langchain/core/tools';
|
|
4
6
|
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
5
|
-
import {
|
|
7
|
+
import { Constants, EnvVar } from '../common/enum.mjs';
|
|
6
8
|
|
|
7
9
|
config();
|
|
8
10
|
const imageExtRegex = /\.(jpg|jpeg|png|gif|webp)$/i;
|
|
@@ -61,7 +63,7 @@ Usage:
|
|
|
61
63
|
...params,
|
|
62
64
|
};
|
|
63
65
|
try {
|
|
64
|
-
const
|
|
66
|
+
const fetchOptions = {
|
|
65
67
|
method: 'POST',
|
|
66
68
|
headers: {
|
|
67
69
|
'Content-Type': 'application/json',
|
|
@@ -69,7 +71,11 @@ Usage:
|
|
|
69
71
|
'X-API-Key': apiKey,
|
|
70
72
|
},
|
|
71
73
|
body: JSON.stringify(postData),
|
|
72
|
-
}
|
|
74
|
+
};
|
|
75
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
76
|
+
fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
|
|
77
|
+
}
|
|
78
|
+
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
73
79
|
if (!response.ok) {
|
|
74
80
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
75
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\nimport { config } from 'dotenv';\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
|
|
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,CAAC;AAErG,MAAM,YAAY,GAAG,+CAA+C;AACpE,MAAM,YAAY,GAAG,+CAA+C;AAEpE,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;AACvC,IAAA,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC;QACX,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,GAAG;QACH,KAAK;QACL,MAAM;QACN,KAAK;QACL,IAAI;QACJ,IAAI;QACJ,GAAG;QACH,KAAK;QACL,GAAG;KACJ;SACE,QAAQ,CAAC,6DAA6D,CAAC;AAC1E,IA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AAA,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { END, MessagesAnnotation, isCommand, isGraphInterrupt } from '@langchain/langgraph';\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\nimport type { RunnableConfig, RunnableToolLike } from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport{ RunnableCallable } from '@/utils';\nimport { GraphNodeKeys } from '@/common';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n toolCallStepIds?: Map<string, string>;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n const message = Array.isArray(input)\n ? input[input.length - 1]\n : input.messages[input.messages.length - 1];\n\n if (message._getType() !== 'ai') {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n (message as AIMessage).tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n }\n const outputs = await Promise.all(\n (message as AIMessage).tool_calls?.map(async (call) => {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId },\n config,\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n name: tool.name,\n content:\n typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n return new ToolMessage({\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }) ?? []\n );\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs = outputs.map((output) => {\n if (isCommand(output)) {\n return output;\n }\n return Array.isArray(input) ? [output] : { messages: [output] };\n });\n return combinedOutputs as T;\n }\n}\n\nexport function toolsCondition(\n state: BaseMessage[] | typeof MessagesAnnotation.State\n): 'tools' | typeof END {\n const message = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n return GraphNodeKeys.TOOLS;\n } else {\n return END;\n }\n}"],"names":[],"mappings":";;;;;AASA;AACM,MAAO,QAAkB,SAAQ,gBAAsB,CAAA;AAC3D,IAAA,KAAK
|
|
1
|
+
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { END, MessagesAnnotation, isCommand, isGraphInterrupt } from '@langchain/langgraph';\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\nimport type { RunnableConfig, RunnableToolLike } from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport{ RunnableCallable } from '@/utils';\nimport { GraphNodeKeys } from '@/common';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n toolCallStepIds?: Map<string, string>;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n const message = Array.isArray(input)\n ? input[input.length - 1]\n : input.messages[input.messages.length - 1];\n\n if (message._getType() !== 'ai') {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n (message as AIMessage).tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n }\n const outputs = await Promise.all(\n (message as AIMessage).tool_calls?.map(async (call) => {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId },\n config,\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n name: tool.name,\n content:\n typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n return new ToolMessage({\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }) ?? []\n );\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs = outputs.map((output) => {\n if (isCommand(output)) {\n return output;\n }\n return Array.isArray(input) ? [output] : { messages: [output] };\n });\n return combinedOutputs as T;\n }\n}\n\nexport function toolsCondition(\n state: BaseMessage[] | typeof MessagesAnnotation.State\n): 'tools' | typeof END {\n const message = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n return GraphNodeKeys.TOOLS;\n } else {\n return END;\n }\n}"],"names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AC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,YAAY,IAAI,OAAO;QACvB,CAAE,OAAqB,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC,EACpD;QACA,OAAO,aAAa,CAAC,KAAK;;SACrB;AACL,QAAA,OAAO,GAAG;;AAEd;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.mjs","sources":["../../../src/utils/graph.ts"],"sourcesContent":["export const resetIfNotEmpty = <T>(value: T, resetValue: T): T => {\n if (Array.isArray(value)) {\n return value.length > 0 ? resetValue : value;\n }\n if (value instanceof Set || value instanceof Map) {\n return value.size > 0 ? resetValue : value;\n }\n return value !== undefined ? resetValue : value;\n};\n\nexport const joinKeys = (args: (string | number | undefined)[]): string => args.join('_');"],"names":[],"mappings":"MAAa,eAAe,GAAG,CAAI,KAAQ,EAAE,UAAa,KAAO;AAC/D,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,QAAA,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,UAAU,GAAG,KAAK,
|
|
1
|
+
{"version":3,"file":"graph.mjs","sources":["../../../src/utils/graph.ts"],"sourcesContent":["export const resetIfNotEmpty = <T>(value: T, resetValue: T): T => {\n if (Array.isArray(value)) {\n return value.length > 0 ? resetValue : value;\n }\n if (value instanceof Set || value instanceof Map) {\n return value.size > 0 ? resetValue : value;\n }\n return value !== undefined ? resetValue : value;\n};\n\nexport const joinKeys = (args: (string | number | undefined)[]): string => args.join('_');"],"names":[],"mappings":"MAAa,eAAe,GAAG,CAAI,KAAQ,EAAE,UAAa,KAAO;AAC/D,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,QAAA,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,UAAU,GAAG,KAAK;;IAE9C,IAAI,KAAK,YAAY,GAAG,IAAI,KAAK,YAAY,GAAG,EAAE;AAChD,QAAA,OAAO,KAAK,CAAC,IAAI,GAAG,CAAC,GAAG,UAAU,GAAG,KAAK;;IAE5C,OAAO,KAAK,KAAK,SAAS,GAAG,UAAU,GAAG,KAAK;AACjD;AAEO,MAAM,QAAQ,GAAG,CAAC,IAAqC,KAAa,IAAI,CAAC,IAAI,CAAC,GAAG;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llm.mjs","sources":["../../../src/utils/llm.ts"],"sourcesContent":["// src/utils/llm.ts\nimport { Providers } from '@/common';\n\nexport function isOpenAILike(provider?: string | Providers): boolean {\n if (provider == null) {\n return false;\n }\n return ([Providers.OPENAI, Providers.AZURE] as string[]).includes(provider);\n}\n\nexport function isGoogleLike(provider?: string | Providers): boolean {\n if (provider == null) {\n return false;\n }\n return ([Providers.GOOGLE, Providers.VERTEXAI] as string[]).includes(provider);\n}"],"names":[],"mappings":";;AAAA;AAGM,SAAU,YAAY,CAAC,QAA6B,EAAA;AACxD,IAAA,IAAI,QAAQ,IAAI,IAAI,EAAE;AACpB,QAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"llm.mjs","sources":["../../../src/utils/llm.ts"],"sourcesContent":["// src/utils/llm.ts\nimport { Providers } from '@/common';\n\nexport function isOpenAILike(provider?: string | Providers): boolean {\n if (provider == null) {\n return false;\n }\n return ([Providers.OPENAI, Providers.AZURE] as string[]).includes(provider);\n}\n\nexport function isGoogleLike(provider?: string | Providers): boolean {\n if (provider == null) {\n return false;\n }\n return ([Providers.GOOGLE, Providers.VERTEXAI] as string[]).includes(provider);\n}"],"names":[],"mappings":";;AAAA;AAGM,SAAU,YAAY,CAAC,QAA6B,EAAA;AACxD,IAAA,IAAI,QAAQ,IAAI,IAAI,EAAE;AACpB,QAAA,OAAO,KAAK;;AAEd,IAAA,OAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,CAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;AAC7E;AAEM,SAAU,YAAY,CAAC,QAA6B,EAAA;AACxD,IAAA,IAAI,QAAQ,IAAI,IAAI,EAAE;AACpB,QAAA,OAAO,KAAK;;AAEd,IAAA,OAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,QAAQ,CAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;AAChF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"misc.mjs","sources":["../../../src/utils/misc.ts"],"sourcesContent":["/**\n * Unescapes a c-escaped string\n * @param str The string to unescape\n * @returns The unescaped string\n */\nconst unescapeString = (string: string): string => string.replace(/\\\\(.)/g, (_, char) => {\n switch (char) {\n case 'n':\n return '\\n';\n case 't':\n return '\\t';\n case 'r':\n return '\\r';\n case '\"':\n return '\"';\n case '\\'':\n return '\\'';\n case '\\\\':\n return '\\\\';\n default:\n return char;\n }\n});\n\n/**\n * Recursively unescapes all string values in an object\n * @param obj The object to unescape\n * @returns The unescaped object\n */\nexport function unescapeObject(obj: unknown, key?: string): unknown {\n if (typeof obj === 'string') {\n let unescaped = unescapeString(obj);\n if (key === 'filePath' && unescaped.match(/^\"(.+)\"$/)) {\n unescaped = unescaped.substring(1, unescaped.length - 1);\n }\n return unescaped;\n }\n if (Array.isArray(obj)) {\n return obj.map((value) => unescapeObject(value, key === 'contextPaths' ? 'filePath' : ''));\n }\n if (typeof obj === 'object' && obj !== null) {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, unescapeObject(value, key)]));\n }\n return obj;\n}"],"names":[],"mappings":"AAAA;;;;AAIG;AACH,MAAM,cAAc,GAAG,CAAC,MAAc,KAAa,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,EAAE,IAAI,KAAI;IACtF,QAAQ,IAAI;AACZ,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,IAAI
|
|
1
|
+
{"version":3,"file":"misc.mjs","sources":["../../../src/utils/misc.ts"],"sourcesContent":["/**\n * Unescapes a c-escaped string\n * @param str The string to unescape\n * @returns The unescaped string\n */\nconst unescapeString = (string: string): string => string.replace(/\\\\(.)/g, (_, char) => {\n switch (char) {\n case 'n':\n return '\\n';\n case 't':\n return '\\t';\n case 'r':\n return '\\r';\n case '\"':\n return '\"';\n case '\\'':\n return '\\'';\n case '\\\\':\n return '\\\\';\n default:\n return char;\n }\n});\n\n/**\n * Recursively unescapes all string values in an object\n * @param obj The object to unescape\n * @returns The unescaped object\n */\nexport function unescapeObject(obj: unknown, key?: string): unknown {\n if (typeof obj === 'string') {\n let unescaped = unescapeString(obj);\n if (key === 'filePath' && unescaped.match(/^\"(.+)\"$/)) {\n unescaped = unescaped.substring(1, unescaped.length - 1);\n }\n return unescaped;\n }\n if (Array.isArray(obj)) {\n return obj.map((value) => unescapeObject(value, key === 'contextPaths' ? 'filePath' : ''));\n }\n if (typeof obj === 'object' && obj !== null) {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, unescapeObject(value, key)]));\n }\n return obj;\n}"],"names":[],"mappings":"AAAA;;;;AAIG;AACH,MAAM,cAAc,GAAG,CAAC,MAAc,KAAa,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,EAAE,IAAI,KAAI;IACtF,QAAQ,IAAI;AACZ,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,IAAI;AACb,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,IAAI;AACb,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,IAAI;AACb,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,GAAG;AACZ,QAAA,KAAK,IAAI;AACP,YAAA,OAAO,IAAI;AACb,QAAA,KAAK,IAAI;AACP,YAAA,OAAO,IAAI;AACb,QAAA;AACE,YAAA,OAAO,IAAI;;AAEf,CAAC,CAAC;AAEF;;;;AAIG;AACa,SAAA,cAAc,CAAC,GAAY,EAAE,GAAY,EAAA;AACvD,IAAA,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;AAC3B,QAAA,IAAI,SAAS,GAAG,cAAc,CAAC,GAAG,CAAC;QACnC,IAAI,GAAG,KAAK,UAAU,IAAI,SAAS,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE;AACrD,YAAA,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;;AAE1D,QAAA,OAAO,SAAS;;AAElB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QACtB,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,KAAK,cAAc,CAAC,KAAK,EAAE,GAAG,KAAK,cAAc,GAAG,UAAU,GAAG,EAAE,CAAC,CAAC;;IAE5F,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE;AAC3C,QAAA,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,cAAc,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;;AAEzG,IAAA,OAAO,GAAG;AACZ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.mjs","sources":["../../../src/utils/run.ts"],"sourcesContent":["import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';\nimport {\n mergeConfigs,\n patchConfig,\n Runnable,\n RunnableConfig,\n} from '@langchain/core/runnables';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\n\n/**\n * Delays the execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to delay.\n * @return {Promise<void>} A promise that resolves after the specified delay.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RunnableCallableArgs extends Partial<any> {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n tags?: string[];\n trace?: boolean;\n recurse?: boolean;\n}\n\nexport class RunnableCallable<I = unknown, O = unknown> extends Runnable<I, O> {\n lc_namespace: string[] = ['langgraph'];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n\n tags?: string[];\n\n config?: RunnableConfig;\n\n trace: boolean = true;\n\n recurse: boolean = true;\n\n constructor(fields: RunnableCallableArgs) {\n super();\n this.name = fields.name ?? fields.func.name;\n this.func = fields.func;\n this.config = fields.tags ? { tags: fields.tags } : undefined;\n this.trace = fields.trace ?? this.trace;\n this.recurse = fields.recurse ?? this.recurse;\n }\n\n protected async _tracedInvoke(\n input: I,\n config?: Partial<RunnableConfig>,\n runManager?: CallbackManagerForChainRun\n ): Promise<O> {\n return new Promise<O>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n childConfig,\n async () => {\n try {\n const output = await this.func(input, childConfig);\n resolve(output);\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n }\n\n async invoke(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n options?: Partial<RunnableConfig> | undefined\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnValue: any;\n\n if (this.trace) {\n returnValue = await this._callWithConfig(\n this._tracedInvoke,\n input,\n mergeConfigs(this.config, options)\n );\n } else {\n returnValue = await this.func(input, mergeConfigs(this.config, options));\n }\n\n if (Runnable.isRunnable(returnValue) && this.recurse) {\n return await returnValue.invoke(input, options);\n }\n\n return returnValue;\n }\n}"],"names":[],"mappings":";;;AASA;;;;;AAKG;AACG,SAAU,KAAK,CAAC,EAAU,EAAA;AAC9B,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC
|
|
1
|
+
{"version":3,"file":"run.mjs","sources":["../../../src/utils/run.ts"],"sourcesContent":["import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';\nimport {\n mergeConfigs,\n patchConfig,\n Runnable,\n RunnableConfig,\n} from '@langchain/core/runnables';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\n\n/**\n * Delays the execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to delay.\n * @return {Promise<void>} A promise that resolves after the specified delay.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RunnableCallableArgs extends Partial<any> {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n tags?: string[];\n trace?: boolean;\n recurse?: boolean;\n}\n\nexport class RunnableCallable<I = unknown, O = unknown> extends Runnable<I, O> {\n lc_namespace: string[] = ['langgraph'];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n\n tags?: string[];\n\n config?: RunnableConfig;\n\n trace: boolean = true;\n\n recurse: boolean = true;\n\n constructor(fields: RunnableCallableArgs) {\n super();\n this.name = fields.name ?? fields.func.name;\n this.func = fields.func;\n this.config = fields.tags ? { tags: fields.tags } : undefined;\n this.trace = fields.trace ?? this.trace;\n this.recurse = fields.recurse ?? this.recurse;\n }\n\n protected async _tracedInvoke(\n input: I,\n config?: Partial<RunnableConfig>,\n runManager?: CallbackManagerForChainRun\n ): Promise<O> {\n return new Promise<O>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n childConfig,\n async () => {\n try {\n const output = await this.func(input, childConfig);\n resolve(output);\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n }\n\n async invoke(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n options?: Partial<RunnableConfig> | undefined\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnValue: any;\n\n if (this.trace) {\n returnValue = await this._callWithConfig(\n this._tracedInvoke,\n input,\n mergeConfigs(this.config, options)\n );\n } else {\n returnValue = await this.func(input, mergeConfigs(this.config, options));\n }\n\n if (Runnable.isRunnable(returnValue) && this.recurse) {\n return await returnValue.invoke(input, options);\n }\n\n return returnValue;\n }\n}"],"names":[],"mappings":";;;AASA;;;;;AAKG;AACG,SAAU,KAAK,CAAC,EAAU,EAAA;AAC9B,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAC1D;AAYM,MAAO,gBAA2C,SAAQ,QAAc,CAAA;AAC5E,IAAA,YAAY,GAAa,CAAC,WAAW,CAAC;;AAGtC,IAAA,IAAI;AAEJ,IAAA,IAAI;AAEJ,IAAA,MAAM;IAEN,KAAK,GAAY,IAAI;IAErB,OAAO,GAAY,IAAI;AAEvB,IAAA,WAAA,CAAY,MAA4B,EAAA;AACtC,QAAA,KAAK,EAAE;AACP,QAAA,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI;AAC3C,QAAA,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,SAAS;QAC7D,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK;QACvC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO;;AAGrC,IAAA,MAAM,aAAa,CAC3B,KAAQ,EACR,MAAgC,EAChC,UAAuC,EAAA;QAEvC,OAAO,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,KAAI;AACxC,YAAA,MAAM,WAAW,GAAG,WAAW,CAAC,MAAM,EAAE;AACtC,gBAAA,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE;AAClC,aAAA,CAAC;YACF,KAAK,kCAAkC,CAAC,aAAa,CACnD,WAAW,EACX,YAAW;AACT,gBAAA,IAAI;oBACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC;oBAClD,OAAO,CAAC,MAAM,CAAC;;gBACf,OAAO,CAAC,EAAE;oBACV,MAAM,CAAC,CAAC,CAAC;;AAEb,aAAC,CACF;AACH,SAAC,CAAC;;AAGJ,IAAA,MAAM,MAAM;;AAEV,IAAA,KAAU,EACV;;;;AAIA,QAAA,IAAI,WAAgB;AAEpB,QAAA,IAAI,IAAI,CAAC,KAAK,EAAE;YACd,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CACtC,IAAI,CAAC,aAAa,EAClB,KAAK,EACL,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CACnC;;aACI;AACL,YAAA,WAAW,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;;QAG1E,IAAI,QAAQ,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACpD,OAAO,MAAM,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC;;AAGjD,QAAA,OAAO,WAAW;;AAErB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"title.mjs","sources":["../../../src/utils/title.ts"],"sourcesContent":["import { z } from 'zod';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type { Runnable } from '@langchain/core/runnables';\nimport * as t from '@/types';\n\nconst defaultTitlePrompt = `Write a concise title for this conversation in the detected language. Title in 5 Words or Less. No Punctuation or Quotation.\n{convo}`;\n\nconst languageInstructions = 'Detect the language used in the following text. Note: words may be misspelled or cut off; use context clues to identify the language:\\n{text}';\n\nconst languagePrompt = ChatPromptTemplate.fromTemplate(languageInstructions);\n\nconst languageSchema = z.object({\n language: z.string().describe('The detected language of the conversation')\n});\n\nconst titleSchema = z.object({\n title: z.string().describe('A concise title for the conversation in 5 words or less, without punctuation or quotation'),\n});\n\nexport const createTitleRunnable = async (model: t.ChatModelInstance, _titlePrompt?: string): Promise<Runnable> => {\n // Disabled since this works fine\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /* @ts-ignore */\n const languageLLM = model.withStructuredOutput(languageSchema);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /* @ts-ignore */\n const titleLLM = model.withStructuredOutput(titleSchema);\n\n const languageChain = languagePrompt.pipe(languageLLM);\n\n const titlePrompt = ChatPromptTemplate.fromTemplate(_titlePrompt ?? defaultTitlePrompt);\n\n return new RunnableLambda({\n func: async (input: { convo: string, inputText: string, skipLanguage: boolean }): Promise<{ language: string; title: string } | { title: string }> => {\n if (input.skipLanguage) {\n return await titlePrompt.pipe(titleLLM).invoke({\n convo: input.convo\n }) as { title: string };\n }\n const languageResult = await languageChain.invoke({ text: input.inputText }) as { language: string } | undefined;\n const language = languageResult?.language ?? 'English';\n const titleResult = await titlePrompt.pipe(titleLLM).invoke({\n language,\n convo: input.convo\n }) as { title: string } | undefined;\n return { language, title: titleResult?.title ?? '' };\n },\n });\n};"],"names":[],"mappings":";;;;AAMA,MAAM,kBAAkB,GAAG,CAAA;QACnB
|
|
1
|
+
{"version":3,"file":"title.mjs","sources":["../../../src/utils/title.ts"],"sourcesContent":["import { z } from 'zod';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type { Runnable } from '@langchain/core/runnables';\nimport * as t from '@/types';\n\nconst defaultTitlePrompt = `Write a concise title for this conversation in the detected language. Title in 5 Words or Less. No Punctuation or Quotation.\n{convo}`;\n\nconst languageInstructions = 'Detect the language used in the following text. Note: words may be misspelled or cut off; use context clues to identify the language:\\n{text}';\n\nconst languagePrompt = ChatPromptTemplate.fromTemplate(languageInstructions);\n\nconst languageSchema = z.object({\n language: z.string().describe('The detected language of the conversation')\n});\n\nconst titleSchema = z.object({\n title: z.string().describe('A concise title for the conversation in 5 words or less, without punctuation or quotation'),\n});\n\nexport const createTitleRunnable = async (model: t.ChatModelInstance, _titlePrompt?: string): Promise<Runnable> => {\n // Disabled since this works fine\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /* @ts-ignore */\n const languageLLM = model.withStructuredOutput(languageSchema);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /* @ts-ignore */\n const titleLLM = model.withStructuredOutput(titleSchema);\n\n const languageChain = languagePrompt.pipe(languageLLM);\n\n const titlePrompt = ChatPromptTemplate.fromTemplate(_titlePrompt ?? defaultTitlePrompt);\n\n return new RunnableLambda({\n func: async (input: { convo: string, inputText: string, skipLanguage: boolean }): Promise<{ language: string; title: string } | { title: string }> => {\n if (input.skipLanguage) {\n return await titlePrompt.pipe(titleLLM).invoke({\n convo: input.convo\n }) as { title: string };\n }\n const languageResult = await languageChain.invoke({ text: input.inputText }) as { language: string } | undefined;\n const language = languageResult?.language ?? 'English';\n const titleResult = await titlePrompt.pipe(titleLLM).invoke({\n language,\n convo: input.convo\n }) as { title: string } | undefined;\n return { language, title: titleResult?.title ?? '' };\n },\n });\n};"],"names":[],"mappings":";;;;AAMA,MAAM,kBAAkB,GAAG,CAAA;QACnB;AAER,MAAM,oBAAoB,GAAG,+IAA+I;AAE5K,MAAM,cAAc,GAAG,kBAAkB,CAAC,YAAY,CAAC,oBAAoB,CAAC;AAE5E,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAA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1,3 +1,4 @@
|
|
|
1
|
+
import type { UsageMetadata, BaseMessageFields } from '@langchain/core/messages';
|
|
1
2
|
import type { Graph } from '@/graphs';
|
|
2
3
|
import type * as t from '@/types';
|
|
3
4
|
export declare class HandlerRegistry {
|
|
@@ -6,6 +7,8 @@ export declare class HandlerRegistry {
|
|
|
6
7
|
getHandler(eventType: string): t.EventHandler | undefined;
|
|
7
8
|
}
|
|
8
9
|
export declare class ModelEndHandler implements t.EventHandler {
|
|
10
|
+
collectedUsage?: UsageMetadata[];
|
|
11
|
+
constructor(collectedUsage?: UsageMetadata[]);
|
|
9
12
|
handle(event: string, data: t.ModelEndData, metadata?: Record<string, unknown>, graph?: Graph): void;
|
|
10
13
|
}
|
|
11
14
|
export declare class ToolEndHandler implements t.EventHandler {
|
|
@@ -22,4 +25,4 @@ export declare class TestChatStreamHandler implements t.EventHandler {
|
|
|
22
25
|
export declare class LLMStreamHandler implements t.EventHandler {
|
|
23
26
|
handle(event: string, data: t.StreamEventData | undefined, metadata?: Record<string, unknown>): void;
|
|
24
27
|
}
|
|
25
|
-
export declare const createMetadataAggregator: (_collected?: Record<string,
|
|
28
|
+
export declare const createMetadataAggregator: (_collected?: Record<string, NonNullable<BaseMessageFields["response_metadata"]>>[]) => t.MetadataAggregatorResult;
|
|
@@ -4,7 +4,7 @@ import { Runnable, RunnableConfig } from '@langchain/core/runnables';
|
|
|
4
4
|
import { SystemMessage } from '@langchain/core/messages';
|
|
5
5
|
import type { BaseMessage } from '@langchain/core/messages';
|
|
6
6
|
import type * as t from '@/types';
|
|
7
|
-
import { Providers, GraphNodeKeys, Callback } from '@/common';
|
|
7
|
+
import { Providers, GraphNodeKeys, Callback, ContentTypes } from '@/common';
|
|
8
8
|
import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
|
|
9
9
|
import { HandlerRegistry } from '@/events';
|
|
10
10
|
export type GraphNode = GraphNodeKeys | typeof START;
|
|
@@ -33,9 +33,14 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
33
33
|
abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;
|
|
34
34
|
abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;
|
|
35
35
|
abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;
|
|
36
|
+
abstract dispatchReasoningDelta(stepId: string, delta: t.ReasoningDelta): void;
|
|
36
37
|
abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;
|
|
37
38
|
abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;
|
|
38
39
|
abstract createWorkflow(): t.CompiledWorkflow<T>;
|
|
40
|
+
lastToken?: string;
|
|
41
|
+
tokenTypeSwitch?: 'reasoning' | 'content';
|
|
42
|
+
reasoningKey: 'reasoning_content' | 'reasoning';
|
|
43
|
+
currentTokenType: ContentTypes.TEXT | ContentTypes.THINK;
|
|
39
44
|
messageStepHasToolCalls: Map<string, boolean>;
|
|
40
45
|
messageIdsByStepKey: Map<string, string>;
|
|
41
46
|
prelimMessageIdsByStepKey: Map<string, string>;
|
|
@@ -64,18 +69,7 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
|
|
|
64
69
|
provider: Providers;
|
|
65
70
|
toolEnd: boolean;
|
|
66
71
|
signal: AbortSignal | undefined;
|
|
67
|
-
constructor({ runId, tools, toolMap, provider,
|
|
68
|
-
runId?: string;
|
|
69
|
-
signal?: AbortSignal;
|
|
70
|
-
provider: Providers;
|
|
71
|
-
tools?: t.GenericTool[];
|
|
72
|
-
toolMap?: t.ToolMap;
|
|
73
|
-
clientOptions: Record<string, unknown>;
|
|
74
|
-
instructions?: string;
|
|
75
|
-
additional_instructions?: string;
|
|
76
|
-
streamBuffer?: number;
|
|
77
|
-
toolEnd?: boolean;
|
|
78
|
-
});
|
|
72
|
+
constructor({ runId, tools, signal, toolMap, provider, streamBuffer, instructions, reasoningKey, clientOptions, toolEnd, additional_instructions, }: t.StandardGraphInput);
|
|
79
73
|
resetValues(keepContent?: boolean): void;
|
|
80
74
|
getRunStep(stepId: string): t.RunStep | undefined;
|
|
81
75
|
getStepKey(metadata: Record<string, unknown> | undefined): string;
|
|
@@ -88,6 +82,7 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
|
|
|
88
82
|
createGraphState(): t.GraphStateChannels<t.BaseGraphState>;
|
|
89
83
|
initializeTools(): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState>;
|
|
90
84
|
initializeModel(): Runnable;
|
|
85
|
+
overrideTestModel(responses: string[], sleep?: number): void;
|
|
91
86
|
getNewModel({ clientOptions, omitOriginalOptions, }: {
|
|
92
87
|
clientOptions?: t.ClientOptions;
|
|
93
88
|
omitOriginalOptions?: string[];
|
|
@@ -101,4 +96,5 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
|
|
|
101
96
|
handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;
|
|
102
97
|
dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;
|
|
103
98
|
dispatchMessageDelta(id: string, delta: t.MessageDelta): void;
|
|
99
|
+
dispatchReasoningDelta: (stepId: string, delta: t.ReasoningDelta) => void;
|
|
104
100
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { BaseMessage } from '@langchain/core/messages';
|
|
2
|
+
import type { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
3
|
+
import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
4
|
+
import { FakeListChatModel } from '@langchain/core/utils/testing';
|
|
5
|
+
type SplitStrategy = {
|
|
6
|
+
type: 'regex' | 'fixed';
|
|
7
|
+
value: RegExp | number;
|
|
8
|
+
};
|
|
9
|
+
export declare class FakeChatModel extends FakeListChatModel {
|
|
10
|
+
private splitStrategy;
|
|
11
|
+
constructor({ responses, sleep, emitCustomEvent, splitStrategy }: {
|
|
12
|
+
responses: string[];
|
|
13
|
+
sleep?: number;
|
|
14
|
+
emitCustomEvent?: boolean;
|
|
15
|
+
splitStrategy?: SplitStrategy;
|
|
16
|
+
});
|
|
17
|
+
private splitText;
|
|
18
|
+
_streamResponseChunks(_messages: BaseMessage[], options: this['ParsedCallOptions'], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
|
|
19
|
+
}
|
|
20
|
+
export declare function createFakeStreamingLLM(responses: string[], sleep?: number, splitStrategy?: SplitStrategy): FakeChatModel;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function capitalizeFirstLetter(string: string): string;
|
package/dist/types/stream.d.ts
CHANGED
|
@@ -1,20 +1,16 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AIMessageChunk } from '@langchain/core/messages';
|
|
2
|
+
import type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';
|
|
2
3
|
import type { Graph } from '@/graphs';
|
|
3
4
|
import type * as t from '@/types';
|
|
4
|
-
import { GraphEvents } from '@/common';
|
|
5
5
|
export declare const getMessageId: (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId?: boolean) => string | undefined;
|
|
6
6
|
export declare const handleToolCalls: (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph) => void;
|
|
7
7
|
export declare class ChatModelStreamHandler implements t.EventHandler {
|
|
8
8
|
handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
aggregateContent: ({ event, data }: {
|
|
14
|
-
event: GraphEvents;
|
|
15
|
-
data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {
|
|
16
|
-
result: t.ToolEndEvent;
|
|
17
|
-
};
|
|
9
|
+
handleToolCallChunks: ({ graph, stepKey, toolCallChunks, }: {
|
|
10
|
+
graph: Graph;
|
|
11
|
+
stepKey: string;
|
|
12
|
+
toolCallChunks: ToolCallChunk[];
|
|
18
13
|
}) => void;
|
|
19
|
-
|
|
20
|
-
|
|
14
|
+
handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void;
|
|
15
|
+
}
|
|
16
|
+
export declare function createContentAggregator(): t.ContentAggregatorResult;
|
|
@@ -2,6 +2,9 @@ import type { StateGraphArgs, StateGraph, CompiledStateGraph } from '@langchain/
|
|
|
2
2
|
import type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
3
3
|
import type { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
4
4
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
5
|
+
import type { ToolMap, GenericTool } from '@/types/tools';
|
|
6
|
+
import type { ClientOptions } from '@/types/llm';
|
|
7
|
+
import type { Providers } from '@/common';
|
|
5
8
|
import type { Graph } from '@/graphs';
|
|
6
9
|
export type BaseGraphState = {
|
|
7
10
|
messages: BaseMessage[];
|
|
@@ -117,3 +120,16 @@ export type PartMetadata = {
|
|
|
117
120
|
export type ModelEndData = StreamEventData & {
|
|
118
121
|
output: AIMessageChunk | undefined;
|
|
119
122
|
} | undefined;
|
|
123
|
+
export type StandardGraphInput = {
|
|
124
|
+
runId?: string;
|
|
125
|
+
toolEnd?: boolean;
|
|
126
|
+
toolMap?: ToolMap;
|
|
127
|
+
provider: Providers;
|
|
128
|
+
signal?: AbortSignal;
|
|
129
|
+
instructions?: string;
|
|
130
|
+
streamBuffer?: number;
|
|
131
|
+
tools?: GenericTool[];
|
|
132
|
+
clientOptions: ClientOptions;
|
|
133
|
+
additional_instructions?: string;
|
|
134
|
+
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
135
|
+
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ChatOllama } from '@langchain/ollama';
|
|
2
|
+
import { ChatDeepSeek } from '@langchain/deepseek';
|
|
2
3
|
import { ChatAnthropic } from '@langchain/anthropic';
|
|
3
4
|
import { ChatMistralAI } from '@langchain/mistralai';
|
|
4
5
|
import { ChatBedrockConverse } from '@langchain/aws';
|
|
@@ -11,6 +12,7 @@ import type { ChatOpenAIFields, OpenAIChatInput, AzureOpenAIInput } from '@langc
|
|
|
11
12
|
import type { BedrockChatFields } from '@langchain/community/chat_models/bedrock/web';
|
|
12
13
|
import type { GoogleGenerativeAIChatInput } from '@langchain/google-genai';
|
|
13
14
|
import type { ChatVertexAIInput } from '@langchain/google-vertexai';
|
|
15
|
+
import type { ChatDeepSeekCallOptions } from '@langchain/deepseek';
|
|
14
16
|
import type { ChatBedrockConverseInput } from '@langchain/aws';
|
|
15
17
|
import type { ChatMistralAIInput } from '@langchain/mistralai';
|
|
16
18
|
import type { StructuredTool } from '@langchain/core/tools';
|
|
@@ -37,28 +39,31 @@ export type VertexAIClientOptions = ChatVertexAIInput;
|
|
|
37
39
|
export type BedrockClientOptions = BedrockChatFields;
|
|
38
40
|
export type BedrockConverseClientOptions = ChatBedrockConverseInput;
|
|
39
41
|
export type GoogleClientOptions = GoogleGenerativeAIChatInput;
|
|
40
|
-
export type
|
|
42
|
+
export type DeepSeekClientOptions = ChatDeepSeekCallOptions;
|
|
43
|
+
export type ClientOptions = OpenAIClientOptions | AzureClientOptions | OllamaClientOptions | AnthropicClientOptions | MistralAIClientOptions | VertexAIClientOptions | BedrockClientOptions | BedrockConverseClientOptions | GoogleClientOptions | DeepSeekClientOptions;
|
|
41
44
|
export type LLMConfig = {
|
|
42
45
|
provider: Providers;
|
|
43
46
|
} & ClientOptions;
|
|
44
47
|
export type ProviderOptionsMap = {
|
|
45
|
-
[Providers.OPENAI]: OpenAIClientOptions;
|
|
46
48
|
[Providers.AZURE]: AzureClientOptions;
|
|
49
|
+
[Providers.OPENAI]: OpenAIClientOptions;
|
|
47
50
|
[Providers.OLLAMA]: OllamaClientOptions;
|
|
51
|
+
[Providers.GOOGLE]: GoogleClientOptions;
|
|
52
|
+
[Providers.VERTEXAI]: VertexAIClientOptions;
|
|
53
|
+
[Providers.DEEPSEEK]: DeepSeekClientOptions;
|
|
48
54
|
[Providers.ANTHROPIC]: AnthropicClientOptions;
|
|
49
55
|
[Providers.MISTRALAI]: MistralAIClientOptions;
|
|
50
|
-
[Providers.VERTEXAI]: VertexAIClientOptions;
|
|
51
56
|
[Providers.BEDROCK_LEGACY]: BedrockClientOptions;
|
|
52
57
|
[Providers.BEDROCK]: BedrockConverseClientOptions;
|
|
53
|
-
[Providers.GOOGLE]: GoogleClientOptions;
|
|
54
58
|
};
|
|
55
59
|
export type ChatModelMap = {
|
|
56
60
|
[Providers.OPENAI]: ChatOpenAI;
|
|
57
61
|
[Providers.OLLAMA]: ChatOllama;
|
|
58
62
|
[Providers.AZURE]: AzureChatOpenAI;
|
|
63
|
+
[Providers.DEEPSEEK]: ChatDeepSeek;
|
|
64
|
+
[Providers.VERTEXAI]: ChatVertexAI;
|
|
59
65
|
[Providers.ANTHROPIC]: ChatAnthropic;
|
|
60
66
|
[Providers.MISTRALAI]: ChatMistralAI;
|
|
61
|
-
[Providers.VERTEXAI]: ChatVertexAI;
|
|
62
67
|
[Providers.BEDROCK_LEGACY]: BedrockChat;
|
|
63
68
|
[Providers.BEDROCK]: ChatBedrockConverse;
|
|
64
69
|
[Providers.GOOGLE]: ChatGoogleGenerativeAI;
|
|
@@ -5,23 +5,15 @@ import type { BaseCallbackHandler, CallbackHandlerMethods } from '@langchain/cor
|
|
|
5
5
|
import type * as graph from '@/graphs/Graph';
|
|
6
6
|
import type * as e from '@/common/enum';
|
|
7
7
|
import type * as g from '@/types/graph';
|
|
8
|
-
import type * as t from '@/types/tools';
|
|
9
8
|
import type * as l from '@/types/llm';
|
|
10
9
|
export type ZodObjectAny = z.ZodObject<any, any, any, any>;
|
|
11
|
-
export type
|
|
12
|
-
runId?: string;
|
|
10
|
+
export type BaseGraphConfig = {
|
|
13
11
|
type?: 'standard';
|
|
14
|
-
provider?: e.Providers;
|
|
15
|
-
instructions?: string;
|
|
16
12
|
llmConfig: l.LLMConfig;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
additional_instructions?: string;
|
|
20
|
-
streamBuffer?: number;
|
|
21
|
-
signal?: AbortSignal;
|
|
22
|
-
clientOptions?: Record<string, unknown>;
|
|
23
|
-
toolEnd?: boolean;
|
|
13
|
+
provider?: e.Providers;
|
|
14
|
+
clientOptions?: l.ClientOptions;
|
|
24
15
|
};
|
|
16
|
+
export type StandardGraphConfig = BaseGraphConfig & Omit<g.StandardGraphInput, 'provider' | 'clientOptions'>;
|
|
25
17
|
export interface AgentStateChannels {
|
|
26
18
|
messages: BaseMessage[];
|
|
27
19
|
next: string;
|