Skip to content
Merged
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
51 changes: 51 additions & 0 deletions docs/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,57 @@ By default, the trace is named "Agent workflow". You can set this name if you us

In addition, you can set up [custom trace processors](#custom-tracing-processors) to push traces to other destinations (as a replacement, or secondary destination).

## Long-running workers and immediate exports

The default [`BatchTraceProcessor`][agents.tracing.processors.BatchTraceProcessor] exports traces
in the background every few seconds, or sooner when the in-memory queue reaches its size trigger,
and also performs a final flush when the process exits. In long-running workers such as Celery,
RQ, Dramatiq, or FastAPI background tasks, this means traces are usually exported automatically
without any extra code, but they may not appear in the Traces dashboard immediately after each job
finishes.

If you need an immediate delivery guarantee at the end of a unit of work, call
[`flush_traces()`][agents.tracing.flush_traces] after the trace context exits.

```python
from agents import Runner, flush_traces, trace


@celery_app.task
def run_agent_task(prompt: str):
try:
with trace("celery_task"):
result = Runner.run_sync(agent, prompt)
return result.final_output
finally:
flush_traces()
```

```python
from fastapi import BackgroundTasks, FastAPI
from agents import Runner, flush_traces, trace

app = FastAPI()


def process_in_background(prompt: str) -> None:
try:
with trace("background_job"):
Runner.run_sync(agent, prompt)
finally:
flush_traces()


@app.post("/run")
async def run(prompt: str, background_tasks: BackgroundTasks):
background_tasks.add_task(process_in_background, prompt)
return {"status": "queued"}
```

[`flush_traces()`][agents.tracing.flush_traces] blocks until currently buffered traces and spans are
exported, so call it after `trace()` closes to avoid flushing a partially built trace. You can skip
this call when the default export latency is acceptable.

## Higher level traces

Sometimes, you might want multiple calls to `run()` to be part of a single trace. You can do this by wrapping the entire code in a `trace()`.
Expand Down
Loading