Skip to content

Commit 31ed091

Browse files
docs: Fix tracing setup documentation (openai#1734)
1 parent 4901770 commit 31ed091

File tree

3 files changed

+270
-27
lines changed

3 files changed

+270
-27
lines changed

src/agents/tracing/processor_interface.py

Lines changed: 84 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,52 +7,125 @@
77

88

99
class TracingProcessor(abc.ABC):
10-
"""Interface for processing spans."""
10+
"""Interface for processing and monitoring traces and spans in the OpenAI Agents system.
11+
12+
This abstract class defines the interface that all tracing processors must implement.
13+
Processors receive notifications when traces and spans start and end, allowing them
14+
to collect, process, and export tracing data.
15+
16+
Example:
17+
```python
18+
class CustomProcessor(TracingProcessor):
19+
def __init__(self):
20+
self.active_traces = {}
21+
self.active_spans = {}
22+
23+
def on_trace_start(self, trace):
24+
self.active_traces[trace.trace_id] = trace
25+
26+
def on_trace_end(self, trace):
27+
# Process completed trace
28+
del self.active_traces[trace.trace_id]
29+
30+
def on_span_start(self, span):
31+
self.active_spans[span.span_id] = span
32+
33+
def on_span_end(self, span):
34+
# Process completed span
35+
del self.active_spans[span.span_id]
36+
37+
def shutdown(self):
38+
# Clean up resources
39+
self.active_traces.clear()
40+
self.active_spans.clear()
41+
42+
def force_flush(self):
43+
# Force processing of any queued items
44+
pass
45+
```
46+
47+
Notes:
48+
- All methods should be thread-safe
49+
- Methods should not block for long periods
50+
- Handle errors gracefully to prevent disrupting agent execution
51+
"""
1152

1253
@abc.abstractmethod
1354
def on_trace_start(self, trace: "Trace") -> None:
14-
"""Called when a trace is started.
55+
"""Called when a new trace begins execution.
1556
1657
Args:
17-
trace: The trace that started.
58+
trace: The trace that started. Contains workflow name and metadata.
59+
60+
Notes:
61+
- Called synchronously on trace start
62+
- Should return quickly to avoid blocking execution
63+
- Any errors should be caught and handled internally
1864
"""
1965
pass
2066

2167
@abc.abstractmethod
2268
def on_trace_end(self, trace: "Trace") -> None:
23-
"""Called when a trace is finished.
69+
"""Called when a trace completes execution.
2470
2571
Args:
26-
trace: The trace that finished.
72+
trace: The completed trace containing all spans and results.
73+
74+
Notes:
75+
- Called synchronously when trace finishes
76+
- Good time to export/process the complete trace
77+
- Should handle cleanup of any trace-specific resources
2778
"""
2879
pass
2980

3081
@abc.abstractmethod
3182
def on_span_start(self, span: "Span[Any]") -> None:
32-
"""Called when a span is started.
83+
"""Called when a new span begins execution.
3384
3485
Args:
35-
span: The span that started.
86+
span: The span that started. Contains operation details and context.
87+
88+
Notes:
89+
- Called synchronously on span start
90+
- Should return quickly to avoid blocking execution
91+
- Spans are automatically nested under current trace/span
3692
"""
3793
pass
3894

3995
@abc.abstractmethod
4096
def on_span_end(self, span: "Span[Any]") -> None:
41-
"""Called when a span is finished. Should not block or raise exceptions.
97+
"""Called when a span completes execution.
4298
4399
Args:
44-
span: The span that finished.
100+
span: The completed span containing execution results.
101+
102+
Notes:
103+
- Called synchronously when span finishes
104+
- Should not block or raise exceptions
105+
- Good time to export/process the individual span
45106
"""
46107
pass
47108

48109
@abc.abstractmethod
49110
def shutdown(self) -> None:
50-
"""Called when the application stops."""
111+
"""Called when the application stops to clean up resources.
112+
113+
Should perform any necessary cleanup like:
114+
- Flushing queued traces/spans
115+
- Closing connections
116+
- Releasing resources
117+
"""
51118
pass
52119

53120
@abc.abstractmethod
54121
def force_flush(self) -> None:
55-
"""Forces an immediate flush of all queued spans/traces."""
122+
"""Forces immediate processing of any queued traces/spans.
123+
124+
Notes:
125+
- Should process all queued items before returning
126+
- Useful before shutdown or when immediate processing is needed
127+
- May block while processing completes
128+
"""
56129
pass
57130

58131

src/agents/tracing/spans.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,83 @@
1616

1717

1818
class SpanError(TypedDict):
19+
"""Represents an error that occurred during span execution.
20+
21+
Attributes:
22+
message: A human-readable error description
23+
data: Optional dictionary containing additional error context
24+
"""
1925
message: str
2026
data: dict[str, Any] | None
2127

2228

2329
class Span(abc.ABC, Generic[TSpanData]):
30+
"""Base class for representing traceable operations with timing and context.
31+
32+
A span represents a single operation within a trace (e.g., an LLM call, tool execution,
33+
or agent run). Spans track timing, relationships between operations, and operation-specific
34+
data.
35+
36+
Type Args:
37+
TSpanData: The type of span-specific data this span contains.
38+
39+
Example:
40+
```python
41+
# Creating a custom span
42+
with custom_span("database_query", {
43+
"operation": "SELECT",
44+
"table": "users"
45+
}) as span:
46+
results = await db.query("SELECT * FROM users")
47+
span.set_output({"count": len(results)})
48+
49+
# Handling errors in spans
50+
with custom_span("risky_operation") as span:
51+
try:
52+
result = perform_risky_operation()
53+
except Exception as e:
54+
span.set_error({
55+
"message": str(e),
56+
"data": {"operation": "risky_operation"}
57+
})
58+
raise
59+
```
60+
61+
Notes:
62+
- Spans automatically nest under the current trace
63+
- Use context managers for reliable start/finish
64+
- Include relevant data but avoid sensitive information
65+
- Handle errors properly using set_error()
66+
"""
67+
2468
@property
2569
@abc.abstractmethod
2670
def trace_id(self) -> str:
71+
"""The ID of the trace this span belongs to.
72+
73+
Returns:
74+
str: Unique identifier of the parent trace.
75+
"""
2776
pass
2877

2978
@property
3079
@abc.abstractmethod
3180
def span_id(self) -> str:
81+
"""Unique identifier for this span.
82+
83+
Returns:
84+
str: The span's unique ID within its trace.
85+
"""
3286
pass
3387

3488
@property
3589
@abc.abstractmethod
3690
def span_data(self) -> TSpanData:
91+
"""Operation-specific data for this span.
92+
93+
Returns:
94+
TSpanData: Data specific to this type of span (e.g., LLM generation data).
95+
"""
3796
pass
3897

3998
@abc.abstractmethod
@@ -67,6 +126,11 @@ def __exit__(self, exc_type, exc_val, exc_tb):
67126
@property
68127
@abc.abstractmethod
69128
def parent_id(self) -> str | None:
129+
"""ID of the parent span, if any.
130+
131+
Returns:
132+
str | None: The parent span's ID, or None if this is a root span.
133+
"""
70134
pass
71135

72136
@abc.abstractmethod
@@ -76,6 +140,11 @@ def set_error(self, error: SpanError) -> None:
76140
@property
77141
@abc.abstractmethod
78142
def error(self) -> SpanError | None:
143+
"""Any error that occurred during span execution.
144+
145+
Returns:
146+
SpanError | None: Error details if an error occurred, None otherwise.
147+
"""
79148
pass
80149

81150
@abc.abstractmethod
@@ -85,15 +154,33 @@ def export(self) -> dict[str, Any] | None:
85154
@property
86155
@abc.abstractmethod
87156
def started_at(self) -> str | None:
157+
"""When the span started execution.
158+
159+
Returns:
160+
str | None: ISO format timestamp of span start, None if not started.
161+
"""
88162
pass
89163

90164
@property
91165
@abc.abstractmethod
92166
def ended_at(self) -> str | None:
167+
"""When the span finished execution.
168+
169+
Returns:
170+
str | None: ISO format timestamp of span end, None if not finished.
171+
"""
93172
pass
94173

95174

96175
class NoOpSpan(Span[TSpanData]):
176+
"""A no-op implementation of Span that doesn't record any data.
177+
178+
Used when tracing is disabled but span operations still need to work.
179+
180+
Args:
181+
span_data: The operation-specific data for this span.
182+
"""
183+
97184
__slots__ = ("_span_data", "_prev_span_token")
98185

99186
def __init__(self, span_data: TSpanData):

0 commit comments

Comments
 (0)