Skip to content

The agent engineering platform.

fix(core): ensure `tool_call_count` is never null (#34431)

Mason Daugherty04ec6cacaf8f
diff --git a/libs/core/langchain_core/tracers/core.py b/libs/core/langchain_core/tracers/core.py
index 76a4a0356f..ea67caf444 100644
--- a/libs/core/langchain_core/tracers/core.py
+++ b/libs/core/langchain_core/tracers/core.py
@@ -289,7 +289,7 @@ class _TracerCore(ABC):
for generation in generations:
if hasattr(generation, "message"):
msg = generation.message
- if hasattr(msg, "tool_calls"):
+ if hasattr(msg, "tool_calls") and msg.tool_calls:
tool_call_count += len(msg.tool_calls)
if tool_call_count > 0:
llm_run.extra["tool_call_count"] = tool_call_count
diff --git a/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py b/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py
index 147997c2c1..c9d4797e74 100644
--- a/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py
+++ b/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py
@@ -126,3 +126,30 @@ def test_complete_llm_run_counts_tool_calls_from_multiple_generations() -> None:
completed_run = tracer._complete_llm_run(response=response, run_id=run.id)
assert completed_run.extra["tool_call_count"] == 3
+
+
+def test_complete_llm_run_handles_null_tool_calls() -> None:
+ """Test that `_complete_llm_run` handles null `tool_calls` gracefully."""
+ tracer = MockTracerCore()
+
+ run = MagicMock(spec=Run)
+ run.id = "test-llm-run-id-null-tools"
+ run.run_type = "llm"
+ run.extra = {}
+ run.outputs = {}
+ run.events = []
+ run.end_time = None
+ run.inputs = {}
+
+ tracer.run_map[str(run.id)] = run
+
+ message = AIMessage(content="Test with null tool_calls")
+ generation = ChatGeneration(message=message)
+ # Bypass Pydantic validation by directly setting attribute
+ object.__setattr__(message, "tool_calls", None)
+ response = LLMResult(generations=[[generation]])
+
+ # Should not raise TypeError from len(None)
+ completed_run = tracer._complete_llm_run(response=response, run_id=run.id)
+
+ assert "tool_call_count" not in completed_run.extra