illuma-agents 1.0.7 → 1.0.9
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/LICENSE +1 -5
- package/dist/cjs/common/enum.cjs +1 -2
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/instrumentation.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -2
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +99 -0
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -0
- package/dist/cjs/llm/fake.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +78 -9
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +185 -28
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/providers.cjs +13 -16
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/cjs/llm/text.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +14 -14
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/ids.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/run.cjs +10 -1
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/splitStream.cjs.map +1 -1
- package/dist/cjs/stream.cjs +4 -1
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +163 -55
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +29 -25
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
- package/dist/cjs/tools/search/content.cjs.map +1 -1
- package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
- package/dist/cjs/tools/search/format.cjs.map +1 -1
- package/dist/cjs/tools/search/highlights.cjs.map +1 -1
- package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
- package/dist/cjs/tools/search/schema.cjs +25 -25
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs +6 -1
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +162 -35
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/search/utils.cjs.map +1 -1
- package/dist/cjs/utils/graph.cjs.map +1 -1
- package/dist/cjs/utils/llm.cjs +0 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/misc.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/cjs/utils/title.cjs +7 -7
- package/dist/cjs/utils/title.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -2
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/instrumentation.mjs.map +1 -1
- package/dist/esm/llm/anthropic/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -2
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +97 -0
- package/dist/esm/llm/bedrock/index.mjs.map +1 -0
- package/dist/esm/llm/fake.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +79 -10
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +184 -30
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/providers.mjs +2 -5
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/esm/llm/text.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +14 -14
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/ids.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/run.mjs +10 -1
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/splitStream.mjs.map +1 -1
- package/dist/esm/stream.mjs +4 -1
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +164 -56
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +30 -26
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/tools/search/anthropic.mjs.map +1 -1
- package/dist/esm/tools/search/content.mjs.map +1 -1
- package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
- package/dist/esm/tools/search/format.mjs.map +1 -1
- package/dist/esm/tools/search/highlights.mjs.map +1 -1
- package/dist/esm/tools/search/rerankers.mjs.map +1 -1
- package/dist/esm/tools/search/schema.mjs +25 -25
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs +6 -1
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +162 -35
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/search/utils.mjs.map +1 -1
- package/dist/esm/utils/graph.mjs.map +1 -1
- package/dist/esm/utils/llm.mjs +0 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/misc.mjs.map +1 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/esm/utils/title.mjs +7 -7
- package/dist/esm/utils/title.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +1 -2
- package/dist/types/llm/bedrock/index.d.ts +36 -0
- package/dist/types/llm/google/index.d.ts +10 -0
- package/dist/types/llm/google/types.d.ts +11 -1
- package/dist/types/llm/google/utils/common.d.ts +17 -2
- package/dist/types/tools/ToolNode.d.ts +9 -1
- package/dist/types/tools/search/types.d.ts +2 -0
- package/dist/types/types/llm.d.ts +3 -8
- package/dist/types/types/tools.d.ts +1 -1
- package/package.json +15 -11
- package/src/common/enum.ts +1 -2
- package/src/common/index.ts +1 -1
- package/src/instrumentation.ts +22 -22
- package/src/llm/anthropic/llm.spec.ts +1442 -1442
- package/src/llm/anthropic/types.ts +140 -140
- package/src/llm/anthropic/utils/message_inputs.ts +757 -660
- package/src/llm/anthropic/utils/output_parsers.ts +133 -133
- package/src/llm/anthropic/utils/tools.ts +29 -29
- package/src/llm/bedrock/index.ts +128 -0
- package/src/llm/fake.ts +133 -133
- package/src/llm/google/data/gettysburg10.wav +0 -0
- package/src/llm/google/data/hotdog.jpg +0 -0
- package/src/llm/google/index.ts +129 -14
- package/src/llm/google/llm.spec.ts +932 -0
- package/src/llm/google/types.ts +56 -43
- package/src/llm/google/utils/common.ts +873 -660
- package/src/llm/google/utils/tools.ts +160 -160
- package/src/llm/openai/types.ts +24 -24
- package/src/llm/openai/utils/isReasoningModel.test.ts +90 -90
- package/src/llm/providers.ts +2 -7
- package/src/llm/text.ts +94 -94
- package/src/messages/core.ts +463 -463
- package/src/messages/formatAgentMessages.tools.test.ts +400 -400
- package/src/messages/formatMessage.test.ts +693 -693
- package/src/messages/ids.ts +26 -26
- package/src/messages/prune.ts +567 -567
- package/src/messages/shiftIndexTokenCountMap.test.ts +81 -81
- package/src/mockStream.ts +98 -98
- package/src/prompts/collab.ts +5 -5
- package/src/prompts/index.ts +1 -1
- package/src/prompts/taskmanager.ts +61 -61
- package/src/run.ts +13 -4
- package/src/scripts/ant_web_search_edge_case.ts +162 -0
- package/src/scripts/ant_web_search_error_edge_case.ts +148 -0
- package/src/scripts/args.ts +48 -48
- package/src/scripts/caching.ts +123 -123
- package/src/scripts/code_exec_files.ts +193 -193
- package/src/scripts/empty_input.ts +137 -137
- package/src/scripts/image.ts +178 -178
- package/src/scripts/memory.ts +97 -97
- package/src/scripts/thinking.ts +149 -149
- package/src/specs/anthropic.simple.test.ts +67 -0
- package/src/specs/spec.utils.ts +3 -3
- package/src/specs/token-distribution-edge-case.test.ts +316 -316
- package/src/specs/tool-error.test.ts +193 -193
- package/src/splitStream.test.ts +691 -691
- package/src/splitStream.ts +234 -234
- package/src/stream.test.ts +94 -94
- package/src/stream.ts +4 -1
- package/src/tools/ToolNode.ts +206 -64
- package/src/tools/handlers.ts +32 -28
- package/src/tools/search/anthropic.ts +51 -51
- package/src/tools/search/content.test.ts +173 -173
- package/src/tools/search/content.ts +147 -147
- package/src/tools/search/direct-url.test.ts +530 -0
- package/src/tools/search/firecrawl.ts +210 -210
- package/src/tools/search/format.ts +250 -250
- package/src/tools/search/highlights.ts +320 -320
- package/src/tools/search/index.ts +2 -2
- package/src/tools/search/jina-reranker.test.ts +126 -126
- package/src/tools/search/output.md +2775 -2775
- package/src/tools/search/rerankers.ts +242 -242
- package/src/tools/search/schema.ts +63 -63
- package/src/tools/search/search.ts +766 -759
- package/src/tools/search/serper-scraper.ts +155 -155
- package/src/tools/search/test.html +883 -883
- package/src/tools/search/test.md +642 -642
- package/src/tools/search/test.ts +159 -159
- package/src/tools/search/tool.ts +619 -471
- package/src/tools/search/types.ts +689 -687
- package/src/tools/search/utils.ts +79 -79
- package/src/types/index.ts +6 -6
- package/src/types/llm.ts +2 -8
- package/src/types/tools.ts +80 -80
- package/src/utils/graph.ts +10 -10
- package/src/utils/llm.ts +26 -27
- package/src/utils/llmConfig.ts +5 -3
- package/src/utils/logging.ts +48 -48
- package/src/utils/misc.ts +57 -57
- package/src/utils/run.ts +100 -100
- package/src/utils/title.ts +165 -165
- package/dist/cjs/llm/ollama/index.cjs +0 -70
- package/dist/cjs/llm/ollama/index.cjs.map +0 -1
- package/dist/cjs/llm/ollama/utils.cjs +0 -158
- package/dist/cjs/llm/ollama/utils.cjs.map +0 -1
- package/dist/esm/llm/ollama/index.mjs +0 -68
- package/dist/esm/llm/ollama/index.mjs.map +0 -1
- package/dist/esm/llm/ollama/utils.mjs +0 -155
- package/dist/esm/llm/ollama/utils.mjs.map +0 -1
- package/dist/types/llm/ollama/index.d.ts +0 -8
- package/dist/types/llm/ollama/utils.d.ts +0 -7
- package/src/llm/ollama/index.ts +0 -92
- package/src/llm/ollama/utils.ts +0 -193
- package/src/proto/CollabGraph.ts +0 -269
- package/src/proto/TaskManager.ts +0 -243
- package/src/proto/collab.ts +0 -200
- package/src/proto/collab_design.ts +0 -184
- package/src/proto/collab_design_v2.ts +0 -224
- package/src/proto/collab_design_v3.ts +0 -255
- package/src/proto/collab_design_v4.ts +0 -220
- package/src/proto/collab_design_v5.ts +0 -251
- package/src/proto/collab_graph.ts +0 -181
- package/src/proto/collab_original.ts +0 -123
- package/src/proto/example.ts +0 -93
- package/src/proto/example_new.ts +0 -68
- package/src/proto/example_old.ts +0 -201
- package/src/proto/example_test.ts +0 -152
- package/src/proto/example_test_anthropic.ts +0 -100
- package/src/proto/log_stream.ts +0 -202
- package/src/proto/main_collab_community_event.ts +0 -133
- package/src/proto/main_collab_design_v2.ts +0 -96
- package/src/proto/main_collab_design_v4.ts +0 -100
- package/src/proto/main_collab_design_v5.ts +0 -135
- package/src/proto/main_collab_global_analysis.ts +0 -122
- package/src/proto/main_collab_hackathon_event.ts +0 -153
- package/src/proto/main_collab_space_mission.ts +0 -153
- package/src/proto/main_philosophy.ts +0 -210
- package/src/proto/original_script.ts +0 -126
- package/src/proto/standard.ts +0 -100
- package/src/proto/stream.ts +0 -56
- package/src/proto/tasks.ts +0 -118
- package/src/proto/tools/global_analysis_tools.ts +0 -86
- package/src/proto/tools/space_mission_tools.ts +0 -60
- package/src/proto/vertexai.ts +0 -54
package/LICENSE
CHANGED
|
@@ -18,8 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
18
18
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
19
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
Portions of this software are derived from works by Danny Avila, originally licensed under the MIT License (Copyright (c) 2024).
|
|
21
|
+
SOFTWARE.
|
package/dist/cjs/common/enum.cjs
CHANGED
|
@@ -63,7 +63,6 @@ exports.Providers = void 0;
|
|
|
63
63
|
Providers["ANTHROPIC"] = "anthropic";
|
|
64
64
|
Providers["MISTRALAI"] = "mistralai";
|
|
65
65
|
Providers["MISTRAL"] = "mistral";
|
|
66
|
-
Providers["OLLAMA"] = "ollama";
|
|
67
66
|
Providers["GOOGLE"] = "google";
|
|
68
67
|
Providers["AZURE"] = "azureOpenAI";
|
|
69
68
|
Providers["DEEPSEEK"] = "deepseek";
|
|
@@ -159,6 +158,6 @@ exports.TitleMethod = void 0;
|
|
|
159
158
|
exports.EnvVar = void 0;
|
|
160
159
|
(function (EnvVar) {
|
|
161
160
|
EnvVar["CODE_API_KEY"] = "CODE_EXECUTOR_API_KEY";
|
|
162
|
-
EnvVar["CODE_BASEURL"] = "
|
|
161
|
+
EnvVar["CODE_BASEURL"] = "CODE_EXECUTOR_BASEURL";
|
|
163
162
|
})(exports.EnvVar || (exports.EnvVar = {}));
|
|
164
163
|
//# sourceMappingURL=enum.cjs.map
|
|
@@ -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',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n
|
|
1
|
+
{"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] 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 VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\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 ROUTER = 'router',\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 /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\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 */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.illuma.ai/v1',\n EXECUTE_CODE = 'execute_code',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n}\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_API_KEY = 'CODE_EXECUTOR_API_KEY',\n CODE_BASEURL = 'CODE_EXECUTOR_BASEURL',\n}\n"],"names":["GraphEvents","Providers","GraphNodeKeys","GraphNodeActions","CommonEvents","StepTypes","ContentTypes","ToolCallTypes","Callback","Constants","TitleMethod","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,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AQ,KAARA,gBAAQ,GAqBnB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,SAAS,EAAA;AACnB,IAAA,SAAA,CAAA,uBAAA,CAAA,GAAA,0BAAkD;AAClD,IAAA,SAAA,CAAA,cAAA,CAAA,GAAA,cAA6B;AAC7B,IAAA,SAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,SAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,SAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;AACrC,CAAC,EANWA,iBAAS,KAATA,iBAAS,GAMpB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,WAAW,EAAA;AACrB,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,WAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AAC3B,CAAC,EAJWA,mBAAW,KAAXA,mBAAW,GAItB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,uBAAsC;AACtC,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,uBAAsC;AACxC,CAAC,EAHWA,cAAM,KAANA,cAAM,GAGjB,EAAA,CAAA,CAAA;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.cjs","sources":["../../src/instrumentation.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\
|
|
1
|
+
{"version":3,"file":"instrumentation.cjs","sources":["../../src/instrumentation.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { LangfuseSpanProcessor } from '@langfuse/otel';\nimport { isPresent } from '@/utils/misc';\n\nif (\n isPresent(process.env.LANGFUSE_SECRET_KEY) &&\n isPresent(process.env.LANGFUSE_PUBLIC_KEY) &&\n isPresent(process.env.LANGFUSE_BASE_URL)\n) {\n const langfuseSpanProcessor = new LangfuseSpanProcessor({\n publicKey: process.env.LANGFUSE_PUBLIC_KEY,\n secretKey: process.env.LANGFUSE_SECRET_KEY,\n baseUrl: process.env.LANGFUSE_BASE_URL,\n environment: process.env.NODE_ENV ?? 'development',\n });\n\n const sdk = new NodeSDK({\n spanProcessors: [langfuseSpanProcessor],\n });\n\n sdk.start();\n}\n"],"names":["isPresent","LangfuseSpanProcessor","NodeSDK"],"mappings":";;;;;;AAIA,IACEA,cAAS,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;AAC1C,IAAAA,cAAS,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC1CA,cAAS,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,EACxC;AACA,IAAA,MAAM,qBAAqB,GAAG,IAAIC,0BAAqB,CAAC;AACtD,QAAA,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB;AAC1C,QAAA,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB;AAC1C,QAAA,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,iBAAiB;AACtC,QAAA,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa;AACnD,KAAA,CAAC;AAEF,IAAA,MAAM,GAAG,GAAG,IAAIC,eAAO,CAAC;QACtB,cAAc,EAAE,CAAC,qBAAqB,CAAC;AACxC,KAAA,CAAC;IAEF,GAAG,CAAC,KAAK,EAAE;AACb;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sources":["../../../../src/llm/anthropic/types.ts"],"sourcesContent":["import Anthropic from '@anthropic-ai/sdk';\
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":["../../../../src/llm/anthropic/types.ts"],"sourcesContent":["import Anthropic from '@anthropic-ai/sdk';\nimport { BindToolsInput } from '@langchain/core/language_models/chat_models';\n\nexport type AnthropicStreamUsage = Anthropic.Usage;\nexport type AnthropicMessageDeltaEvent = Anthropic.MessageDeltaEvent;\nexport type AnthropicMessageStartEvent = Anthropic.MessageStartEvent;\n\nexport type AnthropicToolResponse = {\n type: 'tool_use';\n id: string;\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: Record<string, any>;\n};\n\nexport type AnthropicMessageParam = Anthropic.MessageParam;\nexport type AnthropicMessageResponse =\n | Anthropic.ContentBlock\n | AnthropicToolResponse;\nexport type AnthropicMessageCreateParams =\n Anthropic.MessageCreateParamsNonStreaming;\nexport type AnthropicStreamingMessageCreateParams =\n Anthropic.MessageCreateParamsStreaming;\nexport type AnthropicThinkingConfigParam = Anthropic.ThinkingConfigParam;\nexport type AnthropicMessageStreamEvent = Anthropic.MessageStreamEvent;\nexport type AnthropicRequestOptions = Anthropic.RequestOptions;\nexport type AnthropicToolChoice =\n | {\n type: 'tool';\n name: string;\n }\n | 'any'\n | 'auto'\n | 'none'\n | string;\nexport type ChatAnthropicToolType = Anthropic.Messages.Tool | BindToolsInput;\nexport type AnthropicTextBlockParam = Anthropic.Messages.TextBlockParam;\nexport type AnthropicImageBlockParam = Anthropic.Messages.ImageBlockParam;\nexport type AnthropicToolUseBlockParam = Anthropic.Messages.ToolUseBlockParam;\nexport type AnthropicToolResultBlockParam =\n Anthropic.Messages.ToolResultBlockParam;\nexport type AnthropicDocumentBlockParam = Anthropic.Messages.DocumentBlockParam;\nexport type AnthropicThinkingBlockParam = Anthropic.Messages.ThinkingBlockParam;\nexport type AnthropicRedactedThinkingBlockParam =\n Anthropic.Messages.RedactedThinkingBlockParam;\nexport type AnthropicServerToolUseBlockParam =\n Anthropic.Messages.ServerToolUseBlockParam;\nexport type AnthropicWebSearchToolResultBlockParam =\n Anthropic.Messages.WebSearchToolResultBlockParam;\nexport type AnthropicWebSearchResultBlockParam =\n Anthropic.Messages.WebSearchResultBlockParam;\nexport type AnthropicSearchResultBlockParam =\n Anthropic.Beta.BetaSearchResultBlockParam;\n\n// Union of all possible content block types including server tool use\nexport type AnthropicContentBlock =\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicWebSearchResultBlockParam;\n\n// Union of all possible content block types including server tool use\nexport type ChatAnthropicContentBlock =\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicWebSearchResultBlockParam\n | AnthropicSearchResultBlockParam;\n\nexport function isAnthropicImageBlockParam(\n block: unknown\n): block is AnthropicImageBlockParam {\n if (block == null) {\n return false;\n }\n if (typeof block !== 'object') {\n return false;\n }\n if (!('type' in block) || block.type !== 'image') {\n return false;\n }\n\n if (!('source' in block) || typeof block.source !== 'object') {\n return false;\n }\n\n if (block.source == null) {\n return false;\n }\n\n if (!('type' in block.source)) {\n return false;\n }\n\n if (block.source.type === 'base64') {\n if (!('media_type' in block.source)) {\n return false;\n }\n\n if (typeof block.source.media_type !== 'string') {\n return false;\n }\n\n if (!('data' in block.source)) {\n return false;\n }\n\n if (typeof block.source.data !== 'string') {\n return false;\n }\n\n return true;\n }\n\n if (block.source.type === 'url') {\n if (!('url' in block.source)) {\n return false;\n }\n\n if (typeof block.source.url !== 'string') {\n return false;\n }\n\n return true;\n }\n\n return false;\n}\n"],"names":[],"mappings":";;AAiFM,SAAU,0BAA0B,CACxC,KAAc,EAAA;AAEd,IAAA,IAAI,KAAK,IAAI,IAAI,EAAE;AACjB,QAAA,OAAO,KAAK;;AAEd,IAAA,IAAI,OAAO,KAAK,KAAK,QAAQ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301
301
|
}
|
|
302
302
|
else {
|
|
303
303
|
const contentBlocks = content.map((contentPart) => {
|
|
304
|
+
/**
|
|
305
|
+
* Handle malformed blocks that have server tool fields mixed with text type.
|
|
306
|
+
* These can occur when server_tool_use blocks get mislabeled during aggregation.
|
|
307
|
+
* Correct their type ONLY if we can confirm it's a server tool by checking the ID prefix.
|
|
308
|
+
* Anthropic needs both server_tool_use and web_search_tool_result blocks for citations to work.
|
|
309
|
+
*/
|
|
310
|
+
if ('id' in contentPart &&
|
|
311
|
+
'name' in contentPart &&
|
|
312
|
+
'input' in contentPart &&
|
|
313
|
+
contentPart.type === 'text') {
|
|
314
|
+
const rawPart = contentPart;
|
|
315
|
+
const id = rawPart.id;
|
|
316
|
+
// Only correct if this is definitely a server tool (ID starts with 'srvtoolu_')
|
|
317
|
+
if (id && id.startsWith('srvtoolu_')) {
|
|
318
|
+
let input = rawPart.input;
|
|
319
|
+
// Ensure input is an object
|
|
320
|
+
if (typeof input === 'string') {
|
|
321
|
+
try {
|
|
322
|
+
input = JSON.parse(input);
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
input = {};
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const corrected = {
|
|
329
|
+
type: 'server_tool_use',
|
|
330
|
+
id,
|
|
331
|
+
name: 'web_search',
|
|
332
|
+
input: input,
|
|
333
|
+
};
|
|
334
|
+
return corrected;
|
|
335
|
+
}
|
|
336
|
+
// If it's not a server tool, skip it (return null to filter it out)
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Handle malformed web_search_tool_result blocks marked as text.
|
|
341
|
+
* These have tool_use_id and nested content - fix their type instead of filtering.
|
|
342
|
+
* Only correct if we can confirm it's a web search result by checking the tool_use_id prefix.
|
|
343
|
+
*
|
|
344
|
+
* Handles both success results (array content) and error results (object with error_code).
|
|
345
|
+
*/
|
|
346
|
+
if ('tool_use_id' in contentPart &&
|
|
347
|
+
'content' in contentPart &&
|
|
348
|
+
contentPart.type === 'text') {
|
|
349
|
+
const rawPart = contentPart;
|
|
350
|
+
const toolUseId = rawPart.tool_use_id;
|
|
351
|
+
const content = rawPart.content;
|
|
352
|
+
// Only correct if this is definitely a server tool result (tool_use_id starts with 'srvtoolu_')
|
|
353
|
+
if (toolUseId && toolUseId.startsWith('srvtoolu_')) {
|
|
354
|
+
// Verify content is either an array (success) or error object
|
|
355
|
+
const isValidContent = Array.isArray(content) ||
|
|
356
|
+
(content != null &&
|
|
357
|
+
typeof content === 'object' &&
|
|
358
|
+
'type' in content &&
|
|
359
|
+
content.type ===
|
|
360
|
+
'web_search_tool_result_error');
|
|
361
|
+
if (isValidContent) {
|
|
362
|
+
const corrected = {
|
|
363
|
+
type: 'web_search_tool_result',
|
|
364
|
+
tool_use_id: toolUseId,
|
|
365
|
+
content: content,
|
|
366
|
+
};
|
|
367
|
+
return corrected;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
// If it's not a recognized server tool result format, skip it (return null to filter it out)
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
304
373
|
if (messages.isDataContentBlock(contentPart)) {
|
|
305
374
|
return messages.convertToProviderContentBlock(contentPart, standardContentBlockConverter);
|
|
306
375
|
}
|
|
@@ -395,6 +464,13 @@ function _formatContent(message) {
|
|
|
395
464
|
}
|
|
396
465
|
}
|
|
397
466
|
}
|
|
467
|
+
/**
|
|
468
|
+
* For multi-turn conversations with citations, we must preserve ALL blocks
|
|
469
|
+
* including server_tool_use, web_search_tool_result, and web_search_result.
|
|
470
|
+
* Citations reference search results by index, so filtering changes indices and breaks references.
|
|
471
|
+
*
|
|
472
|
+
* The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.
|
|
473
|
+
*/
|
|
398
474
|
// TODO: Fix when SDK types are fixed
|
|
399
475
|
return {
|
|
400
476
|
...contentPartCopy,
|
|
@@ -419,10 +495,11 @@ function _formatContent(message) {
|
|
|
419
495
|
};
|
|
420
496
|
}
|
|
421
497
|
else {
|
|
498
|
+
console.error('Unsupported content part:', JSON.stringify(contentPart, null, 2));
|
|
422
499
|
throw new Error('Unsupported message content format');
|
|
423
500
|
}
|
|
424
501
|
});
|
|
425
|
-
return contentBlocks;
|
|
502
|
+
return contentBlocks.filter((block) => block !== null);
|
|
426
503
|
}
|
|
427
504
|
}
|
|
428
505
|
/**
|
|
@@ -475,7 +552,7 @@ function _convertMessagesToAnthropicPayload(messages$1) {
|
|
|
475
552
|
}
|
|
476
553
|
else {
|
|
477
554
|
const { content } = message;
|
|
478
|
-
const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find((contentPart) => (contentPart.type === 'tool_use' ||
|
|
555
|
+
const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => !!content.find((contentPart) => (contentPart.type === 'tool_use' ||
|
|
479
556
|
contentPart.type === 'input_json_delta' ||
|
|
480
557
|
contentPart.type === 'server_tool_use') &&
|
|
481
558
|
contentPart.id === toolCall.id));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.cjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\r\n/* eslint-disable no-console */\r\n/**\r\n * This util file contains functions for converting LangChain messages to Anthropic messages.\r\n */\r\nimport {\r\n type BaseMessage,\r\n type SystemMessage,\r\n HumanMessage,\r\n type AIMessage,\r\n type ToolMessage,\r\n isAIMessage,\r\n type StandardContentBlockConverter,\r\n type StandardTextBlock,\r\n type StandardImageBlock,\r\n type StandardFileBlock,\r\n MessageContentComplex,\r\n isDataContentBlock,\r\n convertToProviderContentBlock,\r\n parseBase64DataUrl,\r\n} from '@langchain/core/messages';\r\nimport { ToolCall } from '@langchain/core/messages/tool';\r\nimport {\r\n AnthropicImageBlockParam,\r\n AnthropicMessageCreateParams,\r\n AnthropicTextBlockParam,\r\n AnthropicToolResultBlockParam,\r\n AnthropicToolUseBlockParam,\r\n AnthropicDocumentBlockParam,\r\n AnthropicThinkingBlockParam,\r\n AnthropicRedactedThinkingBlockParam,\r\n AnthropicServerToolUseBlockParam,\r\n AnthropicWebSearchToolResultBlockParam,\r\n isAnthropicImageBlockParam,\r\n AnthropicSearchResultBlockParam,\r\n AnthropicToolResponse,\r\n} from '../types';\r\n\r\nfunction _formatImage(imageUrl: string) {\r\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\r\n if (parsed) {\r\n return {\r\n type: 'base64',\r\n media_type: parsed.mime_type,\r\n data: parsed.data,\r\n };\r\n }\r\n let parsedUrl: URL;\r\n\r\n try {\r\n parsedUrl = new URL(imageUrl);\r\n } catch {\r\n throw new Error(\r\n [\r\n `Malformed image URL: ${JSON.stringify(\r\n imageUrl\r\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\r\n 'Example: data:image/png;base64,/9j/4AAQSk...',\r\n 'Example: https://example.com/image.jpg',\r\n ].join('\\n\\n')\r\n );\r\n }\r\n\r\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\r\n return {\r\n type: 'url',\r\n url: imageUrl,\r\n };\r\n }\r\n\r\n throw new Error(\r\n [\r\n `Invalid image URL protocol: ${JSON.stringify(\r\n parsedUrl.protocol\r\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\r\n 'Example: data:image/png;base64,/9j/4AAQSk...',\r\n 'Example: https://example.com/image.jpg',\r\n ].join('\\n\\n')\r\n );\r\n}\r\n\r\nfunction _ensureMessageContents(\r\n messages: BaseMessage[]\r\n): (SystemMessage | HumanMessage | AIMessage)[] {\r\n // Merge runs of human/tool messages into single human messages with content blocks.\r\n const updatedMsgs = [];\r\n for (const message of messages) {\r\n if (message._getType() === 'tool') {\r\n if (typeof message.content === 'string') {\r\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\r\n if (\r\n previousMessage._getType() === 'human' &&\r\n Array.isArray(previousMessage.content) &&\r\n 'type' in previousMessage.content[0] &&\r\n previousMessage.content[0].type === 'tool_result'\r\n ) {\r\n // If the previous message was a tool result, we merge this tool message into it.\r\n (previousMessage.content as MessageContentComplex[]).push({\r\n type: 'tool_result',\r\n content: message.content,\r\n tool_use_id: (message as ToolMessage).tool_call_id,\r\n });\r\n } else {\r\n // If not, we create a new human message with the tool result.\r\n updatedMsgs.push(\r\n new HumanMessage({\r\n content: [\r\n {\r\n type: 'tool_result',\r\n content: message.content,\r\n tool_use_id: (message as ToolMessage).tool_call_id,\r\n },\r\n ],\r\n })\r\n );\r\n }\r\n } else {\r\n updatedMsgs.push(\r\n new HumanMessage({\r\n content: [\r\n {\r\n type: 'tool_result',\r\n // rare case: message.content could be undefined\r\n ...(message.content != null\r\n ? { content: _formatContent(message) }\r\n : {}),\r\n tool_use_id: (message as ToolMessage).tool_call_id,\r\n },\r\n ],\r\n })\r\n );\r\n }\r\n } else {\r\n updatedMsgs.push(message);\r\n }\r\n }\r\n return updatedMsgs;\r\n}\r\n\r\nexport function _convertLangChainToolCallToAnthropic(\r\n toolCall: ToolCall\r\n): AnthropicToolResponse {\r\n if (toolCall.id === undefined) {\r\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\r\n }\r\n return {\r\n type: 'tool_use',\r\n id: toolCall.id,\r\n name: toolCall.name,\r\n input: toolCall.args,\r\n };\r\n}\r\n\r\nconst standardContentBlockConverter: StandardContentBlockConverter<{\r\n text: AnthropicTextBlockParam;\r\n image: AnthropicImageBlockParam;\r\n file: AnthropicDocumentBlockParam;\r\n}> = {\r\n providerName: 'anthropic',\r\n\r\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\r\n return {\r\n type: 'text',\r\n text: block.text,\r\n ...('citations' in (block.metadata ?? {})\r\n ? { citations: block.metadata!.citations }\r\n : {}),\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n } as AnthropicTextBlockParam;\r\n },\r\n\r\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\r\n if (block.source_type === 'url') {\r\n const data = parseBase64DataUrl({\r\n dataUrl: block.url,\r\n asTypedArray: false,\r\n });\r\n if (data) {\r\n return {\r\n type: 'image',\r\n source: {\r\n type: 'base64',\r\n data: data.data,\r\n media_type: data.mime_type,\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n } as AnthropicImageBlockParam;\r\n } else {\r\n return {\r\n type: 'image',\r\n source: {\r\n type: 'url',\r\n url: block.url,\r\n media_type: block.mime_type ?? '',\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n } as AnthropicImageBlockParam;\r\n }\r\n } else {\r\n if (block.source_type === 'base64') {\r\n return {\r\n type: 'image',\r\n source: {\r\n type: 'base64',\r\n data: block.data,\r\n media_type: block.mime_type ?? '',\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n } as AnthropicImageBlockParam;\r\n } else {\r\n throw new Error(`Unsupported image source type: ${block.source_type}`);\r\n }\r\n }\r\n },\r\n\r\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\r\n const mime_type = (block.mime_type ?? '').split(';')[0];\r\n\r\n if (block.source_type === 'url') {\r\n if (mime_type === 'application/pdf' || mime_type === '') {\r\n return {\r\n type: 'document',\r\n source: {\r\n type: 'url',\r\n url: block.url,\r\n media_type: block.mime_type ?? '',\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n ...('citations' in (block.metadata ?? {})\r\n ? { citations: block.metadata!.citations }\r\n : {}),\r\n ...('context' in (block.metadata ?? {})\r\n ? { context: block.metadata!.context }\r\n : {}),\r\n ...('title' in (block.metadata ?? {})\r\n ? { title: block.metadata!.title }\r\n : {}),\r\n } as AnthropicDocumentBlockParam;\r\n }\r\n throw new Error(\r\n `Unsupported file mime type for file url source: ${block.mime_type}`\r\n );\r\n } else if (block.source_type === 'text') {\r\n if (mime_type === 'text/plain' || mime_type === '') {\r\n return {\r\n type: 'document',\r\n source: {\r\n type: 'text',\r\n data: block.text,\r\n media_type: block.mime_type ?? '',\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n ...('citations' in (block.metadata ?? {})\r\n ? { citations: block.metadata!.citations }\r\n : {}),\r\n ...('context' in (block.metadata ?? {})\r\n ? { context: block.metadata!.context }\r\n : {}),\r\n ...('title' in (block.metadata ?? {})\r\n ? { title: block.metadata!.title }\r\n : {}),\r\n } as AnthropicDocumentBlockParam;\r\n } else {\r\n throw new Error(\r\n `Unsupported file mime type for file text source: ${block.mime_type}`\r\n );\r\n }\r\n } else if (block.source_type === 'base64') {\r\n if (mime_type === 'application/pdf' || mime_type === '') {\r\n return {\r\n type: 'document',\r\n source: {\r\n type: 'base64',\r\n data: block.data,\r\n media_type: 'application/pdf',\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n ...('citations' in (block.metadata ?? {})\r\n ? { citations: block.metadata!.citations }\r\n : {}),\r\n ...('context' in (block.metadata ?? {})\r\n ? { context: block.metadata!.context }\r\n : {}),\r\n ...('title' in (block.metadata ?? {})\r\n ? { title: block.metadata!.title }\r\n : {}),\r\n } as AnthropicDocumentBlockParam;\r\n } else if (\r\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\r\n mime_type\r\n )\r\n ) {\r\n return {\r\n type: 'document',\r\n source: {\r\n type: 'content',\r\n content: [\r\n {\r\n type: 'image',\r\n source: {\r\n type: 'base64',\r\n data: block.data,\r\n media_type: mime_type as\r\n | 'image/jpeg'\r\n | 'image/png'\r\n | 'image/gif'\r\n | 'image/webp',\r\n },\r\n },\r\n ],\r\n },\r\n ...('cache_control' in (block.metadata ?? {})\r\n ? { cache_control: block.metadata!.cache_control }\r\n : {}),\r\n ...('citations' in (block.metadata ?? {})\r\n ? { citations: block.metadata!.citations }\r\n : {}),\r\n ...('context' in (block.metadata ?? {})\r\n ? { context: block.metadata!.context }\r\n : {}),\r\n ...('title' in (block.metadata ?? {})\r\n ? { title: block.metadata!.title }\r\n : {}),\r\n } as AnthropicDocumentBlockParam;\r\n } else {\r\n throw new Error(\r\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\r\n );\r\n }\r\n } else {\r\n throw new Error(`Unsupported file source type: ${block.source_type}`);\r\n }\r\n },\r\n};\r\n\r\nfunction _formatContent(message: BaseMessage) {\r\n const toolTypes = [\r\n 'tool_use',\r\n 'tool_result',\r\n 'input_json_delta',\r\n 'server_tool_use',\r\n 'web_search_tool_result',\r\n 'web_search_result',\r\n ];\r\n const textTypes = ['text', 'text_delta'];\r\n const { content } = message;\r\n\r\n if (typeof content === 'string') {\r\n return content;\r\n } else {\r\n const contentBlocks = content.map((contentPart) => {\r\n if (isDataContentBlock(contentPart)) {\r\n return convertToProviderContentBlock(\r\n contentPart,\r\n standardContentBlockConverter\r\n );\r\n }\r\n\r\n const cacheControl =\r\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\r\n\r\n if (contentPart.type === 'image_url') {\r\n let source;\r\n if (typeof contentPart.image_url === 'string') {\r\n source = _formatImage(contentPart.image_url);\r\n } else {\r\n source = _formatImage(contentPart.image_url.url);\r\n }\r\n return {\r\n type: 'image' as const, // Explicitly setting the type as \"image\"\r\n source,\r\n ...(cacheControl ? { cache_control: cacheControl } : {}),\r\n };\r\n } else if (isAnthropicImageBlockParam(contentPart)) {\r\n return contentPart;\r\n } else if (contentPart.type === 'document') {\r\n // PDF\r\n return {\r\n ...contentPart,\r\n ...(cacheControl ? { cache_control: cacheControl } : {}),\r\n };\r\n } else if (contentPart.type === 'thinking') {\r\n const block: AnthropicThinkingBlockParam = {\r\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\r\n thinking: contentPart.thinking,\r\n signature: contentPart.signature,\r\n ...(cacheControl ? { cache_control: cacheControl } : {}),\r\n };\r\n return block;\r\n } else if (contentPart.type === 'redacted_thinking') {\r\n const block: AnthropicRedactedThinkingBlockParam = {\r\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\r\n data: contentPart.data,\r\n ...(cacheControl ? { cache_control: cacheControl } : {}),\r\n };\r\n return block;\r\n } else if (contentPart.type === 'search_result') {\r\n const block: AnthropicSearchResultBlockParam = {\r\n type: 'search_result' as const, // Explicitly setting the type as \"search_result\"\r\n title: contentPart.title,\r\n source: contentPart.source,\r\n ...('cache_control' in contentPart && contentPart.cache_control\r\n ? { cache_control: contentPart.cache_control }\r\n : {}),\r\n ...('citations' in contentPart && contentPart.citations\r\n ? { citations: contentPart.citations }\r\n : {}),\r\n content: contentPart.content,\r\n };\r\n return block;\r\n } else if (\r\n textTypes.find((t) => t === contentPart.type) &&\r\n 'text' in contentPart\r\n ) {\r\n // Assuming contentPart is of type MessageContentText here\r\n return {\r\n type: 'text' as const, // Explicitly setting the type as \"text\"\r\n text: contentPart.text,\r\n ...(cacheControl ? { cache_control: cacheControl } : {}),\r\n ...('citations' in contentPart && contentPart.citations\r\n ? { citations: contentPart.citations }\r\n : {}),\r\n };\r\n } else if (toolTypes.find((t) => t === contentPart.type)) {\r\n const contentPartCopy = { ...contentPart };\r\n if ('index' in contentPartCopy) {\r\n // Anthropic does not support passing the index field here, so we remove it.\r\n delete contentPartCopy.index;\r\n }\r\n\r\n if (contentPartCopy.type === 'input_json_delta') {\r\n // `input_json_delta` type only represents yielding partial tool inputs\r\n // and is not a valid type for Anthropic messages.\r\n contentPartCopy.type = 'tool_use';\r\n }\r\n\r\n if ('input' in contentPartCopy) {\r\n // Anthropic tool use inputs should be valid objects, when applicable.\r\n if (typeof contentPartCopy.input === 'string') {\r\n try {\r\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\r\n } catch {\r\n contentPartCopy.input = {};\r\n }\r\n }\r\n }\r\n\r\n // TODO: Fix when SDK types are fixed\r\n return {\r\n ...contentPartCopy,\r\n ...(cacheControl ? { cache_control: cacheControl } : {}),\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n } as any;\r\n } else if (\r\n 'functionCall' in contentPart &&\r\n contentPart.functionCall &&\r\n typeof contentPart.functionCall === 'object' &&\r\n isAIMessage(message)\r\n ) {\r\n const correspondingToolCall = message.tool_calls?.find(\r\n (toolCall) => toolCall.name === contentPart.functionCall.name\r\n );\r\n if (!correspondingToolCall) {\r\n throw new Error(\r\n `Could not find tool call for function call ${contentPart.functionCall.name}`\r\n );\r\n }\r\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\r\n return {\r\n id: correspondingToolCall.id,\r\n type: 'tool_use',\r\n name: correspondingToolCall.name,\r\n input: contentPart.functionCall.args,\r\n };\r\n } else {\r\n throw new Error('Unsupported message content format');\r\n }\r\n });\r\n return contentBlocks;\r\n }\r\n}\r\n\r\n/**\r\n * Formats messages as a prompt for the model.\r\n * Used in LangSmith, export is important here.\r\n * @param messages The base messages to format as a prompt.\r\n * @returns The formatted prompt.\r\n */\r\nexport function _convertMessagesToAnthropicPayload(\r\n messages: BaseMessage[]\r\n): AnthropicMessageCreateParams {\r\n const mergedMessages = _ensureMessageContents(messages);\r\n let system;\r\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\r\n system = messages[0].content;\r\n }\r\n const conversationMessages =\r\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\r\n const formattedMessages = conversationMessages.map((message) => {\r\n let role;\r\n if (message._getType() === 'human') {\r\n role = 'user' as const;\r\n } else if (message._getType() === 'ai') {\r\n role = 'assistant' as const;\r\n } else if (message._getType() === 'tool') {\r\n role = 'user' as const;\r\n } else if (message._getType() === 'system') {\r\n throw new Error(\r\n 'System messages are only permitted as the first passed message.'\r\n );\r\n } else {\r\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\r\n }\r\n if (isAIMessage(message) && !!message.tool_calls?.length) {\r\n if (typeof message.content === 'string') {\r\n if (message.content === '') {\r\n return {\r\n role,\r\n content: message.tool_calls.map(\r\n _convertLangChainToolCallToAnthropic\r\n ),\r\n };\r\n } else {\r\n return {\r\n role,\r\n content: [\r\n { type: 'text', text: message.content },\r\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\r\n ],\r\n };\r\n }\r\n } else {\r\n const { content } = message;\r\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\r\n content.find(\r\n (contentPart) =>\r\n (contentPart.type === 'tool_use' ||\r\n contentPart.type === 'input_json_delta' ||\r\n contentPart.type === 'server_tool_use') &&\r\n contentPart.id === toolCall.id\r\n )\r\n );\r\n if (hasMismatchedToolCalls) {\r\n console.warn(\r\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\r\n );\r\n }\r\n return {\r\n role,\r\n content: _formatContent(message),\r\n };\r\n }\r\n } else {\r\n return {\r\n role,\r\n content: _formatContent(message),\r\n };\r\n }\r\n });\r\n return {\r\n messages: mergeMessages(formattedMessages),\r\n system,\r\n } as AnthropicMessageCreateParams;\r\n}\r\n\r\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\r\n if (!messages || messages.length <= 1) {\r\n return messages;\r\n }\r\n\r\n const result: AnthropicMessageCreateParams['messages'] = [];\r\n let currentMessage = messages[0];\r\n\r\n const normalizeContent = (\r\n content:\r\n | string\r\n | Array<\r\n | AnthropicTextBlockParam\r\n | AnthropicImageBlockParam\r\n | AnthropicToolUseBlockParam\r\n | AnthropicToolResultBlockParam\r\n | AnthropicDocumentBlockParam\r\n | AnthropicThinkingBlockParam\r\n | AnthropicRedactedThinkingBlockParam\r\n | AnthropicServerToolUseBlockParam\r\n | AnthropicWebSearchToolResultBlockParam\r\n >\r\n ): Array<\r\n | AnthropicTextBlockParam\r\n | AnthropicImageBlockParam\r\n | AnthropicToolUseBlockParam\r\n | AnthropicToolResultBlockParam\r\n | AnthropicDocumentBlockParam\r\n | AnthropicThinkingBlockParam\r\n | AnthropicRedactedThinkingBlockParam\r\n | AnthropicServerToolUseBlockParam\r\n | AnthropicWebSearchToolResultBlockParam\r\n > => {\r\n if (typeof content === 'string') {\r\n return [\r\n {\r\n type: 'text',\r\n text: content,\r\n },\r\n ];\r\n }\r\n return content;\r\n };\r\n\r\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\r\n if (msg.role !== 'user') return false;\r\n\r\n if (typeof msg.content === 'string') {\r\n return false;\r\n }\r\n\r\n return (\r\n Array.isArray(msg.content) &&\r\n msg.content.every((item) => item.type === 'tool_result')\r\n );\r\n };\r\n\r\n for (let i = 1; i < messages.length; i += 1) {\r\n const nextMessage = messages[i];\r\n\r\n if (\r\n isToolResultMessage(currentMessage) &&\r\n isToolResultMessage(nextMessage)\r\n ) {\r\n // Merge the messages by combining their content arrays\r\n currentMessage = {\r\n ...currentMessage,\r\n content: [\r\n ...normalizeContent(currentMessage.content),\r\n ...normalizeContent(nextMessage.content),\r\n ],\r\n };\r\n } else {\r\n result.push(currentMessage);\r\n currentMessage = nextMessage;\r\n }\r\n }\r\n\r\n result.push(currentMessage);\r\n return result;\r\n}\r\n"],"names":["parseBase64DataUrl","messages","HumanMessage","isDataContentBlock","convertToProviderContentBlock","isAnthropicImageBlockParam","isAIMessage"],"mappings":";;;;;AAAA;AACA;AACA;;AAEG;AAkCH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAGA,2BAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACxD,IAAI,MAAM,EAAE;QACV,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,MAAM,CAAC,SAAS;YAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB;;AAEH,IAAA,IAAI,SAAc;AAElB,IAAA,IAAI;AACF,QAAA,SAAS,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC;;AAC7B,IAAA,MAAM;QACN,MAAM,IAAI,KAAK,CACb;A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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 @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n type ToolMessage,\n isAIMessage,\n type StandardContentBlockConverter,\n type StandardTextBlock,\n type StandardImageBlock,\n type StandardFileBlock,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicToolResultBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicToolResponse,\n} from '../types';\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\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];\n if (\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 as MessageContentComplex[]).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 // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\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\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n /**\n * Handle malformed blocks that have server tool fields mixed with text type.\n * These can occur when server_tool_use blocks get mislabeled during aggregation.\n * Correct their type ONLY if we can confirm it's a server tool by checking the ID prefix.\n * Anthropic needs both server_tool_use and web_search_tool_result blocks for citations to work.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const id = rawPart.id as string;\n\n // Only correct if this is definitely a server tool (ID starts with 'srvtoolu_')\n if (id && id.startsWith('srvtoolu_')) {\n let input = rawPart.input;\n\n // Ensure input is an object\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id,\n name: 'web_search',\n input: input as Record<string, unknown>,\n };\n\n return corrected;\n }\n\n // If it's not a server tool, skip it (return null to filter it out)\n return null;\n }\n\n /**\n * Handle malformed web_search_tool_result blocks marked as text.\n * These have tool_use_id and nested content - fix their type instead of filtering.\n * Only correct if we can confirm it's a web search result by checking the tool_use_id prefix.\n *\n * Handles both success results (array content) and error results (object with error_code).\n */\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const toolUseId = rawPart.tool_use_id as string;\n const content = rawPart.content;\n\n // Only correct if this is definitely a server tool result (tool_use_id starts with 'srvtoolu_')\n if (toolUseId && toolUseId.startsWith('srvtoolu_')) {\n // Verify content is either an array (success) or error object\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n }\n\n // If it's not a recognized server tool result format, skip it (return null to filter it out)\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\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 (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\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 (contentPart.type === 'search_result') {\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const, // Explicitly setting the type as \"search_result\"\n title: contentPart.title,\n source: contentPart.source,\n ...('cache_control' in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\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 ...('citations' in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type)) {\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 if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\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 if (\n 'functionCall' in contentPart &&\n contentPart.functionCall &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === contentPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${contentPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: contentPart.functionCall.args,\n };\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks.filter((block) => block !== null);\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(\n (toolCall) =>\n !!content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta' ||\n contentPart.type === 'server_tool_use') &&\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),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\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 | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\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]) => {\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}\n"],"names":["parseBase64DataUrl","messages","HumanMessage","isDataContentBlock","convertToProviderContentBlock","isAnthropicImageBlockParam","isAIMessage"],"mappings":";;;;;AAAA;AACA;AACA;;AAEG;AAkCH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAGA,2BAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACxD,IAAI,MAAM,EAAE;QACV,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,MAAM,CAAC,SAAS;YAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB;;AAEH,IAAA,IAAI,SAAc;AAElB,IAAA,IAAI;AACF,QAAA,SAAS,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC;;AAC7B,IAAA,MAAM;QACN,MAAM,IAAI,KAAK,CACb;AACE,YAAA,CAAA,qBAAA,EAAwB,IAAI,CAAC,SAAS,CACpC,QAAQ,CACT,CAA+F,6FAAA,CAAA;YAChG,8CAA8C;YAC9C,wCAAwC;AACzC,SAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;;AAGH,IAAA,IAAI,SAAS,CAAC,QAAQ,KAAK,OAAO,IAAI,SAAS,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACrE,OAAO;AACL,YAAA,IAAI,EAAE,KAAK;AACX,YAAA,GAAG,EAAE,QAAQ;SACd;;IAGH,MAAM,IAAI,KAAK,CACb;QACE,CAA+B,4BAAA,EAAA,IAAI,CAAC,SAAS,CAC3C,SAAS,CAAC,QAAQ,CACnB,CAA6G,2GAAA,CAAA;QAC9G,8CAA8C;QAC9C,wCAAwC;AACzC,KAAA,CAAC,IAAI,CAAC,MAAM,CAAC,C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I,CAAC,cAAc,CAAC;YAC3B,cAAc,GAAG,WAAW;;;AAIhC,IAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;AAC3B,IAAA,OAAO,MAAM;AACf;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.cjs","sources":["../../../../../src/llm/anthropic/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from '@anthropic-ai/sdk';\
|
|
1
|
+
{"version":3,"file":"tools.cjs","sources":["../../../../../src/llm/anthropic/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from '@anthropic-ai/sdk';\nimport { AnthropicToolChoice } from '../types.js';\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | undefined {\n if (toolChoice == null) {\n return undefined;\n } else if (toolChoice === 'any') {\n return {\n type: 'any',\n };\n } else if (toolChoice === 'auto') {\n return {\n type: 'auto',\n };\n } else if (typeof toolChoice === 'string') {\n return {\n type: 'tool',\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n"],"names":[],"mappings":";;AAGM,SAAU,gBAAgB,CAC9B,UAAgC,EAAA;AAMhC,IAAA,IAAI,UAAU,IAAI,IAAI,EAAE;AACtB,QAAA,OAAO,SAAS;;AACX,SAAA,IAAI,UAAU,KAAK,KAAK,EAAE;QAC/B,OAAO;AACL,YAAA,IAAI,EAAE,KAAK;SACZ;;AACI,SAAA,IAAI,UAAU,KAAK,MAAM,EAAE;QAChC,OAAO;AACL,YAAA,IAAI,EAAE,MAAM;SACb;;AACI,SAAA,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;QACzC,OAAO;AACL,YAAA,IAAI,EAAE,MAAM;AACZ,YAAA,IAAI,EAAE,UAAU;SACjB;;SACI;AACL,QAAA,OAAO,UAAU;;AAErB;;;;"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var aws = require('@langchain/aws');
|
|
4
|
+
var messages = require('@langchain/core/messages');
|
|
5
|
+
var outputs = require('@langchain/core/outputs');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Optimized ChatBedrockConverse wrapper that fixes contentBlockIndex conflicts
|
|
9
|
+
*
|
|
10
|
+
* Bedrock sends the same contentBlockIndex for both text and tool_use content blocks,
|
|
11
|
+
* causing LangChain's merge logic to fail with "field[contentBlockIndex] already exists"
|
|
12
|
+
* errors. This wrapper simply strips contentBlockIndex from response_metadata to avoid
|
|
13
|
+
* the conflict.
|
|
14
|
+
*
|
|
15
|
+
* The contentBlockIndex field is only used internally by Bedrock's streaming protocol
|
|
16
|
+
* and isn't needed by application logic - the index field on tool_call_chunks serves
|
|
17
|
+
* the purpose of tracking tool call ordering.
|
|
18
|
+
*/
|
|
19
|
+
class CustomChatBedrockConverse extends aws.ChatBedrockConverse {
|
|
20
|
+
constructor(fields) {
|
|
21
|
+
super(fields);
|
|
22
|
+
}
|
|
23
|
+
static lc_name() {
|
|
24
|
+
return 'IllumaBedrockConverse';
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Override _streamResponseChunks to strip contentBlockIndex from response_metadata
|
|
28
|
+
* This prevents LangChain's merge conflicts when the same index is used for
|
|
29
|
+
* different content types (text vs tool calls)
|
|
30
|
+
*/
|
|
31
|
+
async *_streamResponseChunks(messages$1, options, runManager) {
|
|
32
|
+
const baseStream = super._streamResponseChunks(messages$1, options, runManager);
|
|
33
|
+
for await (const chunk of baseStream) {
|
|
34
|
+
// Only process if we have response_metadata
|
|
35
|
+
if (chunk.message instanceof messages.AIMessageChunk &&
|
|
36
|
+
chunk.message.response_metadata &&
|
|
37
|
+
typeof chunk.message.response_metadata === 'object') {
|
|
38
|
+
// Check if contentBlockIndex exists anywhere in response_metadata (top level or nested)
|
|
39
|
+
const hasContentBlockIndex = this.hasContentBlockIndex(chunk.message.response_metadata);
|
|
40
|
+
if (hasContentBlockIndex) {
|
|
41
|
+
const cleanedMetadata = this.removeContentBlockIndex(chunk.message.response_metadata);
|
|
42
|
+
yield new outputs.ChatGenerationChunk({
|
|
43
|
+
text: chunk.text,
|
|
44
|
+
message: new messages.AIMessageChunk({
|
|
45
|
+
...chunk.message,
|
|
46
|
+
response_metadata: cleanedMetadata,
|
|
47
|
+
}),
|
|
48
|
+
generationInfo: chunk.generationInfo,
|
|
49
|
+
});
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
yield chunk;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Check if contentBlockIndex exists at any level in the object
|
|
58
|
+
*/
|
|
59
|
+
hasContentBlockIndex(obj) {
|
|
60
|
+
if (obj === null || obj === undefined || typeof obj !== 'object') {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
if ('contentBlockIndex' in obj) {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
for (const value of Object.values(obj)) {
|
|
67
|
+
if (typeof value === 'object' && value !== null) {
|
|
68
|
+
if (this.hasContentBlockIndex(value)) {
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Recursively remove contentBlockIndex from all levels of an object
|
|
77
|
+
*/
|
|
78
|
+
removeContentBlockIndex(obj) {
|
|
79
|
+
if (obj === null || obj === undefined) {
|
|
80
|
+
return obj;
|
|
81
|
+
}
|
|
82
|
+
if (Array.isArray(obj)) {
|
|
83
|
+
return obj.map((item) => this.removeContentBlockIndex(item));
|
|
84
|
+
}
|
|
85
|
+
if (typeof obj === 'object') {
|
|
86
|
+
const cleaned = {};
|
|
87
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
88
|
+
if (key !== 'contentBlockIndex') {
|
|
89
|
+
cleaned[key] = this.removeContentBlockIndex(value);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return cleaned;
|
|
93
|
+
}
|
|
94
|
+
return obj;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
exports.CustomChatBedrockConverse = CustomChatBedrockConverse;
|
|
99
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../../../src/llm/bedrock/index.ts"],"sourcesContent":["/**\n * Optimized ChatBedrockConverse wrapper that fixes contentBlockIndex conflicts\n *\n * Bedrock sends the same contentBlockIndex for both text and tool_use content blocks,\n * causing LangChain's merge logic to fail with \"field[contentBlockIndex] already exists\"\n * errors. This wrapper simply strips contentBlockIndex from response_metadata to avoid\n * the conflict.\n *\n * The contentBlockIndex field is only used internally by Bedrock's streaming protocol\n * and isn't needed by application logic - the index field on tool_call_chunks serves\n * the purpose of tracking tool call ordering.\n */\n\nimport { ChatBedrockConverse } from '@langchain/aws';\nimport type { ChatBedrockConverseInput } from '@langchain/aws';\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\nexport class CustomChatBedrockConverse extends ChatBedrockConverse {\n constructor(fields?: ChatBedrockConverseInput) {\n super(fields);\n }\n\n static lc_name(): string {\n return 'IllumaBedrockConverse';\n }\n\n /**\n * Override _streamResponseChunks to strip contentBlockIndex from response_metadata\n * This prevents LangChain's merge conflicts when the same index is used for\n * different content types (text vs tool calls)\n */\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const baseStream = super._streamResponseChunks(\n messages,\n options,\n runManager\n );\n\n for await (const chunk of baseStream) {\n // Only process if we have response_metadata\n if (\n chunk.message instanceof AIMessageChunk &&\n (chunk.message as Partial<AIMessageChunk>).response_metadata &&\n typeof chunk.message.response_metadata === 'object'\n ) {\n // Check if contentBlockIndex exists anywhere in response_metadata (top level or nested)\n const hasContentBlockIndex = this.hasContentBlockIndex(\n chunk.message.response_metadata\n );\n\n if (hasContentBlockIndex) {\n const cleanedMetadata = this.removeContentBlockIndex(\n chunk.message.response_metadata\n ) as Record<string, unknown>;\n\n yield new ChatGenerationChunk({\n text: chunk.text,\n message: new AIMessageChunk({\n ...chunk.message,\n response_metadata: cleanedMetadata,\n }),\n generationInfo: chunk.generationInfo,\n });\n continue;\n }\n }\n\n yield chunk;\n }\n }\n\n /**\n * Check if contentBlockIndex exists at any level in the object\n */\n private hasContentBlockIndex(obj: unknown): boolean {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return false;\n }\n\n if ('contentBlockIndex' in obj) {\n return true;\n }\n\n for (const value of Object.values(obj)) {\n if (typeof value === 'object' && value !== null) {\n if (this.hasContentBlockIndex(value)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Recursively remove contentBlockIndex from all levels of an object\n */\n private removeContentBlockIndex(obj: unknown): unknown {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => this.removeContentBlockIndex(item));\n }\n\n if (typeof obj === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (key !== 'contentBlockIndex') {\n cleaned[key] = this.removeContentBlockIndex(value);\n }\n }\n return cleaned;\n }\n\n return obj;\n }\n}\n\nexport type { ChatBedrockConverseInput };\n"],"names":["ChatBedrockConverse","messages","AIMessageChunk","ChatGenerationChunk"],"mappings":";;;;;;AAAA;;;;;;;;;;;AAWG;AASG,MAAO,yBAA0B,SAAQA,uBAAmB,CAAA;AAChE,IAAA,WAAA,CAAY,MAAiC,EAAA;QAC3C,KAAK,CAAC,MAAM,CAAC;;AAGf,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,uBAAuB;;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K,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE;AAC/C,gBAAA,IAAI,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC,EAAE;AACpC,oBAAA,OAAO,IAAI;;;;AAKjB,QAAA,OAAO,KAAK;;AAGd;;AAEG;AACK,IAAA,uBAAuB,CAAC,GAAY,EAAA;QAC1C,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,EAAE;AACrC,YAAA,OAAO,GAAG;;AAGZ,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AACtB,YAAA,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;;AAG9D,QAAA,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;YAC3B,MAAM,OAAO,GAA4B,EAAE;AAC3C,YAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AAC9C,gBAAA,IAAI,GAAG,KAAK,mBAAmB,EAAE;oBAC/B,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC;;;AAGtD,YAAA,OAAO,OAAO;;AAGhB,QAAA,OAAO,GAAG;;AAEb;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake.cjs","sources":["../../../src/llm/fake.ts"],"sourcesContent":["import { ChatGenerationChunk } from '@langchain/core/outputs';\
|
|
1
|
+
{"version":3,"file":"fake.cjs","sources":["../../../src/llm/fake.ts"],"sourcesContent":["import { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { FakeListChatModel } from '@langchain/core/utils/testing';\nimport { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\n\ntype SplitStrategy = {\n type: 'regex' | 'fixed';\n value: RegExp | number;\n};\n\nexport class FakeChatModel extends FakeListChatModel {\n private splitStrategy: SplitStrategy;\n private toolCalls: ToolCall[] = [];\n private addedToolCalls: boolean = false;\n\n constructor({\n responses,\n sleep,\n emitCustomEvent,\n splitStrategy = { type: 'regex', value: /(?<=\\s+)|(?=\\s+)/ },\n toolCalls = []\n }: {\n responses: string[];\n sleep?: number;\n emitCustomEvent?: boolean;\n splitStrategy?: SplitStrategy;\n toolCalls?: ToolCall[];\n }) {\n super({ responses, sleep, emitCustomEvent });\n this.splitStrategy = splitStrategy;\n this.toolCalls = toolCalls;\n }\n\n private splitText(text: string): string[] {\n if (this.splitStrategy.type === 'regex') {\n return text.split(this.splitStrategy.value as RegExp);\n } else {\n const chunkSize = this.splitStrategy.value as number;\n const chunks: string[] = [];\n for (let i = 0; i < text.length; i += chunkSize) {\n chunks.push(text.slice(i, i + chunkSize));\n }\n return chunks;\n }\n }\n _createResponseChunk(text: string, tool_call_chunks?: ToolCallChunk[]): ChatGenerationChunk {\n return new ChatGenerationChunk({\n text,\n generationInfo: {},\n message: new AIMessageChunk({\n content: text,\n tool_call_chunks,\n additional_kwargs: tool_call_chunks ? {\n tool_calls: tool_call_chunks.map((toolCall) => ({\n index: toolCall.index ?? 0,\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name ?? '',\n arguments: toolCall.args ?? '',\n },\n })),\n } : undefined,\n })});\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const response = this._currentResponse();\n this._incrementResponse();\n\n if (this.emitCustomEvent) {\n await runManager?.handleCustomEvent('some_test_event', {\n someval: true,\n });\n }\n\n const chunks = this.splitText(response);\n for await (const chunk of chunks) {\n await this._sleepIfRequested();\n\n if (options.thrownErrorString != null && options.thrownErrorString) {\n throw new Error(options.thrownErrorString);\n }\n\n const responseChunk = super._createResponseChunk(chunk);\n yield responseChunk;\n void runManager?.handleLLMNewToken(chunk);\n }\n\n await this._sleepIfRequested();\n if (this.toolCalls.length > 0 && !this.addedToolCalls) {\n this.addedToolCalls = true;\n const toolCallChunks = this.toolCalls.map((toolCall) => {;\n return {\n name: toolCall.name,\n args: JSON.stringify(toolCall.args),\n id: toolCall.id,\n type: 'tool_call_chunk',\n } as ToolCallChunk;\n });\n const responseChunk = this._createResponseChunk('', toolCallChunks);\n yield responseChunk;\n void runManager?.handleLLMNewToken('');\n }\n }\n}\n\nexport function createFakeStreamingLLM({\n responses,\n sleep,\n splitStrategy,\n toolCalls,\n} : {\n responses: string[],\n sleep?: number,\n splitStrategy?: SplitStrategy,\n toolCalls?: ToolCall[]\n}\n): FakeChatModel {\n return new FakeChatModel({\n sleep,\n responses,\n emitCustomEvent: true,\n splitStrategy,\n toolCalls,\n });\n}\n"],"names":["FakeListChatModel","ChatGenerationChunk","AIMessageChunk"],"mappings":";;;;;;AAYM,MAAO,aAAc,SAAQA,yBAAiB,CAAA;AAC1C,IAAA,aAAa;IACb,SAAS,GAAe,EAAE;IAC1B,cAAc,GAAY,KAAK;IAEvC,WAAY,CAAA,EACV,SAAS,EACT,KAAK,EACL,eAAe,EACf,aAAa,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,EAC5D,SAAS,GAAG,EAAE,EAOf,EAAA;QACC,KAAK,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;AAC5C,QAAA,IAAI,CAAC,aAAa,GAAG,aAAa;AAClC,QAAA,IAAI,CAAC,SAAS,GAAG,SAAS;;AAGpB,IAAA,SAAS,CAAC,IAAY,EAAA;QAC5B,IAAI,IAAI,CAAC,aAAa,CAAC,IAAI,KAAK,OAAO,EAAE;YACvC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,KAAe,CAAC;;aAChD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