All Agent Engineering

OpenAI Agents SDK: Put Several Runs in One Trace and Check the Data Boundary

Wrap two Runner.run calls in trace() so they share one trace, then check the disable switches, sensitive data capture, export path and flush behavior.

AINavWritten / Updated
On this page

At a glance

This entry follows the official Tracing page at a fixed revision and covers one task: confirming that two agent runs belong to one trace, what data those traces may hold, and how that data leaves the process. The page's own example only defines a main function and never calls it. Nothing was installed or executed in this batch.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • OpenAI Agents SDK Documented openai_agents_sdk task and conditions

Execution locations and responsibilities

  • Python application definition and caller Define the configuration or request shown here and check its inputs, outputs and failure branches.

When to use

  • An existing Python application or request that can call Runner.run inside an async function, with an event loop you start yourself. The source example defines async def main() but does not call it and imports no asyncio.

When not to use

  • The source describes tracing behavior and configuration only. It does not say which model credentials Runner.run needs, how to install the SDK or which versions are supported, and this entry adds none of that.

Prepare the input and environment

  • An existing Python application or request that can call Runner.run inside an async function, with an event loop you start yourself. The source example defines async def main() but does not call it and imports no asyncio.
  • The agents package that provides Agent, Runner and trace, plus whatever model access your agent needs. The source example shows neither model credentials nor installation, so confirm both against the SDK documentation for your environment.
  • An organization that is not under a Zero Data Retention (ZDR) policy, because the source says tracing is unavailable for those organizations.
  • A look at whether OPENAI_AGENTS_DISABLE_TRACING or OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA is already set in the environment, so the starting state is known. If you use non-OpenAI models and want traces in the OpenAI Traces dashboard, you also need an OpenAI API key for the tracing exporter.

Mechanism and data flow

Trace and span ownership: The source defines a trace as a single end-to-end operation of a workflow, composed of spans. A trace has workflow_name, trace_id, an optional group_id, disabled and optional metadata. If you do not pass a trace_id one is generated, and it must have the format trace_<32_alphanumeric>. Spans carry started_at, ended_at, trace_id, an optional parent_id and span_data. By default each Runner.run, Runner.run_sync or Runner.run_streamed call is wrapped in its own trace() named with the literal string Agent workflow, so two separate calls give two traces unless you add an outer one.

Trace context and grouping: To put several run() calls in one trace, the source wraps the whole block in trace(). It recommends using the trace as a context manager, with trace(...) as my_trace, which starts and ends the trace at the right time. You can also call trace.start() and trace.finish() yourself, in which case you pass mark_as_current to start() and reset_current to finish(). The current trace is tracked through a Python contextvar, which the source says works with concurrency automatically. Spans join the current trace and nest under the nearest current span. group_id is a separate tool for linking multiple traces from the same conversation, such as a chat thread ID.

Data boundary and disable switches: Tracing is on by default. The source lists three common ways to turn it off: the environment variable OPENAI_AGENTS_DISABLE_TRACING=1, set_tracing_disabled(True) in code, and RunConfig.tracing_disabled set to True for a single run. generation_span() and function_span() store inputs and outputs that may be sensitive, and RunConfig.trace_include_sensitive_data can turn that capture off; it defaults to True. The environment variable OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA sets the default with true/1 or false/0. With False, Responses model spans omit the request input and response output; for official OpenAI endpoints the response_id stays as correlation metadata, and for custom endpoints it is omitted. Disabling tracing and hiding sensitive content are two different controls.

Export path and flush: The default TraceProvider uses a BatchTraceProcessor that hands batches to a BackendSpanExporter, which exports to the OpenAI backend. Export runs in the background every few seconds, sooner when the in-memory queue reaches its size trigger, with a final flush at process exit, so a trace may not show up in the dashboard right after a job ends. flush_traces() blocks until buffered traces and spans are exported, and the source says to call it after the trace context exits. Disabling tracing does not discard data already buffered, and flush_traces() still flushes it. add_trace_processor() adds a destination and keeps the default exporter, while set_trace_processors() replaces the defaults, so nothing reaches the OpenAI backend unless your processors include one. If export depends on successful redaction, the source says to keep redaction and delivery inside the same application-owned exporter.

Workflow map

Workflow stages and responsibilities
StageWhat happens
Trace and span ownershipThe source defines a trace as a single end-to-end operation of a workflow, composed of spans.
Trace context and groupingTo put several run() calls in one trace, the source wraps the whole block in trace().
Data boundary and disable switchesTracing is on by default.
Export path and flushThe default TraceProvider uses a BatchTraceProcessor that hands batches to a BackendSpanExporter, which exports to the OpenAI backend.

Complete the task

Confirm eligibility and the current switch state: The configuration checks and sequence below are editorial recommendations; specific SDK behavior comes from s1. Confirm the organization is not under a ZDR policy, since tracing is unavailable for those organizations. Check OPENAI_AGENTS_DISABLE_TRACING, calls to set_tracing_disabled(True) and the intended RunConfig.tracing_disabled setting. The first two disable tracing globally; the last disables tracing for the specified single run. The source does not say that the single-run switch disables an explicitly created outer trace(). Read and record the initial values so they can be restored as appropriate. Do not infer that the single-run switch prevents all new traces.

Fix the trace boundary and name: Decide which Runner.run calls belong to one logical workflow. The source example wraps two calls in a single with trace("Joke workflow"):, so both runs become one overall trace instead of each creating its own. Without your own wrapper the default trace name is Agent workflow. If several traces belong to one conversation, the source suggests linking them with group_id, for example a chat thread ID. Keeping sensitive information out of the chosen name is an editorial recommendation; workflow_name is recorded with the trace.

Decide whether sensitive data is recorded: Check whether your runs pass user input, model output or tool arguments through generation_span() and function_span(). The source says these inputs and outputs may be sensitive and are captured by default, because trace_include_sensitive_data defaults to True. If capture is not allowed, set it to False in RunConfig, or set OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA to false or 0 before starting the app. With False, Responses model spans omit request input and response output, though the response_id of an official endpoint remains. Make this choice before the run, since it cannot recall data that was already exported.

Configure the export destination and credential before running: As an editorial recommendation, decide which destination may receive data and check the scope of the tracing credential first. The source says the default BatchTraceProcessor and BackendSpanExporter export to OpenAI. add_trace_processor() adds a processor and keeps the default exporter; registering a redactor first does not by itself prevent default export. When delivery depends on successful redaction, the source requires replacing the defaults with set_trace_processors() and a BatchTraceProcessor configured with an application-owned exporter. Keep redaction and delivery in that exporter: copy serialized payloads, redact the copies and deliver only redacted results. If serialization, copying or redaction fails, drop the batch and log a fixed failure message without payloads, exception text or a traceback. The redactor and destination must not independently log or send original data. Configure this replacement before creating traces or running agents. It affects future callbacks and does not erase data already buffered by old processors. The official example lacks this configuration, which the application must supply separately. For non-OpenAI models exported to the OpenAI dashboard, use set_tracing_export_api_key; to change only one run's tracing key, pass api_key in RunConfig's tracing setting.

Attach the source example to your own runtime: The official code block below stays unchanged. It imports Agent, Runner and trace, creates Joke generator in main, and awaits two Runner.run calls in an outer trace. The second input uses first_result.final_output. It only defines the function, so your application must supply the async entry point that calls main and the model access configuration. Complete the preceding data and export setup before invoking it. The original code has no empty-output branch and proceeds directly to the second call. As an editorial recommendation, implement a separate check in your integration after the first return and before the second call: if first_result.final_output is empty, stop further calls and record the attempt as incomplete. Empty output from the second call is also incomplete. These controls are not in the original code block. Stopping does not recall buffered or exported traces. The final print calls write to stdout; deciding how to handle sensitive stdout content is a separate editorial recommendation for the application.

Decide whether you need to flush: If the default background export latency is acceptable, you can skip flush_traces(). If the end of a unit of work needs an immediate delivery guarantee, call flush_traces() after the trace context exits; the source places it in a finally block. Do not call it before trace() closes, or you may flush a partially built trace. It blocks until buffered data is exported. It still flushes buffered data after tracing is disabled, so it is not a guarantee that no more data leaves the process.

Run the completion checks and clean up (editorial): Check statically that both Runner.run calls share the outer trace and that the second prompt uses the first final_output. Record the global and single-run disable switches, sensitive-data settings, export destination and tracing credential scope. To claim actual trace ownership was verified, observe the corresponding trace in an approved environment; two non-empty outputs are insufficient. When immediate delivery is required, record whether flush_traces() completed after the context closed. Mark unexecuted, unobserved or unchecked items as unverified. After success, an error, empty output or a manual stop, restore starting configuration as appropriate, remove temporary tracing keys and handle sensitive local output. Finish required export and flush before clearing temporary credentials needed for them. Manual cleanup and stopping are editorial recommendations, not a cancellation API, and do not recall buffered or exported data.

Worked example

The source example creates agent = Agent(name="Joke generator", instructions="Tell funny jokes."). Inside with trace("Joke workflow"): it awaits Runner.run(agent, "Tell me a joke") and stores first_result, then awaits a second Runner.run whose prompt joins Rate this joke: with first_result.final_output, stored as second_result. It finishes by printing a Joke: line and a Rating: line from the two final_output values. The input is the two prompt strings; the output is two printed lines plus trace data. Per the source annotation, the two calls are wrapped in with trace(), so they become one overall trace instead of two. The # (1)! comment is a documentation marker. The dependencies are Agent, Runner and trace from agents; what is missing is code that calls main, an event loop and model access configuration. This is an official example, not an observation from this batch, and it does not show whether the joke or rating is sensible. The example itself has no export-destination configuration, processor replacement, empty-output checks or flush. The actual integration must supply those separately according to the documented behavior and editorial recommendations above. No trace or destination data was observed in this batch.

Example: official documentation excerpt; read under the stated prerequisites; not run in this batch
python
from agents import Agent, Runner, trace


async def main():
    agent = Agent(name="Joke generator", instructions="Tell funny jokes.")

    with trace("Joke workflow"):  # (1)!
        first_result = await Runner.run(agent, "Tell me a joke")
        second_result = await Runner.run(agent, f"Rate this joke: {first_result.final_output}")
        print(f"Joke: {first_result.final_output}")
        print(f"Rating: {second_result.final_output}")

Check the result and failure paths

  • Static check (editorial): preserve the official code bytes, confirm that both Runner.run calls share the outer with trace() and that the second prompt uses the first output. The actual integration also needs your entry point to call main. Static structure does not prove execution or export.
  • Success condition (editorial): record the verified trace boundary, global and single-run disable switches, sensitive-data settings, export destination and tracing credential scope, and whether required flush completed after the context closed. Two non-empty outputs and correct use of the first output are useful output checks, but do not replace data and export boundary checks. A claim of verified actual trace ownership requires observing the corresponding trace. Keep unexecuted, unobserved or unchecked items marked unverified.
  • Failure condition (editorial): a call or import raises; expected tracing conflicts with switches or ZDR; a required processor replacement was not configured before running; destination or credential scope was not checked; or immediate delivery was required but flush did not complete. Record these as incomplete.
  • Empty output condition (editorial): the original code has no such branch, so implement it separately in the actual integration. After the first return and before the second call, check first_result.final_output; if empty, stop further calls and mark the attempt incomplete. An empty second_result.final_output is also incomplete. Stopping neither blocks nor recalls trace data already buffered or exported.
  • User stopping condition (editorial): mark a manual interruption incomplete. After the trace context exits, perform required flush to the checked destination, then clean up owned resources and temporary configuration. The source provides no trace cancellation API. Stopping does not guarantee that background export stops or recall existing data.

Scope and limits

  • The source example is only a function definition for main. It shows no event loop, real output or dashboard screen, so this entry does not claim the platform has displayed any trace.
  • trace_include_sensitive_data controls only the span data the source lists. Disabling tracing, hiding sensitive content and authorizing export to a third-party destination are three separate decisions.
  • The external processors list in the source consists of community and vendor integrations. The source says a listing is not an OpenAI endorsement or security certification, so evaluate any of them yourself.

No product or API was installed, imported or called in this batch, and no platform login or Traces dashboard was used. SDK behavior comes from the official Tracing page at the fixed revision. The sequence, configuration checks, sensitive-name avoidance, stdout handling, completion checks, manual stopping and cleanup are editorial recommendations, not executed results.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. OpenAI · Tracing
    91fb508

Found an error? Tell us →