diff --git a/pyproject.toml b/pyproject.toml index 10aa580c08..95171ab7d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,6 +42,7 @@ Homepage = "https://openai.github.io/openai-agents-python/" Repository = "https://github.com/openai/openai-agents-python" [project.optional-dependencies] +opentelemetry = ["opentelemetry-api>=1.45.0,<2"] # Protobuf exclusions retain patched 5.x and 6.x releases (GHSA-7gcm-g887-7qv7). voice = ["numpy>=2.2.0, <3; python_version>='3.10'", "websockets>=15.0, <18"] viz = ["graphviz>=0.17"] @@ -95,6 +96,7 @@ temporal = [ [dependency-groups] dev = [ + "opentelemetry-sdk>=1.45.0,<2", "mypy", "ruff==0.17.1", "pytest>=9.0.3", diff --git a/src/agents/extensions/models/any_llm_model.py b/src/agents/extensions/models/any_llm_model.py index 80b5759ad5..b6f07520af 100644 --- a/src/agents/extensions/models/any_llm_model.py +++ b/src/agents/extensions/models/any_llm_model.py @@ -51,10 +51,13 @@ Converter as OpenAIResponsesConverter, _coerce_response_includables, _materialize_responses_tool_params, + _record_prepared_request, + _record_response_operation, ) from ...retry import ModelRetryAdvice, ModelRetryAdviceRequest from ...tool import Tool -from ...tracing import generation_span, response_span +from ...tracing import generation_span +from ...tracing._model import model_span from ...tracing.span_data import GenerationSpanData from ...tracing.spans import Span from ...usage import ( @@ -414,7 +417,7 @@ async def _get_response_via_responses( prompt: ResponsePromptParam | None, ) -> ModelResponse: with ( - response_span(disabled=tracing.is_disabled()) as span_response, + model_span(tracing, self.model) as span_response, model_span_errors( span_response, message="Error getting response", @@ -465,9 +468,7 @@ async def _get_response_via_responses( span_response.span_data.usage = model_usage_to_span_usage(usage) - if tracing.include_data(): - span_response.span_data.response = response - span_response.span_data.input = input + _record_response_operation(span_response, response, input, tracing) return ModelResponse( output=response.output, @@ -496,7 +497,7 @@ async def _stream_response_via_responses( prompt: ResponsePromptParam | None, ) -> AsyncGenerator[ResponseStreamEvent, None]: with ( - response_span(disabled=tracing.is_disabled()) as span_response, + model_span(tracing, self.model) as span_response, model_span_errors( span_response, message="Error streaming response", @@ -561,9 +562,10 @@ async def _stream_response_via_responses( requests=_requests_for_response_without_usage(final_response) ) ) - if tracing.include_data() and final_response is not None: - span_response.span_data.response = final_response - span_response.span_data.input = input + if final_response is not None: + _record_response_operation( + span_response, final_response, input, tracing + ) if terminal_failure_error is not None: # The failure is already known here. A consumer that stops at # this event closes the generator, which raises GeneratorExit @@ -1123,6 +1125,11 @@ async def _fetch_responses_response( } transport_kwargs = self._build_responses_transport_kwargs(model_settings) + prepared_request = dict(request_kwargs) + extra_body = prepared_request.get("extra_body") + if isinstance(extra_body, Mapping): + prepared_request.update(extra_body) + _record_prepared_request(prepared_request) response = await self._call_any_llm_responses( request_kwargs=request_kwargs, transport_kwargs=transport_kwargs, diff --git a/src/agents/extensions/tracing/__init__.py b/src/agents/extensions/tracing/__init__.py new file mode 100644 index 0000000000..4710b5e900 --- /dev/null +++ b/src/agents/extensions/tracing/__init__.py @@ -0,0 +1,5 @@ +"""Optional integrations for Agents SDK tracing.""" + +from .opentelemetry import OpenTelemetryTracingProcessor + +__all__ = ["OpenTelemetryTracingProcessor"] diff --git a/src/agents/extensions/tracing/opentelemetry.py b/src/agents/extensions/tracing/opentelemetry.py new file mode 100644 index 0000000000..2883788459 --- /dev/null +++ b/src/agents/extensions/tracing/opentelemetry.py @@ -0,0 +1,443 @@ +"""Translate native SDK spans into live OpenTelemetry spans. + +Install ``openai-agents[opentelemetry]`` and register this processor with +``agents.add_trace_processor``. Configure exporters and sampling on the application's +OpenTelemetry tracer provider; this processor does not own that provider's lifecycle. + +The GenAI mapping follows semantic-conventions-genai commit +``622b2b6073b15e5ed886c3c12a65a892b9cd5c70``. These conventions are in development. +""" + +from __future__ import annotations + +import json +import threading +from collections.abc import Mapping, Sequence +from contextvars import ContextVar +from typing import Any + +from opentelemetry import context as otel_context, trace as otel_trace +from opentelemetry.trace import SpanKind, StatusCode, TracerProvider + +from ...logger import logger +from ...tracing.processor_interface import TracingProcessor +from ...tracing.span_data import ( + AgentSpanData, + CustomSpanData, + FunctionSpanData, + GenerationSpanData, + GuardrailSpanData, + HandoffSpanData, + ResponseSpanData, + SpanData, + TaskSpanData, + TurnSpanData, +) +from ...tracing.spans import Span +from ...tracing.traces import Trace +from ...tracing.util import _parse_iso_timestamp +from ...version import __version__ + +_scope_owner: ContextVar[object | None] = ContextVar("agents_otel_scope_owner", default=None) + + +def _timestamp(value: str | None) -> int | None: + if value is None: + return None + parsed, nanos = _parse_iso_timestamp(value) + seconds = int(parsed.timestamp()) + return seconds * 1_000_000_000 + nanos + + +def _json_value(value: Any) -> Any: + if isinstance(value, str): + try: + return json.loads(value) + except ValueError: + pass + return value + + +def _messages(value: Any, *, output: bool = False) -> list[dict[str, Any]]: + """Project Responses text and tool content into the GenAI message schema.""" + if isinstance(value, str): + return [ + { + "role": "assistant" if output else "user", + "parts": [{"type": "text", "content": value}], + } + ] + if not isinstance(value, Sequence): + return [] + messages: list[dict[str, Any]] = [] + for item in value: + if not isinstance(item, Mapping): + continue + kind = item.get("type", "message") + role = item.get("role", "assistant" if output else "user") + parts: list[dict[str, Any]] = [] + if kind in ("input_text", "output_text", "text"): + part = {"type": "text", "content": item.get("text", "")} + for flag in ("partial", "truncated"): + if isinstance(item.get(flag), bool): + part[flag] = item[flag] + parts.append(part) + elif item.get("truncated") is True and "content" not in item and "tool_calls" not in item: + parts.append({"type": "openai.omitted", "reason": "truncated"}) + elif kind in ("function_call", "custom_tool_call"): + role = "assistant" + parts.append( + { + "type": "tool_call", + "name": item.get("name", ""), + "id": item.get("call_id"), + "arguments": _json_value(item.get("arguments", item.get("input"))), + } + ) + elif kind in ("function_call_output", "custom_tool_call_output"): + role = "tool" + parts.append( + { + "type": "tool_call_response", + "id": item.get("call_id"), + "response": item.get("output"), + } + ) + elif kind == "message": + content = item.get("content") + if role == "tool" and "tool_call_id" in item: + parts.append( + {"type": "tool_call_response", "id": item["tool_call_id"], "response": content} + ) + elif isinstance(content, str): + parts.append({"type": "text", "content": content}) + elif isinstance(content, Sequence): + for part in content: + if not isinstance(part, Mapping): + continue + if part.get("type") in ("input_text", "output_text", "text"): + parts.append({"type": "text", "content": part.get("text", "")}) + elif part.get("type") == "refusal": + parts.append({"type": "text", "content": part.get("refusal", "")}) + else: + # Preserve part order without exporting media or hidden reasoning. + parts.append({"type": "openai.omitted", "reason": "unsupported_content"}) + refusal = item.get("refusal") + if isinstance(refusal, str): + parts.append({"type": "text", "content": refusal}) + for call in item.get("tool_calls") or (): + if not isinstance(call, Mapping) or call.get("type") != "function": + continue + function = call.get("function") + if isinstance(function, Mapping): + canonical = { + "type": "function_call", + "call_id": call.get("id"), + "name": function.get("name", ""), + "arguments": function.get("arguments"), + } + parts.extend(_messages([canonical], output=True)[0]["parts"]) + else: + parts.append({"type": "openai.omitted", "reason": "unsupported_content"}) + if output and messages: + messages[0]["parts"].extend(parts) + else: + messages.append({"role": role, "parts": parts}) + return messages + + +def _message_schema(value: Any, role: str) -> list[dict[str, Any]]: + """Preserve the message schema when the shared budget replaces a container.""" + messages: list[dict[str, Any]] = [] + for item in value if isinstance(value, list) else [{}]: + if not isinstance(item, Mapping) or "parts" not in item: + messages.append( + {"role": role, "parts": [{"type": "openai.omitted", "reason": "truncated"}]} + ) + continue + parts = [ + part + if isinstance(part, Mapping) and "type" in part + else {"type": "openai.omitted", "reason": "truncated"} + for part in item["parts"] + ] + messages.append({"role": item.get("role", role), "parts": parts}) + return messages + + +def _identity(data: SpanData) -> tuple[str, str, SpanKind]: + if isinstance(data, TaskSpanData): + return f"invoke_runner {data.name}", "invoke_runner", SpanKind.INTERNAL + if isinstance(data, AgentSpanData): + return f"invoke_agent {data.name}", "invoke_agent", SpanKind.INTERNAL + if isinstance(data, TurnSpanData): + return "openai.agents.turn", "openai.agents.turn", SpanKind.INTERNAL + if isinstance(data, FunctionSpanData): + if data.operation.outcome in ("paused", "rejected"): + return ( + f"openai.agents.tool_approval {data.name}", + "openai.agents.tool_approval", + SpanKind.INTERNAL, + ) + return f"execute_tool {data.name}", "execute_tool", SpanKind.INTERNAL + if isinstance(data, (GenerationSpanData, ResponseSpanData)): + model = data.operation.model or getattr(data, "model", None) + if isinstance(data, ResponseSpanData) and data.response is not None: + model = model or data.response.model + return f"chat {model}" if model else "chat", "chat", SpanKind.CLIENT + if isinstance(data, HandoffSpanData): + return "openai.agents.handoff", "openai.agents.handoff", SpanKind.INTERNAL + if isinstance(data, GuardrailSpanData): + return f"openai.agents.guardrail {data.name}", "openai.agents.guardrail", SpanKind.INTERNAL + if isinstance(data, CustomSpanData): + if data.name == "tool_approval": + name = data.data.get("tool_name") + return ( + f"openai.agents.tool_approval {name}" if name else "openai.agents.tool_approval", + "openai.agents.tool_approval", + SpanKind.INTERNAL, + ) + return data.name, "openai.agents.custom", SpanKind.INTERNAL + return f"openai.agents.{data.type}", f"openai.agents.{data.type}", SpanKind.INTERNAL + + +class OpenTelemetryTracingProcessor(TracingProcessor): + """Export native SDK spans through the application's OpenTelemetry provider. + + Content permission belongs to each SDK operation. Legacy SDK payload fields do not + grant permission to export content through this integration. ``force_flush`` and + ``shutdown`` do not flush or shut down the caller-owned OpenTelemetry provider. + """ + + def __init__(self, *, tracer_provider: TracerProvider | None = None) -> None: + self._tracer = otel_trace.get_tracer( + "openai.agents", __version__, tracer_provider=tracer_provider + ) + self._lock = threading.RLock() + self._spans: dict[tuple[str, str], otel_trace.Span] = {} + self._parents: dict[tuple[str, str], otel_trace.Span] = {} + self._traces: dict[str, dict[int, Trace]] = {} + + def on_trace_start(self, trace: Trace) -> None: + # A native trace may group several Runner invocations; task spans represent runs. + with self._lock: + self._traces.setdefault(trace.trace_id, {})[id(trace)] = trace + + def on_trace_end(self, trace: Trace) -> None: + with self._lock: + owners = self._traces.get(trace.trace_id) + if owners is None or id(trace) not in owners: + return + owners.pop(id(trace)) + if owners: + return + self._traces.pop(trace.trace_id, None) + unfinished = [ + self._spans.pop(key) for key in list(self._spans) if key[0] == trace.trace_id + ] + for key in [key for key in self._parents if key[0] == trace.trace_id]: + self._parents.pop(key, None) + self._end_interrupted(unfinished) + + def on_span_start(self, span: Span[Any]) -> None: + key = (span.trace_id, span.span_id) + with self._lock: + if key in self._spans: + return + parent = self._parents.get((span.trace_id, span.parent_id or "")) + context = otel_trace.set_span_in_context(parent) if parent is not None else None + name, operation, kind = _identity(span.span_data) + attributes = self._attributes(span) + attributes["gen_ai.operation.name"] = operation + attributes["openai.agents.span.type"] = span.span_data.type + otel_span = self._tracer.start_span( + name, + context=context, + kind=kind, + attributes=attributes, + start_time=_timestamp(span.started_at), + ) + self._spans[key] = otel_span + # Keep only identity after completion, not exported content or SDK resources. + self._parents[key] = otel_trace.NonRecordingSpan(otel_span.get_span_context()) + + def on_span_end(self, span: Span[Any]) -> None: + with self._lock: + otel_span = self._spans.pop((span.trace_id, span.span_id), None) + if span.trace_id not in self._traces and not any( + key[0] == span.trace_id for key in self._spans + ): + for key in [key for key in self._parents if key[0] == span.trace_id]: + self._parents.pop(key, None) + if otel_span is None: + return + try: + otel_span.set_attributes(self._attributes(span)) + if span.error is not None: + # Error messages may contain payloads even when content capture is disabled. + otel_span.set_attribute("error.type", "_OTHER") + otel_span.set_status(StatusCode.ERROR) + operation = getattr(span.span_data, "operation", None) + if operation is not None and operation.outcome in ( + "error", + "failed", + "cancelled", + "interrupted", + ): + otel_span.set_attribute("error.type", "_OTHER") + otel_span.set_status(StatusCode.ERROR) + finally: + otel_span.end(end_time=_timestamp(span.ended_at)) + + def on_span_scope_enter(self, span: Span[Any]) -> object | None: + """Activate a span only for the SDK execution scope that owns its context.""" + with self._lock: + otel_span = self._spans.get((span.trace_id, span.span_id)) + if otel_span is None: + return None + owner_token = _scope_owner.set(object()) + return owner_token, otel_context.attach(otel_trace.set_span_in_context(otel_span)) + + def on_span_scope_exit(self, span: Span[Any], token: Any) -> None: + if token is not None: + owner_token, context_token = token + try: + _scope_owner.reset(owner_token) + except ValueError: + # Async-generator finalization cannot reset the originating task's context. + return + otel_context.detach(context_token) + + def _attributes(self, span: Span[Any]) -> dict[str, Any]: + data = span.span_data + attributes: dict[str, Any] = {} + if isinstance(data, (GenerationSpanData, ResponseSpanData)): + if isinstance(data, ResponseSpanData) or data.operation.api_type == "responses": + attributes["gen_ai.provider.name"] = "openai" + attributes["openai.api.type"] = "responses" + model = data.operation.model or getattr(data, "model", None) + if isinstance(data, ResponseSpanData) and data.response is not None: + model = model or data.response.model + if model: + attributes["gen_ai.request.model"] = model + usage = data.usage + if usage: + for source, destination in ( + ("input_tokens", "gen_ai.usage.input_tokens"), + ("output_tokens", "gen_ai.usage.output_tokens"), + ): + if isinstance(usage.get(source), int): + attributes[destination] = usage[source] + if data.operation.response_model: + attributes["gen_ai.response.model"] = data.operation.response_model + if data.operation.response_id: + attributes["gen_ai.response.id"] = data.operation.response_id + if data.operation.previous_response_id: + attributes["openai.response.previous_response_id"] = ( + data.operation.previous_response_id + ) + if isinstance(data, (AgentSpanData, TurnSpanData)): + attributes["gen_ai.agent.name"] = ( + data.name if isinstance(data, AgentSpanData) else data.agent_name + ) + if isinstance(data, TurnSpanData): + attributes["openai.agents.turn.number"] = data.turn + if isinstance(data, FunctionSpanData): + attributes["gen_ai.tool.name"] = data.name + attributes["gen_ai.tool.type"] = "function" + if isinstance(data, (GenerationSpanData, ResponseSpanData, FunctionSpanData)): + operation = data.operation + if operation.outcome: + attributes["openai.agents.operation.outcome"] = operation.outcome + if operation.estimated_end: + attributes["openai.agents.operation.estimated_end"] = True + if operation.operation_id: + attributes["openai.agents.operation.id"] = operation.operation_id + if operation.tool_call_id: + attributes["gen_ai.tool.call.id"] = operation.tool_call_id + if operation.detail == "content": + attributes.update(self._content_attributes(data)) + if isinstance(data, CustomSpanData) and data.name == "codex.tracing.coverage": + for key in ("provider", "coverage", "reason"): + if isinstance(data.data.get(key), str): + attributes[f"openai.agents.operation.{key}"] = data.data[key] + if isinstance(data, CustomSpanData) and data.name == "tool_approval": + for source, target in ( + ("tool_name", "gen_ai.tool.name"), + ("tool_call_id", "gen_ai.tool.call.id"), + ("outcome", "openai.agents.operation.outcome"), + ): + if isinstance(data.data.get(source), str): + attributes[target] = data.data[source] + return attributes + + def _content_attributes( + self, data: GenerationSpanData | ResponseSpanData | FunctionSpanData + ) -> dict[str, Any]: + from ...tracing._content import bound_content + + values: dict[str, Any] = {} + if isinstance(data, FunctionSpanData): + if data.input is not None: + values["gen_ai.tool.call.arguments"] = bound_content(_json_value(data.input)) + if data.output is not None: + values["gen_ai.tool.call.result"] = bound_content(data.output) + else: + if isinstance(data, ResponseSpanData): + inputs = bound_content(data.input) + output = bound_content(data.response.output) if data.response is not None else None + else: + inputs = data.input + output = data.output + request: dict[str, Any] = {} + if inputs is not None: + request["messages"] = _messages(inputs) + if output is not None: + values["gen_ai.output.messages"] = _message_schema( + bound_content(_messages(output, output=True)), "assistant" + ) + if isinstance(data, GenerationSpanData) and data.model_config: + instructions = data.model_config.get("instructions") + if isinstance(instructions, str): + request["instructions"] = [{"type": "text", "content": instructions}] + if isinstance(data, GenerationSpanData) and data.tools is not None: + request["tools"] = data.tools + request = bound_content(request) + if "messages" in request: + values["gen_ai.input.messages"] = _message_schema(request["messages"], "user") + if "instructions" in request: + values["gen_ai.system_instructions"] = request["instructions"] + if "tools" in request: + values["gen_ai.tool.definitions"] = request["tools"] + return values + + def force_flush(self) -> None: + """Leave exporter flushing to the application's OpenTelemetry provider.""" + pass + + @staticmethod + def _end_interrupted(spans: list[otel_trace.Span]) -> None: + for span in spans: + try: + try: + span.set_attributes( + { + "openai.agents.operation.outcome": "interrupted", + "openai.agents.operation.estimated_end": True, + "error.type": "_OTHER", + } + ) + span.set_status(StatusCode.ERROR) + finally: + span.end() + except Exception: + logger.warning("Error while ending an interrupted OpenTelemetry span") + + def shutdown(self) -> None: + """End outstanding spans without shutting down the application's provider.""" + with self._lock: + spans = list(self._spans.values()) + self._spans.clear() + self._parents.clear() + self._traces.clear() + self._end_interrupted(spans) diff --git a/src/agents/models/_trace.py b/src/agents/models/_trace.py index 4f8991e29e..2173099b69 100644 --- a/src/agents/models/_trace.py +++ b/src/agents/models/_trace.py @@ -59,7 +59,10 @@ def populate_generation_span( ) -> None: """Populate generation trace data from a Chat Completions adapter response.""" if tracing.include_data(): - span_generation.span_data.output = [final_response.model_dump()] + if span_generation.span_data.operation.detail == "content": + span_generation.span_data.output = [item.model_dump() for item in final_response.output] + else: + span_generation.span_data.output = [final_response.model_dump()] if final_response.usage is not None: span_generation.span_data.usage = { diff --git a/src/agents/models/openai_responses.py b/src/agents/models/openai_responses.py index 7e013e30be..b63c257fa6 100644 --- a/src/agents/models/openai_responses.py +++ b/src/agents/models/openai_responses.py @@ -74,7 +74,11 @@ validate_responses_programmatic_tool_calling_configuration, validate_responses_tool_search_configuration, ) -from ..tracing import SpanError, response_span +from ..tracing._content import bound_content +from ..tracing._model import ModelSpan, finish_model_span, model_span, record_model_input +from ..tracing.scope import Scope +from ..tracing.span_data import GenerationSpanData, ResponseSpanData +from ..tracing.util import time_iso from ..usage import ( Usage, _attach_raw_usage_snapshot, @@ -184,6 +188,68 @@ def _materialize_responses_tool_params( return typed_tools +def _record_response_id(span: ModelSpan, response_id: str) -> None: + span.span_data.operation.response_id = response_id + if isinstance(span.span_data, ResponseSpanData): + span.span_data._response_id = response_id + + +def _record_response_operation( + span: ModelSpan, + response: Response, + input: str | list[TResponseInputItem], + tracing: ModelTracing, + *, + outcome: Literal["completed", "failed"] = "completed", +) -> None: + data = span.span_data + data.operation.response_model = getattr(response, "model", None) + data.operation.outcome = outcome + if tracing.include_data(): + data.operation.response_id = response.id + if isinstance(data, ResponseSpanData): + if tracing.include_data() and outcome == "completed": + data.response = response + data.input = input + elif data.operation.detail == "content": + data.output = bound_content(response.output) + + +def _record_prepared_request(request: Mapping[str, Any]) -> None: + span = Scope.get_current_span() + if span is None or not isinstance(span.span_data, (GenerationSpanData, ResponseSpanData)): + return + data = span.span_data + model = request.get("model") + data.operation.model = model if isinstance(model, str) else None + if isinstance(data, GenerationSpanData): + data.model = data.operation.model + if not isinstance(data, GenerationSpanData) or data.operation.detail != "content": + return + record_model_input(data, dict(request)) + + +def _record_failed_response(response: Response, *, response_id_trusted: bool) -> None: + span = Scope.get_current_span() + if span is None or not isinstance(span.span_data, (GenerationSpanData, ResponseSpanData)): + return + data = span.span_data + if isinstance(data, GenerationSpanData): + _record_response_operation( + span, + response, + [], + ModelTracing.ENABLED + if data.operation.detail == "content" + else ModelTracing.ENABLED_WITHOUT_DATA, + outcome="failed", + ) + if response_id_trusted: + data.operation.response_id = response.id + else: + data.operation.response_model = getattr(response, "model", None) + + async def _refresh_openai_client_api_key_if_supported(client: Any) -> None: """Backward-compatible wrapper around shared WebSocket client credential refresh.""" await refresh_openai_client_api_key_if_supported(client) @@ -622,7 +688,7 @@ async def get_response( conversation_id: str | None = None, prompt: ResponsePromptParam | None = None, ) -> ModelResponse: - with response_span(disabled=tracing.is_disabled()) as span_response: + with model_span(tracing, self.model) as span_response: try: redacted_response_id_endpoint_is_trusted = ( not tracing.include_data() @@ -658,14 +724,12 @@ async def get_response( if response.usage is not None or usage.requests: span_response.span_data.usage = model_usage_to_span_usage(usage) - if tracing.include_data(): - span_response.span_data.response = response - span_response.span_data.input = input - elif ( + _record_response_operation(span_response, response, input, tracing) + if ( redacted_response_id_endpoint_is_trusted and self._uses_official_openai_endpoint() ): - span_response.span_data._response_id = response.id + _record_response_id(span_response, response.id) except asyncio.CancelledError: record_current_task_model_timeout_on_span( span_response, @@ -676,15 +740,11 @@ async def get_response( except Exception as e: if isinstance(e, ModelBehaviorError) and e._terminal_usage is not None: span_response.span_data.usage = model_usage_to_span_usage(e._terminal_usage) - span_response.set_error( - SpanError( - message="Error getting response", - data={ - "error": str(e) - if tracing.include_data() - else "Error details are redacted.", - }, - ) + record_model_error_on_span( + span_response, + message="Error getting response", + error=e, + trace_include_sensitive_data=tracing.include_data(), ) message = "Error getting response" if not _debug.DONT_LOG_MODEL_DATA: @@ -720,7 +780,8 @@ async def stream_response( """ Yields a partial message as it is generated, as well as the usage information. """ - with response_span(disabled=tracing.is_disabled()) as span_response: + with model_span(tracing, self.model) as span_response: + terminal_ended_at: str | None = None try: redacted_response_id_endpoint_is_trusted = ( not tracing.include_data() @@ -748,12 +809,13 @@ async def stream_response( async for chunk in stream: chunk_type = getattr(chunk, "type", None) if isinstance(chunk, ResponseCompletedEvent): + terminal_ended_at = time_iso() final_response = chunk.response if ( redacted_response_id_endpoint_is_trusted and self._uses_official_openai_endpoint() ): - span_response.span_data._response_id = chunk.response.id + _record_response_id(span_response, chunk.response.id) if model_settings.preserve_raw_usage is True: _attach_raw_usage_snapshot(chunk.response, chunk.response.usage) usage = _usage_from_response(chunk.response) @@ -761,17 +823,30 @@ async def stream_response( # Record before yielding the terminal event because consumers may # close the generator immediately after receiving it. span_response.span_data.usage = model_usage_to_span_usage(usage) - if tracing.include_data(): - # Same reason as usage: a consumer that stops at the terminal - # event closes the generator and never reaches the post-loop - # assignment, so record the model I/O before yielding. - span_response.span_data.response = chunk.response - span_response.span_data.input = input + _record_response_operation( + span_response, chunk.response, input, tracing + ) elif chunk_type in { "response.failed", "response.incomplete", }: + terminal_ended_at = time_iso() terminal_response = getattr(chunk, "response", None) + if isinstance(terminal_response, Response): + _record_response_operation( + span_response, + terminal_response, + input, + tracing, + outcome="failed", + ) + if ( + redacted_response_id_endpoint_is_trusted + and self._uses_official_openai_endpoint() + ): + span_response.span_data.operation.response_id = ( + terminal_response.id + ) terminal_failure_error = response_terminal_failure_error( cast(str, chunk_type), terminal_response @@ -783,6 +858,7 @@ async def stream_response( terminal_failure_error._terminal_usage ) elif chunk_type in {"error", "response.error"}: + terminal_ended_at = time_iso() terminal_failure_error = response_error_event_failure_error( cast(str, chunk_type), chunk, @@ -796,6 +872,7 @@ async def stream_response( }: yielded_terminal_event = True if terminal_failure_error is not None: + span_response.span_data.operation.outcome = "failed" # A consumer that stops at this event closes the # generator, which raises GeneratorExit at the yield # below and skips the raise after the loop, so the @@ -831,9 +908,8 @@ async def stream_response( if terminal_failure_error is not None: raise terminal_failure_error - if final_response is not None and tracing.include_data(): - span_response.span_data.response = final_response - span_response.span_data.input = input + if final_response is not None: + _record_response_operation(span_response, final_response, input, tracing) except asyncio.CancelledError: record_current_task_model_timeout_on_span( span_response, @@ -842,18 +918,17 @@ async def stream_response( ) raise except Exception as e: - span_response.set_error( - SpanError( - message="Error streaming response", - data={ - "error": str(e) - if tracing.include_data() - else "Error details are redacted.", - }, - ) + record_model_error_on_span( + span_response, + message="Error streaming response", + error=e, + trace_include_sensitive_data=tracing.include_data(), ) log_model_action_error(logger, "Error streaming response", e) raise + finally: + if terminal_ended_at is not None: + finish_model_span(span_response, ended_at=terminal_ended_at) @overload async def _fetch_response( @@ -910,11 +985,23 @@ async def _fetch_response( stream=stream, prompt=prompt, ) + prepared_request = dict(create_kwargs) + extra_body = prepared_request.get("extra_body") + if isinstance(extra_body, Mapping): + prepared_request.update(extra_body) + _record_prepared_request(prepared_request) client = self._get_client() if not stream: + response_id_trusted = self._uses_official_openai_endpoint() response = await client.responses.create(**create_kwargs) if getattr(response, "status", None) in {"failed", "incomplete"}: + _record_failed_response( + response, + response_id_trusted=( + response_id_trusted and self._uses_official_openai_endpoint() + ), + ) raise response_terminal_failure_error(f"response.{response.status}", response) _mark_transport_request_without_usage(response) return cast(Response, response) @@ -1344,6 +1431,7 @@ async def _fetch_response( final_response: Response | None = None terminal_event_type: str | None = None + response_id_trusted = self._uses_official_openai_endpoint() async for event in self._iter_websocket_response_events(create_kwargs): event_type = getattr(event, "type", None) if isinstance(event, ResponseCompletedEvent): @@ -1352,6 +1440,13 @@ async def _fetch_response( elif event_type in {"response.incomplete", "response.failed"}: terminal_event_type = cast(str, event_type) terminal_response = getattr(event, "response", None) + if isinstance(terminal_response, Response): + _record_failed_response( + terminal_response, + response_id_trusted=( + response_id_trusted and self._uses_official_openai_endpoint() + ), + ) raise response_terminal_failure_error( terminal_event_type, terminal_response if isinstance(terminal_response, Response) else None, @@ -1390,6 +1485,7 @@ async def _iter_websocket_response_events( request_frame, ws_url, request_headers = await self._prepare_websocket_request( create_kwargs ) + _record_prepared_request(request_frame) retry_pre_event_disconnect = _should_retry_pre_event_websocket_disconnect() while True: connection: Any = None diff --git a/src/agents/run.py b/src/agents/run.py index 92e499622b..57ca88bbe2 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -185,7 +185,7 @@ task_span, turn_span, ) -from .tracing.config import include_task_and_turn_spans +from .tracing.config import include_task_and_turn_spans, operation_tracing_scope from .tracing.context import TraceCtxManager, create_trace_for_run from .tracing.span_data import AgentSpanData, TaskSpanData from .util import _error_tracing @@ -591,6 +591,9 @@ async def run( redacted_error: BaseException | None = None # Mask caller tracing before any run-owned preparation or cleanup can execute. with contextlib.ExitStack() as trace_stack: + trace_stack.enter_context( + operation_tracing_scope(run_config.tracing, run_config.trace_include_sensitive_data) + ) try: try: if run_config.tracing_disabled: @@ -2656,6 +2659,7 @@ def run_streamed( # Synchronous setup can invoke application providers before the task starts. # Restore caller context before creating the independently masked background task. with ( + operation_tracing_scope(run_config.tracing, run_config.trace_include_sensitive_data), TraceCtxManager( workflow_name=run_config.workflow_name, trace_id=run_config.trace_id, @@ -2665,7 +2669,7 @@ def run_streamed( disabled=True, ) if run_config.tracing_disabled - else contextlib.nullcontext() + else contextlib.nullcontext(), ): # Handle RunState input is_resumed_state = isinstance(input, RunState) @@ -2896,43 +2900,46 @@ def run_streamed( # Kick off the actual agent loop in the background and return the streamed result object. async def run_loop() -> None: - if isinstance(session, ResumableRun): - try: - await session.begin(input) - except BaseException: - streamed_result.is_complete = True - streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - raise - configuration_agent = ( - run_state._current_agent - if run_state is not None and run_state._current_agent is not None - else starting_agent - ) with ( + operation_tracing_scope( + run_config.tracing, run_config.trace_include_sensitive_data + ), # Mask the inherited span in this task; the streaming loop owns the trace. custom_span(name="Agent run", disabled=True) if run_config.tracing_disabled else contextlib.nullcontext(), - agent_tool_configuration_run(configuration_agent), ): - await start_streaming( - starting_input=input_for_result, - streamed_result=streamed_result, - starting_agent=starting_agent, - max_turns=max_turns, - hooks=hooks, - context_wrapper=context_wrapper, - run_config=run_config, - error_handlers=error_handlers, - previous_response_id=previous_response_id, - auto_previous_response_id=auto_previous_response_id, - conversation_id=conversation_id, - session=session, - run_state=run_state, - trace_workflow_name=trace_workflow_name, - is_resumed_state=is_resumed_state, - sandbox_runtime=sandbox_runtime, + if isinstance(session, ResumableRun): + try: + await session.begin(input) + except BaseException: + streamed_result.is_complete = True + streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) + raise + configuration_agent = ( + run_state._current_agent + if run_state is not None and run_state._current_agent is not None + else starting_agent ) + with agent_tool_configuration_run(configuration_agent): + await start_streaming( + starting_input=input_for_result, + streamed_result=streamed_result, + starting_agent=starting_agent, + max_turns=max_turns, + hooks=hooks, + context_wrapper=context_wrapper, + run_config=run_config, + error_handlers=error_handlers, + previous_response_id=previous_response_id, + auto_previous_response_id=auto_previous_response_id, + conversation_id=conversation_id, + session=session, + run_state=run_state, + trace_workflow_name=trace_workflow_name, + is_resumed_state=is_resumed_state, + sandbox_runtime=sandbox_runtime, + ) # Keep the outer task frame inside the boundary so it cannot retain run payloads. streamed_result.run_loop_task = asyncio.create_task( diff --git a/src/agents/run_internal/error_handlers.py b/src/agents/run_internal/error_handlers.py index f55e8b9929..ccb92c95a4 100644 --- a/src/agents/run_internal/error_handlers.py +++ b/src/agents/run_internal/error_handlers.py @@ -93,7 +93,7 @@ def attach_generic_agent_error( return detail = ( _format_agent_error_detail(exc) - if trace_include_sensitive_data + if _error_tracing.include_error_text(trace_include_sensitive_data) else REDACTED_TRACE_ERROR_MESSAGE ) _error_tracing.attach_error_to_span( diff --git a/src/agents/run_internal/model_provider_lifecycle.py b/src/agents/run_internal/model_provider_lifecycle.py index a3c22e8d53..17d32326c1 100644 --- a/src/agents/run_internal/model_provider_lifecycle.py +++ b/src/agents/run_internal/model_provider_lifecycle.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +from copy import copy from typing import Any from ..logger import log_model_action_warning, logger @@ -16,6 +17,13 @@ def _normalize_run_config_for_runner( isinstance(value, dict) and "model_provider" not in value ) run_config = RunConfig() if value is None else _coerce_run_config(value) + detail = run_config.tracing.get("operation_detail") if run_config.tracing else None + if detail not in (None, "metadata", "content"): + raise ValueError("operation_detail must be 'metadata' or 'content'") + if 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 return run_config, owns_model_provider diff --git a/src/agents/run_internal/model_retry.py b/src/agents/run_internal/model_retry.py index 358567e0ce..4f23b729a8 100644 --- a/src/agents/run_internal/model_retry.py +++ b/src/agents/run_internal/model_retry.py @@ -35,6 +35,7 @@ _coerce_backoff_settings, retry_policy_retries_safe_transport_errors, ) +from ..tracing._model import ModelRetrySpans, model_retry_scope from ..usage import RequestUsage, Usage from ..util._error_tracing import mark_model_timeout_task @@ -619,91 +620,96 @@ async def get_response_with_retry( conversation_id=conversation_id, ) - while True: - try: - # Keep provider retries on the initial attempt, but disable them on explicit - # no-retry settings and on any replay attempt that the runner manages itself. - with ( - provider_managed_retries_disabled( - _should_disable_provider_managed_retries( - retry_settings, - attempt=request_attempt, - stateful_request=stateful_request, - replay_unsafe_request=replay_unsafe_request, - ) - ), - websocket_pre_event_retries_disabled(disable_websocket_pre_event_retry), - ): - response = await _await_model_attempt(get_response(), timeout) - response.usage = apply_retry_attempt_usage( - response.usage, request_attempt - 1, reported_usage - ) - return response - except Exception as error: - if isinstance(error, ModelBehaviorError) and error._terminal_usage is not None: - reported_usage[request_attempt] = error._terminal_usage - if ( - not replay_unsafe_request - and _is_conversation_locked_error(error) - and _should_preserve_conversation_locked_compatibility(retry_settings) - ): - # Preserve the historical conversation_locked retry path for backward - # compatibility, including when callers enable retry policies for unrelated - # failures. Callers can explicitly opt out of this compatibility behavior with - # max_retries=0. - if compatibility_retries_taken < COMPATIBILITY_CONVERSATION_LOCKED_RETRIES: - compatibility_retries_taken += 1 - delay = 1.0 * (2 ** (compatibility_retries_taken - 1)) - logger.debug( - "Conversation locked, retrying in %ss (attempt %s/%s).", - delay, - compatibility_retries_taken, - COMPATIBILITY_CONVERSATION_LOCKED_RETRIES, + model_spans = ModelRetrySpans() + try: + while True: + try: + # Keep provider retries on the initial attempt, but disable them on explicit + # no-retry settings and on any replay attempt that the runner manages itself. + with ( + provider_managed_retries_disabled( + _should_disable_provider_managed_retries( + retry_settings, + attempt=request_attempt, + stateful_request=stateful_request, + replay_unsafe_request=replay_unsafe_request, + ) + ), + websocket_pre_event_retries_disabled(disable_websocket_pre_event_retry), + model_retry_scope(model_spans, request_attempt), + ): + response = await _await_model_attempt(get_response(), timeout) + response.usage = apply_retry_attempt_usage( + response.usage, request_attempt - 1, reported_usage + ) + return response + except Exception as error: + if isinstance(error, ModelBehaviorError) and error._terminal_usage is not None: + reported_usage[request_attempt] = error._terminal_usage + if ( + not replay_unsafe_request + and _is_conversation_locked_error(error) + and _should_preserve_conversation_locked_compatibility(retry_settings) + ): + # Preserve the historical conversation_locked retry path for backward + # compatibility, including when callers enable retry policies for unrelated + # failures. Callers can explicitly opt out of this compatibility behavior with + # max_retries=0. + if compatibility_retries_taken < COMPATIBILITY_CONVERSATION_LOCKED_RETRIES: + compatibility_retries_taken += 1 + delay = 1.0 * (2 ** (compatibility_retries_taken - 1)) + logger.debug( + "Conversation locked, retrying in %ss (attempt %s/%s).", + delay, + compatibility_retries_taken, + COMPATIBILITY_CONVERSATION_LOCKED_RETRIES, + ) + await rewind() + await _sleep_for_retry(delay) + request_attempt += 1 + continue + + provider_advice = get_retry_advice( + ModelRetryAdviceRequest( + error=error, + attempt=policy_attempt, + stream=False, + previous_response_id=previous_response_id, + conversation_id=conversation_id, ) - await rewind() - await _sleep_for_retry(delay) - request_attempt += 1 - continue - - provider_advice = get_retry_advice( - ModelRetryAdviceRequest( + ) + decision = await _evaluate_retry( error=error, attempt=policy_attempt, + max_retries=( + max(retry_settings.max_retries or 0, 0) if retry_settings is not None else 0 + ), + retry_policy=retry_settings.policy if retry_settings is not None else None, + retry_backoff=retry_settings.backoff if retry_settings is not None else None, stream=False, + replay_unsafe_request=replay_unsafe_request, + emitted_retry_unsafe_event=False, + provider_advice=provider_advice, previous_response_id=previous_response_id, conversation_id=conversation_id, ) - ) - decision = await _evaluate_retry( - error=error, - attempt=policy_attempt, - max_retries=( - max(retry_settings.max_retries or 0, 0) if retry_settings is not None else 0 - ), - retry_policy=retry_settings.policy if retry_settings is not None else None, - retry_backoff=retry_settings.backoff if retry_settings is not None else None, - stream=False, - replay_unsafe_request=replay_unsafe_request, - emitted_retry_unsafe_event=False, - provider_advice=provider_advice, - previous_response_id=previous_response_id, - conversation_id=conversation_id, - ) - if not decision.retry: - raise - - logger.debug( - "Retrying failed model request in %ss (attempt %s/%s).", - decision.delay, - policy_attempt, - retry_settings.max_retries - if retry_settings is not None and retry_settings.max_retries is not None - else 0, - ) - await rewind() - await _sleep_for_retry(decision.delay or 0.0) - request_attempt += 1 - policy_attempt += 1 + if not decision.retry: + raise + + logger.debug( + "Retrying failed model request in %ss (attempt %s/%s).", + decision.delay, + policy_attempt, + retry_settings.max_retries + if retry_settings is not None and retry_settings.max_retries is not None + else 0, + ) + await rewind() + await _sleep_for_retry(decision.delay or 0.0) + request_attempt += 1 + policy_attempt += 1 + finally: + model_spans.finish() async def stream_response_with_retry( @@ -730,192 +736,205 @@ async def stream_response_with_retry( conversation_id=conversation_id, ) - while True: - emitted_retry_unsafe_event = False - event: TResponseStreamEvent | None = None - stream: AsyncIterator[TResponseStreamEvent] | None = None - stream_owner: asyncio.Task[None] | None = None - deadline = asyncio.get_running_loop().time() + timeout if timeout is not None else None - try: - disable_provider_managed_retries = _should_disable_provider_managed_retries( - retry_settings, - attempt=request_attempt, - stateful_request=stateful_request, - replay_unsafe_request=replay_unsafe_request, - ) - stream_requests: asyncio.Queue[None] | None = None - stream_results: ( - asyncio.Queue[tuple[str, TResponseStreamEvent | BaseException | None]] | None - ) = None - if timeout is None: - # Pull stream events under the retry-disable context, but yield them outside it - # so unrelated model calls made by the consumer do not inherit this setting. - with ( - provider_managed_retries_disabled(disable_provider_managed_retries), - websocket_pre_event_retries_disabled(disable_websocket_pre_event_retry), - ): - stream = get_stream() - else: - stream_requests = asyncio.Queue() - stream_results = asyncio.Queue() - with ( - provider_managed_retries_disabled(disable_provider_managed_retries), - websocket_pre_event_retries_disabled(disable_websocket_pre_event_retry), - ): - stream_owner = asyncio.create_task( - _run_stream_attempt_in_one_task( - get_stream, - stream_requests, - stream_results, - ) - ) + model_spans = ModelRetrySpans() + try: + while True: + emitted_retry_unsafe_event = False + event: TResponseStreamEvent | None = None + stream: AsyncIterator[TResponseStreamEvent] | None = None + stream_owner: asyncio.Task[None] | None = None + deadline = asyncio.get_running_loop().time() + timeout if timeout is not None else None try: - while True: - try: - if timeout is None: - assert stream is not None - with ( - provider_managed_retries_disabled(disable_provider_managed_retries), - websocket_pre_event_retries_disabled( - disable_websocket_pre_event_retry - ), - ): - event = await stream.__anext__() - else: - assert stream_owner is not None - assert stream_requests is not None - assert stream_results is not None - assert deadline is not None - stream_requests.put_nowait(None) - remaining = max(deadline - asyncio.get_running_loop().time(), 0.0) - try: - result_kind, result_value = await _await_model_attempt( - stream_results.get(), - remaining, - timeout_error_seconds=timeout, - ) - except ModelTimeoutError as error: - await _cancel_and_drain_model_attempt_task( - stream_owner, - error, - cancel_cleanup=True, - ) - raise - except asyncio.CancelledError: - await _cancel_and_drain_model_attempt_task(stream_owner) - raise - if result_kind == "done": - remaining = max(deadline - asyncio.get_running_loop().time(), 0.0) - await _await_model_attempt( - stream_owner, - remaining, - timeout_error_seconds=timeout, - ) - return - if result_kind == "error": + disable_provider_managed_retries = _should_disable_provider_managed_retries( + retry_settings, + attempt=request_attempt, + stateful_request=stateful_request, + replay_unsafe_request=replay_unsafe_request, + ) + stream_requests: asyncio.Queue[None] | None = None + stream_results: ( + asyncio.Queue[tuple[str, TResponseStreamEvent | BaseException | None]] | None + ) = None + if timeout is None: + # Pull stream events under the retry-disable context, but yield them outside it + # so unrelated model calls made by the consumer do not inherit this setting. + with ( + provider_managed_retries_disabled(disable_provider_managed_retries), + websocket_pre_event_retries_disabled(disable_websocket_pre_event_retry), + model_retry_scope(model_spans, request_attempt), + ): + stream = get_stream() + else: + stream_requests = asyncio.Queue() + stream_results = asyncio.Queue() + with ( + provider_managed_retries_disabled(disable_provider_managed_retries), + websocket_pre_event_retries_disabled(disable_websocket_pre_event_retry), + model_retry_scope(model_spans, request_attempt), + ): + stream_owner = asyncio.create_task( + _run_stream_attempt_in_one_task( + get_stream, + stream_requests, + stream_results, + ) + ) + try: + while True: + try: + if timeout is None: + assert stream is not None + with ( + provider_managed_retries_disabled( + disable_provider_managed_retries + ), + websocket_pre_event_retries_disabled( + disable_websocket_pre_event_retry + ), + model_retry_scope(model_spans, request_attempt), + ): + event = await stream.__anext__() + else: + assert stream_owner is not None + assert stream_requests is not None + assert stream_results is not None + assert deadline is not None + stream_requests.put_nowait(None) remaining = max(deadline - asyncio.get_running_loop().time(), 0.0) - await _await_model_attempt( - stream_owner, - remaining, - timeout_error_seconds=timeout, - ) - assert isinstance(result_value, BaseException) - raise result_value - assert result_kind == "event" - assert result_value is not None - assert not isinstance(result_value, BaseException) - event = result_value - except StopAsyncIteration: - if stream_owner is None: - await _close_async_iterator_quietly(stream) - return - if _stream_event_blocks_retry(event): - emitted_retry_unsafe_event = True - if failed_retry_attempts_out is not None: - failed_retry_attempts_out[:] = [ - failed_policy_attempts + compatibility_retries_taken - ] - yield event - finally: - if stream_owner is not None and not stream_owner.done(): - await _cancel_and_drain_model_attempt_task(stream_owner) - return - except _StreamAttemptSkipped as skipped: - raise skipped.reason from None - except BaseException as error: - if isinstance(error, ModelTimeoutError): - # The timed owner has already been cancelled and drained. Do not retain its - # task, result queues, or previous event in the public timeout traceback frame. - stream = None - stream_owner = None - stream_requests = None - stream_results = None - event = None - result_value = None - if stream_owner is None: - await _close_async_iterator_quietly(stream) - if isinstance(error, asyncio.CancelledError | GeneratorExit): - raise - if not isinstance(error, Exception): - raise - if ( - not replay_unsafe_request - and _is_conversation_locked_error(error) - and _should_preserve_conversation_locked_compatibility(retry_settings) - ): - if compatibility_retries_taken < COMPATIBILITY_CONVERSATION_LOCKED_RETRIES: - compatibility_retries_taken += 1 - delay = 1.0 * (2 ** (compatibility_retries_taken - 1)) - logger.debug( - ( - "Conversation locked during streamed request, retrying in %ss " - "(attempt %s/%s)." - ), - delay, - compatibility_retries_taken, - COMPATIBILITY_CONVERSATION_LOCKED_RETRIES, + try: + result_kind, result_value = await _await_model_attempt( + stream_results.get(), + remaining, + timeout_error_seconds=timeout, + ) + except ModelTimeoutError as error: + await _cancel_and_drain_model_attempt_task( + stream_owner, + error, + cancel_cleanup=True, + ) + raise + except asyncio.CancelledError: + await _cancel_and_drain_model_attempt_task(stream_owner) + raise + if result_kind == "done": + remaining = max( + deadline - asyncio.get_running_loop().time(), 0.0 + ) + await _await_model_attempt( + stream_owner, + remaining, + timeout_error_seconds=timeout, + ) + return + if result_kind == "error": + remaining = max( + deadline - asyncio.get_running_loop().time(), 0.0 + ) + await _await_model_attempt( + stream_owner, + remaining, + timeout_error_seconds=timeout, + ) + assert isinstance(result_value, BaseException) + raise result_value + assert result_kind == "event" + assert result_value is not None + assert not isinstance(result_value, BaseException) + event = result_value + except StopAsyncIteration: + if stream_owner is None: + await _close_async_iterator_quietly(stream) + return + if _stream_event_blocks_retry(event): + emitted_retry_unsafe_event = True + if failed_retry_attempts_out is not None: + failed_retry_attempts_out[:] = [ + failed_policy_attempts + compatibility_retries_taken + ] + yield event + finally: + if stream_owner is not None and not stream_owner.done(): + await _cancel_and_drain_model_attempt_task(stream_owner) + return + except _StreamAttemptSkipped as skipped: + raise skipped.reason from None + except BaseException as error: + if isinstance(error, ModelTimeoutError): + # The timed owner has already been cancelled and drained. Do not retain its + # task, result queues, or previous event in the public timeout traceback frame. + stream = None + stream_owner = None + stream_requests = None + stream_results = None + event = None + result_value = None + if stream_owner is None: + await _close_async_iterator_quietly(stream) + if isinstance(error, asyncio.CancelledError | GeneratorExit): + raise + if not isinstance(error, Exception): + raise + if ( + not replay_unsafe_request + and _is_conversation_locked_error(error) + and _should_preserve_conversation_locked_compatibility(retry_settings) + ): + if compatibility_retries_taken < COMPATIBILITY_CONVERSATION_LOCKED_RETRIES: + compatibility_retries_taken += 1 + delay = 1.0 * (2 ** (compatibility_retries_taken - 1)) + logger.debug( + ( + "Conversation locked during streamed request, retrying in %ss " + "(attempt %s/%s)." + ), + delay, + compatibility_retries_taken, + COMPATIBILITY_CONVERSATION_LOCKED_RETRIES, + ) + await rewind() + await _sleep_for_retry(delay) + request_attempt += 1 + continue + provider_advice = get_retry_advice( + ModelRetryAdviceRequest( + error=error, + attempt=policy_attempt, + stream=True, + previous_response_id=previous_response_id, + conversation_id=conversation_id, ) - await rewind() - await _sleep_for_retry(delay) - request_attempt += 1 - continue - provider_advice = get_retry_advice( - ModelRetryAdviceRequest( + ) + decision = await _evaluate_retry( error=error, attempt=policy_attempt, + max_retries=( + max(retry_settings.max_retries or 0, 0) if retry_settings is not None else 0 + ), + retry_policy=retry_settings.policy if retry_settings is not None else None, + retry_backoff=retry_settings.backoff if retry_settings is not None else None, stream=True, + replay_unsafe_request=replay_unsafe_request, + emitted_retry_unsafe_event=emitted_retry_unsafe_event, + provider_advice=provider_advice, previous_response_id=previous_response_id, conversation_id=conversation_id, ) - ) - decision = await _evaluate_retry( - error=error, - attempt=policy_attempt, - max_retries=( - max(retry_settings.max_retries or 0, 0) if retry_settings is not None else 0 - ), - retry_policy=retry_settings.policy if retry_settings is not None else None, - retry_backoff=retry_settings.backoff if retry_settings is not None else None, - stream=True, - replay_unsafe_request=replay_unsafe_request, - emitted_retry_unsafe_event=emitted_retry_unsafe_event, - provider_advice=provider_advice, - previous_response_id=previous_response_id, - conversation_id=conversation_id, - ) - if not decision.retry: - raise - - logger.debug( - "Retrying failed streamed model request in %ss (attempt %s/%s).", - decision.delay, - policy_attempt, - retry_settings.max_retries - if retry_settings is not None and retry_settings.max_retries is not None - else 0, - ) - await rewind() - await _sleep_for_retry(decision.delay or 0.0) - request_attempt += 1 - policy_attempt += 1 - failed_policy_attempts += 1 + if not decision.retry: + raise + + logger.debug( + "Retrying failed streamed model request in %ss (attempt %s/%s).", + decision.delay, + policy_attempt, + retry_settings.max_retries + if retry_settings is not None and retry_settings.max_retries is not None + else 0, + ) + await rewind() + await _sleep_for_retry(decision.delay or 0.0) + request_attempt += 1 + policy_attempt += 1 + failed_policy_attempts += 1 + finally: + model_spans.finish() diff --git a/src/agents/run_internal/tool_actions.py b/src/agents/run_internal/tool_actions.py index 7bf3779e48..62c924264a 100644 --- a/src/agents/run_internal/tool_actions.py +++ b/src/agents/run_internal/tool_actions.py @@ -55,6 +55,7 @@ normalize_max_output_length, normalize_shell_output, normalize_shell_output_entries, + pending_tool_span, render_shell_outputs, resolve_approval_rejection_message, resolve_approval_status, @@ -62,7 +63,6 @@ run_tool_end_hooks, serialize_shell_output, truncate_shell_outputs, - with_tool_function_span, ) from .tool_hooks import transform_tool_output @@ -123,8 +123,8 @@ async def execute( """Run a computer action, capturing a screenshot and notifying hooks.""" trace_tool_name = get_tool_trace_name_for_tool(action.computer_tool) or cls.TRACE_TOOL_NAME - async def _run_action(span: Any | None) -> RunItem: - if span is not None and config.trace_include_sensitive_data: + async def _run_action(span: Any) -> RunItem: + if config.trace_include_sensitive_data: span.span_data.input = _serialize_trace_payload( cls._get_trace_input_payload(action.tool_call) ) @@ -133,6 +133,7 @@ async def _run_action(span: Any | None) -> RunItem: tool=action.computer_tool, run_context=context_wrapper ) agent_hooks = agent.hooks + span.start(mark_as_current=True) context_wrapper._mark_tool_invocation_executed( action.tool_call, tool_name=action.computer_tool.name, @@ -154,16 +155,15 @@ async def _run_action(span: Any | None) -> RunItem: trace_include_sensitive_data=config.trace_include_sensitive_data, error_message=error_text, ) - if span is not None: - span.set_error( - SpanError( - message="Error running tool", - data={ - "tool_name": trace_tool_name, - "error": trace_error, - }, - ) + span.set_error( + SpanError( + message="Error running tool", + data={ + "tool_name": trace_tool_name, + "error": trace_error, + }, ) + ) log_tool_action_error("Failed to execute computer action", exc) raise @@ -172,7 +172,7 @@ async def _run_action(span: Any | None) -> RunItem: ) async def finalize_output( - screenshot: str, span: Any | None, agent_hooks: AgentHooks[Any] | None + screenshot: str, span: Any, agent_hooks: AgentHooks[Any] | None ) -> ToolCallOutputItem: output = await transform_tool_output( config, context_wrapper, agent, action.computer_tool, action.tool_call, screenshot @@ -213,16 +213,13 @@ async def finalize_output( hooks, agent_hooks, context_wrapper, agent, action.computer_tool, output ) - if span is not None and config.trace_include_sensitive_data: + if config.trace_include_sensitive_data: span.span_data.output = image_url return output_item - return await with_tool_function_span( - config=config, - tool_name=trace_tool_name, - fn=_run_action, - ) + with pending_tool_span(config, trace_tool_name, action.tool_call.call_id) as span: + return await _run_action(span) @classmethod async def _execute_action_and_capture( @@ -434,35 +431,46 @@ async def execute( ctx_wrapper=context_wrapper, data=call.tool_call, ) - output = call.local_shell_tool.executor(request) - raw_result = await output if inspect.isawaitable(output) else output - - async def finalize_output() -> ToolCallOutputItem: - result = await transform_tool_output( - config, context_wrapper, agent, call.local_shell_tool, call.tool_call, raw_result - ) - - raw_payload: dict[str, Any] = { - "type": "local_shell_call_output", - "call_id": call.tool_call.call_id, - "output": result, - } - output_item = ToolCallOutputItem( - agent=agent, - output=result, - raw_item=raw_payload, - ) + with pending_tool_span(config, call.local_shell_tool.name, call.tool_call.call_id) as span: + span.start(mark_as_current=True) + if span.span_data.operation.detail == "content": + span.span_data.input = _serialize_trace_payload(call.tool_call.action) + output = call.local_shell_tool.executor(request) + raw_result = await output if inspect.isawaitable(output) else output + + async def finalize_output() -> ToolCallOutputItem: + result = await transform_tool_output( + config, + context_wrapper, + agent, + call.local_shell_tool, + call.tool_call, + raw_result, + ) + if span.span_data.operation.detail == "content": + span.span_data.output = result + + raw_payload: dict[str, Any] = { + "type": "local_shell_call_output", + "call_id": call.tool_call.call_id, + "output": result, + } + output_item = ToolCallOutputItem( + agent=agent, + output=result, + raw_item=raw_payload, + ) - if tool_output_committer is not None: - tool_output_committer(output_item) + if tool_output_committer is not None: + tool_output_committer(output_item) - await run_tool_end_hooks( - hooks, agent_hooks, context_wrapper, agent, call.local_shell_tool, result - ) + await run_tool_end_hooks( + hooks, agent_hooks, context_wrapper, agent, call.local_shell_tool, result + ) - return output_item + return output_item - return await run_native_tool_post_invoke(finalize_output(), sibling_category_failure) + return await run_native_tool_post_invoke(finalize_output(), sibling_category_failure) class ShellAction: @@ -490,7 +498,7 @@ async def execute( tool_name=shell_tool.name, ) - async def _run_call(span: Any | None) -> RunItem: + async def _run_call(span: Any) -> RunItem: if span is not None and config.trace_include_sensitive_data: span.span_data.input = _serialize_trace_payload( dataclasses.asdict(shell_call.action) @@ -527,6 +535,7 @@ async def _run_call(span: Any | None) -> RunItem: ) if approval_status is None: + span.span_data.operation.outcome = "paused" return approval_item if approval_status is False: @@ -550,6 +559,7 @@ async def _run_call(span: Any | None) -> RunItem: call.tool_call, tool_name=shell_tool.name, ) + span.start(mark_as_current=True) await gather_with_cancel( hooks.on_tool_start(context_wrapper, agent, shell_tool), ( @@ -587,7 +597,7 @@ async def finalize_output( result: str | ShellResult, status: Literal["completed", "failed"], requested_max_output_length: int | None, - span: Any | None, + span: Any, ) -> ToolCallOutputItem: result = await transform_tool_output( config, context_wrapper, agent, shell_tool, call.tool_call, result @@ -655,11 +665,12 @@ async def finalize_output( hooks, agent_hooks, context_wrapper, agent, shell_tool, output_text ) + span.span_data.operation.outcome = status if span is not None and config.trace_include_sensitive_data: span.span_data.output = output_text return output_item - def record_shell_failure(exc: Exception, span: Any | None) -> str: + def record_shell_failure(exc: Exception, span: Any) -> str: message = format_shell_error(exc) if span is not None: trace_error = get_trace_tool_error( @@ -675,11 +686,8 @@ def record_shell_failure(exc: Exception, span: Any | None) -> str: log_tool_action_error("Shell executor failed", exc) return message - return await with_tool_function_span( - config=config, - tool_name=shell_tool.name, - fn=_run_call, - ) + with pending_tool_span(config, shell_tool.name, shell_call.call_id) as span: + return await _run_call(span) class CustomToolAction: @@ -720,8 +728,8 @@ async def execute( tool_name=custom_tool.name, ) - async def _run_call(span: Any | None) -> RunItem: - if span is not None and config.trace_include_sensitive_data: + async def _run_call(span: Any) -> RunItem: + if config.trace_include_sensitive_data: span.span_data.input = tool_input approval_status = context_wrapper.get_approval_status( @@ -752,6 +760,7 @@ async def _run_call(span: Any | None) -> RunItem: ) if approval_status is None: + span.span_data.operation.outcome = "paused" return approval_item if approval_status is False: @@ -779,6 +788,7 @@ async def _run_call(span: Any | None) -> RunItem: call.tool_call, tool_name=custom_tool.name, ) + span.start(mark_as_current=True) await gather_with_cancel( hooks.on_tool_start(tool_context, agent, custom_tool), ( @@ -798,23 +808,22 @@ async def _run_call(span: Any | None) -> RunItem: trace_include_sensitive_data=config.trace_include_sensitive_data, error_message=output_text, ) - if span is not None: - span.set_error( - SpanError( - message="Error running tool", - data={ - "tool_name": custom_tool.name, - "error": trace_error, - }, - ) + span.set_error( + SpanError( + message="Error running tool", + data={ + "tool_name": custom_tool.name, + "error": trace_error, + }, ) + ) log_tool_action_error("Custom tool failed", exc) return await run_native_tool_post_invoke( finalize_output(output_text, span), sibling_category_failure ) - async def finalize_output(result: str, span: Any | None) -> ToolCallOutputItem: + async def finalize_output(result: str, span: Any) -> ToolCallOutputItem: output_text = await transform_tool_output( config, tool_context, agent, custom_tool, call.tool_call, result ) @@ -850,15 +859,12 @@ async def finalize_output(result: str, span: Any | None) -> ToolCallOutputItem: hooks, agent_hooks, tool_context, agent, custom_tool, output_text ) - if span is not None and config.trace_include_sensitive_data: + if config.trace_include_sensitive_data: span.span_data.output = output_text return output_item - return await with_tool_function_span( - config=config, - tool_name=custom_tool.name, - fn=_run_call, - ) + with pending_tool_span(config, custom_tool.name, call_id) as span: + return await _run_call(span) @staticmethod def _normalize_output(output: Any) -> str: @@ -927,8 +933,8 @@ async def execute( tool_name=apply_patch_tool.name, ) - async def _run_call(span: Any | None) -> RunItem: - if span is not None and config.trace_include_sensitive_data: + async def _run_call(span: Any) -> RunItem: + if config.trace_include_sensitive_data: span.span_data.input = _serialize_trace_payload( [ { @@ -970,6 +976,7 @@ async def _run_call(span: Any | None) -> RunItem: ) if approval_status is None: + span.span_data.operation.outcome = "paused" return approval_item if approval_status is False: @@ -994,6 +1001,7 @@ async def _run_call(span: Any | None) -> RunItem: call.tool_call, tool_name=apply_patch_tool.name, ) + span.start(mark_as_current=True) await gather_with_cancel( hooks.on_tool_start(context_wrapper, agent, apply_patch_tool), ( @@ -1038,16 +1046,15 @@ async def _run_call(span: Any | None) -> RunItem: trace_include_sensitive_data=config.trace_include_sensitive_data, error_message=output_text, ) - if span is not None: - span.set_error( - SpanError( - message="Error running tool", - data={ - "tool_name": apply_patch_tool.name, - "error": trace_error, - }, - ) + span.set_error( + SpanError( + message="Error running tool", + data={ + "tool_name": apply_patch_tool.name, + "error": trace_error, + }, ) + ) log_tool_action_error("Apply patch editor failed", exc) return await run_native_tool_post_invoke( @@ -1055,7 +1062,7 @@ async def _run_call(span: Any | None) -> RunItem: ) async def finalize_output( - result: str, status: Literal["completed", "failed"], span: Any | None + result: str, status: Literal["completed", "failed"], span: Any ) -> ToolCallOutputItem: output_text = await transform_tool_output( config, context_wrapper, agent, apply_patch_tool, call.tool_call, result @@ -1096,16 +1103,14 @@ async def finalize_output( hooks, agent_hooks, context_wrapper, agent, apply_patch_tool, output_text ) - if span is not None and config.trace_include_sensitive_data: + span.span_data.operation.outcome = status + if config.trace_include_sensitive_data: span.span_data.output = output_text return output_item - return await with_tool_function_span( - config=config, - tool_name=apply_patch_tool.name, - fn=_run_call, - ) + with pending_tool_span(config, apply_patch_tool.name, call_id) as span: + return await _run_call(span) __all__ = [ diff --git a/src/agents/run_internal/tool_execution.py b/src/agents/run_internal/tool_execution.py index 42fd412f55..84d0855cd2 100644 --- a/src/agents/run_internal/tool_execution.py +++ b/src/agents/run_internal/tool_execution.py @@ -12,7 +12,8 @@ import inspect import json from collections import deque -from collections.abc import Awaitable, Callable, Mapping, Sequence +from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence +from contextlib import contextmanager from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast from openai.types.responses import ResponseFunctionToolCall @@ -98,13 +99,12 @@ ToolOutputGuardrailData, ToolOutputGuardrailResult, ) -from ..tracing import Span, SpanError, function_span, get_current_trace +from ..tracing import FunctionSpanData, Span, SpanError, custom_span, function_span from ..util import _coro, _error_tracing from ..util._approvals import evaluate_function_tool_approval from ..util._asyncio_tasks import _consume_future_exception, gather_with_cancel from ..util._custom_data import maybe_extract_custom_data, merge_custom_data from ..util._tool_errors import get_trace_tool_error -from ..util._types import MaybeAwaitable from ._asyncio_progress import get_function_tool_task_progress_deadline from .agent_bindings import AgentBindings, bind_public_agent from .approvals import append_approval_error_output @@ -152,7 +152,7 @@ "normalize_shell_output_entries", "format_shell_error", "get_trace_tool_error", - "with_tool_function_span", + "pending_tool_span", "build_litellm_json_tool_call", "collect_manual_mcp_approvals", "index_approval_items_by_call_id", @@ -1128,26 +1128,48 @@ def log_tool_action_error( ) -async def with_tool_function_span( - *, - config: RunConfig, - tool_name: str, - fn: Callable[[Span[Any] | None], MaybeAwaitable[TToolSpanResult]], -) -> TToolSpanResult: - """Execute a tool callback in a function span when tracing is active.""" - if config.tracing_disabled or get_current_trace() is None: - result = fn(None) - if inspect.isawaitable(result): - return await result - direct_result: object = result - return cast(TToolSpanResult, direct_result) - - with function_span(tool_name) as span: - result = fn(span) - if inspect.isawaitable(result): - return await result - span_result: object = result - return cast(TToolSpanResult, span_result) +@contextmanager +def pending_tool_span( + config: RunConfig, tool_name: str, call_id: str | None +) -> Iterator[Span[FunctionSpanData]]: + """Prepare a span that the executor starts after approval and input guardrails.""" + span = function_span(tool_name, disabled=config.tracing_disabled) + operation = span.span_data.operation + operation.tool_call_id = call_id + try: + yield span + except asyncio.CancelledError: + operation.outcome = "interrupted" + raise + except Exception: + operation.outcome = "failed" + if span.error is None: + span.set_error(SpanError(message="Error running tool", data=None)) + raise + finally: + if span.started_at is not None: + if operation.outcome is None: + operation.outcome = "failed" if span.error else "completed" + span.finish(reset_current=True) + elif span.trace_id == "no-op": + span.finish(reset_current=True) + else: + # An early return is a decision about a tool, before execution begins. + operation.outcome = operation.outcome or "rejected" + if operation.detail is None: + # Existing processors read approval inputs and results from function spans. + span.start() + span.finish() + else: + with custom_span( + "tool_approval", + data={ + "tool_name": tool_name, + "tool_call_id": call_id, + "outcome": operation.outcome, + }, + ): + pass def build_litellm_json_tool_call(output: ResponseFunctionToolCall) -> FunctionTool: @@ -1814,7 +1836,7 @@ async def _run_single_tool( or get_function_tool_trace_name(func_tool) or func_tool.name ) - with function_span(trace_tool_name) as span_fn: + with pending_tool_span(self.config, trace_tool_name, tool_call.call_id) as span_fn: tool_context_namespace = get_tool_call_namespace(raw_tool_call) if tool_context_namespace is None: tool_context_namespace = get_tool_call_namespace(tool_call) @@ -1841,8 +1863,11 @@ async def _run_single_tool( ) if approval_result is not None: result = approval_result + if isinstance(result.run_item, ToolApprovalItem): + span_fn.span_data.operation.outcome = "paused" else: result = await self._execute_single_tool_body( + span=span_fn, outer_task=outer_task, task_state=task_state, func_tool=func_tool, @@ -1855,7 +1880,7 @@ async def _run_single_tool( trace_include_sensitive_data=self.config.trace_include_sensitive_data, error_message=str(e), ) - _error_tracing.attach_error_to_current_span( + span_fn.set_error( SpanError( message="Error running tool", data={"tool_name": func_tool.name, "error": trace_error}, @@ -2026,6 +2051,7 @@ async def _maybe_execute_tool_approval( async def _execute_single_tool_body( self, *, + span: Span[FunctionSpanData], outer_task: asyncio.Task[Any] | None, task_state: _FunctionToolTaskState, func_tool: FunctionTool, @@ -2053,6 +2079,8 @@ async def _execute_single_tool_body( self.schema_bypassed_tool_runs.add(id(task_state.tool_run)) return rejected_message + span.start(mark_as_current=True) + if not is_nested_continuation: await gather_with_cancel( self.hooks.on_tool_start(tool_context, self.public_agent, func_tool), ( diff --git a/src/agents/tracing/_content.py b/src/agents/tracing/_content.py new file mode 100644 index 0000000000..10b240b9ba --- /dev/null +++ b/src/agents/tracing/_content.py @@ -0,0 +1,165 @@ +"""Bound the JSON values captured for an opted-in operation.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Mapping +from itertools import chain +from typing import Any + +from pydantic import BaseModel + +CONTENT_LIMIT = 32 * 1024 +_TRUNCATED = "[truncated]" +_OMIT_FIELDS = { + "api_key", + "authorization", + "access_token", + "refresh_token", + "password", + "headers", + "encrypted_content", + "reasoning", + "reasoning_content", + "reasoning_details", + "thinking", + "image_url", + "file_data", + "image_data", + "audio_data", + "b64_json", + "client_metadata", + "x_api_key", +} +_OMIT_TYPES = { + "reasoning", + "reasoning_text", + "thinking", + "redacted_thinking", + "compaction", + "image", + "input_image", + "output_image", + "image_url", + "computer_screenshot", + "image_generation_call", + "audio", + "input_audio", + "output_audio", + "file", + "input_file", + "video", + "input_video", + "encrypted_content", +} +_OMIT_FIELDS = {key.replace("_", "") for key in _OMIT_FIELDS} +# Consume the entire header even if the payload is missing, so repeated +# "data:" prefixes in one malformed header cannot trigger quadratic rescans. +_DATA_URI = re.compile(r"data:[^\s;,][^\s,]*(,[^\s\"'<>]+)?", re.IGNORECASE) +_JSON_PREFIX = re.compile(r"\s*[\[{]") + + +def _json(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + + +def _size(value: Any) -> int: + return len(json.dumps(value, ensure_ascii=False, allow_nan=False).encode("utf-8")) + + +def _text(value: str, budget: int) -> str: + if len(value) <= budget and _size(value) <= budget: + return value + low, high = 0, min(budget, len(value)) + while low < high: + pivot = (low + high + 1) // 2 + if _size(value[:pivot] + _TRUNCATED) <= budget: + low = pivot + else: + high = pivot - 1 + return value[:low] + _TRUNCATED + + +def _project(value: Any, budget: int, depth: int) -> Any: + if depth > 32: + return _TRUNCATED + if isinstance(value, str): + if _JSON_PREFIX.match(value): + if len(value) > budget or len(value.encode("utf-8")) > budget: + return _json({"omitted": True, "truncated": True, "reason": "capture_budget"}) + try: + embedded = json.loads(value) + except ValueError: + pass + else: + safe = _project(embedded, budget, depth + 1) + if safe == embedded and _size(value) <= budget: + return value + encoded = _json(safe) + if _size(encoded) > budget: + # Escaping can double the bytes. Rebudget the value rather than + # slicing encoded JSON into an invalid tool result. + encoded = _json(_project(embedded, (budget - 2) // 2, depth + 1)) + return encoded + value = _DATA_URI.sub( + lambda match: "[omitted: media]" if match.start(1) >= 0 else match[0], + _text(value, budget), + ) + return _text(value, budget) + if value is None or isinstance(value, (bool, float, int)): + return value if _size(value) <= budget else _TRUNCATED + if isinstance(value, BaseModel): + value = value.model_dump(mode="python") + if isinstance(value, Mapping): + kind = value.get("type") + if isinstance(kind, str) and kind in _OMIT_TYPES: + return {"type": kind, "omitted": True, "reason": "unsupported_content"} + resource = value.get("resource") + if kind == "resource" and isinstance(resource, Mapping) and "blob" in resource: + return {"type": kind, "omitted": True, "reason": "unsupported_content"} + result: dict[str, Any] = {} + used = 2 + identity = ("type", "role", "id", "call_id", "name") + prioritized = ((key, value[key]) for key in identity if key in value) + remaining = ((key, item) for key, item in value.items() if key not in identity) + for key, item in chain(prioritized, remaining): + if not isinstance(key, str): + continue + # Reserve space for a trailing marker before accepting another field. + available = budget - used - 4 - 32 + if len(key) > available: + result["truncated"] = True + break + key_size = _size(key) + available -= key_size + if available < 84: + result["truncated"] = True + break + if key.lower().replace("-", "").replace("_", "") in _OMIT_FIELDS: + item = "[omitted]" + result[key] = _project(item, available, depth + 1) + used += key_size + _size(result[key]) + 4 + return result + if isinstance(value, (list, tuple)): + items: list[Any] = [] + used = 2 + for item in value: + available = budget - used - 2 - 32 + if available < 84: + items.append({"truncated": True}) + break + items.append(_project(item, available, depth + 1)) + used += _size(items[-1]) + 2 + return items + return "[omitted: binary or unsupported]" + + +def bound_content(value: Any) -> Any: + """Keep readable text and structure within a 32 KiB serialized UTF-8 budget.""" + try: + captured = _project(value, CONTENT_LIMIT - 256, 0) + return captured if _size(captured) <= CONTENT_LIMIT else {"truncated": True} + except Exception: + # A tool result may have a custom serializer. Tracing must not fail its caller. + return "[omitted: serialization failed]" diff --git a/src/agents/tracing/_model.py b/src/agents/tracing/_model.py new file mode 100644 index 0000000000..bb38784814 --- /dev/null +++ b/src/agents/tracing/_model.py @@ -0,0 +1,208 @@ +"""Shared model operation lifecycle for provider adapters and Runner retries.""" + +from __future__ import annotations + +import asyncio +import sys +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from . import util +from .config import get_operation_detail +from .create import generation_span, response_span +from .span_data import GenerationSpanData, OperationMetadata, ResponseSpanData +from .spans import Span +from .traces import Trace + +if TYPE_CHECKING: + from ..models.interface import ModelTracing + +ModelSpan = Span[GenerationSpanData] | Span[ResponseSpanData] + + +@dataclass +class ModelRetrySpans: + attempt: int = 0 + operations: int = 0 + active: ModelSpan | None = None + pending: ModelSpan | None = None + ended_at: str | None = None + carried_usage: dict[str, Any] | None = None + + def begin_attempt(self, attempt: int) -> None: + if attempt != self.attempt: + self.attempt = attempt + self.operations = 0 + self.active = None + + def finish(self) -> None: + if self.pending is not None: + span, self.pending = self.pending, None + if isinstance(sys.exc_info()[1], asyncio.CancelledError): + span.span_data.operation.outcome = "interrupted" + span.span_data.operation.estimated_end = True + self.ended_at = None + if self.ended_at is not None: + span.finish_at(self.ended_at) + else: + span.finish() + + +_retry_spans: ContextVar[ModelRetrySpans | None] = ContextVar("model_retry_spans", default=None) + + +@contextmanager +def model_retry_scope(group: ModelRetrySpans, attempt: int) -> Iterator[None]: + group.begin_attempt(attempt) + token = _retry_spans.set(group) + try: + yield + finally: + _retry_spans.reset(token) + + +def acquire_model_span( + tracing: ModelTracing, + model: str | None = None, + *, + parent: Trace | Span[Any] | None = None, + started_at: str | None = None, +) -> ModelSpan: + detail = get_operation_detail(include_data=tracing.include_data()) + group = _retry_spans.get() if detail is not None else None + if group is not None: + if group.operations == 0 and group.pending is not None: + span, group.pending = group.pending, None + group.ended_at = None + group.carried_usage = span.span_data.usage + span.span_data.usage = None + span.span_data.operation = OperationMetadata( + detail=detail, api_type="responses", model=model + ) + if isinstance(span.span_data, GenerationSpanData): + span.span_data.input = None + span.span_data.output = None + span.span_data.model_config = None + span.span_data.tools = None + span.span_data.model = model + span.clear_error() + group.operations += 1 + group.active = span + return span + group.finish() + group.operations += 1 + span = ( + generation_span(model=model, parent=parent, disabled=tracing.is_disabled()) + if detail is not None + else response_span(parent=parent, disabled=tracing.is_disabled()) + ) + if group is not None: + group.active = span + span.span_data.operation.api_type = "responses" + span.span_data.operation.detail = detail + span.span_data.operation.model = model + if started_at is not None: + span.start_at(started_at) + else: + span.start() + return span + + +def finish_model_span(span: ModelSpan, *, ended_at: str | None = None) -> None: + operation = span.span_data.operation + group = _retry_spans.get() if operation.detail is not None else None + if span.ended_at is not None or (group is not None and group.pending is span): + return + if operation.outcome is None: + operation.outcome = "failed" if span.error is not None else "completed" + if group is not None and group.active is not span: + group = None + if group is not None and group.carried_usage is not None: + span.span_data.usage = _add_usage(group.carried_usage, span.span_data.usage or {}) + group.carried_usage = None + if group is not None and group.operations == 1 and operation.outcome == "failed": + group.finish() + group.pending = span + group.ended_at = ended_at or util.time_iso() + return + if ended_at is not None: + span.finish_at(ended_at) + else: + span.finish() + + +@contextmanager +def model_span(tracing: ModelTracing, model: str | None = None) -> Iterator[ModelSpan]: + span = acquire_model_span(tracing, model) + with span.as_current(): + try: + yield span + except BaseException as error: + if isinstance(error, Exception) or span.error is not None: + span.span_data.operation.outcome = "failed" + elif span.span_data.operation.outcome is None: + span.span_data.operation.outcome = "interrupted" + raise + finally: + finish_model_span(span) + + +def _add_usage(previous: dict[str, Any], current: dict[str, Any]) -> dict[str, Any]: + result = dict(previous) + for key, value in current.items(): + old = result.get(key) + if isinstance(old, dict) and isinstance(value, dict): + result[key] = _add_usage(old, value) + elif isinstance(old, int) and isinstance(value, int): + result[key] = old + value + else: + result[key] = value + return result + + +def record_model_input(data: GenerationSpanData, request: Any) -> None: + """Capture the approved request fields under one shared input-direction budget.""" + from ._content import bound_content + + if data.operation.detail != "content": + return + if not isinstance(request, dict): + data.input = [{"omitted": True, "reason": "unsupported input projection"}] + return + previous_response_id = request.get("previous_response_id") + if isinstance(previous_response_id, str): + data.operation.previous_response_id = previous_response_id + approved = { + key: request[key] for key in ("input", "truncated", "omitted", "reason") if key in request + } + if isinstance(approved.get("input"), str): + approved["input"] = [{"role": "user", "content": approved["input"]}] + instructions = request.get("instructions") + if isinstance(instructions, str): + approved["instructions"] = instructions + captured = bound_content(approved) + if not isinstance(captured, dict): + data.input = [{"omitted": True, "reason": "input serialization failed"}] + return + if "input" not in captured and captured.get("omitted"): + data.input = [captured] + return + marker = {key: captured[key] for key in ("truncated", "omitted", "reason") if key in captured} + if marker: + items = captured.get("input", []) + if isinstance(items, list): + # Rebudget after moving the outer marker so exporters cannot lose it on extraction. + with_marker = {"input": [*items, marker]} + if "instructions" in captured: + with_marker["instructions"] = captured["instructions"] + captured = bound_content(with_marker) + items = captured.get("input") + if isinstance(items, str): + items = [{"role": "user", "content": items}] + data.input = items + data.model_config = ( + {"instructions": captured["instructions"]} if "instructions" in captured else None + ) diff --git a/src/agents/tracing/config.py b/src/agents/tracing/config.py index fb6ee013d1..5516c46f86 100644 --- a/src/agents/tracing/config.py +++ b/src/agents/tracing/config.py @@ -1,7 +1,17 @@ from __future__ import annotations +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Literal + from typing_extensions import TypedDict +from .scope import Scope + +OperationDetail = Literal["metadata", "content"] +_operation_detail: ContextVar[OperationDetail | None] = ContextVar("operation_detail", default=None) + class TracingConfig(TypedDict, total=False): """Configuration for tracing behavior and export.""" @@ -12,7 +22,43 @@ class TracingConfig(TypedDict, total=False): include_task_and_turn_spans: bool """Whether the runner creates task and turn spans. Defaults to True when omitted.""" + operation_detail: OperationDetail + """Select metadata or bounded content for model calls and tools in this run. + + Omit to use existing SDK payload fields. Explicit content capture requires + trace_include_sensitive_data in the run configuration. + """ + def include_task_and_turn_spans(config: TracingConfig | None) -> bool: """Resolve whether automatic runner task and turn spans are enabled.""" return config is None or config.get("include_task_and_turn_spans", True) + + +def get_operation_detail(*, include_data: bool = True) -> OperationDetail | None: + """Return the current run's effective capture setting.""" + detail = _operation_detail.get() + if detail == "content": + span = Scope.get_current_span() + trace = Scope.get_current_trace() + if ( + not include_data + or (trace is not None and trace.trace_id == "no-op") + or (span is not None and span.trace_id == "no-op") + ): + return "metadata" + return detail + + +@contextmanager +def operation_tracing_scope( + config: TracingConfig | None, include_sensitive: bool +) -> Iterator[None]: + detail = config.get("operation_detail") if config else None + if detail is not None and not include_sensitive: + detail = "metadata" + token = _operation_detail.set(detail) + try: + yield + finally: + _operation_detail.reset(token) diff --git a/src/agents/tracing/processor_interface.py b/src/agents/tracing/processor_interface.py index d0f18bde38..1f8896797d 100644 --- a/src/agents/tracing/processor_interface.py +++ b/src/agents/tracing/processor_interface.py @@ -128,6 +128,18 @@ def force_flush(self) -> None: """ pass + def on_span_scope_enter(self, span: "Span[Any]") -> object | None: + """Activate optional execution context after a span becomes current. + + The return value belongs to the matching scope exit, independently of span end. + Existing processors do not need to implement these optional methods. + """ + return None + + def on_span_scope_exit(self, span: "Span[Any]", token: object) -> None: + """Restore the execution context associated with a matching scope entry.""" + return None + class TracingExporter(abc.ABC): """Exports traces and spans. For example, could log them or send them to a backend.""" diff --git a/src/agents/tracing/provider.py b/src/agents/tracing/provider.py index fcc807b778..d07e7230f6 100644 --- a/src/agents/tracing/provider.py +++ b/src/agents/tracing/provider.py @@ -174,6 +174,28 @@ def on_span_end(self, span: Span[Any]) -> None: diagnostic_extra=partial(_processor_diagnostic_extra, processor), ) + def on_span_scope_enter(self, span: Span[Any]) -> object: + entered: list[tuple[TracingProcessor, object]] = [] + for processor in self._processors: + callback = getattr(processor, "on_span_scope_enter", None) + if callback is None: + continue + try: + token = callback(span) + if token is not None: + entered.append((processor, token)) + except Exception: + logger.warning("Error in trace processor during scope entry") + return entered + + def on_span_scope_exit(self, span: Span[Any], token: object) -> None: + # Restore the processors that entered, even if registration changed meanwhile. + for processor, scope_token in reversed(cast(list[tuple[TracingProcessor, object]], token)): + try: + processor.on_span_scope_exit(span, scope_token) + except Exception: + logger.warning("Error in trace processor during scope exit") + def shutdown(self, timeout: float | None = None) -> None: """ Called when the application stops. diff --git a/src/agents/tracing/span_data.py b/src/agents/tracing/span_data.py index 6cf38937c8..ae82e0131d 100644 --- a/src/agents/tracing/span_data.py +++ b/src/agents/tracing/span_data.py @@ -2,7 +2,11 @@ import abc from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast + +from ._content import bound_content +from .config import OperationDetail, get_operation_detail if TYPE_CHECKING: from openai.types.responses import Response, ResponseInputItemParam @@ -132,13 +136,79 @@ def export(self) -> dict[str, Any]: } -class FunctionSpanData(SpanData): +@dataclass(slots=True) +class OperationMetadata: + """Capture permission and source facts for one model call or tool execution.""" + + detail: OperationDetail | None = field(default_factory=get_operation_detail) + api_type: str | None = None + model: str | None = None + response_model: str | None = None + response_id: str | None = None + previous_response_id: str | None = None + tool_call_id: str | None = None + operation_id: str | None = None + outcome: str | None = None + estimated_end: bool = False + + def export(self) -> dict[str, Any]: + """Supply detailed operation facts alongside the existing hosted span schema.""" + values = { + "detail": self.detail, + "api_type": self.api_type, + "model": self.model, + "response_model": self.response_model, + "response_id": self.response_id, + "previous_response_id": self.previous_response_id, + "tool_call_id": self.tool_call_id, + "operation_id": self.operation_id, + "outcome": self.outcome, + "estimated_end": True if self.estimated_end else None, + } + return {key: value for key, value in values.items() if value is not None} + + +_Payload = TypeVar("_Payload") +_Input = TypeVar("_Input") +_Output = TypeVar("_Output") + + +def _capture_payload(operation: OperationMetadata, value: _Payload) -> _Payload | None: + if operation.detail == "metadata": + return None + if operation.detail == "content" and value is not None: + return cast(_Payload, bound_content(value)) + return value + + +class _CapturedSpanData(SpanData, Generic[_Input, _Output]): + __slots__ = ("_input", "_output", "operation") + operation: OperationMetadata + + @property + def input(self) -> _Input | None: + return self._input + + @input.setter + def input(self, value: _Input | None) -> None: + self._input = _capture_payload(self.operation, value) + + @property + def output(self) -> _Output | None: + return self._output + + @output.setter + def output(self, value: _Output | None) -> None: + self._output = _capture_payload(self.operation, value) + + +class FunctionSpanData(_CapturedSpanData[str, Any]): """ Represents a Function Span in the trace. Includes input, output and MCP data (if applicable). """ - __slots__ = ("name", "input", "output", "mcp_data") + __slots__ = ("name", "mcp_data") def __init__( self, @@ -148,6 +218,7 @@ def __init__( mcp_data: dict[str, Any] | None = None, ): self.name = name + self.operation = OperationMetadata() self.input = input self.output = output self.mcp_data = mcp_data @@ -166,19 +237,19 @@ def export(self) -> dict[str, Any]: } -class GenerationSpanData(SpanData): +class GenerationSpanData( + _CapturedSpanData[Sequence[Mapping[str, Any]], Sequence[Mapping[str, Any]]] +): """ Represents a Generation Span in the trace. Includes input, output, model, model configuration, usage, and optional tool definitions. """ __slots__ = ( - "input", - "output", "model", - "model_config", + "_model_config", "usage", - "tools", + "_tools", ) def __init__( @@ -190,6 +261,10 @@ def __init__( usage: dict[str, Any] | None = None, tools: Sequence[Mapping[str, Any]] | None = None, ): + self.operation = OperationMetadata(model=model) + self._input = None + self._model_config = None + self._tools = None self.input = input self.output = output self.model = model @@ -197,6 +272,51 @@ def __init__( self.usage = usage self.tools = tools + def _set_input_payload(self, field: str, value: Any) -> None: + if self.operation.detail != "content": + setattr(self, f"_{field}", _capture_payload(self.operation, value)) + return + # Keep submitted messages ahead of optional configuration and tool definitions. + payload = {"input": self._input, "model_config": self._model_config, "tools": self._tools} + payload[field] = value + captured = bound_content({key: item for key, item in payload.items() if item is not None}) + if not isinstance(captured, Mapping): + captured = {"input": [{"omitted": True, "reason": "serialization_failed"}]} + captured = cast(Mapping[str, Any], captured) + self._input = captured.get("input") + self._model_config = captured.get("model_config") + self._tools = captured.get("tools") + if captured.get("truncated"): + marker = {"truncated": True} + if self._input is None: + self._input = [marker] + elif isinstance(self._input, list) and marker not in self._input: + self._input = [*self._input, marker] + + @property + def input(self) -> Sequence[Mapping[str, Any]] | None: + return self._input + + @input.setter + def input(self, value: Sequence[Mapping[str, Any]] | None) -> None: + self._set_input_payload("input", value) + + @property + def model_config(self) -> Mapping[str, Any] | None: + return self._model_config + + @model_config.setter + def model_config(self, value: Mapping[str, Any] | None) -> None: + self._set_input_payload("model_config", value) + + @property + def tools(self) -> Sequence[Mapping[str, Any]] | None: + return self._tools + + @tools.setter + def tools(self, value: Sequence[Mapping[str, Any]] | None) -> None: + self._set_input_payload("tools", value) + @property def type(self) -> str: return "generation" @@ -219,7 +339,7 @@ class ResponseSpanData(SpanData): Includes response and input. """ - __slots__ = ("response", "input", "usage", "_response_id") + __slots__ = ("response", "input", "usage", "_response_id", "operation") def __init__( self, @@ -233,15 +353,19 @@ def __init__( self.input = input self.usage = usage self._response_id: str | None = None + self.operation = OperationMetadata() @property def type(self) -> str: return "response" def export(self) -> dict[str, Any]: + response_id = self.response.id if self.response is not None else self._response_id + if self.operation.operation_id is not None: + response_id = self.operation.response_id return { "type": self.type, - "response_id": (self.response.id if self.response is not None else self._response_id), + "response_id": response_id, "usage": self.usage, } diff --git a/src/agents/tracing/spans.py b/src/agents/tracing/spans.py index 8f564beedb..cbbb35d97c 100644 --- a/src/agents/tracing/spans.py +++ b/src/agents/tracing/spans.py @@ -2,6 +2,8 @@ import abc import contextvars +from collections.abc import Iterator +from contextlib import contextmanager from typing import Any, Generic, TypeVar from typing_extensions import TypedDict @@ -10,7 +12,7 @@ from . import util from .processor_interface import TracingProcessor from .scope import Scope -from .span_data import SpanData +from .span_data import OperationMetadata, SpanData TSpanData = TypeVar("TSpanData", bound=SpanData) _SPAN_METADATA_ROUTING_KEYS = ("agent_harness_id",) @@ -46,6 +48,9 @@ def _finish_on_generator_exit(span: Span[Any]) -> None: """ span.finish(reset_current=False) + if isinstance(span, SpanImpl): + span._exit_processor_scope() + token: contextvars.Token[Span[Any] | None] | None = span._prev_span_token # type: ignore[attr-defined] if token is None: return @@ -145,6 +150,53 @@ def finish(self, reset_current: bool = False) -> None: """ pass + def start_at(self, started_at: str) -> None: + """Start an external operation at its source ISO 8601 timestamp.""" + self.start() + + def finish_at(self, ended_at: str) -> None: + """Finish an external operation at its source ISO 8601 timestamp.""" + self.finish() + + def clear_error(self) -> None: + """Clear a transient error when retrying the same operation.""" + + @contextmanager + def as_current(self) -> Iterator[Span[TSpanData]]: + """Activate an already-started span without changing its lifetime. + + Use this scope when one source-timed or retried operation spans several execution + intervals. Start and finish remain the caller's responsibility. + """ + token = Scope.set_current_span(self) + processor = getattr(self, "_processor", None) + callback = getattr(processor, "on_span_scope_enter", None) + scope_token: object | None = None + if callback is not None: + try: + scope_token = callback(self) + except Exception: + logger.warning("Error in trace processor during scope entry") + generator_exit = False + try: + yield self + except GeneratorExit: + generator_exit = True + raise + finally: + callback = getattr(processor, "on_span_scope_exit", None) + if callback is not None and scope_token is not None: + try: + callback(self, scope_token) + except Exception: + logger.warning("Error in trace processor during scope exit") + try: + Scope.reset_current_span(token) + except ValueError: + if not generator_exit: + raise + logger.debug("Skipping span context reset, token belongs to another context") + @abc.abstractmethod def __enter__(self) -> Span[TSpanData]: pass @@ -299,6 +351,7 @@ class SpanImpl(Span[TSpanData]): "_span_data", "_tracing_api_key", "_trace_metadata", + "_processor_scope_token", ) def __init__( @@ -322,6 +375,7 @@ def __init__( self._span_data = span_data self._tracing_api_key = tracing_api_key self._trace_metadata = trace_metadata + self._processor_scope_token: object | None = None @property def trace_id(self) -> str: @@ -340,26 +394,56 @@ def parent_id(self) -> str | None: return self._parent_id def start(self, mark_as_current: bool = False): + self._start(util.time_iso(), mark_as_current) + + def start_at(self, started_at: str) -> None: + self._start(started_at, mark_as_current=False) + + def _start(self, started_at: str, mark_as_current: bool) -> None: if self.started_at is not None: logger.warning("Span already started") return - self._started_at = util.time_iso() + self._started_at = started_at self._processor.on_span_start(self) if mark_as_current: self._prev_span_token = Scope.set_current_span(self) + callback = getattr(self._processor, "on_span_scope_enter", None) + if callback is not None: + try: + self._processor_scope_token = callback(self) + except Exception: + logger.warning("Error in trace processor during scope entry") def finish(self, reset_current: bool = False) -> None: + self._finish(util.time_iso(), reset_current) + + def finish_at(self, ended_at: str) -> None: + self._finish(ended_at, reset_current=False) + + def _finish(self, ended_at: str, reset_current: bool) -> None: if self.ended_at is not None: logger.warning("Span already finished") return - self._ended_at = util.time_iso() + self._ended_at = ended_at self._processor.on_span_end(self) if reset_current and self._prev_span_token is not None: + self._exit_processor_scope() Scope.reset_current_span(self._prev_span_token) self._prev_span_token = None + def _exit_processor_scope(self) -> None: + token = self._processor_scope_token + self._processor_scope_token = None + if token is not None: + callback = getattr(self._processor, "on_span_scope_exit", None) + if callback is not None: + try: + callback(self, token) + except Exception: + logger.warning("Error in trace processor during scope exit") + def __enter__(self) -> Span[TSpanData]: self.start(mark_as_current=True) return self @@ -373,6 +457,9 @@ def __exit__(self, exc_type, exc_val, exc_tb): def set_error(self, error: SpanError) -> None: self._error = error + def clear_error(self) -> None: + self._error = None + @property def error(self) -> SpanError | None: return self._error @@ -418,6 +505,9 @@ def export(self) -> dict[str, Any] | None: metadata.update( {key: value for key, value in span_data_metadata.items() if key not in metadata} ) + operation = getattr(self.span_data, "operation", None) + if isinstance(operation, OperationMetadata) and operation.detail is not None: + metadata["operation"] = operation.export() if metadata: payload["metadata"] = metadata return payload diff --git a/src/agents/tracing/util.py b/src/agents/tracing/util.py index 7f436d0192..8b2a5269d5 100644 --- a/src/agents/tracing/util.py +++ b/src/agents/tracing/util.py @@ -1,6 +1,23 @@ +import re +from datetime import datetime + from .setup import get_trace_provider +def _parse_iso_timestamp(value: str) -> tuple[datetime, int]: + """Parse timezone-aware source time without losing its nanosecond fraction.""" + fraction = re.search( + r"^\d{4}-\d{2}-\d{2}.\d{2}:\d{2}:\d{2}\.(\d+)(?=Z$|[+-]\d{2}:\d{2}$|$)", value + ) + # Python 3.10 cannot parse arbitrary fractional precision; retain it separately. + whole_seconds = value[: fraction.start(1) - 1] + value[fraction.end(1) :] if fraction else value + parsed = datetime.fromisoformat(whole_seconds.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError("Source timestamp must include timezone.") + nanos = int(fraction.group(1).ljust(9, "0")[:9]) if fraction else parsed.microsecond * 1000 + return parsed.replace(microsecond=0), nanos + + def time_iso() -> str: """Return the current time in ISO 8601 format.""" return get_trace_provider().time_iso() diff --git a/src/agents/util/_error_tracing.py b/src/agents/util/_error_tracing.py index 230ef3acf2..71636256ee 100644 --- a/src/agents/util/_error_tracing.py +++ b/src/agents/util/_error_tracing.py @@ -7,6 +7,7 @@ from ..exceptions import ModelTimeoutError from ..logger import log_model_action_warning, logger from ..tracing import Span, SpanError, get_current_span +from ..tracing.config import get_operation_detail REDACTED_TRACE_ERROR_MESSAGE = "Error details are redacted." _MODEL_TIMEOUT_ERROR_ATTR = "_openai_agents_model_timeout_error" @@ -43,6 +44,12 @@ def record_current_task_model_timeout_on_span( return True +def include_error_text(include_sensitive: bool) -> bool: + # Detailed content covers submitted messages and results. An exception can + # contain transport headers reflected by the endpoint. + return include_sensitive and get_operation_detail() is None + + def get_trace_error( *, trace_include_sensitive_data: bool, @@ -50,7 +57,7 @@ def get_trace_error( redacted_message: str = REDACTED_TRACE_ERROR_MESSAGE, ) -> str: """Return a trace-safe error string based on the sensitive-data setting.""" - return error_message if trace_include_sensitive_data else redacted_message + return error_message if include_error_text(trace_include_sensitive_data) else redacted_message def attach_error_to_span(span: Span[Any], error: SpanError) -> None: @@ -74,7 +81,7 @@ def _model_error_text(error: Exception, *, trace_include_sensitive_data: bool) - provider exception with a side-effecting `__str__` is not invoked just to have its output thrown away by redaction. """ - if not trace_include_sensitive_data: + if not include_error_text(trace_include_sensitive_data): return REDACTED_TRACE_ERROR_MESSAGE try: return str(error) diff --git a/tests/models/test_any_llm_model.py b/tests/models/test_any_llm_model.py index e0c20d0b1e..7f4775f2ac 100644 --- a/tests/models/test_any_llm_model.py +++ b/tests/models/test_any_llm_model.py @@ -2376,14 +2376,16 @@ async def test_any_llm_responses_stream_populates_span_before_yielding_completed ) -> None: """The response span must carry the response and input when the completed event arrives.""" stream = _ClosableStream([_completed_event()]) - module, model = _responses_module_and_model_with_stream(monkeypatch, stream) - spans = _capture_spans(monkeypatch, module, "response_span") + from agents.tracing import get_current_span + + _module, model = _responses_module_and_model_with_stream(monkeypatch, stream) with trace(workflow_name="any-llm-responses-span"): stream_agen = cast(Any, _stream_events(model, ModelTracing.ENABLED)) async for event in stream_agen: if event.type == "response.completed": - [span] = spans + span = get_current_span() + assert span is not None assert span.span_data.response is not None assert span.span_data.response.id == "resp_123" assert span.span_data.input == "hi" diff --git a/tests/models/test_response_operation_tracing.py b/tests/models/test_response_operation_tracing.py new file mode 100644 index 0000000000..d1ca920fe6 --- /dev/null +++ b/tests/models/test_response_operation_tracing.py @@ -0,0 +1,472 @@ +from __future__ import annotations + +import asyncio +import json +from typing import Any, Literal + +import httpx2 +import pytest +from openai import AsyncOpenAI + +from agents import Agent, ModelSettings, RunConfig, Runner +from agents.models.openai_responses import OpenAIResponsesModel +from agents.retry import ModelRetrySettings +from agents.tracing.span_data import GenerationSpanData, ResponseSpanData +from tests.model_test_helpers import get_response_obj +from tests.test_responses import get_text_message +from tests.testing_processor import fetch_ordered_spans + + +def test_response_capture_stops_reading_output_at_the_budget() -> None: + from agents.models.interface import ModelTracing + from agents.models.openai_responses import _record_response_operation + from agents.tracing import generation_span + from agents.tracing._content import CONTENT_LIMIT + from agents.tracing.config import operation_tracing_scope + + # Count reads at the capture boundary independently of response parsing and logging. + class OutputItems(list[Any]): + inspected = 0 + + def __iter__(self): + for item in super().__iter__(): + self.inspected += 1 + yield item + + items = OutputItems([get_text_message("visible " + "x" * CONTENT_LIMIT)] * 100) + response = get_response_obj([]).model_copy(update={"output": items}) + with operation_tracing_scope({"operation_detail": "content"}, True): + span = generation_span(disabled=True) + _record_response_operation(span, response, "prompt", ModelTracing.ENABLED) + retained = json.dumps(span.span_data.output) + assert "visible" in retained and "truncated" in retained + assert len(retained.encode()) <= CONTENT_LIMIT + assert items.inspected < len(items) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize( + ("detail", "exhausted", "retry_owner"), + [ + (None, False, "runner"), + ("metadata", False, "runner"), + ("content", False, "runner"), + ("metadata", True, "runner"), + (None, False, "transport"), + ], +) +async def test_runner_retries_preserve_default_attempts_and_coalesce_detailed_operations( + stream: bool, + detail: Literal["metadata", "content"] | None, + exhausted: bool, + retry_owner: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + requests: list[dict[str, Any]] = [] + + # A wire double preserves provider errors, stream parsing, and actual Runner retry ownership. + async def handler(request: httpx2.Request) -> httpx2.Response: + requests.append(json.loads(request.content)) + if len(requests) == 1 or exhausted: + return httpx2.Response( + 503, json={"error": {"message": "retry", "type": "server_error"}} + ) + payload = get_response_obj([get_text_message("done")]).model_dump(mode="json") + if stream: + event = {"type": "response.completed", "response": payload, "sequence_number": 0} + return httpx2.Response( + 200, + content=f"event: response.completed\ndata: {json.dumps(event)}\n\n", + headers={"content-type": "text/event-stream"}, + ) + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test", + base_url="https://provider.example/v1", + max_retries=1 if retry_owner == "transport" else 0, + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ) as client: + monkeypatch.setattr(client, "_calculate_retry_timeout", lambda *args, **kwargs: 0) + agent = Agent( + name="retry", + model=OpenAIResponsesModel(model="fake", openai_client=client), + model_settings=ModelSettings( + retry=ModelRetrySettings( + max_retries=1, + backoff={"initial_delay": 0}, + policy=lambda _: True, + ) + if retry_owner == "runner" + else None + ), + ) + config = RunConfig(tracing={} if detail is None else {"operation_detail": detail}) + error: Exception | None = None + result = None + try: + if stream: + result = Runner.run_streamed(agent, "hello", run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "hello", run_config=config) + except Exception as exc: + error = exc + + assert len(requests) == 2, repr(error) + assert (error is not None) is exhausted + if not exhausted: + assert result is not None + assert result.final_output == "done" + spans = [ + span + for span in fetch_ordered_spans() + if isinstance(span.span_data, (GenerationSpanData, ResponseSpanData)) + ] + assert len(spans) == (2 if detail is None and retry_owner == "runner" else 1) + assert all(span.started_at is not None and span.ended_at is not None for span in spans) + assert (spans[-1].error is not None) is exhausted + assert spans[-1].span_data.operation.outcome == ("failed" if exhausted else "completed") + if detail is not None: + assert isinstance(spans[0].span_data, GenerationSpanData) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("transport", ["http", "websocket"]) +@pytest.mark.parametrize( + ("detail", "oversized"), [("content", False), ("content", True), ("metadata", False)] +) +async def test_content_uses_prepared_request_overrides( + transport: str, + detail: Literal["metadata", "content"], + oversized: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from unittest.mock import AsyncMock + + from agents.models.openai_responses import OpenAIResponsesWSModel + from tests.models.test_openai_responses import DummyWSConnection + + requests: list[dict[str, Any]] = [] + response = get_response_obj([get_text_message("done")]).model_dump(mode="json") + + # These transport doubles preserve final request assembly, including extra_body overrides. + async def handler(request: httpx2.Request) -> httpx2.Response: + requests.append(json.loads(request.content)) + return httpx2.Response(200, json=response) + + frame = {"type": "response.completed", "response": response, "sequence_number": 0} + connection = DummyWSConnection([json.dumps(frame)]) + submitted = [{"role": "user", "content": "☃" * 20000 if oversized else "submitted input"}] + async with AsyncOpenAI( + api_key="test", + base_url="https://provider.example/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ) as client: + model_class = OpenAIResponsesWSModel if transport == "websocket" else OpenAIResponsesModel + model = model_class(model="initial-model", openai_client=client) + if transport == "websocket": + monkeypatch.setattr( + model, "_open_websocket_connection", AsyncMock(return_value=connection) + ) + agent = Agent( + name="prepared", + instructions="initial instructions", + model=model, + model_settings=ModelSettings( + extra_headers={"Authorization": "transport-secret"}, + extra_body={ + "input": submitted, + "instructions": "submitted instructions", + "model": "submitted-model", + "previous_response_id": "previous-response", + "authorization": "body-secret", + }, + ), + ) + try: + result = await Runner.run( + agent, + "initial input", + run_config=RunConfig(tracing={"operation_detail": detail}), + ) + finally: + await model.close() + if transport == "websocket": + requests = connection.sent_messages + assert result.final_output == "done" + assert len(requests) == 1 + data = next( + span.span_data + for span in fetch_ordered_spans() + if isinstance(span.span_data, GenerationSpanData) + ) + assert requests[0]["input"] == submitted + if detail == "metadata": + assert data.input is None + assert data.output is None + assert data.model_config is None + elif oversized: + captured = json.dumps( + {"input": data.input, **(data.model_config or {})}, ensure_ascii=False + ).encode("utf-8") + assert len(captured) <= 32 * 1024 + assert b"truncated" in captured + else: + assert data.input == submitted + assert data.model_config == {"instructions": requests[0]["instructions"]} + assert data.model == "submitted-model" + assert data.operation.previous_response_id == ( + "previous-response" if detail == "content" else None + ) + assert "transport-secret" not in repr(data.export()) + assert "body-secret" not in repr(data.export()) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +async def test_cancel_during_retry_backoff_finishes_logical_model_span( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from agents.run_internal import model_retry + + in_backoff = asyncio.Event() + release = asyncio.Event() + + async def backoff(_delay: float) -> None: + in_backoff.set() + await release.wait() + + async def handler(_request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(503, json={"error": {"message": "retry", "type": "server_error"}}) + + monkeypatch.setattr(model_retry, "_sleep_for_retry", backoff) + async with AsyncOpenAI( + api_key="test", + max_retries=0, + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ) as client: + agent = Agent( + name="cancel retry", + model=OpenAIResponsesModel(model="fake", openai_client=client), + model_settings=ModelSettings( + retry=ModelRetrySettings(max_retries=1, policy=lambda _: True) + ), + ) + task = asyncio.create_task( + Runner.run( + agent, "hello", run_config=RunConfig(tracing={"operation_detail": "metadata"}) + ) + ) + try: + await asyncio.wait_for(in_backoff.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + finally: + release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + spans = [ + span for span in fetch_ordered_spans() if isinstance(span.span_data, GenerationSpanData) + ] + assert len(spans) == 1 + assert spans[0].ended_at is not None + assert spans[0].span_data.operation.outcome == "interrupted" + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("terminal", ["failed", "incomplete"]) +@pytest.mark.parametrize( + ("detail", "sensitive", "official"), + [ + (None, True, False), + ("content", True, False), + ("content", False, False), + ("metadata", False, True), + ], +) +async def test_failed_terminal_records_outcome_before_exposure_and_preserves_source_end( + terminal: str, + detail: Literal["metadata", "content"] | None, + sensitive: bool, + official: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from agents import ModelTracing, trace + from agents.models import openai_responses + from agents.tracing.config import operation_tracing_scope + from agents.tracing.scope import Scope + from agents.usage import Usage + + payload = get_response_obj( + [get_text_message("partial")], + response_id="terminal-response", + usage=Usage(requests=1, input_tokens=7, output_tokens=2, total_tokens=9), + ).model_dump(mode="json") + payload["status"] = terminal + if terminal == "incomplete": + payload["incomplete_details"] = {"reason": "max_output_tokens"} + else: + payload["error"] = {"code": "server_error", "message": "synthetic failure"} + event = {"type": f"response.{terminal}", "response": payload, "sequence_number": 0} + source_ends: list[str] = [] + original_clock = openai_responses.time_iso + + def terminal_clock() -> str: + source_ends.append(original_clock()) + return source_ends[-1] + + monkeypatch.setattr(openai_responses, "time_iso", terminal_clock) + async with AsyncOpenAI( + api_key="test", + base_url="https://api.openai.com/v1" if official else "https://provider.example/v1", + http_client=httpx2.AsyncClient( + transport=httpx2.MockTransport( + lambda _: httpx2.Response( + 200, + content=f"event: response.{terminal}\ndata: {json.dumps(event)}\n\n", + headers={"content-type": "text/event-stream"}, + ) + ) + ), + ) as client: + model = OpenAIResponsesModel(model="requested-model", openai_client=client) + with ( + trace("terminal"), + operation_tracing_scope( + {} if detail is None else {"operation_detail": detail}, sensitive + ), + ): + stream = model.stream_response( + system_instructions=None, + input="caller input", + model_settings=ModelSettings(), + tools=[], + output_schema=None, + handoffs=[], + tracing=ModelTracing.ENABLED if sensitive else ModelTracing.ENABLED_WITHOUT_DATA, + ) + try: + chunk = await stream.__anext__() + assert chunk.type == f"response.{terminal}" + live = Scope.get_current_span() + assert live is not None + assert live.span_data.operation.outcome == "failed" + assert live.span_data.operation.response_model == payload["model"] + assert live.span_data.usage["input_tokens"] == 7 + assert live.span_data.operation.response_id == ( + "terminal-response" if sensitive or official else None + ) + if isinstance(live.span_data, ResponseSpanData): + assert live.span_data.input is None + assert live.span_data.response is None + assert live.span_data.export()["response_id"] is None + elif not sensitive: + assert live.span_data.input is None + assert live.span_data.output is None + finally: + await stream.aclose() + spans = [ + span + for span in fetch_ordered_spans() + if isinstance(span.span_data, (GenerationSpanData, ResponseSpanData)) + ] + assert len(spans) == 1 + assert spans[0].span_data.operation.outcome == "failed" + assert spans[0].error is not None + assert spans[0].ended_at == source_ends[0] + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("transport", ["http", "websocket"]) +@pytest.mark.parametrize("terminal", ["failed", "incomplete"]) +@pytest.mark.parametrize( + ("detail", "sensitive", "official"), + [ + (None, True, True), + ("metadata", True, True), + ("content", True, False), + ("content", False, False), + ], +) +async def test_nonstream_terminal_retains_permitted_metadata_and_partial_output( + transport: str, + terminal: str, + detail: Literal["metadata", "content"] | None, + sensitive: bool, + official: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from unittest.mock import AsyncMock + + from agents import ModelBehaviorError + from agents.models.openai_responses import OpenAIResponsesWSModel + from agents.usage import Usage + from tests.models.test_openai_responses import DummyWSConnection + + response = get_response_obj( + [get_text_message("visible partial answer")], + response_id="terminal-response", + usage=Usage(requests=1, input_tokens=7, output_tokens=2, total_tokens=9), + ).model_dump(mode="json") + response["status"] = terminal + if terminal == "incomplete": + response["incomplete_details"] = {"reason": "max_output_tokens"} + else: + response["error"] = {"code": "server_error", "message": "synthetic failure"} + frame = {"type": f"response.{terminal}", "response": response, "sequence_number": 0} + connection = DummyWSConnection([json.dumps(frame)]) + async with AsyncOpenAI( + api_key="test", + base_url="https://api.openai.com/v1" if official else "https://provider.example/v1", + max_retries=0, + http_client=httpx2.AsyncClient( + transport=httpx2.MockTransport(lambda _: httpx2.Response(200, json=response)) + ), + ) as client: + model_class = OpenAIResponsesWSModel if transport == "websocket" else OpenAIResponsesModel + model = model_class(model="requested-model", openai_client=client) + if transport == "websocket": + monkeypatch.setattr( + model, "_open_websocket_connection", AsyncMock(return_value=connection) + ) + try: + with pytest.raises(ModelBehaviorError, match=f"response.{terminal}"): + await Runner.run( + Agent(name="failed response", model=model), + "caller input", + run_config=RunConfig( + tracing={} if detail is None else {"operation_detail": detail}, + trace_include_sensitive_data=sensitive, + ), + ) + finally: + await model.close() + span = next( + span + for span in fetch_ordered_spans() + if isinstance(span.span_data, (ResponseSpanData, GenerationSpanData)) + ) + data = span.span_data + assert span.error is not None + assert data.operation.outcome == "failed" + assert data.operation.response_model == response["model"] + assert data.usage["input_tokens"] == 7 + assert data.usage["output_tokens"] == 2 + if isinstance(data, ResponseSpanData): + assert data.response is None + assert data.input is None + assert data.export()["response_id"] is None + else: + assert data.operation.response_id == ( + "terminal-response" if sensitive or official else None + ) + assert data.output == (response["output"] if detail == "content" and sensitive else None) diff --git a/tests/test_local_shell_tool.py b/tests/test_local_shell_tool.py index ca385ace31..586cea0cd9 100644 --- a/tests/test_local_shell_tool.py +++ b/tests/test_local_shell_tool.py @@ -32,6 +32,7 @@ from tests.model_test_helpers import get_response_obj from .test_responses import get_text_message +from .testing_processor import fetch_ordered_spans class RecordingLocalShellExecutor: @@ -186,6 +187,10 @@ async def test_runner_executes_local_shell_calls() -> None: result = await Runner.run(agent, input="please run shell") + (span,) = [s for s in fetch_ordered_spans() if s.span_data.type == "function"] + assert span.span_data.name == tool.name + assert span.span_data.operation.tool_call_id == "call_local_shell" + assert span.span_data.operation.outcome == "completed" assert len(executor.calls) == 1 request = executor.calls[0] assert isinstance(request, LocalShellCommandRequest) diff --git a/tests/tracing/test_content_capture.py b/tests/tracing/test_content_capture.py new file mode 100644 index 0000000000..d99d6a5ecc --- /dev/null +++ b/tests/tracing/test_content_capture.py @@ -0,0 +1,617 @@ +from __future__ import annotations + +import json +from collections.abc import Iterator, Mapping +from typing import Any + +import httpx2 +import pytest +from openai import AsyncOpenAI, BadRequestError +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 agents import Agent, RunConfig, Runner +from agents.extensions.tracing import OpenTelemetryTracingProcessor +from agents.models.openai_responses import OpenAIResponsesModel +from agents.tracing import ( + add_trace_processor, + function_span, + generation_span, + set_trace_processors, + trace, +) +from agents.tracing._content import CONTENT_LIMIT, bound_content +from agents.tracing.config import OperationDetail, operation_tracing_scope +from agents.tracing.span_data import GenerationSpanData +from tests.testing_processor import SPAN_PROCESSOR_TESTING, SpanProcessorForTests + + +@pytest.fixture +def exporter() -> Iterator[InMemorySpanExporter]: + provider = TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + set_trace_processors([processor]) + try: + yield exporter + finally: + processor.shutdown() + set_trace_processors([SPAN_PROCESSOR_TESTING]) + provider.shutdown() + + +def test_public_tool_export_redacts_embedded_credentials_and_binary(exporter) -> None: + arguments = { + "request": json.dumps( + { + "apiKey": "CREDENTIAL_CANARY", + "query": "visible query", + "media": json.dumps({"uri": "data:image/png;base64,NESTED_CANARY"}), + } + ), + "file": {"type": "input_file", "file_data": "FILE_CANARY"}, + } + result = json.dumps( + [ + {"type": "image", "data": "IMAGE_CANARY", "mimeType": "image/png"}, + {"type": "resource", "resource": {"blob": "BLOB_CANARY"}}, + {"type": "resource", "resource": {"text": "visible resource"}}, + {"type": "text", "text": "visible result"}, + ] + ) + with trace("content"), function_span("lookup", input=json.dumps(arguments)) as tool: + tool.span_data.operation.detail = "content" + tool.span_data.output = result + attributes = dict(exporter.get_finished_spans()[0].attributes) + serialized = json.dumps(attributes) + assert "CANARY" not in serialized + assert "visible query" in serialized + assert "visible resource" in serialized + assert "visible result" in serialized + assert "omitted" in serialized + # Function data remains a string; the exporter preserves embedded JSON validity. + assert isinstance(tool.span_data.input, str) + assert isinstance(json.loads(attributes["gen_ai.tool.call.result"]), list) + + +def test_public_model_export_omits_hidden_reasoning_and_embedded_media(exporter) -> None: + incomplete_header = "data:" * 6_000 + with trace("content"), generation_span(model="test-model") as model: + model.span_data.operation.detail = "content" + model.span_data.input = [ + { + "role": "user", + "content": ( + f"{incomplete_header} visible before data:image/png;base64,BINARY_CANARY" + " visible after" + ), + } + ] + model.span_data.output = [ + { + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": json.dumps( + {"Authorization": "AUTH_CANARY", "answer": "visible answer"} + ), + }, + {"type": "reasoning", "text": "REASONING_CANARY"}, + ], + } + ] + serialized = json.dumps(dict(exporter.get_finished_spans()[0].attributes)) + assert "CANARY" not in serialized + assert incomplete_header in serialized + assert "visible before" in serialized + assert "visible after" in serialized + assert "visible answer" in serialized + assert "omitted" in serialized + + +@pytest.mark.parametrize( + "message", + [ + {"content": [{"type": "refusal", "refusal": "Visible refusal."}]}, + {"content": None, "refusal": "Visible refusal."}, + ], + ids=["responses", "chat-completions"], +) +def test_public_model_export_preserves_visible_refusal_text(exporter, message) -> None: + with trace("refusal"), generation_span(model="test-model") as model: + model.span_data.operation.detail = "content" + model.span_data.output = [{"role": "assistant", **message}] + attributes = exporter.get_finished_spans()[0].attributes + messages = json.loads(json.dumps(attributes["gen_ai.output.messages"])) + assert messages == [ + {"role": "assistant", "parts": [{"type": "text", "content": "Visible refusal."}]} + ] + + +def test_public_tool_export_omits_oversized_structured_result_with_bounded_json(exporter) -> None: + with trace("content"), function_span("read_file") as tool: + tool.span_data.operation.detail = "content" + tool.span_data.output = json.dumps({"text": "file prefix: " + "é🙂" * 40_000}) + captured = exporter.get_finished_spans()[0].attributes["gen_ai.tool.call.result"] + assert len(json.dumps(captured, ensure_ascii=False).encode("utf-8")) <= CONTENT_LIMIT + decoded = json.loads(captured) + assert decoded == {"omitted": True, "truncated": True, "reason": "capture_budget"} + + +@pytest.mark.parametrize( + "value", + [ + "é🙂" * 40_000, + " " * (CONTENT_LIMIT * 8) + "ordinary text", + [{"text": "x" * 180}] * 3_000, + {"input": [{"role": "user", "content": "x" * 80_000}], "instructions": "later"}, + ], +) +def test_projection_keeps_valid_structure_and_inline_budget_marker(value) -> None: + captured = bound_content(value) + serialized = json.dumps(captured, ensure_ascii=False) + assert len(serialized.encode("utf-8")) <= CONTENT_LIMIT + assert "truncated" in serialized + assert json.loads(serialized) == captured + if isinstance(value, str): + assert captured.endswith("[truncated]") + + +@pytest.mark.parametrize( + "raw", + [ + json.dumps({"accessToken": "TOKEN_CANARY", "result": "prefix " + "🙂" * 40_000}), + "[" + ",".join(['{"apiKey":"TOKEN_CANARY"}'] * 60_000) + "]", + json.dumps({"text": "🙂" * 10_000}, ensure_ascii=False), + " " * (CONTENT_LIMIT * 8) + '{"apiKey":"TOKEN_CANARY"}', + ], + ids=["object", "array", "utf8-byte-limit", "whitespace-prefix"], +) +def test_oversized_embedded_tool_json_is_omitted_without_parsing( + raw: str, monkeypatch: pytest.MonkeyPatch +) -> None: + original_loads = json.loads + monkeypatch.setattr( + "agents.tracing._content.json.loads", + lambda _: pytest.fail("Oversized structured content must not be parsed."), + ) + captured = bound_content(raw) + assert isinstance(captured, str) + assert original_loads(captured) == { + "omitted": True, + "truncated": True, + "reason": "capture_budget", + } + assert len(json.dumps(captured, ensure_ascii=False).encode("utf-8")) <= CONTENT_LIMIT + + +def test_embedded_json_that_fits_the_budget_remains_intact() -> None: + raw = json.dumps({"text": "x" * 27_000}) + assert bound_content(raw) == raw + + +def test_oversized_content_preserves_message_role_and_part_identity() -> None: + captured = bound_content( + [{"content": [{"text": "prefix " + "x" * 80_000, "type": "input_text"}], "role": "user"}] + ) + assert captured[0]["role"] == "user" + assert captured[0]["content"][0]["type"] == "input_text" + assert captured[0]["content"][0]["text"].startswith("prefix ") + assert captured[0]["content"][0]["text"].endswith("[truncated]") + + +def test_tool_capture_limits_mapping_traversal_and_prioritizes_identity(exporter) -> None: + class CountedMapping(Mapping[str, Any]): + # The traversal guard distinguishes bounded capture from eager enumeration without timing. + def __init__(self, values: dict[str, Any]) -> None: + self.values = values + self.reads = 0 + + def __len__(self) -> int: + return len(self.values) + + def __getitem__(self, key: str) -> Any: + return self.values[key] + + def __iter__(self) -> Iterator[str]: + for key in self.values: + self.reads += 1 + # Sixteen 5 KiB values cannot fit in a 32 KiB capture. + if self.reads > 16: + raise AssertionError("Capture traversed fields beyond its byte budget.") + yield key + + payload = CountedMapping( + { + "Authorization": "CREDENTIAL_CANARY", + "media": {"type": "input_image", "image_url": "MEDIA_CANARY"}, + **{f"field_{index}": "visible " + "x" * 5_000 for index in range(1_000)}, + "type": "message", + "role": "tool", + "id": "late-id", + "call_id": "late-call", + "name": "late-name", + } + ) + native = SpanProcessorForTests() + add_trace_processor(native) + with trace("bounded"), function_span("lookup") as span: + span.span_data.operation.detail = "content" + span.span_data.output = payload + captured = next( + item.span_data.output + for item in native.get_ordered_spans() + if item.span_data.type == "function" + ) + assert isinstance(captured, dict) + assert {key: captured[key] for key in ("type", "role", "id", "call_id", "name")} == { + "type": "message", + "role": "tool", + "id": "late-id", + "call_id": "late-call", + "name": "late-name", + } + encoded = json.dumps(captured, ensure_ascii=False) + assert len(encoded.encode()) <= CONTENT_LIMIT + assert "CANARY" not in encoded + assert "visible" in encoded and "truncated" in encoded + assert payload.reads <= 16 + + +def test_capture_rejects_oversized_mapping_key_before_encoding(monkeypatch) -> None: + original_dumps = json.dumps + + def bounded_dumps(value: Any, *args: Any, **kwargs: Any) -> str: + if isinstance(value, str) and len(value) > CONTENT_LIMIT: + pytest.fail("Capture encoded a key that cannot fit its byte budget.") + return original_dumps(value, *args, **kwargs) + + monkeypatch.setattr("agents.tracing._content.json.dumps", bounded_dumps) + captured = bound_content({"k" * (CONTENT_LIMIT * 2): "discarded", "id": "late-id"}) + assert captured == {"id": "late-id", "truncated": True} + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +async def test_provider_error_cannot_export_a_reflected_transport_credential( + exporter, stream +) -> None: + native = SpanProcessorForTests() + add_trace_processor(native) + authorization_headers: list[str] = [] + + # An actual provider request can receive an error message echoing its auth header. + # The wire double preserves the SDK's exception conversion and both Runner paths. + async def handler(request: httpx2.Request) -> httpx2.Response: + authorization = request.headers["authorization"] + authorization_headers.append(authorization) + return httpx2.Response( + 400, + json={"error": {"message": json.dumps({"headers": {"Authorization": authorization}})}}, + ) + + async with AsyncOpenAI( + api_key="TRANSPORT_CREDENTIAL_CANARY", + base_url="https://provider.example/v1", + max_retries=0, + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ) as client: + agent = Agent( + name="worker", model=OpenAIResponsesModel(model="fixture", openai_client=client) + ) + config = RunConfig(tracing={"operation_detail": "content"}) + with pytest.raises(BadRequestError): + if stream: + result = Runner.run_streamed(agent, "hello", run_config=config) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "hello", run_config=config) + + assert authorization_headers == ["Bearer TRANSPORT_CREDENTIAL_CANARY"] + spans = native.get_ordered_spans() + model_spans = [span for span in spans if span.span_data.type == "generation"] + assert len(model_spans) == 1 + assert model_spans[0].error is not None + assert model_spans[0].span_data.operation.outcome == "failed" + # Check every native span, including agent/task/turn error fields and hosted exports. + assert "TRANSPORT_CREDENTIAL_CANARY" not in json.dumps([span.export() for span in spans]) + for span in exporter.get_finished_spans(): + assert "TRANSPORT_CREDENTIAL_CANARY" not in str( + (dict(span.attributes), span.events, span.status.description) + ) + + +@pytest.mark.parametrize("detail", [None, "metadata", "content"]) +@pytest.mark.parametrize("assign", [False, True], ids=["constructor", "assignment"]) +def test_generation_payload_capture_policy(detail: OperationDetail | None, assign: bool) -> None: + messages = [{"role": "user", "content": "visible prompt " + "é🙂" * 40_000}] + output = [ + { + "role": "assistant", + "reasoning_content": "HIDDEN_CANARY", + "content": "visible answer " + "é🙂" * 40_000, + } + ] + config = { + "instructions": "visible instructions " + "é🙂" * 40_000, + "metadata": {"Authorization": "AUTH_CANARY"}, + } + tools = [ + { + "type": "function", + "function": {"name": "lookup", "description": "visible tool " + "é🙂" * 40_000}, + } + ] + usage = {"input_tokens": 10, "output_tokens": 5} + policy = {"operation_detail": detail} if detail is not None else None + with operation_tracing_scope(policy, include_sensitive=True): + if assign: + data = GenerationSpanData(model="fixture", usage=usage) + data.input, data.output, data.model_config, data.tools = messages, output, config, tools + else: + data = GenerationSpanData(messages, output, "fixture", config, usage, tools) + captured = (data.input, data.output, data.model_config, data.tools) + assert all( + value is repeated + for value, repeated in zip( + captured, (data.input, data.output, data.model_config, data.tools), strict=True + ) + ) + originals = (messages, output, config, tools) + assert data.model == "fixture" and data.usage is usage + if detail is None: + assert all(value is original for value, original in zip(captured, originals, strict=True)) + elif detail == "metadata": + assert captured == (None, None, None, None) + assert "CANARY" not in json.dumps(data.export()) + else: + assert ( + len( + json.dumps( + {"input": data.input, "model_config": data.model_config, "tools": data.tools}, + ensure_ascii=False, + ).encode() + ) + <= CONTENT_LIMIT + ) + assert len(json.dumps(data.output, ensure_ascii=False).encode()) <= CONTENT_LIMIT + exported = json.dumps(data.export(), ensure_ascii=False) + assert "CANARY" not in exported + assert "visible prompt" in exported and "visible answer" in exported + assert "truncated" in exported + assert data.model_config is None and data.tools is None + + +def test_generation_payload_assignments_honor_content_veto() -> None: + with operation_tracing_scope({"operation_detail": "content"}, include_sensitive=False): + data = GenerationSpanData() + data.input = [{"role": "user", "content": "INPUT_CANARY"}] + data.output = [{"role": "assistant", "content": "OUTPUT_CANARY"}] + data.model_config = {"instructions": "INSTRUCTIONS_CANARY"} + data.tools = [{"description": "TOOL_CANARY"}] + assert (data.input, data.output, data.model_config, data.tools) == (None, None, None, None) + assert "CANARY" not in json.dumps(data.export()) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("mode", ["default", "content", "veto"]) +async def test_chat_input_capture_shares_one_budget_without_changing_the_request( + exporter, stream: bool, mode: str +) -> None: + from agents import OpenAIChatCompletionsModel + from agents.decorators import tool + from tests.models.test_openai_chatcompletions import _minimal_chat_completion + + native = SpanProcessorForTests() + add_trace_processor(native) + + @tool + def lookup() -> str: + """Return a value.""" + return "ok" + + lookup.description = "tool-description " + "t" * 40_000 + prompt = "user-message " + "i" * 40_000 + requests = [] + + async def handler(request: httpx2.Request) -> httpx2.Response: + requests.append(json.loads(request.content)) + payload = _minimal_chat_completion("done").model_dump(mode="json") + if stream: + payload.update( + object="chat.completion.chunk", + choices=[ + { + "index": 0, + "delta": payload["choices"][0]["message"], + "finish_reason": "stop", + } + ], + ) + return httpx2.Response( + 200, + content=f"data: {json.dumps(payload)}\n\ndata: [DONE]\n\n", + headers={"content-type": "text/event-stream"}, + ) + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test", + base_url="https://provider.example/v1", + max_retries=0, + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ) as client: + agent = Agent( + name="worker", model=OpenAIChatCompletionsModel("fixture", client), tools=[lookup] + ) + config = RunConfig( + tracing={} if mode == "default" else {"operation_detail": "content"}, + trace_include_sensitive_data=mode != "veto", + ) + if stream: + result = Runner.run_streamed(agent, prompt, run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, prompt, run_config=config) + assert result.final_output == "done" + assert requests[0]["messages"][-1]["content"] == prompt + assert requests[0]["tools"][0]["function"]["description"] == lookup.description + data = next( + span.span_data for span in native.get_ordered_spans() if span.span_data.type == "generation" + ) + attributes = dict( + next( + span + for span in exporter.get_finished_spans() + if span.attributes.get("gen_ai.operation.name") == "chat" + ).attributes + ) + captured = {"input": data.input, "model_config": data.model_config, "tools": data.tools} + exported = { + key: value + for key, value in attributes.items() + if key in {"gen_ai.input.messages", "gen_ai.system_instructions", "gen_ai.tool.definitions"} + } + if mode == "default": + assert data.input[-1]["content"] == prompt + assert data.tools[0]["function"]["description"] == lookup.description + assert exported == {} + elif mode == "veto": + assert all(value is None for value in captured.values()) + assert exported == {} + else: + assert len(json.dumps(captured, ensure_ascii=False).encode()) <= CONTENT_LIMIT + assert len(json.dumps(exported, ensure_ascii=False).encode()) <= CONTENT_LIMIT + assert "user-message" in json.dumps(captured) + assert "truncated" in json.dumps(captured) + assert data.tools is None + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("mode", ["default", "content", "metadata", "veto"]) +async def test_any_llm_responses_capture_bounds_sdk_and_otel_without_changing_provider_data( + exporter, monkeypatch, stream: bool, mode: str +) -> None: + pytest.importorskip("any_llm") + from any_llm.providers.openai import base as any_llm_openai + + from agents import ModelSettings + from agents.extensions.models.any_llm_model import AnyLLMModel + from agents.tracing.span_data import ResponseSpanData + from tests.models.test_any_llm_model import _response, _responses_output + + native = SpanProcessorForTests() + add_trace_processor(native) + input_secret, output_secret = "INPUT_CREDENTIAL_CANARY", "OUTPUT_CREDENTIAL_CANARY" + prompt = "UNSENT_INPUT_CANARY" + wire_input = [ + {"role": "user", "content": json.dumps({"api_key": input_secret, "query": "input-visible"})} + ] + wire_instructions = "wire-instructions-visible " + "i" * 40_000 + long_output = "answer-visible " + "o" * 40_000 + response = _response(json.dumps({"password": output_secret, "result": "output-visible"})) + content = response.output[0].content + assert content is not None + content.extend(_responses_output(long_output)[0].content) + payload = response.model_dump(mode="json") + requests = [] + + async def handler(request: httpx2.Request) -> httpx2.Response: + requests.append(json.loads(request.content)) + if stream: + event = {"type": "response.completed", "response": payload, "sequence_number": 0} + return httpx2.Response( + 200, + content=f"event: response.completed\ndata: {json.dumps(event)}\n\n", + headers={"content-type": "text/event-stream"}, + ) + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test", + base_url="https://provider.example/v1", + max_retries=0, + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler), trust_env=False), + ) as client: + # Keep the real AnyLLM provider and replace only its HTTP client. + monkeypatch.setattr(any_llm_openai, "AsyncOpenAI", lambda **kwargs: client) + agent = Agent( + name="worker", + model=AnyLLMModel("openai/fixture", api="responses", api_key="test"), + instructions="UNSENT_INSTRUCTIONS_CANARY", + model_settings=ModelSettings( + extra_body={"input": wire_input, "instructions": wire_instructions} + ), + ) + config = RunConfig( + tracing={} + if mode == "default" + else {"operation_detail": "metadata" if mode == "metadata" else "content"}, + trace_include_sensitive_data=mode != "veto", + ) + if stream: + result = Runner.run_streamed(agent, prompt, run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, prompt, run_config=config) + assert len(requests) == 1 + assert requests[0]["input"] == wire_input + assert requests[0]["instructions"] == wire_instructions + assert long_output in result.final_output and output_secret in result.final_output + data = next( + span.span_data + for span in native.get_ordered_spans() + if span.span_data.type in {"response", "generation"} + ) + if isinstance(data, ResponseSpanData): + captured_input = data.input + captured_output = ( + [item.model_dump(mode="json") for item in data.response.output] + if data.response + else None + ) + else: + captured_input = {"input": data.input, "model_config": data.model_config} + captured_output = data.output + attributes = dict( + next( + span + for span in exporter.get_finished_spans() + if span.attributes.get("gen_ai.operation.name") == "chat" + ).attributes + ) + exported_input = { + key: attributes[key] + for key in ("gen_ai.input.messages", "gen_ai.system_instructions") + if key in attributes + } + exported_output = attributes.get("gen_ai.output.messages") + if mode == "default": + assert isinstance(data, ResponseSpanData) + assert data.input == [{"role": "user", "content": prompt}] + assert long_output in json.dumps(captured_output) + assert not exported_input and exported_output is None + elif mode in {"metadata", "veto"}: + assert data.input is None and captured_output is None + assert not exported_input and exported_output is None + else: + for value in (captured_input, captured_output, exported_input, exported_output): + encoded = json.dumps(value, ensure_ascii=False) + assert len(encoded.encode()) <= CONTENT_LIMIT + assert input_secret not in encoded and output_secret not in encoded + assert "UNSENT_" not in encoded and "truncated" in encoded + for value in (captured_input, exported_input): + assert "input-visible" in json.dumps(value) + assert "wire-instructions-visible" in json.dumps(value) + assert "output-visible" in json.dumps(captured_output) diff --git a/tests/tracing/test_local_shell_operation_tracing.py b/tests/tracing/test_local_shell_operation_tracing.py new file mode 100644 index 0000000000..7796634373 --- /dev/null +++ b/tests/tracing/test_local_shell_operation_tracing.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest +from openai.types.responses.response_output_item import LocalShellCall, LocalShellCallAction +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 agents import ( + Agent, + LocalShellTool, + RunConfig, + RunHooks, + Runner, + ToolExecutionConfig, + UserError, +) +from agents.extensions.tracing import OpenTelemetryTracingProcessor +from agents.testing import ScriptedModel, assistant_message +from agents.tracing import custom_span, get_current_span, set_trace_processors +from tests.model_test_helpers import get_exact_output_stream_step +from tests.testing_processor import SPAN_PROCESSOR_TESTING, fetch_ordered_spans + + +def _agent(live: list[Any], streamed: bool = False) -> tuple[Agent[Any], ScriptedModel]: + def execute(request: Any) -> str: + live.append(get_current_span()) + return "executor-only" + + call = LocalShellCall( + id="local-shell", + call_id="shell-call", + status="completed", + type="local_shell_call", + action=LocalShellCallAction(command=["echo", "hello"], env={}, type="exec"), + ) + model = ScriptedModel( + [get_exact_output_stream_step([call]) if streamed else [call], [assistant_message("done")]] + ) + return Agent(name="shell", model=model, tools=[LocalShellTool(executor=execute)]), model + + +async def _run(agent: Agent[Any], config: RunConfig, hooks: RunHooks[Any], streamed: bool) -> Any: + if streamed: + result = Runner.run_streamed(agent, "run", run_config=config, hooks=hooks) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, "run", run_config=config, hooks=hooks) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_local_shell_finalization_keeps_live_parent_and_captures_effective_output( + streamed: bool, +) -> None: + provider = TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + tracer = provider.get_tracer(__name__) + set_trace_processors([SPAN_PROCESSOR_TESTING, processor]) + live: list[Any] = [] + observations = [] + agent, model = _agent(live, streamed) + + async def prepare(context: Any, output: Any) -> str: + current = get_current_span() + assert current + observations.append((current.span_id, current.ended_at)) + with custom_span("prepare"): + with tracer.start_as_current_span("prepare-io"): + return "published" + + class Hooks(RunHooks[Any]): + async def on_tool_end(self, context: Any, agent: Any, tool: Any, result: Any) -> None: + current = get_current_span() + assert current + observations.append((current.span_id, current.ended_at)) + assert result == "published" + + try: + result = await _run( + agent, + RunConfig( + tracing={"operation_detail": "content"}, + tool_execution=ToolExecutionConfig(prepare_tool_output=prepare), + ), + Hooks(), + streamed, + ) + assert result.final_output == "done" + (span,) = live + assert observations == [(span.span_id, None), (span.span_id, None)] + assert span.span_data.output == "published" + assert span.span_data.operation.outcome == "completed" + assert any( + item.get("output") == "published" + for item in model.calls[1].input + if isinstance(item, dict) + ) + (child,) = [ + s for s in fetch_ordered_spans() if getattr(s.span_data, "name", None) == "prepare" + ] + assert child.parent_id == span.span_id + exported = exporter.get_finished_spans() + (execution,) = [s for s in exported if s.name == "execute_tool local_shell"] + (prepare_span,) = [s for s in exported if s.name == "prepare"] + (io,) = [s for s in exported if s.name == "prepare-io"] + assert execution.context and prepare_span.parent and prepare_span.context and io.parent + assert prepare_span.parent.span_id == execution.context.span_id + assert io.parent.span_id == prepare_span.context.span_id + finally: + set_trace_processors([SPAN_PROCESSOR_TESTING]) + processor.shutdown() + provider.shutdown() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["prepare", "end"]) +async def test_local_shell_finalization_failure_marks_operation_failed(failure: str) -> None: + live: list[Any] = [] + agent, model = _agent(live) + + async def prepare(context: Any, output: Any) -> str: + if failure == "prepare": + raise UserError("prepare failed") + return "published" + + class Hooks(RunHooks[Any]): + async def on_tool_end(self, context: Any, agent: Any, tool: Any, result: Any) -> None: + raise UserError("end failed") + + with pytest.raises(UserError): + await _run( + agent, + RunConfig( + tracing={"operation_detail": "content"}, + tool_execution=ToolExecutionConfig(prepare_tool_output=prepare), + ), + Hooks(), + False, + ) + (span,) = live + assert span.span_data.operation.outcome == "failed" + assert span.error and span.ended_at + assert span.span_data.output == ("published" if failure == "end" else None) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("phase", ["prepare", "end"]) +async def test_local_shell_finalization_cancellation_marks_operation_interrupted( + phase: str, +) -> None: + live: list[Any] = [] + agent, model = _agent(live) + entered, release, stopped = asyncio.Event(), asyncio.Event(), asyncio.Event() + + async def wait_for_cancellation() -> None: + entered.set() + try: + await release.wait() + finally: + stopped.set() + + async def prepare(context: Any, output: Any) -> str: + if phase == "prepare": + await wait_for_cancellation() + return "published" + + class Hooks(RunHooks[Any]): + async def on_tool_end(self, context: Any, agent: Any, tool: Any, result: Any) -> None: + if phase == "end": + await wait_for_cancellation() + + task = asyncio.create_task( + _run( + agent, + RunConfig( + tracing={"operation_detail": "content"}, + tool_execution=ToolExecutionConfig(prepare_tool_output=prepare), + ), + Hooks(), + False, + ) + ) + try: + await asyncio.wait_for(entered.wait(), 5) + (span,) = live + assert span.ended_at is None + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.wait_for(stopped.wait(), 5) + assert span.span_data.operation.outcome == "interrupted" + assert span.ended_at + assert span.span_data.output == ("published" if phase == "end" else None) + assert len(model.calls) == 1 + finally: + release.set() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["default", "metadata", "content", "veto"]) +async def test_local_shell_effective_output_respects_capture_policy(mode: str) -> None: + live: list[Any] = [] + agent, _ = _agent(live) + + async def prepare(context: Any, output: Any) -> str: + return "published" + + config = RunConfig( + tracing={} + if mode == "default" + else {"operation_detail": "metadata" if mode == "metadata" else "content"}, + trace_include_sensitive_data=mode != "veto", + tool_execution=ToolExecutionConfig(prepare_tool_output=prepare), + ) + result = await _run(agent, config, RunHooks(), False) + assert result.final_output == "done" + (span,) = live + assert span.span_data.output == ("published" if mode == "content" else None) diff --git a/tests/tracing/test_opentelemetry.py b/tests/tracing/test_opentelemetry.py new file mode 100644 index 0000000000..1c65745494 --- /dev/null +++ b/tests/tracing/test_opentelemetry.py @@ -0,0 +1,502 @@ +from __future__ import annotations + +import asyncio +import json +import subprocess +import sys +from collections.abc import Iterator + +import pytest +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.sdk.trace.sampling import ALWAYS_OFF + +from agents.extensions.tracing import OpenTelemetryTracingProcessor +from agents.tracing import ( + agent_span, + custom_span, + function_span, + generation_span, + set_trace_processors, + task_span, + trace, + turn_span, +) +from tests.testing_processor import SPAN_PROCESSOR_TESTING + + +@pytest.fixture +def otel() -> Iterator[tuple[TracerProvider, InMemorySpanExporter]]: + provider = TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + set_trace_processors([processor]) + try: + yield provider, exporter + finally: + processor.shutdown() + set_trace_processors([SPAN_PROCESSOR_TESTING]) + provider.shutdown() + + +def test_mapping_and_legacy_content_privacy(otel) -> None: + provider, exporter = otel + with trace("group"), task_span("assistant"), agent_span("Worker"), turn_span(1, "Worker"): + with generation_span(model="test-model", input=[{"content": "private-input"}]) as model: + model.span_data.output = [{"content": "private-output"}] + model.span_data.usage = {"input_tokens": 13, "output_tokens": 5} + with function_span("lookup", input="private-arguments") as tool: + tool.span_data.output = "private-result" + spans = exporter.get_finished_spans() + by_operation = {span.attributes["gen_ai.operation.name"]: span for span in spans} + assert set(by_operation) == { + "invoke_runner", + "invoke_agent", + "openai.agents.turn", + "chat", + "execute_tool", + } + inference = by_operation["chat"] + assert by_operation["invoke_runner"].parent is None + assert inference.name == "chat test-model" + assert inference.attributes["gen_ai.usage.input_tokens"] == 13 + assert inference.attributes["gen_ai.usage.output_tokens"] == 5 + assert inference.parent.span_id == by_operation["openai.agents.turn"].context.span_id + assert by_operation["execute_tool"].parent.span_id == inference.parent.span_id + assert "private-" not in str([span.attributes for span in spans]) + + +def test_tool_scope_and_caller_context(otel) -> None: + provider, exporter = otel + from opentelemetry import trace as otel_trace + + tracer = provider.get_tracer("application") + with tracer.start_as_current_span("caller") as caller: + with trace("group"), task_span("assistant"): + with function_span("lookup"): + with tracer.start_as_current_span("database"): + pass + assert otel_trace.get_current_span() is not caller + assert otel_trace.get_current_span() is caller + by_name = {span.name: span for span in exporter.get_finished_spans()} + assert by_name["invoke_runner assistant"].parent.span_id == caller.get_span_context().span_id + assert by_name["database"].parent.span_id == by_name["execute_tool lookup"].context.span_id + + +def test_multiple_runs_inside_one_native_trace(otel) -> None: + provider, exporter = otel + tracer = provider.get_tracer("application") + with trace("conversation"): + for name in ("first", "second"): + with tracer.start_as_current_span(name): + with task_span("assistant"): + pass + spans = exporter.get_finished_spans() + callers = {span.name: span for span in spans if span.name in ("first", "second")} + runs = [span for span in spans if span.name == "invoke_runner assistant"] + assert len(runs) == 2 + assert {span.parent.span_id for span in runs} == { + span.context.span_id for span in callers.values() + } + + +def test_error_metadata_excludes_error_payload(otel) -> None: + _, exporter = otel + with trace("group"), function_span("lookup") as tool: + tool.set_error({"message": "private-arguments", "data": {"output": "private-result"}}) + span = exporter.get_finished_spans()[0] + assert span.status.is_ok is False + assert span.attributes["error.type"] == "_OTHER" + assert "private-" not in str(span.attributes) + assert span.status.description is None + assert not span.events + + +def test_sampling_and_provider_lifecycle() -> None: + provider = TracerProvider(sampler=ALWAYS_OFF) + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + set_trace_processors([processor]) + try: + with trace("group"), task_span("assistant"), function_span("lookup"): + pass + processor.force_flush() + processor.shutdown() + assert not exporter.get_finished_spans() + assert provider.force_flush() + finally: + set_trace_processors([SPAN_PROCESSOR_TESTING]) + provider.shutdown() + + +@pytest.mark.asyncio +async def test_concurrent_tool_context_and_content_permissions(otel) -> None: + provider, exporter = otel + from opentelemetry import trace as otel_trace + + tracer = provider.get_tracer("application") + started = [asyncio.Event(), asyncio.Event()] + release = [asyncio.Event(), asyncio.Event()] + + async def execute(index: int) -> None: + with function_span(f"lookup-{index}", input=f"private-input-{index}") as tool: + tool.span_data.operation.detail = "content" if index == 0 else "metadata" + tool.span_data.output = f"private-result-{index}" + started[index].set() + await release[index].wait() + with tracer.start_as_current_span(f"database-{index}"): + pass + + with tracer.start_as_current_span("caller") as caller: + with trace("group"), task_span("assistant"): + tasks = [asyncio.create_task(execute(index)) for index in range(2)] + await asyncio.gather(*(event.wait() for event in started)) + release[1].set() + await tasks[1] + release[0].set() + await tasks[0] + assert otel_trace.get_current_span() is caller + spans = {span.name: span for span in exporter.get_finished_spans()} + for index in range(2): + assert ( + spans[f"database-{index}"].parent.span_id + == spans[f"execute_tool lookup-{index}"].context.span_id + ) + assert "private-input-0" in str(spans["execute_tool lookup-0"].attributes) + assert "private-result-0" in str(spans["execute_tool lookup-0"].attributes) + assert "private-" not in str(spans["execute_tool lookup-1"].attributes) + + +@pytest.mark.asyncio +async def test_cancelled_tool_closes_scope(otel) -> None: + provider, exporter = otel + from opentelemetry import trace as otel_trace + + tracer = provider.get_tracer("application") + started = asyncio.Event() + + async def execute() -> None: + with function_span("lookup"): + started.set() + await asyncio.Future() + + with tracer.start_as_current_span("caller") as caller: + with trace("group"), task_span("assistant"): + task = asyncio.create_task(execute()) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert otel_trace.get_current_span() is caller + spans = exporter.get_finished_spans() + assert len([span for span in spans if span.name == "execute_tool lookup"]) == 1 + + +def test_content_schema_and_budget(otel) -> None: + _, exporter = otel + with trace("group"), generation_span(model="test-model") as model: + model.span_data.operation.detail = "content" + model.span_data.input = [ + {"role": "user", "content": [{"type": "input_text", "text": "é" * 30_000}]} + ] + model.span_data.model_config = {"instructions": "instruction-canary"} + model.span_data.output = [ + { + "type": "function_call", + "call_id": "call-1", + "name": "lookup", + "arguments": '{"city":"Paris"}', + } + ] + span = exporter.get_finished_spans()[0] + inputs = span.attributes["gen_ai.input.messages"] + assert inputs[0]["role"] == "user" + assert inputs[0]["parts"][0]["type"] == "text" + assert "[truncated]" in inputs[0]["parts"][0]["content"] + directions = { + key: value + for key, value in span.attributes.items() + if key in ("gen_ai.input.messages", "gen_ai.system_instructions") + } + assert len(json.dumps(directions, ensure_ascii=False).encode("utf-8")) <= 32 * 1024 + output = span.attributes["gen_ai.output.messages"] + assert output[0]["parts"][0] == { + "type": "tool_call", + "id": "call-1", + "name": "lookup", + "arguments": {"city": "Paris"}, + } + + +def test_failing_otel_export_does_not_change_sdk_execution(otel) -> None: + from opentelemetry.sdk.trace import SpanProcessor + + class FailingProcessor(SpanProcessor): + def on_start(self, span, parent_context=None): + raise RuntimeError("synthetic telemetry failure") + + def on_end(self, span): + raise RuntimeError("synthetic telemetry failure") + + provider, _ = otel + provider.add_span_processor(FailingProcessor()) + with trace("group"), task_span("assistant"), function_span("lookup"): + result = "application-result" + assert result == "application-result" + + +def test_core_import_without_opentelemetry() -> None: + script = """ +import importlib.abc +import sys + +class BlockOTel(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == 'opentelemetry' or fullname.startswith('opentelemetry.'): + raise ModuleNotFoundError('optional OTel dependency unavailable', name=fullname) + return None + +sys.meta_path.insert(0, BlockOTel()) +import agents +from agents.tracing import TracingProcessor +assert 'opentelemetry' not in sys.modules +""" + subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=True) + + +def test_external_source_timestamps_preserve_nanoseconds(otel) -> None: + _, exporter = otel + with trace("group"): + model = generation_span(model="test-model") + model.start_at("2026-11-20T06:00:00.123456789Z") + model.finish_at("2026-11-20T06:00:01.987654321Z") + span = exporter.get_finished_spans()[0] + assert span.start_time == 1_795_154_400_123_456_789 + assert span.end_time == 1_795_154_401_987_654_321 + + +def test_reused_model_execution_scopes_preserve_live_parent(otel) -> None: + from opentelemetry import trace as otel_trace + + provider, exporter = otel + tracer = provider.get_tracer("application") + with tracer.start_as_current_span("caller") as caller: + with trace("group"): + model = generation_span(model="test-model") + model.start() + for attempt in range(2): + with model.as_current(): + with tracer.start_as_current_span(f"http-{attempt}"): + pass + assert otel_trace.get_current_span() is caller + model.finish() + by_name = {span.name: span for span in exporter.get_finished_spans()} + for attempt in range(2): + assert ( + by_name[f"http-{attempt}"].parent.span_id == by_name["chat test-model"].context.span_id + ) + + +def test_tool_approval_mapping_and_partial_coverage(otel) -> None: + provider, exporter = otel + tracer = provider.get_tracer("application") + with trace("group"): + with tracer.start_as_current_span("before-approval"): + approval = function_span("lookup") + approval.span_data.operation.outcome = "paused" + approval.start() + approval.finish() + with tracer.start_as_current_span("after-approval"): + with function_span("lookup"): + pass + with custom_span("tool_approval", {"tool_name": "denied", "outcome": "rejected"}): + pass + with custom_span( + "codex.tracing.coverage", + {"coverage": "partial", "provider": "codex", "reason": "unsupported"}, + ): + pass + spans = exporter.get_finished_spans() + executions = [ + span for span in spans if span.attributes.get("gen_ai.operation.name") == "execute_tool" + ] + approvals = [ + span + for span in spans + if span.attributes.get("gen_ai.operation.name") == "openai.agents.tool_approval" + ] + assert len(executions) == 1 + assert len(approvals) == 2 + by_name = {span.name: span for span in spans} + assert executions[0].parent.span_id == by_name["after-approval"].context.span_id + assert ( + by_name["openai.agents.tool_approval lookup"].parent.span_id + == by_name["before-approval"].context.span_id + ) + assert ( + by_name["codex.tracing.coverage"].attributes["openai.agents.operation.coverage"] + == "partial" + ) + + +def test_marker_only_content_preserves_omission(otel) -> None: + _, exporter = otel + with trace("group"), generation_span(model="test-model") as model: + model.span_data.operation.detail = "content" + model.span_data.input = [{"truncated": True}] + model.span_data.output = [{"truncated": True}] + span = exporter.get_finished_spans()[0] + for attribute in ("gen_ai.input.messages", "gen_ai.output.messages"): + assert list(span.attributes[attribute][0]["parts"]) == [ + {"type": "openai.omitted", "reason": "truncated"} + ] + + +@pytest.mark.asyncio +async def test_overlapping_runs_with_same_native_trace_id(otel) -> None: + provider, exporter = otel + tracer = provider.get_tracer("application") + first_done, second_started, release_second = (asyncio.Event() for _ in range(3)) + shared_id = "trace_" + "a" * 32 + + async def first() -> None: + with tracer.start_as_current_span("caller-first"): + with trace("first", trace_id=shared_id), task_span("first"): + await second_started.wait() + first_done.set() + + async def second() -> None: + with tracer.start_as_current_span("caller-second"): + with trace("second", trace_id=shared_id), task_span("second"): + second_started.set() + await release_second.wait() + with function_span("lookup"): + with tracer.start_as_current_span("database"): + pass + + first_task, second_task = asyncio.create_task(first()), asyncio.create_task(second()) + await first_done.wait() + assert "invoke_runner second" not in {span.name for span in exporter.get_finished_spans()} + release_second.set() + await asyncio.gather(first_task, second_task) + spans = {span.name: span for span in exporter.get_finished_spans()} + assert spans["invoke_runner second"].parent.span_id == spans["caller-second"].context.span_id + assert ( + spans["execute_tool lookup"].parent.span_id == spans["invoke_runner second"].context.span_id + ) + assert spans["database"].parent.span_id == spans["execute_tool lookup"].context.span_id + + +def test_trace_end_and_shutdown_close_missing_terminals_without_provider_shutdown(otel) -> None: + provider, exporter = otel + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + set_trace_processors([processor]) + with trace("group"): + pending = function_span("orphan") + pending.start() + spans = exporter.get_finished_spans() + assert len(spans) == 1 + assert spans[0].attributes["openai.agents.operation.outcome"] == "interrupted" + assert spans[0].attributes["openai.agents.operation.estimated_end"] is True + # A late completion cannot export the same operation twice. + pending.finish() + active_trace = trace("missing-trace-end") + active_trace.start(mark_as_current=True) + try: + missing_terminal = function_span("missing-terminal") + missing_terminal.start() + processor.shutdown() + processor.shutdown() + assert len(exporter.get_finished_spans()) == 2 + assert ( + exporter.get_finished_spans()[1].attributes["openai.agents.operation.outcome"] + == "interrupted" + ) + with provider.get_tracer("application").start_as_current_span("provider-still-active"): + pass + assert len(exporter.get_finished_spans()) == 3 + finally: + active_trace.finish(reset_current=True) + + +def test_trace_cleanup_continues_after_otel_end_failure(otel) -> None: + from opentelemetry.sdk.trace import SpanProcessor + + class FailingOnEnd(SpanProcessor): + def on_end(self, span): + raise RuntimeError("synthetic telemetry failure") + + provider, exporter = otel + provider.add_span_processor(FailingOnEnd()) + with trace("group"): + for name in ("first-orphan", "second-orphan"): + pending = function_span(name) + pending.start() + spans = exporter.get_finished_spans() + assert len(spans) == 2 + assert {span.name for span in spans} == { + "execute_tool first-orphan", + "execute_tool second-orphan", + } + assert all( + span.attributes["openai.agents.operation.outcome"] == "interrupted" for span in spans + ) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_chat_completions_native_payloads_reach_otel(otel, monkeypatch, streamed) -> None: + from unittest.mock import AsyncMock + + from openai import AsyncOpenAI + from openai.types.chat import ChatCompletionChunk + + from agents import ModelSettings, ModelTracing, OpenAIChatCompletionsModel + from agents.tracing.config import operation_tracing_scope + from tests.models.test_openai_chatcompletions import _minimal_chat_completion + + _, exporter = otel + completion = _minimal_chat_completion("answer") + call = { + "id": "call-lookup", + "type": "function", + "function": {"name": "lookup", "arguments": '{"key":"value"}'}, + } + completion.choices[0].message = type(completion.choices[0].message).model_validate( + {**completion.choices[0].message.model_dump(), "tool_calls": [call]} + ) + + async def chunks(): + payload = completion.model_dump() + delta = {**payload["choices"][0]["message"], "tool_calls": [{**call, "index": 0}]} + payload.update( + object="chat.completion.chunk", + choices=[{"index": 0, "delta": delta, "finish_reason": "tool_calls"}], + ) + yield ChatCompletionChunk.model_validate(payload) + + async with AsyncOpenAI(api_key="test-placeholder") as client: + monkeypatch.setattr( + client.chat.completions, + "create", + AsyncMock(return_value=chunks() if streamed else completion), + ) + model = OpenAIChatCompletionsModel("fixture", client) + with trace("group"), operation_tracing_scope({"operation_detail": "content"}, True): + args = (None, "prompt", ModelSettings(), [], None, [], ModelTracing.ENABLED) + if streamed: + async for _ in model.stream_response(*args): + pass + else: + await model.get_response(*args) + span = next(s for s in exporter.get_finished_spans() if s.name == "chat fixture") + messages = json.loads(json.dumps(span.attributes["gen_ai.output.messages"])) + assert messages[0]["role"] == "assistant" + assert messages[0]["parts"] == [ + {"type": "text", "content": "answer"}, + {"type": "tool_call", "id": "call-lookup", "name": "lookup", "arguments": {"key": "value"}}, + ] diff --git a/tests/tracing/test_resumable_operation_policy.py b/tests/tracing/test_resumable_operation_policy.py new file mode 100644 index 0000000000..de24839b92 --- /dev/null +++ b/tests/tracing/test_resumable_operation_policy.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import asyncio +import json + +import pytest + +from agents import Agent, RunConfig, Runner +from agents.decorators import tool +from agents.memory.resumable_session import ResumableSession +from agents.testing import ScriptedModel, assistant_message, function_call +from agents.tracing import generation_span +from agents.tracing.config import get_operation_detail +from tests.memory.test_resumable_session import MemoryStore +from tests.testing_processor import fetch_ordered_spans + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("mode", ["default", "metadata", "content", "veto", "disabled"]) +async def test_resumable_storage_uses_current_run_capture_policy(streamed: bool, mode: str) -> None: + observations: list[tuple[str, str | None]] = [] + + class Store(MemoryStore): + def observe(self, phase: str) -> None: + observations.append((phase, get_operation_detail())) + with generation_span(model="checkpoint", input=[{"content": "CHECKPOINT_CANARY"}]): + pass + + async def save(self, session_id: str, value: str, *, expected: str | None) -> bool: + self.observe(json.loads(value)["status"]) + await super().save(session_id, value, expected=expected) + # Exercise acknowledged-write recovery through the adjacent load callback. + return False + + async def load(self, session_id: str) -> str | None: + self.observe("load") + return await super().load(session_id) + + store = Store() + session = await ResumableSession.create(store) + observations.clear() + prior_spans = {s.span_id for s in fetch_ordered_spans()} + inner_model = ScriptedModel([[assistant_message("done")]]) + inner = Agent(name="inner", model=inner_model) + config = RunConfig( + tracing={} + if mode == "default" + else {"operation_detail": "metadata" if mode == "metadata" else "content"}, + trace_include_sensitive_data=mode not in {"metadata", "veto"}, + tracing_disabled=mode == "disabled", + ) + + outer_detail = "metadata" if mode == "content" else "content" + + @tool + async def nested() -> str: + if streamed: + result = Runner.run_streamed(inner, "question", session=session, run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(inner, "question", session=session, run_config=config) + assert get_operation_detail() == outer_detail + return str(result.final_output) + + outer = Agent( + name="outer", + tools=[nested], + tool_use_behavior="stop_on_first_tool", + model=ScriptedModel([[function_call("nested", {}, call_id="nested-call")]]), + ) + result = await Runner.run( + outer, "run", run_config=RunConfig(tracing={"operation_detail": outer_detail}) + ) + assert result.final_output == "done" + assert store.checkpoint(session.session_id)["status"] == "ready" + assert len(inner_model.calls) == 1 + expected = None if mode == "default" else "content" if mode == "content" else "metadata" + checkpoints = [ + s + for s in fetch_ordered_spans() + if s.span_id not in prior_spans and getattr(s.span_data, "model", None) == "checkpoint" + ] + assert len(checkpoints) == (0 if mode == "disabled" else 4) + for span in checkpoints: + if mode in {"metadata", "veto"}: + assert span.span_data.input is None + else: + assert "CHECKPOINT_CANARY" in json.dumps(span.export()) + assert span.span_data.operation.detail == expected + assert observations == [(phase, expected) for phase in ["active", "load", "ready", "load"]] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_resumable_initial_claim_settles_before_cancellation(streamed: bool) -> None: + entered, release = asyncio.Event(), asyncio.Event() + + class Store(MemoryStore): + async def save(self, session_id: str, value: str, *, expected: str | None) -> bool: + if json.loads(value)["status"] == "active": + entered.set() + await release.wait() + return await super().save(session_id, value, expected=expected) + + store = Store() + session = await ResumableSession.create(store) + model = ScriptedModel([[assistant_message("unused")]]) + agent = Agent(name="inner", model=model) + config = RunConfig(tracing={"operation_detail": "metadata"}, trace_include_sensitive_data=False) + if streamed: + result = Runner.run_streamed(agent, "question", session=session, run_config=config) + assert result.run_loop_task + task = result.run_loop_task + else: + task = asyncio.create_task( + Runner.run(agent, "question", session=session, run_config=config) + ) + try: + await asyncio.wait_for(entered.wait(), 5) + if streamed: + result.cancel() + else: + task.cancel() + release.set() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(asyncio.shield(task), 5) + assert store.checkpoint(session.session_id)["status"] == "active" + assert not model.calls + if streamed: + assert result.is_complete + assert [event async for event in result.stream_events()] == [] + finally: + release.set() + task.cancel() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/tracing/test_tool_operation_tracing.py b/tests/tracing/test_tool_operation_tracing.py new file mode 100644 index 0000000000..b258ae1c92 --- /dev/null +++ b/tests/tracing/test_tool_operation_tracing.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import pytest +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 agents import Agent, RunConfig, Runner, RunState +from agents.decorators import tool +from agents.extensions.tracing import OpenTelemetryTracingProcessor +from agents.testing import ScriptedModel +from agents.tracing import get_current_span, set_trace_processors +from agents.tracing.config import OperationDetail +from tests.test_responses import get_function_tool_call +from tests.testing_processor import SPAN_PROCESSOR_TESTING, fetch_ordered_spans + + +@pytest.mark.asyncio +@pytest.mark.parametrize("detail", [None, "metadata", "content"]) +@pytest.mark.parametrize("streamed", [False, True]) +async def test_approved_tool_runs_under_the_resuming_caller( + detail: OperationDetail | None, streamed: bool +) -> None: + provider = TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + tracer = provider.get_tracer(__name__) + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + set_trace_processors([SPAN_PROCESSOR_TESTING, processor]) + calls = [] + + @tool(needs_approval=True) + async def lookup() -> str: + span = get_current_span() + assert span + calls.append(span.span_id) + with tracer.start_as_current_span("query"): + return "success" + + agent = Agent( + name="worker", + tools=[lookup], + model=ScriptedModel(steps=[[get_function_tool_call("lookup", "{}", call_id="lookup-1")]]), + tool_use_behavior="stop_on_first_tool", + ) + config = RunConfig(tracing={"operation_detail": detail} if detail else {}) + + async def invoke(input: str | RunState[None]): + if streamed: + result = Runner.run_streamed(agent, input, run_config=config) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, input, run_config=config) + + try: + with tracer.start_as_current_span("original") as original: + paused = await invoke("lookup") + assert not calls + state = paused.to_state() + state.approve(paused.interruptions[0]) + with tracer.start_as_current_span("resume") as resume: + result = await invoke(state) + assert result.final_output == "success" + native = [span for span in fetch_ordered_spans() if span.span_id in calls] + assert len(native) == len(calls) == 1 + assert native[0].span_data.operation.outcome == "completed" + assert native[0].span_data.operation.tool_call_id == "lookup-1" + exported = exporter.get_finished_spans() + (decision,) = [s for s in exported if s.name == "openai.agents.tool_approval lookup"] + (execution,) = [s for s in exported if s.name == "execute_tool lookup"] + (query,) = [s for s in exported if s.name == "query"] + assert decision.context and execution.context and query.parent + assert decision.context.trace_id == original.get_span_context().trace_id + assert execution.context.trace_id == resume.get_span_context().trace_id + assert query.parent.span_id == execution.context.span_id + finally: + set_trace_processors([SPAN_PROCESSOR_TESTING]) + processor.shutdown() + provider.shutdown() diff --git a/uv.lock b/uv.lock index 636d6c80fa..8ca8cdb761 100644 --- a/uv.lock +++ b/uv.lock @@ -2852,6 +2852,9 @@ modal = [ mongodb = [ { name = "pymongo" }, ] +opentelemetry = [ + { name = "opentelemetry-api" }, +] realtime = [ { name = "websockets", version = "16.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "websockets", version = "17.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, @@ -2904,6 +2907,7 @@ dev = [ { name = "mkdocs-static-i18n" }, { name = "mkdocstrings", extra = ["python"] }, { name = "mypy" }, + { name = "opentelemetry-sdk" }, { name = "playwright" }, { name = "protobuf" }, { name = "pygments" }, @@ -2958,6 +2962,7 @@ requires-dist = [ { name = "modal", marker = "extra == 'modal'", specifier = "==1.4.3" }, { name = "numpy", marker = "python_full_version >= '3.10' and extra == 'voice'", specifier = ">=2.2.0,<3" }, { name = "openai", specifier = ">=3.0.0,<4" }, + { name = "opentelemetry-api", marker = "extra == 'opentelemetry'", specifier = ">=1.45.0,<2" }, { name = "protobuf", marker = "extra == 'dapr'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, { name = "protobuf", marker = "extra == 'daytona'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, { name = "protobuf", marker = "extra == 'e2b'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, @@ -2984,7 +2989,7 @@ requires-dist = [ { name = "websockets", marker = "extra == 'realtime'", specifier = ">=15.0,<18" }, { name = "websockets", marker = "extra == 'voice'", specifier = ">=15.0,<18" }, ] -provides-extras = ["voice", "viz", "litellm", "any-llm", "realtime", "sqlalchemy", "encrypt", "redis", "dapr", "mongodb", "docker", "blaxel", "daytona", "cloudflare", "e2b", "modal", "vercel", "s3", "temporal"] +provides-extras = ["opentelemetry", "voice", "viz", "litellm", "any-llm", "realtime", "sqlalchemy", "encrypt", "redis", "dapr", "mongodb", "docker", "blaxel", "daytona", "cloudflare", "e2b", "modal", "vercel", "s3", "temporal"] [package.metadata.requires-dev] dev = [ @@ -3005,6 +3010,7 @@ dev = [ { name = "mkdocs-static-i18n", specifier = ">=1.3.0" }, { name = "mkdocstrings", extras = ["python"], specifier = ">=0.28.0" }, { name = "mypy" }, + { name = "opentelemetry-sdk", specifier = ">=1.45.0,<2" }, { name = "playwright", specifier = "==1.63.0" }, { name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, { name = "pygments", specifier = ">=2.20.0" },