@librechat/agents 2.1.7 → 2.1.8
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 +6 -3
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +1 -13
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/messages.cjs +43 -5
- package/dist/cjs/messages.cjs.map +1 -1
- package/dist/cjs/stream.cjs +3 -3
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +6 -3
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +1 -13
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/messages.mjs +43 -5
- package/dist/esm/messages.mjs.map +1 -1
- package/dist/esm/stream.mjs +3 -3
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +6 -3
- package/dist/types/messages.d.ts +2 -1
- package/dist/types/types/stream.d.ts +10 -1
- package/package.json +2 -2
- package/src/common/enum.ts +6 -3
- package/src/graphs/Graph.ts +1 -13
- package/src/messages.ts +56 -5
- package/src/stream.ts +3 -3
- package/src/types/stream.ts +8 -1
package/dist/cjs/common/enum.cjs
CHANGED
|
@@ -92,12 +92,15 @@ exports.StepTypes = void 0;
|
|
|
92
92
|
exports.ContentTypes = void 0;
|
|
93
93
|
(function (ContentTypes) {
|
|
94
94
|
ContentTypes["TEXT"] = "text";
|
|
95
|
+
ContentTypes["ERROR"] = "error";
|
|
95
96
|
ContentTypes["THINK"] = "think";
|
|
96
|
-
ContentTypes["THINKING"] = "thinking";
|
|
97
97
|
ContentTypes["TOOL_CALL"] = "tool_call";
|
|
98
|
-
ContentTypes["IMAGE_FILE"] = "image_file";
|
|
99
98
|
ContentTypes["IMAGE_URL"] = "image_url";
|
|
100
|
-
ContentTypes["
|
|
99
|
+
ContentTypes["IMAGE_FILE"] = "image_file";
|
|
100
|
+
/** Anthropic */
|
|
101
|
+
ContentTypes["THINKING"] = "thinking";
|
|
102
|
+
/** Bedrock */
|
|
103
|
+
ContentTypes["REASONING_CONTENT"] = "reasoning_content";
|
|
101
104
|
})(exports.ContentTypes || (exports.ContentTypes = {}));
|
|
102
105
|
exports.ToolCallTypes = void 0;
|
|
103
106
|
(function (ToolCallTypes) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end'\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n BEDROCK_LEGACY = 'bedrock_legacy',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n OLLAMA = 'ollama',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools',\n AGENT = 'agent',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation'\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n
|
|
1
|
+
{"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end'\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n BEDROCK_LEGACY = 'bedrock_legacy',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n OLLAMA = 'ollama',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools',\n AGENT = 'agent',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation'\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n CUSTOM_EVENT = 'handleCustomEvent'\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n}\n\nexport enum EnvVar {\n CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',\n CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL'\n}\n"],"names":["GraphEvents","Providers","GraphNodeKeys","GraphNodeActions","CommonEvents","StepTypes","ContentTypes","ToolCallTypes","Callback","Constants","EnvVar"],"mappings":";;AAAA;;;;;AAKG;AACSA;AAAZ,CAAA,UAAY,WAAW,EAAA;;;AAIrB,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;;AAE3B,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;;AAEvC,IAAA,WAAA,CAAA,uBAAA,CAAA,GAAA,uBAA+C;;AAE/C,IAAA,WAAA,CAAA,kBAAA,CAAA,GAAA,kBAAqC;;AAErC,IAAA,WAAA,CAAA,oBAAA,CAAA,GAAA,oBAAyC;;;AAKzC,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,kBAAA,CAAA,GAAA,qBAAwC;;AAGxC,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,sBAA0C;;AAG1C,IAAA,WAAA,CAAA,gBAAA,CAAA,GAAA,mBAAoC;;AAGpC,IAAA,WAAA,CAAA,WAAA,CAAA,GAAA,cAA0B;;AAG1B,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,eAA4B;;AAG5B,IAAA,WAAA,CAAA,SAAA,CAAA,GAAA,YAAsB;;AAGtB,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,gBAA8B;;AAG9B,IAAA,WAAA,CAAA,cAAA,CAAA,GAAA,iBAAgC;;AAGhC,IAAA,WAAA,CAAA,WAAA,CAAA,GAAA,cAA0B;;AAG1B,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,eAA4B;;AAG5B,IAAA,WAAA,CAAA,UAAA,CAAA,GAAA,aAAwB;;AAGxB,IAAA,WAAA,CAAA,iBAAA,CAAA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,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,kBAAA,CAAA,GAAA,kBAAqC;;AAErC,IAAA,aAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACzB,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAOxB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,QAAQ,EAAA;AAClB,IAAA,QAAA,CAAA,YAAA,CAAA,GAAA,iBAA8B;AAC9B,IAAA,QAAA,CAAA,YAAA,CAAA,GAAA,iBAA8B;AAC9B,IAAA,QAAA,CAAA,UAAA,CAAA,GAAA,eAA0B;AAC1B;;;;;;;;;;;;;;;;AAgBE;AACJ,CAAC,EArBWA,gBAAQ,KAARA,gBAAQ,GAqBnB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,SAAS,EAAA;AACnB,IAAA,SAAA,CAAA,uBAAA,CAAA,GAAA,6BAAqD;AACrD,IAAA,SAAA,CAAA,cAAA,CAAA,GAAA,cAA6B;AAC7B,IAAA,SAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EAJWA,iBAAS,KAATA,iBAAS,GAIpB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACvC,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACzC,CAAC,EAHWA,cAAM,KAANA,cAAM,GAGjB,EAAA,CAAA,CAAA;;"}
|
|
@@ -278,19 +278,7 @@ class StandardGraph extends Graph {
|
|
|
278
278
|
finalChunk = stream.concat(finalChunk, chunk);
|
|
279
279
|
}
|
|
280
280
|
}
|
|
281
|
-
finalChunk = messages$1.modifyDeltaProperties(finalChunk);
|
|
282
|
-
if (this.provider === _enum.Providers.ANTHROPIC && Array.isArray(finalChunk?.content)) {
|
|
283
|
-
finalChunk.content = finalChunk.content.map((block) => {
|
|
284
|
-
if (block?.['thinking'] && block.type !== _enum.ContentTypes.THINKING) {
|
|
285
|
-
return {
|
|
286
|
-
...block,
|
|
287
|
-
type: _enum.ContentTypes.THINKING,
|
|
288
|
-
thinking: block.thinking ?? '',
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
return block;
|
|
292
|
-
});
|
|
293
|
-
}
|
|
281
|
+
finalChunk = messages$1.modifyDeltaProperties(this.provider, finalChunk);
|
|
294
282
|
return { messages: [finalChunk] };
|
|
295
283
|
}
|
|
296
284
|
const finalMessage = (await this.boundModel.invoke(finalMessages, config));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Graph.cjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { START, END, StateGraph } from '@langchain/langgraph';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';\nimport { AIMessageChunk, ToolMessage, SystemMessage } from '@langchain/core/messages';\nimport type { BaseMessage, BaseMessageFields } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback, ContentTypes } from '@/common';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (graph: StandardGraph, ...args: T) => void;\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n}\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<infer Args>\n ? (...args: Args) => void\n : never;\n};\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract createGraphState(): t.GraphStateChannels<T>;\n abstract initializeTools(): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel(): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;\n abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;\n abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;\n abstract dispatchReasoningDelta(stepId: string, delta: t.ReasoningDelta): void;\n abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;\n\n abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n abstract createWorkflow(): t.CompiledWorkflow<T>;\n lastToken?: string;\n tokenTypeSwitch?: 'reasoning' | 'content';\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK = ContentTypes.TEXT;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\n signal?: AbortSignal;\n}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n clientOptions: t.ClientOptions;\n boundModel: Runnable;\n /** The last recorded timestamp that a stream API call was invoked */\n lastStreamCall: number | undefined;\n handlerRegistry: HandlerRegistry | undefined;\n systemMessage: SystemMessage | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n startIndex: number = 0;\n provider: Providers;\n toolEnd: boolean;\n signal: AbortSignal | undefined;\n\n constructor({\n runId,\n tools,\n signal,\n toolMap,\n provider,\n streamBuffer,\n instructions,\n reasoningKey,\n clientOptions,\n toolEnd = false,\n additional_instructions = '',\n } : t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.signal = signal;\n this.toolEnd = toolEnd;\n this.toolMap = toolMap;\n this.provider = provider;\n this.streamBuffer = streamBuffer;\n this.clientOptions = clientOptions;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n\n let finalInstructions: string | BaseMessageFields = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\n }\n\n if (finalInstructions && provider === Providers.ANTHROPIC && (clientOptions as t.AnthropicClientOptions)?.clientOptions?.defaultHeaders?.['anthropic-beta']?.includes('prompt-caching')) {\n finalInstructions = {\n content: [\n {\n type: \"text\",\n text: instructions,\n cache_control: { type: \"ephemeral\" },\n },\n ],\n };\n }\n\n if (finalInstructions) {\n this.systemMessage = new SystemMessage(finalInstructions);\n }\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(this.messageIdsByStepKey, new Map());\n this.messageStepHasToolCalls = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.currentTokenType = resetIfNotEmpty(this.currentTokenType, ContentTypes.TEXT);\n this.lastToken = resetIfNotEmpty(this.lastToken, undefined);\n this.tokenTypeSwitch = resetIfNotEmpty(this.tokenTypeSwitch, undefined);\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n if (this.currentTokenType === ContentTypes.THINK) {\n keyList.push('reasoning');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /* Graph */\n\n createGraphState(): t.GraphStateChannels<t.BaseGraphState> {\n return {\n messages: {\n value: (x: BaseMessage[], y: BaseMessage[]): BaseMessage[] => {\n if (!x.length) {\n if (this.systemMessage) {\n x.push(this.systemMessage);\n }\n\n this.startIndex = x.length + y.length;\n }\n const current = x.concat(y);\n this.messages = current;\n return current;\n },\n default: () => [],\n },\n };\n }\n\n initializeTools(): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n // return new ToolNode<t.BaseGraphState>(this.tools);\n return new CustomToolNode<t.BaseGraphState>({\n tools: this.tools || [],\n toolMap: this.toolMap,\n toolCallStepIds: this.toolCallStepIds,\n });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n\n if (isOpenAILike(this.provider) && (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {\n model.temperature = (this.clientOptions as t.OpenAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (this.clientOptions as t.OpenAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.OpenAIClientOptions).presencePenalty as number;\n model.n = (this.clientOptions as t.OpenAIClientOptions).n as number;\n } else if (this.provider === Providers.VERTEXAI && model instanceof ChatVertexAI) {\n model.temperature = (this.clientOptions as t.VertexAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (this.clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (this.clientOptions as t.VertexAIClientOptions).topLogprobs as number;\n model.frequencyPenalty = (this.clientOptions as t.VertexAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.VertexAIClientOptions).presencePenalty as number;\n model.maxOutputTokens = (this.clientOptions as t.VertexAIClientOptions).maxOutputTokens as number;\n }\n\n if (!this.tools || this.tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(this.tools);\n }\n overrideTestModel(responses: string[], sleep?: number): void {\n this.boundModel = createFakeStreamingLLM(responses, sleep);\n }\n\n getNewModel({\n clientOptions = {},\n omitOriginalOptions,\n } : {\n clientOptions?: t.ClientOptions;\n omitOriginalOptions?: string[]\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(this.provider);\n const _options = omitOriginalOptions ? Object.fromEntries(\n Object.entries(this.clientOptions).filter(([key]) => !omitOriginalOptions.includes(key)),\n ) : this.clientOptions;\n const options = Object.assign(_options, clientOptions);\n return new ChatModelClass(options);\n }\n\n createCallModel() {\n return async (state: t.BaseGraphState, config?: RunnableConfig): Promise<Partial<t.BaseGraphState>> => {\n const { provider = '' } = (config?.configurable as t.GraphConfig | undefined) ?? {} ;\n if (!config || !provider) {\n throw new Error(`No ${config ? 'provider' : 'config'} provided`);\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n const finalMessages = messages;\n const lastMessageX = finalMessages[finalMessages.length - 2];\n const lastMessageY = finalMessages[finalMessages.length - 1];\n\n if (\n provider === Providers.BEDROCK\n && lastMessageX instanceof AIMessageChunk\n && lastMessageY instanceof ToolMessage\n && typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (isLatestToolMessage && provider === Providers.ANTHROPIC) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n (isOpenAILike(provider) || isGoogleLike(provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (this.lastStreamCall != null && this.streamBuffer != null) {\n const timeSinceLastCall = Date.now() - this.lastStreamCall;\n if (timeSinceLastCall < this.streamBuffer) {\n const timeToWait = Math.ceil((this.streamBuffer - timeSinceLastCall) / 1000) * 1000;\n await sleep(timeToWait);\n }\n }\n\n this.lastStreamCall = Date.now();\n\n if ((this.tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n const stream = await this.boundModel.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n if (!finalChunk) {\n finalChunk = chunk;\n } else {\n finalChunk = concat(finalChunk, chunk);\n }\n }\n\n finalChunk = modifyDeltaProperties(finalChunk);\n if (this.provider === Providers.ANTHROPIC && Array.isArray(finalChunk?.content)) {\n finalChunk.content = finalChunk.content.map((block) => {\n if ((block as t.ThinkingContentText | undefined)?.['thinking'] && block.type !== ContentTypes.THINKING) {\n return {\n ...block,\n type: ContentTypes.THINKING,\n thinking: (block as t.ThinkingContentText).thinking ?? '',\n } as t.ThinkingContentText;\n }\n return block;\n })\n }\n return { messages: [finalChunk as AIMessageChunk] };\n }\n\n const finalMessage = (await this.boundModel.invoke(finalMessages, config)) as AIMessageChunk;\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {\n if (!tool_call.name) {\n return false;\n }\n return true;\n });\n }\n return { messages: [finalMessage] };\n };\n }\n\n createWorkflow(): t.CompiledWorkflow<t.BaseGraphState> {\n const routeMessage = (state: t.BaseGraphState, config?: RunnableConfig): string => {\n this.config = config;\n // const lastMessage = state.messages[state.messages.length - 1] as AIMessage;\n // if (!lastMessage?.tool_calls?.length) {\n // return END;\n // }\n // return TOOLS;\n return toolsCondition(state);\n };\n\n const workflow = new StateGraph<t.BaseGraphState>({\n channels: this.graphState,\n })\n .addNode(AGENT, this.createCallModel())\n .addNode(TOOLS, this.initializeTools())\n .addEdge(START, AGENT)\n .addConditionalEdges(AGENT, routeMessage)\n .addEdge(TOOLS, this.toolEnd ? END : AGENT);\n\n return workflow.compile();\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP, runStep, this.config);\n return stepId;\n }\n\n handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output } = data;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content),\n progress: 1,\n };\n\n this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n { result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call\n } as t.ToolCompleteEvent,\n },\n metadata,\n this,\n );\n }\n\n dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP_DELTA, runStepDelta, this.config);\n }\n\n dispatchMessageDelta(id: string, delta: t.MessageDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_MESSAGE_DELTA, messageDelta, this.config);\n }\n\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_REASONING_DELTA, reasoningDelta, this.config);\n };\n}\n"],"names":["GraphNodeKeys","ContentTypes","Providers","SystemMessage","resetIfNotEmpty","joinKeys","nanoid","convertMessagesToContent","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","messages","AIMessageChunk","ToolMessage","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","sleep","manualToolStreamProviders","stream","dispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","toolsCondition","StateGraph","START","END","StepTypes"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAyBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa;MAchB,KAAK,CAAA;AAyBzB,IAAA,SAAS;AACT,IAAA,eAAe;IACf,YAAY,GAAsC,mBAAmB;AACrE,IAAA,gBAAgB,GAA2CC,kBAAY,CAAC,IAAI;AAC5E,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;;AAEhD,IAAA,YAAY;AACZ,IAAA,MAAM;AACP;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU;AAClB,IAAA,aAAa;AACb,IAAA,UAAU;;AAEV,IAAA,cAAc;AACd,IAAA,eAAe;AACf,IAAA,aAAa;IACb,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;AACL,IAAA,KAAK;AACL,IAAA,OAAO;IACP,UAAU,GAAW,CAAC;AACtB,IAAA,QAAQ;AACR,IAAA,OAAO;AACP,IAAA,MAAM;IAEN,WAAY,CAAA,EACV,KAAK,EACL,KAAK,EACL,MAAM,EACN,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,OAAO,GAAG,KAAK,EACf,uBAAuB,GAAG,EAAE,GACN,EAAA;AACtB,QAAA,KAAK,EAAE;AACP,QA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A,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;QACDD,4BAAmB,CAACC,iBAAW,CAAC,kBAAkB,EAAE,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC;AAClF,KAAC;AACF;;;;;"}
|
|
1
|
+
{"version":3,"file":"Graph.cjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { START, END, StateGraph } from '@langchain/langgraph';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';\nimport { AIMessageChunk, ToolMessage, SystemMessage } from '@langchain/core/messages';\nimport type { BaseMessage, BaseMessageFields } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback, ContentTypes } from '@/common';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (graph: StandardGraph, ...args: T) => void;\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n}\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<infer Args>\n ? (...args: Args) => void\n : never;\n};\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract createGraphState(): t.GraphStateChannels<T>;\n abstract initializeTools(): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel(): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;\n abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;\n abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;\n abstract dispatchReasoningDelta(stepId: string, delta: t.ReasoningDelta): void;\n abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;\n\n abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n abstract createWorkflow(): t.CompiledWorkflow<T>;\n lastToken?: string;\n tokenTypeSwitch?: 'reasoning' | 'content';\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK = ContentTypes.TEXT;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\n signal?: AbortSignal;\n}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n clientOptions: t.ClientOptions;\n boundModel: Runnable;\n /** The last recorded timestamp that a stream API call was invoked */\n lastStreamCall: number | undefined;\n handlerRegistry: HandlerRegistry | undefined;\n systemMessage: SystemMessage | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n startIndex: number = 0;\n provider: Providers;\n toolEnd: boolean;\n signal: AbortSignal | undefined;\n\n constructor({\n runId,\n tools,\n signal,\n toolMap,\n provider,\n streamBuffer,\n instructions,\n reasoningKey,\n clientOptions,\n toolEnd = false,\n additional_instructions = '',\n } : t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.signal = signal;\n this.toolEnd = toolEnd;\n this.toolMap = toolMap;\n this.provider = provider;\n this.streamBuffer = streamBuffer;\n this.clientOptions = clientOptions;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n\n let finalInstructions: string | BaseMessageFields = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\n }\n\n if (finalInstructions && provider === Providers.ANTHROPIC && (clientOptions as t.AnthropicClientOptions)?.clientOptions?.defaultHeaders?.['anthropic-beta']?.includes('prompt-caching')) {\n finalInstructions = {\n content: [\n {\n type: \"text\",\n text: instructions,\n cache_control: { type: \"ephemeral\" },\n },\n ],\n };\n }\n\n if (finalInstructions) {\n this.systemMessage = new SystemMessage(finalInstructions);\n }\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(this.messageIdsByStepKey, new Map());\n this.messageStepHasToolCalls = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.currentTokenType = resetIfNotEmpty(this.currentTokenType, ContentTypes.TEXT);\n this.lastToken = resetIfNotEmpty(this.lastToken, undefined);\n this.tokenTypeSwitch = resetIfNotEmpty(this.tokenTypeSwitch, undefined);\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n if (this.currentTokenType === ContentTypes.THINK) {\n keyList.push('reasoning');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /* Graph */\n\n createGraphState(): t.GraphStateChannels<t.BaseGraphState> {\n return {\n messages: {\n value: (x: BaseMessage[], y: BaseMessage[]): BaseMessage[] => {\n if (!x.length) {\n if (this.systemMessage) {\n x.push(this.systemMessage);\n }\n\n this.startIndex = x.length + y.length;\n }\n const current = x.concat(y);\n this.messages = current;\n return current;\n },\n default: () => [],\n },\n };\n }\n\n initializeTools(): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n // return new ToolNode<t.BaseGraphState>(this.tools);\n return new CustomToolNode<t.BaseGraphState>({\n tools: this.tools || [],\n toolMap: this.toolMap,\n toolCallStepIds: this.toolCallStepIds,\n });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n\n if (isOpenAILike(this.provider) && (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {\n model.temperature = (this.clientOptions as t.OpenAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (this.clientOptions as t.OpenAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.OpenAIClientOptions).presencePenalty as number;\n model.n = (this.clientOptions as t.OpenAIClientOptions).n as number;\n } else if (this.provider === Providers.VERTEXAI && model instanceof ChatVertexAI) {\n model.temperature = (this.clientOptions as t.VertexAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (this.clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (this.clientOptions as t.VertexAIClientOptions).topLogprobs as number;\n model.frequencyPenalty = (this.clientOptions as t.VertexAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.VertexAIClientOptions).presencePenalty as number;\n model.maxOutputTokens = (this.clientOptions as t.VertexAIClientOptions).maxOutputTokens as number;\n }\n\n if (!this.tools || this.tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(this.tools);\n }\n overrideTestModel(responses: string[], sleep?: number): void {\n this.boundModel = createFakeStreamingLLM(responses, sleep);\n }\n\n getNewModel({\n clientOptions = {},\n omitOriginalOptions,\n } : {\n clientOptions?: t.ClientOptions;\n omitOriginalOptions?: string[]\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(this.provider);\n const _options = omitOriginalOptions ? Object.fromEntries(\n Object.entries(this.clientOptions).filter(([key]) => !omitOriginalOptions.includes(key)),\n ) : this.clientOptions;\n const options = Object.assign(_options, clientOptions);\n return new ChatModelClass(options);\n }\n\n createCallModel() {\n return async (state: t.BaseGraphState, config?: RunnableConfig): Promise<Partial<t.BaseGraphState>> => {\n const { provider = '' } = (config?.configurable as t.GraphConfig | undefined) ?? {} ;\n if (!config || !provider) {\n throw new Error(`No ${config ? 'provider' : 'config'} provided`);\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n const finalMessages = messages;\n const lastMessageX = finalMessages[finalMessages.length - 2];\n const lastMessageY = finalMessages[finalMessages.length - 1];\n\n if (\n provider === Providers.BEDROCK\n && lastMessageX instanceof AIMessageChunk\n && lastMessageY instanceof ToolMessage\n && typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (isLatestToolMessage && provider === Providers.ANTHROPIC) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n (isOpenAILike(provider) || isGoogleLike(provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (this.lastStreamCall != null && this.streamBuffer != null) {\n const timeSinceLastCall = Date.now() - this.lastStreamCall;\n if (timeSinceLastCall < this.streamBuffer) {\n const timeToWait = Math.ceil((this.streamBuffer - timeSinceLastCall) / 1000) * 1000;\n await sleep(timeToWait);\n }\n }\n\n this.lastStreamCall = Date.now();\n\n if ((this.tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n const stream = await this.boundModel.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n if (!finalChunk) {\n finalChunk = chunk;\n } else {\n finalChunk = concat(finalChunk, chunk);\n }\n }\n\n finalChunk = modifyDeltaProperties(this.provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n }\n\n const finalMessage = (await this.boundModel.invoke(finalMessages, config)) as AIMessageChunk;\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {\n if (!tool_call.name) {\n return false;\n }\n return true;\n });\n }\n return { messages: [finalMessage] };\n };\n }\n\n createWorkflow(): t.CompiledWorkflow<t.BaseGraphState> {\n const routeMessage = (state: t.BaseGraphState, config?: RunnableConfig): string => {\n this.config = config;\n // const lastMessage = state.messages[state.messages.length - 1] as AIMessage;\n // if (!lastMessage?.tool_calls?.length) {\n // return END;\n // }\n // return TOOLS;\n return toolsCondition(state);\n };\n\n const workflow = new StateGraph<t.BaseGraphState>({\n channels: this.graphState,\n })\n .addNode(AGENT, this.createCallModel())\n .addNode(TOOLS, this.initializeTools())\n .addEdge(START, AGENT)\n .addConditionalEdges(AGENT, routeMessage)\n .addEdge(TOOLS, this.toolEnd ? END : AGENT);\n\n return workflow.compile();\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP, runStep, this.config);\n return stepId;\n }\n\n handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output } = data;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content),\n progress: 1,\n };\n\n this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n { result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call\n } as t.ToolCompleteEvent,\n },\n metadata,\n this,\n );\n }\n\n dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP_DELTA, runStepDelta, this.config);\n }\n\n dispatchMessageDelta(id: string, delta: t.MessageDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_MESSAGE_DELTA, messageDelta, this.config);\n }\n\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_REASONING_DELTA, reasoningDelta, this.config);\n };\n}\n"],"names":["GraphNodeKeys","ContentTypes","Providers","SystemMessage","resetIfNotEmpty","joinKeys","nanoid","convertMessagesToContent","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","messages","AIMessageChunk","ToolMessage","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","sleep","manualToolStreamProviders","stream","dispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","toolsCondition","StateGraph","START","END","StepTypes"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAyBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa;MAchB,KAAK,CAAA;AAyBzB,IAAA,SAAS;AACT,IAAA,eAAe;IACf,YAAY,GAAsC,mBAAmB;AACrE,IAAA,gBAAgB,GAA2CC,kBAAY,CAAC,IAAI;AAC5E,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,G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,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;QACDD,4BAAmB,CAACC,iBAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC;;AAG9E,IAAA,sBAAsB,GAAG,CAAC,MAAc,EAAE,KAAuB,KAAU;AACzE,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;QACDD,4BAAmB,CAACC,iBAAW,CAAC,kBAAkB,EAAE,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC;AAClF,KAAC;AACF;;;;;"}
|
package/dist/cjs/messages.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var messages = require('@langchain/core/messages');
|
|
4
|
+
var _enum = require('./common/enum.cjs');
|
|
4
5
|
|
|
5
6
|
// src/messages.ts
|
|
6
7
|
function getConverseOverrideMessage({ userMessage, lastMessageX, lastMessageY }) {
|
|
@@ -21,14 +22,21 @@ User: ${userMessage[1]}
|
|
|
21
22
|
`;
|
|
22
23
|
return new messages.HumanMessage(content);
|
|
23
24
|
}
|
|
24
|
-
const
|
|
25
|
+
const _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];
|
|
26
|
+
const allowedTypesByProvider = {
|
|
27
|
+
default: _allowedTypes,
|
|
28
|
+
[_enum.Providers.ANTHROPIC]: [..._allowedTypes, 'thinking'],
|
|
29
|
+
[_enum.Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],
|
|
30
|
+
[_enum.Providers.OPENAI]: _allowedTypes,
|
|
31
|
+
};
|
|
32
|
+
const modifyContent = ({ provider, messageType, content }) => {
|
|
33
|
+
const allowedTypes = allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;
|
|
25
34
|
return content.map(item => {
|
|
26
35
|
if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {
|
|
27
36
|
let newType = item.type;
|
|
28
37
|
if (newType.endsWith('_delta')) {
|
|
29
38
|
newType = newType.replace('_delta', '');
|
|
30
39
|
}
|
|
31
|
-
const allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];
|
|
32
40
|
if (!allowedTypes.includes(newType)) {
|
|
33
41
|
newType = 'text';
|
|
34
42
|
}
|
|
@@ -41,15 +49,45 @@ const modifyContent = (messageType, content) => {
|
|
|
41
49
|
return item;
|
|
42
50
|
});
|
|
43
51
|
};
|
|
44
|
-
function
|
|
52
|
+
function reduceBlocks(blocks) {
|
|
53
|
+
const reduced = [];
|
|
54
|
+
for (const block of blocks) {
|
|
55
|
+
const lastBlock = reduced[reduced.length - 1];
|
|
56
|
+
// Merge consecutive 'reasoning_content'
|
|
57
|
+
if (block.type === 'reasoning_content' && lastBlock?.type === 'reasoning_content') {
|
|
58
|
+
// append text if exists
|
|
59
|
+
if (block.reasoningText?.text) {
|
|
60
|
+
lastBlock.reasoningText.text = (lastBlock.reasoningText.text || '') + block.reasoningText.text;
|
|
61
|
+
}
|
|
62
|
+
// preserve the signature if exists
|
|
63
|
+
if (block.reasoningText?.signature) {
|
|
64
|
+
lastBlock.reasoningText.signature = block.reasoningText.signature;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// Merge consecutive 'text'
|
|
68
|
+
else if (block.type === 'text' && lastBlock?.type === 'text') {
|
|
69
|
+
lastBlock.text += block.text;
|
|
70
|
+
}
|
|
71
|
+
// add a new block as it's a different type or first element
|
|
72
|
+
else {
|
|
73
|
+
// deep copy to avoid mutation of original
|
|
74
|
+
reduced.push(JSON.parse(JSON.stringify(block)));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return reduced;
|
|
78
|
+
}
|
|
79
|
+
function modifyDeltaProperties(provider, obj) {
|
|
45
80
|
if (!obj || typeof obj !== 'object')
|
|
46
81
|
return obj;
|
|
47
82
|
const messageType = obj._getType ? obj._getType() : '';
|
|
83
|
+
if (provider === _enum.Providers.BEDROCK && Array.isArray(obj.content)) {
|
|
84
|
+
obj.content = reduceBlocks(obj.content);
|
|
85
|
+
}
|
|
48
86
|
if (Array.isArray(obj.content)) {
|
|
49
|
-
obj.content = modifyContent(messageType, obj.content);
|
|
87
|
+
obj.content = modifyContent({ provider, messageType, content: obj.content });
|
|
50
88
|
}
|
|
51
89
|
if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {
|
|
52
|
-
obj.lc_kwargs.content = modifyContent(messageType, obj.lc_kwargs.content);
|
|
90
|
+
obj.lc_kwargs.content = modifyContent({ provider, messageType, content: obj.lc_kwargs.content });
|
|
53
91
|
}
|
|
54
92
|
return obj;
|
|
55
93
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.cjs","sources":["../../src/messages.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst modifyContent = (messageType: string, content: t.ExtendedMessageContent[]): t.ExtendedMessageContent[] => {\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n const allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\nexport function modifyDeltaProperties(obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent(messageType, obj.content);\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent(messageType, obj.lc_kwargs.content);\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch (e) {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":["HumanMessage","AIMessage","messages","ToolMessage","AIMessageChunk"],"mappings":";;;;AAAA;AAKM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,EAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CAAC,CAAC;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO;CACvB;AAEC,IAAA,OAAO,IAAIA,qBAAY,CAAC,OAAO,CAAC;AAClC;AAEA,MAAM,aAAa,GAAG,CAAC,WAAmB,EAAE,OAAmC,KAAgC;AAC7G,IAA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AA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"messages.cjs","sources":["../../src/messages.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { Providers } from '@/common';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [..._allowedTypes, 'thinking'],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content\n}: {\n provider: Providers, messageType: string, content: t.ExtendedMessageContent[]\n}): t.ExtendedMessageContent[] => {\n const allowedTypes = allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock = t.BedrockReasoningContentText | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1];\n\n // Merge consecutive 'reasoning_content'\n if (block.type === 'reasoning_content' && lastBlock?.type === 'reasoning_content') {\n // append text if exists\n if (block.reasoningText?.text) {\n lastBlock.reasoningText.text = (lastBlock.reasoningText.text || '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (block.reasoningText?.signature) {\n lastBlock.reasoningText.signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n } \n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nexport function modifyDeltaProperties(provider: Providers, obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = reduceBlocks(obj.content as ContentBlock[]);\n }\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent({ provider, messageType, content: obj.content });\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent({ provider, messageType, content: obj.lc_kwargs.content });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch (e) {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":["HumanMessage","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I,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE;YACzC;;QAEF,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;YAC/B;;QAEF,iBAAiB,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC;AACtC,QAAA,GAAG,CAAC,OAAO,GAAG,kEAAkE;QAChF,iBAAiB,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC;AACjD,KAAC,CAAC;;AAGF,IAAA,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;AAChC,QAAAD,UAAQ,CAAC,IAAI,CAAC,IAAIH,qBAAY,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;;AAEnE;AAEgB,SAAA,aAAa,CAAI,KAAU,EAAE,SAAgC,EAAA;AAC3E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;;;;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -194,11 +194,11 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
194
194
|
content,
|
|
195
195
|
});
|
|
196
196
|
}
|
|
197
|
-
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.THINKING))) {
|
|
197
|
+
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.THINKING) || c.type?.startsWith(_enum.ContentTypes.REASONING_CONTENT))) {
|
|
198
198
|
graph.dispatchReasoningDelta(stepId, {
|
|
199
199
|
content: content.map((c) => ({
|
|
200
200
|
type: _enum.ContentTypes.THINK,
|
|
201
|
-
think: c.thinking,
|
|
201
|
+
think: c.thinking ?? c.reasoningText?.text ?? '',
|
|
202
202
|
}))
|
|
203
203
|
});
|
|
204
204
|
}
|
|
@@ -266,7 +266,7 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
266
266
|
};
|
|
267
267
|
handleReasoning(chunk, graph) {
|
|
268
268
|
let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey];
|
|
269
|
-
if (Array.isArray(chunk.content) && chunk.content[0]?.type === 'thinking') {
|
|
269
|
+
if (Array.isArray(chunk.content) && (chunk.content[0]?.type === 'thinking' || chunk.content[0]?.type === 'reasoning_content')) {
|
|
270
270
|
reasoning_content = 'valid';
|
|
271
271
|
}
|
|
272
272
|
if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '' || reasoning_content === 'valid')) {
|