fix(api): Robustly handle complex LangChain message content in API responses and persistence

This commit is contained in:
Yunxiao Xu
2026-02-11 15:53:11 -08:00
parent 85329cffda
commit b7abdfe457
3 changed files with 60 additions and 10 deletions

View File

@@ -1,5 +1,6 @@
from datetime import timedelta
from ea_chatbot.api.utils import create_access_token, decode_access_token
from ea_chatbot.api.utils import create_access_token, decode_access_token, convert_to_json_compatible
from langchain_core.messages import AIMessage
def test_create_and_decode_access_token():
"""Test that a token can be created and then decoded."""
@@ -22,3 +23,29 @@ def test_expired_token():
token = create_access_token(data, expires_delta=timedelta(minutes=-1))
assert decode_access_token(token) is None
def test_convert_to_json_compatible_complex_message():
"""Test that list-based message content is handled correctly."""
# Mock a message with list-based content (blocks)
msg = AIMessage(content=[
{"type": "text", "text": "Hello "},
{"type": "text", "text": "world!"},
{"type": "other", "data": "ignore me"}
])
result = convert_to_json_compatible(msg)
assert result["content"] == "Hello world!"
assert result["type"] == "ai"
def test_convert_to_json_compatible_message_with_text_prop():
"""Test that .text property is prioritized if available."""
# Using a MagicMock to simulate the property safely
from unittest.mock import MagicMock
msg = MagicMock(spec=AIMessage)
msg.content = "Raw content"
msg.text = "Just the text"
msg.type = "ai"
msg.additional_kwargs = {}
result = convert_to_json_compatible(msg)
assert result["content"] == "Just the text"