Skip to content

Commit 0b5a7de

Browse files
docs: improve tracing module docstrings in source files
- Add detailed class and method descriptions - Include practical usage examples - Add implementation notes and best practices - Document attributes and parameters - Fix according to review feedback
1 parent 6d371e1 commit 0b5a7de

File tree

4 files changed

+272
-173
lines changed

4 files changed

+272
-173
lines changed

docs/ref/tracing/setup.md

Lines changed: 2 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -1,147 +1,3 @@
1-
# Tracing Setup
1+
# `Setup`
22

3-
The tracing setup module provides functions to configure and initialize tracing for OpenAI Agents.
4-
5-
## Functions
6-
7-
### `set_tracing_disabled(disabled: bool) -> None`
8-
9-
Disables or enables tracing globally.
10-
11-
```python
12-
from agents import set_tracing_disabled
13-
14-
# Disable tracing globally
15-
set_tracing_disabled(True)
16-
17-
# Re-enable tracing
18-
set_tracing_disabled(False)
19-
```
20-
21-
### `set_tracing_export_api_key(api_key: str) -> None`
22-
23-
Sets the API key used for exporting traces to OpenAI's backend.
24-
25-
```python
26-
from agents import set_tracing_export_api_key
27-
28-
# Set a specific API key for tracing
29-
set_tracing_export_api_key("sk-your-openai-api-key")
30-
```
31-
32-
### `add_trace_processor(processor: TraceProcessor) -> None`
33-
34-
Adds an additional trace processor to the existing processors.
35-
36-
```python
37-
from agents import add_trace_processor
38-
from agents.tracing.processors import TraceProcessor
39-
40-
class CustomTraceProcessor(TraceProcessor):
41-
def process_trace(self, trace):
42-
# Custom processing logic
43-
print(f"Processing trace: {trace.trace_id}")
44-
45-
# Add custom processor
46-
add_trace_processor(CustomTraceProcessor())
47-
```
48-
49-
### `set_trace_processors(processors: list[TraceProcessor]) -> None`
50-
51-
Replaces all existing trace processors with the provided list.
52-
53-
```python
54-
from agents import set_trace_processors
55-
from agents.tracing.processors import BatchTraceProcessor, BackendSpanExporter
56-
57-
# Replace with custom processors
58-
custom_processors = [
59-
BatchTraceProcessor(BackendSpanExporter()),
60-
CustomTraceProcessor()
61-
]
62-
set_trace_processors(custom_processors)
63-
```
64-
65-
## Environment Variables
66-
67-
### `OPENAI_AGENTS_DISABLE_TRACING`
68-
69-
Set to `1` to disable tracing globally.
70-
71-
```bash
72-
export OPENAI_AGENTS_DISABLE_TRACING=1
73-
```
74-
75-
## Common Setup Patterns
76-
77-
### Basic Setup with Custom API Key
78-
79-
```python
80-
import os
81-
from agents import set_tracing_export_api_key, Agent, Runner
82-
83-
# Set up tracing with custom API key
84-
tracing_api_key = os.environ.get("OPENAI_TRACING_API_KEY")
85-
if tracing_api_key:
86-
set_tracing_export_api_key(tracing_api_key)
87-
88-
agent = Agent(name="Assistant", instructions="You are helpful")
89-
result = await Runner.run(agent, "Hello world")
90-
```
91-
92-
### Setup with Custom Processor
93-
94-
```python
95-
from agents import add_trace_processor, Agent, Runner
96-
from agents.tracing.processors import TraceProcessor
97-
import json
98-
99-
class LoggingTraceProcessor(TraceProcessor):
100-
def process_trace(self, trace):
101-
# Log trace to file
102-
with open("traces.log", "a") as f:
103-
f.write(json.dumps({
104-
"trace_id": trace.trace_id,
105-
"workflow_name": trace.workflow_name,
106-
"timestamp": trace.started_at.isoformat()
107-
}) + "\n")
108-
109-
# Add logging processor
110-
add_trace_processor(LoggingTraceProcessor())
111-
112-
agent = Agent(name="Assistant")
113-
result = await Runner.run(agent, "Test message")
114-
```
115-
116-
### Disable Tracing for Specific Runs
117-
118-
```python
119-
from agents import Agent, Runner, RunConfig
120-
121-
agent = Agent(name="Assistant")
122-
123-
# Disable tracing for this specific run
124-
result = await Runner.run(
125-
agent,
126-
"Hello world",
127-
run_config=RunConfig(tracing_disabled=True)
128-
)
129-
```
130-
131-
## Troubleshooting
132-
133-
### Common Issues
134-
135-
1. **401 Unauthorized Error**: Make sure you have a valid OpenAI API key set
136-
2. **Tracing Not Working**: Check if `OPENAI_AGENTS_DISABLE_TRACING=1` is set
137-
3. **Custom Processors Not Receiving Data**: Ensure processors are added before running agents
138-
139-
### Debug Mode
140-
141-
Enable verbose logging to debug tracing issues:
142-
143-
```python
144-
from agents import enable_verbose_stdout_logging
145-
146-
enable_verbose_stdout_logging()
147-
```
3+
::: agents.tracing.setup

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

0 commit comments

Comments
 (0)