mirror of
https://github.com/khoj-ai/khoj.git
synced 2024-11-23 15:38:55 +01:00
Improve serializing conversation JSON to print messages on console
- Handle chatml message.content with non-json serializable data like WebP image binary data used by Gemini models
This commit is contained in:
parent
3f70d2f685
commit
9e74de9b4f
1 changed files with 16 additions and 2 deletions
|
@ -740,6 +740,20 @@ Metadata
|
|||
|
||||
def messages_to_print(messages: list[ChatMessage], max_length: int = 70) -> str:
|
||||
"""
|
||||
Format, truncate messages to print
|
||||
Format and truncate messages to print, ensuring JSON serializable content
|
||||
"""
|
||||
return "\n".join([f"{json.dumps(message.content)[:max_length]}..." for message in messages])
|
||||
|
||||
def safe_serialize(content: Any) -> str:
|
||||
try:
|
||||
# Try JSON serialization
|
||||
json.dumps(content)
|
||||
return content
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
# Handle non-serializable types
|
||||
if hasattr(content, "format") and content.format == "WEBP":
|
||||
return "[WebP Image]"
|
||||
elif hasattr(content, "__dict__"):
|
||||
return str(content.__dict__)
|
||||
return str(content)
|
||||
|
||||
return "\n".join([f"{json.dumps(safe_serialize(message.content))[:max_length]}..." for message in messages])
|
||||
|
|
Loading…
Reference in a new issue