telemetry-dev 0.3.3__tar.gz → 0.3.5__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.3/README.md → telemetry_dev-0.3.5/PKG-INFO +44 -4
  2. telemetry_dev-0.3.3/PKG-INFO → telemetry_dev-0.3.5/README.md +17 -29
  3. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/pyproject.toml +3 -1
  4. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/pyproject.toml.orig +7 -1
  5. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_client.py +5 -1
  6. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_experiments.py +102 -8
  7. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_export.py +77 -8
  8. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_metrics.py +3 -5
  9. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_spans.py +5 -2
  10. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/otel.py +2 -0
  11. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/LICENSE +0 -0
  12. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/__init__.py +0 -0
  13. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_api.py +0 -0
  14. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_capture.py +0 -0
  15. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_ci.py +0 -0
  16. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_config.py +0 -0
  17. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_context.py +0 -0
  18. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_logs.py +0 -0
  19. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_observe.py +0 -0
  20. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_process_lock.py +0 -0
  21. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_processor.py +0 -0
  22. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_prompts.py +0 -0
  23. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_scores.py +0 -0
  24. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_semconv.py +0 -0
  25. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/_serialize.py +0 -0
  26. {telemetry_dev-0.3.3 → telemetry_dev-0.3.5}/src/telemetry_dev/py.typed +0 -0
@@ -1,3 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: telemetry-dev
3
+ Version: 0.3.5
4
+ Summary: telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics
5
+ Keywords: telemetry,opentelemetry,llm,genai,tracing,observability
6
+ Author: telemetry.dev
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Typing :: Typed
17
+ Requires-Dist: opentelemetry-api>=1.39.0,<2
18
+ Requires-Dist: opentelemetry-sdk>=1.39.0,<2
19
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.39.0,<2
20
+ Requires-Dist: googleapis-common-protos>=1.63.1,<2
21
+ Requires-Dist: requests>=2.28,<3
22
+ Requires-Dist: rfc8785>=0.1.4
23
+ Requires-Python: >=3.10
24
+ Project-URL: Homepage, https://telemetry.dev
25
+ Project-URL: Repository, https://github.com/telemetry-dev/telemetry
26
+ Description-Content-Type: text/markdown
27
+
1
28
  # telemetry-dev
2
29
 
3
30
  telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics. Thin
@@ -74,6 +101,11 @@ initialization. Explicit and propagated session IDs take precedence, and valid p
74
101
  context is preserved. The generated session ends when the client is shut down or replaced; a
75
102
  later `init()` generates a new ID. It is not persisted across processes.
76
103
 
104
+ The root spans of a session join one trace for each API key, and the trace keeps the environment
105
+ of its first turn. When one key sends turns of the same session id from two environments, the
106
+ later turns show under the first environment, or get a 403 when the key may not send that
107
+ environment. Use a key for each environment, or give each environment its own session ids.
108
+
77
109
  ## API reference
78
110
 
79
111
  | Name | Description |
@@ -388,10 +420,16 @@ result = telemetry_dev.run_experiment(
388
420
  it when it got none.
389
421
  - The key needs Run experiments in its Access on the API keys page (the `datasets:read` and
390
422
  `experiments:write` scopes). `run_experiment` uses the same
391
- API key and base URL as `get_prompt`, or its own `api_key` and `base_url`. With
392
- `environment="experiment"`, the key of the telemetry client must be for all environments or for
393
- `experiment`: a key for another environment cannot send the traces of the items, and the items
394
- then have no trace and no cost.
423
+ API key and base URL as `get_prompt`, or its own `api_key` and `base_url`.
424
+ - The items send their traces with the key of the telemetry client, which needs Send telemetry. A
425
+ key for one environment also sends the `experiment` environment when it has Run experiments.
426
+ Without a client, without Send telemetry, with a key for another environment and no Run
427
+ experiments, or when Accept telemetry is off in the project settings, the items have no trace
428
+ and no cost. The export error says why, and the job summary of the experiment action says that
429
+ the runs have no traces, with the reason of the ingest.
430
+ - When the ingest refuses a trace export because the key is not valid (401), for example after
431
+ the key was revoked or its project was deleted, and the client sends with the key and the base
432
+ URL of the run, `run_experiment` starts no more items and raises `ExperimentError` with `invalid_api_key`.
395
433
 
396
434
  The outputs, the exceptions of failed tasks, the scorer reasons, and `metadata` go to telemetry.dev
397
435
  and stay with the experiment, because they are its result. `capture_output`, `mask`, and the
@@ -435,6 +473,8 @@ telemetry_dev.score(
435
473
  ```
436
474
 
437
475
  - Give `trace_id`, `session_id`, or the two, and a `span_id` of the trace for a score on one span.
476
+ With a `trace_id`, the score belongs to that trace and shows in the session of the trace, even
477
+ when the `session_id` names another session.
438
478
  Give `value`, `label`, or the two. `user_feedback` takes the value 1 for up or 0 for down, and
439
479
  no label. A pass/fail score has the label `pass` with the value 1, or `fail` with 0.
440
480
  - Like the telemetry functions, `score` never raises. It returns the id of the score, or `None`
@@ -1,28 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: telemetry-dev
3
- Version: 0.3.3
4
- Summary: telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics
5
- Keywords: telemetry,opentelemetry,llm,genai,tracing,observability
6
- Author: telemetry.dev
7
- License-Expression: MIT
8
- License-File: LICENSE
9
- Classifier: Development Status :: 4 - Beta
10
- Classifier: Intended Audience :: Developers
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.10
13
- Classifier: Programming Language :: Python :: 3.11
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.13
16
- Classifier: Typing :: Typed
17
- Requires-Dist: opentelemetry-api>=1.39.0,<2
18
- Requires-Dist: opentelemetry-sdk>=1.39.0,<2
19
- Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.39.0,<2
20
- Requires-Dist: rfc8785>=0.1.4
21
- Requires-Python: >=3.10
22
- Project-URL: Homepage, https://telemetry.dev
23
- Project-URL: Repository, https://github.com/telemetry-dev/telemetry
24
- Description-Content-Type: text/markdown
25
-
26
1
  # telemetry-dev
27
2
 
28
3
  telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics. Thin
@@ -99,6 +74,11 @@ initialization. Explicit and propagated session IDs take precedence, and valid p
99
74
  context is preserved. The generated session ends when the client is shut down or replaced; a
100
75
  later `init()` generates a new ID. It is not persisted across processes.
101
76
 
77
+ The root spans of a session join one trace for each API key, and the trace keeps the environment
78
+ of its first turn. When one key sends turns of the same session id from two environments, the
79
+ later turns show under the first environment, or get a 403 when the key may not send that
80
+ environment. Use a key for each environment, or give each environment its own session ids.
81
+
102
82
  ## API reference
103
83
 
104
84
  | Name | Description |
@@ -413,10 +393,16 @@ result = telemetry_dev.run_experiment(
413
393
  it when it got none.
414
394
  - The key needs Run experiments in its Access on the API keys page (the `datasets:read` and
415
395
  `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.
396
+ API key and base URL as `get_prompt`, or its own `api_key` and `base_url`.
397
+ - The items send their traces with the key of the telemetry client, which needs Send telemetry. A
398
+ key for one environment also sends the `experiment` environment when it has Run experiments.
399
+ Without a client, without Send telemetry, with a key for another environment and no Run
400
+ experiments, or when Accept telemetry is off in the project settings, the items have no trace
401
+ and no cost. The export error says why, and the job summary of the experiment action says that
402
+ the runs have no traces, with the reason of the ingest.
403
+ - When the ingest refuses a trace export because the key is not valid (401), for example after
404
+ the key was revoked or its project was deleted, and the client sends with the key and the base
405
+ URL of the run, `run_experiment` starts no more items and raises `ExperimentError` with `invalid_api_key`.
420
406
 
421
407
  The outputs, the exceptions of failed tasks, the scorer reasons, and `metadata` go to telemetry.dev
422
408
  and stay with the experiment, because they are its result. `capture_output`, `mask`, and the
@@ -460,6 +446,8 @@ telemetry_dev.score(
460
446
  ```
461
447
 
462
448
  - Give `trace_id`, `session_id`, or the two, and a `span_id` of the trace for a score on one span.
449
+ With a `trace_id`, the score belongs to that trace and shows in the session of the trace, even
450
+ when the `session_id` names another session.
463
451
  Give `value`, `label`, or the two. `user_feedback` takes the value 1 for up or 0 for down, and
464
452
  no label. A pass/fail score has the label `pass` with the value 1, or `fail` with 0.
465
453
  - Like the telemetry functions, `score` never raises. It returns the id of the score, or `None`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.3.3"
3
+ version = "0.3.5"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -28,6 +28,8 @@ dependencies = [
28
28
  "opentelemetry-api>=1.39.0,<2",
29
29
  "opentelemetry-sdk>=1.39.0,<2",
30
30
  "opentelemetry-exporter-otlp-proto-http>=1.39.0,<2",
31
+ "googleapis-common-protos>=1.63.1,<2",
32
+ "requests>=2.28,<3",
31
33
  "rfc8785>=0.1.4",
32
34
  ]
33
35
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev"
3
- version = "0.3.3"
3
+ version = "0.3.5"
4
4
  description = "telemetry.dev SDK for Python — OpenTelemetry-native GenAI tracing, logs, and metrics"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -22,6 +22,12 @@ dependencies = [
22
22
  "opentelemetry-api>=1.39.0,<2",
23
23
  "opentelemetry-sdk>=1.39.0,<2",
24
24
  "opentelemetry-exporter-otlp-proto-http>=1.39.0,<2",
25
+ # The OTLP exporter sends with requests, and the ingest answers a refused export with a
26
+ # google.rpc.Status. The exporter requires both; the SDK reads the Status of the response.
27
+ # 1.63.1 is the first release that imports with protobuf 5, which opentelemetry-proto needs.
28
+ # The requests floor of the exporter, 2.7, does not import on Python 3.10; 2.28 does.
29
+ "googleapis-common-protos>=1.63.1,<2",
30
+ "requests>=2.28,<3",
25
31
  "rfc8785>=0.1.4",
26
32
  ]
27
33
 
@@ -50,6 +50,7 @@ from ._export import (
50
50
  ReportingLogExporter,
51
51
  ReportingSpanExporter,
52
52
  after_export,
53
+ otlp_session,
53
54
  resolve_byte_bound,
54
55
  )
55
56
  from ._metrics import (
@@ -156,6 +157,7 @@ class Client:
156
157
  self._logger_provider: LoggerProvider | None = None
157
158
  self._meter_provider: MeterProvider | None = None
158
159
  self._output_chunks: OutputChunkAggregation | None = None
160
+ self.export_failures: ExportFailures = ExportFailures(on_error)
159
161
 
160
162
  if not enabled:
161
163
  return
@@ -185,7 +187,7 @@ class Client:
185
187
  ),
186
188
  )
187
189
  self._tracer_provider.sampler = SessionSampler(self._tracer_provider.sampler)
188
- failures = ExportFailures(on_error)
190
+ failures = self.export_failures
189
191
 
190
192
  # Without an api key (enabled via a test seam), never construct real network
191
193
  # exporters — they would POST to the ingest with a bogus Authorization header.
@@ -218,6 +220,7 @@ class Client:
218
220
  headers=headers,
219
221
  compression=Compression.Gzip,
220
222
  timeout=timeout,
223
+ session=otlp_session(),
221
224
  ),
222
225
  failures,
223
226
  on_error,
@@ -242,6 +245,7 @@ class Client:
242
245
  headers=headers,
243
246
  compression=Compression.Gzip,
244
247
  timeout=timeout,
248
+ session=otlp_session(),
245
249
  ),
246
250
  failures,
247
251
  on_error,
@@ -14,7 +14,8 @@ import urllib.parse
14
14
  from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence
15
15
  from concurrent.futures import ThreadPoolExecutor
16
16
  from dataclasses import dataclass
17
- from decimal import Decimal
17
+ from decimal import ROUND_HALF_UP, Decimal
18
+ from decimal import Context as DecimalContext
18
19
  from time import perf_counter
19
20
  from typing import Any, Literal, TypeAlias, TypeGuard, cast
20
21
 
@@ -621,6 +622,7 @@ def _run_items(api: Api, run: _Run, created: _Created, runs: _Runs) -> None:
621
622
  def worker() -> None:
622
623
  while not failures:
623
624
  try:
625
+ _check_key(api)
624
626
  item = runs.next()
625
627
  if item is None:
626
628
  return
@@ -648,6 +650,7 @@ async def _run_items_async(api: Api, run: _Run, created: _Created, runs: _Runs)
648
650
  async def worker() -> None:
649
651
  while not failures:
650
652
  try:
653
+ _check_key(api)
651
654
  item = await asyncio.to_thread(runs.next)
652
655
  if item is None:
653
656
  return
@@ -661,6 +664,43 @@ async def _run_items_async(api: Api, run: _Run, created: _Created, runs: _Runs)
661
664
  await asyncio.to_thread(_end_items, batch, runs, failures)
662
665
 
663
666
 
667
+ def _check_key(api: Api) -> None:
668
+ """Raise when the ingest refused an export of the client with 401 since an export last
669
+ reached it, and the client sends with the key of the run to the same server. The key then
670
+ stopped working, for example because it was revoked or its project was deleted, and the API
671
+ will refuse the results of the items too."""
672
+ client = get_client()
673
+ if (
674
+ client is None
675
+ or client.config.api_key != api.api_key
676
+ or client.config.base_url != api.base_url
677
+ ):
678
+ return
679
+ rejected = client.export_failures.rejected
680
+ if rejected is not None and rejected.status == 401:
681
+ error = ExperimentError(
682
+ "invalid_api_key",
683
+ f"The API key was not accepted, so no more items run: {rejected}",
684
+ 401,
685
+ )
686
+ error.__cause__ = rejected
687
+ raise error
688
+
689
+
690
+ def _traces() -> dict[str, Any]:
691
+ """For the results line of the experiment action: ``traced`` is False without an enabled
692
+ client, or when the ingest refused an export of the client with 401 or 403 since an export
693
+ last reached it, and ``tracesError`` then gives its reason. Exports that failed for another
694
+ reason, such as an outage, are not counted."""
695
+ client = get_client()
696
+ if client is None or not client.enabled:
697
+ return {"traced": False}
698
+ rejected = client.export_failures.rejected
699
+ if rejected is not None:
700
+ return {"traced": False, "tracesError": str(rejected)}
701
+ return {"traced": True}
702
+
703
+
664
704
  def _end_items(batch: _Batch, runs: _Runs, failures: list[BaseException]) -> None:
665
705
  if not failures:
666
706
  try:
@@ -899,7 +939,12 @@ def _finish(api: Api, run: _Run, created: _Created) -> ExperimentResult:
899
939
  _complete(api, created)
900
940
  result, body = _wait_for_result(api, created.id)
901
941
  # The action skips the check of a result with the CI mode off, and counts the items from runs.
902
- line = {**cast("dict[str, Any]", body), "ci": run.in_ci, "runsPerItem": run.runs_per_item}
942
+ line = {
943
+ **cast("dict[str, Any]", body),
944
+ "ci": run.in_ci,
945
+ "runsPerItem": run.runs_per_item,
946
+ **_traces(),
947
+ }
903
948
  write_result(os.environ, line, api.on_error)
904
949
  print(_describe(result, run.runs_per_item), flush=True)
905
950
  if run.in_ci:
@@ -956,12 +1001,7 @@ def _check_result(result: ExperimentResult, runs_per_item: int) -> None:
956
1001
  )
957
1002
  if result.check_status != "failed":
958
1003
  return
959
- failed = [
960
- f"{score.name} is {_format(score.kind, score.value)}, under the pass mark "
961
- f"{_format(score.kind, score.min_score)}"
962
- for score in result.scores
963
- if score.passed is False
964
- ]
1004
+ failed = [_under_mark(score) for score in result.scores if score.passed is False]
965
1005
  if result.items_failed > 0:
966
1006
  failed.insert(0, _items_failed_text(result, runs_per_item))
967
1007
  detail = f": {'; '.join(failed)}" if failed else ""
@@ -981,6 +1021,60 @@ def _items_failed_text(result: ExperimentResult, runs_per_item: int) -> str:
981
1021
  return f"{result.items_failed} of {result.items_done} {unit} failed"
982
1022
 
983
1023
 
1024
+ def _under_mark(score: ExperimentScore) -> str:
1025
+ """A score under its pass mark, with the numbers of the annotation of the action.
1026
+
1027
+ The mark has 10 decimals. The value has 2 decimals for a rate and 3 otherwise, and one more
1028
+ while it rounds to the mark or above it, up to 17, so that a value just under the mark does not
1029
+ read as the mark. A rate shows both as percents. A score with no kind had no values: a mark of
1030
+ 1 or less on it is a pass rate, as the action reads it.
1031
+ """
1032
+ rate = score.kind in _RATE_KINDS or (
1033
+ score.kind is None and score.min_score is not None and score.min_score <= 1
1034
+ )
1035
+
1036
+ def rounded(number: float, digits: int) -> float:
1037
+ # float() first: a whole number from the JSON is an int, which JavaScript holds as a float.
1038
+ return _js_fixed(float(number) * 100 if rate else float(number), digits)
1039
+
1040
+ def text(number: float) -> str:
1041
+ return _js_string(number) + ("%" if rate else "")
1042
+
1043
+ mark = None if score.min_score is None else rounded(score.min_score, 10)
1044
+ mark_text = "no score" if mark is None else text(mark)
1045
+ if score.value is None:
1046
+ return f"{score.name} is no score, under the pass mark {mark_text}"
1047
+ digits = 2 if rate else 3
1048
+ while mark is not None and digits < 17 and rounded(score.value, digits) >= mark:
1049
+ digits += 1
1050
+ return f"{score.name} is {text(rounded(score.value, digits))}, under the pass mark {mark_text}"
1051
+
1052
+
1053
+ def _js_fixed(number: float, digits: int) -> float:
1054
+ # +number.toFixed(digits) of JavaScript: the exact value with a half rounded away from zero.
1055
+ # The precision holds the 309 whole digits of the largest float and the decimals.
1056
+ step = Decimal(1).scaleb(-digits)
1057
+ return float(Decimal(number).quantize(step, ROUND_HALF_UP, DecimalContext(prec=400)))
1058
+
1059
+
1060
+ def _js_string(number: float) -> str:
1061
+ """String(number) of JavaScript: the digits of repr(), with an exponent under 1e-6 and from
1062
+ 1e21 only, and no ".0" or "-0"."""
1063
+ _, digit_tuple, exponent = Decimal(repr(abs(number))).normalize().as_tuple()
1064
+ digits = "".join(map(str, digit_tuple))
1065
+ point = len(digits) + int(exponent)
1066
+ if len(digits) <= point <= 21:
1067
+ text = digits + "0" * (point - len(digits))
1068
+ elif 0 < point <= 21:
1069
+ text = f"{digits[:point]}.{digits[point:]}"
1070
+ elif -6 < point <= 0:
1071
+ text = f"0.{'0' * -point}{digits}"
1072
+ else:
1073
+ mantissa = digits if len(digits) == 1 else f"{digits[0]}.{digits[1:]}"
1074
+ text = f"{mantissa}e{'+' if point > 0 else '-'}{abs(point - 1)}"
1075
+ return f"{'-' if number < 0 else ''}{text}"
1076
+
1077
+
984
1078
  def _describe(result: ExperimentResult, runs_per_item: int) -> str:
985
1079
  if result.status != "completed":
986
1080
  outcome = result.status + (f": {result.error}" if result.error else "")
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import atexit
4
4
  import copy
5
+ import json
5
6
  import math
6
7
  import os
7
8
  import threading
@@ -11,6 +12,7 @@ from contextlib import contextmanager
11
12
  from enum import Enum
12
13
  from typing import Any, TypeVar, cast
13
14
 
15
+ import requests
14
16
  from opentelemetry.exporter.otlp.proto.common._log_encoder import encode_logs
15
17
  from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans
16
18
  from opentelemetry.sdk._logs.export import LogRecordExporter, LogRecordExportResult
@@ -434,6 +436,8 @@ _export_state = threading.local()
434
436
  @contextmanager
435
437
  def exporting() -> Generator[None]:
436
438
  """Marks the current thread as inside an export of this SDK while the block runs."""
439
+ if not getattr(_export_state, "depth", 0):
440
+ _export_state.refused = None
437
441
  _export_state.depth = getattr(_export_state, "depth", 0) + 1
438
442
  try:
439
443
  yield
@@ -441,6 +445,67 @@ def exporting() -> Generator[None]:
441
445
  _export_state.depth -= 1
442
446
 
443
447
 
448
+ class IngestError(RuntimeError):
449
+ """A failed export, with the HTTP status that the ingest answered."""
450
+
451
+ def __init__(self, message: str, status: int) -> None:
452
+ super().__init__(message)
453
+ self.status = status
454
+
455
+
456
+ def otlp_session() -> requests.Session:
457
+ """A session for an OTLP exporter of this SDK. It keeps the last response of an export that
458
+ the ingest refused, so that the failure names the reason that the ingest gave. The OTLP
459
+ exporter sends on the thread of the export, thus the response is kept for that thread."""
460
+ session = requests.Session()
461
+ session.hooks["response"].append(_keep_refused)
462
+ return session
463
+
464
+
465
+ def _keep_refused(response: requests.Response, *args: Any, **kwargs: Any) -> None:
466
+ _export_state.refused = None if response.ok else response
467
+
468
+
469
+ def export_error(label: str) -> RuntimeError:
470
+ """The error of a failed export of this thread: the status and the message of the response
471
+ that the ingest refused it with, when there was one."""
472
+ response: requests.Response | None = getattr(_export_state, "refused", None)
473
+ if response is None:
474
+ return RuntimeError(f"OTLP {label} export failed (check the API key and ingest URL)")
475
+ reason = _status_message(response)
476
+ return IngestError(
477
+ f"telemetry.dev {_LABELS.get(label, label)} ingest failed: {response.status_code}"
478
+ + (f" {reason}" if reason else ""),
479
+ response.status_code,
480
+ )
481
+
482
+
483
+ # The labels of the TypeScript transport, so that both SDKs report a failure the same way.
484
+ _LABELS = {"span": "trace"}
485
+
486
+
487
+ def _status_message(response: requests.Response) -> str | None:
488
+ """The message of the JSON or protobuf Status of an OTLP error response, as the telemetry.dev
489
+ ingest sends it, such as "This API key cannot send telemetry. Create a key with Send
490
+ telemetry access." None for another content type, or a body that cannot be read."""
491
+ content_type = response.headers.get("content-type", "")
492
+ try:
493
+ # The exporter has read the whole body; a cut could split the Status.
494
+ body = response.content
495
+ if "json" in content_type:
496
+ message = json.loads(body).get("message")
497
+ elif "protobuf" in content_type:
498
+ # Imported here, so that a protobuf stack that cannot load it loses only the message.
499
+ from google.rpc.status_pb2 import Status
500
+
501
+ message = Status.FromString(body).message
502
+ else:
503
+ return None
504
+ except Exception:
505
+ return None
506
+ return message.strip() or None if isinstance(message, str) else None
507
+
508
+
444
509
  # The keys of the work items whose thread has not finished, each with the process of its thread.
445
510
  # A fork that runs no hooks, as uWSGI's fork of its workers by default, copies the keys but not
446
511
  # the threads, so a key of another process does not count.
@@ -527,9 +592,18 @@ class ExportFailures:
527
592
  self._on_error = on_error
528
593
  self._lock = ProcessLock(threading.Lock)
529
594
  self._reported = False
595
+ self._rejected: IngestError | None = None
596
+
597
+ @property
598
+ def rejected(self) -> IngestError | None:
599
+ """The last export that the ingest refused with 401 (the API key is not valid) or 403
600
+ (the key cannot send telemetry) since an export reached the ingest."""
601
+ return self._rejected
530
602
 
531
603
  def report(self, message: str, exc: BaseException) -> None:
532
604
  with self._lock():
605
+ if isinstance(exc, IngestError) and exc.status in (401, 403):
606
+ self._rejected = exc
533
607
  if self._reported:
534
608
  return
535
609
  self._reported = True
@@ -541,6 +615,7 @@ class ExportFailures:
541
615
  """Records that an export reached the ingest, so that report() sends the next failure."""
542
616
  with self._lock():
543
617
  self._reported = False
618
+ self._rejected = None
544
619
 
545
620
 
546
621
  class ReportingSpanExporter(SpanExporter):
@@ -577,10 +652,7 @@ class ReportingSpanExporter(SpanExporter):
577
652
  # Every record was dropped: the export did not fail, and the series goes on.
578
653
  return SpanExportResult.SUCCESS
579
654
  if result is SpanExportResult.FAILURE:
580
- self._failures.report(
581
- "span export failed",
582
- RuntimeError("OTLP span export failed (check the API key and ingest URL)"),
583
- )
655
+ self._failures.report("span export failed", export_error("span"))
584
656
  else:
585
657
  self._failures.clear()
586
658
  return result
@@ -625,10 +697,7 @@ class ReportingLogExporter(LogRecordExporter):
625
697
  # Every record was dropped: the export did not fail, and the series goes on.
626
698
  return LogRecordExportResult.SUCCESS
627
699
  if result is LogRecordExportResult.FAILURE:
628
- self._failures.report(
629
- "log export failed",
630
- RuntimeError("OTLP log export failed (check the API key and ingest URL)"),
631
- )
700
+ self._failures.report("log export failed", export_error("log"))
632
701
  else:
633
702
  self._failures.clear()
634
703
  return result
@@ -27,7 +27,7 @@ from opentelemetry.sdk.trace import ReadableSpan
27
27
  from opentelemetry.trace import INVALID_SPAN_CONTEXT, NonRecordingSpan, set_span_in_context
28
28
 
29
29
  from ._config import report_error
30
- from ._export import ExportFailures, exporting
30
+ from ._export import ExportFailures, export_error, exporting, otlp_session
31
31
  from ._process_lock import ProcessLock
32
32
  from ._semconv import (
33
33
  ATTR_ERROR_TYPE,
@@ -177,6 +177,7 @@ class GuardedOTLPMetricExporter(OTLPMetricExporter):
177
177
  failures: ExportFailures,
178
178
  **kwargs: Any,
179
179
  ) -> None:
180
+ kwargs.setdefault("session", otlp_session())
180
181
  super().__init__(*args, **kwargs) # pyright: ignore[reportUnknownMemberType]
181
182
  self._td_failures = failures
182
183
  self.output_chunks: OutputChunkAggregation | None = None
@@ -201,10 +202,7 @@ class GuardedOTLPMetricExporter(OTLPMetricExporter):
201
202
  self._td_failures.report("metric export failed", exc)
202
203
  return MetricExportResult.FAILURE
203
204
  if result is MetricExportResult.FAILURE:
204
- self._td_failures.report(
205
- "metric export failed",
206
- RuntimeError("OTLP metric export failed (check the API key and ingest URL)"),
207
- )
205
+ self._td_failures.report("metric export failed", export_error("metric"))
208
206
  else:
209
207
  self._td_failures.clear()
210
208
  return result
@@ -740,9 +740,12 @@ def start_span(
740
740
  )
741
741
  attrs = _fields_to_attributes(client, state, fields)
742
742
  initial: dict[str, otel_types.AttributeValue] = {ATTR_OPERATION: operation}
743
- if operation == "execute_tool":
743
+ # A span named after its operation, such as "invoke_agent" or "invoke_agent AGENT123" from
744
+ # an integration that names it by id, names no agent or tool.
745
+ named = name != operation and not name.startswith(f"{operation} ")
746
+ if operation == "execute_tool" and named:
744
747
  initial[ATTR_TOOL_NAME] = name
745
- elif operation == "invoke_agent":
748
+ elif operation == "invoke_agent" and named:
746
749
  initial[ATTR_AGENT_NAME] = name
747
750
  ctx = context_from_parent(parent)
748
751
  propagated = propagated_attributes(ctx)
@@ -28,6 +28,7 @@ from ._export import (
28
28
  ExportFailures,
29
29
  ReportingSpanExporter,
30
30
  after_export,
31
+ otlp_session,
31
32
  resolve_byte_bound,
32
33
  )
33
34
  from ._metrics import GuardedOTLPMetricExporter, MetricsRecorder, sdk_meter_provider
@@ -70,6 +71,7 @@ def _otlp_span_exporter(
70
71
  },
71
72
  compression=Compression.Gzip,
72
73
  timeout=timeout,
74
+ session=otlp_session(),
73
75
  )
74
76
 
75
77
 
File without changes