Repository navigation
Description
Package: temporalio-openai-agents 1.1.0 and main (5e91c26); also temporalio.contrib.openai_agents in temporalio 1.33.0 and 1.34.0.
What happens
The OpenAI Agents SDK lets a run or a trace choose its own tracing key:
RunConfig(tracing={"api_key": ...}) ("If you only need a different tracing key for a single run,
pass it via RunConfig") or trace(..., tracing={"api_key": ...}). The exporter sends each span
with its trace's key and falls back to OPENAI_API_KEY only when the span has none.
The plugin passes the current trace to Workflows and Activities in a header that holds only the
trace name, trace ID and span ID. The receiving side rebuilds the trace without the key, so the
spans made there are exported with that process's OPENAI_API_KEY:
- a run with its own key in a Workflow: the model call's generation span, which holds the prompt,
goes out with the Worker's key; - a Workflow started inside a keyed client trace: every Workflow and Activity span goes out with
the Worker's key.
Against OpenAI's trace ingest the key selects the account, so those spans land in another account,
and nothing reports it.
Reproduction
One file: a loopback fake answers Chat Completions and records the Authorization header with which
the framework's own exporter posts each span. It runs one Workflow with a run key, then one inside a
keyed client trace, on a Worker whose OPENAI_API_KEY is sk-worker-default, and exits 1 when a
span goes out with that key. Run it against a dev server as
python reproduce_issue.py <temporal-address> <free-port>.
"""Spans made in Activities lose the tracing key that a run or its trace chose.
python reproduce_issue.py <temporal-address> <free-port>
A loopback fake answers Chat Completions and records the key of each span the exporter posts.
The Worker's key is OPENAI_API_KEY=sk-worker-default. Exit 1 if a span goes out with it.
"""
import asyncio
import json
import os
import sys
import threading
from datetime import timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ADDRESS, PORT = sys.argv[1], int(sys.argv[2])
os.environ["OPENAI_BASE_URL"] = f"http://127.0.0.1:{PORT}/v1"
os.environ["OPENAI_API_KEY"] = "sk-worker-default"
from agents import Agent, OpenAIProvider, RunConfig, Runner, flush_traces, trace # noqa: E402
from agents.tracing.processors import default_exporter # noqa: E402
from temporalio import workflow # noqa: E402
from temporalio.client import Client # noqa: E402
from temporalio.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin # noqa: E402
from temporalio.worker import Worker # noqa: E402
SPANS: list[tuple[str, str]] = [] # (span type and name, key it was exported with)
REPLY = {"id": "c", "object": "chat.completion", "created": 0, "model": "m", "choices": [
{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "hi"}}]}
class Fake(BaseHTTPRequestHandler):
def log_message(self, *args) -> None:
pass
def do_POST(self) -> None: # noqa: N802
body = json.loads(self.rfile.read(int(self.headers["content-length"])))
if self.path.endswith("/traces/ingest"):
key = self.headers["authorization"].removeprefix("Bearer ")
SPANS.extend((f"{i['span_data']['type']}:{i['span_data'].get('name', '')}".rstrip(":"), key)
for i in body["data"] if i["object"] == "trace.span")
data = json.dumps({} if self.path.endswith("/traces/ingest") else REPLY).encode()
self.send_response(200)
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
@workflow.defn(sandboxed=False)
class OneCall:
@workflow.run
async def run(self, key: str | None) -> str:
tracing = {"api_key": key} if key else None
result = await Runner.run(Agent(name="a", model="m"), "PROMPT", run_config=RunConfig(tracing=tracing))
return result.final_output
async def main() -> int:
threading.Thread(target=ThreadingHTTPServer(("127.0.0.1", PORT), Fake).serve_forever, daemon=True).start()
default_exporter().endpoint = f"http://127.0.0.1:{PORT}/v1/traces/ingest"
plugin = OpenAIAgentsPlugin(model_params=ModelActivityParameters(start_to_close_timeout=timedelta(seconds=20)),
model_provider=OpenAIProvider(use_responses=False))
client = await Client.connect(ADDRESS, plugins=[plugin])
async with Worker(client, task_queue="tracing-key", workflows=[OneCall]):
# 1. The run chooses its key with RunConfig(tracing=...).
await client.execute_workflow(OneCall.run, "sk-tracing-run", id="run-key", task_queue="tracing-key")
flush_traces()
print("run key: ", sorted(set(SPANS)))
run_key_spans = SPANS[:]
SPANS.clear()
# 2. The client trace chooses its key with trace(..., tracing=...).
with plugin.tracing_context(), trace("client", tracing={"api_key": "sk-tracing-trace"}):
await client.execute_workflow(OneCall.run, None, id="trace-key", task_queue="tracing-key")
flush_traces()
print("trace key:", sorted(set(SPANS)))
return 1 if any(key == "sk-worker-default" for _, key in run_key_spans + SPANS) else 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))
Output with temporalio-openai-agents 1.1.0 (openai-agents 0.22.0, openai 3.8.0, temporalio 1.33.0):
run key: [('agent:a', 'sk-tracing-run'), ('custom:task', 'sk-tracing-run'), ('custom:temporal:executeActivity', 'sk-worker-default'), ('custom:temporal:startActivity', 'sk-tracing-run'), ('custom:turn', 'sk-tracing-run'), ('generation', 'sk-worker-default')]
trace key: [('agent:a', 'sk-worker-default'), ('custom:task', 'sk-worker-default'), ('custom:temporal:executeActivity', 'sk-worker-default'), ('custom:temporal:executeWorkflow', 'sk-worker-default'), ('custom:temporal:startActivity', 'sk-worker-default'), ('custom:temporal:startWorkflow:OneCall', 'sk-tracing-trace'), ('custom:turn', 'sk-worker-default'), ('generation', 'sk-worker-default')]
exit=1
main at 5e91c26 gives the same result. Without Temporal, the same run and the same trace export
every span, including the generation span, with their own key.
Proposed fix
The header is stored in Event History, so it must not carry the key. Refuse such traces instead:
- In
OpenAIAgentsContextPropagationInterceptor.set_header_from_context, which every client and
Workflow outbound call uses, raiseValueErrorwhen the current trace has its own tracing key,
and say to set the key on every process withset_tracing_export_api_keyorOPENAI_API_KEY. - In Workflow code, gate the check with
workflow.patched("openai_agents.refuse-trace-tracing-key")
so a run that started before the fix and already made such a call keeps the old behavior and
replays. A run that started before the fix but makes its first such call after the upgrade is
refused at that call; before upgrading, let such runs finish or keep them on the earlier build
with Worker Versioning. - Document it in the README's "Tracing" section.
This is a breaking change for applications that use a per-run or per-trace key today: their Workflow
Task, or their client call, now fails until the key moves to process-wide settings. A branch with
the change, a regression test and a replay test is ready.
Activity