Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import uuid
import json
from typing import Optional, List, Any, Union, AsyncGenerator, Generator
from dataclasses import is_dataclass, asdict
from datetime import date, datetime

from langgraph.graph.state import CompiledStateGraph
from langchain.schema import BaseMessage, SystemMessage
Expand All @@ -29,7 +27,9 @@
langchain_messages_to_agui,
resolve_reasoning_content,
resolve_message_content,
camel_to_snake
camel_to_snake,
json_safe_stringify,
make_json_safe
)

from ag_ui.core import (
Expand Down Expand Up @@ -90,7 +90,12 @@ def __init__(self, *, name: str, graph: CompiledStateGraph, description: Optiona
self.active_step = None

def _dispatch_event(self, event: ProcessedEvents) -> str:
return event # Fallback if no encoder
if event.type == EventType.RAW:
event.event = make_json_safe(event.event)
elif event.raw_event:
event.raw_event = make_json_safe(event.raw_event)

return event

async def run(self, input: RunAgentInput) -> AsyncGenerator[str, None]:
forwarded_props = {}
Expand Down Expand Up @@ -224,7 +229,7 @@ async def _handle_stream_events(self, input: RunAgentInput) -> AsyncGenerator[st
CustomEvent(
type=EventType.CUSTOM,
name=LangGraphEventTypes.OnInterrupt.value,
value=json.dumps(interrupt.value, default=make_json_safe) if not isinstance(interrupt.value, str) else interrupt.value,
value=json.dumps(interrupt.value, default=json_safe_stringify) if not isinstance(interrupt.value, str) else interrupt.value,
raw_event=interrupt,
)
)
Expand Down Expand Up @@ -735,16 +740,3 @@ def end_step(self):
self.active_run["node_name"] = None
self.active_step = None
return dispatch

def make_json_safe(o):
if is_dataclass(o): # dataclasses like Flight(...)
return asdict(o)
if hasattr(o, "model_dump"): # pydantic v2
return o.model_dump()
if hasattr(o, "dict"): # pydantic v1
return o.dict()
if hasattr(o, "__dict__"): # plain objects
return vars(o)
if isinstance(o, (datetime, date)):
return o.isoformat()
return str(o) # last resort
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import json
import re
from typing import List, Any, Dict, Union
from dataclasses import is_dataclass, asdict
from datetime import date, datetime

from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage, ToolMessage
from ag_ui.core import (
Expand Down Expand Up @@ -177,3 +179,60 @@ def resolve_message_content(content: Any) -> str | None:

def camel_to_snake(name):
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()

def json_safe_stringify(o):
if is_dataclass(o): # dataclasses like Flight(...)
return asdict(o)
if hasattr(o, "model_dump"): # pydantic v2
return o.model_dump()
if hasattr(o, "dict"): # pydantic v1
return o.dict()
if hasattr(o, "__dict__"): # plain objects
return vars(o)
if isinstance(o, (datetime, date)):
return o.isoformat()
return str(o) # last resort

def make_json_safe(value: Any) -> Any:
"""
Recursively convert a value into a JSON-serializable structure.

- Handles Pydantic models via `model_dump`.
- Handles LangChain messages via `to_dict`.
- Recursively walks dicts, lists, and tuples.
- For arbitrary objects, falls back to `__dict__` if available, else `repr()`.
"""
# Pydantic models
if hasattr(value, "model_dump"):
try:
return make_json_safe(value.model_dump(by_alias=True, exclude_none=True))
except Exception:
pass

# LangChain-style objects
if hasattr(value, "to_dict"):
try:
return make_json_safe(value.to_dict())
except Exception:
pass

# Dict
if isinstance(value, dict):
return {key: make_json_safe(sub_value) for key, sub_value in value.items()}

# List / tuple
if isinstance(value, (list, tuple)):
return [make_json_safe(sub_value) for sub_value in value]

# Already JSON safe
if isinstance(value, (str, int, float, bool)) or value is None:
return value

# Arbitrary object: try __dict__ first, fallback to repr
if hasattr(value, "__dict__"):
return {
"__type__": type(value).__name__,
**make_json_safe(value.__dict__),
}

return repr(value)
Loading