Skip to content

fix(openai-agents): keep create_agent instructions out of traces when the SDK excludes sensitive data - #1981

Open
basil-k-aji-dev wants to merge 2 commits into
openlit:mainfrom
basil-k-aji-dev:fix/openai-agents-sensitive-instructions
Open

basil-k-aji-dev wants to merge 2 commits into
openlit:mainfrom
basil-k-aji-dev:fix/openai-agents-sensitive-instructions

Conversation

@basil-k-aji-dev

@basil-k-aji-dev basil-k-aji-dev commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: Fixes #1759

Change description:

The Agents SDK lets an application keep model inputs and outputs out of traces with OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA=false. OpenLIT's spans built from SDK span data already follow it, because the SDK leaves those fields empty. The create_agent span is the exception: _wrap_agent_init reads instance.instructions directly and recorded the full system prompt in gen_ai.system_instructions, checking only capture_message_content.

The fix asks the SDK for its own decision instead of re-implementing it. _sdk_default_trace_include_sensitive_data() reads the default of the public agents.RunConfig.trace_include_sensitive_data dataclass field (calling its default_factory, without building a RunConfig), and the instructions are recorded only when that is true.

  • Setting exists but cannot be evaluated: fail closed, only this one attribute is omitted.
  • SDK has no such field: nothing to honour, current behaviour is kept.
  • capture_message_content=False still omits the attribute, as before.

Limitation: a per-run RunConfig(trace_include_sensitive_data=False) cannot be honoured here. No run exists when an Agent is constructed, and one agent can later run under several configs. Only the global setting is honoured on this span. Users who need per-run privacy can use the environment variable or capture_message_content=False.

An earlier PR (#1786) took a similar route and was closed by its author. It imported the private agents.run_config._default_trace_include_sensitive_data, which does not exist before the helper moved there, so on those SDK versions its fallback recorded the instructions even with the variable set to false. This one only uses the public dataclass field.

How was this tested

CI does not run pytest for the Python SDK (the step is commented out in ci-python.yml; only pylint runs), so this is local evidence.

New sdk/python/tests/test_openai_agents.py: three hermetic tests with a fake agents module, no API key, plus a contract test that skips when openai-agents is not installed. Red on the unmodified source, on the attribute value:

FAILED test_create_agent_omits_instructions_when_sdk_sensitive_data_disabled
E  assert 'gen_ai.system_instructions' not in mappingproxy({... 'never reveal the refund limit.' ...})
1 failed, 2 passed, 1 skipped

With the fix: 4 passed (the contract test ran against openai-agents 0.25.0). Forcing the helper to return True fails the first test, and forcing it to return False fails the second.

Against the real SDK, not the fake: instrumenting the real agents.Agent with an in-memory exporter and constructing Agent(name=..., instructions="secret refund limit 500") gave system_instructions=None with the variable false, and the formatted instructions with it unset or true. On the original code the secret is recorded in both cases.

The helper matched RunConfig() for every value tried (true, 1, YES, false, 0, off, unset) on openai-agents 0.0.3, 0.1.0, 0.2.11, 0.3.3, 0.4.2, 0.6.1 and 0.25.0. Pylint is 10.00/10 on both files.

Not covered: only the SDK's global default is honoured (see above), and the TypeScript Agents instrumentation was not touched.

Checklist

If your change doesn't seem to apply, please leave them unchecked.

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Summary by Sourcery

Honor the Agents SDK's global sensitive-data setting when capturing instructions in OpenAI Agents creation spans.

Bug Fixes:

  • Prevent create_agent spans from recording agent instructions when the Agents SDK disables sensitive trace data globally.

Enhancements:

  • Use the Agents SDK's public RunConfig default to determine whether system instructions may be captured while preserving existing content-capture behavior.

Documentation:

  • Document how the Python integration handles sensitive data for create_agent spans, including the limitation of per-run RunConfig overrides.

Tests:

  • Add hermetic coverage for sensitive-data and message-content capture behavior, plus a compatibility contract test for the Agents SDK configuration field.

@basil-k-aji-dev
basil-k-aji-dev requested review from a team and ishanjainn as code owners November 22, 2026 08:05
@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Read the SDK-default helper alongside the instruction-capture condition it governs, so the privacy decision and its use can be reviewed together.

  • sdk/python/src/openlit/instrumentation/openai_agents/__init__.py L5, L28-46, L103-107

Documentation

Review the user-facing explanation of when agent instructions appear on create_agent spans and the limitation of per-run settings.

  • docs/latest/sdk/integrations/openai-agents.mdx L38-41

Tests

Check the tests for SDK-default filtering, existing capture_message_content behavior, and the RunConfig field contract.

  • sdk/python/tests/test_openai_agents.py L1-124

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Respect Agents SDK privacy setting on create_agent spans

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Prevent create_agent spans from recording system instructions when the Agents SDK excludes
 sensitive data.
• Preserve instruction capture when permitted by both the SDK default and OpenLIT configuration.
• Add isolated span tests and an optional SDK compatibility check.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed behavior affects one bounded end-to-end observability capability: Agent construction is instrumented into a create_agent span and the resulting system-instruction attribute is exported with that span.
  • The inspected processor consumes native Agent run spans and links them to creation contexts, but no source evidence shows this specific attribute driving an independent application capability.
Sources

sdk/python/src/openlit/instrumentation/openai_agents/init.py[103-107]

                if (
                    instructions
                    and capture_message_content
                    and _sdk_default_trace_include_sensitive_data()
                ):
Behavioral complexity 🟡 Medium 🧩 Compatibility cases

  • Before: instruction capture depended on the existing capture_message_content condition.
  • After: it also inspects the installed Agents SDK RunConfig dataclass and supports a default_factory, a direct default, an absent field, and exception fallback.
  • New correctness condition: the instrumentation must honor the SDK's global sensitive-data default across supported SDK representations while not treating a per-run RunConfig override as available during Agent construction.
  • These are compatibility cases around SDK versions/configuration representation; the underlying operation remains a direct conditional attribute assignment and does not introduce new concurrency, persistence, or application-state invariants.
Sources

sdk/python/src/openlit/instrumentation/openai_agents/init.py[28-44]

def _sdk_default_trace_include_sensitive_data():
    """Return the Agents SDK's global default for RunConfig.trace_include_sensitive_data
    (OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA). A per-run RunConfig override is not
    known when an Agent is constructed, so only the global default can be honoured here."""
    try:
        from agents import RunConfig

        for field in dataclasses.fields(RunConfig):
            if field.name == "trace_include_sensitive_data":
                if field.default_factory is not dataclasses.MISSING:
                    return bool(field.default_factory())
                if field.default is not dataclasses.MISSING:
                    return bool(field.default)
                return False
        return True
    except Exception:
        return False

sdk/python/src/openlit/instrumentation/openai_agents/init.py[103-107]

                if (
                    instructions
                    and capture_message_content
                    and _sdk_default_trace_include_sensitive_data()
                ):
Potential damage 🟡 Medium 🩹 Recoverable

  • If this behavior regresses, create_agent spans may omit system instructions when they should be recorded, or may record them when the SDK global sensitive-data setting disables them.
  • The supported consequence is degraded or policy-inconsistent observability for the OpenAI Agents integration, not an agent execution failure or application-data mutation.
  • Future telemetry can be corrected by restoring the code/configuration and creating new spans, but instructions omitted from already-exported spans cannot be reconstructed from those spans alone.
  • The equal-importance baseline is used because no business-criticality declaration was supplied.
  • Code/configuration rollback restores behavior for future Agent constructions.
  • Previously emitted spans with omitted instructions require the original Agent instructions or another source for any manual reconstruction; telemetry already exported cannot be automatically repaired by this code.
Sources

sdk/python/src/openlit/instrumentation/openai_agents/init.py[28-44]

def _sdk_default_trace_include_sensitive_data():
    """Return the Agents SDK's global default for RunConfig.trace_include_sensitive_data
    (OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA). A per-run RunConfig override is not
    known when an Agent is constructed, so only the global default can be honoured here."""
    try:
        from agents import RunConfig

        for field in dataclasses.fields(RunConfig):
            if field.name == "trace_include_sensitive_data":
                if field.default_factory is not dataclasses.MISSING:
                    return bool(field.default_factory())
                if field.default is not dataclasses.MISSING:
                    return bool(field.default)
                return False
        return True
    except Exception:
        return False

sdk/python/src/openlit/instrumentation/openai_agents/init.py[103-107]

                if (
                    instructions
                    and capture_message_content
                    and _sdk_default_trace_include_sensitive_data()
                ):
Assessed commit db2f428
Diagram

graph TD
  A["Agent construction"] --> B["Create span"] --> C{"Capture enabled?"} -->|yes| D{"SDK permits?"} -->|yes| E["Record instructions"]
  F["RunConfig default"] --> D
  C -->|no| G["Omit instructions"]
  D -->|no| G
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Parse the environment variable directly
  • ➕ Avoids inspecting the SDK's RunConfig dataclass.
  • ➖ Duplicates SDK parsing and default semantics, which could diverge across versions.

Recommendation: Use the SDK field default as proposed: it follows the SDK's own global decision without constructing a RunConfig or relying on a private helper. The construction-time span cannot reflect later per-run overrides; reviewers should keep that limitation in mind.

Files changed (2) +149 / -1

Bug fix (1) +25 / -1
__init__.pyGate creation-span instructions on the SDK sensitive-data default +25/-1

Gate creation-span instructions on the SDK sensitive-data default

• Reads the public RunConfig dataclass field default before adding gen_ai.system_instructions. An unevaluable setting omits instructions, an absent field preserves previous behavior, and capture_message_content remains an independent gate.

sdk/python/src/openlit/instrumentation/openai_agents/init.py

Tests (1) +124 / -0
test_openai_agents.pyTest create_agent instruction privacy behavior +124/-0

Test create_agent instruction privacy behavior

• Adds credential-free span tests for disabled SDK tracing, the unset default, and disabled OpenLIT content capture. An optional contract test checks that an installed Agents SDK exposes the expected RunConfig field.

sdk/python/tests/test_openai_agents.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can route each severity your way: inline, summary, both, or drop

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit db2f428

#1759 Bug: OpenAI Agents `create_agent` span records the agent's instructions although the Agents SDK is set to keep sensitive data out of traces · 1 of 1 met

# Requirement Status Notes
1 Omit gen_ai.system_instructions from create_agent spans when the Agents SDK's global sensitive-data setting is off. ✅ Met The wrapper checks the public RunConfig.trace_include_sensitive_data default before recording instructions; the tests cover the disabled and enabled defaults.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/openai_agents/__init__.py" line_range="106" />
<code_context>
+                if (
+                    instructions
+                    and capture_message_content
+                    and _sdk_default_trace_include_sensitive_data()
+                ):
                     formatted = format_system_instructions(instructions)
</code_context>
<issue_to_address>
**Per-run privacy opt-out is ignored**

When the global sensitive-data default is enabled and a run passes `RunConfig(trace_include_sensitive_data=False)`, `_sdk_default_trace_include_sensitive_data()` checks only the global `RunConfig` default, so `_wrap_agent_init` records instructions before the per-run config is available and the exported `create_agent` span contains the prompt despite the run's privacy opt-out.

Defer capturing or exporting the instructions until the run's `RunConfig` is known, and honor its `trace_include_sensitive_data` value.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/instrumentation/openai_agents/__init__.py" line_range="44" />
<code_context>
+                    return bool(field.default_factory())
+                if field.default is not dataclasses.MISSING:
+                    return bool(field.default)
+                return False
+        return True
+    except Exception:
</code_context>
<issue_to_address>
**SDK setting failures go unnoticed**

When the `RunConfig` import, dataclass field inspection, or default factory raises an exception, the broad exception handler returns `False` without recording the error, so `_wrap_agent_init` omits `gen_ai.system_instructions` and operators cannot distinguish an SDK/default-factory failure from intentional sensitive-data suppression.

Keep the fail-closed return value, but emit a diagnostic for the evaluation failure.
</issue_to_address>

### Comment 3
<location path="sdk/python/src/openlit/instrumentation/openai_agents/__init__.py" line_range="106" />
<code_context>
+                if (
+                    instructions
+                    and capture_message_content
+                    and _sdk_default_trace_include_sensitive_data()
+                ):
                     formatted = format_system_instructions(instructions)
</code_context>
<issue_to_address>
**New privacy behavior stays undocumented**

When the `create_agent` span starts honoring the SDK's sensitive-data setting, the OpenAI Agents integration guide does not explain that `create_agent` instructions are now omitted when the SDK's global sensitive-data setting is disabled, so OpenLIT users cannot learn about this behavior from the documentation.

Update the OpenAI Agents integration guide to document how the SDK's global sensitive-data setting affects captured instructions.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: sdk/python/src/openlit/instrumentation/openai_agents/__init__.py:106, sdk/python/src/openlit/instrumentation/openai_agents/__init__.py:44


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

if (
instructions
and capture_message_content
and _sdk_default_trace_include_sensitive_data()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Per-run privacy opt-out is ignored

When the global sensitive-data default is enabled and a run passes RunConfig(trace_include_sensitive_data=False), _sdk_default_trace_include_sensitive_data() checks only the global RunConfig default, so _wrap_agent_init records instructions before the per-run config is available and the exported create_agent span contains the prompt despite the run's privacy opt-out.

Defer capturing or exporting the instructions until the run's RunConfig is known, and honor its trace_include_sensitive_data value.

Prompt for AI agents
In `sdk/python/src/openlit/instrumentation/openai_agents/__init__.py` at line 106:

**Per-run privacy opt-out is ignored**

When the global sensitive-data default is enabled and a run passes `RunConfig(trace_include_sensitive_data=False)`, `_sdk_default_trace_include_sensitive_data()` checks only the global `RunConfig` default, so `_wrap_agent_init` records instructions before the per-run config is available and the exported `create_agent` span contains the prompt despite the run's privacy opt-out.

Defer capturing or exporting the instructions until the run's `RunConfig` is known, and honor its `trace_include_sensitive_data` value.

From #1759:

Omit create_agent instructions when the SDK's sensitive-data setting is disabled, globally or per run.

return False
return True
except Exception:
return False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · SDK setting failures go unnoticed

When the RunConfig import, dataclass field inspection, or default factory raises an exception, the broad exception handler returns False without recording the error, so _wrap_agent_init omits gen_ai.system_instructions and operators cannot distinguish an SDK/default-factory failure from intentional sensitive-data suppression.

Keep the fail-closed return value, but emit a diagnostic for the evaluation failure.

Prompt for AI agents
In `sdk/python/src/openlit/instrumentation/openai_agents/__init__.py` at line 44:

**SDK setting failures go unnoticed**

When the `RunConfig` import, dataclass field inspection, or default factory raises an exception, the broad exception handler returns `False` without recording the error, so `_wrap_agent_init` omits `gen_ai.system_instructions` and operators cannot distinguish an SDK/default-factory failure from intentional sensitive-data suppression.

Keep the fail-closed return value, but emit a diagnostic for the evaluation failure.

@mintlify

mintlify Bot commented Nov 24, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit db2f428.

Approve preview

This branch was previously deployed

1 inactive (outdated) deployment
release-notes — c7a1238b Deployed Nov 22, 2026 by basil-k-aji-dev via Normalize / Conventional title #877
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: OpenAI Agents create_agent span records the agent's instructions although the Agents SDK is set to keep sensitive data out of traces

1 participant