Skip to content

Commit 61e4fb8

Browse files
authored
Fix set_api_key breaking cached property mechanism (#1339)
1 parent a9763dc commit 61e4fb8

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/agents/tracing/processors.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,12 @@ def set_api_key(self, api_key: str):
6969
api_key: The OpenAI API key to use. This is the same key used by the OpenAI Python
7070
client.
7171
"""
72-
# We're specifically setting the underlying cached property as well
72+
# Clear the cached property if it exists
73+
if 'api_key' in self.__dict__:
74+
del self.__dict__['api_key']
75+
76+
# Update the private attribute
7377
self._api_key = api_key
74-
self.api_key = api_key
7578

7679
@cached_property
7780
def api_key(self):

tests/tracing/test_set_api_key_fix.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import os
2+
3+
from agents.tracing.processors import BackendSpanExporter
4+
5+
6+
def test_set_api_key_preserves_env_fallback():
7+
"""Test that set_api_key doesn't break environment variable fallback."""
8+
# Set up environment
9+
original_key = os.environ.get("OPENAI_API_KEY")
10+
os.environ["OPENAI_API_KEY"] = "env-key"
11+
12+
try:
13+
exporter = BackendSpanExporter()
14+
15+
# Initially should use env var
16+
assert exporter.api_key == "env-key"
17+
18+
# Set explicit key
19+
exporter.set_api_key("explicit-key")
20+
assert exporter.api_key == "explicit-key"
21+
22+
# Clear explicit key and verify env fallback works
23+
exporter._api_key = None
24+
if "api_key" in exporter.__dict__:
25+
del exporter.__dict__["api_key"]
26+
assert exporter.api_key == "env-key"
27+
28+
finally:
29+
if original_key is None:
30+
os.environ.pop("OPENAI_API_KEY", None)
31+
else:
32+
os.environ["OPENAI_API_KEY"] = original_key

0 commit comments

Comments
 (0)