diff --git a/examples/basic/approved_output_ui.md b/examples/basic/approved_output_ui.md new file mode 100644 index 0000000000..843748165f --- /dev/null +++ b/examples/basic/approved_output_ui.md @@ -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`. diff --git a/examples/basic/approved_output_ui.py b/examples/basic/approved_output_ui.py new file mode 100644 index 0000000000..7b812aa10a --- /dev/null +++ b/examples/basic/approved_output_ui.py @@ -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()) diff --git a/examples/basic/business_tracing.md b/examples/basic/business_tracing.md new file mode 100644 index 0000000000..8f120c9891 --- /dev/null +++ b/examples/basic/business_tracing.md @@ -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. diff --git a/examples/basic/business_tracing.py b/examples/basic/business_tracing.py new file mode 100644 index 0000000000..32a3e547dc --- /dev/null +++ b/examples/basic/business_tracing.py @@ -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()) diff --git a/src/agents/run_internal/model_provider_lifecycle.py b/src/agents/run_internal/model_provider_lifecycle.py index 6e15f6e8c3..a0fcdb25a8 100644 --- a/src/agents/run_internal/model_provider_lifecycle.py +++ b/src/agents/run_internal/model_provider_lifecycle.py @@ -8,6 +8,7 @@ from ..logger import log_model_action_warning, logger from ..models.interface import ModelProvider from ..run_config import RunConfig, _coerce_run_config +from ..tracing.config import _metadata_only_runs def _normalize_run_config_for_runner( @@ -26,12 +27,14 @@ def _normalize_run_config_for_runner( redactor = run_config.redact_text elif run_config.redact_text is not None and run_config.redact_text is not redactor: raise ValueError("A nested run cannot replace its parent's redact_text policy.") - if redactor is not None or (detail == "metadata" and run_config.trace_include_sensitive_data): + force_metadata = redactor is not None or (_metadata_only_runs.get() and detail != "metadata") + if force_metadata or (detail == "metadata" and run_config.trace_include_sensitive_data): # Route every existing capture decision through the run's sensitive-data gate. run_config = copy(run_config) run_config.trace_include_sensitive_data = False if redactor is not None: run_config.redact_text = redactor + if force_metadata: run_config.tracing = {**(run_config.tracing or {}), "operation_detail": "metadata"} return run_config, owns_model_provider diff --git a/src/agents/tracing/__init__.py b/src/agents/tracing/__init__.py index 28b2f28bc8..d0230b797f 100644 --- a/src/agents/tracing/__init__.py +++ b/src/agents/tracing/__init__.py @@ -1,4 +1,4 @@ -from .config import TracingConfig +from .config import TracingConfig, metadata_only_run_tracing from .context import TraceCtxManager from .create import ( agent_span, @@ -54,6 +54,7 @@ "get_trace_provider", "guardrail_span", "handoff_span", + "metadata_only_run_tracing", "response_span", "set_trace_processors", "set_trace_provider", diff --git a/src/agents/tracing/config.py b/src/agents/tracing/config.py index 3310dbecd8..92538cc2c0 100644 --- a/src/agents/tracing/config.py +++ b/src/agents/tracing/config.py @@ -1,8 +1,8 @@ from __future__ import annotations from collections.abc import Iterator -from contextlib import contextmanager -from contextvars import ContextVar +from contextlib import AbstractContextManager, contextmanager +from contextvars import ContextVar, Token from typing import Literal from typing_extensions import TypedDict @@ -11,6 +11,42 @@ OperationDetail = Literal["metadata", "content"] _operation_detail: ContextVar[OperationDetail | None] = ContextVar("operation_detail", default=None) +_metadata_only_runs: ContextVar[bool] = ContextVar("metadata_only_runs", default=False) + + +class _MetadataOnlyRunTracing(AbstractContextManager[None]): + _token: Token[bool] | None = None + + def __enter__(self) -> None: + if self._token is not None: + raise RuntimeError( + "Create a new metadata_only_run_tracing() scope for each with block." + ) + self._token = _metadata_only_runs.set(True) + + def __exit__(self, *exc: object) -> None: + assert self._token is not None + _metadata_only_runs.reset(self._token) + self._token = None + + +def metadata_only_run_tracing() -> AbstractContextManager[None]: + """Limit automatic model and tool capture for Runner calls in this context. + + A child config can override a parent's operation_detail. In this scope, + nested Runner calls and agents used as tools use metadata detail with + trace_include_sensitive_data=False even if they request content. + Disabled tracing stays disabled. + + Use `with metadata_only_run_tracing():` inside the function doing the work. + Start Runner.run_streamed() and drain result.stream_events() inside the + scope. New asyncio tasks inherit it. Independent resumes and remote + services need their own scope. + + The scope does not sanitize raw stream events, returned data, saved state, + exceptions, logs, names, IDs, custom spans or trace metadata. + """ + return _MetadataOnlyRunTracing() class TracingConfig(TypedDict, total=False): @@ -28,6 +64,9 @@ class TracingConfig(TypedDict, total=False): Omit to use existing SDK payload fields. Explicit content capture requires trace_include_sensitive_data in the run configuration. All settings keep one span per logical model call, with retries recorded on that span. + + A nested run can override this setting. Use metadata_only_run_tracing() + to enforce metadata detail across nested Runner calls and agent tools. """ diff --git a/tests/test_approved_output_ui_example.py b/tests/test_approved_output_ui_example.py new file mode 100644 index 0000000000..a6383a62d5 --- /dev/null +++ b/tests/test_approved_output_ui_example.py @@ -0,0 +1,365 @@ +import asyncio + +import pytest +from openai.types.responses import ( + ResponseCompletedEvent, + ResponseCreatedEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseTextDeltaEvent, +) + +from agents import Agent, GuardrailFunctionOutput, RunConfig +from agents.decorators import output_guardrail, tool +from agents.models.multi_provider import MultiProvider +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call +from examples.basic.approved_output_ui import View, display + +from .model_test_helpers import get_response_obj + + +@pytest.fixture +def closed_providers(monkeypatch): + closed = [] + close = MultiProvider.aclose + + async def record_close(provider): + await close(provider) + closed.append(provider) + + monkeypatch.setattr(MultiProvider, "aclose", record_close) + return closed + + +@pytest.mark.asyncio +@pytest.mark.asyncio +async def test_ui_withholds_secret_split_across_raw_deltas(closed_providers): + item = assistant_message("private-marker") + events = [ + ResponseTextDeltaEvent( + type="response.output_text.delta", + item_id=item.id, + output_index=0, + content_index=0, + delta=part, + sequence_number=i, + logprobs=[], + ) + for i, part in enumerate(["pri", "vate-", "marker"]) + ] + events.insert( + 0, + ResponseCreatedEvent( + type="response.created", response=get_response_obj([]), sequence_number=0 + ), + ) + events.insert( + 1, + ResponseOutputItemAddedEvent( + type="response.output_item.added", item=item, output_index=0, sequence_number=0 + ), + ) + events.extend( + [ + ResponseOutputItemDoneEvent( + type="response.output_item.done", item=item, output_index=0, sequence_number=3 + ), + ResponseCompletedEvent( + type="response.completed", response=get_response_obj([item]), sequence_number=4 + ), + ] + ) + events = [event.model_copy(update={"sequence_number": i}) for i, event in enumerate(events)] + view = await display( + Agent(name="demo", model=ScriptedModel([ModelStep.stream(events)])), + "Synthetic prompt", + allow_final=lambda text: False, + ) + assert view.states == ["running", "producer_complete", "rejected"] + assert "private-marker" not in repr(view) + assert view.output is None and view.native_transport_attempts is None + assert len(closed_providers) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "answer", ["public answer", "é" * 32769], ids=["short", "over-preview-limit"] +) +async def test_ui_publishes_only_approved_complete_final(answer, closed_providers): + closed_at_approval = [] + + def allow_final(text): + closed_at_approval.append(len(closed_providers)) + return text == answer + + view = await display( + Agent(name="demo", model=ScriptedModel([[assistant_message(answer)]])), + "Synthetic prompt", + allow_final=allow_final, + ) + assert closed_at_approval == [1] + assert view.output == answer + assert view.states == ["running", "producer_complete", "complete"] + assert len(closed_providers) == 1 + + +@pytest.mark.asyncio +async def test_ui_rejected_final_and_sensitive_model_error(closed_providers): + @output_guardrail + def refuse(context, agent, output): + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True) + + rejected = await display( + Agent( + name="demo", + model=ScriptedModel([[assistant_message("secret candidate")]]), + output_guardrails=[refuse], + ), + "Synthetic prompt", + allow_final=lambda text: True, + ) + failed = await display( + Agent( + name="demo", + model=ScriptedModel([ModelStep.raise_error(RuntimeError("credential-secret"))]), + ), + "Synthetic prompt", + allow_final=lambda text: True, + ) + assert len(closed_providers) == 2 + for view in [rejected, failed]: + assert view.states[-1] == "failed" and view.output is None + assert "secret" not in repr(view) + + +@pytest.mark.asyncio +async def test_ui_reports_approval_pause_without_tool_execution(closed_providers): + writes = [] + + @tool(needs_approval=True) + def write() -> str: + """Write a synthetic record.""" + writes.append("write") + return "written" + + view = await display( + Agent( + name="demo", + tools=[write], + model=ScriptedModel([[function_call("write", {}, call_id="write-one")]]), + ), + "Synthetic prompt", + allow_final=lambda text: True, + ) + assert view.states[-1] == "paused" and view.output is None and writes == [] + assert len(closed_providers) == 1 + + +@pytest.mark.asyncio +async def test_ui_cancellation_joins_producer_and_keeps_status(closed_providers): + entered, release, cleaned = asyncio.Event(), asyncio.Event(), asyncio.Event() + + async def delayed(call): + entered.set() + try: + await release.wait() + return [assistant_message("never displayed")] + finally: + cleaned.set() + + view = View() + pending = asyncio.create_task( + display( + Agent(name="demo", model=ScriptedModel([ModelStep.respond(delayed)])), + "Synthetic prompt", + allow_final=lambda text: True, + view=view, + ) + ) + await entered.wait() + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert view.states[-1] == "cancelled" and view.output is None + assert cleaned.is_set() + assert len(closed_providers) == 1 + + +@pytest.mark.asyncio +async def test_trace_summary_distinguishes_requests_attempts_owner_parent_and_terminal( + closed_providers, +): + from agents import ModelRetrySettings, ModelSettings + from agents.tracing import set_trace_processors + from examples.basic.approved_output_ui import MetadataCounter + + counter = MetadataCounter() + set_trace_processors([counter]) + + @tool + def lookup() -> str: + """Return a synthetic public tool result.""" + return "public tool result" + + model = ScriptedModel( + [ + RuntimeError("private transient error"), + [function_call("lookup", {}, call_id="public-call")], + [assistant_message("public answer")], + ], + emit_traces=True, + ) + config = RunConfig( + model_settings=ModelSettings( + retry=ModelRetrySettings( + max_retries=1, backoff={"initial_delay": 0}, policy=lambda ctx: True + ) + ) + ) + try: + view = await display( + Agent(name="demo", model=model, tools=[lookup]), + "Synthetic prompt", + allow_final=lambda text: text == "public answer", + run_config=config, + ) + assert closed_providers == [] + finally: + await config.model_provider.aclose() + assert closed_providers == [config.model_provider] + rows = counter.observations + models = [row for row in rows if row["kind"] == "model"] + tools = [row for row in rows if row["kind"] == "tool"] + assert view.outer_requests == 2 and len(model.calls) == 3 + assert models and all(row["observed_adapter_attempts"] is None for row in models) + assert view.tool_owners == ["sdk"] + assert tools and all(row["tool_owner"] == "unknown" for row in tools) + assert all(row["parent"] is not None for row in models + tools) + assert all(row["transport_attempts"] is None for row in rows) + assert view.states[-1] == "complete" + assert "private transient error" not in str(rows) + + +@pytest.fixture(autouse=True) +def restore_example_processors(): + from agents.tracing import set_trace_processors + + from .testing_processor import SPAN_PROCESSOR_TESTING + + yield + set_trace_processors([SPAN_PROCESSOR_TESTING]) + + +@pytest.mark.asyncio +async def test_ui_mcp_executor_is_external(): + from .mcp.helpers import FakeMCPServer + + server = FakeMCPServer() + server.add_tool("remote_read", {"type": "object", "properties": {}}) + model = ScriptedModel( + [ + [function_call("remote_read", {}, call_id="remote")], + [assistant_message("public")], + ] + ) + view = await display( + Agent(name="demo", model=model, mcp_servers=[server]), + "Synthetic prompt", + allow_final=lambda text: text == "public", + ) + assert server.tool_calls == ["remote_read"] + assert view.states[-1] == "complete" and view.output == "public" + assert view.tool_owners == ["external"] + + +def test_trace_summary_excludes_hostile_names_metadata_payloads_and_errors(): + import json + + from agents.tracing import function_span, response_span, set_trace_processors, trace + from examples.basic.approved_output_ui import MetadataCounter + + counter = MetadataCounter() + set_trace_processors([counter]) + marker = "private-marker" + with trace(marker, metadata={"payload": marker}): + with response_span() as request: + request.span_data.operation.api_type = "responses" + request.span_data.operation.retry_timestamps.extend([marker, marker]) + with function_span(marker, input=marker, output=marker) as child: + child.span_data.operation.outcome = "failed" + child.set_error({"message": marker, "data": {"payload": marker}}) + rows = counter.observations + assert marker not in json.dumps(rows) + models = [row for row in rows if row["kind"] == "model"] + tools = [row for row in rows if row["kind"] == "tool"] + assert len(models) == len(tools) == 1 + assert tools[0]["parent"] == models[0]["id"] + assert tools[0]["status"] == "failed" and tools[0]["tool_owner"] == "unknown" + assert models[0]["observed_adapter_attempts"] == 3 + assert all(row["transport_attempts"] is None for row in rows) + + +@pytest.mark.asyncio +@pytest.mark.skipif(not hasattr(asyncio, "eager_task_factory"), reason="Requires Python 3.12+") +@pytest.mark.parametrize("cancel_during_close", [False, True]) +async def test_ui_joins_eager_run_when_subscription_fails( + monkeypatch, closed_providers, cancel_during_close +): + entered, release, settled = asyncio.Event(), asyncio.Event(), asyncio.Event() + closing, allow_close = asyncio.Event(), asyncio.Event() + close = MultiProvider.aclose + + async def slow_close(provider): + closing.set() + await allow_close.wait() + await close(provider) + + monkeypatch.setattr(MultiProvider, "aclose", slow_close) + + async def respond(call): + entered.set() + try: + await release.wait() + return [assistant_message("private")] + finally: + settled.set() + + view = View() + loop = asyncio.get_running_loop() + previous = loop.get_task_factory() + loop.set_task_factory(asyncio.eager_task_factory) + try: + task = asyncio.create_task( + display( + Agent(name="demo", model=ScriptedModel([ModelStep.respond(respond)])), + "Synthetic prompt", + allow_final=lambda text: pytest.fail("No output should reach approval"), + view=view, + ) + ) + finally: + loop.set_task_factory(previous) + try: + assert not task.done() + await asyncio.wait_for(closing.wait(), timeout=5) + assert not entered.is_set() or settled.is_set() + if cancel_during_close: + task.cancel("first") + await asyncio.sleep(0) + task.cancel("second") + await asyncio.sleep(0) + assert not task.done() + allow_close.set() + if cancel_during_close: + with pytest.raises(asyncio.CancelledError, match="first"): + await task + assert view.states == ["running", "cancelled"] + else: + await task + assert view.states == ["running", "failed"] + assert view.output is None + assert len(closed_providers) == 1 + finally: + release.set() + allow_close.set() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/tracing/test_content_capture.py b/tests/tracing/test_content_capture.py index bc0cf0c91f..55c831467c 100644 --- a/tests/tracing/test_content_capture.py +++ b/tests/tracing/test_content_capture.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import json from collections.abc import Iterator, Mapping from typing import Any @@ -12,12 +13,15 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter from agents import Agent, RunConfig, Runner +from agents.decorators import tool from agents.extensions.tracing import OpenTelemetryTracingProcessor from agents.models.openai_responses import OpenAIResponsesModel +from agents.testing import ScriptedModel, assistant_message, function_call from agents.tracing import ( add_trace_processor, function_span, generation_span, + metadata_only_run_tracing, set_trace_processors, trace, ) @@ -616,3 +620,134 @@ async def handler(request: httpx2.Request) -> httpx2.Response: assert "input-visible" in json.dumps(value) assert "wire-instructions-visible" in json.dumps(value) assert "output-visible" in json.dumps(captured_output) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +async def test_metadata_only_scope_bounds_agent_tool_and_nested_runner(exporter, stream): + from tests.model_test_helpers import get_response_obj + from tests.test_responses import get_text_message + + native = SpanProcessorForTests() + add_trace_processor(native) + + # A real adapter exercises model request and response capture, including streaming. + def respond(request): + assert b"INPUT_CANARY" in request.content + payload = get_response_obj([get_text_message("OUTPUT_CANARY")]).model_dump() + if stream: + event = {"type": "response.completed", "sequence_number": 0, "response": payload} + return httpx2.Response( + 200, + content=f"data: {json.dumps(event)}\n\n", + headers={"content-type": "text/event-stream"}, + ) + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="synthetic", + base_url="https://fixture.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond)), + ) as client: + leaf = Agent(name="leaf", model=OpenAIResponsesModel("fixture", client)) + + async def run(agent, question, config=None): + if stream: + result = Runner.run_streamed(agent, question, run_config=config) + async for _ in result.stream_events(): + pass + return result.final_output + return (await Runner.run(agent, question, run_config=config)).final_output + + @tool + async def lookup(question: str) -> str: + config = { + "tracing": {"operation_detail": "content"}, + "trace_include_sensitive_data": True, + } + return await run(leaf, question, config) + + specialist = Agent( + name="specialist", + model=ScriptedModel( + [[function_call("lookup", {"question": "INPUT_CANARY"}, call_id="lookup")]] + ), + tools=[lookup], + tool_use_behavior="stop_on_first_tool", + ) + parent = Agent( + name="parent", + model=ScriptedModel( + [[function_call("consult", {"input": "INPUT_CANARY"}, call_id="consult")]] + ), + tools=[ + specialist.as_tool( + "consult", + "Consult", + run_config=RunConfig(trace_include_sensitive_data=True), + on_stream=(lambda event: None) if stream else None, + ) + ], + tool_use_behavior="stop_on_first_tool", + ) + with metadata_only_run_tracing(): + answer = await run(parent, "INPUT_CANARY") + + assert answer == "OUTPUT_CANARY" + spans = native.get_ordered_spans() + operations = [s.span_data for s in spans if hasattr(s.span_data, "operation")] + assert {"response", "function"} <= {op.type for op in operations} + for op in operations: + assert op.operation.detail == "metadata" + assert op.input is None and op.output is None + if op.type == "response": + assert op.response is None + assert "CANARY" not in json.dumps([s.export() for s in spans]) + exported = exporter.get_finished_spans() + assert any(s.name == "execute_tool lookup" for s in exported) + assert "CANARY" not in "".join(s.to_json() for s in exported) + + +def test_metadata_only_scope_rejects_async_decorator(): + with pytest.raises(TypeError): + + @metadata_only_run_tracing() # type: ignore[operator] + async def run(): + pass + + +@pytest.mark.asyncio +async def test_metadata_only_scope_is_task_local_and_restored_after_cancellation(): + config = RunConfig(tracing={"operation_detail": "content"}, trace_include_sensitive_data=True) + entered = asyncio.Event() + + async def capture(config): + model = ScriptedModel([[assistant_message("ok")]]) + await Runner.run(Agent(name="worker", model=model), "question", run_config=config) + return model.calls[0].tracing + + async def scoped(): + try: + with metadata_only_run_tracing(): + with metadata_only_run_tracing(): + assert (await capture(RunConfig(tracing_disabled=True))).is_disabled() + assert not (await capture(config)).include_data() + entered.set() + await asyncio.Event().wait() + except asyncio.CancelledError: + assert (await capture(config)).include_data() + raise + finally: + entered.set() + + task = asyncio.create_task(scoped()) + try: + await entered.wait() + assert (await capture(config)).include_data() + assert config.tracing == {"operation_detail": "content"} + assert config.trace_include_sensitive_data + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task diff --git a/tests/tracing/test_opentelemetry.py b/tests/tracing/test_opentelemetry.py index 42f2508da7..8992805b8b 100644 --- a/tests/tracing/test_opentelemetry.py +++ b/tests/tracing/test_opentelemetry.py @@ -544,3 +544,77 @@ def test_missing_or_zero_usage_details_do_not_add_optional_counts(otel, details) "gen_ai.usage.reasoning.output_tokens", ) ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("usage", [None, {"total_tokens": 0}]) +async def test_business_trace_links_stages_and_reports_only_measured_direct_usage(otel, usage): + from agents import Agent, ModelSettings + from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call + from examples.basic.business_tracing import route + + provider, receiver = otel + child_model = ScriptedModel( + [ModelStep(output=[assistant_message("ok")], raw_usage={"total_tokens": 19})] + ) + settings = ModelSettings(preserve_raw_usage=True) + child = Agent(name="child", model=child_model, model_settings=settings) + agent = Agent( + name="classifier", + model=ScriptedModel( + [ + ModelStep( + output=[function_call("lookup", {"input": "check"}, call_id="call_lookup")], + raw_usage={"total_tokens": 0}, + ), + ModelStep(output=[assistant_message("priority")], raw_usage=usage), + ] + ), + model_settings=settings, + tools=[child.as_tool("lookup", "Check the queue")], + ) + outbox = [] + traceparent = "00-" + "1" * 32 + "-" + "2" * 16 + "-01" + await route(provider.get_tracer("test"), traceparent, agent, "PRIVATE_REQUEST", outbox) + + assert len(child_model.calls) == 1 + assert outbox == ["priority"] + spans = {span.name: span for span in receiver.get_finished_spans()} + assert spans["route"].parent.is_remote + assert spans["route"].parent.span_id == int("2" * 16, 16) + for name in ("specialist", "validate", "deliver"): + assert spans[name].parent.span_id == spans["route"].context.span_id + assert spans[name].attributes["app.outcome"] == "ok" + specialist = spans["specialist"] + assert any( + s.name.startswith("invoke_runner ") and s.parent.span_id == specialist.context.span_id + for s in spans.values() + ) + assert specialist.attributes["app.direct_usage.available"] is (usage is not None) + if usage is None: + assert "app.direct_usage.total_tokens" not in specialist.attributes + else: + assert specialist.attributes["app.direct_usage.total_tokens"] == 0 + assert "PRIVATE_REQUEST" not in "".join(s.to_json() for s in receiver.get_finished_spans()) + + +@pytest.mark.asyncio +async def test_business_trace_preserves_errors_without_recording_private_text(otel): + from agents import Agent + from agents.testing import ScriptedModel + from examples.basic.business_tracing import route, stage + + provider, receiver = otel + tracer = provider.get_tracer("test") + agent = Agent(name="classifier", model=ScriptedModel([ValueError("PRIVATE_ERROR")])) + outbox = [] + with pytest.raises(ValueError, match="PRIVATE_ERROR"), stage(tracer, "ingress"): + await route(tracer, "", agent, "PRIVATE_REQUEST", outbox) + assert not outbox + spans = {span.name: span for span in receiver.get_finished_spans()} + for name in ("ingress", "route", "specialist"): + assert spans[name].attributes["app.outcome"] == "failed" + assert not spans[name].status.is_ok + assert spans[name].status.description is None + assert not spans[name].events + assert "PRIVATE_" not in "".join(s.to_json() for s in receiver.get_finished_spans())