1 """Debug traces for conversation."""
3 from collections.abc
import Generator
4 from contextlib
import contextmanager
5 from contextvars
import ContextVar
6 from dataclasses
import asdict, dataclass, field
17 """Type of an event emitted during a conversation."""
19 ASYNC_PROCESS =
"async_process"
20 """The conversation is started from user input."""
22 AGENT_DETAIL =
"agent_detail"
23 """Event detail added by a conversation agent."""
25 TOOL_CALL =
"tool_call"
26 """A conversation agent Tool call or default agent intent call."""
29 @dataclass(frozen=True)
31 """Event emitted during a conversation."""
33 event_type: ConversationTraceEventType
34 data: dict[str, Any] |
None =
None
35 timestamp: str = field(default_factory=
lambda: dt_util.utcnow().isoformat())
39 """Stores debug data related to a conversation."""
42 """Initialize ConversationTrace."""
44 self._events: list[ConversationTraceEvent] = []
45 self.
_error_error: Exception |
None =
None
46 self.
_result_result: dict[str, Any] = {}
50 """Identifier for this trace."""
53 def add_event(self, event: ConversationTraceEvent) ->
None:
54 """Add an event to the trace."""
55 self._events.append(event)
66 """Return dictionary version of this ConversationTrace."""
67 result: dict[str, Any] = {
69 "events": [asdict(event)
for event
in self._events],
71 if self.
_error_error
is not None:
72 result[
"error"] =
str(self.
_error_error)
or self.
_error_error.__class__.__name__
73 if self.
_result_result
is not None:
74 result[
"result"] = self.
_result_result
78 _current_trace: ContextVar[ConversationTrace |
None] = ContextVar(
79 "current_trace", default=
None
81 _recent_traces: LimitedSizeDict[str, ConversationTrace] =
LimitedSizeDict(
82 size_limit=STORED_TRACES
87 event_type: ConversationTraceEventType, event_data: dict[str, Any]
89 """Append a ConversationTraceEvent to the current active trace."""
90 trace = _current_trace.get()
98 """Create a new active ConversationTrace."""
100 token = _current_trace.set(trace)
101 _recent_traces[trace.trace_id] = trace
104 except Exception
as ex:
108 _current_trace.reset(token)
112 """Get the most recent traces."""
113 return list(_recent_traces.values())
117 """Clear all traces."""
118 _recent_traces.clear()
dict[str, Any] as_dict(self)
None set_error(self, Exception ex)
None set_result(self, **Any kwargs)
None add_event(self, ConversationTraceEvent event)
list[ConversationTrace] async_get_traces()
None async_conversation_trace_append(ConversationTraceEventType event_type, dict[str, Any] event_data)
Generator[ConversationTrace] async_conversation_trace()
None async_clear_traces()