AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Explicit Empty Tool_calls List In AIMessage Is Incorrectly Rehydrated From Additional_kwargs During Serialization

When an AIMessage has tool_calls explicitly set to an empty list while additional_kwargs still contains the original OpenAI tool call payload, the _backwards_compat_tool_calls validator treats the empty list as missing and re-parses the additional_kwargs, causing the cleared tool calls to reappear after deserialization or model reconstruction.

highConfidence 95%LangchainAffected V1.6.3

Origin Analysis

The _backwards_compat_tool_calls method uses `not any(values.get(k) for k in ...)` to check if tool_calls is present. An empty list is falsy, so `any()` returns False, causing the method to conclude that tool_calls is not provided and fall back to additional_kwargs['tool_calls']. This violates the explicit intent of the user to clear all tool calls.
1. Create an AIMessage with content='x', tool_calls=[{'name': 'keep', 'args': {}, 'id': '1', 'type': 'tool_call'}], and additional_kwargs={'tool_calls': [{'id': 'call_1', 'type': 'function', 'function': {'name': 'secret_tool', 'arguments': '{"q": 1}'}}]}. 2. Use model_copy(update={'tool_calls': []}) to clear tool_calls. 3. Observe that cleared.tool_calls is []. 4. Serialize and deserialize using loads(dumps(cleared)) or rebuild via AIMessage(**model_dump()), and note that tool_calls now contains the secret_tool call from additional_kwargs.

Fixing Code Block

Edge Case Audit

The change may affect edge cases where code previously relied on an empty list to trigger fallback (though that behavior is now considered a bug). Rollback suggestion: if regressions are found, revert to the original validator but consider adding an explicit sentinel for missing vs empty. Thoroughly test serialization round-trips for messages with both empty and populated additional_kwargs. Also verify compatibility with Pydantic model validation order and any subclasses that override tool_calls.

Ecosystem Topology