Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/agents/tracing/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,12 @@ def set_api_key(self, api_key: str):
api_key: The OpenAI API key to use. This is the same key used by the OpenAI Python
client.
"""
# We're specifically setting the underlying cached property as well
# Clear the cached property if it exists
if 'api_key' in self.__dict__:
del self.__dict__['api_key']

# Update the private attribute
self._api_key = api_key
self.api_key = api_key

@cached_property
def api_key(self):
Expand Down
32 changes: 32 additions & 0 deletions tests/tracing/test_set_api_key_fix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import os

from agents.tracing.processors import BackendSpanExporter


def test_set_api_key_preserves_env_fallback():
"""Test that set_api_key doesn't break environment variable fallback."""
# Set up environment
original_key = os.environ.get("OPENAI_API_KEY")
os.environ["OPENAI_API_KEY"] = "env-key"

try:
exporter = BackendSpanExporter()

# Initially should use env var
assert exporter.api_key == "env-key"

# Set explicit key
exporter.set_api_key("explicit-key")
assert exporter.api_key == "explicit-key"

# Clear explicit key and verify env fallback works
exporter._api_key = None
if "api_key" in exporter.__dict__:
del exporter.__dict__["api_key"]
assert exporter.api_key == "env-key"

finally:
if original_key is None:
os.environ.pop("OPENAI_API_KEY", None)
else:
os.environ["OPENAI_API_KEY"] = original_key