Skip to content

Commit ca1f3d4

Browse files
committed
Add OpenAI embeddings instrumentation
1 parent 4471b15 commit ca1f3d4

8 files changed

Lines changed: 406 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ under Unreleased and move into a version section at release time.
55

66
## Unreleased
77

8+
### Added
9+
10+
- OpenAI sync and async `embeddings.create()` instrumentation records latency,
11+
input token usage, batch size, vector dimensions, model metadata and errors.
12+
Embedding vectors and raw inputs are never attached by this adapter.
13+
`EmbeddingOutputMeta` now accepts optional `tokens_in` for analytics.
14+
815
### Changed
916

1017
- The ultralytics integration now requires ultralytics 8.0.200 or later

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ client libraries? Wrap the call in
115115
to get the same events:
116116
[llm_api_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/llm_api_example.py).
117117

118+
The `openai` integration also tracks sync and async `embeddings.create()` calls.
119+
See [Embeddings](docs/providers.md#embeddings) and the
120+
[example](examples/openai_embeddings_example.py).
121+
118122
**Hub tracking**
119123

120124
Pass `hubs=` to track model download provenance. Hubs are framework-agnostic and can be combined with any integration.

‎docs/providers.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,35 @@ wildedge.register_model(client, source="ollama", model_id="gemma-7b")
5050
providers omit them; they record as `None`, not `0`.
5151
- Streamed responses carry no usage unless you pass
5252
`stream_options={"include_usage": True}`. Timing and TTFT are unaffected.
53+
54+
55+
## Embeddings
56+
57+
The `openai` integration also tracks sync and async `client.embeddings.create()`
58+
calls. Enable instrumentation before constructing the client. OpenAI-compatible
59+
providers work through the same integration if they implement the embeddings
60+
endpoint.
61+
62+
Records latency, resolved model, input token usage, batch size, and dimensions.
63+
Text, batches of strings, token ID arrays, and batches of token ID arrays are
64+
supported. Arbitrary iterables pass through without instrumentation consuming
65+
them; their batch size is omitted. Dimensions come from the returned vector
66+
length, or float32 byte length for explicit base64 output. Usage comes from the
67+
provider, not a local tokenizer. Both float and base64 vectors remain in the
68+
application response and are never included in telemetry. Raw inputs are also
69+
not uploaded by this adapter.
70+
71+
Input usage is recorded in `input_meta.token_count` and `output_meta.tokens_in`
72+
so existing analytics can query it. Embeddings do not emit generated-token
73+
counts, throughput, or TTFT. API exceptions use the existing error tracking.
74+
75+
With `OPENAI_API_KEY` and `WILDEDGE_DSN` configured, run from the SDK root:
76+
77+
```bash
78+
uv run examples/openai_embeddings_example.py
79+
```
80+
81+
This makes two small billable calls, one sync and one async. Find the printed
82+
run ID in WildEdge and verify two inference events, each linked to its named
83+
span, with batch size 2, dimensions, and input usage. Set
84+
`OPENAI_EMBEDDING_MODEL` to override `text-embedding-3-small`.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# /// script
2+
# requires-python = ">=3.10"
3+
# dependencies = ["wildedge-sdk", "openai>=1.30.0"]
4+
#
5+
# [tool.uv.sources]
6+
# wildedge-sdk = { path = "..", editable = true }
7+
# ///
8+
"""Run two small billable embedding calls; requires OPENAI_API_KEY and WILDEDGE_DSN.
9+
10+
From the SDK root: uv run examples/openai_embeddings_example.py
11+
Optionally set OPENAI_EMBEDDING_MODEL. Find the printed run ID in WildEdge.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import asyncio
17+
import os
18+
import uuid
19+
20+
from openai import AsyncOpenAI, OpenAI
21+
22+
import wildedge
23+
24+
MODEL = os.environ.get("OPENAI_EMBEDDING_MODEL", "text-embedding-3-small")
25+
INPUT = ["Hello from WildEdge", "Embedding instrumentation check"]
26+
27+
28+
def check_result(result: object) -> None:
29+
if len(result.data) != len(INPUT) or not result.data[0].embedding:
30+
raise RuntimeError("Expected two nonempty embeddings")
31+
if result.usage is None:
32+
raise RuntimeError("Provider returned no usage")
33+
print(
34+
f"Completed: batch={len(result.data)}, dimensions={len(result.data[0].embedding)}, input_tokens={result.usage.prompt_tokens}"
35+
)
36+
37+
38+
def run_sync() -> None:
39+
with OpenAI() as client, wildedge.span(kind="agent_step", name="embeddings-sync"):
40+
check_result(
41+
client.embeddings.create(model=MODEL, input=INPUT, encoding_format="float")
42+
)
43+
44+
45+
async def run_async() -> None:
46+
async with AsyncOpenAI() as client:
47+
with wildedge.span(kind="agent_step", name="embeddings-async"):
48+
check_result(
49+
await client.embeddings.create(
50+
model=MODEL, input=INPUT, encoding_format="float"
51+
)
52+
)
53+
54+
55+
def main() -> None:
56+
missing = [
57+
key for key in ("OPENAI_API_KEY", "WILDEDGE_DSN") if not os.environ.get(key)
58+
]
59+
if missing:
60+
raise SystemExit("Set required environment variables: " + ", ".join(missing))
61+
run_id = "embeddings-e2e-" + uuid.uuid4().hex[:12]
62+
print(f"Run ID: {run_id}")
63+
sdk = wildedge.init(integrations=["openai"], app_version="embeddings-e2e")
64+
try:
65+
with wildedge.trace(run_id=run_id):
66+
run_sync()
67+
asyncio.run(run_async())
68+
finally:
69+
sdk.close(timeout=15)
70+
print(
71+
"Provider checks passed. Verify two inference events and two spans in WildEdge."
72+
)
73+
74+
75+
if __name__ == "__main__":
76+
main()

‎tests/compat/test_openai_compat.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import json
44

55
import openai
6+
import pytest
67
from conftest import sdk_http_module
78

89
httpx = sdk_http_module("openai")
@@ -116,3 +117,61 @@ def test_api_error_is_tracked(compat_client):
116117
error = compat_client.one("error")
117118
assert error["error"]["http_status"] == 429
118119
assert error["error"]["provider_error_code"] == "rate_limit_exceeded"
120+
121+
122+
@pytest.mark.parametrize("asynchronous", [False, True])
123+
@pytest.mark.parametrize("encoding", ["float", "base64"])
124+
async def test_embeddings_is_tracked(compat_client, asynchronous, encoding):
125+
compat_client.instrument("openai")
126+
127+
def handler(request):
128+
assert request.url.path == "/v1/embeddings"
129+
return httpx.Response(
130+
200,
131+
json={
132+
"object": "list",
133+
"model": "text-embedding-3-small",
134+
"data": [
135+
{
136+
"object": "embedding",
137+
"index": i,
138+
"embedding": [0.25, 0.5, 0.75]
139+
if encoding == "float"
140+
else "AACAPgAAAD8AAEA/",
141+
}
142+
for i in range(2)
143+
],
144+
"usage": {"prompt_tokens": 7, "total_tokens": 7},
145+
},
146+
)
147+
148+
if asynchronous:
149+
client = openai.AsyncOpenAI(
150+
api_key="sk-compat",
151+
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
152+
)
153+
async with client:
154+
result = await client.embeddings.create(
155+
model="text-embedding-3-small",
156+
input=["hello", "world"],
157+
encoding_format=encoding,
158+
)
159+
else:
160+
with _client(handler) as client:
161+
result = client.embeddings.create(
162+
model="text-embedding-3-small",
163+
input=["hello", "world"],
164+
encoding_format=encoding,
165+
)
166+
assert len(result.data) == 2
167+
event = compat_client.one("inference")
168+
inference = event["inference"]
169+
assert inference["batch_size"] == 2
170+
assert inference["input_meta"]["token_count"] == 7
171+
assert inference["output_meta"] == {
172+
"task": "embedding",
173+
"dimensions": 3,
174+
"tokens_in": 7,
175+
}
176+
assert inference["api_meta"]["resolved_model_id"] == "text-embedding-3-small"
177+
assert "embedding" not in inference["output_meta"]
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
from types import SimpleNamespace
2+
from unittest.mock import AsyncMock, MagicMock
3+
4+
import pytest
5+
6+
from wildedge.integrations.openai import wrap_async_embeddings, wrap_sync_embeddings
7+
8+
9+
@pytest.mark.parametrize("asynchronous", [False, True])
10+
@pytest.mark.parametrize(
11+
("value", "batch_size", "chars"),
12+
[
13+
("hello", 1, 5),
14+
(["hello", "world"], 2, 10),
15+
([1, 2, 3], 1, None),
16+
([[1, 2], [3]], 2, None),
17+
],
18+
)
19+
async def test_metadata_and_passthrough(asynchronous, value, batch_size, chars):
20+
result = SimpleNamespace(
21+
model="resolved-model",
22+
usage=SimpleNamespace(prompt_tokens=7),
23+
data=[SimpleNamespace(embedding=[0.1, 0.2, 0.3])],
24+
)
25+
resource = SimpleNamespace(
26+
create=(AsyncMock if asynchronous else MagicMock)(return_value=result)
27+
)
28+
handle = MagicMock()
29+
client = SimpleNamespace(
30+
closed=False, register_model=MagicMock(return_value=handle)
31+
)
32+
(wrap_async_embeddings if asynchronous else wrap_sync_embeddings)(
33+
resource, "openai", lambda: client
34+
)
35+
call = resource.create(model="model", input=value)
36+
assert (await call if asynchronous else call) is result
37+
handle.track_inference.assert_called_once()
38+
event = handle.track_inference.call_args.kwargs
39+
assert event["batch_size"] == batch_size
40+
assert event["input_meta"].token_count == 7
41+
assert event["input_meta"].char_count == chars
42+
assert event["output_meta"].tokens_in == 7
43+
assert event["output_meta"].dimensions == 3
44+
assert event["api_meta"].resolved_model_id == "resolved-model"
45+
assert "hello" not in str(event)
46+
client.closed = True
47+
call = resource.create(model="model", input=value)
48+
assert (await call if asynchronous else call) is result
49+
assert handle.track_inference.call_count == 1
50+
51+
52+
@pytest.mark.parametrize("asynchronous", [False, True])
53+
async def test_error_and_telemetry_failure(asynchronous):
54+
original = (AsyncMock if asynchronous else MagicMock)(
55+
side_effect=TimeoutError("timeout")
56+
)
57+
resource = SimpleNamespace(create=original)
58+
handle = MagicMock()
59+
client = SimpleNamespace(
60+
closed=False, register_model=MagicMock(return_value=handle)
61+
)
62+
(wrap_async_embeddings if asynchronous else wrap_sync_embeddings)(
63+
resource, "openai", lambda: client
64+
)
65+
66+
async def invoke():
67+
call = resource.create(model="model", input="hello")
68+
return await call if asynchronous else call
69+
70+
with pytest.raises(TimeoutError, match="timeout"):
71+
await invoke()
72+
handle.track_error.assert_called_once()
73+
handle.track_inference.assert_not_called()
74+
result = SimpleNamespace(model="model", usage=None, data=[])
75+
original.side_effect = None
76+
original.return_value = result
77+
handle.track_inference.side_effect = RuntimeError("telemetry broken")
78+
assert await invoke() is result
79+
80+
81+
@pytest.mark.parametrize("asynchronous", [False, True])
82+
async def test_input_iterator_is_not_consumed(asynchronous):
83+
def values():
84+
raise AssertionError("instrumentation must not iterate inputs")
85+
yield "unreachable"
86+
87+
result = SimpleNamespace(model="model", usage=None, data=[])
88+
resource = SimpleNamespace(
89+
create=(AsyncMock if asynchronous else MagicMock)(return_value=result)
90+
)
91+
handle = MagicMock()
92+
client = SimpleNamespace(
93+
closed=False, register_model=MagicMock(return_value=handle)
94+
)
95+
(wrap_async_embeddings if asynchronous else wrap_sync_embeddings)(
96+
resource, "openai", lambda: client
97+
)
98+
call = resource.create(model="model", input=values())
99+
assert (await call if asynchronous else call) is result
100+
event = handle.track_inference.call_args.kwargs
101+
assert event["batch_size"] is None
102+
assert event["output_meta"].dimensions is None

‎wildedge/events/inference.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,11 +275,14 @@ def to_dict(self) -> dict:
275275
class EmbeddingOutputMeta:
276276
task: str = "embedding"
277277
dimensions: int | None = None
278+
tokens_in: int | None = None
278279

279280
def to_dict(self) -> dict:
280281
d: dict[str, Any] = {"task": self.task}
281282
if self.dimensions is not None:
282283
d["dimensions"] = self.dimensions
284+
if self.tokens_in is not None:
285+
d["tokens_in"] = self.tokens_in
283286
return d
284287

285288

0 commit comments

Comments
 (0)