Skip to content
Open
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
11 changes: 11 additions & 0 deletions examples/basic/approved_output_ui.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Show only approved final output

Run `uv run python examples/basic/approved_output_ui.py` from this checkout. The offline example retries once, calls an SDK tool, and completes. The public `on_llm_start` hook counts two outer requests while the fixture observes three adapter invocations. Trace-derived attempt counts remain unknown when the adapter supplies no evidence. No span count claims network delivery or billing.

The UI omits the preview callback, so the reader skips preview buffering and its 65,536-byte limit. After the run finishes cleanup, the UI applies its disclosure policy to the complete final text. Split secrets and rejected final answers never enter its display. It reports running, paused, failed, cancelled, rejected and completed states without exception text. Cancellation propagates after producer cleanup.

The example needs to subscribe before the producer starts. With an eager task factory, the producer can start inside `Runner.run_streamed()`. If subscription fails, the UI cancels the run, waits for cleanup and reports failure without displaying any output.

The trace receiver publishes fixed labels and local parent aliases. The tool-start hook identifies native tools, SDK function tools and functions that call an external MCP server. A span alone cannot identify the executor. Other tool owners and native transport attempts remain unknown. Its metadata-only tracing scope prevents nested runs from opting back into automatic content capture. Configure processors once at service startup; do not replace active process-wide processors. Custom logs, names, raw consumers and private history need separate policy.

By default, Runner closes the provider it creates. If you pass a `run_config`, you own its provider, including any CodexProvider, and must close it after its last use. This offline example does not verify live/native providers or add native interception. Reused metadata-scope and business-tracing work comes from PR #6128 at `0c7d9693cbe670e28ccff4ad0ec73e2ca38b969f`.
225 changes: 225 additions & 0 deletions examples/basic/approved_output_ui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
"""Offline, final-only UI. Never display raw stream deltas or exception messages."""

import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any

from agents import (
Agent,
FunctionTool,
ModelRetrySettings,
ModelSettings,
NativeTool,
RunConfig,
RunHooks,
Runner,
RunResultStreaming,
)
from agents.decorators import tool
from agents.model_preflight import tool_ownership
from agents.stream_events import RunCompleted
from agents.testing import ScriptedModel, assistant_message, function_call
from agents.tracing import TracingProcessor, metadata_only_run_tracing, set_trace_processors
from agents.tracing.span_data import FunctionSpanData, GenerationSpanData, ResponseSpanData


class MetadataCounter(TracingProcessor):
"""A fixed-label receiver; no payload, names, IDs or exception details leave it."""

def __init__(self) -> None:
self.finished_spans = 0
self.child_spans = 0
self.observations: list[dict[str, Any]] = []
self._span_ids: dict[str, str] = {}

def on_trace_start(self, trace: Any) -> None:
pass

def on_trace_end(self, trace: Any) -> None:
pass

def on_span_start(self, span: Any) -> None:
self._span_ids.setdefault(span.span_id, f"span-{len(self._span_ids) + 1}")

def on_span_end(self, span: Any) -> None:
self.finished_spans += 1
self.child_spans += int(span.parent_id is not None)
data = span.span_data
if isinstance(data, (GenerationSpanData, ResponseSpanData, FunctionSpanData)):
is_model = isinstance(data, (GenerationSpanData, ResponseSpanData))
# Spans alone do not prove which executor ran a same-named tool.
owner = "unknown"
outcome = data.operation.outcome
status = (
outcome
if outcome in {"completed", "failed", "interrupted", "rejected"}
else "unknown"
)
self.observations.append(
{
"id": self._span_ids.get(span.span_id),
"parent": self._span_ids.get(span.parent_id),
"kind": "model" if is_model else "tool",
"status": status,
"logical_requests": None,
"observed_adapter_attempts": 1 + len(data.operation.retry_timestamps)
if is_model and data.operation.api_type in {"responses", "chat_completions"}
else None,
"transport_attempts": None,
"tool_owner": None if is_model else owner,
}
)

def shutdown(self) -> None:
pass

def force_flush(self) -> None:
pass


@dataclass
class View:
states: list[str] = field(default_factory=lambda: ["running"])
output: str | None = None
# A span is not a network attempt. Native internal activity stays unknown.
native_transport_attempts: None = None
outer_requests: int = 0
tool_owners: list[str] = field(default_factory=list)


class RequestCounter(RunHooks[Any]):
def __init__(self, view: View) -> None:
self.view = view

async def on_llm_start(
self, context: Any, agent: Any, system_prompt: Any, input_items: Any
) -> None:
# Runner invokes this once per outer request, outside its retry loop.
self.view.outer_requests += 1

async def on_tool_start(self, context: Any, agent: Any, tool: Any) -> None:
# Use the execution hook's actual object, never an inferred tool name.
if isinstance(tool, NativeTool):
self.view.tool_owners.append("native")
elif isinstance(tool, FunctionTool):
self.view.tool_owners.append(tool_ownership([tool])[0].executor)
else:
self.view.tool_owners.append("unknown")


async def _cancel_unsubscribed_run(run: RunResultStreaming) -> None:
"""Stop a run whose approved reader never took ownership."""
run.cancel()

async def drain() -> None:
async for _ in run.stream_events():
pass

# Keep cleanup independent of caller cancellation. Subscription already failed.
cleanup = asyncio.gather(drain(), return_exceptions=True)
cancellation = None
while not cleanup.done():
try:
await asyncio.wait((cleanup,))
except asyncio.CancelledError as exc:
if cancellation is None:
cancellation = exc
if cancellation is not None:
raise cancellation


async def display(
agent: Agent[Any],
prompt: str,
*,
allow_final: Callable[[str], bool],
view: View | None = None,
run_config: RunConfig | None = None,
) -> View:
"""Drain the producer and approve complete final text after successful cleanup.

The reader skips previews, so it never buffers partial text for approval.
The application supplies allow_final using its disclosure policy. Completion
itself grants no permission to display output. Exceptions remain available
to the caller's private diagnostics; this UI emits only fixed status labels.
"""
view = view if view is not None else View()
with metadata_only_run_tracing():
try:
run = Runner.run_streamed(
agent,
prompt,
run_config=run_config,
hooks=RequestCounter(view),
)
subscribed = False
try:
async with run.stream_approved_output() as events:
subscribed = True
async for event in events:
if isinstance(event, RunCompleted):
view.states.append("producer_complete")
except RuntimeError:
if not subscribed:
# An eager task factory can start the producer before we subscribe.
await _cancel_unsubscribed_run(run)
raise
if run.interruptions:
view.states.append("paused")
elif isinstance(run.final_output, str) and allow_final(run.final_output):
view.output = run.final_output
view.states.append("complete")
else:
view.states.append("rejected")
except asyncio.CancelledError:
view.states.append("cancelled")
raise
except Exception:
# Do not copy provider/tool errors, tracebacks or rejected answers to UI.
view.states.append("failed")
return view


async def main() -> None:
counter = MetadataCounter()
# Configure once at standalone app startup; do not replace active processors.
set_trace_processors([counter])

@tool
def lookup() -> str:
"""Return a synthetic public result from this SDK executor."""
return "Public tool result"

model = ScriptedModel(
[
RuntimeError("Synthetic private retry detail"),
[function_call("lookup", {}, call_id="public-call")],
[assistant_message("Public result")],
],
emit_traces=True,
)
agent = Agent(
name="demo",
model=model,
tools=[lookup],
model_settings=ModelSettings(
retry=ModelRetrySettings(
max_retries=1,
backoff={"initial_delay": 0},
policy=lambda ctx: True,
)
),
)
view = await display(
agent,
"Return a synthetic public answer.",
allow_final=lambda text: text == "Public result",
)
print(view)
for observation in counter.observations:
print(observation)


if __name__ == "__main__":
asyncio.run(main())
54 changes: 54 additions & 0 deletions examples/basic/business_tracing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Limit automatic trace capture in a business workflow

[Run the offline example](business_tracing.py) from this checkout with the development dependencies installed (`make sync`). No API key, collector or network calls.

```sh
uv run --no-sync python examples/basic/business_tracing.py
```

Expected output — one delivery to an in-memory outbox, five successful application stages and a count of spans received in memory. The scripted classifier supplies synthetic usage. The delivery count comes from the outbox, independently of telemetry.

## Limit capture across nested runs

Set `RunConfig(tracing={"operation_detail": "metadata"})` to omit model and tool payloads from one run's automatic spans. A nested `Runner` call or an agent used as a tool can request content with its own config.

To enforce metadata detail across those calls, wrap `await Runner.run(agent, request)` in `with metadata_only_run_tracing():`. For streaming, start the run and drain its events inside the same scope.

```python
from agents import Runner
from agents.tracing import metadata_only_run_tracing


async def run_streamed(agent, request):
with metadata_only_run_tracing():
result = Runner.run_streamed(agent, request)
async for _ in result.stream_events():
pass
return result
```

Each run in the scope uses metadata detail and `trace_include_sensitive_data=False`, even when a child requests content. Disabled tracing stays disabled. The scope leaves caller configs unchanged.

New asyncio tasks inherit the context at creation. Leaving the scope restores the previous setting in the current task. Enter a fresh scope on independent resume, in an existing worker task or in another service.

The scope does not sanitize raw stream events, returned data, saved state, exceptions or logs. The example discards events without displaying them. Check what you can disclose before sharing `result.final_output`. Keep sensitive values out of names, IDs, custom spans and `trace_metadata`. Third-party instrumentation has its own capture rules.

## Connect application stages

- **Service startup** — choose the OpenTelemetry provider, sampler, exporter, endpoint and retention policy for each service. The standalone example uses `set_trace_processors([bridge])` once for exclusive export to memory. To keep existing SDK destinations, use `add_trace_processor(bridge)`. Both settings affect the whole process. Drain active runs before changing destinations.
- **Service boundary** — the example passes only W3C `traceparent` from ingress to routing. Accept it only from trusted callers. Keep credentials, baggage and capture settings out of propagation. Each receiver chooses its own capture policy.
- **Stages** — routing, specialist work, validation and delivery have fixed span names and outcomes. Use span start and end times for latency. Put business attributes directly on application spans. On every enclosing span, disable both exception recording and automatic exception status descriptions. The example sets a fixed error status and re-raises the original exception.
- **Direct usage** — with direct Responses, `ModelSettings(preserve_raw_usage=True)` preserves available provider usage per response. The specialist span counts only entries in this run's `result.raw_responses`. Separate nested runs and attempts absent from that list are excluded. `app.direct_usage.available` is true when the list is nonempty and every entry supplies a nonnegative integer total. Only then does the example record `app.direct_usage.total_tokens`, including a measured zero. Never export the raw payload. Token counts alone do not establish charges.
- **Shutdown** — after finishing spans, call `flush_traces()` and flush the caller-owned OpenTelemetry provider separately. Shut down the bridge and provider when the service stops.

## Monitor export loss

The example uses a synchronous processor and counts spans in its local receiver. For a queued OTLP exporter, monitor each boundary separately.

| Boundary | What to measure |
| --- | --- |
| Queue | In OpenTelemetry Python SDK 1.45, enable `OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED=true` and pass a configured `meter_provider` to `BatchSpanProcessor`. Alert on `otel.sdk.processor.span.processed` with `error.type=queue_full`. These spans never reached the exporter. |
| Export attempts | Count spans submitted per batch and spans in failed batches. Account for retries when comparing attempts with unique spans. A successful flush or export counter alone cannot establish acceptance. |
| Receiver | Check accepted and rejected counts, including [OTLP partial success](https://opentelemetry.io/docs/specs/otlp/#partial-success) and `rejected_spans`. Reconcile sampled trace and span IDs with receiver receipts where available. Verify durable storage separately. |

Example with no retries — three sampled spans, one queue drop, two sent, one rejected and one accepted. Keep delivery and other business outcomes independent of export success.
90 changes: 90 additions & 0 deletions examples/basic/business_tracing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Offline service example. See business_tracing.md for setup and export monitoring."""

import asyncio
from collections.abc import Iterator
from contextlib import contextmanager

from opentelemetry.context import Context
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import Span, StatusCode, Tracer
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

from agents import Agent, ModelSettings, Runner
from agents.extensions.tracing import OpenTelemetryTracingProcessor
from agents.testing import ModelStep, ScriptedModel, assistant_message
from agents.tracing import flush_traces, metadata_only_run_tracing, set_trace_processors


@contextmanager
def stage(tracer: Tracer, name: str, parent: Context | None = None) -> Iterator[Span]:
with tracer.start_as_current_span(
name, context=parent, record_exception=False, set_status_on_exception=False
) as span:
try:
yield span
except BaseException:
span.set_attribute("app.outcome", "failed")
span.set_status(StatusCode.ERROR)
raise
else:
span.set_attribute("app.outcome", "ok")


async def route(
tracer: Tracer, traceparent: str, agent: Agent, request: str, outbox: list[str]
) -> None:
parent = TraceContextTextMapPropagator().extract({"traceparent": traceparent})
with stage(tracer, "route", parent), metadata_only_run_tracing():
with stage(tracer, "specialist") as span:
result = await Runner.run(agent, request)
totals = [(r.raw_usage or {}).get("total_tokens") for r in result.raw_responses]
measured = [n for n in totals if type(n) is int and n >= 0]
available = bool(totals) and len(measured) == len(totals)
span.set_attribute("app.direct_usage.available", available)
if available:
span.set_attribute("app.direct_usage.total_tokens", sum(measured))
with stage(tracer, "validate"):
queue = result.final_output
if queue not in ("standard", "priority"):
raise ValueError("Unknown queue")
with stage(tracer, "deliver"):
outbox.append(queue)


async def main() -> None:
# Configure this standalone service once, before accepting requests.
provider = TracerProvider()
receiver = InMemorySpanExporter()
provider.add_span_processor(SimpleSpanProcessor(receiver))
bridge = OpenTelemetryTracingProcessor(tracer_provider=provider)
set_trace_processors([bridge])
tracer = provider.get_tracer(__name__)
try:
agent = Agent(
name="classifier",
model=ScriptedModel(
[ModelStep(output=[assistant_message("standard")], raw_usage={"total_tokens": 8})]
),
model_settings=ModelSettings(preserve_raw_usage=True),
)
outbox: list[str] = []
with stage(tracer, "ingress"):
headers: dict[str, str] = {}
TraceContextTextMapPropagator().inject(headers)
await route(tracer, headers.get("traceparent", ""), agent, "Synthetic request", outbox)
print(f"Delivered {len(outbox)} item(s)")
flush_traces()
provider.force_flush()
for span in receiver.get_finished_spans():
if span.attributes and "app.outcome" in span.attributes:
print(span.name, span.attributes["app.outcome"])
print(f"Spans received in memory: {len(receiver.get_finished_spans())}")
finally:
bridge.shutdown()
provider.shutdown()


if __name__ == "__main__":
asyncio.run(main())
Loading
Loading