Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
55 changes: 55 additions & 0 deletions docs/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
101 changes: 101 additions & 0 deletions examples/openai_responses_example.py
Original file line number Diff line number Diff line change
@@ -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()
146 changes: 146 additions & 0 deletions tests/compat/test_openai_compat.py
Original file line number Diff line number Diff line change
@@ -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")
Expand Down Expand Up @@ -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
Loading
Loading