Skip to content

The agent engineering platform.

fix(core): raise ValueError when explicit tool_outputs length mismatches tool_calls in tool_example_to_messages (#39142)

Rin61c5678835a6
diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.py
index 1e63802a5d..301b5241e1 100644
--- a/libs/core/langchain_core/utils/function_calling.py
+++ b/libs/core/langchain_core/utils/function_calling.py
@@ -713,6 +713,13 @@ def tool_example_to_messages(
messages.append(
AIMessage(content="", additional_kwargs={"tool_calls": openai_tool_calls})
)
+ if tool_outputs is not None and len(tool_outputs) != len(openai_tool_calls):
+ msg = (
+ f"The number of tool_outputs ({len(tool_outputs)}) must match the number "
+ f"of tool_calls ({len(openai_tool_calls)}). Got {len(tool_outputs)} "
+ f"output(s) for {len(openai_tool_calls)} tool call(s)."
+ )
+ raise ValueError(msg)
tool_outputs = tool_outputs or ["You have correctly called this tool."] * len(
openai_tool_calls
)
diff --git a/libs/core/tests/unit_tests/utils/test_function_calling.py b/libs/core/tests/unit_tests/utils/test_function_calling.py
index 395ecbc4e4..e53c034406 100644
--- a/libs/core/tests/unit_tests/utils/test_function_calling.py
+++ b/libs/core/tests/unit_tests/utils/test_function_calling.py
@@ -795,6 +795,24 @@ def test_tool_outputs() -> None:
assert not response.tool_calls
+def test_tool_outputs_fewer_than_tool_calls_raises() -> None:
+ with pytest.raises(ValueError, match="must match"):
+ tool_example_to_messages(
+ input="Extract both values",
+ tool_calls=[FakeCall(data="a"), FakeCall(data="b")],
+ tool_outputs=["only one output"],
+ )
+
+
+def test_tool_outputs_more_than_tool_calls_raises() -> None:
+ with pytest.raises(ValueError, match="must match"):
+ tool_example_to_messages(
+ input="Extract one value",
+ tool_calls=[FakeCall(data="a")],
+ tool_outputs=["output1", "extra output"],
+ )
+
+
@pytest.mark.parametrize(
"typed_dict",
[ExtensionsTypedDict, TypingTypedDict],