Skip to content

Commit f4f0b85

Browse files
authored
Read tracing API data lazily (#289)
2 parents 211ffb2 + c0794a9 commit f4f0b85

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

src/agents/tracing/processors.py

+18-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import random
66
import threading
77
import time
8+
from functools import cached_property
89
from typing import Any
910

1011
import httpx
@@ -50,9 +51,9 @@ def __init__(
5051
base_delay: Base delay (in seconds) for the first backoff.
5152
max_delay: Maximum delay (in seconds) for backoff growth.
5253
"""
53-
self.api_key = api_key or os.environ.get("OPENAI_API_KEY")
54-
self.organization = organization or os.environ.get("OPENAI_ORG_ID")
55-
self.project = project or os.environ.get("OPENAI_PROJECT_ID")
54+
self._api_key = api_key
55+
self._organization = organization
56+
self._project = project
5657
self.endpoint = endpoint
5758
self.max_retries = max_retries
5859
self.base_delay = base_delay
@@ -68,8 +69,22 @@ def set_api_key(self, api_key: str):
6869
api_key: The OpenAI API key to use. This is the same key used by the OpenAI Python
6970
client.
7071
"""
72+
# We're specifically setting the underlying cached property as well
73+
self._api_key = api_key
7174
self.api_key = api_key
7275

76+
@cached_property
77+
def api_key(self):
78+
return self._api_key or os.environ.get("OPENAI_API_KEY")
79+
80+
@cached_property
81+
def organization(self):
82+
return self._organization or os.environ.get("OPENAI_ORG_ID")
83+
84+
@cached_property
85+
def project(self):
86+
return self._project or os.environ.get("OPENAI_PROJECT_ID")
87+
7388
def export(self, items: list[Trace | Span[Any]]) -> None:
7489
if not items:
7590
return
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import pytest
2+
3+
from agents.tracing.processors import BackendSpanExporter
4+
5+
6+
@pytest.mark.asyncio
7+
async def test_processor_api_key(monkeypatch):
8+
# If the API key is not set, it should be None
9+
monkeypatch.delenv("OPENAI_API_KEY", None)
10+
processor = BackendSpanExporter()
11+
assert processor.api_key is None
12+
13+
# If we set it afterwards, it should be the new value
14+
processor.set_api_key("test_api_key")
15+
assert processor.api_key == "test_api_key"
16+
17+
18+
@pytest.mark.asyncio
19+
async def test_processor_api_key_from_env(monkeypatch):
20+
# If the API key is not set at creation time but set before access time, it should be the new
21+
# value
22+
monkeypatch.delenv("OPENAI_API_KEY", None)
23+
processor = BackendSpanExporter()
24+
25+
# If we set it afterwards, it should be the new value
26+
monkeypatch.setenv("OPENAI_API_KEY", "foo_bar_123")
27+
assert processor.api_key == "foo_bar_123"

0 commit comments

Comments
 (0)