`BackendSpanExporter.api_key` was a `cached_property` over
`self._api_key or os.environ.get("OPENAI_API_KEY")`. Resolving it before
the variable existed cached `None`, so a key set afterwards, for example
by `load_dotenv()`, never took effect and every export kept logging
"OPENAI_API_KEY is not set, skipping trace export".
`api_key` is now a property that reads the explicit key once and falls
back to the environment only when it is missing. A key found in the
environment is kept, so a later change to the variable does not reroute
exports. A lookup that finds nothing stores nothing, so it cannot
discard a key that `set_api_key()` sets on another thread meanwhile.
A setter keeps `exporter.api_key = "..."` working, since public code
relies on assigning the attribute.
Co-authored-by: Justin Beckwith <jbeckwith@openai.com>
21 lines
634 B
Python
21 lines
634 B
Python
import pytest
|
|
|
|
from agents.tracing.processors import BackendSpanExporter
|
|
|
|
|
|
def test_set_api_key_preserves_env_fallback(monkeypatch: pytest.MonkeyPatch):
|
|
"""Test that set_api_key doesn't break environment variable fallback."""
|
|
monkeypatch.setenv("OPENAI_API_KEY", "env-key")
|
|
|
|
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.set_api_key("")
|
|
assert exporter.api_key == "env-key"
|