Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fe0732e

Browse files
committed
Read tracing API data lazily
1 parent 090e79b commit fe0732e

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

src/agents/tracing/processors.py

Lines changed: 19 additions & 4 deletions
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,7 +69,21 @@ 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
"""
71-
self.api_key = api_key
72+
# Reset the cached property
73+
del self.api_key
74+
self._api_key = api_key
75+
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")
7287

7388
def export(self, items: list[Trace | Span[Any]]) -> None:
7489
if not items:
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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 value
21+
monkeypatch.delenv("OPENAI_API_KEY", None)
22+
processor = BackendSpanExporter()
23+
24+
# If we set it afterwards, it should be the new value
25+
monkeypatch.setenv("OPENAI_API_KEY", "foo_bar_123")
26+
assert processor.api_key == "foo_bar_123"

0 commit comments

Comments
 (0)