telemetry-dev 0.3.6__tar.gz → 0.3.8__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 (26) hide show
  1. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/PKG-INFO +7 -5
  2. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/README.md +6 -4
  3. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/pyproject.toml +1 -1
  4. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/pyproject.toml.orig +1 -1
  5. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_api.py +30 -21
  6. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_semconv.py +2 -2
  7. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_spans.py +94 -2
  8. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/LICENSE +0 -0
  9. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/__init__.py +0 -0
  10. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_capture.py +0 -0
  11. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_ci.py +0 -0
  12. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_client.py +0 -0
  13. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_config.py +0 -0
  14. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_context.py +0 -0
  15. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_experiments.py +0 -0
  16. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_export.py +0 -0
  17. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_logs.py +0 -0
  18. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_metrics.py +0 -0
  19. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_observe.py +0 -0
  20. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_process_lock.py +0 -0
  21. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_processor.py +0 -0
  22. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_prompts.py +0 -0
  23. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_scores.py +0 -0
  24. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/_serialize.py +0 -0
  25. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/src/telemetry_dev/otel.py +0 -0
  26. {telemetry_dev-0.3.6 → telemetry_dev-0.3.8}/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.6
3
+ Version: 0.3.8
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
@@ -414,10 +414,12 @@ result = telemetry_dev.run_experiment(
414
414
  `missing_api_key`, or `timeout`. A read of the dataset or the result, a post of outputs, and the
415
415
  completion go again up to 2 times after a timeout, a network error, a 429, or a 5xx. The server
416
416
  skips an item run that it has. The request that makes the experiment goes again only after a
417
- 429, thus a lost response or a 503 cannot make a second experiment. When the run stops after it
418
- made the experiment, also after Ctrl-C or a cancellation, `run_experiment` sends the completion
419
- before it raises: telemetry.dev then ends the experiment with the item runs that it got, or fails
420
- it when it got none.
417
+ 429, thus a lost response or a 503 cannot make a second experiment. No request goes again after
418
+ a 429 `quota_exceeded`, which a cap of the plan gives, or after a 429 whose `Retry-After` is
419
+ more than 60 seconds: `run_experiment` raises at once with the message of the server. When the
420
+ run stops after it made the experiment, also after Ctrl-C or a cancellation, `run_experiment`
421
+ sends the completion before it raises: telemetry.dev then ends the experiment with the item runs
422
+ that it got, or fails it when it got none.
421
423
  - The key needs Run experiments in its Access on the API keys page (the `datasets:read` and
422
424
  `experiments:write` scopes). `run_experiment` uses the same
423
425
  API key and base URL as `get_prompt`, or its own `api_key` and `base_url`.
@@ -387,10 +387,12 @@ result = telemetry_dev.run_experiment(
387
387
  `missing_api_key`, or `timeout`. A read of the dataset or the result, a post of outputs, and the
388
388
  completion go again up to 2 times after a timeout, a network error, a 429, or a 5xx. The server
389
389
  skips an item run that it has. The request that makes the experiment goes again only after a
390
- 429, thus a lost response or a 503 cannot make a second experiment. When the run stops after it
391
- made the experiment, also after Ctrl-C or a cancellation, `run_experiment` sends the completion
392
- before it raises: telemetry.dev then ends the experiment with the item runs that it got, or fails
393
- it when it got none.
390
+ 429, thus a lost response or a 503 cannot make a second experiment. No request goes again after
391
+ a 429 `quota_exceeded`, which a cap of the plan gives, or after a 429 whose `Retry-After` is
392
+ more than 60 seconds: `run_experiment` raises at once with the message of the server. When the
393
+ run stops after it made the experiment, also after Ctrl-C or a cancellation, `run_experiment`
394
+ sends the completion before it raises: telemetry.dev then ends the experiment with the item runs
395
+ that it got, or fails it when it got none.
394
396
  - The key needs Run experiments in its Access on the API keys page (the `datasets:read` and
395
397
  `experiments:write` scopes). `run_experiment` uses the same
396
398
  API key and base URL as `get_prompt`, or its own `api_key` and `base_url`.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.3.6"
3
+ version = "0.3.8"
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.6"
3
+ version = "0.3.8"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -20,7 +20,8 @@ from ._client import get_client
20
20
  from ._config import SDK_VERSION, resolve_config
21
21
  from ._serialize import json_dumps
22
22
 
23
- # A longer Retry-After waits only this long: the API counts requests by the minute.
23
+ # The longest wait before a retry: the API counts requests by the minute. A 429 with a longer
24
+ # Retry-After fails at once, and a 503 with a longer one waits only this long.
24
25
  _MAX_RETRY_AFTER_S = 60.0
25
26
  # IMF-fixdate, the HTTP date that servers send: Sun, 06 Nov 1994 08:49:37 GMT.
26
27
  _HTTP_DATE = re.compile(r"[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT", re.ASCII)
@@ -52,6 +53,7 @@ def resolve_api(api_key: str | None, base_url: str | None) -> Api:
52
53
  @dataclass(frozen=True)
53
54
  class _Failure:
54
55
  error: Exception
56
+ code: str | None
55
57
  status: int | None
56
58
  retry_after: float | None
57
59
 
@@ -74,7 +76,8 @@ def request(
74
76
  ``http_<status>``. With ``idempotent``, the server takes a repeat at most once, so a timeout, a
75
77
  network error, or a 5xx tries again. Other requests try again only after a 429, which the rate
76
78
  limit answers before the server does any work: a 503 can come after the work committed. A
77
- retry waits for the Retry-After of the response, or for 1 and then 2 seconds. The timeout
79
+ retry waits for the Retry-After of the response, or for 1 and then 2 seconds. A 429
80
+ ``quota_exceeded``, or a 429 with a Retry-After past 60 seconds, raises at once. The timeout
78
81
  applies to each socket operation of urllib.
79
82
  """
80
83
  url = f"{api.base_url}{path}"
@@ -92,7 +95,7 @@ def request(
92
95
  result = _send(error_type, method, url, path, data, headers, timeout_s)
93
96
  if not isinstance(result, _Failure):
94
97
  return result
95
- if attempt >= attempts or not _retryable(result.status, idempotent):
98
+ if attempt >= attempts or not _retryable(result, idempotent):
96
99
  raise result.error
97
100
  time.sleep(min(result.retry_after or float(attempt), _MAX_RETRY_AFTER_S))
98
101
  attempt += 1
@@ -128,18 +131,7 @@ opener = urllib.request.build_opener(NoRedirect)
128
131
 
129
132
  def api_error(error_type: Callable[[str, str, int | None], E], status: int, body: bytes) -> E:
130
133
  """The error of a response that is not 2xx: its API code and message, or ``http_<status>``."""
131
- try:
132
- error = json.loads(body).get("error")
133
- except (ValueError, AttributeError):
134
- error = None
135
- fields = cast("dict[str, Any]", error) if isinstance(error, dict) else {}
136
- code = fields.get("code")
137
- message = fields.get("message")
138
- return error_type(
139
- code if isinstance(code, str) else f"http_{status}",
140
- message if isinstance(message, str) else f"telemetry.dev returned {status}",
141
- status,
142
- )
134
+ return error_type(*_code_and_message(status, body), status)
143
135
 
144
136
 
145
137
  def retry_after(status: int, value: str | None) -> float | None:
@@ -175,8 +167,10 @@ def _send(
175
167
  body: bytes = response.read()
176
168
  except urllib.error.HTTPError as exc:
177
169
  with exc:
170
+ code, message = _code_and_message(exc.code, exc.read())
178
171
  return _Failure(
179
- api_error(error_type, exc.code, exc.read()),
172
+ error_type(code, message, exc.code),
173
+ code,
180
174
  exc.code,
181
175
  retry_after(exc.code, exc.headers.get("Retry-After")),
182
176
  )
@@ -190,14 +184,29 @@ def _send(
190
184
  else error_type("network_error", "Could not reach telemetry.dev", None)
191
185
  )
192
186
  error.__cause__ = exc
193
- return _Failure(error, None, None)
187
+ return _Failure(error, None, None, None)
194
188
  try:
195
189
  return json.loads(body)
196
190
  except ValueError:
197
191
  return None
198
192
 
199
193
 
200
- def _retryable(status: int | None, idempotent: bool) -> bool:
201
- if status == 429:
202
- return True
203
- return idempotent and (status is None or status >= 500)
194
+ def _code_and_message(status: int, body: bytes) -> tuple[str, str]:
195
+ try:
196
+ error = json.loads(body).get("error")
197
+ except (ValueError, AttributeError):
198
+ error = None
199
+ fields = cast("dict[str, Any]", error) if isinstance(error, dict) else {}
200
+ code = fields.get("code")
201
+ message = fields.get("message")
202
+ return (
203
+ code if isinstance(code, str) else f"http_{status}",
204
+ message if isinstance(message, str) else f"telemetry.dev returned {status}",
205
+ )
206
+
207
+
208
+ def _retryable(failure: _Failure, idempotent: bool) -> bool:
209
+ if failure.status == 429:
210
+ # A monthly quota resets at the start of next month, and a gift budget never resets.
211
+ return failure.code != "quota_exceeded" and (failure.retry_after or 0) <= _MAX_RETRY_AFTER_S
212
+ return idempotent and (failure.status is None or failure.status >= 500)
@@ -7,8 +7,8 @@ SCOPE_NAME = "telemetry_dev"
7
7
  SpanType = Literal["span", "generation", "tool", "agent", "embedding"]
8
8
  LogLevel = Literal["debug", "info", "warn", "warning", "error"]
9
9
 
10
- # Plain spans ALWAYS map to "function" — an operation-less span carrying a propagated
11
- # gen_ai.conversation.id would otherwise be classified as "llm" by the ingest heuristic.
10
+ # Plain spans ALWAYS map to "function": without one, the ingest guesses "llm" from other gen_ai.*
11
+ # keys on the span, such as a gen_ai.agent.name the caller set.
12
12
  SPAN_TYPE_TO_OPERATION: dict[str, str] = {
13
13
  "span": "function",
14
14
  "generation": "chat",
@@ -10,7 +10,7 @@ from collections.abc import Callable, Mapping, Sequence
10
10
  from contextvars import Token
11
11
  from dataclasses import dataclass
12
12
  from datetime import datetime
13
- from typing import Any, Literal, TypedDict
13
+ from typing import Any, Literal, TypedDict, cast
14
14
  from weakref import WeakKeyDictionary, WeakValueDictionary
15
15
 
16
16
  from opentelemetry import context as otel_context
@@ -151,10 +151,102 @@ def _to_ns(value: TimeInput) -> int | None:
151
151
  return int(value)
152
152
 
153
153
 
154
+ # Error classes that provider SDKs raise for any failed request, whose name says nothing about the
155
+ # cause: openai's and anthropic's APIStatusError (anthropic's for a stream's error event), and
156
+ # google-genai's APIError, ClientError, and ServerError. botocore's ClientError, and its
157
+ # EventStreamError for a Bedrock stream's exception, carry their code in `response`. Plain
158
+ # Exception is here for errors that carry a code, such as the failures that the integrations build
159
+ # from a response body with `code` and `type` attributes. The TypeScript SDK keeps the same rule in
160
+ # `errorTypeOf` (packages/otel/src/errors.ts); change both together.
161
+ _GENERIC_ERROR_NAMES = frozenset(
162
+ {"Exception", "APIError", "APIStatusError", "ClientError", "ServerError", "EventStreamError"}
163
+ )
164
+
165
+
166
+ def _text(value: object) -> str | None:
167
+ return value if isinstance(value, str) and value else None
168
+
169
+
170
+ def _error_code(value: object) -> str | None:
171
+ # Some providers send numeric codes, such as Z.ai's "1302" for a rate limit, and openai's SDK
172
+ # turns OpenRouter's numeric code into a string. A number names no cause the way a class does.
173
+ code = _text(value)
174
+ return None if code is None or code.isdigit() else code
175
+
176
+
177
+ def _http_status(value: object) -> int | None:
178
+ return (
179
+ value
180
+ if isinstance(value, int) and not isinstance(value, bool) and 400 <= value <= 599
181
+ else None
182
+ )
183
+
184
+
185
+ def _nested(value: object, *keys: str) -> object:
186
+ for key in keys:
187
+ if not isinstance(value, Mapping):
188
+ return None
189
+ value = cast("Mapping[str, object]", value).get(key)
190
+ return value
191
+
192
+
193
+ def _attribute(error: BaseException, name: str) -> object:
194
+ # A property of a third-party exception can raise anything; recording the error must not.
195
+ try:
196
+ return getattr(error, name, None)
197
+ except Exception:
198
+ return None
199
+
200
+
201
+ def _error_type(error: BaseException) -> str:
202
+ """The error.type of a failure: the provider's error code when the error carries one.
203
+
204
+ - An error with an HTTP status and a code that is not only digits (openai's
205
+ `insufficient_quota`, `context_length_exceeded`) gives the code.
206
+ - A generic provider error class gives its code, else its HTTP status (`429`), else the
207
+ provider's error type (anthropic's `overloaded_error` from a stream).
208
+ - Any other error gives its class name.
209
+ """
210
+ name = type(error).__name__
211
+ body = _attribute(error, "body")
212
+ code = _error_code(_attribute(error, "code")) or _error_code(_nested(body, "error", "code"))
213
+ status = next(
214
+ (
215
+ status
216
+ for status in (
217
+ _http_status(_attribute(error, attribute))
218
+ for attribute in ("status_code", "code", "status")
219
+ )
220
+ if status is not None
221
+ ),
222
+ None,
223
+ )
224
+ if code is not None and status is not None:
225
+ return code
226
+ if name not in _GENERIC_ERROR_NAMES:
227
+ return name
228
+ if code is not None:
229
+ return code
230
+ if status is not None:
231
+ return str(status)
232
+ aws_code = _text(_nested(_attribute(error, "response"), "Error", "Code"))
233
+ if aws_code is not None:
234
+ # botocore names a Bedrock stream's exception by its event, such as
235
+ # modelStreamErrorException; the TypeScript SDK records its class,
236
+ # ModelStreamErrorException.
237
+ aws_code = aws_code[0].upper() + aws_code[1:]
238
+ return (
239
+ _text(_attribute(error, "type"))
240
+ or _text(_nested(body, "error", "type"))
241
+ or aws_code
242
+ or name
243
+ )
244
+
245
+
154
246
  def _record_error_on_span(
155
247
  client: Client, span: Span, state: _SpanState, error: BaseException
156
248
  ) -> None:
157
- error_type = type(error).__name__
249
+ error_type = _error_type(error)
158
250
  span.set_attribute(ATTR_ERROR_TYPE, error_type)
159
251
  span.set_status(Status(StatusCode.ERROR))
160
252
  attributes: dict[str, otel_types.AttributeValue] = {
File without changes