From 7a16e635780882f30d7c6d7a19c1a882fde36900 Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Tue, 20 Oct 2026 17:49:59 +0200 Subject: [PATCH] Add OpenAI Responses API instrumentation --- CHANGELOG.md | 8 + README.md | 4 + docs/providers.md | 55 ++++++ examples/openai_responses_example.py | 101 +++++++++++ tests/compat/test_openai_compat.py | 146 ++++++++++++++++ tests/test_integrations_openai_responses.py | 141 +++++++++++++++ wildedge/integrations/openai.py | 180 +++++++++++++++++++- 7 files changed, 634 insertions(+), 1 deletion(-) create mode 100644 examples/openai_responses_example.py create mode 100644 tests/test_integrations_openai_responses.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bc71e07..7294af1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ under Unreleased and move into a version section at release time. ## Unreleased +### Added + +- The OpenAI integration now tracks `responses.create()` for synchronous and + asynchronous clients, including streaming. Records input/output token usage, + cached and reasoning tokens, response status or incomplete reason, resolved + model metadata, and time to first output delta for streams. Older OpenAI SDKs + without Responses remain supported. + ### Changed - The ultralytics integration now requires ultralytics 8.0.200 or later diff --git a/README.md b/README.md index b45abcf..4352e0a 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,10 @@ client libraries? Wrap the call in to get the same events: [llm_api_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/llm_api_example.py). +The `openai` integration also tracks `client.responses.create(...)`, including +async clients and `stream=True`. See [Responses tracking](docs/providers.md#responses-api) +for coverage and streaming behavior. + **Hub tracking** Pass `hubs=` to track model download provenance. Hubs are framework-agnostic and can be combined with any integration. diff --git a/docs/providers.md b/docs/providers.md index 8f78cea..5335150 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -50,3 +50,58 @@ wildedge.register_model(client, source="ollama", model_id="gemma-7b") providers omit them; they record as `None`, not `0`. - Streamed responses carry no usage unless you pass `stream_options={"include_usage": True}`. Timing and TTFT are unaffected. + + +## Responses API + +The `openai` integration instruments `client.responses.create()` and +`await client.responses.create()`, with or without `stream=True`. Enable it +before constructing the OpenAI client, as with Chat Completions. + +```python +import wildedge +from openai import OpenAI + +wildedge.init(integrations=["openai"]) +client = OpenAI() +response = client.responses.create(model="gpt-4o-mini", input="Say hello") +print(response.output_text) +wildedge.flush() +``` + +Usage comes from Responses' `input_tokens` / `output_tokens`, including cached +input and reasoning tokens when provided. The stop reason is the response +status, or the incomplete reason such as `max_output_tokens`. Failed responses +are recorded as unsuccessful. No prompt or response text is uploaded by this +adapter. String input and simple user messages provide text input metadata; +input iterators are passed through without being consumed by instrumentation. + +For streams, consume the iterator to exhaustion to record the terminal response +and its usage. Time to first output ignores lifecycle events and measures the +first nonempty text, refusal, function argument, or audio delta. Streams without +a terminal response do not produce a successful inference event. Early closure, +cancellation, background response polling, and individual tool spans are outside +this initial coverage. API exceptions retain their original behavior and use +the same error tracking as Chat Completions. + +OpenAI-compatible hosts must implement the Responses endpoint to use this path. +Older OpenAI SDK versions without a `responses` resource continue to support +Chat Completions. + + +### End-to-end check + +From the SDK root, with `OPENAI_API_KEY` and `WILDEDGE_DSN` set: + +```bash +uv run examples/openai_responses_example.py +``` + +This uses the local SDK checkout and makes four small, billable requests: +sync, sync streaming, async, and async streaming. Set `OPENAI_MODEL` to override +the default `gpt-4o-mini`. The script checks completion and usage, prints a +unique `responses-e2e-...` run ID, and closes the SDK with a 15-second deadline. +In WildEdge, locate that run and verify four inference events beneath the four +named spans, with input/output token usage and first-output timing on the two +streams. Provider checks alone do not prove telemetry delivery; confirm these +events in the dashboard. diff --git a/examples/openai_responses_example.py b/examples/openai_responses_example.py new file mode 100644 index 0000000..1ae6baa --- /dev/null +++ b/examples/openai_responses_example.py @@ -0,0 +1,101 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["wildedge-sdk", "openai>=1.66.0"] +# +# [tool.uv.sources] +# wildedge-sdk = { path = "..", editable = true } +# /// +"""Exercise all four Responses paths against OpenAI and WildEdge. + +From the SDK root: + uv run examples/openai_responses_example.py + +Requires OPENAI_API_KEY and WILDEDGE_DSN. Optionally set OPENAI_MODEL. +Makes four small, billable API calls. Find the printed run ID in WildEdge. +""" + +from __future__ import annotations + +import asyncio +import os +import uuid + +from openai import AsyncOpenAI, OpenAI + +import wildedge + +PROMPT = "Reply with exactly: Hello from Responses" +MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o-mini") + + +def check_response(result: object, label: str) -> None: + if result.status != "completed" or not result.output_text: + raise RuntimeError(f"{label}: response did not complete with text") + if result.usage is None: + raise RuntimeError(f"{label}: provider returned no usage") + print( + f"{label}: completed; input={result.usage.input_tokens}, output={result.usage.output_tokens}" + ) + + +def run_sync() -> None: + with OpenAI() as client: + with wildedge.span(kind="agent_step", name="responses-sync"): + result = client.responses.create( + model=MODEL, input=PROMPT, max_output_tokens=64 + ) + check_response(result, "sync") + with wildedge.span(kind="agent_step", name="responses-sync-stream"): + terminal = None + with client.responses.create( + model=MODEL, input=PROMPT, max_output_tokens=64, stream=True + ) as stream: + for event in stream: + if event.type == "response.completed": + terminal = event.response + if terminal is None: + raise RuntimeError("sync stream: missing completed response") + check_response(terminal, "sync stream") + + +async def run_async() -> None: + async with AsyncOpenAI() as client: + with wildedge.span(kind="agent_step", name="responses-async"): + result = await client.responses.create( + model=MODEL, input=PROMPT, max_output_tokens=64 + ) + check_response(result, "async") + with wildedge.span(kind="agent_step", name="responses-async-stream"): + terminal = None + async with await client.responses.create( + model=MODEL, input=PROMPT, max_output_tokens=64, stream=True + ) as stream: + async for event in stream: + if event.type == "response.completed": + terminal = event.response + if terminal is None: + raise RuntimeError("async stream: missing completed response") + check_response(terminal, "async stream") + + +def main() -> None: + missing = [ + key for key in ("OPENAI_API_KEY", "WILDEDGE_DSN") if not os.environ.get(key) + ] + if missing: + raise SystemExit("Set required environment variables: " + ", ".join(missing)) + run_id = f"responses-e2e-{uuid.uuid4().hex[:12]}" + print(f"Run ID: {run_id}") + sdk = wildedge.init(integrations=["openai"], app_version="responses-e2e") + try: + with wildedge.trace(run_id=run_id): + run_sync() + asyncio.run(run_async()) + finally: + sdk.close(timeout=15) + print("Provider checks passed. SDK shutdown finished; verify delivery in WildEdge.") + print("Expect four inference events under this run, one beneath each named span.") + + +if __name__ == "__main__": + main() diff --git a/tests/compat/test_openai_compat.py b/tests/compat/test_openai_compat.py index 925686f..a3c836e 100644 --- a/tests/compat/test_openai_compat.py +++ b/tests/compat/test_openai_compat.py @@ -1,8 +1,11 @@ from __future__ import annotations import json +import runpy +from pathlib import Path import openai +import pytest from conftest import sdk_http_module httpx = sdk_http_module("openai") @@ -116,3 +119,146 @@ def test_api_error_is_tracked(compat_client): error = compat_client.one("error") assert error["error"]["http_status"] == 429 assert error["error"]["provider_error_code"] == "rate_limit_exceeded" + + +RESPONSE = { + "id": "resp-compat", + "object": "response", + "created_at": 1700000000, + "model": "gpt-4o-mini", + "status": "completed", + "error": None, + "incomplete_details": None, + "output": [], + "parallel_tool_calls": True, + "tools": [], + "tool_choice": "auto", + "usage": { + "input_tokens": 9, + "output_tokens": 2, + "total_tokens": 11, + "input_tokens_details": {"cached_tokens": 3}, + "output_tokens_details": {"reasoning_tokens": 1}, + }, +} + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("streaming", [False, True]) +async def test_responses_is_tracked(compat_client, asynchronous, streaming): + compat_client.instrument("openai") + with openai.OpenAI(api_key="sk-compat") as probe: + if not hasattr(probe, "responses"): + return # The minimum supported openai version predates Responses. + + def handler(request): + assert request.url.path == "/v1/responses" + if not streaming: + return httpx.Response(200, json=RESPONSE) + events = [ + { + "type": "response.created", + "sequence_number": 0, + "response": {**RESPONSE, "status": "in_progress", "usage": None}, + }, + { + "type": "response.output_text.delta", + "sequence_number": 1, + "item_id": "msg-1", + "output_index": 0, + "content_index": 0, + "delta": "Hi", + "logprobs": [], + }, + {"type": "response.completed", "sequence_number": 2, "response": RESPONSE}, + ] + body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events) + return httpx.Response( + 200, text=body, headers={"content-type": "text/event-stream"} + ) + + if asynchronous: + client = openai.AsyncOpenAI( + api_key="sk-compat", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) + async with client: + result = await client.responses.create( + model="gpt-4o-mini", input="Say hello", stream=streaming + ) + if streaming: + assert [e.type async for e in result][-1] == "response.completed" + else: + assert result.id == RESPONSE["id"] + else: + with _client(handler) as client: + result = client.responses.create( + model="gpt-4o-mini", input="Say hello", stream=streaming + ) + if streaming: + assert [e.type for e in result][-1] == "response.completed" + else: + assert result.id == RESPONSE["id"] + event = compat_client.one("inference") + assert event["model_id"] == "gpt-4o-mini" + output = event["inference"]["output_meta"] + assert output["tokens_in"] == 9 + assert output["tokens_out"] == 2 + assert output["cached_input_tokens"] == 3 + assert output["reasoning_tokens_out"] == 1 + assert output["stop_reason"] == "completed" + + +async def test_responses_example(compat_client): + compat_client.instrument("openai") + with openai.OpenAI(api_key="sk-compat") as probe: + if not hasattr(probe, "responses"): + return + example = runpy.run_path( + str(Path(__file__).parents[2] / "examples" / "openai_responses_example.py") + ) + payload = { + **RESPONSE, + "output": [ + { + "id": "msg-1", + "type": "message", + "role": "assistant", + "status": "completed", + "content": [ + { + "type": "output_text", + "text": "Hello from Responses", + "annotations": [], + } + ], + } + ], + } + + def handler(request): + if not json.loads(request.content).get("stream"): + return httpx.Response(200, json=payload) + event = { + "type": "response.completed", + "sequence_number": 0, + "response": payload, + } + return httpx.Response( + 200, + text=f"event: response.completed\ndata: {json.dumps(event)}\n\n", + headers={"content-type": "text/event-stream"}, + ) + + example["run_sync"].__globals__["OpenAI"] = lambda: _client(handler) + example["run_async"].__globals__["AsyncOpenAI"] = lambda: openai.AsyncOpenAI( + api_key="sk-compat", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) + with compat_client.trace(run_id="responses-example-test"): + example["run_sync"]() + await example["run_async"]() + events = compat_client.of_type("inference") + assert len(events) == 4 + assert all(e["run_id"] == "responses-example-test" for e in events) + assert len({e["parent_span_id"] for e in events}) == 4 diff --git a/tests/test_integrations_openai_responses.py b/tests/test_integrations_openai_responses.py new file mode 100644 index 0000000..3d43655 --- /dev/null +++ b/tests/test_integrations_openai_responses.py @@ -0,0 +1,141 @@ +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from wildedge.integrations.openai import ( + make_responses_stream_callbacks, + wrap_async_responses, + wrap_sync_responses, +) + + +def response(status="completed"): + return SimpleNamespace( + model="resolved", + status=status, + error=None, + incomplete_details=SimpleNamespace(reason="max_output_tokens") + if status == "incomplete" + else None, + usage=SimpleNamespace( + input_tokens=12, + output_tokens=4, + input_tokens_details=SimpleNamespace(cached_tokens=3), + output_tokens_details=SimpleNamespace(reasoning_tokens=2), + ), + ) + + +class AsyncItems: + def __init__(self, items): + self.items = items + + async def __aiter__(self): + for item in self.items: + yield item + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("streaming", [False, True]) +@pytest.mark.parametrize("status", ["completed", "incomplete", "failed"]) +async def test_responses(asynchronous, streaming, status): + result = response(status) + events = [ + SimpleNamespace(type="response.created"), + SimpleNamespace(type="response.output_text.delta", delta="hello"), + SimpleNamespace(type=f"response.{status}", response=result), + ] + returned = ( + (AsyncItems(events) if asynchronous else iter(events)) if streaming else result + ) + original = (AsyncMock if asynchronous else MagicMock)(return_value=returned) + resource = SimpleNamespace(create=original) + handle = MagicMock() + client = SimpleNamespace( + closed=False, register_model=MagicMock(return_value=handle) + ) + (wrap_async_responses if asynchronous else wrap_sync_responses)( + resource, "openai", lambda: client + ) + call = resource.create(model="model", input="hello world", stream=streaming) + actual = await call if asynchronous else call + if streaming: + assert ( + [event async for event in actual] if asynchronous else list(actual) + ) == events + else: + assert actual is result + handle.track_inference.assert_called_once() + data = handle.track_inference.call_args.kwargs + assert data["success"] == (status != "failed") + assert data["input_meta"].char_count == 11 + output = data["output_meta"] + assert ( + output.tokens_in, + output.tokens_out, + output.cached_input_tokens, + output.reasoning_tokens_out, + ) == (12, 4, 3, 2) + assert output.stop_reason == ( + "max_output_tokens" if status == "incomplete" else status + ) + assert data["api_meta"].resolved_model_id == "resolved" + + +def test_ttft_and_once(monkeypatch): + handle = MagicMock() + on_chunk, on_done = make_responses_stream_callbacks(handle, [], 0) + on_chunk(SimpleNamespace(type="response.created")) + monkeypatch.setattr("wildedge.integrations.openai.elapsed_ms", lambda _: 42) + on_chunk(SimpleNamespace(type="response.output_text.delta", delta="hi")) + on_chunk(SimpleNamespace(type="response.completed", response=response())) + on_done(100, 1) + on_done(101, 1) + handle.track_inference.assert_called_once() + assert ( + handle.track_inference.call_args.kwargs["output_meta"].time_to_first_token_ms + == 42 + ) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_error_and_closed_client(asynchronous): + error = TimeoutError("timeout") + original = (AsyncMock if asynchronous else MagicMock)(side_effect=error) + resource = SimpleNamespace(create=original) + handle = MagicMock() + client = SimpleNamespace( + closed=False, register_model=MagicMock(return_value=handle) + ) + (wrap_async_responses if asynchronous else wrap_sync_responses)( + resource, "openai", lambda: client + ) + + async def invoke(): + call = resource.create(model="model", input="hello") + return await call if asynchronous else call + + with pytest.raises(TimeoutError) as caught: + await invoke() + assert caught.value is error + handle.track_error.assert_called_once() + handle.track_inference.assert_not_called() + client.closed = True + original.side_effect = None + original.return_value = "unchanged" + call = resource.create(model="model", input="hello") + assert (await call if asynchronous else call) == "unchanged" + assert client.register_model.call_count == 1 + + +def test_unfinished_and_error_streams(): + handle = MagicMock() + on_chunk, on_done = make_responses_stream_callbacks(handle, [], 0) + on_chunk(SimpleNamespace(type="response.created")) + on_done(100, 1) + handle.track_inference.assert_not_called() + on_chunk(SimpleNamespace(type="error", code="server_error")) + on_done(100, 1) + handle.track_error.assert_called_once() + handle.track_inference.assert_not_called() diff --git a/wildedge/integrations/openai.py b/wildedge/integrations/openai.py index 4ced640..a639951 100644 --- a/wildedge/integrations/openai.py +++ b/wildedge/integrations/openai.py @@ -249,6 +249,168 @@ async def patched_create(*args, **kwargs): completions.create = patched_create # type: ignore[attr-defined] +def responses_messages(value: object) -> list: + """Normalize text inputs without consuming arbitrary input iterables.""" + if isinstance(value, str): + return [{"role": "user", "content": value}] + return value if isinstance(value, list) else [] + + +def build_responses_output_meta( + response: object, duration_ms: int +) -> GenerationOutputMeta: + usage = getattr(response, "usage", None) + tokens_out = getattr(usage, "output_tokens", None) + status = getattr(response, "status", None) + reason = getattr(getattr(response, "incomplete_details", None), "reason", None) + return GenerationOutputMeta( + tokens_in=getattr(usage, "input_tokens", None), + tokens_out=tokens_out, + cached_input_tokens=getattr( + getattr(usage, "input_tokens_details", None), "cached_tokens", None + ), + reasoning_tokens_out=getattr( + getattr(usage, "output_tokens_details", None), "reasoning_tokens", None + ), + tokens_per_second=round(tokens_out / duration_ms * 1000, 1) + if duration_ms > 0 and tokens_out + else None, + stop_reason=reason or status, + ) + + +def record_response( + handle: ModelHandle, + response: object, + messages: list, + duration: int, + ttft_ms: int | None = None, +) -> None: + if getattr(response, "status", None) in ("queued", "in_progress"): + return + output = build_responses_output_meta(response, duration) + output.time_to_first_token_ms = ttft_ms + error = getattr(response, "error", None) + handle.track_inference( + duration_ms=duration, + input_modality="text", + output_modality="generation", + success=getattr(response, "status", None) != "failed" and error is None, + error_code=getattr(error, "code", None), + input_meta=build_input_meta(messages, output.tokens_in), + output_meta=output, + api_meta=build_api_meta(response), + ) + + +def make_responses_stream_callbacks( + handle: ModelHandle, messages: list, t0: float +) -> tuple: + response = None + ttft = None + recorded = False + + def on_chunk(chunk: object) -> None: + nonlocal response, ttft, recorded + event_type = getattr(chunk, "type", "") + if ( + event_type + in ( + "response.output_text.delta", + "response.refusal.delta", + "response.function_call_arguments.delta", + "response.output_audio.delta", + ) + and getattr(chunk, "delta", None) + and ttft is None + ): + ttft = elapsed_ms(t0) + if event_type in ( + "response.completed", + "response.incomplete", + "response.failed", + ): + response = getattr(chunk, "response", None) + elif event_type == "error" and not recorded: + handle.track_error( + error_code=getattr(chunk, "code", None) or "PROVIDER_ERROR", + duration_ms=elapsed_ms(t0), + ) + recorded = True + + def on_done(duration_ms: int, _first_event_ms: int | None) -> None: + nonlocal recorded + if response is not None and not recorded: + recorded = True + record_response(handle, response, messages, duration_ms, ttft) + + return on_chunk, on_done + + +def wrap_sync_responses(responses: object, source: str, client_ref: object) -> None: + original_create = responses.create + model_handles: dict[str, ModelHandle] = {} + + @functools.wraps(original_create) + def patched_create(*args, **kwargs): + client = client_ref() + model_id = kwargs.get("model") + if client is None or client.closed or not model_id: + return original_create(*args, **kwargs) + handle = resolve_handle(model_id, responses, model_handles, client, source) + t0 = time.perf_counter() + try: + result = original_create(*args, **kwargs) + except Exception as exc: + if handle is not None: + track_api_error(handle, exc, elapsed_ms(t0)) + raise + if handle is not None: + try: + messages = responses_messages(kwargs.get("input")) + if kwargs.get("stream"): + callbacks = make_responses_stream_callbacks(handle, messages, t0) + return SyncStreamWrapper(result, handle, t0, *callbacks) + record_response(handle, result, messages, elapsed_ms(t0)) + except Exception as exc: + debug_openai_failure("responses tracking", exc) + return result + + responses.create = patched_create + + +def wrap_async_responses(responses: object, source: str, client_ref: object) -> None: + original_create = responses.create + model_handles: dict[str, ModelHandle] = {} + + @functools.wraps(original_create) + async def patched_create(*args, **kwargs): + client = client_ref() + model_id = kwargs.get("model") + if client is None or client.closed or not model_id: + return await original_create(*args, **kwargs) + handle = resolve_handle(model_id, responses, model_handles, client, source) + t0 = time.perf_counter() + try: + result = await original_create(*args, **kwargs) + except Exception as exc: + if handle is not None: + track_api_error(handle, exc, elapsed_ms(t0)) + raise + if handle is not None: + try: + messages = responses_messages(kwargs.get("input")) + if kwargs.get("stream"): + callbacks = make_responses_stream_callbacks(handle, messages, t0) + return AsyncStreamWrapper(result, handle, t0, *callbacks) + record_response(handle, result, messages, elapsed_ms(t0)) + except Exception as exc: + debug_openai_failure("responses tracking", exc) + return result + + responses.create = patched_create + + class OpenAIExtractor(BaseExtractor): def can_handle(self, obj: object) -> bool: return type(obj).__name__ in ( @@ -256,6 +418,8 @@ def can_handle(self, obj: object) -> bool: "AsyncOpenAI", "Completions", "AsyncCompletions", + "Responses", + "AsyncResponses", ) def extract_info( @@ -280,7 +444,7 @@ def install_hooks(self, obj: object, handle: ModelHandle) -> None: @classmethod def install_auto_load_patch(cls, client_ref: object) -> None: - """Patch openai.OpenAI and openai.AsyncOpenAI to wrap chat.completions.create.""" + """Patch new OpenAI clients to track Chat Completions and Responses.""" global _openai_patched if _openai_patched or _openai is None: return @@ -312,6 +476,13 @@ def patched_sync_init(self_inner, *args, **kwargs): # type: ignore[no-untyped-d ) except Exception as exc: debug_openai_failure("sync client wrap", exc) + if hasattr(self_inner, "responses"): + try: + wrap_sync_responses( + self_inner.responses, source, client_ref + ) + except Exception as exc: + debug_openai_failure("sync responses wrap", exc) def patched_async_init(self_inner, *args, **kwargs): # type: ignore[no-untyped-def] original_async_init(self_inner, *args, **kwargs) @@ -326,6 +497,13 @@ def patched_async_init(self_inner, *args, **kwargs): # type: ignore[no-untyped- ) except Exception as exc: debug_openai_failure("async client wrap", exc) + if hasattr(self_inner, "responses"): + try: + wrap_async_responses( + self_inner.responses, source, client_ref + ) + except Exception as exc: + debug_openai_failure("async responses wrap", exc) patched_sync_init.__wildedge_patch_name__ = OPENAI_INIT_PATCH_NAME # type: ignore[attr-defined] patched_sync_init.__wildedge_original_call__ = original_sync_init # type: ignore[attr-defined]