Skip to content

Commit 6125d2a

Browse files
committed
fix(langchain): convert invalid_tool_calls to ToolCallSchema and skip empty lists
- Apply the same {id, type, name, arguments, error} conversion to invalid_tool_calls as is done for tool_calls - Only assign tool_calls / invalid_tool_calls to message_dict when the converted list is non-empty
1 parent 732f005 commit 6125d2a

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

langfuse/langchain/CallbackHandler.py

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,14 +1122,40 @@ def _convert_message_to_dict(self, message: BaseMessage) -> Dict[str, Any]:
11221122
"arguments": arguments,
11231123
}
11241124
)
1125-
message_dict["tool_calls"] = converted_tool_calls
1125+
if converted_tool_calls:
1126+
message_dict["tool_calls"] = converted_tool_calls
11261127

11271128
if (
1128-
hasattr(message, "invalid_tool_calls")
1129-
and message.invalid_tool_calls is not None
1129+
hasattr(message, "invalid_tool_calls")
1130+
and message.invalid_tool_calls is not None
11301131
and len(message.invalid_tool_calls) > 0
11311132
):
1132-
message_dict["invalid_tool_calls"] = message.invalid_tool_calls
1133+
converted_invalid_tool_calls = []
1134+
for tc in message.invalid_tool_calls:
1135+
if not isinstance(tc, dict):
1136+
langfuse_logger.debug(
1137+
"Skipping invalid_tool_call entry that is not a dict: %s",
1138+
tc,
1139+
)
1140+
continue
1141+
try:
1142+
arguments = json.dumps(tc.get("args", {}))
1143+
except (TypeError, ValueError) as e:
1144+
langfuse_logger.debug(
1145+
"Failed to serialize invalid tool call args to JSON: %s", e
1146+
)
1147+
arguments = "{}"
1148+
converted_invalid_tool_calls.append(
1149+
{
1150+
"id": tc.get("id", ""),
1151+
"type": "function",
1152+
"name": tc.get("name", ""),
1153+
"arguments": arguments,
1154+
"error": tc.get("error", ""),
1155+
}
1156+
)
1157+
if converted_invalid_tool_calls:
1158+
message_dict["invalid_tool_calls"] = converted_invalid_tool_calls
11331159

11341160
elif isinstance(message, SystemMessage):
11351161
message_dict = {"role": "system", "content": message.content}

0 commit comments

Comments
 (0)