@librechat/agents 2.2.0 → 2.2.2
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 +4 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +8 -7
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +19 -8
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/{messages.cjs → messages/core.cjs} +2 -2
- package/dist/cjs/messages/core.cjs.map +1 -0
- package/dist/cjs/messages/format.cjs +313 -0
- package/dist/cjs/messages/format.cjs.map +1 -0
- package/dist/cjs/messages/transformers.cjs +318 -0
- package/dist/cjs/messages/transformers.cjs.map +1 -0
- package/dist/cjs/messages/trimMessagesFactory.cjs +129 -0
- package/dist/cjs/messages/trimMessagesFactory.cjs.map +1 -0
- package/dist/cjs/stream.cjs +13 -0
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +4 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +2 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +4 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/{messages.mjs → messages/core.mjs} +2 -2
- package/dist/esm/messages/core.mjs.map +1 -0
- package/dist/esm/messages/format.mjs +306 -0
- package/dist/esm/messages/format.mjs.map +1 -0
- package/dist/esm/messages/transformers.mjs +316 -0
- package/dist/esm/messages/transformers.mjs.map +1 -0
- package/dist/esm/messages/trimMessagesFactory.mjs +127 -0
- package/dist/esm/messages/trimMessagesFactory.mjs.map +1 -0
- package/dist/esm/stream.mjs +13 -0
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +5 -1
- package/dist/types/messages/format.d.ts +111 -0
- package/dist/types/messages/index.d.ts +4 -0
- package/dist/types/messages/transformers.d.ts +320 -0
- package/dist/types/messages/trimMessagesFactory.d.ts +37 -0
- package/dist/types/types/stream.d.ts +9 -1
- package/package.json +1 -1
- package/src/common/enum.ts +4 -0
- package/src/messages/format.ts +433 -0
- package/src/messages/formatAgentMessages.test.ts +628 -0
- package/src/messages/formatMessage.test.ts +277 -0
- package/src/messages/index.ts +4 -0
- package/src/messages/transformers.ts +786 -0
- package/src/messages/trimMessagesFactory.test.ts +331 -0
- package/src/messages/trimMessagesFactory.ts +140 -0
- package/src/stream.ts +15 -1
- package/src/types/stream.ts +10 -1
- package/dist/cjs/messages.cjs.map +0 -1
- package/dist/esm/messages.mjs.map +0 -1
- /package/dist/types/{messages.d.ts → messages/core.d.ts} +0 -0
- /package/src/{messages.ts → messages/core.ts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Graph.mjs","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":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAyBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAchB,KAAK,CAAA;AAyBzB,IAAA,SAAS;AACT,IAAA,eAAe;IACf,YAAY,GAAsC,mBAAmB;AACrE,IAAA,gBAAgB,GAA2C,YAAY,CAAC,IAAI;AAC5E,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAm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,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;QACD,mBAAmB,CAAC,WAAW,CAAC,kBAAkB,EAAE,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC;AAClF,KAAC;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"Graph.mjs","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":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAyBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAchB,KAAK,CAAA;AAyBzB,IAAA,SAAS;AACT,IAAA,eAAe;IACf,YAAY,GAAsC,mBAAmB;AACrE,IAAA,gBAAgB,GAA2C,YAAY,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;IAC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U;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;QACD,mBAAmB,CAAC,WAAW,CAAC,kBAAkB,EAAE,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC;AAClF,KAAC;AACF;;;;"}
|
package/dist/esm/main.mjs
CHANGED
|
@@ -2,7 +2,10 @@ export { Run } from './run.mjs';
|
|
|
2
2
|
export { ChatModelStreamHandler, createContentAggregator, getMessageId, handleToolCalls } from './stream.mjs';
|
|
3
3
|
export { SEPARATORS, SplitStreamHandler } from './splitStream.mjs';
|
|
4
4
|
export { HandlerRegistry, LLMStreamHandler, ModelEndHandler, TestChatStreamHandler, TestLLMStreamHandler, ToolEndHandler, createMetadataAggregator } from './events.mjs';
|
|
5
|
-
export { convertMessagesToContent, findLastIndex, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, getConverseOverrideMessage, modifyDeltaProperties } from './messages.mjs';
|
|
5
|
+
export { convertMessagesToContent, findLastIndex, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, getConverseOverrideMessage, modifyDeltaProperties } from './messages/core.mjs';
|
|
6
|
+
export { formatAgentMessages, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMessage, formatVisionMessage } from './messages/format.mjs';
|
|
7
|
+
export { trimMessages } from './messages/transformers.mjs';
|
|
8
|
+
export { createTrimMessagesFunction } from './messages/trimMessagesFactory.mjs';
|
|
6
9
|
export { Graph, StandardGraph } from './graphs/Graph.mjs';
|
|
7
10
|
export { createCodeExecutionTool, getCodeBaseURL, imageExtRegex } from './tools/CodeExecutor.mjs';
|
|
8
11
|
export { Callback, CommonEvents, Constants, ContentTypes, EnvVar, GraphEvents, GraphNodeActions, GraphNodeKeys, Providers, StepTypes, ToolCallTypes } from './common/enum.mjs';
|
package/dist/esm/main.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { HumanMessage, AIMessage, ToolMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
2
|
-
import { Providers } from '
|
|
2
|
+
import { Providers } from '../common/enum.mjs';
|
|
3
3
|
|
|
4
4
|
// src/messages.ts
|
|
5
5
|
function getConverseOverrideMessage({ userMessage, lastMessageX, lastMessageY }) {
|
|
@@ -304,4 +304,4 @@ function findLastIndex(array, predicate) {
|
|
|
304
304
|
}
|
|
305
305
|
|
|
306
306
|
export { convertMessagesToContent, findLastIndex, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, getConverseOverrideMessage, modifyDeltaProperties };
|
|
307
|
-
//# sourceMappingURL=
|
|
307
|
+
//# sourceMappingURL=core.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.mjs","sources":["../../../src/messages/core.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":[],"mappings":";;;AAAA;AAMM,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,IAAI,YAAY,CAAC,OAAO,CAAC;AAClC;AAEA,MAAM,aAAa,GAAG,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,CAAC;AACtE,MAAM,sBAAsB,GAA6B;AACvD,IAAA,OAAO,EAAE,aAAa;IACtB,CAAC,SAAS,CAAC,SAAS,GAAG,CAAC,GAAG,aAAa,EAAE,UAAU,CAAC;IACrD,CAAC,SAAS,CAAC,OAA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AC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;"}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { HumanMessage, AIMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
|
|
2
|
+
import { Providers, ContentTypes } from '../common/enum.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Formats a message to OpenAI Vision API payload format.
|
|
6
|
+
*
|
|
7
|
+
* @param {VisionMessageParams} params - The parameters for formatting.
|
|
8
|
+
* @returns {Object} - The formatted message.
|
|
9
|
+
*/
|
|
10
|
+
const formatVisionMessage = ({ message, image_urls, endpoint }) => {
|
|
11
|
+
// Create a new object to avoid mutating the input
|
|
12
|
+
const result = {
|
|
13
|
+
...message,
|
|
14
|
+
content: []
|
|
15
|
+
};
|
|
16
|
+
if (endpoint === Providers.ANTHROPIC) {
|
|
17
|
+
result.content = [
|
|
18
|
+
...image_urls,
|
|
19
|
+
{ type: ContentTypes.TEXT, text: message.content }
|
|
20
|
+
];
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
result.content = [
|
|
24
|
+
{ type: ContentTypes.TEXT, text: message.content },
|
|
25
|
+
...image_urls
|
|
26
|
+
];
|
|
27
|
+
return result;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Formats a message to OpenAI payload format based on the provided options.
|
|
31
|
+
*
|
|
32
|
+
* @param {FormatMessageParams} params - The parameters for formatting.
|
|
33
|
+
* @returns {FormattedMessage | HumanMessage | AIMessage | SystemMessage} - The formatted message.
|
|
34
|
+
*/
|
|
35
|
+
const formatMessage = ({ message, userName, assistantName, endpoint, langChain = false }) => {
|
|
36
|
+
let { role: _role, _name, sender, text, content: _content, lc_id } = message;
|
|
37
|
+
if (lc_id && lc_id[2] && !langChain) {
|
|
38
|
+
const roleMapping = {
|
|
39
|
+
SystemMessage: 'system',
|
|
40
|
+
HumanMessage: 'user',
|
|
41
|
+
AIMessage: 'assistant',
|
|
42
|
+
};
|
|
43
|
+
_role = roleMapping[lc_id[2]] || _role;
|
|
44
|
+
}
|
|
45
|
+
const role = _role ?? (sender && sender?.toLowerCase() === 'user' ? 'user' : 'assistant');
|
|
46
|
+
const content = _content ?? text ?? '';
|
|
47
|
+
const formattedMessage = {
|
|
48
|
+
role,
|
|
49
|
+
content,
|
|
50
|
+
};
|
|
51
|
+
const { image_urls } = message;
|
|
52
|
+
if (Array.isArray(image_urls) && image_urls.length > 0 && role === 'user') {
|
|
53
|
+
return formatVisionMessage({
|
|
54
|
+
message: {
|
|
55
|
+
...formattedMessage,
|
|
56
|
+
content: typeof formattedMessage.content === 'string' ? formattedMessage.content : ''
|
|
57
|
+
},
|
|
58
|
+
image_urls,
|
|
59
|
+
endpoint,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (_name) {
|
|
63
|
+
formattedMessage.name = _name;
|
|
64
|
+
}
|
|
65
|
+
if (userName && formattedMessage.role === 'user') {
|
|
66
|
+
formattedMessage.name = userName;
|
|
67
|
+
}
|
|
68
|
+
if (assistantName && formattedMessage.role === 'assistant') {
|
|
69
|
+
formattedMessage.name = assistantName;
|
|
70
|
+
}
|
|
71
|
+
if (formattedMessage.name) {
|
|
72
|
+
// Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$
|
|
73
|
+
// https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2
|
|
74
|
+
formattedMessage.name = formattedMessage.name.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
75
|
+
if (formattedMessage.name.length > 64) {
|
|
76
|
+
formattedMessage.name = formattedMessage.name.substring(0, 64);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (!langChain) {
|
|
80
|
+
return formattedMessage;
|
|
81
|
+
}
|
|
82
|
+
if (role === 'user') {
|
|
83
|
+
return new HumanMessage(formattedMessage);
|
|
84
|
+
}
|
|
85
|
+
else if (role === 'assistant') {
|
|
86
|
+
return new AIMessage(formattedMessage);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
return new SystemMessage(formattedMessage);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Formats an array of messages for LangChain.
|
|
94
|
+
*
|
|
95
|
+
* @param {Array<MessageInput>} messages - The array of messages to format.
|
|
96
|
+
* @param {Omit<FormatMessageParams, 'message' | 'langChain'>} formatOptions - The options for formatting each message.
|
|
97
|
+
* @returns {Array<HumanMessage | AIMessage | SystemMessage>} - The array of formatted LangChain messages.
|
|
98
|
+
*/
|
|
99
|
+
const formatLangChainMessages = (messages, formatOptions) => {
|
|
100
|
+
return messages.map((msg) => {
|
|
101
|
+
const formatted = formatMessage({ ...formatOptions, message: msg, langChain: true });
|
|
102
|
+
return formatted;
|
|
103
|
+
});
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.
|
|
107
|
+
*
|
|
108
|
+
* @param {LangChainMessage} message - The message object to format.
|
|
109
|
+
* @returns {Record<string, any>} The formatted LangChain message.
|
|
110
|
+
*/
|
|
111
|
+
const formatFromLangChain = (message) => {
|
|
112
|
+
const kwargs = message.lc_kwargs ?? message.kwargs ?? {};
|
|
113
|
+
const { additional_kwargs = {}, ...message_kwargs } = kwargs;
|
|
114
|
+
return {
|
|
115
|
+
...message_kwargs,
|
|
116
|
+
...additional_kwargs,
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.
|
|
121
|
+
*
|
|
122
|
+
* @param {Array<Partial<TMessage>>} payload - The array of messages to format.
|
|
123
|
+
* @param {Record<number, number>} [indexTokenCountMap] - Optional map of message indices to token counts.
|
|
124
|
+
* @returns {Object} - Object containing formatted messages and updated indexTokenCountMap if provided.
|
|
125
|
+
*/
|
|
126
|
+
const formatAgentMessages = (payload, indexTokenCountMap) => {
|
|
127
|
+
const messages = [];
|
|
128
|
+
// If indexTokenCountMap is provided, create a new map to track the updated indices
|
|
129
|
+
const updatedIndexTokenCountMap = {};
|
|
130
|
+
// Keep track of the mapping from original payload indices to result indices
|
|
131
|
+
const indexMapping = {};
|
|
132
|
+
for (let i = 0; i < payload.length; i++) {
|
|
133
|
+
const message = payload[i];
|
|
134
|
+
// Q: Store the current length of messages to track where this payload message starts in the result?
|
|
135
|
+
// const startIndex = messages.length;
|
|
136
|
+
if (typeof message.content === 'string') {
|
|
137
|
+
message.content = [{ type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content }];
|
|
138
|
+
}
|
|
139
|
+
if (message.role !== 'assistant') {
|
|
140
|
+
messages.push(formatMessage({
|
|
141
|
+
message: message,
|
|
142
|
+
langChain: true
|
|
143
|
+
}));
|
|
144
|
+
// Update the index mapping for this message
|
|
145
|
+
indexMapping[i] = [messages.length - 1];
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
// For assistant messages, track the starting index before processing
|
|
149
|
+
const startMessageIndex = messages.length;
|
|
150
|
+
let currentContent = [];
|
|
151
|
+
let lastAIMessage = null;
|
|
152
|
+
let hasReasoning = false;
|
|
153
|
+
if (Array.isArray(message.content)) {
|
|
154
|
+
for (const part of message.content) {
|
|
155
|
+
if (part.type === ContentTypes.TEXT && part.tool_call_ids) {
|
|
156
|
+
/*
|
|
157
|
+
If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.
|
|
158
|
+
For Anthropic models, the "tool_calls" field on a message is only respected if content is a string.
|
|
159
|
+
*/
|
|
160
|
+
if (currentContent.length > 0) {
|
|
161
|
+
let content = currentContent.reduce((acc, curr) => {
|
|
162
|
+
if (curr.type === ContentTypes.TEXT) {
|
|
163
|
+
return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
|
|
164
|
+
}
|
|
165
|
+
return acc;
|
|
166
|
+
}, '');
|
|
167
|
+
content = `${content}\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();
|
|
168
|
+
lastAIMessage = new AIMessage({ content });
|
|
169
|
+
messages.push(lastAIMessage);
|
|
170
|
+
currentContent = [];
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
// Create a new AIMessage with this text and prepare for tool calls
|
|
174
|
+
lastAIMessage = new AIMessage({
|
|
175
|
+
content: part.text || '',
|
|
176
|
+
});
|
|
177
|
+
messages.push(lastAIMessage);
|
|
178
|
+
}
|
|
179
|
+
else if (part.type === ContentTypes.TOOL_CALL) {
|
|
180
|
+
if (!lastAIMessage) {
|
|
181
|
+
throw new Error('Invalid tool call structure: No preceding AIMessage with tool_call_ids');
|
|
182
|
+
}
|
|
183
|
+
// Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it
|
|
184
|
+
const { output, args: _args, ...tool_call } = part.tool_call;
|
|
185
|
+
// TODO: investigate; args as dictionary may need to be providers-or-tool-specific
|
|
186
|
+
let args = _args;
|
|
187
|
+
try {
|
|
188
|
+
if (typeof _args === 'string') {
|
|
189
|
+
args = JSON.parse(_args);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch (e) {
|
|
193
|
+
if (typeof _args === 'string') {
|
|
194
|
+
args = { input: _args };
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
tool_call.args = args;
|
|
198
|
+
if (!lastAIMessage.tool_calls) {
|
|
199
|
+
lastAIMessage.tool_calls = [];
|
|
200
|
+
}
|
|
201
|
+
lastAIMessage.tool_calls.push(tool_call);
|
|
202
|
+
// Add the corresponding ToolMessage
|
|
203
|
+
messages.push(new ToolMessage({
|
|
204
|
+
tool_call_id: tool_call.id,
|
|
205
|
+
name: tool_call.name,
|
|
206
|
+
content: output || '',
|
|
207
|
+
}));
|
|
208
|
+
}
|
|
209
|
+
else if (part.type === ContentTypes.THINK) {
|
|
210
|
+
hasReasoning = true;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
currentContent.push(part);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (hasReasoning && currentContent.length > 0) {
|
|
222
|
+
const content = currentContent
|
|
223
|
+
.reduce((acc, curr) => {
|
|
224
|
+
if (curr.type === ContentTypes.TEXT) {
|
|
225
|
+
return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
|
|
226
|
+
}
|
|
227
|
+
return acc;
|
|
228
|
+
}, '')
|
|
229
|
+
.trim();
|
|
230
|
+
if (content) {
|
|
231
|
+
messages.push(new AIMessage({ content }));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
else if (currentContent.length > 0) {
|
|
235
|
+
messages.push(new AIMessage({ content: currentContent }));
|
|
236
|
+
}
|
|
237
|
+
// Update the index mapping for this assistant message
|
|
238
|
+
// Store all indices that were created from this original message
|
|
239
|
+
const endMessageIndex = messages.length;
|
|
240
|
+
const resultIndices = [];
|
|
241
|
+
for (let j = startMessageIndex; j < endMessageIndex; j++) {
|
|
242
|
+
resultIndices.push(j);
|
|
243
|
+
}
|
|
244
|
+
indexMapping[i] = resultIndices;
|
|
245
|
+
}
|
|
246
|
+
// Update the token count map if it was provided
|
|
247
|
+
if (indexTokenCountMap) {
|
|
248
|
+
for (let originalIndex = 0; originalIndex < payload.length; originalIndex++) {
|
|
249
|
+
const resultIndices = indexMapping[originalIndex] || [];
|
|
250
|
+
const tokenCount = indexTokenCountMap[originalIndex];
|
|
251
|
+
if (tokenCount !== undefined) {
|
|
252
|
+
if (resultIndices.length === 1) {
|
|
253
|
+
// Simple 1:1 mapping
|
|
254
|
+
updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;
|
|
255
|
+
}
|
|
256
|
+
else if (resultIndices.length > 1) {
|
|
257
|
+
// If one message was split into multiple, distribute the token count
|
|
258
|
+
// This is a simplification - in reality, you might want a more sophisticated distribution
|
|
259
|
+
const countPerMessage = Math.floor(tokenCount / resultIndices.length);
|
|
260
|
+
resultIndices.forEach((resultIndex, idx) => {
|
|
261
|
+
if (idx === resultIndices.length - 1) {
|
|
262
|
+
// Give any remainder to the last message
|
|
263
|
+
updatedIndexTokenCountMap[resultIndex] = tokenCount - (countPerMessage * (resultIndices.length - 1));
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
updatedIndexTokenCountMap[resultIndex] = countPerMessage;
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return {
|
|
274
|
+
messages,
|
|
275
|
+
indexTokenCountMap: indexTokenCountMap ? updatedIndexTokenCountMap : undefined
|
|
276
|
+
};
|
|
277
|
+
};
|
|
278
|
+
/**
|
|
279
|
+
* Formats an array of messages for LangChain, making sure all content fields are strings
|
|
280
|
+
* @param {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} payload - The array of messages to format.
|
|
281
|
+
* @returns {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} - The array of formatted LangChain messages, including ToolMessages for tool calls.
|
|
282
|
+
*/
|
|
283
|
+
const formatContentStrings = (payload) => {
|
|
284
|
+
// Create a copy of the payload to avoid modifying the original
|
|
285
|
+
const result = [...payload];
|
|
286
|
+
for (const message of result) {
|
|
287
|
+
if (typeof message.content === 'string') {
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (!Array.isArray(message.content)) {
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
// Reduce text types to a single string, ignore all other types
|
|
294
|
+
const content = message.content.reduce((acc, curr) => {
|
|
295
|
+
if (curr.type === ContentTypes.TEXT) {
|
|
296
|
+
return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
|
|
297
|
+
}
|
|
298
|
+
return acc;
|
|
299
|
+
}, '');
|
|
300
|
+
message.content = content.trim();
|
|
301
|
+
}
|
|
302
|
+
return result;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
export { formatAgentMessages, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMessage, formatVisionMessage };
|
|
306
|
+
//# sourceMappingURL=format.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["import { ToolMessage, BaseMessage } from '@langchain/core/messages';\nimport { HumanMessage, AIMessage, SystemMessage } from '@langchain/core/messages';\nimport { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { MessageContentComplex } from '@/types';\nimport { Providers, ContentTypes } from '@/common';\n\ninterface VisionMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n image_urls: MessageContentImageUrl[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message to OpenAI Vision API payload format.\n *\n * @param {VisionMessageParams} params - The parameters for formatting.\n * @returns {Object} - The formatted message.\n */\nexport const formatVisionMessage = ({ message, image_urls, endpoint }: VisionMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[]\n };\n \n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...image_urls, \n { type: ContentTypes.TEXT, text: message.content }\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content }, \n ...image_urls\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param {FormatMessageParams} params - The parameters for formatting.\n * @returns {FormattedMessage | HumanMessage | AIMessage | SystemMessage} - The formatted message.\n */\nexport const formatMessage = ({ \n message, \n userName, \n assistantName, \n endpoint, \n langChain = false \n}: FormatMessageParams): FormattedMessage | HumanMessage | AIMessage | SystemMessage => {\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role = _role ?? (sender && sender?.toLowerCase() === 'user' ? 'user' : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n const { image_urls } = message;\n if (Array.isArray(image_urls) && image_urls.length > 0 && role === 'user') {\n return formatVisionMessage({\n message: {\n ...formattedMessage,\n content: typeof formattedMessage.content === 'string' ? formattedMessage.content : ''\n },\n image_urls,\n endpoint,\n });\n }\n\n if (_name) {\n formattedMessage.name = _name;\n }\n\n if (userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (assistantName && formattedMessage.role === 'assistant') {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param {Array<MessageInput>} messages - The array of messages to format.\n * @param {Omit<FormatMessageParams, 'message' | 'langChain'>} formatOptions - The options for formatting each message.\n * @returns {Array<HumanMessage | AIMessage | SystemMessage>} - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>, \n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({ ...formatOptions, message: msg, langChain: true });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param {LangChainMessage} message - The message object to format.\n * @returns {Record<string, any>} The formatted LangChain message.\n */\nexport const formatFromLangChain = (message: LangChainMessage): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\ninterface TMessage {\n role?: string;\n content?: string | Array<{\n type: ContentTypes;\n [ContentTypes.TEXT]?: string;\n text?: string;\n tool_call_ids?: string[];\n [key: string]: any;\n }>;\n [key: string]: any;\n}\n\ninterface ToolCallPart {\n type: ContentTypes.TOOL_CALL;\n tool_call: {\n id: string;\n name: string;\n args: string | Record<string, unknown>;\n output?: string;\n [key: string]: any;\n };\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param {Array<Partial<TMessage>>} payload - The array of messages to format.\n * @param {Record<number, number>} [indexTokenCountMap] - Optional map of message indices to token counts.\n * @returns {Object} - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: Array<Partial<TMessage>>, \n indexTokenCountMap?: Record<number, number>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage> = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[]> = {};\n\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [{ type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content }];\n }\n if (message.role !== 'assistant') {\n messages.push(formatMessage({ \n message: message as MessageInput, \n langChain: true \n }) as HumanMessage | AIMessage | SystemMessage);\n \n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n let currentContent: any[] = [];\n let lastAIMessage: AIMessage | null = null;\n\n let hasReasoning = false;\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content = `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n messages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text || '',\n });\n\n messages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n if (!lastAIMessage) {\n throw new Error('Invalid tool call structure: No preceding AIMessage with tool_call_ids');\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const { output, args: _args, ...tool_call } = (part.tool_call as any);\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch (e) {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n // Add the corresponding ToolMessage\n messages.push(\n new ToolMessage({\n tool_call_id: tool_call.id,\n name: tool_call.name,\n content: output || '',\n }),\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n \n if (content) {\n messages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n messages.push(new AIMessage({ content: currentContent }));\n }\n \n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (let originalIndex = 0; originalIndex < payload.length; originalIndex++) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n \n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] = tokenCount - (countPerMessage * (resultIndices.length - 1));\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap ? updatedIndexTokenCountMap : undefined\n };\n};\n\n/**\n * Formats an array of messages for LangChain, making sure all content fields are strings\n * @param {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} payload - The array of messages to format.\n * @returns {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} - The array of formatted LangChain messages, including ToolMessages for tool calls.\n */\nexport const formatContentStrings = (payload: Array<BaseMessage>): Array<BaseMessage> => {\n // Create a copy of the payload to avoid modifying the original\n const result = [...payload];\n\n for (const message of result) {\n if (typeof message.content === 'string') {\n continue;\n }\n\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n // Reduce text types to a single string, ignore all other types\n const content = message.content.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n\n message.content = content.trim();\n }\n\n return result;\n};\n"],"names":[],"mappings":";;;AAkBA;;;;;AAKG;AACI,MAAM,mBAAmB,GAAG,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAuB,KAKtF;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE;KACV;AAED,IAAA,IAAI,QAAQ,KAAK,SAAS,CAAC,SAAS,EAAE;QACpC,MAAM,C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