telemetry-dev 0.3.1__tar.gz → 0.3.3__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 (28) hide show
  1. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/PKG-INFO +240 -16
  2. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/README.md +239 -15
  3. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/pyproject.toml +1 -1
  4. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/pyproject.toml.orig +1 -1
  5. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/__init__.py +30 -0
  6. telemetry_dev-0.3.3/src/telemetry_dev/_api.py +203 -0
  7. telemetry_dev-0.3.3/src/telemetry_dev/_capture.py +390 -0
  8. telemetry_dev-0.3.3/src/telemetry_dev/_ci.py +136 -0
  9. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_client.py +88 -19
  10. telemetry_dev-0.3.3/src/telemetry_dev/_experiments.py +1161 -0
  11. telemetry_dev-0.3.3/src/telemetry_dev/_export.py +641 -0
  12. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_metrics.py +28 -26
  13. telemetry_dev-0.3.3/src/telemetry_dev/_process_lock.py +41 -0
  14. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_processor.py +26 -2
  15. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_prompts.py +296 -100
  16. telemetry_dev-0.3.3/src/telemetry_dev/_scores.py +181 -0
  17. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_semconv.py +2 -0
  18. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_serialize.py +80 -1
  19. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_spans.py +27 -8
  20. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/otel.py +50 -15
  21. telemetry_dev-0.3.1/src/telemetry_dev/_capture.py +0 -189
  22. telemetry_dev-0.3.1/src/telemetry_dev/_export.py +0 -100
  23. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/LICENSE +0 -0
  24. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_config.py +0 -0
  25. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_context.py +0 -0
  26. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_logs.py +0 -0
  27. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/src/telemetry_dev/_observe.py +0 -0
  28. {telemetry_dev-0.3.1 → telemetry_dev-0.3.3}/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.3
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. |
@@ -126,10 +128,6 @@ metric readers, so supplying `metric_reader=` disables this histogram. Duration,
126
128
  time-to-first-chunk metrics remain available; the first accepted streamed span with two or more
127
129
  recorded chunks reports this limitation once through `on_error` and the SDK logger.
128
130
 
129
- Provider integrations feature-detect `record_output_chunk`. Older core SDKs without that method
130
- continue delivering streams and tracing normally, but do not emit chunk-interval metrics. Upgrade
131
- the core SDK with provider integrations to enable the new metric.
132
-
133
131
  ### Span types
134
132
 
135
133
  `type=` maps to `gen_ai.operation.name`:
@@ -181,14 +179,27 @@ metadata, identifiers, resource attributes, or events written directly through r
181
179
  | `log_level` | `"warn"` | SDK diagnostics level: `debug`/`info`/`warn`/`error`/`silent`. |
182
180
  | `capture_input`, `capture_output` | `True` | Global content-capture defaults. |
183
181
  | `mask` | `None` | `Callable[[Any, MaskContext], Any]` redaction hook, runs before JSON serialization on input/output/log messages and `SpanHandle.serialize_content` (`MaskContext.key` is the attribute being written). Not applied to correlation identifiers. |
184
- | `max_attribute_length` | `65536` | Non-negative integer per-content-attribute cap. Invalid values call `on_error`, do not raise into application code, and install a disabled client; truncated values use the ASCII `...[truncated]` marker, or its prefix when the cap is shorter than the marker. The cap also applies, with the marker, to string metadata and log attributes; any other string attribute is cut at the cap without a marker, except that a cap of `0` leaves those at 65536. |
182
+ | `max_attribute_length` | `None` | Per-content-attribute cap in UTF-16 units, the marker included: `None` (no cap, each value is sent whole) or a non-negative integer. Invalid values call `on_error`, do not raise into application code, and install a disabled client; truncated values use the ASCII `...[truncated]` marker, or its prefix when the cap is shorter than the marker. The cap also applies, with the marker, to string metadata and log attributes; any other string attribute is cut at the cap without a marker, except that a cap of `0` leaves those whole. |
183
+ | `max_stream_bytes` | `67108864` (64 MiB) | Maximum output, across the process, that provider integrations keep for streams that have not ended, in UTF-8 bytes of JSON. Each stream keeps at most `MAX_RECORD_BYTES` (16 MiB); while no other stream holds bytes in it, not even the few bytes a started stream holds before any output, a stream may grow to 16 MiB even past this bound. Output past either bound is not kept, and its span gets `telemetry.dev.capture.truncated`. `None` selects the default; other values that are not non-negative integers or `math.inf` call `on_error` and install a disabled client. The bound counts UTF-8 bytes, not Python memory, so each streamed text buffer holds more than it counts: up to 255 of its latest deltas as separate strings, at most about 22 KB, and either about 1.5% of its text on Python 3.10 and 3.11 or, on 3.12 and later, the room `StringIO` reserves to grow, up to about 25% of its text (50% on Windows). Text with a character outside Latin-1, such as an emoji, is stored at up to 4 bytes per character, so its buffer can hold up to about 4 times the bytes counted. |
185
184
  | `span_filter` | `None` | Export predicate `Callable[[ReadableSpan], bool]`. |
186
185
  | `sampler` | OTel environment configuration | OTel `Sampler` that overrides environment settings. Session roots use its root policy. Real parents keep their sampling decisions. |
187
- | `on_error` | `None` | Receives internal SDK errors; repeated instrumentation failures from one stream may be coalesced into one report. The SDK never raises them into application code. A series of failed exports, for example during an ingest outage, is one report to `on_error` and the `telemetry_dev` logger. After an export reaches the ingest, the next failure is a new report. |
186
+ | `on_error` | `None` | Receives internal SDK errors; repeated instrumentation failures from one stream may be coalesced into one report. The SDK never raises them into application code. A series of failed exports, for example during an ingest outage, is one report to `on_error` and the `telemetry_dev` logger. After an export reaches the ingest, the next failure is a new report. A `flush()` or `shutdown()` that `on_error` calls during an export returns at once, before it sends anything, and runs on a new thread, because a batch processor or the metric reader holds a lock during its export that the call needs; the thread waits for that export to end. With `export_mode="immediate"` the span and log exports hold no lock, so the call starts at once, but it still returns before it sends anything: in a serverless handler, call `flush()` after the work, outside `on_error`. The process does not wait for a deferred flush before it exits; the shutdown at exit sends what is left, unless `disable_atexit=True`, where the application must call `shutdown()`. After a deferred `shutdown()`, the client is already gone, and the process waits for the shutdown before it exits; if its thread cannot start, it runs when the process exits, unless the process is already exiting. |
188
187
  | `disable_atexit` | `False` | Skip the automatic atexit shutdown. |
189
- | `timeout` | `10.0` | OTLP HTTP timeout in seconds. |
188
+ | `timeout` | `10.0` | Timeout of each OTLP HTTP export request in seconds. No wait before a retry starts after it, but a request whose connection fails is sent again at once with the same limit, so an ingest that does not answer can take up to twice this time. The limit applies to each wait for the server, so a response that keeps arriving can also take longer. A batch split into several requests gives each request this timeout. |
190
189
  | `span_exporter`, `log_exporter`, `metric_reader` | `None` | Test seams / offline mode; any of them enables the client without an API key. |
191
190
 
191
+ Each export request is at most 16 MiB, the ingest's limit, so a larger batch is sent in several
192
+ requests. A span or log record that is larger than 16 MiB by itself is still sent: its longest
193
+ string values (attributes, or a log record's message) are cut to fit and end with `...[truncated]`,
194
+ the record gets `telemetry.dev.capture.truncated = true`, and `on_error` receives a report. A record
195
+ that still does not fit, because its events or array attributes hold the excess, is dropped and
196
+ reported. `create_telemetry_span_exporter` and `TelemetrySpanProcessor` follow the same rules.
197
+
198
+ In `"batched"` mode, the spans and the log records that wait for export are each bounded to 2048
199
+ records (for logs, `OTEL_BLRP_MAX_QUEUE_SIZE` when it is set) and 64 MiB of string values, each character counted as one byte. A record that arrives
200
+ when its queue is full is dropped, and the first drop of a series is reported to `on_error`. A
201
+ single record larger than the bound is still queued when its queue is empty.
202
+
192
203
  `capture_input=False` and `capture_output=False` omit captured content. Provider integrations may
193
204
  still record non-content metadata such as response IDs and models, finish reasons, usage, timing,
194
205
  and error types. Capture flags do not gate stop sequences, tool descriptions and definitions
@@ -244,6 +255,13 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
244
255
  call returns it at once and fetches a new copy in a background thread. Only a call with no copy
245
256
  waits for a fetch, for 10 seconds at most, also when the network stops. Calls for the same
246
257
  prompt share one fetch. `get_prompt_async` runs the same function in a worker thread.
258
+ - A forked process keeps the copies of its parent: a process that `os.fork()` makes, one that
259
+ `multiprocessing` makes with the `fork` start method, or one that C code forks without running
260
+ fork hooks. A call that starts in the child does not wait for a fetch of the parent, or for a
261
+ lock that a thread of the parent held. If the call must fetch, it starts a new fetch.
262
+ - If a signal handler forks while a call waits for a fetch, that call continues in the child,
263
+ where no thread completes that fetch. Thus the call looks at the cache again, and starts a new
264
+ fetch if it must, which it waits for up to 10 seconds more.
247
265
  - If a fetch fails, `get_prompt` returns the last copy that it fetched and reports the error
248
266
  through `on_error`. With no copy, it returns the `fallback` (`version` is `None` and
249
267
  `is_fallback` is `True`). With no fallback, it raises `PromptError` whose `code` tells why, for
@@ -257,8 +275,8 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
257
275
  without its prompt.
258
276
  - `get_prompt` uses the API key and base URL of an enabled `init()`, or `TELEMETRY_DEV_API_KEY`
259
277
  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.
278
+ telemetry goes to, `https://api.telemetry.dev` by default. The key must have Read prompts in
279
+ its Access on the API keys page (the `prompts:read` scope).
262
280
  - When a label sends part of the traffic to a second version, each session keeps one version: the
263
281
  choice uses the session id of `propagate_attributes` (or of `session_mode="process"`). Without a
264
282
  session id, each call chooses at random.
@@ -267,7 +285,10 @@ pinned = telemetry_dev.get_prompt("support/reply", version=13)
267
285
  `td.prompt.name`, `td.prompt.version`, and `td.prompt.label` (only for a prompt fetched by label).
268
286
  When input capture is on, `td.prompt.variables` holds the JSON of the variables of the last
269
287
  `compile()` of that prompt object before `with_prompt` starts, or of the last `compile()` inside
270
- it, after `mask` and truncation. If threads or tasks that run at the same time share one prompt
288
+ it, after `mask`. Past `max_attribute_length` the longest values are cut one by one, each to a text
289
+ that ends with `...[truncated]`, when the keys and a marker for each cut value fit; the JSON then
290
+ keeps every variable. Otherwise the whole attribute is cut, so it can lose variables and stop being
291
+ valid JSON. If threads or tasks that run at the same time share one prompt
271
292
  object, call `compile()` in `with_prompt`, or call `get_prompt` in each thread or task.
272
293
  `get_prompt` returns a new object from the cache. If you do not, a thread can record the variables
273
294
  of a different thread. Inside one `with_prompt`, an asyncio task records the last `compile()` that
@@ -276,9 +297,185 @@ ran in it, or before it started in the code that started it; with none, it recor
276
297
  for code that has not compiled in its own task. Model calls are the spans of type `generation`
277
298
  (operations `chat`, `text_completion`, and `generate_content`), including the spans of the provider
278
299
  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.
300
+ other OpenTelemetry tracers do not get the attributes.
301
+
302
+ Outside `with_prompt`, those provider integrations record the prompt of the message dicts that
303
+ `compile()` returned. `compile()` of a chat prompt returns instances of a private `dict` subclass
304
+ that also hold its prompt and a copy of its variables and of each list in them. The objects in a
305
+ list are not copied, so a change to one of them after `compile()` changes the variables that a call
306
+ records. A chat call that sends such messages gets `td.prompt.name`, `td.prompt.version`, and
307
+ `td.prompt.label` of the newest `compile()` among them, also when input capture is off, and
308
+ `td.prompt.variables` when it is on. The SDK looks at the first 1000 and the last 1000 messages of
309
+ the call. A message from a placeholder variable keeps the prompt of its own, older `compile()`, so
310
+ it does not win over the `compile()` that put it in the list. A copy of a message (`dict()`,
311
+ `.copy()`, `copy.copy`, `copy.deepcopy`, pickle, JSON, `type(message)(message)`, or
312
+ `dataclasses.asdict`) and a new message with the same text do not hold the prompt, so a call that
313
+ sends only such messages gets no `td.prompt.*` attributes; with input capture on, the call still
314
+ records them as its input. Bedrock Converse and Google GenAI take another message shape: change the
315
+ compiled dicts in place, or use `with_prompt`. A text prompt compiles to a string, which cannot hold
316
+ its prompt: use `with_prompt`. `with_prompt` wins over the message. The integrations do it for OpenAI
317
+ chat completions and responses, Anthropic messages (for `messages.stream()`, at `__enter__`),
318
+ Bedrock Converse, Google GenAI `generate_content`, LiteLLM completion and responses, and OpenRouter
319
+ chat and responses, but not for Bedrock InvokeModel (its body is bytes), embeddings, images, audio,
320
+ video, or OpenAI Realtime. With an older `telemetry-dev` that has no `prompt_attributes_for`, a
321
+ provider integration records the prompt only in `with_prompt`.
322
+
323
+ A compiled message is a `dict` for `isinstance`, and its keys and its JSON (`json`, `orjson`,
324
+ pydantic) do not change. A check of the exact type (`type(message) is dict`), `yaml.safe_dump`,
325
+ and `marshal` reject it: give them `dict(message)`.
326
+
327
+ With input capture on in the client when `compile()` runs, a compiled message keeps the variables
328
+ of its `compile()` for 5 minutes. A call keeps them for 5 more minutes when the newest `compile()`
329
+ of the call is that one. After that time, a call records the prompt without
330
+ `td.prompt.variables`, and the SDK removes the variables from the message, also when you keep the
331
+ message. Other compiles do not change this time. Thus a chat history keeps the variables of the
332
+ compiles of its last 5 minutes, and a guard prompt, a queue, or a compile in another thread before
333
+ the call does not remove them. A message that you compile one time and send in many calls keeps its
334
+ variables while a call names its `compile()` at least one time in 5 minutes. A call that sends only
335
+ messages of earlier turns records the prompt of the newest `compile()` among them, and its
336
+ variables when they are less than 5 minutes old. With input capture off, the message keeps no
337
+ variables.
338
+
339
+ For your own spans, `prompt_attributes_for(messages)` gives the attributes to pass as
340
+ `attributes`. It gives `{}` inside `with_prompt`, and a span with `capture_input=False` drops
341
+ `td.prompt.variables`. A model call whose parent is in `with_prompt` gets the prompt of the
342
+ `with_prompt` and none of the `td.prompt.*` attributes that you pass, at start or in `update`,
343
+ `end`, or `update_current_span`, also when its `parent` context comes from a `with_prompt` that the
344
+ call is not in.
345
+
346
+ ## Experiments
347
+
348
+ `run_experiment` runs your code on each item of a dataset that you manage in telemetry.dev, and
349
+ records the outputs and the scores as an experiment. The experiment page compares it with the
350
+ baseline of the dataset.
351
+
352
+ ```python
353
+ import telemetry_dev
354
+
355
+ telemetry_dev.init(environment="experiment")
356
+
357
+ result = telemetry_dev.run_experiment(
358
+ name="reply-v13-gpt-4o",
359
+ dataset="support-golden",
360
+ task=lambda item: reply_to_customer(item.input),
361
+ evaluators=["correctness", "helpfulness"],
362
+ scorers={"short": lambda output, item: len(output) < 600},
363
+ min_scores={"correctness": 0.9},
364
+ )
365
+ ```
366
+
367
+ - `run_experiment` reads the newest version of the dataset, or `dataset_version`, 100 items at a
368
+ time. With `split`, it runs only the items of that split. Then it makes the experiment, with a
369
+ name that telemetry.dev picks when you give no `name`.
370
+ - `task(item)` gets an `ExperimentItem`: `id`, `number`, `input`, `expected_output`, `metadata`,
371
+ `tags`, `split`, and `run_index`. Its return value is the output. A string stays as it is, and a
372
+ different value becomes JSON, cut to 100,000 UTF-16 units. A value that JSON cannot hold, such
373
+ as a dict that holds itself, gives no output. A task that raises fails only its item, and the
374
+ item records the type and the message of the exception.
375
+ - `concurrency` (1 to 100, default 4) threads run the items, each in a copy of the context of the
376
+ caller, so `propagate_attributes` around the call applies to each item. With `runs_per_item`
377
+ (default 1, at most 5), each item runs more than one time. Each run gets its own copy of the
378
+ item, so a task that changes its input does not change the next run. The pass rate and the mean
379
+ of each score use all runs.
380
+ - `run_experiment_async` takes async tasks and scorers. `concurrency` asyncio tasks run the items,
381
+ and the requests go in worker threads. A task that is not async runs on the event loop, so use
382
+ `run_experiment` for it. `run_experiment` raises `TypeError` for an async task or scorer.
383
+ - Each item run is a trace of its own, with the span `experiment <name>`. The SDK puts
384
+ `td.experiment.id` and `td.dataset.item_id` on each span of the run, also on the spans of the
385
+ provider integrations. Each run also gets its own session id,
386
+ `<experiment id>:<item id>:<run index>`, as `gen_ai.conversation.id`.
387
+ - Call `init(environment="experiment")` before the run. Pages, metrics, and alerts leave out the
388
+ `experiment` environment by default. In a different environment, `run_experiment` logs a
389
+ warning. Without an enabled client, the items record no traces and no cost.
390
+ - `evaluators` names evaluators of the project: LLM judges, code checks, and rules. telemetry.dev
391
+ runs them on the outputs. `scorers` run on your machine, after the span of the item ends. A
392
+ scorer returns `True` or `False` for a pass or a fail, a number, a label, or a mapping with
393
+ `value`, `label`, and `reason`. A scorer that raises, or returns a score that is not valid, gives
394
+ no score for that item and sends a `scorer_failed` error to `on_error`. A scorer cannot have the
395
+ name of an evaluator of the run, or the name `user_feedback`.
396
+ - `run_experiment` sends the outputs in batches of 100 items at most, and then waits up to 30
397
+ minutes for the server evaluators. Then it prints the scores and returns an `ExperimentResult`:
398
+ `status`, `check_status`, item counts, `scores` with the value, the baseline value, the change,
399
+ the pass mark, and the failed runs (`items_failed`) of each score, and the `url` of the
400
+ experiment page.
401
+ - `min_scores` sets a pass mark for each score name: the lowest pass rate (0 to 1) of a pass/fail
402
+ score, or the lowest mean of a number score. A score under its mark fails the check. A run whose
403
+ task raises has no score, so the value of a score leaves it out, and with pass marks a failed
404
+ run fails the check.
405
+ - A failed request raises `ExperimentError` whose `code` tells why, for example
406
+ `dataset_not_found`, `dataset_empty`, `evaluator_not_found`, `insufficient_scope`,
407
+ `missing_api_key`, or `timeout`. A read of the dataset or the result, a post of outputs, and the
408
+ completion go again up to 2 times after a timeout, a network error, a 429, or a 5xx. The server
409
+ skips an item run that it has. The request that makes the experiment goes again only after a
410
+ 429, thus a lost response or a 503 cannot make a second experiment. When the run stops after it
411
+ made the experiment, also after Ctrl-C or a cancellation, `run_experiment` sends the completion
412
+ before it raises: telemetry.dev then ends the experiment with the item runs that it got, or fails
413
+ it when it got none.
414
+ - The key needs Run experiments in its Access on the API keys page (the `datasets:read` and
415
+ `experiments:write` scopes). `run_experiment` uses the same
416
+ API key and base URL as `get_prompt`, or its own `api_key` and `base_url`. With
417
+ `environment="experiment"`, the key of the telemetry client must be for all environments or for
418
+ `experiment`: a key for another environment cannot send the traces of the items, and the items
419
+ then have no trace and no cost.
420
+
421
+ The outputs, the exceptions of failed tasks, the scorer reasons, and `metadata` go to telemetry.dev
422
+ and stay with the experiment, because they are its result. `capture_output`, `mask`, and the
423
+ capture setting of the environment in the project do not apply to them. They apply only to the
424
+ spans of the run.
425
+
426
+ ### CI mode
427
+
428
+ When the `CI` variable is `true` or `1`, or with `ci=True`, `run_experiment` raises when the check
429
+ fails (`check_failed`) or when the experiment does not complete (`experiment_failed`), so the
430
+ process exits with an error. The error has the `result`. In GitHub Actions, the experiment also
431
+ records the repository, the commit, the run URL, and the number, the title, and the URL of the pull
432
+ request. The commit of a pull request is its head commit.
433
+
434
+ The [experiment action](../../actions/experiment) runs your eval script in a workflow, and posts
435
+ the result on the pull request. It gives `run_experiment` the `dataset` input in
436
+ `TELEMETRY_DEV_EXPERIMENT_DATASET`, which must agree with the `dataset` of the script, and the
437
+ `min-scores` input in `TELEMETRY_DEV_EXPERIMENT_MIN_SCORES`, which wins over `min_scores` for the
438
+ same name. Use the action as `telemetry-dev/telemetry/actions/experiment@experiment-action-v1`, a
439
+ tag that moves to each 1.x release of the action. In the action, a failed experiment with `ci=False`
440
+ shows its result but does not fail the job.
441
+
442
+ ## Scores
443
+
444
+ `score` records a score on a trace, a span, or a session, for example the thumbs up or down of a
445
+ user on a reply:
446
+
447
+ ```python
448
+ import telemetry_dev
449
+
450
+ # When the app replies, keep the trace id and the span id of the reply with the message:
451
+ with telemetry_dev.start_span("reply") as span:
452
+ text = reply_to_customer(message)
453
+ context = span.span.get_span_context()
454
+ trace_id, span_id = f"{context.trace_id:032x}", f"{context.span_id:016x}"
455
+
456
+ # Later, when the user clicks thumbs down:
457
+ telemetry_dev.score(
458
+ name="user_feedback", trace_id=trace_id, span_id=span_id, value=0, comment="Wrong amount"
459
+ )
460
+ ```
461
+
462
+ - Give `trace_id`, `session_id`, or the two, and a `span_id` of the trace for a score on one span.
463
+ Give `value`, `label`, or the two. `user_feedback` takes the value 1 for up or 0 for down, and
464
+ no label. A pass/fail score has the label `pass` with the value 1, or `fail` with 0.
465
+ - Like the telemetry functions, `score` never raises. It returns the id of the score, or `None`
466
+ after it sends a `ScoreError` to `on_error`. It checks the score before it sends it
467
+ (`invalid_score`). The trace id of a span from a client that is not enabled is all zeros, and
468
+ `score` reports it as `invalid_score`.
469
+ - Give the `span_id` of the reply for feedback on one reply. The SDK puts all the turns of a session
470
+ in one trace, so feedback with only a `trace_id` counts for the turn that started last before the
471
+ feedback came, which can be a later turn than the reply.
472
+ - The rates of the dashboard count one `user_feedback` vote for each span, turn, or session: a
473
+ later `user_feedback` score on the same span (on the same turn, for feedback with only a trace,
474
+ or on the same session, for feedback with no trace) replaces the earlier one. The SDK sends
475
+ feedback with no author, so all the feedback that the SDK sends on one span or one turn counts as
476
+ one vote: the newest.
477
+ - `score` makes one request, with no retry. `score_async` runs it in a worker thread. The key
478
+ needs Run experiments in its Access on the API keys page (the `scores:write` scope).
282
479
 
283
480
  ## Auto-metrics
284
481
 
@@ -306,6 +503,27 @@ telemetry_dev.init(export_mode="immediate")
306
503
  telemetry_dev.flush() # force-flush traces + logs + metrics
307
504
  ```
308
505
 
506
+ ## Forking servers
507
+
508
+ A server that forks its workers from the process that called `init()`, as gunicorn,
509
+ `multiprocessing` with the `fork` start method, or `os.fork()`, needs no setup. Python runs the
510
+ fork hooks of the SDK and of OpenTelemetry in each worker, and the SDK does not wait in a worker
511
+ for a lock that a thread of the parent held at the fork.
512
+
513
+ uWSGI loads the app before it forks its workers, and by default it runs no Python fork hooks in
514
+ them. Traces and logs still go out, but the OpenTelemetry metric reader starts its thread again
515
+ only in a fork hook, so a worker sends metrics only when it calls `telemetry_dev.flush()`. Set one
516
+ of these uWSGI options:
517
+
518
+ - `lazy-apps = true`: each worker loads the app, and thus calls `init()` itself.
519
+ - `py-call-uwsgi-fork-hooks = true` (uWSGI 2.0.21 and later): uWSGI runs the Python fork hooks
520
+ around each fork. Before 2.0.27, it runs only the hooks of the child, which is enough for the
521
+ SDK.
522
+
523
+ Before uWSGI 2.0.27, Python threads run only with `enable-threads = true` or more than one
524
+ `threads`. The SDK sends telemetry from its own threads, so set one of them too, also with
525
+ `lazy-apps`.
526
+
309
527
  ## Bring your own OTel (`telemetry_dev.otel`)
310
528
 
311
529
  If you already run an OpenTelemetry SDK, attach the telemetry.dev processor to your provider
@@ -327,6 +545,10 @@ span_exporter = create_telemetry_span_exporter()
327
545
  your_tracer_provider.add_span_processor(BatchSpanProcessor(span_exporter))
328
546
  ```
329
547
 
548
+ `create_telemetry_span_exporter` takes `api_key`, `base_url`, and `timeout`, in seconds (default
549
+ `10.0`). The timeout works as the `timeout` option of `init` describes, also for each request of a
550
+ batch that is split.
551
+
330
552
  `TelemetrySpanProcessor` remains available from the package root for compatibility:
331
553
 
332
554
  ```python
@@ -341,12 +563,14 @@ from telemetry_dev import TelemetrySpanProcessor
341
563
  | `max_export_batch_size` | `64` | BatchSpanProcessor export batch size. |
342
564
  | `schedule_delay_millis` | `1000` | BatchSpanProcessor schedule delay. |
343
565
  | `max_queue_size` | `2048` | BatchSpanProcessor queue size. |
344
- | `export_timeout_millis` | `30000` | BatchSpanProcessor export timeout. |
566
+ | `max_queue_bytes` | `67108864` (64 MiB) | Maximum size of the queued spans, counting each character of their string attribute values as one byte. A span is still queued when the queue is empty. Spans over the bound are dropped and reported to `on_error`. |
567
+ | `max_stream_bytes` | `67108864` (64 MiB) | Maximum output that provider integrations keep, across the process, for streams that have not ended (UTF-8 bytes of JSON). Each stream keeps at most `MAX_RECORD_BYTES` (16 MiB); while no other stream holds bytes in it, not even the few bytes a started stream holds before any output, a stream may grow to 16 MiB even past this bound. The bound is process-wide, so the span processor started last sets it. `None` selects the default; other values that are not non-negative integers or `math.inf` are reported to `on_error`, and the processor exports nothing. Output past either bound is not kept, and its span gets `telemetry.dev.capture.truncated`. The bound counts UTF-8 bytes, not Python memory, so each streamed text buffer holds more than it counts: up to 255 of its latest deltas as separate strings, at most about 22 KB, and either about 1.5% of its text on Python 3.10 and 3.11 or, on 3.12 and later, the room `StringIO` reserves to grow, up to about 25% of its text (50% on Windows). Text with a character outside Latin-1, such as an emoji, is stored at up to 4 bytes per character, so its buffer can hold up to about 4 times the bytes counted. |
568
+ | `export_timeout_millis` | `30000` | Passed to BatchSpanProcessor, which does not apply it. The telemetry.dev exporter applies a 10-second `timeout` to each request, as the `init` option describes. |
345
569
  | `span_filter` | `None` | Export predicate `Callable[[ReadableSpan], bool]`; failures export the span. |
346
570
  | `metrics` | `True` | Auto-record GenAI duration/token histograms for exported spans when an API key is available. |
347
571
  | `service_name` | `OTEL_SERVICE_NAME` or `unknown_service` | `service.name` on the metrics resource. |
348
572
  | `environment` | `TELEMETRY_DEV_ENVIRONMENT` or `production` | `deployment.environment.name` on the metrics resource. |
349
- | `on_error` | `None` | Receives export errors of the telemetry.dev exporters and internal processor errors; errors are never raised into your code. A series of failed exports is one report. After an export reaches the ingest, the next failure is a new report. |
573
+ | `on_error` | `None` | Receives export errors of the telemetry.dev exporters and internal processor errors; errors are never raised into your code. A series of failed exports is one report. After an export reaches the ingest, the next failure is a new report. A `force_flush()` or `shutdown()` of the processor that `on_error` calls during an export returns at once (`force_flush()` returns `False`) and runs on a new thread. The process waits for a deferred `shutdown()` before it exits, and runs it at exit if its thread cannot start, unless the process is already exiting; it does not wait for a deferred `force_flush()`. |
350
574
  | `span_exporter` | `None` | Advanced/test seam replacing the telemetry.dev OTLP trace exporter. |
351
575
 
352
576
  Without an API key and without `span_exporter`, `TelemetrySpanProcessor()` is an inert no-op: