Skip to content

Commit 9b42349

Browse files
authored
fix(llm-observability): flatten langchain's additional_kwargs (#166)
* fix: flatten additional_kwargs * fix: remove print
1 parent 7870ccd commit 9b42349

File tree

2 files changed

+43
-5
lines changed

2 files changed

+43
-5
lines changed

posthog/ai/langchain/callbacks.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,8 @@ def _convert_message_to_dict(message: BaseMessage) -> Dict[str, Any]:
333333
else:
334334
message_dict = {"role": message.type, "content": str(message.content)}
335335

336-
if "name" in message.additional_kwargs:
337-
message_dict["name"] = message.additional_kwargs["name"]
338336
if message.additional_kwargs:
339-
message_dict["additional_kwargs"] = message.additional_kwargs
337+
message_dict.update(message.additional_kwargs)
340338

341339
return message_dict
342340

posthog/test/ai/langchain/test_callbacks.py

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,7 @@ def test_openai_chain(mock_client):
448448
{
449449
"role": "assistant",
450450
"content": "Bar",
451-
"additional_kwargs": {"refusal": None},
451+
"refusal": None,
452452
}
453453
]
454454
}
@@ -491,7 +491,7 @@ def test_openai_captures_multiple_generations(mock_client):
491491
{
492492
"role": "assistant",
493493
"content": "Bar",
494-
"additional_kwargs": {"refusal": None},
494+
"refusal": None,
495495
},
496496
{
497497
"role": "assistant",
@@ -650,3 +650,43 @@ def test_privacy_mode_global(mock_client):
650650
call = mock_client.capture.call_args[1]
651651
assert call["properties"]["$ai_input"] is None
652652
assert call["properties"]["$ai_output"] is None
653+
654+
655+
def test_tool_calls(mock_client):
656+
prompt = ChatPromptTemplate.from_messages([("user", "Foo")])
657+
model = FakeMessagesListChatModel(
658+
responses=[
659+
AIMessage(
660+
content="Bar",
661+
additional_kwargs={
662+
"tool_calls": [
663+
{
664+
"type": "function",
665+
"id": "123",
666+
"function": {
667+
"name": "test",
668+
"args": '{"a": 1}',
669+
},
670+
}
671+
]
672+
},
673+
)
674+
]
675+
)
676+
chain = prompt | model
677+
callbacks = CallbackHandler(mock_client)
678+
chain.invoke({}, config={"callbacks": [callbacks]})
679+
680+
assert mock_client.capture.call_count == 1
681+
call = mock_client.capture.call_args[1]
682+
assert call["properties"]["$ai_output"]["choices"][0]["tool_calls"] == [
683+
{
684+
"type": "function",
685+
"id": "123",
686+
"function": {
687+
"name": "test",
688+
"args": '{"a": 1}',
689+
},
690+
}
691+
]
692+
assert "additional_kwargs" not in call["properties"]["$ai_output"]["choices"][0]

0 commit comments

Comments
 (0)