@librechat/agents 2.3.95 → 2.3.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/providers.cjs +6 -1
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/providers.mjs +6 -1
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +1 -0
- package/dist/types/types/llm.d.ts +4 -2
- package/package.json +12 -25
- package/src/common/enum.ts +4 -3
- package/src/llm/anthropic/utils/message_inputs.ts +1 -1
- package/src/llm/providers.ts +12 -3
- package/src/scripts/simple.ts +16 -0
- package/src/types/llm.ts +40 -24
- package/src/utils/llmConfig.ts +18 -6
package/dist/cjs/common/enum.cjs
CHANGED
|
@@ -63,6 +63,7 @@ exports.Providers = void 0;
|
|
|
63
63
|
Providers["BEDROCK"] = "bedrock";
|
|
64
64
|
Providers["ANTHROPIC"] = "anthropic";
|
|
65
65
|
Providers["MISTRALAI"] = "mistralai";
|
|
66
|
+
Providers["MISTRAL"] = "mistral";
|
|
66
67
|
Providers["OLLAMA"] = "ollama";
|
|
67
68
|
Providers["GOOGLE"] = "google";
|
|
68
69
|
Providers["AZURE"] = "azureOpenAI";
|
|
@@ -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] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\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'
|
|
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] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\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 MISTRAL = 'mistral',\n OLLAMA = 'ollama',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\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 /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\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,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,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,I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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;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.cjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n isAIMessage,\n HumanMessage,\n SystemMessage,\n MessageContent,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n AnthropicToolResponse,\n AnthropicMessageParam,\n AnthropicTextBlockParam,\n AnthropicImageBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicMessageCreateParams,\n AnthropicToolResultBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n} from '@/llm/anthropic/types';\n\nfunction _formatImage(imageUrl: string): { type: string; media_type: string; data: string } {\n const regex = /^data:(image\\/.+);base64,(.+)$/;\n const match = imageUrl.match(regex);\n if (match === null) {\n throw new Error(\n [\n 'Anthropic only supports base64-encoded images currently.',\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n ].join('\\n\\n')\n );\n }\n return {\n type: 'base64',\n media_type: match[1] ?? '',\n data: match[2] ?? '',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1] as BaseMessage | undefined;\n if (\n previousMessage &&\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n previousMessage.content.push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: _formatContent(message.content),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n return {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _formatContent(content: MessageContent): string | Record<string, any>[] {\n const toolTypes = ['tool_use', 'tool_result', 'input_json_delta'];\n const textTypes = ['text', 'text_delta'];\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n if (typeof contentPart.image_url === 'string') {\n source = _formatImage(contentPart.image_url);\n } else {\n source = _formatImage(contentPart.image_url.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) != null &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type) != null) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n // no-op\n }\n }\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else {\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks;\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n if (typeof message.content === 'string') {\n if (message.content === '') {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: 'text', text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages as AnthropicMessageCreateParams['messages']),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages?: AnthropicMessageCreateParams['messages']): AnthropicMessageParam[] {\n if (!messages || messages.length <= 1) {\n return messages ?? [];\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n > => {\n if (typeof content === 'string') {\n return [\n {\n type: 'text',\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]): boolean => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}"],"names":["messages","HumanMessage","isAIMessage"],"mappings":";;;;AAAA;AACA;;AAEG;AAwBH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,KAAK,GAAG,gCAAgC;IAC9C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC;AACnC,IAAA,IAAI,KAAK,KAAK,IAAI,EAAE;QAClB,MAAM,IAAI,KAAK,CACb;YACE,0DAA0D;YAC1D,8CAA8C;AAC/C,SAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;;IAEH,OAAO;AACL,QAAA,IAAI,EAAE,QAAQ;AACd,QAAA,UAA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QACE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;AAC1B,YAAA,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,aAAa,CAAC;AAE5D,KAAC;AAED,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;AAC3C,QAAA,MAAM,WAAW,GAAG,QAAQ,CAAC,CAAC,CAAC;QAE/B,IACE,mBAAmB,CAAC,cAAc,CAAC;AACnC,YAAA,mBAAmB,CAAC,WAAW,CAAC,EAChC;;AAEA,YAAA,cAAc,GAAG;AACf,gBAAA,GAAG,cAAc;AACjB,gBAAA,OAAO,EAAE;AACP,oBAAA,GAAG,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC;AAC3C,oBAAA,GAAG,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC;AACzC,iBAAA;aACF;;aACI;AACL,YAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;YAC3B,cAAc,GAAG,WAAW;;;AAIhC,IAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;AAC3B,IAAA,OAAO,MAAM;AACf;;;;;"}
|
|
1
|
+
{"version":3,"file":"message_inputs.cjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n isAIMessage,\n HumanMessage,\n SystemMessage,\n MessageContent,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n AnthropicToolResponse,\n AnthropicMessageParam,\n AnthropicTextBlockParam,\n AnthropicImageBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicMessageCreateParams,\n AnthropicToolResultBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n} from '@/llm/anthropic/types';\n\nfunction _formatImage(imageUrl: string): { type: string; media_type: string; data: string } {\n const regex = /^data:(image\\/.+);base64,(.+)$/;\n const match = imageUrl.match(regex);\n if (match === null) {\n throw new Error(\n [\n 'Anthropic only supports base64-encoded images currently.',\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n ].join('\\n\\n')\n );\n }\n return {\n type: 'base64',\n media_type: match[1] ?? '',\n data: match[2] ?? '',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1] as BaseMessage | undefined;\n if (\n previousMessage &&\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n previousMessage.content.push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: _formatContent(message.content),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n return {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _formatContent(content: MessageContent): string | Record<string, any>[] {\n const toolTypes = ['tool_use', 'tool_result', 'input_json_delta'];\n const textTypes = ['text', 'text_delta'];\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n if (typeof contentPart.image_url === 'string') {\n source = _formatImage(contentPart.image_url);\n } else {\n source = _formatImage(contentPart.image_url.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) != null &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type) != null) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else {\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks;\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n if (typeof message.content === 'string') {\n if (message.content === '') {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: 'text', text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages as AnthropicMessageCreateParams['messages']),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages?: AnthropicMessageCreateParams['messages']): AnthropicMessageParam[] {\n if (!messages || messages.length <= 1) {\n return messages ?? [];\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n > => {\n if (typeof content === 'string') {\n return [\n {\n type: 'text',\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]): boolean => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);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f;;;;;"}
|
|
@@ -22,6 +22,7 @@ const llmProviders = {
|
|
|
22
22
|
[_enum.Providers.VERTEXAI]: googleVertexai.ChatVertexAI,
|
|
23
23
|
[_enum.Providers.DEEPSEEK]: deepseek.ChatDeepSeek,
|
|
24
24
|
[_enum.Providers.MISTRALAI]: mistralai.ChatMistralAI,
|
|
25
|
+
[_enum.Providers.MISTRAL]: mistralai.ChatMistralAI,
|
|
25
26
|
[_enum.Providers.ANTHROPIC]: llm$1.CustomAnthropic,
|
|
26
27
|
[_enum.Providers.OPENROUTER]: llm.ChatOpenRouter,
|
|
27
28
|
[_enum.Providers.BEDROCK_LEGACY]: web.BedrockChat,
|
|
@@ -29,7 +30,11 @@ const llmProviders = {
|
|
|
29
30
|
// [Providers.ANTHROPIC]: ChatAnthropic,
|
|
30
31
|
[_enum.Providers.GOOGLE]: googleGenai.ChatGoogleGenerativeAI,
|
|
31
32
|
};
|
|
32
|
-
const manualToolStreamProviders = new Set([
|
|
33
|
+
const manualToolStreamProviders = new Set([
|
|
34
|
+
_enum.Providers.ANTHROPIC,
|
|
35
|
+
_enum.Providers.BEDROCK,
|
|
36
|
+
_enum.Providers.OLLAMA,
|
|
37
|
+
]);
|
|
33
38
|
const getChatModelClass = (provider) => {
|
|
34
39
|
const ChatModelClass = llmProviders[provider];
|
|
35
40
|
if (!ChatModelClass) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.cjs","sources":["../../../src/llm/providers.ts"],"sourcesContent":["// src/llm/providers.ts\nimport { ChatXAI } from '@langchain/xai';\nimport { ChatOllama } from '@langchain/ollama';\nimport { ChatDeepSeek } from '@langchain/deepseek';\nimport { ChatMistralAI } from '@langchain/mistralai';\nimport { ChatBedrockConverse } from '@langchain/aws';\n// import { ChatAnthropic } from '@langchain/anthropic';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { BedrockChat } from '@langchain/community/chat_models/bedrock/web';\nimport type {
|
|
1
|
+
{"version":3,"file":"providers.cjs","sources":["../../../src/llm/providers.ts"],"sourcesContent":["// src/llm/providers.ts\nimport { ChatXAI } from '@langchain/xai';\nimport { ChatOllama } from '@langchain/ollama';\nimport { ChatDeepSeek } from '@langchain/deepseek';\nimport { ChatMistralAI } from '@langchain/mistralai';\nimport { ChatBedrockConverse } from '@langchain/aws';\n// import { ChatAnthropic } from '@langchain/anthropic';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { BedrockChat } from '@langchain/community/chat_models/bedrock/web';\nimport type {\n ChatModelConstructorMap,\n ProviderOptionsMap,\n ChatModelMap,\n} from '@/types';\nimport { CustomAnthropic } from '@/llm/anthropic/llm';\nimport { ChatOpenRouter } from '@/llm/openrouter/llm';\nimport { Providers } from '@/common';\n\nexport const llmProviders: Partial<ChatModelConstructorMap> = {\n [Providers.XAI]: ChatXAI,\n [Providers.OPENAI]: ChatOpenAI,\n [Providers.OLLAMA]: ChatOllama,\n [Providers.AZURE]: AzureChatOpenAI,\n [Providers.VERTEXAI]: ChatVertexAI,\n [Providers.DEEPSEEK]: ChatDeepSeek,\n [Providers.MISTRALAI]: ChatMistralAI,\n [Providers.MISTRAL]: ChatMistralAI,\n [Providers.ANTHROPIC]: CustomAnthropic,\n [Providers.OPENROUTER]: ChatOpenRouter,\n [Providers.BEDROCK_LEGACY]: BedrockChat,\n [Providers.BEDROCK]: ChatBedrockConverse,\n // [Providers.ANTHROPIC]: ChatAnthropic,\n [Providers.GOOGLE]: ChatGoogleGenerativeAI,\n};\n\nexport const manualToolStreamProviders = new Set<Providers | string>([\n Providers.ANTHROPIC,\n Providers.BEDROCK,\n Providers.OLLAMA,\n]);\n\nexport const getChatModelClass = <P extends Providers>(\n provider: P\n): new (config: ProviderOptionsMap[P]) => ChatModelMap[P] => {\n const ChatModelClass = llmProviders[provider];\n if (!ChatModelClass) {\n throw new Error(`Unsupported LLM provider: ${provider}`);\n }\n\n return ChatModelClass;\n};\n"],"names":["Providers","ChatXAI","ChatOpenAI","ChatOllama","AzureChatOpenAI","ChatVertexAI","ChatDeepSeek","ChatMistralAI","CustomAnthropic","ChatOpenRouter","BedrockChat","ChatBedrockConverse","ChatGoogleGenerativeAI"],"mappings":";;;;;;;;;;;;;;;AAAA;AAoBa,MAAA,YAAY,GAAqC;AAC5D,IAAA,CAACA,eAAS,CAAC,GAAG,GAAGC,WAAO;AACxB,IAAA,CAACD,eAAS,CAAC,MAAM,GAAGE,iBAAU;AAC9B,IAAA,CAACF,eAAS,CAAC,MAAM,GAAGG,iBAAU;AAC9B,IAAA,CAACH,eAAS,CAAC,KAAK,GAAGI,sBAAe;AAClC,IAAA,CAACJ,eAAS,CAAC,QAAQ,GAAGK,2BAAY;AAClC,IAAA,CAACL,eAAS,CAAC,QAAQ,GAAGM,qBAAY;AAClC,IAAA,CAACN,eAAS,CAAC,SAAS,GAAGO,uBAAa;AACpC,IAAA,CAACP,eAAS,CAAC,OAAO,GAAGO,uBAAa;AAClC,IAAA,CAACP,eAAS,CAAC,SAAS,GAAGQ,qBAAe;AACtC,IAAA,CAACR,eAAS,CAAC,UAAU,GAAGS,kBAAc;AACtC,IAAA,CAACT,eAAS,CAAC,cAAc,GAAGU,eAAW;AACvC,IAAA,CAACV,eAAS,CAAC,OAAO,GAAGW,uBAAmB;;AAExC,IAAA,CAACX,eAAS,CAAC,MAAM,GAAGY,kCAAsB;;AAG/B,MAAA,yBAAyB,GAAG,IAAI,GAAG,CAAqB;AACnE,IAAAZ,eAAS,CAAC,SAAS;AACnB,IAAAA,eAAS,CAAC,OAAO;AACjB,IAAAA,eAAS,CAAC,MAAM;AACjB,CAAA;AAEY,MAAA,iBAAiB,GAAG,CAC/B,QAAW,KAC+C;AAC1D,IAAA,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC;IAC7C,IAAI,CAAC,cAAc,EAAE;AACnB,QAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,QAAQ,CAAA,CAAE,CAAC;;AAG1D,IAAA,OAAO,cAAc;AACvB;;;;;;"}
|
package/dist/esm/common/enum.mjs
CHANGED
|
@@ -61,6 +61,7 @@ var Providers;
|
|
|
61
61
|
Providers["BEDROCK"] = "bedrock";
|
|
62
62
|
Providers["ANTHROPIC"] = "anthropic";
|
|
63
63
|
Providers["MISTRALAI"] = "mistralai";
|
|
64
|
+
Providers["MISTRAL"] = "mistral";
|
|
64
65
|
Providers["OLLAMA"] = "ollama";
|
|
65
66
|
Providers["GOOGLE"] = "google";
|
|
66
67
|
Providers["AZURE"] = "azureOpenAI";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.mjs","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] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\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'
|
|
1
|
+
{"version":3,"file":"enum.mjs","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] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\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 MISTRAL = 'mistral',\n OLLAMA = 'ollama',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\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 /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\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":[],"mappings":"AAAA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kBAAqC;;AAErC,IAAA,aAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACzB,CAAC,EAPW,aAAa,KAAb,aAAa,GAOxB,EAAA,CAAA,CAAA;IAEW;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,EArBW,QAAQ,KAAR,QAAQ,GAqBnB,EAAA,CAAA,CAAA;IAEW;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,EAJW,SAAS,KAAT,SAAS,GAIpB,EAAA,CAAA,CAAA;IAEW;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACvC,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACzC,CAAC,EAHW,MAAM,KAAN,MAAM,GAGjB,EAAA,CAAA,CAAA;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.mjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n isAIMessage,\n HumanMessage,\n SystemMessage,\n MessageContent,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n AnthropicToolResponse,\n AnthropicMessageParam,\n AnthropicTextBlockParam,\n AnthropicImageBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicMessageCreateParams,\n AnthropicToolResultBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n} from '@/llm/anthropic/types';\n\nfunction _formatImage(imageUrl: string): { type: string; media_type: string; data: string } {\n const regex = /^data:(image\\/.+);base64,(.+)$/;\n const match = imageUrl.match(regex);\n if (match === null) {\n throw new Error(\n [\n 'Anthropic only supports base64-encoded images currently.',\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n ].join('\\n\\n')\n );\n }\n return {\n type: 'base64',\n media_type: match[1] ?? '',\n data: match[2] ?? '',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1] as BaseMessage | undefined;\n if (\n previousMessage &&\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n previousMessage.content.push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: _formatContent(message.content),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n return {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _formatContent(content: MessageContent): string | Record<string, any>[] {\n const toolTypes = ['tool_use', 'tool_result', 'input_json_delta'];\n const textTypes = ['text', 'text_delta'];\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n if (typeof contentPart.image_url === 'string') {\n source = _formatImage(contentPart.image_url);\n } else {\n source = _formatImage(contentPart.image_url.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) != null &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type) != null) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n // no-op\n }\n }\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else {\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks;\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n if (typeof message.content === 'string') {\n if (message.content === '') {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: 'text', text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages as AnthropicMessageCreateParams['messages']),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages?: AnthropicMessageCreateParams['messages']): AnthropicMessageParam[] {\n if (!messages || messages.length <= 1) {\n return messages ?? [];\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n > => {\n if (typeof content === 'string') {\n return [\n {\n type: 'text',\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]): boolean => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}"],"names":[],"mappings":";;AAAA;AACA;;AAEG;AAwBH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,KAAK,GAAG,gCAAgC;IAC9C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC;AACnC,IAAA,IAAI,KAAK,KAAK,IAAI,EAAE;QAClB,MAAM,IAAI,KAAK,CACb;YACE,0DAA0D;YAC1D,8CAA8C;AAC/C,SAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;;IAEH,OAAO;AACL,QAAA,IAAI,EAAE,QAAQ;AACd,QAAA,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE;AAC1B,QAAA,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE;;KAEd;AACV;AAEA,SAAS,sBAAsB,CAC7B,QAAuB,EAAA;;IAGvB,MAAM,WAAW,GAAG,EAAE;AACtB,IAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;AAC9B,QAAA,IAAI,OAAO,CAAC,QAAQ,EAAE,KAAK,MAAM,EAAE;AACjC,YAAA,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;gBACvC,MAAM,eAAe,GAAG,WAAW,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAA4B;AACtF,gBAAA,IACE,eAAe;AACf,oBAAA,eAAe,CAAC,QAAQ,EAAE,KAAK,OAAO;AACtC,oBAAA,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC;AACtC,oBAAA,MAAM,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;oBACpC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,aAAa,EACjD;;AAEA,oBAAA,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC;A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O,MAAM;AACf;;;;"}
|
|
1
|
+
{"version":3,"file":"message_inputs.mjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n isAIMessage,\n HumanMessage,\n SystemMessage,\n MessageContent,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n AnthropicToolResponse,\n AnthropicMessageParam,\n AnthropicTextBlockParam,\n AnthropicImageBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicMessageCreateParams,\n AnthropicToolResultBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n} from '@/llm/anthropic/types';\n\nfunction _formatImage(imageUrl: string): { type: string; media_type: string; data: string } {\n const regex = /^data:(image\\/.+);base64,(.+)$/;\n const match = imageUrl.match(regex);\n if (match === null) {\n throw new Error(\n [\n 'Anthropic only supports base64-encoded images currently.',\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n ].join('\\n\\n')\n );\n }\n return {\n type: 'base64',\n media_type: match[1] ?? '',\n data: match[2] ?? '',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1] as BaseMessage | undefined;\n if (\n previousMessage &&\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n previousMessage.content.push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: _formatContent(message.content),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n return {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _formatContent(content: MessageContent): string | Record<string, any>[] {\n const toolTypes = ['tool_use', 'tool_result', 'input_json_delta'];\n const textTypes = ['text', 'text_delta'];\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n if (typeof contentPart.image_url === 'string') {\n source = _formatImage(contentPart.image_url);\n } else {\n source = _formatImage(contentPart.image_url.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) != null &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type) != null) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else {\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks;\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n if (typeof message.content === 'string') {\n if (message.content === '') {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: 'text', text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message.content),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages as AnthropicMessageCreateParams['messages']),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages?: AnthropicMessageCreateParams['messages']): AnthropicMessageParam[] {\n if (!messages || messages.length <= 1) {\n return messages ?? [];\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n > => {\n if (typeof content === 'string') {\n return [\n {\n type: 'text',\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]): boolean => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}"],"names":[],"mappings":";;AAAA;AACA;;AAEG;AAwBH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,KAAK,GAAG,gCAAgC;IAC9C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC;AACnC,IAAA,IAAI,KAAK,KAAK,IAAI,EAAE;QAClB,MAAM,IAAI,KAAK,CACb;YACE,0DAA0D;YAC1D,8CAA8C;AAC/C,SAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;;IAEH,OAAO;AACL,QAAA,IAAI,EAAE,QAAQ;AACd,QAAA,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE;AAC1B,QAAA,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE;;KAEd;AACV;AAEA,SAAS,sBAAsB,CAC7B,QAAuB,EAAA;;IAGvB,MAAM,WAAW,GAAG,EAAE;AACtB,IAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;AAC9B,QAAA,IAAI,OAAO,CAAC,QAAQ,EAAE,KAAK,MAAM,EAAE;AACjC,YAAA,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;gBACvC,MAAM,eAAe,GAAG,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,cAAc,CAAC;AACnC,YAAA,mBAAmB,CAAC,WAAW,CAAC,EAChC;;AAEA,YAAA,cAAc,GAAG;AACf,gBAAA,GAAG,cAAc;AACjB,gBAAA,OAAO,EAAE;AACP,oBAAA,GAAG,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC;AAC3C,oBAAA,GAAG,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC;AACzC,iBAAA;aACF;;aACI;AACL,YAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;YAC3B,cAAc,GAAG,WAAW;;;AAIhC,IAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;AAC3B,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
@@ -20,6 +20,7 @@ const llmProviders = {
|
|
|
20
20
|
[Providers.VERTEXAI]: ChatVertexAI,
|
|
21
21
|
[Providers.DEEPSEEK]: ChatDeepSeek,
|
|
22
22
|
[Providers.MISTRALAI]: ChatMistralAI,
|
|
23
|
+
[Providers.MISTRAL]: ChatMistralAI,
|
|
23
24
|
[Providers.ANTHROPIC]: CustomAnthropic,
|
|
24
25
|
[Providers.OPENROUTER]: ChatOpenRouter,
|
|
25
26
|
[Providers.BEDROCK_LEGACY]: BedrockChat,
|
|
@@ -27,7 +28,11 @@ const llmProviders = {
|
|
|
27
28
|
// [Providers.ANTHROPIC]: ChatAnthropic,
|
|
28
29
|
[Providers.GOOGLE]: ChatGoogleGenerativeAI,
|
|
29
30
|
};
|
|
30
|
-
const manualToolStreamProviders = new Set([
|
|
31
|
+
const manualToolStreamProviders = new Set([
|
|
32
|
+
Providers.ANTHROPIC,
|
|
33
|
+
Providers.BEDROCK,
|
|
34
|
+
Providers.OLLAMA,
|
|
35
|
+
]);
|
|
31
36
|
const getChatModelClass = (provider) => {
|
|
32
37
|
const ChatModelClass = llmProviders[provider];
|
|
33
38
|
if (!ChatModelClass) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.mjs","sources":["../../../src/llm/providers.ts"],"sourcesContent":["// src/llm/providers.ts\nimport { ChatXAI } from '@langchain/xai';\nimport { ChatOllama } from '@langchain/ollama';\nimport { ChatDeepSeek } from '@langchain/deepseek';\nimport { ChatMistralAI } from '@langchain/mistralai';\nimport { ChatBedrockConverse } from '@langchain/aws';\n// import { ChatAnthropic } from '@langchain/anthropic';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { BedrockChat } from '@langchain/community/chat_models/bedrock/web';\nimport type {
|
|
1
|
+
{"version":3,"file":"providers.mjs","sources":["../../../src/llm/providers.ts"],"sourcesContent":["// src/llm/providers.ts\nimport { ChatXAI } from '@langchain/xai';\nimport { ChatOllama } from '@langchain/ollama';\nimport { ChatDeepSeek } from '@langchain/deepseek';\nimport { ChatMistralAI } from '@langchain/mistralai';\nimport { ChatBedrockConverse } from '@langchain/aws';\n// import { ChatAnthropic } from '@langchain/anthropic';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { BedrockChat } from '@langchain/community/chat_models/bedrock/web';\nimport type {\n ChatModelConstructorMap,\n ProviderOptionsMap,\n ChatModelMap,\n} from '@/types';\nimport { CustomAnthropic } from '@/llm/anthropic/llm';\nimport { ChatOpenRouter } from '@/llm/openrouter/llm';\nimport { Providers } from '@/common';\n\nexport const llmProviders: Partial<ChatModelConstructorMap> = {\n [Providers.XAI]: ChatXAI,\n [Providers.OPENAI]: ChatOpenAI,\n [Providers.OLLAMA]: ChatOllama,\n [Providers.AZURE]: AzureChatOpenAI,\n [Providers.VERTEXAI]: ChatVertexAI,\n [Providers.DEEPSEEK]: ChatDeepSeek,\n [Providers.MISTRALAI]: ChatMistralAI,\n [Providers.MISTRAL]: ChatMistralAI,\n [Providers.ANTHROPIC]: CustomAnthropic,\n [Providers.OPENROUTER]: ChatOpenRouter,\n [Providers.BEDROCK_LEGACY]: BedrockChat,\n [Providers.BEDROCK]: ChatBedrockConverse,\n // [Providers.ANTHROPIC]: ChatAnthropic,\n [Providers.GOOGLE]: ChatGoogleGenerativeAI,\n};\n\nexport const manualToolStreamProviders = new Set<Providers | string>([\n Providers.ANTHROPIC,\n Providers.BEDROCK,\n Providers.OLLAMA,\n]);\n\nexport const getChatModelClass = <P extends Providers>(\n provider: P\n): new (config: ProviderOptionsMap[P]) => ChatModelMap[P] => {\n const ChatModelClass = llmProviders[provider];\n if (!ChatModelClass) {\n throw new Error(`Unsupported LLM provider: ${provider}`);\n }\n\n return ChatModelClass;\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;AAAA;AAoBa,MAAA,YAAY,GAAqC;AAC5D,IAAA,CAAC,SAAS,CAAC,GAAG,GAAG,OAAO;AACxB,IAAA,CAAC,SAAS,CAAC,MAAM,GAAG,UAAU;AAC9B,IAAA,CAAC,SAAS,CAAC,MAAM,GAAG,UAAU;AAC9B,IAAA,CAAC,SAAS,CAAC,KAAK,GAAG,eAAe;AAClC,IAAA,CAAC,SAAS,CAAC,QAAQ,GAAG,YAAY;AAClC,IAAA,CAAC,SAAS,CAAC,QAAQ,GAAG,YAAY;AAClC,IAAA,CAAC,SAAS,CAAC,SAAS,GAAG,aAAa;AACpC,IAAA,CAAC,SAAS,CAAC,OAAO,GAAG,aAAa;AAClC,IAAA,CAAC,SAAS,CAAC,SAAS,GAAG,eAAe;AACtC,IAAA,CAAC,SAAS,CAAC,UAAU,GAAG,cAAc;AACtC,IAAA,CAAC,SAAS,CAAC,cAAc,GAAG,WAAW;AACvC,IAAA,CAAC,SAAS,CAAC,OAAO,GAAG,mBAAmB;;AAExC,IAAA,CAAC,SAAS,CAAC,MAAM,GAAG,sBAAsB;;AAG/B,MAAA,yBAAyB,GAAG,IAAI,GAAG,CAAqB;AACnE,IAAA,SAAS,CAAC,SAAS;AACnB,IAAA,SAAS,CAAC,OAAO;AACjB,IAAA,SAAS,CAAC,MAAM;AACjB,CAAA;AAEY,MAAA,iBAAiB,GAAG,CAC/B,QAAW,KAC+C;AAC1D,IAAA,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC;IAC7C,IAAI,CAAC,cAAc,EAAE;AACnB,QAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,QAAQ,CAAA,CAAE,CAAC;;AAG1D,IAAA,OAAO,cAAc;AACvB;;;;"}
|
|
@@ -25,14 +25,14 @@ import type { ChatXAIInput } from '@langchain/xai';
|
|
|
25
25
|
import type { ChatOpenRouterCallOptions } from '@/llm/openrouter/llm';
|
|
26
26
|
import { ChatOpenRouter } from '@/llm/openrouter/llm';
|
|
27
27
|
import { Providers } from '@/common';
|
|
28
|
-
export type AzureClientOptions =
|
|
28
|
+
export type AzureClientOptions = Partial<OpenAIChatInput> & Partial<AzureOpenAIInput> & {
|
|
29
29
|
openAIApiKey?: string;
|
|
30
30
|
openAIApiVersion?: string;
|
|
31
31
|
openAIBasePath?: string;
|
|
32
32
|
deploymentName?: string;
|
|
33
33
|
} & BaseChatModelParams & {
|
|
34
34
|
configuration?: OAIClientOptions;
|
|
35
|
-
}
|
|
35
|
+
};
|
|
36
36
|
export type ThinkingConfig = AnthropicInput['thinking'];
|
|
37
37
|
export type ChatOpenAIToolType = BindToolsInput | OpenAIClient.ChatCompletionTool;
|
|
38
38
|
export type CommonToolType = StructuredTool | ChatOpenAIToolType;
|
|
@@ -66,6 +66,7 @@ export type ProviderOptionsMap = {
|
|
|
66
66
|
[Providers.DEEPSEEK]: DeepSeekClientOptions;
|
|
67
67
|
[Providers.ANTHROPIC]: AnthropicClientOptions;
|
|
68
68
|
[Providers.MISTRALAI]: MistralAIClientOptions;
|
|
69
|
+
[Providers.MISTRAL]: MistralAIClientOptions;
|
|
69
70
|
[Providers.OPENROUTER]: ChatOpenRouterCallOptions;
|
|
70
71
|
[Providers.BEDROCK_LEGACY]: BedrockClientOptions;
|
|
71
72
|
[Providers.BEDROCK]: BedrockConverseClientOptions;
|
|
@@ -79,6 +80,7 @@ export type ChatModelMap = {
|
|
|
79
80
|
[Providers.VERTEXAI]: ChatVertexAI;
|
|
80
81
|
[Providers.ANTHROPIC]: ChatAnthropic;
|
|
81
82
|
[Providers.MISTRALAI]: ChatMistralAI;
|
|
83
|
+
[Providers.MISTRAL]: ChatMistralAI;
|
|
82
84
|
[Providers.OPENROUTER]: ChatOpenRouter;
|
|
83
85
|
[Providers.BEDROCK_LEGACY]: BedrockChat;
|
|
84
86
|
[Providers.BEDROCK]: ChatBedrockConverse;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@librechat/agents",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.96",
|
|
4
4
|
"main": "./dist/cjs/main.cjs",
|
|
5
5
|
"module": "./dist/esm/main.mjs",
|
|
6
6
|
"types": "./dist/types/index.d.ts",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"image": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/image.ts --provider 'google' --name 'Jo' --location 'New York, NY'",
|
|
48
48
|
"code_exec_files": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_files.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
|
|
49
49
|
"code_exec_simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_simple.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
|
|
50
|
-
"simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider '
|
|
50
|
+
"simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'mistral' --name 'Jo' --location 'New York, NY'",
|
|
51
51
|
"caching": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/caching.ts --name 'Jo' --location 'New York, NY'",
|
|
52
52
|
"thinking": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/thinking.ts --name 'Jo' --location 'New York, NY'",
|
|
53
53
|
"memory": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/memory.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
|
|
@@ -71,35 +71,22 @@
|
|
|
71
71
|
"format": "prettier --write ."
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@
|
|
75
|
-
"@aws-sdk/credential-provider-node": "^3.613.0",
|
|
76
|
-
"@aws-sdk/types": "^3.609.0",
|
|
77
|
-
"@langchain/anthropic": "^0.3.14",
|
|
74
|
+
"@langchain/anthropic": "^0.3.16",
|
|
78
75
|
"@langchain/aws": "^0.1.7",
|
|
79
|
-
"@langchain/community": "^0.3.
|
|
76
|
+
"@langchain/community": "^0.3.39",
|
|
80
77
|
"@langchain/core": "^0.3.40",
|
|
81
78
|
"@langchain/deepseek": "^0.0.1",
|
|
82
|
-
"@langchain/google-genai": "^0.
|
|
83
|
-
"@langchain/google-vertexai": "^0.2.
|
|
84
|
-
"@langchain/langgraph": "^0.2.
|
|
85
|
-
"@langchain/mistralai": "^0.0
|
|
86
|
-
"@langchain/ollama": "^0.
|
|
87
|
-
"@langchain/openai": "^0.
|
|
79
|
+
"@langchain/google-genai": "^0.2.2",
|
|
80
|
+
"@langchain/google-vertexai": "^0.2.3",
|
|
81
|
+
"@langchain/langgraph": "^0.2.62",
|
|
82
|
+
"@langchain/mistralai": "^0.2.0",
|
|
83
|
+
"@langchain/ollama": "^0.2.0",
|
|
84
|
+
"@langchain/openai": "^0.5.3",
|
|
88
85
|
"@langchain/xai": "^0.0.2",
|
|
89
|
-
"@smithy/eventstream-codec": "^2.2.0",
|
|
90
|
-
"@smithy/protocol-http": "^3.0.6",
|
|
91
|
-
"@smithy/signature-v4": "^2.0.10",
|
|
92
|
-
"@smithy/util-utf8": "^2.0.0",
|
|
93
86
|
"dotenv": "^16.4.7",
|
|
94
87
|
"https-proxy-agent": "^7.0.6",
|
|
95
88
|
"nanoid": "^3.3.7"
|
|
96
89
|
},
|
|
97
|
-
"resolutions": {
|
|
98
|
-
"@smithy/eventstream-codec": "^2.2.0",
|
|
99
|
-
"@smithy/protocol-http": "^3.0.6",
|
|
100
|
-
"@smithy/signature-v4": "^2.0.10",
|
|
101
|
-
"@smithy/util-utf8": "^2.0.0"
|
|
102
|
-
},
|
|
103
90
|
"imports": {
|
|
104
91
|
"@/*": "./src/*",
|
|
105
92
|
"~/*": "./*"
|
|
@@ -107,7 +94,7 @@
|
|
|
107
94
|
"devDependencies": {
|
|
108
95
|
"@eslint/compat": "^1.2.7",
|
|
109
96
|
"@rollup/plugin-alias": "^5.1.0",
|
|
110
|
-
"@rollup/plugin-commonjs": "^
|
|
97
|
+
"@rollup/plugin-commonjs": "^28.0.3",
|
|
111
98
|
"@rollup/plugin-json": "^6.1.0",
|
|
112
99
|
"@rollup/plugin-node-resolve": "^15.2.3",
|
|
113
100
|
"@rollup/plugin-terser": "^0.4.4",
|
|
@@ -128,7 +115,7 @@
|
|
|
128
115
|
"rollup": "^4.34.6",
|
|
129
116
|
"rollup-plugin-cleandir": "^2.0.0",
|
|
130
117
|
"rollup-plugin-obfuscator": "^1.1.0",
|
|
131
|
-
"ts-jest": "^29.
|
|
118
|
+
"ts-jest": "^29.3.1",
|
|
132
119
|
"ts-node": "^10.9.2",
|
|
133
120
|
"tsc-alias": "^1.8.10",
|
|
134
121
|
"tsconfig-paths": "^4.2.0",
|
package/src/common/enum.ts
CHANGED
|
@@ -67,7 +67,7 @@ export enum GraphEvents {
|
|
|
67
67
|
PROMPT_START = 'on_prompt_start',
|
|
68
68
|
|
|
69
69
|
/** Emitted when a prompt completes its processing. */
|
|
70
|
-
PROMPT_END = 'on_prompt_end'
|
|
70
|
+
PROMPT_END = 'on_prompt_end',
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
export enum Providers {
|
|
@@ -77,6 +77,7 @@ export enum Providers {
|
|
|
77
77
|
BEDROCK = 'bedrock',
|
|
78
78
|
ANTHROPIC = 'anthropic',
|
|
79
79
|
MISTRALAI = 'mistralai',
|
|
80
|
+
MISTRAL = 'mistral',
|
|
80
81
|
OLLAMA = 'ollama',
|
|
81
82
|
GOOGLE = 'google',
|
|
82
83
|
AZURE = 'azureOpenAI',
|
|
@@ -104,7 +105,7 @@ export enum CommonEvents {
|
|
|
104
105
|
|
|
105
106
|
export enum StepTypes {
|
|
106
107
|
TOOL_CALLS = 'tool_calls',
|
|
107
|
-
MESSAGE_CREATION = 'message_creation'
|
|
108
|
+
MESSAGE_CREATION = 'message_creation',
|
|
108
109
|
}
|
|
109
110
|
|
|
110
111
|
export enum ContentTypes {
|
|
@@ -162,5 +163,5 @@ export enum Constants {
|
|
|
162
163
|
|
|
163
164
|
export enum EnvVar {
|
|
164
165
|
CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',
|
|
165
|
-
CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL'
|
|
166
|
+
CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',
|
|
166
167
|
}
|
package/src/llm/providers.ts
CHANGED
|
@@ -9,7 +9,11 @@ import { ChatVertexAI } from '@langchain/google-vertexai';
|
|
|
9
9
|
import { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';
|
|
10
10
|
import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
|
|
11
11
|
import { BedrockChat } from '@langchain/community/chat_models/bedrock/web';
|
|
12
|
-
import type {
|
|
12
|
+
import type {
|
|
13
|
+
ChatModelConstructorMap,
|
|
14
|
+
ProviderOptionsMap,
|
|
15
|
+
ChatModelMap,
|
|
16
|
+
} from '@/types';
|
|
13
17
|
import { CustomAnthropic } from '@/llm/anthropic/llm';
|
|
14
18
|
import { ChatOpenRouter } from '@/llm/openrouter/llm';
|
|
15
19
|
import { Providers } from '@/common';
|
|
@@ -22,6 +26,7 @@ export const llmProviders: Partial<ChatModelConstructorMap> = {
|
|
|
22
26
|
[Providers.VERTEXAI]: ChatVertexAI,
|
|
23
27
|
[Providers.DEEPSEEK]: ChatDeepSeek,
|
|
24
28
|
[Providers.MISTRALAI]: ChatMistralAI,
|
|
29
|
+
[Providers.MISTRAL]: ChatMistralAI,
|
|
25
30
|
[Providers.ANTHROPIC]: CustomAnthropic,
|
|
26
31
|
[Providers.OPENROUTER]: ChatOpenRouter,
|
|
27
32
|
[Providers.BEDROCK_LEGACY]: BedrockChat,
|
|
@@ -30,7 +35,11 @@ export const llmProviders: Partial<ChatModelConstructorMap> = {
|
|
|
30
35
|
[Providers.GOOGLE]: ChatGoogleGenerativeAI,
|
|
31
36
|
};
|
|
32
37
|
|
|
33
|
-
export const manualToolStreamProviders = new Set<Providers | string>([
|
|
38
|
+
export const manualToolStreamProviders = new Set<Providers | string>([
|
|
39
|
+
Providers.ANTHROPIC,
|
|
40
|
+
Providers.BEDROCK,
|
|
41
|
+
Providers.OLLAMA,
|
|
42
|
+
]);
|
|
34
43
|
|
|
35
44
|
export const getChatModelClass = <P extends Providers>(
|
|
36
45
|
provider: P
|
|
@@ -41,4 +50,4 @@ export const getChatModelClass = <P extends Providers>(
|
|
|
41
50
|
}
|
|
42
51
|
|
|
43
52
|
return ChatModelClass;
|
|
44
|
-
};
|
|
53
|
+
};
|
package/src/scripts/simple.ts
CHANGED
|
@@ -92,6 +92,22 @@ async function testStandardStreaming(): Promise<void> {
|
|
|
92
92
|
};
|
|
93
93
|
|
|
94
94
|
const llmConfig = getLLMConfig(provider);
|
|
95
|
+
if (
|
|
96
|
+
'configuration' in llmConfig &&
|
|
97
|
+
(llmConfig as t.OpenAIClientOptions).configuration != null
|
|
98
|
+
) {
|
|
99
|
+
const openAIConfig = llmConfig as t.OpenAIClientOptions;
|
|
100
|
+
if (openAIConfig.configuration) {
|
|
101
|
+
openAIConfig.configuration.fetch = (
|
|
102
|
+
url: RequestInfo,
|
|
103
|
+
init?: RequestInit
|
|
104
|
+
) => {
|
|
105
|
+
console.log('Fetching:', url);
|
|
106
|
+
return fetch(url, init);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
95
111
|
if (provider === Providers.ANTHROPIC) {
|
|
96
112
|
(llmConfig as t.AnthropicClientOptions).clientOptions = {
|
|
97
113
|
defaultHeaders: {
|
package/src/types/llm.ts
CHANGED
|
@@ -8,9 +8,20 @@ import { ChatBedrockConverse } from '@langchain/aws';
|
|
|
8
8
|
import { ChatVertexAI } from '@langchain/google-vertexai';
|
|
9
9
|
import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
|
|
10
10
|
import { BedrockChat } from '@langchain/community/chat_models/bedrock/web';
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
import {
|
|
12
|
+
ChatOpenAI,
|
|
13
|
+
AzureChatOpenAI,
|
|
14
|
+
ClientOptions as OAIClientOptions,
|
|
15
|
+
} from '@langchain/openai';
|
|
16
|
+
import type {
|
|
17
|
+
BindToolsInput,
|
|
18
|
+
BaseChatModelParams,
|
|
19
|
+
} from '@langchain/core/language_models/chat_models';
|
|
20
|
+
import type {
|
|
21
|
+
ChatOpenAIFields,
|
|
22
|
+
OpenAIChatInput,
|
|
23
|
+
AzureOpenAIInput,
|
|
24
|
+
} from '@langchain/openai';
|
|
14
25
|
import type { BedrockChatFields } from '@langchain/community/chat_models/bedrock/web';
|
|
15
26
|
import type { GoogleGenerativeAIChatInput } from '@langchain/google-genai';
|
|
16
27
|
import type { ChatVertexAIInput } from '@langchain/google-vertexai';
|
|
@@ -27,16 +38,19 @@ import type { ChatOpenRouterCallOptions } from '@/llm/openrouter/llm';
|
|
|
27
38
|
import { ChatOpenRouter } from '@/llm/openrouter/llm';
|
|
28
39
|
import { Providers } from '@/common';
|
|
29
40
|
|
|
30
|
-
export type AzureClientOptions =
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
export type AzureClientOptions = Partial<OpenAIChatInput> &
|
|
42
|
+
Partial<AzureOpenAIInput> & {
|
|
43
|
+
openAIApiKey?: string;
|
|
44
|
+
openAIApiVersion?: string;
|
|
45
|
+
openAIBasePath?: string;
|
|
46
|
+
deploymentName?: string;
|
|
47
|
+
} & BaseChatModelParams & {
|
|
48
|
+
configuration?: OAIClientOptions;
|
|
49
|
+
};
|
|
38
50
|
export type ThinkingConfig = AnthropicInput['thinking'];
|
|
39
|
-
export type ChatOpenAIToolType =
|
|
51
|
+
export type ChatOpenAIToolType =
|
|
52
|
+
| BindToolsInput
|
|
53
|
+
| OpenAIClient.ChatCompletionTool;
|
|
40
54
|
export type CommonToolType = StructuredTool | ChatOpenAIToolType;
|
|
41
55
|
export type AnthropicReasoning = {
|
|
42
56
|
thinking?: ThinkingConfig | boolean;
|
|
@@ -58,17 +72,17 @@ export type DeepSeekClientOptions = ChatDeepSeekCallOptions;
|
|
|
58
72
|
export type XAIClientOptions = ChatXAIInput;
|
|
59
73
|
|
|
60
74
|
export type ClientOptions =
|
|
61
|
-
| OpenAIClientOptions
|
|
62
|
-
| AzureClientOptions
|
|
63
|
-
| OllamaClientOptions
|
|
64
|
-
| AnthropicClientOptions
|
|
65
|
-
| MistralAIClientOptions
|
|
66
|
-
| VertexAIClientOptions
|
|
67
|
-
| BedrockClientOptions
|
|
68
|
-
| BedrockConverseClientOptions
|
|
69
|
-
| GoogleClientOptions
|
|
70
|
-
| DeepSeekClientOptions
|
|
71
|
-
| XAIClientOptions;
|
|
75
|
+
| OpenAIClientOptions
|
|
76
|
+
| AzureClientOptions
|
|
77
|
+
| OllamaClientOptions
|
|
78
|
+
| AnthropicClientOptions
|
|
79
|
+
| MistralAIClientOptions
|
|
80
|
+
| VertexAIClientOptions
|
|
81
|
+
| BedrockClientOptions
|
|
82
|
+
| BedrockConverseClientOptions
|
|
83
|
+
| GoogleClientOptions
|
|
84
|
+
| DeepSeekClientOptions
|
|
85
|
+
| XAIClientOptions;
|
|
72
86
|
|
|
73
87
|
export type LLMConfig = {
|
|
74
88
|
provider: Providers;
|
|
@@ -83,6 +97,7 @@ export type ProviderOptionsMap = {
|
|
|
83
97
|
[Providers.DEEPSEEK]: DeepSeekClientOptions;
|
|
84
98
|
[Providers.ANTHROPIC]: AnthropicClientOptions;
|
|
85
99
|
[Providers.MISTRALAI]: MistralAIClientOptions;
|
|
100
|
+
[Providers.MISTRAL]: MistralAIClientOptions;
|
|
86
101
|
[Providers.OPENROUTER]: ChatOpenRouterCallOptions;
|
|
87
102
|
[Providers.BEDROCK_LEGACY]: BedrockClientOptions;
|
|
88
103
|
[Providers.BEDROCK]: BedrockConverseClientOptions;
|
|
@@ -97,6 +112,7 @@ export type ChatModelMap = {
|
|
|
97
112
|
[Providers.VERTEXAI]: ChatVertexAI;
|
|
98
113
|
[Providers.ANTHROPIC]: ChatAnthropic;
|
|
99
114
|
[Providers.MISTRALAI]: ChatMistralAI;
|
|
115
|
+
[Providers.MISTRAL]: ChatMistralAI;
|
|
100
116
|
[Providers.OPENROUTER]: ChatOpenRouter;
|
|
101
117
|
[Providers.BEDROCK_LEGACY]: BedrockChat;
|
|
102
118
|
[Providers.BEDROCK]: ChatBedrockConverse;
|
|
@@ -112,4 +128,4 @@ export type ChatModelInstance = ChatModelMap[Providers];
|
|
|
112
128
|
|
|
113
129
|
export type ModelWithTools = ChatModelInstance & {
|
|
114
130
|
bindTools(tools: CommonToolType[]): Runnable;
|
|
115
|
-
}
|
|
131
|
+
};
|
package/src/utils/llmConfig.ts
CHANGED
|
@@ -59,7 +59,7 @@ export const llmConfigs: Record<string, t.LLMConfig | undefined> = {
|
|
|
59
59
|
model: 'llama3.2',
|
|
60
60
|
streaming: true,
|
|
61
61
|
streamUsage: true,
|
|
62
|
-
baseUrl: 'http://host.docker.internal:11434'
|
|
62
|
+
baseUrl: 'http://host.docker.internal:11434',
|
|
63
63
|
},
|
|
64
64
|
[Providers.DEEPSEEK]: {
|
|
65
65
|
provider: Providers.DEEPSEEK,
|
|
@@ -73,11 +73,23 @@ export const llmConfigs: Record<string, t.LLMConfig | undefined> = {
|
|
|
73
73
|
streaming: true,
|
|
74
74
|
streamUsage: true,
|
|
75
75
|
},
|
|
76
|
-
[Providers.MISTRALAI]: {
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
// [Providers.MISTRALAI]: {
|
|
77
|
+
// provider: Providers.MISTRALAI,
|
|
78
|
+
// model: 'mistral-large-latest',
|
|
79
|
+
// streaming: true,
|
|
80
|
+
// streamUsage: true,
|
|
81
|
+
// },
|
|
82
|
+
[Providers.MISTRAL]: {
|
|
83
|
+
provider: Providers.OPENAI,
|
|
79
84
|
streaming: true,
|
|
80
|
-
streamUsage:
|
|
85
|
+
streamUsage: false,
|
|
86
|
+
// model: 'codestral-latest',
|
|
87
|
+
model: 'mistral-large-latest',
|
|
88
|
+
openAIApiKey: '12OGQ62FIijUbjaloc5o3IpSYHQNV9Py',
|
|
89
|
+
configuration: {
|
|
90
|
+
baseURL: 'https://api.mistral.ai/v1',
|
|
91
|
+
defaultHeaders: {},
|
|
92
|
+
},
|
|
81
93
|
},
|
|
82
94
|
[Providers.VERTEXAI]: {
|
|
83
95
|
provider: Providers.VERTEXAI,
|
|
@@ -112,7 +124,7 @@ export const llmConfigs: Record<string, t.LLMConfig | undefined> = {
|
|
|
112
124
|
apiKey: process.env.PERPLEXITY_API_KEY,
|
|
113
125
|
configuration: {
|
|
114
126
|
baseURL: 'https://api.perplexity.ai/',
|
|
115
|
-
}
|
|
127
|
+
},
|
|
116
128
|
},
|
|
117
129
|
};
|
|
118
130
|
|