struct-sdk 0.5.27__tar.gz → 0.5.28__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 (43) hide show
  1. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/PKG-INFO +9 -5
  2. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/PYPI.md +3 -2
  3. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/README.md +2 -2
  4. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/pyproject.toml +10 -6
  5. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/anthropic.py +36 -4
  6. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/autogen.py +45 -12
  7. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/core.py +110 -33
  8. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/litellm.py +1 -1
  9. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/.gitignore +0 -0
  10. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/LICENSE +0 -0
  11. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/__init__.py +0 -0
  12. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_auto.py +0 -0
  13. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_container.py +0 -0
  14. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_distro.py +0 -0
  15. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_event_loop.py +0 -0
  16. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_fork_safe_http.py +0 -0
  17. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_genai_content.py +0 -0
  18. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_metrics.py +0 -0
  19. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/__init__.py +0 -0
  20. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/config.py +0 -0
  21. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/health.py +0 -0
  22. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/identity.py +0 -0
  23. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/native_events.py +0 -0
  24. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/outputs.py +0 -0
  25. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/poller.py +0 -0
  26. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/routing.py +0 -0
  27. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/runtime.py +0 -0
  28. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/self_metrics.py +0 -0
  29. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_observations/uwsgi.py +0 -0
  30. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_operation_details.py +0 -0
  31. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/_pool.py +0 -0
  32. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/ag2.py +0 -0
  33. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/claude_agent.py +0 -0
  34. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/crewai.py +0 -0
  35. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/gcp.py +0 -0
  36. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/google_genai.py +0 -0
  37. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/langchain.py +0 -0
  38. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/llamaindex.py +0 -0
  39. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/mcp.py +0 -0
  40. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/openai.py +0 -0
  41. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/openai_agents.py +0 -0
  42. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/src/struct_sdk/pydantic_ai.py +0 -0
  43. {struct_sdk-0.5.27 → struct_sdk-0.5.28}/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.27
3
+ Version: 0.5.28
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,15 @@ 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
26
27
  Requires-Dist: opentelemetry-sdk>=1.27.0
27
- Requires-Dist: struct-sdk-native==0.2.0
28
- Requires-Dist: wrapt>=1.16.0
28
+ Requires-Dist: struct-sdk-native==0.2.1
29
+ Requires-Dist: wrapt>=1.17.3
29
30
  Provides-Extra: anthropic
30
31
  Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
31
32
  Provides-Extra: auto
@@ -99,6 +100,7 @@ Provides-Extra: langchain
99
100
  Requires-Dist: langchain-core>=1.3.3; extra == 'langchain'
100
101
  Provides-Extra: litellm
101
102
  Requires-Dist: litellm[mcp]>=1.70.0; extra == 'litellm'
103
+ Requires-Dist: litellm[mcp]>=1.93.0; (python_version >= '3.14') and extra == 'litellm'
102
104
  Provides-Extra: llamaindex
103
105
  Requires-Dist: llama-index-core>=0.13.0; extra == 'llamaindex'
104
106
  Provides-Extra: mcp
@@ -113,6 +115,7 @@ Provides-Extra: structlog
113
115
  Requires-Dist: opentelemetry-instrumentation-structlog; extra == 'structlog'
114
116
  Provides-Extra: temporal
115
117
  Requires-Dist: temporalio>=1.11.0; extra == 'temporal'
118
+ Requires-Dist: temporalio>=1.19.0; (python_version >= '3.14') and extra == 'temporal'
116
119
  Description-Content-Type: text/markdown
117
120
 
118
121
  # Struct Python SDK
@@ -167,5 +170,6 @@ the OpenAI Agents SDK, and the Claude Agent SDK.
167
170
 
168
171
  Publish an Observation through the Struct CLI or ask your coding agent to set
169
172
  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.13 and a key with access to Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
173
+ or metrics. Live capture requires a supported native runtime on CPython 3.12,
174
+ 3.13, or 3.14 (3.14.5 or later; free-threaded builds aren't supported) and a key
175
+ 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.13 and a key with access to Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
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 a supported
15
- CPython 3.12 or 3.13 build with the native runtime.
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.27"
7
+ version = "0.5.28"
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
  ]
@@ -30,10 +31,11 @@ dependencies = [
30
31
  "opentelemetry-exporter-otlp-proto-http>=1.27.0",
31
32
  # Stream proxies (struct_sdk.openai): isinstance-transparent, as in
32
33
  # OpenLLMetry and ddtrace. Already required by every OTel instrumentor.
33
- "wrapt>=1.16.0",
34
+ # 1.17.3 is the first release with CPython 3.14 wheels.
35
+ "wrapt>=1.17.3",
34
36
  # Native capture runtime. Always installs: platforms without a native build
35
37
  # get its pure py3-none-any wheel, which reports the capability unavailable.
36
- "struct-sdk-native==0.2.0",
38
+ "struct-sdk-native==0.2.1",
37
39
  ]
38
40
 
39
41
  [project.urls]
@@ -70,7 +72,8 @@ google-genai = ["google-genai>=1.12.1"]
70
72
  # suite runs against. Recent LiteLLM releases import their MCP client (mcp 2.x)
71
73
  # whenever a completion passes ``tools``, and fail without it; LiteLLM's own
72
74
  # ``mcp`` extra installs it (releases without that extra ignore it).
73
- litellm = ["litellm[mcp]>=1.70.0"]
75
+ # LiteLLM releases before 1.93.0 refuse Python 3.14.
76
+ litellm = ["litellm[mcp]>=1.70.0", "litellm[mcp]>=1.93.0; python_version >= '3.14'"]
74
77
  # LlamaIndex's instrumentation dispatcher and agent workflows; 0.13.0 is the
75
78
  # first release whose workflow agents run their own steps.
76
79
  llamaindex = ["llama-index-core>=0.13.0"]
@@ -135,7 +138,8 @@ structlog = ["opentelemetry-instrumentation-structlog"]
135
138
  exceptions = ["opentelemetry-instrumentation-exceptions"]
136
139
  azure = ["azure-core-tracing-opentelemetry>=1.0.0b11"]
137
140
  # TracingInterceptor(always_create_workflow_spans=...) exists from 1.11.0 onward.
138
- temporal = ["temporalio>=1.11.0"]
141
+ # CPython 3.14 needs 1.19.0 or later.
142
+ temporal = ["temporalio>=1.11.0", "temporalio>=1.19.0; python_version >= '3.14'"]
139
143
  demo = [
140
144
  "langchain>=1.3.9",
141
145
  "langchain-core>=1.3.3",
@@ -264,7 +268,7 @@ conflicts = [
264
268
  [{ group = "dev" }, { extra = "litellm" }],
265
269
  ]
266
270
  # 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
271
+ # 3.12 and 3.14. Published metadata still allows 3.10. Pillow 13, the first release
268
272
  # with the fixes for its 2026 CVEs, needs 3.11, so a 3.10 lock entry
269
273
  # could only hold vulnerable Pillow 12.
270
274
  environments = ["python_full_version >= '3.11'"]
@@ -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
- try:
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
- """Wrap ``BaseOpenAIChatCompletionClient.create`` and register the session
110
- processor. Raises ImportError if autogen-ext (with its OpenAI extra) is not
111
- installed."""
112
- global _processor
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, tracer, sdk) # type: ignore[method-assign]
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`` and deactivate the session processor. Primarily for tests."""
130
- global _processor
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
@@ -100,6 +101,14 @@ except Exception: # noqa: BLE001
100
101
 
101
102
  DEFAULT_ENDPOINT = "https://ingest.struct.ai"
102
103
 
104
+ # asyncio's check also accepts its ``_is_coroutine`` marker, which inspect's misses
105
+ # on every version (asgiref's sync_to_async sets it on 3.10/3.11). asyncio
106
+ # deprecates its check from 3.14.
107
+ if sys.version_info >= (3, 14):
108
+ _is_coroutine_function = inspect.iscoroutinefunction
109
+ else:
110
+ _is_coroutine_function = asyncio.iscoroutinefunction
111
+
103
112
 
104
113
  class ContentCaptureMode(str, Enum):
105
114
  """Controls how LLM message content is captured in telemetry.
@@ -391,6 +400,58 @@ def _detach_current_span(
391
400
  # Registry of patched integrations — prevents double-patching
392
401
  _patched_integrations: set[str] = set()
393
402
 
403
+ # Each GenAI integration: its name, its Struct module, and the modules whose import
404
+ # by the app activates it (SDK-PY-5). LiteLLM's patch() waits for that import itself
405
+ # (SDK-PY-72), so init() calls it at once.
406
+ _GENAI_INTEGRATIONS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
407
+ ("ag2", "struct_sdk.ag2", ("autogen", "ag2")),
408
+ ("anthropic", "struct_sdk.anthropic", ("anthropic",)),
409
+ ("autogen_ext", "struct_sdk.autogen", ("autogen_ext",)),
410
+ ("claude_agent_sdk", "struct_sdk.claude_agent", ("claude_agent_sdk",)),
411
+ ("crewai", "struct_sdk.crewai", ("crewai",)),
412
+ ("langchain_core", "struct_sdk.langchain", ("langchain_core",)),
413
+ ("litellm", "struct_sdk.litellm", ()),
414
+ ("llama_index", "struct_sdk.llamaindex", ("llama_index.core",)),
415
+ ("openai", "struct_sdk.openai", ("openai",)),
416
+ ("pydantic_ai", "struct_sdk.pydantic_ai", ("pydantic_ai",)),
417
+ ("openai_agents", "struct_sdk.openai_agents", ("agents",)),
418
+ ("mcp", "struct_sdk.mcp", ("mcp",)),
419
+ ("google_genai", "struct_sdk.google_genai", ("google.genai",)),
420
+ )
421
+
422
+ # Integrations waiting for the app to import their library, each with the SDK
423
+ # that asked; a later init() replaces it. wrapt keeps one callback per module.
424
+ _pending_integrations: dict[str, "weakref.ref[StructSDK]"] = {}
425
+ _import_hooks: set[str] = set()
426
+ _pending_lock = threading.Lock()
427
+
428
+
429
+ def _importable(name: str) -> bool:
430
+ """Whether ``name`` is installed; dotted lookups may import parent packages."""
431
+ import importlib.util
432
+
433
+ try:
434
+ return importlib.util.find_spec(name) is not None
435
+ except (ImportError, ValueError):
436
+ return False
437
+
438
+
439
+ def _patch_on_import(module: Any) -> None:
440
+ """wrapt's post-import callback: it runs inside the app's import, after the
441
+ module has executed, so nothing may escape into that import."""
442
+
443
+ def activate() -> None:
444
+ for lib_name, module_path, modules in _GENAI_INTEGRATIONS:
445
+ if module.__name__ not in modules:
446
+ continue
447
+ with _pending_lock:
448
+ owner = _pending_integrations.pop(lib_name, None)
449
+ sdk = owner() if owner is not None else None
450
+ if sdk is not None and sdk._initialized and not sdk._activation_cancelled:
451
+ sdk._patch_integration(lib_name, module_path)
452
+
453
+ _contain_logged(activate, site="integrations.patch_on_import")
454
+
394
455
  # Sites that have already logged a first-failure WARN; subsequent failures log at DEBUG.
395
456
  _first_failure_logged: set[str] = set()
396
457
 
@@ -1256,6 +1317,8 @@ def _rearm_owns(sdk: "StructSDK") -> bool:
1256
1317
 
1257
1318
 
1258
1319
  def _sdk_after_fork() -> None:
1320
+ global _pending_lock
1321
+ _pending_lock = threading.Lock()
1259
1322
  for sdk in list(_sdk_instances.values()):
1260
1323
  # A vanished worker's frame can retain its cleanup job. The SDK still owns
1261
1324
  # these objects; drop only the job's references, without flushing or locking.
@@ -1763,49 +1826,48 @@ class StructSDK:
1763
1826
  return self._shutdown_job.deadline if self._shutdown_job is not None else None
1764
1827
 
1765
1828
  def _auto_instrument(self, options: Optional[Mapping[str, Mapping[str, Any]]] = None):
1766
- """Detect and patch installed libraries, except those turned off with
1767
- ``instrumentation_options={name: {"enabled": False}}``."""
1829
+ """Patch each GenAI library the app has imported, and each other installed one
1830
+ when the app imports it, except those turned off with
1831
+ ``instrumentation_options={name: {"enabled": False}}`` (SDK-PY-5)."""
1832
+ import wrapt
1833
+
1768
1834
  from struct_sdk import _auto
1769
1835
 
1770
1836
  # The same ownership rule applies to GenAI patches and contrib
1771
1837
  # instrumentors. Explicit AI-only mode keeps its isolated patches.
1772
1838
  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
1839
  left_to_ddtrace = []
1790
- for lib_name, module_path in integrations:
1840
+ for lib_name, module_path, modules in _GENAI_INTEGRATIONS:
1791
1841
  if lib_name in _patched_integrations:
1792
1842
  continue
1793
1843
  if (options or {}).get(lib_name, {}).get("enabled", True) is False:
1794
1844
  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
1845
  try:
1800
- import importlib
1801
- mod = importlib.import_module(module_path)
1802
- mod.patch(self) # type: ignore[attr-defined]
1803
- _patched_integrations.add(lib_name)
1804
- logger.info("Auto-instrumented: %s", lib_name)
1805
- except ImportError:
1806
- pass
1846
+ if _auto._left_to_ddtrace(lib_name, ddtrace_owned):
1847
+ if _auto._genai_installed(lib_name):
1848
+ left_to_ddtrace.append(lib_name)
1849
+ continue
1850
+ if not modules or any(module in sys.modules for module in modules):
1851
+ self._patch_integration(lib_name, module_path)
1852
+ continue
1853
+ # Importing a library the app has not imported runs its import-time
1854
+ # code in the app's process (warnings, network fetches, start-up
1855
+ # cost), so the patch waits for the app's own import.
1856
+ for module in modules:
1857
+ if not _importable(module):
1858
+ continue
1859
+ with _pending_lock:
1860
+ _pending_integrations[lib_name] = weakref.ref(self)
1861
+ registered = module in _import_hooks
1862
+ if registered:
1863
+ continue
1864
+ # Marked only once wrapt holds the callback: a second
1865
+ # registration is harmless, as activation pops the owner.
1866
+ wrapt.register_post_import_hook(_patch_on_import, module)
1867
+ with _pending_lock:
1868
+ _import_hooks.add(module)
1807
1869
  except Exception:
1808
- logger.debug("Failed to instrument %s", lib_name, exc_info=True)
1870
+ logger.debug("Failed to set up instrumentation for %s", lib_name, exc_info=True)
1809
1871
  if left_to_ddtrace:
1810
1872
  # WARNING, unlike the contrib skips' INFO: these libraries get no
1811
1873
  # Struct model spans at all, which a ddtrace-run user can't see.
@@ -1815,6 +1877,21 @@ class StructSDK:
1815
1877
  ", ".join(sorted(left_to_ddtrace)),
1816
1878
  )
1817
1879
 
1880
+ def _patch_integration(self, lib_name: str, module_path: str) -> None:
1881
+ if lib_name in _patched_integrations:
1882
+ return
1883
+ try:
1884
+ import importlib
1885
+
1886
+ mod = importlib.import_module(module_path)
1887
+ mod.patch(self) # type: ignore[attr-defined]
1888
+ _patched_integrations.add(lib_name)
1889
+ logger.info("Auto-instrumented: %s", lib_name)
1890
+ except ImportError:
1891
+ pass
1892
+ except Exception:
1893
+ logger.debug("Failed to instrument %s", lib_name, exc_info=True)
1894
+
1818
1895
  @property
1819
1896
  def ai_tracer_provider(self) -> Optional[TracerProvider]:
1820
1897
  """The provider the GenAI spans use: the host's SDK provider in attach mode, else
@@ -2149,7 +2226,7 @@ class _AgentContext:
2149
2226
  version = self._version
2150
2227
  metadata = self._metadata
2151
2228
 
2152
- if asyncio.iscoroutinefunction(fn):
2229
+ if _is_coroutine_function(fn):
2153
2230
  @functools.wraps(fn)
2154
2231
  async def wrapper(*args: Any, **kwargs: Any) -> Any:
2155
2232
  async with _AgentContext(sdk, name=span_name, session_id=explicit_session_id, agent_id=agent_id, version=version, metadata=metadata):
@@ -2543,7 +2620,7 @@ class _ToolContext:
2543
2620
  sdk = self._sdk
2544
2621
  tool_call_id = self._tool_call_id
2545
2622
 
2546
- if asyncio.iscoroutinefunction(fn):
2623
+ if _is_coroutine_function(fn):
2547
2624
  @functools.wraps(fn)
2548
2625
  async def wrapper(*args: Any, **kwargs: Any) -> Any:
2549
2626
  async with _ToolContext(sdk, name=tool_name, tool_call_id=tool_call_id) as ctx:
@@ -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
 
File without changes
File without changes