telemetry-dev 0.3.1__tar.gz → 0.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/PKG-INFO +174 -6
  2. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/README.md +173 -5
  3. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/pyproject.toml +1 -1
  4. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/pyproject.toml.orig +1 -1
  5. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/__init__.py +28 -0
  6. telemetry_dev-0.3.2/src/telemetry_dev/_api.py +203 -0
  7. telemetry_dev-0.3.2/src/telemetry_dev/_ci.py +136 -0
  8. telemetry_dev-0.3.2/src/telemetry_dev/_experiments.py +1138 -0
  9. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_prompts.py +232 -89
  10. telemetry_dev-0.3.2/src/telemetry_dev/_scores.py +181 -0
  11. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_semconv.py +2 -0
  12. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_serialize.py +5 -0
  13. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_spans.py +22 -4
  14. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/LICENSE +0 -0
  15. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_capture.py +0 -0
  16. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_client.py +0 -0
  17. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_config.py +0 -0
  18. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_context.py +0 -0
  19. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_export.py +0 -0
  20. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_logs.py +0 -0
  21. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_metrics.py +0 -0
  22. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_observe.py +0 -0
  23. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/_processor.py +0 -0
  24. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/otel.py +0 -0
  25. {telemetry_dev-0.3.1 → telemetry_dev-0.3.2}/src/telemetry_dev/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telemetry-dev
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics
5
5
  Keywords: telemetry,opentelemetry,llm,genai,tracing,observability
6
6
  Author: telemetry.dev
@@ -114,6 +114,8 @@ later `init()` generates a new ID. It is not persisted across processes.
114
114
  | `get_traceparent() -> str \| None` | W3C traceparent of the current context. |
115
115
  | `get_prompt(name, *, label=, version=, type="chat", cache_ttl_seconds=60, fallback=, api_key=, base_url=)` / `get_prompt_async(...)` | Fetch a prompt by label or version; see [Prompts](#prompts). |
116
116
  | `with_prompt(prompt)` | Context manager recording the prompt on each model call started inside. |
117
+ | `run_experiment(*, task, dataset=, name=, dataset_version=, split=, evaluators=, scorers=, min_scores=, runs_per_item=1, concurrency=4, metadata=, ci=, api_key=, base_url=)` / `run_experiment_async(...)` | Run your code on a dataset as an experiment; see [Experiments](#experiments). |
118
+ | `score(*, name, trace_id=, span_id=, session_id=, value=, label=, comment=, api_key=, base_url=)` / `score_async(...)` | Record a score on a trace, a span, or a session; see [Scores](#scores). |
117
119
  | `flush(timeout_s=10.0)` / `shutdown(timeout_s=10.0)` | Force-flush / tear down traces + logs + metrics. Shutdown also runs atexit unless `disable_atexit=True`. |
118
120
  | `TelemetrySpanProcessor` / `telemetry_dev.otel.create_telemetry_span_exporter` | Bring-your-own-OTel helpers (below). |
119
121
  | `MaskContext`, `Usage`, `SpanHandle`, `Client`, `NOT_GIVEN` | Supporting types. |
@@ -244,6 +246,13 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
244
246
  call returns it at once and fetches a new copy in a background thread. Only a call with no copy
245
247
  waits for a fetch, for 10 seconds at most, also when the network stops. Calls for the same
246
248
  prompt share one fetch. `get_prompt_async` runs the same function in a worker thread.
249
+ - A process that `os.fork()` makes keeps the copies of its parent. This includes a process of
250
+ `multiprocessing` with the `fork` start method. A call that starts in the child does not wait
251
+ for a fetch of the parent. If the call must fetch, it starts a new fetch.
252
+ - If a signal handler forks while a call waits for a fetch, that call continues in the child. No
253
+ thread of the child completes that fetch. Thus the call waits until 10 seconds after the start
254
+ of the fetch. Then the call returns the `fallback`, or raises `PromptError` with the code
255
+ `timeout`.
247
256
  - If a fetch fails, `get_prompt` returns the last copy that it fetched and reports the error
248
257
  through `on_error`. With no copy, it returns the `fallback` (`version` is `None` and
249
258
  `is_fallback` is `True`). With no fallback, it raises `PromptError` whose `code` tells why, for
@@ -257,8 +266,8 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
257
266
  without its prompt.
258
267
  - `get_prompt` uses the API key and base URL of an enabled `init()`, or `TELEMETRY_DEV_API_KEY`
259
268
  and `TELEMETRY_DEV_BASE_URL`, or its own `api_key` and `base_url`. It reads the same host that
260
- telemetry goes to, `https://api.telemetry.dev` by default. The key needs the read scope for
261
- prompts.
269
+ telemetry goes to, `https://api.telemetry.dev` by default. The key must have Read prompts in
270
+ its Access on the API keys page (the `prompts:read` scope).
262
271
  - When a label sends part of the traffic to a second version, each session keeps one version: the
263
272
  choice uses the session id of `propagate_attributes` (or of `session_mode="process"`). Without a
264
273
  session id, each call chooses at random.
@@ -276,9 +285,168 @@ ran in it, or before it started in the code that started it; with none, it recor
276
285
  for code that has not compiled in its own task. Model calls are the spans of type `generation`
277
286
  (operations `chat`, `text_completion`, and `generate_content`), including the spans of the provider
278
287
  integrations: OpenAI, Anthropic, Amazon Bedrock, Google GenAI, LiteLLM, and OpenRouter. Spans from
279
- other OpenTelemetry tracers do not get the attributes. A model call outside `with_prompt` does not
280
- get the attributes, even when it sends messages from `compile()`; with input capture on, the call
281
- still records those messages as its input.
288
+ other OpenTelemetry tracers do not get the attributes.
289
+
290
+ Outside `with_prompt`, those provider integrations record the prompt of the message dicts that
291
+ `compile()` returned. `compile()` of a chat prompt returns instances of a private `dict` subclass
292
+ that also hold its prompt and a copy of its variables and of each list in them. The objects in a
293
+ list are not copied, so a change to one of them after `compile()` changes the variables that a call
294
+ records. A chat call that sends such messages gets `td.prompt.name`, `td.prompt.version`, and
295
+ `td.prompt.label` of the newest `compile()` among them, also when input capture is off, and
296
+ `td.prompt.variables` when it is on. The SDK looks at the first 1000 and the last 1000 messages of
297
+ the call. A message from a placeholder variable keeps the prompt of its own, older `compile()`, so
298
+ it does not win over the `compile()` that put it in the list. A copy of a message (`dict()`,
299
+ `.copy()`, `copy.copy`, `copy.deepcopy`, pickle, JSON, `type(message)(message)`, or
300
+ `dataclasses.asdict`) and a new message with the same text do not hold the prompt, so a call that
301
+ sends only such messages gets no `td.prompt.*` attributes; with input capture on, the call still
302
+ records them as its input. Bedrock Converse and Google GenAI take another message shape: change the
303
+ compiled dicts in place, or use `with_prompt`. A text prompt compiles to a string, which cannot hold
304
+ its prompt: use `with_prompt`. `with_prompt` wins over the message. The integrations do it for OpenAI
305
+ chat completions and responses, Anthropic messages (for `messages.stream()`, at `__enter__`),
306
+ Bedrock Converse, Google GenAI `generate_content`, LiteLLM completion and responses, and OpenRouter
307
+ chat and responses, but not for Bedrock InvokeModel (its body is bytes), embeddings, images, audio,
308
+ video, or OpenAI Realtime. With an older `telemetry-dev` that has no `prompt_attributes_for`, a
309
+ provider integration records the prompt only in `with_prompt`.
310
+
311
+ A compiled message is a `dict` for `isinstance`, and its keys and its JSON (`json`, `orjson`,
312
+ pydantic) do not change. A check of the exact type (`type(message) is dict`), `yaml.safe_dump`,
313
+ and `marshal` reject it: give them `dict(message)`.
314
+
315
+ With input capture on in the client when `compile()` runs, a compiled message keeps the variables
316
+ of its `compile()` for 5 minutes. A call keeps them for 5 more minutes when the newest `compile()`
317
+ of the call is that one. After that time, a call records the prompt without
318
+ `td.prompt.variables`, and the SDK removes the variables from the message, also when you keep the
319
+ message. Other compiles do not change this time. Thus a chat history keeps the variables of the
320
+ compiles of its last 5 minutes, and a guard prompt, a queue, or a compile in another thread before
321
+ the call does not remove them. A message that you compile one time and send in many calls keeps its
322
+ variables while a call names its `compile()` at least one time in 5 minutes. A call that sends only
323
+ messages of earlier turns records the prompt of the newest `compile()` among them, and its
324
+ variables when they are less than 5 minutes old. With input capture off, the message keeps no
325
+ variables.
326
+
327
+ For your own spans, `prompt_attributes_for(messages)` gives the attributes to pass as
328
+ `attributes`. It gives `{}` inside `with_prompt`, and a span with `capture_input=False` drops
329
+ `td.prompt.variables`. A model call whose parent is in `with_prompt` gets the prompt of the
330
+ `with_prompt` and none of the `td.prompt.*` attributes that you pass, at start or in `update`,
331
+ `end`, or `update_current_span`, also when its `parent` context comes from a `with_prompt` that the
332
+ call is not in.
333
+
334
+ ## Experiments
335
+
336
+ `run_experiment` runs your code on each item of a dataset that you manage in telemetry.dev, and
337
+ records the outputs and the scores as an experiment. The experiment page compares it with the
338
+ baseline of the dataset.
339
+
340
+ ```python
341
+ import telemetry_dev
342
+
343
+ telemetry_dev.init(environment="experiment")
344
+
345
+ result = telemetry_dev.run_experiment(
346
+ name="reply-v13-gpt-4o",
347
+ dataset="support-golden",
348
+ task=lambda item: reply_to_customer(item.input),
349
+ evaluators=["correctness", "helpfulness"],
350
+ scorers={"short": lambda output, item: len(output) < 600},
351
+ min_scores={"correctness": 0.9},
352
+ )
353
+ ```
354
+
355
+ - `run_experiment` reads the newest version of the dataset, or `dataset_version`, 100 items at a
356
+ time. With `split`, it runs only the items of that split. Then it makes the experiment, with a
357
+ name that telemetry.dev picks when you give no `name`.
358
+ - `task(item)` gets an `ExperimentItem`: `id`, `number`, `input`, `expected_output`, `metadata`,
359
+ `tags`, `split`, and `run_index`. Its return value is the output. A string stays as it is, and a
360
+ different value becomes JSON, cut to 100,000 UTF-16 units. A value that JSON cannot hold, such
361
+ as a dict that holds itself, gives no output. A task that raises fails only its item, and the
362
+ item records the type and the message of the exception.
363
+ - `concurrency` (1 to 100, default 4) threads run the items, each in a copy of the context of the
364
+ caller, so `propagate_attributes` around the call applies to each item. With `runs_per_item`
365
+ (default 1, at most 5), each item runs more than one time. Each run gets its own copy of the
366
+ item, so a task that changes its input does not change the next run. The pass rate and the mean
367
+ of each score use all runs.
368
+ - `run_experiment_async` takes async tasks and scorers. `concurrency` asyncio tasks run the items,
369
+ and the requests go in worker threads. A task that is not async runs on the event loop, so use
370
+ `run_experiment` for it. `run_experiment` raises `TypeError` for an async task or scorer.
371
+ - Each item run is a trace of its own, with the span `experiment <name>`. The SDK puts
372
+ `td.experiment.id` and `td.dataset.item_id` on each span of the run, also on the spans of the
373
+ provider integrations. Each run also gets its own session id,
374
+ `<experiment id>:<item id>:<run index>`, as `gen_ai.conversation.id`.
375
+ - Call `init(environment="experiment")` before the run. Pages, metrics, and alerts leave out the
376
+ `experiment` environment by default. In a different environment, `run_experiment` logs a
377
+ warning. Without an enabled client, the items record no traces and no cost.
378
+ - `evaluators` names evaluators of the project: LLM judges, code checks, and rules. telemetry.dev
379
+ runs them on the outputs. `scorers` run on your machine, after the span of the item ends. A
380
+ scorer returns `True` or `False` for a pass or a fail, a number, a label, or a mapping with
381
+ `value`, `label`, and `reason`. A scorer that raises, or returns a score that is not valid, gives
382
+ no score for that item and sends a `scorer_failed` error to `on_error`. A scorer cannot have the
383
+ name of an evaluator of the run, or the name `user_feedback`.
384
+ - `run_experiment` sends the outputs in batches of 100 items at most, and then waits up to 30
385
+ minutes for the server evaluators. Then it prints the scores and returns an `ExperimentResult`:
386
+ `status`, `check_status`, item counts, `scores` with the value, the baseline value, the change,
387
+ and the pass mark of each score, and the `url` of the experiment page.
388
+ - `min_scores` sets a pass mark for each score name: the lowest pass rate (0 to 1) of a pass/fail
389
+ score, or the lowest mean of a number score. A score under its mark fails the check.
390
+ - A failed request raises `ExperimentError` whose `code` tells why, for example
391
+ `dataset_not_found`, `dataset_empty`, `evaluator_not_found`, `insufficient_scope`,
392
+ `missing_api_key`, or `timeout`. A read of the dataset or the result, a post of outputs, and the
393
+ completion go again up to 2 times after a timeout, a network error, a 429, or a 5xx. The server
394
+ skips an item run that it has. The request that makes the experiment goes again only after a
395
+ 429, thus a lost response or a 503 cannot make a second experiment. When the run stops after it
396
+ made the experiment, also after Ctrl-C or a cancellation, `run_experiment` sends the completion
397
+ before it raises: telemetry.dev then ends the experiment with the item runs that it got, or fails
398
+ it when it got none.
399
+ - The key needs the `datasets:read` and `experiments:write` scopes. `run_experiment` uses the same
400
+ API key and base URL as `get_prompt`, or its own `api_key` and `base_url`. With
401
+ `environment="experiment"`, the key of the telemetry client must be for all environments or for
402
+ `experiment`: a key for another environment cannot send the traces of the items, and the items
403
+ then have no trace and no cost.
404
+
405
+ The outputs, the exceptions of failed tasks, the scorer reasons, and `metadata` go to telemetry.dev
406
+ and stay with the experiment, because they are its result. `capture_output`, `mask`, and the
407
+ capture setting of the environment in the project do not apply to them. They apply only to the
408
+ spans of the run.
409
+
410
+ ### CI mode
411
+
412
+ When the `CI` variable is `true` or `1`, or with `ci=True`, `run_experiment` raises when the check
413
+ fails (`check_failed`) or when the experiment does not complete (`experiment_failed`), so the
414
+ process exits with an error. The error has the `result`. In GitHub Actions, the experiment also
415
+ records the repository, the commit, the run URL, and the number, the title, and the URL of the pull
416
+ request. The commit of a pull request is its head commit.
417
+
418
+ The [experiment action](../../actions/experiment) runs your eval script in a workflow, and posts
419
+ the result on the pull request. It gives `run_experiment` the `dataset` input in
420
+ `TELEMETRY_DEV_EXPERIMENT_DATASET`, which must agree with the `dataset` of the script, and the
421
+ `min-scores` input in `TELEMETRY_DEV_EXPERIMENT_MIN_SCORES`, which wins over `min_scores` for the
422
+ same name.
423
+
424
+ ## Scores
425
+
426
+ `score` records a score on a trace, a span, or a session, for example the thumbs up or down of a
427
+ user on a reply:
428
+
429
+ ```python
430
+ import telemetry_dev
431
+
432
+ # When the app replies, keep the trace id of the reply with the message:
433
+ with telemetry_dev.start_span("reply") as span:
434
+ text = reply_to_customer(message)
435
+ trace_id = f"{span.span.get_span_context().trace_id:032x}"
436
+
437
+ # Later, when the user clicks thumbs down:
438
+ telemetry_dev.score(name="user_feedback", trace_id=trace_id, value=0, comment="Wrong amount")
439
+ ```
440
+
441
+ - Give `trace_id`, `session_id`, or the two, and a `span_id` of the trace for a score on one span.
442
+ Give `value`, `label`, or the two. `user_feedback` takes the value 1 for up or 0 for down, and
443
+ no label. A pass/fail score has the label `pass` with the value 1, or `fail` with 0.
444
+ - Like the telemetry functions, `score` never raises. It returns the id of the score, or `None`
445
+ after it sends a `ScoreError` to `on_error`. It checks the score before it sends it
446
+ (`invalid_score`). The trace id of a span from a client that is not enabled is all zeros, and
447
+ `score` reports it as `invalid_score`.
448
+ - `score` makes one request, with no retry. `score_async` runs it in a worker thread. The key
449
+ needs the `scores:write` scope.
282
450
 
283
451
  ## Auto-metrics
284
452
 
@@ -89,6 +89,8 @@ later `init()` generates a new ID. It is not persisted across processes.
89
89
  | `get_traceparent() -> str \| None` | W3C traceparent of the current context. |
90
90
  | `get_prompt(name, *, label=, version=, type="chat", cache_ttl_seconds=60, fallback=, api_key=, base_url=)` / `get_prompt_async(...)` | Fetch a prompt by label or version; see [Prompts](#prompts). |
91
91
  | `with_prompt(prompt)` | Context manager recording the prompt on each model call started inside. |
92
+ | `run_experiment(*, task, dataset=, name=, dataset_version=, split=, evaluators=, scorers=, min_scores=, runs_per_item=1, concurrency=4, metadata=, ci=, api_key=, base_url=)` / `run_experiment_async(...)` | Run your code on a dataset as an experiment; see [Experiments](#experiments). |
93
+ | `score(*, name, trace_id=, span_id=, session_id=, value=, label=, comment=, api_key=, base_url=)` / `score_async(...)` | Record a score on a trace, a span, or a session; see [Scores](#scores). |
92
94
  | `flush(timeout_s=10.0)` / `shutdown(timeout_s=10.0)` | Force-flush / tear down traces + logs + metrics. Shutdown also runs atexit unless `disable_atexit=True`. |
93
95
  | `TelemetrySpanProcessor` / `telemetry_dev.otel.create_telemetry_span_exporter` | Bring-your-own-OTel helpers (below). |
94
96
  | `MaskContext`, `Usage`, `SpanHandle`, `Client`, `NOT_GIVEN` | Supporting types. |
@@ -219,6 +221,13 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
219
221
  call returns it at once and fetches a new copy in a background thread. Only a call with no copy
220
222
  waits for a fetch, for 10 seconds at most, also when the network stops. Calls for the same
221
223
  prompt share one fetch. `get_prompt_async` runs the same function in a worker thread.
224
+ - A process that `os.fork()` makes keeps the copies of its parent. This includes a process of
225
+ `multiprocessing` with the `fork` start method. A call that starts in the child does not wait
226
+ for a fetch of the parent. If the call must fetch, it starts a new fetch.
227
+ - If a signal handler forks while a call waits for a fetch, that call continues in the child. No
228
+ thread of the child completes that fetch. Thus the call waits until 10 seconds after the start
229
+ of the fetch. Then the call returns the `fallback`, or raises `PromptError` with the code
230
+ `timeout`.
222
231
  - If a fetch fails, `get_prompt` returns the last copy that it fetched and reports the error
223
232
  through `on_error`. With no copy, it returns the `fallback` (`version` is `None` and
224
233
  `is_fallback` is `True`). With no fallback, it raises `PromptError` whose `code` tells why, for
@@ -232,8 +241,8 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
232
241
  without its prompt.
233
242
  - `get_prompt` uses the API key and base URL of an enabled `init()`, or `TELEMETRY_DEV_API_KEY`
234
243
  and `TELEMETRY_DEV_BASE_URL`, or its own `api_key` and `base_url`. It reads the same host that
235
- telemetry goes to, `https://api.telemetry.dev` by default. The key needs the read scope for
236
- prompts.
244
+ telemetry goes to, `https://api.telemetry.dev` by default. The key must have Read prompts in
245
+ its Access on the API keys page (the `prompts:read` scope).
237
246
  - When a label sends part of the traffic to a second version, each session keeps one version: the
238
247
  choice uses the session id of `propagate_attributes` (or of `session_mode="process"`). Without a
239
248
  session id, each call chooses at random.
@@ -251,9 +260,168 @@ ran in it, or before it started in the code that started it; with none, it recor
251
260
  for code that has not compiled in its own task. Model calls are the spans of type `generation`
252
261
  (operations `chat`, `text_completion`, and `generate_content`), including the spans of the provider
253
262
  integrations: OpenAI, Anthropic, Amazon Bedrock, Google GenAI, LiteLLM, and OpenRouter. Spans from
254
- other OpenTelemetry tracers do not get the attributes. A model call outside `with_prompt` does not
255
- get the attributes, even when it sends messages from `compile()`; with input capture on, the call
256
- still records those messages as its input.
263
+ other OpenTelemetry tracers do not get the attributes.
264
+
265
+ Outside `with_prompt`, those provider integrations record the prompt of the message dicts that
266
+ `compile()` returned. `compile()` of a chat prompt returns instances of a private `dict` subclass
267
+ that also hold its prompt and a copy of its variables and of each list in them. The objects in a
268
+ list are not copied, so a change to one of them after `compile()` changes the variables that a call
269
+ records. A chat call that sends such messages gets `td.prompt.name`, `td.prompt.version`, and
270
+ `td.prompt.label` of the newest `compile()` among them, also when input capture is off, and
271
+ `td.prompt.variables` when it is on. The SDK looks at the first 1000 and the last 1000 messages of
272
+ the call. A message from a placeholder variable keeps the prompt of its own, older `compile()`, so
273
+ it does not win over the `compile()` that put it in the list. A copy of a message (`dict()`,
274
+ `.copy()`, `copy.copy`, `copy.deepcopy`, pickle, JSON, `type(message)(message)`, or
275
+ `dataclasses.asdict`) and a new message with the same text do not hold the prompt, so a call that
276
+ sends only such messages gets no `td.prompt.*` attributes; with input capture on, the call still
277
+ records them as its input. Bedrock Converse and Google GenAI take another message shape: change the
278
+ compiled dicts in place, or use `with_prompt`. A text prompt compiles to a string, which cannot hold
279
+ its prompt: use `with_prompt`. `with_prompt` wins over the message. The integrations do it for OpenAI
280
+ chat completions and responses, Anthropic messages (for `messages.stream()`, at `__enter__`),
281
+ Bedrock Converse, Google GenAI `generate_content`, LiteLLM completion and responses, and OpenRouter
282
+ chat and responses, but not for Bedrock InvokeModel (its body is bytes), embeddings, images, audio,
283
+ video, or OpenAI Realtime. With an older `telemetry-dev` that has no `prompt_attributes_for`, a
284
+ provider integration records the prompt only in `with_prompt`.
285
+
286
+ A compiled message is a `dict` for `isinstance`, and its keys and its JSON (`json`, `orjson`,
287
+ pydantic) do not change. A check of the exact type (`type(message) is dict`), `yaml.safe_dump`,
288
+ and `marshal` reject it: give them `dict(message)`.
289
+
290
+ With input capture on in the client when `compile()` runs, a compiled message keeps the variables
291
+ of its `compile()` for 5 minutes. A call keeps them for 5 more minutes when the newest `compile()`
292
+ of the call is that one. After that time, a call records the prompt without
293
+ `td.prompt.variables`, and the SDK removes the variables from the message, also when you keep the
294
+ message. Other compiles do not change this time. Thus a chat history keeps the variables of the
295
+ compiles of its last 5 minutes, and a guard prompt, a queue, or a compile in another thread before
296
+ the call does not remove them. A message that you compile one time and send in many calls keeps its
297
+ variables while a call names its `compile()` at least one time in 5 minutes. A call that sends only
298
+ messages of earlier turns records the prompt of the newest `compile()` among them, and its
299
+ variables when they are less than 5 minutes old. With input capture off, the message keeps no
300
+ variables.
301
+
302
+ For your own spans, `prompt_attributes_for(messages)` gives the attributes to pass as
303
+ `attributes`. It gives `{}` inside `with_prompt`, and a span with `capture_input=False` drops
304
+ `td.prompt.variables`. A model call whose parent is in `with_prompt` gets the prompt of the
305
+ `with_prompt` and none of the `td.prompt.*` attributes that you pass, at start or in `update`,
306
+ `end`, or `update_current_span`, also when its `parent` context comes from a `with_prompt` that the
307
+ call is not in.
308
+
309
+ ## Experiments
310
+
311
+ `run_experiment` runs your code on each item of a dataset that you manage in telemetry.dev, and
312
+ records the outputs and the scores as an experiment. The experiment page compares it with the
313
+ baseline of the dataset.
314
+
315
+ ```python
316
+ import telemetry_dev
317
+
318
+ telemetry_dev.init(environment="experiment")
319
+
320
+ result = telemetry_dev.run_experiment(
321
+ name="reply-v13-gpt-4o",
322
+ dataset="support-golden",
323
+ task=lambda item: reply_to_customer(item.input),
324
+ evaluators=["correctness", "helpfulness"],
325
+ scorers={"short": lambda output, item: len(output) < 600},
326
+ min_scores={"correctness": 0.9},
327
+ )
328
+ ```
329
+
330
+ - `run_experiment` reads the newest version of the dataset, or `dataset_version`, 100 items at a
331
+ time. With `split`, it runs only the items of that split. Then it makes the experiment, with a
332
+ name that telemetry.dev picks when you give no `name`.
333
+ - `task(item)` gets an `ExperimentItem`: `id`, `number`, `input`, `expected_output`, `metadata`,
334
+ `tags`, `split`, and `run_index`. Its return value is the output. A string stays as it is, and a
335
+ different value becomes JSON, cut to 100,000 UTF-16 units. A value that JSON cannot hold, such
336
+ as a dict that holds itself, gives no output. A task that raises fails only its item, and the
337
+ item records the type and the message of the exception.
338
+ - `concurrency` (1 to 100, default 4) threads run the items, each in a copy of the context of the
339
+ caller, so `propagate_attributes` around the call applies to each item. With `runs_per_item`
340
+ (default 1, at most 5), each item runs more than one time. Each run gets its own copy of the
341
+ item, so a task that changes its input does not change the next run. The pass rate and the mean
342
+ of each score use all runs.
343
+ - `run_experiment_async` takes async tasks and scorers. `concurrency` asyncio tasks run the items,
344
+ and the requests go in worker threads. A task that is not async runs on the event loop, so use
345
+ `run_experiment` for it. `run_experiment` raises `TypeError` for an async task or scorer.
346
+ - Each item run is a trace of its own, with the span `experiment <name>`. The SDK puts
347
+ `td.experiment.id` and `td.dataset.item_id` on each span of the run, also on the spans of the
348
+ provider integrations. Each run also gets its own session id,
349
+ `<experiment id>:<item id>:<run index>`, as `gen_ai.conversation.id`.
350
+ - Call `init(environment="experiment")` before the run. Pages, metrics, and alerts leave out the
351
+ `experiment` environment by default. In a different environment, `run_experiment` logs a
352
+ warning. Without an enabled client, the items record no traces and no cost.
353
+ - `evaluators` names evaluators of the project: LLM judges, code checks, and rules. telemetry.dev
354
+ runs them on the outputs. `scorers` run on your machine, after the span of the item ends. A
355
+ scorer returns `True` or `False` for a pass or a fail, a number, a label, or a mapping with
356
+ `value`, `label`, and `reason`. A scorer that raises, or returns a score that is not valid, gives
357
+ no score for that item and sends a `scorer_failed` error to `on_error`. A scorer cannot have the
358
+ name of an evaluator of the run, or the name `user_feedback`.
359
+ - `run_experiment` sends the outputs in batches of 100 items at most, and then waits up to 30
360
+ minutes for the server evaluators. Then it prints the scores and returns an `ExperimentResult`:
361
+ `status`, `check_status`, item counts, `scores` with the value, the baseline value, the change,
362
+ and the pass mark of each score, and the `url` of the experiment page.
363
+ - `min_scores` sets a pass mark for each score name: the lowest pass rate (0 to 1) of a pass/fail
364
+ score, or the lowest mean of a number score. A score under its mark fails the check.
365
+ - A failed request raises `ExperimentError` whose `code` tells why, for example
366
+ `dataset_not_found`, `dataset_empty`, `evaluator_not_found`, `insufficient_scope`,
367
+ `missing_api_key`, or `timeout`. A read of the dataset or the result, a post of outputs, and the
368
+ completion go again up to 2 times after a timeout, a network error, a 429, or a 5xx. The server
369
+ skips an item run that it has. The request that makes the experiment goes again only after a
370
+ 429, thus a lost response or a 503 cannot make a second experiment. When the run stops after it
371
+ made the experiment, also after Ctrl-C or a cancellation, `run_experiment` sends the completion
372
+ before it raises: telemetry.dev then ends the experiment with the item runs that it got, or fails
373
+ it when it got none.
374
+ - The key needs the `datasets:read` and `experiments:write` scopes. `run_experiment` uses the same
375
+ API key and base URL as `get_prompt`, or its own `api_key` and `base_url`. With
376
+ `environment="experiment"`, the key of the telemetry client must be for all environments or for
377
+ `experiment`: a key for another environment cannot send the traces of the items, and the items
378
+ then have no trace and no cost.
379
+
380
+ The outputs, the exceptions of failed tasks, the scorer reasons, and `metadata` go to telemetry.dev
381
+ and stay with the experiment, because they are its result. `capture_output`, `mask`, and the
382
+ capture setting of the environment in the project do not apply to them. They apply only to the
383
+ spans of the run.
384
+
385
+ ### CI mode
386
+
387
+ When the `CI` variable is `true` or `1`, or with `ci=True`, `run_experiment` raises when the check
388
+ fails (`check_failed`) or when the experiment does not complete (`experiment_failed`), so the
389
+ process exits with an error. The error has the `result`. In GitHub Actions, the experiment also
390
+ records the repository, the commit, the run URL, and the number, the title, and the URL of the pull
391
+ request. The commit of a pull request is its head commit.
392
+
393
+ The [experiment action](../../actions/experiment) runs your eval script in a workflow, and posts
394
+ the result on the pull request. It gives `run_experiment` the `dataset` input in
395
+ `TELEMETRY_DEV_EXPERIMENT_DATASET`, which must agree with the `dataset` of the script, and the
396
+ `min-scores` input in `TELEMETRY_DEV_EXPERIMENT_MIN_SCORES`, which wins over `min_scores` for the
397
+ same name.
398
+
399
+ ## Scores
400
+
401
+ `score` records a score on a trace, a span, or a session, for example the thumbs up or down of a
402
+ user on a reply:
403
+
404
+ ```python
405
+ import telemetry_dev
406
+
407
+ # When the app replies, keep the trace id of the reply with the message:
408
+ with telemetry_dev.start_span("reply") as span:
409
+ text = reply_to_customer(message)
410
+ trace_id = f"{span.span.get_span_context().trace_id:032x}"
411
+
412
+ # Later, when the user clicks thumbs down:
413
+ telemetry_dev.score(name="user_feedback", trace_id=trace_id, value=0, comment="Wrong amount")
414
+ ```
415
+
416
+ - Give `trace_id`, `session_id`, or the two, and a `span_id` of the trace for a score on one span.
417
+ Give `value`, `label`, or the two. `user_feedback` takes the value 1 for up or 0 for down, and
418
+ no label. A pass/fail score has the label `pass` with the value 1, or `fail` with 0.
419
+ - Like the telemetry functions, `score` never raises. It returns the id of the score, or `None`
420
+ after it sends a `ScoreError` to `on_error`. It checks the score before it sends it
421
+ (`invalid_score`). The trace id of a span from a client that is not enabled is all zeros, and
422
+ `score` reports it as `invalid_score`.
423
+ - `score` makes one request, with no retry. `score_async` runs it in a worker thread. The key
424
+ needs the `scores:write` scope.
257
425
 
258
426
  ## Auto-metrics
259
427
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.3.1"
3
+ version = "0.3.2"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.3.1"
3
+ version = "0.3.2"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -17,6 +17,18 @@ from ._client import Client, flush, get_client, init, shutdown
17
17
  from ._config import SDK_VERSION as __version__
18
18
  from ._config import LogLevelOption
19
19
  from ._context import get_traceparent, propagate_attributes
20
+ from ._experiments import (
21
+ AsyncScorer,
22
+ DatasetItem,
23
+ ExperimentError,
24
+ ExperimentItem,
25
+ ExperimentResult,
26
+ ExperimentScore,
27
+ Scorer,
28
+ ScorerResult,
29
+ run_experiment,
30
+ run_experiment_async,
31
+ )
20
32
  from ._logs import log
21
33
  from ._observe import observe
22
34
  from ._prompts import (
@@ -27,8 +39,10 @@ from ._prompts import (
27
39
  TextPrompt,
28
40
  get_prompt,
29
41
  get_prompt_async,
42
+ prompt_attributes_for,
30
43
  with_prompt,
31
44
  )
45
+ from ._scores import ScoreError, score, score_async
32
46
  from ._semconv import LogLevel, SpanType
33
47
  from ._serialize import AttributeValue, Mask, MaskContext
34
48
  from ._spans import (
@@ -42,10 +56,16 @@ from .otel import TelemetrySpanProcessor
42
56
 
43
57
  __all__ = [
44
58
  "NOT_GIVEN",
59
+ "AsyncScorer",
45
60
  "AttributeValue",
46
61
  "CaptureBudget",
47
62
  "ChatPrompt",
48
63
  "Client",
64
+ "DatasetItem",
65
+ "ExperimentError",
66
+ "ExperimentItem",
67
+ "ExperimentResult",
68
+ "ExperimentScore",
49
69
  "LogLevel",
50
70
  "LogLevelOption",
51
71
  "Mask",
@@ -53,6 +73,9 @@ __all__ = [
53
73
  "Prompt",
54
74
  "PromptError",
55
75
  "PromptModel",
76
+ "ScoreError",
77
+ "Scorer",
78
+ "ScorerResult",
56
79
  "SpanHandle",
57
80
  "SpanType",
58
81
  "TelemetrySpanProcessor",
@@ -67,7 +90,12 @@ __all__ = [
67
90
  "init",
68
91
  "log",
69
92
  "observe",
93
+ "prompt_attributes_for",
70
94
  "propagate_attributes",
95
+ "run_experiment",
96
+ "run_experiment_async",
97
+ "score",
98
+ "score_async",
71
99
  "shutdown",
72
100
  "start_span",
73
101
  "update_current_span",