struct-sdk 0.5.27__tar.gz → 0.5.29__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.
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/PKG-INFO +10 -5
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/PYPI.md +3 -2
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/README.md +2 -2
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/pyproject.toml +13 -6
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_auto.py +7 -7
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/health.py +2 -2
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_operation_details.py +4 -7
- struct_sdk-0.5.29/src/struct_sdk/_otel_logs.py +52 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/anthropic.py +36 -4
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/autogen.py +45 -12
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/core.py +156 -51
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/litellm.py +1 -1
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/mcp.py +43 -23
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/.gitignore +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/LICENSE +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/__init__.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_container.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_distro.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_event_loop.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_fork_safe_http.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_genai_content.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_metrics.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/__init__.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/config.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/identity.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/native_events.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/outputs.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/poller.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/routing.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/runtime.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/self_metrics.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_observations/uwsgi.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/_pool.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/ag2.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/claude_agent.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/crewai.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/gcp.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/google_genai.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/langchain.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/llamaindex.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/openai.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/openai_agents.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/pydantic_ai.py +0 -0
- {struct_sdk-0.5.27 → struct_sdk-0.5.29}/src/struct_sdk/temporal.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: struct-sdk
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.29
|
|
4
4
|
Summary: Python SDK for OTel auto-instrumentation and live instrumentation on Struct.
|
|
5
5
|
Project-URL: Homepage, https://struct.ai
|
|
6
6
|
Project-URL: Documentation, https://docs.struct.ai/observability/instrumentation/python
|
|
@@ -18,14 +18,16 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
18
18
|
Classifier: Programming Language :: Python :: 3.11
|
|
19
19
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
20
|
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
22
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
23
|
Classifier: Topic :: System :: Monitoring
|
|
23
24
|
Requires-Python: >=3.10
|
|
24
25
|
Requires-Dist: opentelemetry-api>=1.45.1
|
|
25
26
|
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
|
|
27
|
+
Requires-Dist: opentelemetry-instrumentation-logging>=0.66b1
|
|
26
28
|
Requires-Dist: opentelemetry-sdk>=1.27.0
|
|
27
|
-
Requires-Dist: struct-sdk-native==0.2.
|
|
28
|
-
Requires-Dist: wrapt>=1.
|
|
29
|
+
Requires-Dist: struct-sdk-native==0.2.1
|
|
30
|
+
Requires-Dist: wrapt>=1.17.3
|
|
29
31
|
Provides-Extra: anthropic
|
|
30
32
|
Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
|
|
31
33
|
Provides-Extra: auto
|
|
@@ -99,6 +101,7 @@ Provides-Extra: langchain
|
|
|
99
101
|
Requires-Dist: langchain-core>=1.3.3; extra == 'langchain'
|
|
100
102
|
Provides-Extra: litellm
|
|
101
103
|
Requires-Dist: litellm[mcp]>=1.70.0; extra == 'litellm'
|
|
104
|
+
Requires-Dist: litellm[mcp]>=1.93.0; (python_version >= '3.14') and extra == 'litellm'
|
|
102
105
|
Provides-Extra: llamaindex
|
|
103
106
|
Requires-Dist: llama-index-core>=0.13.0; extra == 'llamaindex'
|
|
104
107
|
Provides-Extra: mcp
|
|
@@ -113,6 +116,7 @@ Provides-Extra: structlog
|
|
|
113
116
|
Requires-Dist: opentelemetry-instrumentation-structlog; extra == 'structlog'
|
|
114
117
|
Provides-Extra: temporal
|
|
115
118
|
Requires-Dist: temporalio>=1.11.0; extra == 'temporal'
|
|
119
|
+
Requires-Dist: temporalio>=1.19.0; (python_version >= '3.14') and extra == 'temporal'
|
|
116
120
|
Description-Content-Type: text/markdown
|
|
117
121
|
|
|
118
122
|
# Struct Python SDK
|
|
@@ -167,5 +171,6 @@ the OpenAI Agents SDK, and the Claude Agent SDK.
|
|
|
167
171
|
|
|
168
172
|
Publish an Observation through the Struct CLI or ask your coding agent to set
|
|
169
173
|
one up. An Observation tells the running SDK where to capture events, spans,
|
|
170
|
-
or metrics. Live capture requires a supported native runtime on CPython 3.12
|
|
171
|
-
or 3.
|
|
174
|
+
or metrics. Live capture requires a supported native runtime on CPython 3.12,
|
|
175
|
+
3.13, or 3.14 (3.14.5 or later; free-threaded builds aren't supported) and a key
|
|
176
|
+
with access to Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
|
|
@@ -50,5 +50,6 @@ the OpenAI Agents SDK, and the Claude Agent SDK.
|
|
|
50
50
|
|
|
51
51
|
Publish an Observation through the Struct CLI or ask your coding agent to set
|
|
52
52
|
one up. An Observation tells the running SDK where to capture events, spans,
|
|
53
|
-
or metrics. Live capture requires a supported native runtime on CPython 3.12
|
|
54
|
-
or 3.
|
|
53
|
+
or metrics. Live capture requires a supported native runtime on CPython 3.12,
|
|
54
|
+
3.13, or 3.14 (3.14.5 or later; free-threaded builds aren't supported) and a key
|
|
55
|
+
with access to Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
|
|
@@ -11,8 +11,8 @@ when checkout fails.
|
|
|
11
11
|
pip install "struct-sdk[auto]"
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
The SDK requires Python 3.10 or later. Observations require
|
|
15
|
-
CPython 3.12 or 3.
|
|
14
|
+
The SDK requires Python 3.10 or later. Observations require the native runtime on
|
|
15
|
+
CPython 3.12, 3.13, or 3.14 (3.14.5 or later); free-threaded builds aren't supported.
|
|
16
16
|
|
|
17
17
|
## Quickstart
|
|
18
18
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "struct-sdk"
|
|
7
|
-
version = "0.5.
|
|
7
|
+
version = "0.5.29"
|
|
8
8
|
description = "Python SDK for OTel auto-instrumentation and live instrumentation on Struct."
|
|
9
9
|
readme = "PYPI.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -21,6 +21,7 @@ classifiers = [
|
|
|
21
21
|
"Programming Language :: Python :: 3.11",
|
|
22
22
|
"Programming Language :: Python :: 3.12",
|
|
23
23
|
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Programming Language :: Python :: 3.14",
|
|
24
25
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
26
|
"Topic :: System :: Monitoring",
|
|
26
27
|
]
|
|
@@ -28,12 +29,16 @@ dependencies = [
|
|
|
28
29
|
"opentelemetry-api>=1.45.1",
|
|
29
30
|
"opentelemetry-sdk>=1.27.0",
|
|
30
31
|
"opentelemetry-exporter-otlp-proto-http>=1.27.0",
|
|
32
|
+
# The app-log bridge's handler. OpenTelemetry 1.46.0 removed the SDK's own;
|
|
33
|
+
# 0.66b1 is the first release paired with API 1.45.1.
|
|
34
|
+
"opentelemetry-instrumentation-logging>=0.66b1",
|
|
31
35
|
# Stream proxies (struct_sdk.openai): isinstance-transparent, as in
|
|
32
36
|
# OpenLLMetry and ddtrace. Already required by every OTel instrumentor.
|
|
33
|
-
|
|
37
|
+
# 1.17.3 is the first release with CPython 3.14 wheels.
|
|
38
|
+
"wrapt>=1.17.3",
|
|
34
39
|
# Native capture runtime. Always installs: platforms without a native build
|
|
35
40
|
# get its pure py3-none-any wheel, which reports the capability unavailable.
|
|
36
|
-
"struct-sdk-native==0.2.
|
|
41
|
+
"struct-sdk-native==0.2.1",
|
|
37
42
|
]
|
|
38
43
|
|
|
39
44
|
[project.urls]
|
|
@@ -70,7 +75,8 @@ google-genai = ["google-genai>=1.12.1"]
|
|
|
70
75
|
# suite runs against. Recent LiteLLM releases import their MCP client (mcp 2.x)
|
|
71
76
|
# whenever a completion passes ``tools``, and fail without it; LiteLLM's own
|
|
72
77
|
# ``mcp`` extra installs it (releases without that extra ignore it).
|
|
73
|
-
|
|
78
|
+
# LiteLLM releases before 1.93.0 refuse Python 3.14.
|
|
79
|
+
litellm = ["litellm[mcp]>=1.70.0", "litellm[mcp]>=1.93.0; python_version >= '3.14'"]
|
|
74
80
|
# LlamaIndex's instrumentation dispatcher and agent workflows; 0.13.0 is the
|
|
75
81
|
# first release whose workflow agents run their own steps.
|
|
76
82
|
llamaindex = ["llama-index-core>=0.13.0"]
|
|
@@ -135,7 +141,8 @@ structlog = ["opentelemetry-instrumentation-structlog"]
|
|
|
135
141
|
exceptions = ["opentelemetry-instrumentation-exceptions"]
|
|
136
142
|
azure = ["azure-core-tracing-opentelemetry>=1.0.0b11"]
|
|
137
143
|
# TracingInterceptor(always_create_workflow_spans=...) exists from 1.11.0 onward.
|
|
138
|
-
|
|
144
|
+
# CPython 3.14 needs 1.19.0 or later.
|
|
145
|
+
temporal = ["temporalio>=1.11.0", "temporalio>=1.19.0; python_version >= '3.14'"]
|
|
139
146
|
demo = [
|
|
140
147
|
"langchain>=1.3.9",
|
|
141
148
|
"langchain-core>=1.3.3",
|
|
@@ -264,7 +271,7 @@ conflicts = [
|
|
|
264
271
|
[{ group = "dev" }, { extra = "litellm" }],
|
|
265
272
|
]
|
|
266
273
|
# Lock development environments on Python 3.11+ only; CI runs every suite on
|
|
267
|
-
# 3.12. Published metadata still allows 3.10. Pillow 13, the first release
|
|
274
|
+
# 3.12 and 3.14. Published metadata still allows 3.10. Pillow 13, the first release
|
|
268
275
|
# with the fixes for its 2026 CVEs, needs 3.11, so a 3.10 lock entry
|
|
269
276
|
# could only hold vulnerable Pillow 12.
|
|
270
277
|
environments = ["python_full_version >= '3.11'"]
|
|
@@ -34,14 +34,14 @@ from dataclasses import dataclass, field
|
|
|
34
34
|
from importlib.metadata import PackageNotFoundError, entry_points, version
|
|
35
35
|
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional
|
|
36
36
|
|
|
37
|
-
from opentelemetry import
|
|
37
|
+
from opentelemetry import context, metrics, trace
|
|
38
38
|
from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY, Context
|
|
39
39
|
from opentelemetry.propagators.textmap import TextMapPropagator
|
|
40
|
-
from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
41
40
|
from opentelemetry.sdk.metrics import MeterProvider
|
|
42
41
|
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
|
|
43
42
|
|
|
44
|
-
from struct_sdk import _metrics
|
|
43
|
+
from struct_sdk import _metrics, _otel_logs
|
|
44
|
+
from struct_sdk._otel_logs import LoggerProvider, LogRecordProcessor
|
|
45
45
|
from struct_sdk.core import (
|
|
46
46
|
_body_value,
|
|
47
47
|
_contain_logged,
|
|
@@ -272,7 +272,7 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
272
272
|
|
|
273
273
|
host_tracer_provider = trace.get_tracer_provider()
|
|
274
274
|
host_meter_provider = metrics.get_meter_provider()
|
|
275
|
-
host_logger_provider =
|
|
275
|
+
host_logger_provider = _otel_logs.api.get_logger_provider()
|
|
276
276
|
options = _with_env_disabled(options)
|
|
277
277
|
owns_traces = isinstance(host_tracer_provider, trace.ProxyTracerProvider)
|
|
278
278
|
no_host = owns_traces and _is_unset(host_meter_provider) and _is_unset(host_logger_provider)
|
|
@@ -312,7 +312,7 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
312
312
|
sdk._meter_provider = meter_provider
|
|
313
313
|
metrics.set_meter_provider(meter_provider)
|
|
314
314
|
if owns_logs:
|
|
315
|
-
|
|
315
|
+
_otel_logs.api.set_logger_provider(logger_provider)
|
|
316
316
|
|
|
317
317
|
if _enabled(options, METRICS):
|
|
318
318
|
def attach_metrics() -> None:
|
|
@@ -928,8 +928,8 @@ class _ExportPathFilteringLogProcessor(LogRecordProcessor):
|
|
|
928
928
|
if not self._skip(log_data):
|
|
929
929
|
_safe(lambda: self._inner.emit(log_data), site="auto.host_logs.emit") # type: ignore[attr-defined] # ty: ignore[missing-attribute]
|
|
930
930
|
|
|
931
|
-
def shutdown(self) -> None:
|
|
932
|
-
_shut_down_within(self._inner, self._budget_seconds)
|
|
931
|
+
def shutdown(self, timeout_millis: float = 30_000, **_kwargs: Any) -> None:
|
|
932
|
+
_shut_down_within(self._inner, min(self._budget_seconds, max(0, timeout_millis) / 1000))
|
|
933
933
|
|
|
934
934
|
def force_flush(self, timeout_millis: int = 30000) -> bool:
|
|
935
935
|
flushed = False
|
|
@@ -23,10 +23,10 @@ from typing import Any, Callable, Mapping, Optional, Sequence
|
|
|
23
23
|
from uuid import uuid4
|
|
24
24
|
|
|
25
25
|
from opentelemetry import context
|
|
26
|
-
from opentelemetry._logs import LogRecord, LoggerProvider, SeverityNumber
|
|
27
26
|
from opentelemetry.context import Context, _SUPPRESS_INSTRUMENTATION_KEY
|
|
28
27
|
|
|
29
28
|
from struct_sdk import core
|
|
29
|
+
from struct_sdk._otel_logs import LogRecord, SeverityNumber, api
|
|
30
30
|
from struct_sdk._observations.poller import ConfigClientStatus, ObservationConfigClient
|
|
31
31
|
|
|
32
32
|
_MAX_INT = (1 << 63) - 1
|
|
@@ -154,7 +154,7 @@ class ObservationHealth:
|
|
|
154
154
|
"""
|
|
155
155
|
|
|
156
156
|
def __init__(
|
|
157
|
-
self, provider: Optional[LoggerProvider] = None, *, logger: Any = None,
|
|
157
|
+
self, provider: Optional[api.LoggerProvider] = None, *, logger: Any = None,
|
|
158
158
|
limits: HealthLimits = HealthLimits(),
|
|
159
159
|
config_client: Optional[ObservationConfigClient] = None,
|
|
160
160
|
clock: Callable[[], float] = time.monotonic,
|
|
@@ -31,7 +31,7 @@ from typing import Any, Optional
|
|
|
31
31
|
|
|
32
32
|
from opentelemetry.sdk.trace import Span as SdkSpan
|
|
33
33
|
from opentelemetry.sdk.trace import SpanProcessor
|
|
34
|
-
from opentelemetry.trace import StatusCode
|
|
34
|
+
from opentelemetry.trace import NonRecordingSpan, StatusCode, set_span_in_context
|
|
35
35
|
|
|
36
36
|
from struct_sdk._genai_content import truncate_and_serialize
|
|
37
37
|
from struct_sdk.core import _contain_logged
|
|
@@ -94,7 +94,7 @@ if hasattr(os, "register_at_fork"):
|
|
|
94
94
|
def _log_record_has_event_name() -> bool:
|
|
95
95
|
import inspect
|
|
96
96
|
|
|
97
|
-
from
|
|
97
|
+
from struct_sdk._otel_logs import LogRecord
|
|
98
98
|
|
|
99
99
|
try:
|
|
100
100
|
return "event_name" in inspect.signature(LogRecord.__init__).parameters
|
|
@@ -243,7 +243,7 @@ class OperationDetailsProcessor(SpanProcessor):
|
|
|
243
243
|
"gen_ai.input.messages" in content or "gen_ai.output.messages" in content
|
|
244
244
|
):
|
|
245
245
|
return
|
|
246
|
-
from
|
|
246
|
+
from struct_sdk._otel_logs import LogRecord, SeverityNumber
|
|
247
247
|
|
|
248
248
|
span_attributes = dict(span.attributes or {})
|
|
249
249
|
attributes: dict[str, Any] = {"event.name": OPERATION_DETAILS_EVENT}
|
|
@@ -260,12 +260,9 @@ class OperationDetailsProcessor(SpanProcessor):
|
|
|
260
260
|
attributes.setdefault("error.type", _error_type(span, status))
|
|
261
261
|
attributes.update(content)
|
|
262
262
|
|
|
263
|
-
context = span.get_span_context()
|
|
264
263
|
record: dict[str, Any] = {
|
|
265
264
|
"timestamp": span.end_time,
|
|
266
|
-
"
|
|
267
|
-
"span_id": context.span_id,
|
|
268
|
-
"trace_flags": context.trace_flags,
|
|
265
|
+
"context": set_span_in_context(NonRecordingSpan(span.get_span_context())),
|
|
269
266
|
"severity_text": "DEBUG",
|
|
270
267
|
"severity_number": SeverityNumber.DEBUG,
|
|
271
268
|
"body": OPERATION_DETAILS_EVENT, # Struct's readers match the body
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""OpenTelemetry's logs API and SDK, from where the installed release keeps them.
|
|
2
|
+
|
|
3
|
+
OpenTelemetry 1.46.0 moved both out of ``opentelemetry._logs`` and
|
|
4
|
+
``opentelemetry.sdk._logs``, which it keeps as deprecated aliases, and removed
|
|
5
|
+
``LogExportResult``, ``LogExporter`` and the SDK's ``LoggingHandler``. Older
|
|
6
|
+
releases have only the private modules, and only from 1.39 ``LogRecordExportResult``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from opentelemetry import _logs as api
|
|
13
|
+
from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
14
|
+
from opentelemetry.sdk._logs.export import (
|
|
15
|
+
BatchLogRecordProcessor,
|
|
16
|
+
LogRecordExportResult,
|
|
17
|
+
)
|
|
18
|
+
else:
|
|
19
|
+
try:
|
|
20
|
+
from opentelemetry import logs as api
|
|
21
|
+
except ImportError:
|
|
22
|
+
from opentelemetry import _logs as api
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from opentelemetry.sdk.logs import LoggerProvider, LogRecordProcessor
|
|
26
|
+
from opentelemetry.sdk.logs.export import (
|
|
27
|
+
BatchLogRecordProcessor,
|
|
28
|
+
LogRecordExportResult,
|
|
29
|
+
)
|
|
30
|
+
except ImportError:
|
|
31
|
+
from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
32
|
+
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
from opentelemetry.sdk._logs.export import LogRecordExportResult
|
|
36
|
+
except ImportError:
|
|
37
|
+
from opentelemetry.sdk._logs.export import (
|
|
38
|
+
LogExportResult as LogRecordExportResult,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
LogRecord = api.LogRecord
|
|
42
|
+
SeverityNumber = api.SeverityNumber
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"BatchLogRecordProcessor",
|
|
46
|
+
"LogRecord",
|
|
47
|
+
"LogRecordExportResult",
|
|
48
|
+
"LogRecordProcessor",
|
|
49
|
+
"LoggerProvider",
|
|
50
|
+
"SeverityNumber",
|
|
51
|
+
"api",
|
|
52
|
+
]
|
|
@@ -26,6 +26,7 @@ import functools
|
|
|
26
26
|
import inspect
|
|
27
27
|
import json
|
|
28
28
|
import logging
|
|
29
|
+
import re
|
|
29
30
|
import threading
|
|
30
31
|
from types import SimpleNamespace
|
|
31
32
|
from typing import TYPE_CHECKING, Any, Callable, Generator, Optional, cast
|
|
@@ -407,6 +408,40 @@ def _attached_telemetry(stream: Any) -> Any:
|
|
|
407
408
|
_TEXT_BUDGET = _MAX_FIELD_SIZE + 1
|
|
408
409
|
"""Characters of text or reasoning one content block retains: one over the
|
|
409
410
|
exported field cap, so truncation (and its marker) still applies downstream."""
|
|
411
|
+
_MAX_TOOL_INPUT_DEPTH = 10_000
|
|
412
|
+
_JSON_STRUCTURE = re.compile(r'[\\"\[\]{}]')
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _parse_tool_input(raw: str) -> Any:
|
|
416
|
+
"""Tool arguments as JSON, or the raw text when malformed or nested deeper than
|
|
417
|
+
``_MAX_TOOL_INPUT_DEPTH``, where json stops on CPython 3.12 and 3.13: from 3.14
|
|
418
|
+
json's nesting is bounded only by the C stack. The depth check is one pass over
|
|
419
|
+
the structural characters; brackets inside strings do not count."""
|
|
420
|
+
if not raw:
|
|
421
|
+
return {}
|
|
422
|
+
if raw.count("[") + raw.count("{") > _MAX_TOOL_INPUT_DEPTH:
|
|
423
|
+
depth, in_string, escaped_at = 0, False, -1
|
|
424
|
+
for match in _JSON_STRUCTURE.finditer(raw):
|
|
425
|
+
char, at = match.group(), match.start()
|
|
426
|
+
if in_string:
|
|
427
|
+
if at == escaped_at:
|
|
428
|
+
continue
|
|
429
|
+
if char == "\\":
|
|
430
|
+
escaped_at = at + 1
|
|
431
|
+
elif char == '"':
|
|
432
|
+
in_string = False
|
|
433
|
+
elif char == '"':
|
|
434
|
+
in_string = True
|
|
435
|
+
elif char in "[{":
|
|
436
|
+
depth += 1
|
|
437
|
+
if depth > _MAX_TOOL_INPUT_DEPTH:
|
|
438
|
+
return raw
|
|
439
|
+
elif char in "]}":
|
|
440
|
+
depth -= 1
|
|
441
|
+
try:
|
|
442
|
+
return json.loads(raw)
|
|
443
|
+
except (ValueError, RecursionError):
|
|
444
|
+
return raw
|
|
410
445
|
|
|
411
446
|
|
|
412
447
|
class _StreamAccumulator:
|
|
@@ -495,10 +530,7 @@ class _StreamAccumulator:
|
|
|
495
530
|
for key, value in self._blocks[index].items() if key != "budget"}
|
|
496
531
|
raw = entry.pop("json", None)
|
|
497
532
|
if raw is not None:
|
|
498
|
-
|
|
499
|
-
entry["input"] = json.loads(raw) if raw else {}
|
|
500
|
-
except (ValueError, RecursionError):
|
|
501
|
-
entry["input"] = raw # malformed or too deep: keep the raw arguments
|
|
533
|
+
entry["input"] = _parse_tool_input(raw)
|
|
502
534
|
content.append(SimpleNamespace(**entry))
|
|
503
535
|
return SimpleNamespace(
|
|
504
536
|
id=self.id, model=self.model, stop_reason=self.stop_reason, content=content,
|
|
@@ -42,10 +42,12 @@ from __future__ import annotations
|
|
|
42
42
|
import functools
|
|
43
43
|
import json
|
|
44
44
|
import logging
|
|
45
|
+
import sys
|
|
45
46
|
import types
|
|
46
47
|
from collections.abc import Mapping
|
|
47
48
|
from typing import TYPE_CHECKING, Any, Generator, Optional
|
|
48
49
|
|
|
50
|
+
import wrapt
|
|
49
51
|
from opentelemetry import trace
|
|
50
52
|
from opentelemetry.sdk.trace import SpanProcessor
|
|
51
53
|
from opentelemetry.trace import StatusCode
|
|
@@ -78,8 +80,12 @@ _CHOICE_FINISH_REASONS = {
|
|
|
78
80
|
"content_filter": "content_filter",
|
|
79
81
|
}
|
|
80
82
|
|
|
83
|
+
_OPENAI_CLIENT_MODULE = "autogen_ext.models.openai"
|
|
84
|
+
|
|
81
85
|
_wrapped: list[tuple[type, Any]] = []
|
|
82
86
|
_processor: Optional[_SessionProcessor] = None
|
|
87
|
+
_pending_sdk: Optional["StructSDK"] = None
|
|
88
|
+
_import_hook_registered = False
|
|
83
89
|
|
|
84
90
|
|
|
85
91
|
class _SessionProcessor(SpanProcessor):
|
|
@@ -106,28 +112,55 @@ class _SessionProcessor(SpanProcessor):
|
|
|
106
112
|
|
|
107
113
|
|
|
108
114
|
def patch(sdk: StructSDK) -> None:
|
|
109
|
-
"""
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
"""Register the session processor, and wrap
|
|
116
|
+
``BaseOpenAIChatCompletionClient.create`` now if the app has loaded AutoGen's
|
|
117
|
+
OpenAI client, else when it does, so importing ``autogen_ext`` alone never
|
|
118
|
+
loads ``openai`` (SDK-PY-5). Raises ImportError if autogen-ext is not installed."""
|
|
119
|
+
global _processor, _pending_sdk, _import_hook_registered
|
|
120
|
+
import autogen_ext # noqa: F401
|
|
121
|
+
|
|
122
|
+
provider = sdk.ai_tracer_provider
|
|
123
|
+
if _processor is None and provider is not None and hasattr(provider, "add_span_processor"):
|
|
124
|
+
_processor = _SessionProcessor()
|
|
125
|
+
provider.add_span_processor(_processor)
|
|
126
|
+
if _OPENAI_CLIENT_MODULE in sys.modules:
|
|
127
|
+
_wrap_openai_client(sdk)
|
|
128
|
+
return
|
|
129
|
+
_pending_sdk = sdk
|
|
130
|
+
if not _import_hook_registered:
|
|
131
|
+
_import_hook_registered = True
|
|
132
|
+
try:
|
|
133
|
+
wrapt.register_post_import_hook(_on_openai_client_import, _OPENAI_CLIENT_MODULE)
|
|
134
|
+
except BaseException:
|
|
135
|
+
_pending_sdk = None
|
|
136
|
+
_import_hook_registered = False
|
|
137
|
+
raise
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _on_openai_client_import(module: types.ModuleType) -> None:
|
|
141
|
+
global _pending_sdk, _import_hook_registered
|
|
142
|
+
_import_hook_registered = False
|
|
143
|
+
sdk, _pending_sdk = _pending_sdk, None
|
|
144
|
+
if sdk is not None and sdk._initialized and not sdk._activation_cancelled:
|
|
145
|
+
_contain(lambda: _wrap_openai_client(sdk), "autogen.patch_on_import")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _wrap_openai_client(sdk: StructSDK) -> None:
|
|
113
149
|
from autogen_ext.models.openai import BaseOpenAIChatCompletionClient
|
|
114
150
|
|
|
115
151
|
if _wrapped:
|
|
116
152
|
return
|
|
117
|
-
tracer = sdk.get_tracer(_TRACER_NAME)
|
|
118
153
|
original = BaseOpenAIChatCompletionClient.__dict__.get("create")
|
|
119
154
|
if original is not None and not getattr(original, "__struct_wrapped__", False):
|
|
120
|
-
BaseOpenAIChatCompletionClient.create = _wrap(original,
|
|
155
|
+
BaseOpenAIChatCompletionClient.create = _wrap(original, sdk.get_tracer(_TRACER_NAME), sdk) # type: ignore[method-assign]
|
|
121
156
|
_wrapped.append((BaseOpenAIChatCompletionClient, original))
|
|
122
|
-
provider = sdk.ai_tracer_provider
|
|
123
|
-
if _processor is None and provider is not None and hasattr(provider, "add_span_processor"):
|
|
124
|
-
_processor = _SessionProcessor()
|
|
125
|
-
provider.add_span_processor(_processor)
|
|
126
157
|
|
|
127
158
|
|
|
128
159
|
def unpatch() -> None:
|
|
129
|
-
"""Restore ``create
|
|
130
|
-
|
|
160
|
+
"""Restore ``create``, cancel a pending wrap and deactivate the session processor.
|
|
161
|
+
Primarily for tests."""
|
|
162
|
+
global _processor, _pending_sdk
|
|
163
|
+
_pending_sdk = None
|
|
131
164
|
while _wrapped:
|
|
132
165
|
cls, original = _wrapped.pop()
|
|
133
166
|
setattr(cls, "create", original)
|
|
@@ -17,6 +17,7 @@ import contextvars
|
|
|
17
17
|
import dataclasses
|
|
18
18
|
import fnmatch
|
|
19
19
|
import functools
|
|
20
|
+
import inspect
|
|
20
21
|
import json
|
|
21
22
|
import logging
|
|
22
23
|
import os
|
|
@@ -44,15 +45,11 @@ from typing import (
|
|
|
44
45
|
|
|
45
46
|
from opentelemetry import context as _otel_context
|
|
46
47
|
from opentelemetry import trace
|
|
47
|
-
from opentelemetry._logs import LogRecord
|
|
48
48
|
from opentelemetry.context import create_key
|
|
49
49
|
from opentelemetry.context.context import Context as _OtelContext
|
|
50
50
|
from opentelemetry.exporter.otlp.proto.http import _OTLP_HTTP_HEADERS, Compression
|
|
51
|
-
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
52
51
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
|
53
52
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
54
|
-
from opentelemetry.sdk._logs import LoggerProvider
|
|
55
|
-
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogExportResult # ty: ignore[deprecated] — supported older OTel releases lack LogRecordExportResult
|
|
56
53
|
from opentelemetry.sdk.metrics import (
|
|
57
54
|
Counter,
|
|
58
55
|
Histogram,
|
|
@@ -81,9 +78,17 @@ import requests
|
|
|
81
78
|
from requests.adapters import HTTPAdapter
|
|
82
79
|
|
|
83
80
|
from struct_sdk._fork_safe_http import fork_safe_session
|
|
81
|
+
from struct_sdk._otel_logs import BatchLogRecordProcessor, LoggerProvider, LogRecord, LogRecordExportResult
|
|
84
82
|
|
|
85
83
|
if TYPE_CHECKING:
|
|
84
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
85
|
+
|
|
86
86
|
from struct_sdk._auto import FullAppState
|
|
87
|
+
else:
|
|
88
|
+
try:
|
|
89
|
+
from opentelemetry.exporter.otlp.proto.http.log_exporter import OTLPLogExporter
|
|
90
|
+
except ImportError:
|
|
91
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
87
92
|
|
|
88
93
|
logger = logging.getLogger("struct_sdk")
|
|
89
94
|
# A library must not configure logging on the host's behalf. Attach a NullHandler
|
|
@@ -100,6 +105,14 @@ except Exception: # noqa: BLE001
|
|
|
100
105
|
|
|
101
106
|
DEFAULT_ENDPOINT = "https://ingest.struct.ai"
|
|
102
107
|
|
|
108
|
+
# asyncio's check also accepts its ``_is_coroutine`` marker, which inspect's misses
|
|
109
|
+
# on every version (asgiref's sync_to_async sets it on 3.10/3.11). asyncio
|
|
110
|
+
# deprecates its check from 3.14.
|
|
111
|
+
if sys.version_info >= (3, 14):
|
|
112
|
+
_is_coroutine_function = inspect.iscoroutinefunction
|
|
113
|
+
else:
|
|
114
|
+
_is_coroutine_function = asyncio.iscoroutinefunction
|
|
115
|
+
|
|
103
116
|
|
|
104
117
|
class ContentCaptureMode(str, Enum):
|
|
105
118
|
"""Controls how LLM message content is captured in telemetry.
|
|
@@ -391,6 +404,58 @@ def _detach_current_span(
|
|
|
391
404
|
# Registry of patched integrations — prevents double-patching
|
|
392
405
|
_patched_integrations: set[str] = set()
|
|
393
406
|
|
|
407
|
+
# Each GenAI integration: its name, its Struct module, and the modules whose import
|
|
408
|
+
# by the app activates it (SDK-PY-5). LiteLLM's patch() waits for that import itself
|
|
409
|
+
# (SDK-PY-72), so init() calls it at once.
|
|
410
|
+
_GENAI_INTEGRATIONS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
|
411
|
+
("ag2", "struct_sdk.ag2", ("autogen", "ag2")),
|
|
412
|
+
("anthropic", "struct_sdk.anthropic", ("anthropic",)),
|
|
413
|
+
("autogen_ext", "struct_sdk.autogen", ("autogen_ext",)),
|
|
414
|
+
("claude_agent_sdk", "struct_sdk.claude_agent", ("claude_agent_sdk",)),
|
|
415
|
+
("crewai", "struct_sdk.crewai", ("crewai",)),
|
|
416
|
+
("langchain_core", "struct_sdk.langchain", ("langchain_core",)),
|
|
417
|
+
("litellm", "struct_sdk.litellm", ()),
|
|
418
|
+
("llama_index", "struct_sdk.llamaindex", ("llama_index.core",)),
|
|
419
|
+
("openai", "struct_sdk.openai", ("openai",)),
|
|
420
|
+
("pydantic_ai", "struct_sdk.pydantic_ai", ("pydantic_ai",)),
|
|
421
|
+
("openai_agents", "struct_sdk.openai_agents", ("agents",)),
|
|
422
|
+
("mcp", "struct_sdk.mcp", ("mcp",)),
|
|
423
|
+
("google_genai", "struct_sdk.google_genai", ("google.genai",)),
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
# Integrations waiting for the app to import their library, each with the SDK
|
|
427
|
+
# that asked; a later init() replaces it. wrapt keeps one callback per module.
|
|
428
|
+
_pending_integrations: dict[str, "weakref.ref[StructSDK]"] = {}
|
|
429
|
+
_import_hooks: set[str] = set()
|
|
430
|
+
_pending_lock = threading.Lock()
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _importable(name: str) -> bool:
|
|
434
|
+
"""Whether ``name`` is installed; dotted lookups may import parent packages."""
|
|
435
|
+
import importlib.util
|
|
436
|
+
|
|
437
|
+
try:
|
|
438
|
+
return importlib.util.find_spec(name) is not None
|
|
439
|
+
except (ImportError, ValueError):
|
|
440
|
+
return False
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _patch_on_import(module: Any) -> None:
|
|
444
|
+
"""wrapt's post-import callback: it runs inside the app's import, after the
|
|
445
|
+
module has executed, so nothing may escape into that import."""
|
|
446
|
+
|
|
447
|
+
def activate() -> None:
|
|
448
|
+
for lib_name, module_path, modules in _GENAI_INTEGRATIONS:
|
|
449
|
+
if module.__name__ not in modules:
|
|
450
|
+
continue
|
|
451
|
+
with _pending_lock:
|
|
452
|
+
owner = _pending_integrations.pop(lib_name, None)
|
|
453
|
+
sdk = owner() if owner is not None else None
|
|
454
|
+
if sdk is not None and sdk._initialized and not sdk._activation_cancelled:
|
|
455
|
+
sdk._patch_integration(lib_name, module_path)
|
|
456
|
+
|
|
457
|
+
_contain_logged(activate, site="integrations.patch_on_import")
|
|
458
|
+
|
|
394
459
|
# Sites that have already logged a first-failure WARN; subsequent failures log at DEBUG.
|
|
395
460
|
_first_failure_logged: set[str] = set()
|
|
396
461
|
|
|
@@ -478,24 +543,37 @@ def _exception_type_name(exc: BaseException) -> str:
|
|
|
478
543
|
|
|
479
544
|
|
|
480
545
|
def _record_span_error(
|
|
481
|
-
span: Any,
|
|
546
|
+
span: Any,
|
|
547
|
+
exc: BaseException,
|
|
548
|
+
sdk: Any,
|
|
549
|
+
site: str,
|
|
550
|
+
*,
|
|
551
|
+
error_type: Optional[str] = None,
|
|
552
|
+
description: Optional[str] = None,
|
|
482
553
|
) -> None:
|
|
483
554
|
"""Mark ``span`` failed by ``exc`` (SDK-PY-47): ``error.type`` and status ERROR always.
|
|
484
555
|
In span-content modes the status description is ``str(exc)`` and ``record_exception``
|
|
485
556
|
adds the message and stack trace; otherwise the description is the type name and the
|
|
486
557
|
``exception`` event carries only ``exception.type``. Each step is contained on its own,
|
|
487
558
|
BaseException included: these run on the host's error path, where a hostile ``__str__``
|
|
488
|
-
must not replace the host's exception (SDK-PY-19).
|
|
559
|
+
must not replace the host's exception (SDK-PY-19). A given ``description`` replaces the status
|
|
560
|
+
description: OpenTelemetry 1.46.0 keeps the first description an ERROR status gets."""
|
|
489
561
|
type_name = _exception_type_name(exc)
|
|
490
562
|
err_type = error_type or type_name
|
|
491
563
|
_contain_logged(lambda: span.set_attribute("error.type", err_type), site=f"{site}.error_type")
|
|
492
564
|
if _error_text_on_spans(sdk):
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
565
|
+
text = [type_name] # kept when ``str(exc)`` raises
|
|
566
|
+
if description is None:
|
|
567
|
+
_contain_logged(lambda: text.__setitem__(0, str(exc)), site=f"{site}.error_text")
|
|
568
|
+
else:
|
|
569
|
+
text[0] = description
|
|
570
|
+
_contain_logged(lambda: span.set_status(StatusCode.ERROR, text[0]), site=f"{site}.error_status")
|
|
496
571
|
_contain_logged(lambda: span.record_exception(exc), site=f"{site}.record_exception")
|
|
497
572
|
return
|
|
498
|
-
_contain_logged(
|
|
573
|
+
_contain_logged(
|
|
574
|
+
lambda: span.set_status(StatusCode.ERROR, type_name if description is None else description),
|
|
575
|
+
site=f"{site}.error_status",
|
|
576
|
+
)
|
|
499
577
|
_contain_logged(
|
|
500
578
|
lambda: span.add_event("exception", {"exception.type": _exception_type(exc)}),
|
|
501
579
|
site=f"{site}.record_exception",
|
|
@@ -564,6 +642,7 @@ _BATCH_PROCESSOR_LOGGERS = (
|
|
|
564
642
|
"opentelemetry.sdk._shared_internal",
|
|
565
643
|
"opentelemetry.sdk.trace.export",
|
|
566
644
|
"opentelemetry.sdk._logs._internal.export",
|
|
645
|
+
"opentelemetry.sdk.logs._internal.export",
|
|
567
646
|
)
|
|
568
647
|
# Where the metrics SDK reports a collection: a callback that raised, a reader
|
|
569
648
|
# shut down twice or never registered.
|
|
@@ -915,7 +994,7 @@ class _StructSpanExporter(_InStructExportScope, OTLPSpanExporter):
|
|
|
915
994
|
|
|
916
995
|
|
|
917
996
|
class _StructLogExporter(_InStructExportScope, OTLPLogExporter):
|
|
918
|
-
_FAILURE =
|
|
997
|
+
_FAILURE = LogRecordExportResult.FAILURE
|
|
919
998
|
|
|
920
999
|
def export(self, batch: Any, *args: Any, **kwargs: Any) -> Any:
|
|
921
1000
|
if _redact_patterns or any(
|
|
@@ -1256,6 +1335,8 @@ def _rearm_owns(sdk: "StructSDK") -> bool:
|
|
|
1256
1335
|
|
|
1257
1336
|
|
|
1258
1337
|
def _sdk_after_fork() -> None:
|
|
1338
|
+
global _pending_lock
|
|
1339
|
+
_pending_lock = threading.Lock()
|
|
1259
1340
|
for sdk in list(_sdk_instances.values()):
|
|
1260
1341
|
# A vanished worker's frame can retain its cleanup job. The SDK still owns
|
|
1261
1342
|
# these objects; drop only the job's references, without flushing or locking.
|
|
@@ -1763,49 +1844,48 @@ class StructSDK:
|
|
|
1763
1844
|
return self._shutdown_job.deadline if self._shutdown_job is not None else None
|
|
1764
1845
|
|
|
1765
1846
|
def _auto_instrument(self, options: Optional[Mapping[str, Mapping[str, Any]]] = None):
|
|
1766
|
-
"""
|
|
1767
|
-
|
|
1847
|
+
"""Patch each GenAI library the app has imported, and each other installed one
|
|
1848
|
+
when the app imports it, except those turned off with
|
|
1849
|
+
``instrumentation_options={name: {"enabled": False}}`` (SDK-PY-5)."""
|
|
1850
|
+
import wrapt
|
|
1851
|
+
|
|
1768
1852
|
from struct_sdk import _auto
|
|
1769
1853
|
|
|
1770
1854
|
# The same ownership rule applies to GenAI patches and contrib
|
|
1771
1855
|
# instrumentors. Explicit AI-only mode keeps its isolated patches.
|
|
1772
1856
|
ddtrace_owned = _auto._ddtrace_instrumented() if self._full_app_requested else set()
|
|
1773
|
-
integrations = [
|
|
1774
|
-
("ag2", "struct_sdk.ag2"),
|
|
1775
|
-
("anthropic", "struct_sdk.anthropic"),
|
|
1776
|
-
("autogen_ext", "struct_sdk.autogen"),
|
|
1777
|
-
("claude_agent_sdk", "struct_sdk.claude_agent"),
|
|
1778
|
-
("crewai", "struct_sdk.crewai"),
|
|
1779
|
-
("langchain_core", "struct_sdk.langchain"),
|
|
1780
|
-
("litellm", "struct_sdk.litellm"),
|
|
1781
|
-
("llama_index", "struct_sdk.llamaindex"),
|
|
1782
|
-
("openai", "struct_sdk.openai"),
|
|
1783
|
-
("pydantic_ai", "struct_sdk.pydantic_ai"),
|
|
1784
|
-
("openai_agents", "struct_sdk.openai_agents"),
|
|
1785
|
-
("mcp", "struct_sdk.mcp"),
|
|
1786
|
-
("google_genai", "struct_sdk.google_genai"),
|
|
1787
|
-
]
|
|
1788
|
-
|
|
1789
1857
|
left_to_ddtrace = []
|
|
1790
|
-
for lib_name, module_path in
|
|
1858
|
+
for lib_name, module_path, modules in _GENAI_INTEGRATIONS:
|
|
1791
1859
|
if lib_name in _patched_integrations:
|
|
1792
1860
|
continue
|
|
1793
1861
|
if (options or {}).get(lib_name, {}).get("enabled", True) is False:
|
|
1794
1862
|
continue
|
|
1795
|
-
if _auto._left_to_ddtrace(lib_name, ddtrace_owned):
|
|
1796
|
-
if _auto._genai_installed(lib_name):
|
|
1797
|
-
left_to_ddtrace.append(lib_name)
|
|
1798
|
-
continue
|
|
1799
1863
|
try:
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1864
|
+
if _auto._left_to_ddtrace(lib_name, ddtrace_owned):
|
|
1865
|
+
if _auto._genai_installed(lib_name):
|
|
1866
|
+
left_to_ddtrace.append(lib_name)
|
|
1867
|
+
continue
|
|
1868
|
+
if not modules or any(module in sys.modules for module in modules):
|
|
1869
|
+
self._patch_integration(lib_name, module_path)
|
|
1870
|
+
continue
|
|
1871
|
+
# Importing a library the app has not imported runs its import-time
|
|
1872
|
+
# code in the app's process (warnings, network fetches, start-up
|
|
1873
|
+
# cost), so the patch waits for the app's own import.
|
|
1874
|
+
for module in modules:
|
|
1875
|
+
if not _importable(module):
|
|
1876
|
+
continue
|
|
1877
|
+
with _pending_lock:
|
|
1878
|
+
_pending_integrations[lib_name] = weakref.ref(self)
|
|
1879
|
+
registered = module in _import_hooks
|
|
1880
|
+
if registered:
|
|
1881
|
+
continue
|
|
1882
|
+
# Marked only once wrapt holds the callback: a second
|
|
1883
|
+
# registration is harmless, as activation pops the owner.
|
|
1884
|
+
wrapt.register_post_import_hook(_patch_on_import, module)
|
|
1885
|
+
with _pending_lock:
|
|
1886
|
+
_import_hooks.add(module)
|
|
1807
1887
|
except Exception:
|
|
1808
|
-
logger.debug("Failed to
|
|
1888
|
+
logger.debug("Failed to set up instrumentation for %s", lib_name, exc_info=True)
|
|
1809
1889
|
if left_to_ddtrace:
|
|
1810
1890
|
# WARNING, unlike the contrib skips' INFO: these libraries get no
|
|
1811
1891
|
# Struct model spans at all, which a ddtrace-run user can't see.
|
|
@@ -1815,6 +1895,21 @@ class StructSDK:
|
|
|
1815
1895
|
", ".join(sorted(left_to_ddtrace)),
|
|
1816
1896
|
)
|
|
1817
1897
|
|
|
1898
|
+
def _patch_integration(self, lib_name: str, module_path: str) -> None:
|
|
1899
|
+
if lib_name in _patched_integrations:
|
|
1900
|
+
return
|
|
1901
|
+
try:
|
|
1902
|
+
import importlib
|
|
1903
|
+
|
|
1904
|
+
mod = importlib.import_module(module_path)
|
|
1905
|
+
mod.patch(self) # type: ignore[attr-defined]
|
|
1906
|
+
_patched_integrations.add(lib_name)
|
|
1907
|
+
logger.info("Auto-instrumented: %s", lib_name)
|
|
1908
|
+
except ImportError:
|
|
1909
|
+
pass
|
|
1910
|
+
except Exception:
|
|
1911
|
+
logger.debug("Failed to instrument %s", lib_name, exc_info=True)
|
|
1912
|
+
|
|
1818
1913
|
@property
|
|
1819
1914
|
def ai_tracer_provider(self) -> Optional[TracerProvider]:
|
|
1820
1915
|
"""The provider the GenAI spans use: the host's SDK provider in attach mode, else
|
|
@@ -2149,7 +2244,7 @@ class _AgentContext:
|
|
|
2149
2244
|
version = self._version
|
|
2150
2245
|
metadata = self._metadata
|
|
2151
2246
|
|
|
2152
|
-
if
|
|
2247
|
+
if _is_coroutine_function(fn):
|
|
2153
2248
|
@functools.wraps(fn)
|
|
2154
2249
|
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
2155
2250
|
async with _AgentContext(sdk, name=span_name, session_id=explicit_session_id, agent_id=agent_id, version=version, metadata=metadata):
|
|
@@ -2503,17 +2598,21 @@ def _tool_error_status_message(result: Any) -> str:
|
|
|
2503
2598
|
|
|
2504
2599
|
|
|
2505
2600
|
# An integration whose own call a Struct execute_tool span also records (MCP:
|
|
2506
|
-
# SDK-PY-57) stores that call's outcome on the span, as
|
|
2601
|
+
# SDK-PY-57) stores that call's outcome on the span, as private fields (state
|
|
2507
2602
|
# on the object Struct created): the call's exception, or True for a failed
|
|
2508
|
-
# result. A struct.tool() scope's exit
|
|
2509
|
-
#
|
|
2603
|
+
# result, and the function that records it. A struct.tool() scope's exit runs
|
|
2604
|
+
# that function unless a different exception ends the scope, so the span's
|
|
2605
|
+
# status is set once: OpenTelemetry 1.46.0 keeps the first ERROR description.
|
|
2510
2606
|
_INNER_OUTCOME = "_struct_inner_outcome"
|
|
2607
|
+
_INNER_RECORD = "_struct_inner_record"
|
|
2511
2608
|
_NO_INNER_OUTCOME = object()
|
|
2512
2609
|
|
|
2513
2610
|
|
|
2514
|
-
def _record_inner_outcome(span: Any, outcome: Any) -> None:
|
|
2515
|
-
"""Mark ``span``'s outcome as set by an inner call: its exception, or True
|
|
2611
|
+
def _record_inner_outcome(span: Any, outcome: Any, record: Callable[[], object]) -> None:
|
|
2612
|
+
"""Mark ``span``'s outcome as set by an inner call: its exception, or True, and
|
|
2613
|
+
``record``, which the enclosing scope's exit runs to write that outcome."""
|
|
2516
2614
|
setattr(span, _INNER_OUTCOME, outcome)
|
|
2615
|
+
setattr(span, _INNER_RECORD, record)
|
|
2517
2616
|
|
|
2518
2617
|
|
|
2519
2618
|
def _inner_outcome(span: Any) -> Any:
|
|
@@ -2523,6 +2622,12 @@ def _inner_outcome(span: Any) -> Any:
|
|
|
2523
2622
|
return _NO_INNER_OUTCOME
|
|
2524
2623
|
|
|
2525
2624
|
|
|
2625
|
+
def _run_inner_record(span: Any) -> None:
|
|
2626
|
+
record = getattr(span, _INNER_RECORD, None)
|
|
2627
|
+
if record is not None:
|
|
2628
|
+
_contain_logged(record, site="tool.end_span.inner_outcome")
|
|
2629
|
+
|
|
2630
|
+
|
|
2526
2631
|
class _ToolContext:
|
|
2527
2632
|
"""Creates an ``execute_tool {name}`` span per the OTel GenAI spec."""
|
|
2528
2633
|
|
|
@@ -2543,7 +2648,7 @@ class _ToolContext:
|
|
|
2543
2648
|
sdk = self._sdk
|
|
2544
2649
|
tool_call_id = self._tool_call_id
|
|
2545
2650
|
|
|
2546
|
-
if
|
|
2651
|
+
if _is_coroutine_function(fn):
|
|
2547
2652
|
@functools.wraps(fn)
|
|
2548
2653
|
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
2549
2654
|
async with _ToolContext(sdk, name=tool_name, tool_call_id=tool_call_id) as ctx:
|
|
@@ -2625,7 +2730,7 @@ class _ToolContext:
|
|
|
2625
2730
|
if span is not None:
|
|
2626
2731
|
inner = _inner_outcome(span)
|
|
2627
2732
|
if exc_val and exc_val is inner:
|
|
2628
|
-
|
|
2733
|
+
_run_inner_record(span) # the inner call's exception: its code and status
|
|
2629
2734
|
elif exc_val:
|
|
2630
2735
|
_record_span_error(span, exc_val, self._sdk, "tool.end_span")
|
|
2631
2736
|
elif self._result_is_error:
|
|
@@ -2634,7 +2739,7 @@ class _ToolContext:
|
|
|
2634
2739
|
_safe(lambda: span.set_status(StatusCode.ERROR, self._result_error_message),
|
|
2635
2740
|
site="tool.end_span.tool_error_status")
|
|
2636
2741
|
elif inner is not _NO_INNER_OUTCOME:
|
|
2637
|
-
|
|
2742
|
+
_run_inner_record(span) # the inner call failed; its ERROR, not OK
|
|
2638
2743
|
else:
|
|
2639
2744
|
_safe(lambda: span.set_status(StatusCode.OK),
|
|
2640
2745
|
site="tool.end_span.set_ok")
|
|
@@ -151,7 +151,7 @@ def _on_import(module: ModuleType) -> None:
|
|
|
151
151
|
with _lock:
|
|
152
152
|
_import_hook_registered = False
|
|
153
153
|
sdk, _pending_sdk = _pending_sdk, None
|
|
154
|
-
if sdk is not None:
|
|
154
|
+
if sdk is not None and sdk._initialized and not sdk._activation_cancelled:
|
|
155
155
|
_contain(lambda: _patch_module(module, sdk), "litellm.patch_on_import")
|
|
156
156
|
|
|
157
157
|
|
|
@@ -27,8 +27,9 @@ Owner per span: when a Struct ``execute_tool`` span is current and has no MCP
|
|
|
27
27
|
call yet (``struct.tool()``), the MCP conventions say not to add a second span;
|
|
28
28
|
that span gets the MCP attributes and the call's outcome (``error.type``,
|
|
29
29
|
``rpc.response.status_code``, status) and is propagated instead. The outcome
|
|
30
|
-
is
|
|
31
|
-
|
|
30
|
+
is handed to the span (``core._record_inner_outcome``) and the scope's exit
|
|
31
|
+
records it, unless a different exception ends the scope: the span's status is
|
|
32
|
+
set once, as OpenTelemetry 1.46.0 keeps the first ERROR description. mcp 2.x also creates its own ``MCP send ...`` transport span (through
|
|
32
33
|
the global tracer provider); it nests under Struct's span.
|
|
33
34
|
|
|
34
35
|
Auto-applied by ``struct.init()`` when the ``mcp`` package is installed.
|
|
@@ -186,7 +187,7 @@ def _call_tool_telemetry(
|
|
|
186
187
|
) -> Generator:
|
|
187
188
|
"""Telemetry around one ``call_tool``. ``f, args, kwargs = yield`` marks the
|
|
188
189
|
host call; ``kwargs`` may carry the injected ``meta``."""
|
|
189
|
-
from struct_sdk.core import _record_inner_outcome, _safe
|
|
190
|
+
from struct_sdk.core import _record_inner_outcome, _safe, _tool_result_signals_error
|
|
190
191
|
|
|
191
192
|
# call_tool(self, name, arguments=None, ...); ``meta`` is keyword-only.
|
|
192
193
|
session = args[0] if args else None
|
|
@@ -211,8 +212,11 @@ def _call_tool_telemetry(
|
|
|
211
212
|
exc = e # ``except ... as e`` unbinds ``e`` before the closure runs
|
|
212
213
|
|
|
213
214
|
def record_failure() -> None:
|
|
214
|
-
|
|
215
|
-
|
|
215
|
+
# Read now: the caller can change the error before the scope ends.
|
|
216
|
+
code, description = _error_outcome(exc, sdk)
|
|
217
|
+
if code is not None:
|
|
218
|
+
outer.set_attribute("rpc.response.status_code", str(code))
|
|
219
|
+
_record_inner_outcome(outer, exc, lambda: _write_error(outer, exc, sdk, code, description))
|
|
216
220
|
|
|
217
221
|
# On the host's error path, and stringifying a hostile exception
|
|
218
222
|
# can raise anything: ``_contain``, not ``_safe``.
|
|
@@ -220,8 +224,9 @@ def _call_tool_telemetry(
|
|
|
220
224
|
raise
|
|
221
225
|
|
|
222
226
|
def outcome() -> None:
|
|
223
|
-
if
|
|
224
|
-
|
|
227
|
+
if _tool_result_signals_error(result):
|
|
228
|
+
message = _tool_error_message(sdk, result) # the result is the caller's to change
|
|
229
|
+
_record_inner_outcome(outer, True, lambda: _mark_tool_error(outer, message))
|
|
225
230
|
|
|
226
231
|
_safe(outcome, site="mcp.call_tool.outer_result")
|
|
227
232
|
return result # noqa: B901
|
|
@@ -345,34 +350,49 @@ def _record_result(span: trace.Span, sdk: StructSDK, result: Any) -> None:
|
|
|
345
350
|
|
|
346
351
|
def _record_tool_error(span: trace.Span, sdk: StructSDK, result: Any) -> bool:
|
|
347
352
|
"""Mark ``span`` as a tool error when ``result`` has ``isError`` set."""
|
|
348
|
-
from struct_sdk.core import
|
|
353
|
+
from struct_sdk.core import _tool_result_signals_error
|
|
349
354
|
|
|
350
355
|
if not _tool_result_signals_error(result):
|
|
351
356
|
return False
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
)
|
|
357
|
+
_mark_tool_error(span, _tool_error_message(sdk, result))
|
|
358
|
+
return True
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _tool_error_message(sdk: StructSDK, result: Any) -> str:
|
|
362
|
+
"""The status description for an error result. It is content on a span (the
|
|
363
|
+
tool's error text): only the span-content modes carry it, as for struct.tool()."""
|
|
364
|
+
from struct_sdk.core import _tool_error_status_message
|
|
365
|
+
|
|
366
|
+
return _tool_error_status_message(result) if sdk.emit_span_content else "tool returned is_error=true"
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _mark_tool_error(span: trace.Span, message: str) -> None:
|
|
359
370
|
span.set_attribute("error.type", "tool_error")
|
|
360
371
|
span.set_status(StatusCode.ERROR, message)
|
|
361
|
-
return True
|
|
362
372
|
|
|
363
373
|
|
|
364
374
|
def _record_error(span: trace.Span, exc: BaseException, sdk: Any) -> None:
|
|
365
375
|
"""A failed call: a JSON-RPC error's code as ``error.type``, else the exception's type.
|
|
366
376
|
Its text (the server's error message, the exception's message and stack trace) reaches
|
|
367
377
|
the span only in span-content modes (SDK-PY-47): it can quote the tool's arguments."""
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
378
|
+
_write_error(span, exc, sdk, *_error_outcome(exc, sdk))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _error_outcome(exc: BaseException, sdk: Any) -> tuple[Optional[int], Optional[str]]:
|
|
382
|
+
"""A JSON-RPC error's code and status description, else (None, None)."""
|
|
383
|
+
code = getattr(getattr(exc, "error", None), "code", None)
|
|
384
|
+
if not isinstance(code, int) or isinstance(code, bool):
|
|
385
|
+
return None, None
|
|
386
|
+
message = getattr(getattr(exc, "error", None), "message", None)
|
|
387
|
+
return code, span_error_description(sdk, message, str(code)) if isinstance(message, str) else None
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _write_error(
|
|
391
|
+
span: trace.Span, exc: BaseException, sdk: Any, code: Optional[int], description: Optional[str]
|
|
392
|
+
) -> None:
|
|
393
|
+
if code is not None:
|
|
371
394
|
span.set_attribute("rpc.response.status_code", str(code))
|
|
372
|
-
|
|
373
|
-
record_span_error(span, exc, sdk, "mcp.error", error_type=str(code))
|
|
374
|
-
if isinstance(message, str):
|
|
375
|
-
span.set_status(StatusCode.ERROR, span_error_description(sdk, message, str(code)))
|
|
395
|
+
record_span_error(span, exc, sdk, "mcp.error", error_type=str(code), description=description)
|
|
376
396
|
else:
|
|
377
397
|
record_span_error(span, exc, sdk, "mcp.error")
|
|
378
398
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|