struct-sdk 0.4.22__tar.gz → 0.5.2__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 (30) hide show
  1. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/PKG-INFO +40 -25
  2. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/README.md +38 -24
  3. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/pyproject.toml +8 -1
  4. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_auto.py +146 -69
  5. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/autogen.py +3 -3
  6. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/core.py +47 -19
  7. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/pydantic_ai.py +39 -23
  8. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/temporal.py +14 -8
  9. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/.gitignore +0 -0
  10. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/LICENSE +0 -0
  11. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/__init__.py +0 -0
  12. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_container.py +0 -0
  13. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_distro.py +0 -0
  14. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_event_loop.py +0 -0
  15. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_genai_content.py +0 -0
  16. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_metrics.py +0 -0
  17. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_operation_details.py +0 -0
  18. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/_pool.py +0 -0
  19. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/ag2.py +0 -0
  20. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/anthropic.py +0 -0
  21. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/claude_agent.py +0 -0
  22. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/crewai.py +0 -0
  23. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/gcp.py +0 -0
  24. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/google_genai.py +0 -0
  25. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/langchain.py +0 -0
  26. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/litellm.py +0 -0
  27. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/llamaindex.py +0 -0
  28. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/mcp.py +0 -0
  29. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/openai.py +0 -0
  30. {struct_sdk-0.4.22 → struct_sdk-0.5.2}/src/struct_sdk/openai_agents.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: struct-sdk
3
- Version: 0.4.22
3
+ Version: 0.5.2
4
4
  Summary: Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry
5
5
  Project-URL: Homepage, https://struct.ai
6
6
  Project-URL: Documentation, https://struct.ai/docs
@@ -24,6 +24,7 @@ Requires-Python: >=3.10
24
24
  Requires-Dist: opentelemetry-api>=1.45.1
25
25
  Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
26
26
  Requires-Dist: opentelemetry-sdk>=1.27.0
27
+ Requires-Dist: struct-sdk-native<0.2,>=0.1.0
27
28
  Requires-Dist: wrapt>=1.16.0
28
29
  Provides-Extra: anthropic
29
30
  Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
@@ -184,7 +185,7 @@ async with struct.agent(name="checkout"):
184
185
  |---|---|---|
185
186
  | `anthropic` | `chat {model}` | Cache-token accounting; streaming chats with tool-use reconstruction. Bedrock and Vertex variants supported if installed. |
186
187
  | `openai` (Responses and Chat Completions) | `chat {model}` | `responses.create` and `chat.completions.create` on sync and async clients, streaming or not, including the `.stream()` helpers (Azure and OpenAI-compatible clients such as vLLM, Groq, DeepSeek and xAI included). Raw `create(stream=True)` spans end exactly once on exhaustion, `close()`, `with` exit, error, cancellation or garbage collection; every loop over a stream shares one iteration (LiteLLM starts one per chunk), so a `break` ends the span when it releases the stream. Helper streams that exit early end when the helper is released. Chat Completions streamed usage is recorded when you pass `stream_options={"include_usage": True}`; Responses records terminal usage without that option. The SDK never changes your request. Cached-token accounting from the usage details. Message-content capture at parity with the Anthropic integration: in event modes, one `gen_ai.client.inference.operation.details` record per call (one output message per choice; for a stream, written when the stream ends); in span modes, `gen_ai.input.messages` / `gen_ai.output.messages` on the span. Reasoning items are skipped (`encrypted_content` is never emitted). `chat.completions.parse()` and `responses.parse()` calls are not traced. |
187
- | `pydantic_ai` | `invoke_agent {agent}`, `chat {model}`, `execute_tool {tool}` | pydantic-ai's own instrumentation, turned on with Struct's tracer provider. See [pydantic-ai](#pydantic-ai). |
188
+ | `pydantic_ai` | `invoke_agent {agent}`, `chat {model}`, `execute_tool {tool}` | pydantic-ai's own instrumentation, turned on with the tracer provider Struct's GenAI spans use. See [pydantic-ai](#pydantic-ai). |
188
189
  | `agents` (OpenAI Agents SDK) | `invoke_agent {workflow}`, `invoke_agent {agent}`, `chat {model}`, `execute_tool {tool}` | A `TracingProcessor` added next to the host's: every run, agent, model call (Responses, Chat Completions and LiteLLM models, streamed or not), function tool and handoff. See [OpenAI Agents SDK](#openai-agents-sdk). |
189
190
  | `mcp` (`ClientSession.call_tool`) | `tools/call {tool}` | One CLIENT span per MCP tool call (`gen_ai.operation.name = execute_tool`), with the trace context sent in `params._meta`. See [MCP](#mcp). |
190
191
  | `google.genai` | `generate_content {model}` | `client.models.generate_content` and `client.aio.models.generate_content` (Gemini API → `gcp.gemini`, Vertex AI → `gcp.vertex_ai`), usage with cached and thinking tokens. Streams pass through untraced. Google ADK's own spans own its model calls. See [Gemini and Google ADK](#gemini-and-google-adk). |
@@ -257,7 +258,7 @@ direct `InstrumentedModel` exception recording are outside this guarantee.
257
258
  - **Content:** in event modes, each chat call's messages go to one
258
259
  `operation.details` event. Span modes keep chat content on spans. Tool
259
260
  arguments and results remain on `execute_tool` spans in every mode but `none`.
260
- - **Sessions:** on Struct's provider, a `struct.agent(session_id=...)`
261
+ - **Sessions:** through Struct's settings, a `struct.agent(session_id=...)`
261
262
  around the run wins; otherwise pydantic-ai's `conversation_id` is used.
262
263
  Instrumentation configured on your own provider keeps its conversation IDs.
263
264
  - **Turn it off** with
@@ -410,9 +411,8 @@ async with struct.agent(name="support", session_id=conversation_id):
410
411
  AutoGen (0.7+) traces its agents and tools through the global
411
412
  OpenTelemetry provider, which Struct owns or attaches to in the default
412
413
  full-app mode; with `auto_instrument=False` only Struct's `chat` spans
413
- arrive. The `struct.agent()` session reaches AutoGen's own spans only when
414
- Struct owns the provider (owned full-app mode); attached to your provider,
415
- only Struct's `chat` spans carry it. Streamed model calls
414
+ arrive. In full-app mode the `struct.agent()` session reaches AutoGen's own
415
+ spans on the shared provider. Streamed model calls
416
416
  (`model_client_stream=True`) get no AutoGen span; the `openai` integration
417
417
  traces them. This is Microsoft AutoGen (`autogen-agentchat`), not AG2.
418
418
 
@@ -803,8 +803,12 @@ setup is unaffected. The default is [full-app mode](#full-app-mode).
803
803
 
804
804
  Service identity follows the standard OpenTelemetry variables when you don't
805
805
  pass it: `OTEL_SERVICE_NAME`, and `service.version` and
806
- `deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES`. Arguments to `init()`
807
- win. The resource also carries host, runtime and (with the `[auto]` extra)
806
+ `deployment.environment.name` in `OTEL_RESOURCE_ATTRIBUTES`. Arguments to `init()`
807
+ win. The resource carries the environment as `deployment.environment.name` and
808
+ as the deprecated `deployment.environment`. Either key in
809
+ `OTEL_RESOURCE_ATTRIBUTES` fills the other when it is missing or empty; different
810
+ values are kept, and Struct reads the standard key. The resource also carries host,
811
+ runtime and (with the `[auto]` extra)
808
812
  container metadata, plus the commit when `STRUCT_GIT_COMMIT_SHA` and
809
813
  `STRUCT_GIT_REPOSITORY_URL` are set. On Azure Container Apps it also carries
810
814
  `cloud.platform`, `container_app`, `container_app_revision` and `replica`, read
@@ -869,9 +873,9 @@ before `init()`, call the contrib instrumentor directly (for example
869
873
 
870
874
  AWS calls through boto3/botocore or aiobotocore become one span per API
871
875
  operation (for example `S3.PutObject`), retries included, and carry the X-Ray
872
- header AWS services propagate. When Struct attaches to your existing
873
- OpenTelemetry setup, it instruments no library, so AWS operation spans reach
874
- Struct only if your setup instruments botocore itself.
876
+ header AWS services propagate. When your OpenTelemetry setup owns traces, Struct
877
+ turns on no trace instrumentor, so AWS operation spans reach Struct only if your
878
+ setup instruments botocore itself.
875
879
 
876
880
  Each instrumentor activates only when its library is installed.
877
881
  `instrumentation_options` disables or configures one by name; other keys are
@@ -893,16 +897,25 @@ libraries off (`OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=requests,urllib3`, or
893
897
  `*` for all of them). An explicit `instrumentation_options` entry takes
894
898
  precedence over it.
895
899
 
896
- Full-app mode installs Struct's providers as the global OpenTelemetry
897
- providers only when no tracer, meter or logger provider is installed. If the
898
- process already configured any of them (Azure Monitor, your own SDK setup),
899
- Struct adds its exporters to your SDK tracer and logger providers and one
900
- metric reader to your SDK meter provider, and instruments no library: your
901
- setup keeps ownership of instrumentation, sampling and shutdown. Struct's own
902
- container and event-loop metrics run on a meter provider of Struct's that is
903
- never global, so nothing new reaches your own backend. Struct's own GenAI
904
- spans keep their isolated provider either way, so your sampler does not drop
905
- them.
900
+ Full-app mode decides each signal on its own. For a signal the process already
901
+ configured (Azure Monitor, your own SDK setup), Struct adds its exporter to your
902
+ SDK provider, or one metric reader to your SDK meter provider, and instruments
903
+ nothing for that signal: your setup keeps ownership of its instrumentation,
904
+ sampling and shutdown. Struct's own
905
+ container, event-loop and connection-pool metrics run on a meter provider of
906
+ Struct's that is never global, so they add nothing to your own backend.
907
+
908
+ A signal you left unset is Struct's: with a tracer provider but no logger
909
+ provider, for example, Struct installs its logger provider and your app logs
910
+ reach Struct. Set up your own OpenTelemetry before `struct.init()` for any signal
911
+ you want to keep, because OpenTelemetry refuses a second provider.
912
+
913
+ Struct's GenAI spans use your SDK tracer provider, so they join your traces, reach your
914
+ backend and carry your resource, and your sampler and span processors apply to them: a
915
+ background agent run that starts its own trace can be sampled out of Struct too. Captured content is off by default.
916
+ In span-content modes it reaches every exporter on your provider; in `event_only`, chat messages
917
+ stay in Struct's logs, while agent prompt previews and tool arguments and results can reach your
918
+ backend. Filter span content in your pipeline; `redact_attributes` applies only to Struct's copy.
906
919
 
907
920
  Adding a reader to an existing meter provider needs opentelemetry-sdk 1.43 or
908
921
  later. On an older SDK, Struct logs one warning and your metrics are not sent
@@ -928,8 +941,9 @@ propagation is unchanged. An AWS instrumentor your own setup turns on keeps its
928
941
  propagator, and because both clients share botocore's request hook, its HTTP
929
942
  headers reach the other client's requests too. Logs, process metrics, thread context, AI spans and libraries
930
943
  ddtrace doesn't patch still go to Struct. With `DD_TRACE_OTEL_ENABLED=true`,
931
- ddtrace's OpenTelemetry provider isn't the OpenTelemetry SDK, so full-app
932
- mode attaches nothing (an INFO line says so) and only AI spans reach Struct.
944
+ ddtrace's OpenTelemetry provider isn't the OpenTelemetry SDK, so Struct attaches no
945
+ span exporter to it. AI spans go to Struct on Struct's own provider, and Struct installs
946
+ its provider for metrics and logs if you left those unset.
933
947
 
934
948
  ### Zero-code activation
935
949
 
@@ -979,8 +993,9 @@ exports are not logged. Pass
979
993
  `forward_core_logs=False` to keep Core's console output, or `core_logger=` to
980
994
  choose the logger. If you build your own `TelemetryConfig`, pass
981
995
  `logging=temporal.logging_config()` for the same logging. `tracing_interceptor()` (temporalio 1.11+) traces
982
- workflows and activities with Struct's tracer; a failing span processor never
983
- blocks a Temporal call or replaces its exception.
996
+ workflows and activities on the same provider as Struct's GenAI spans. On Struct's
997
+ provider a failing span processor never blocks a Temporal call or replaces its
998
+ exception; on yours, your processors run as they do for any library.
984
999
  Temporal server metrics are a Prometheus endpoint; scrape them with an
985
1000
  OpenTelemetry Collector and export OTLP/HTTP to your Struct ingest endpoint
986
1001
  with the `x-struct-ingest-key` header.
@@ -68,7 +68,7 @@ async with struct.agent(name="checkout"):
68
68
  |---|---|---|
69
69
  | `anthropic` | `chat {model}` | Cache-token accounting; streaming chats with tool-use reconstruction. Bedrock and Vertex variants supported if installed. |
70
70
  | `openai` (Responses and Chat Completions) | `chat {model}` | `responses.create` and `chat.completions.create` on sync and async clients, streaming or not, including the `.stream()` helpers (Azure and OpenAI-compatible clients such as vLLM, Groq, DeepSeek and xAI included). Raw `create(stream=True)` spans end exactly once on exhaustion, `close()`, `with` exit, error, cancellation or garbage collection; every loop over a stream shares one iteration (LiteLLM starts one per chunk), so a `break` ends the span when it releases the stream. Helper streams that exit early end when the helper is released. Chat Completions streamed usage is recorded when you pass `stream_options={"include_usage": True}`; Responses records terminal usage without that option. The SDK never changes your request. Cached-token accounting from the usage details. Message-content capture at parity with the Anthropic integration: in event modes, one `gen_ai.client.inference.operation.details` record per call (one output message per choice; for a stream, written when the stream ends); in span modes, `gen_ai.input.messages` / `gen_ai.output.messages` on the span. Reasoning items are skipped (`encrypted_content` is never emitted). `chat.completions.parse()` and `responses.parse()` calls are not traced. |
71
- | `pydantic_ai` | `invoke_agent {agent}`, `chat {model}`, `execute_tool {tool}` | pydantic-ai's own instrumentation, turned on with Struct's tracer provider. See [pydantic-ai](#pydantic-ai). |
71
+ | `pydantic_ai` | `invoke_agent {agent}`, `chat {model}`, `execute_tool {tool}` | pydantic-ai's own instrumentation, turned on with the tracer provider Struct's GenAI spans use. See [pydantic-ai](#pydantic-ai). |
72
72
  | `agents` (OpenAI Agents SDK) | `invoke_agent {workflow}`, `invoke_agent {agent}`, `chat {model}`, `execute_tool {tool}` | A `TracingProcessor` added next to the host's: every run, agent, model call (Responses, Chat Completions and LiteLLM models, streamed or not), function tool and handoff. See [OpenAI Agents SDK](#openai-agents-sdk). |
73
73
  | `mcp` (`ClientSession.call_tool`) | `tools/call {tool}` | One CLIENT span per MCP tool call (`gen_ai.operation.name = execute_tool`), with the trace context sent in `params._meta`. See [MCP](#mcp). |
74
74
  | `google.genai` | `generate_content {model}` | `client.models.generate_content` and `client.aio.models.generate_content` (Gemini API → `gcp.gemini`, Vertex AI → `gcp.vertex_ai`), usage with cached and thinking tokens. Streams pass through untraced. Google ADK's own spans own its model calls. See [Gemini and Google ADK](#gemini-and-google-adk). |
@@ -141,7 +141,7 @@ direct `InstrumentedModel` exception recording are outside this guarantee.
141
141
  - **Content:** in event modes, each chat call's messages go to one
142
142
  `operation.details` event. Span modes keep chat content on spans. Tool
143
143
  arguments and results remain on `execute_tool` spans in every mode but `none`.
144
- - **Sessions:** on Struct's provider, a `struct.agent(session_id=...)`
144
+ - **Sessions:** through Struct's settings, a `struct.agent(session_id=...)`
145
145
  around the run wins; otherwise pydantic-ai's `conversation_id` is used.
146
146
  Instrumentation configured on your own provider keeps its conversation IDs.
147
147
  - **Turn it off** with
@@ -294,9 +294,8 @@ async with struct.agent(name="support", session_id=conversation_id):
294
294
  AutoGen (0.7+) traces its agents and tools through the global
295
295
  OpenTelemetry provider, which Struct owns or attaches to in the default
296
296
  full-app mode; with `auto_instrument=False` only Struct's `chat` spans
297
- arrive. The `struct.agent()` session reaches AutoGen's own spans only when
298
- Struct owns the provider (owned full-app mode); attached to your provider,
299
- only Struct's `chat` spans carry it. Streamed model calls
297
+ arrive. In full-app mode the `struct.agent()` session reaches AutoGen's own
298
+ spans on the shared provider. Streamed model calls
300
299
  (`model_client_stream=True`) get no AutoGen span; the `openai` integration
301
300
  traces them. This is Microsoft AutoGen (`autogen-agentchat`), not AG2.
302
301
 
@@ -687,8 +686,12 @@ setup is unaffected. The default is [full-app mode](#full-app-mode).
687
686
 
688
687
  Service identity follows the standard OpenTelemetry variables when you don't
689
688
  pass it: `OTEL_SERVICE_NAME`, and `service.version` and
690
- `deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES`. Arguments to `init()`
691
- win. The resource also carries host, runtime and (with the `[auto]` extra)
689
+ `deployment.environment.name` in `OTEL_RESOURCE_ATTRIBUTES`. Arguments to `init()`
690
+ win. The resource carries the environment as `deployment.environment.name` and
691
+ as the deprecated `deployment.environment`. Either key in
692
+ `OTEL_RESOURCE_ATTRIBUTES` fills the other when it is missing or empty; different
693
+ values are kept, and Struct reads the standard key. The resource also carries host,
694
+ runtime and (with the `[auto]` extra)
692
695
  container metadata, plus the commit when `STRUCT_GIT_COMMIT_SHA` and
693
696
  `STRUCT_GIT_REPOSITORY_URL` are set. On Azure Container Apps it also carries
694
697
  `cloud.platform`, `container_app`, `container_app_revision` and `replica`, read
@@ -753,9 +756,9 @@ before `init()`, call the contrib instrumentor directly (for example
753
756
 
754
757
  AWS calls through boto3/botocore or aiobotocore become one span per API
755
758
  operation (for example `S3.PutObject`), retries included, and carry the X-Ray
756
- header AWS services propagate. When Struct attaches to your existing
757
- OpenTelemetry setup, it instruments no library, so AWS operation spans reach
758
- Struct only if your setup instruments botocore itself.
759
+ header AWS services propagate. When your OpenTelemetry setup owns traces, Struct
760
+ turns on no trace instrumentor, so AWS operation spans reach Struct only if your
761
+ setup instruments botocore itself.
759
762
 
760
763
  Each instrumentor activates only when its library is installed.
761
764
  `instrumentation_options` disables or configures one by name; other keys are
@@ -777,16 +780,25 @@ libraries off (`OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=requests,urllib3`, or
777
780
  `*` for all of them). An explicit `instrumentation_options` entry takes
778
781
  precedence over it.
779
782
 
780
- Full-app mode installs Struct's providers as the global OpenTelemetry
781
- providers only when no tracer, meter or logger provider is installed. If the
782
- process already configured any of them (Azure Monitor, your own SDK setup),
783
- Struct adds its exporters to your SDK tracer and logger providers and one
784
- metric reader to your SDK meter provider, and instruments no library: your
785
- setup keeps ownership of instrumentation, sampling and shutdown. Struct's own
786
- container and event-loop metrics run on a meter provider of Struct's that is
787
- never global, so nothing new reaches your own backend. Struct's own GenAI
788
- spans keep their isolated provider either way, so your sampler does not drop
789
- them.
783
+ Full-app mode decides each signal on its own. For a signal the process already
784
+ configured (Azure Monitor, your own SDK setup), Struct adds its exporter to your
785
+ SDK provider, or one metric reader to your SDK meter provider, and instruments
786
+ nothing for that signal: your setup keeps ownership of its instrumentation,
787
+ sampling and shutdown. Struct's own
788
+ container, event-loop and connection-pool metrics run on a meter provider of
789
+ Struct's that is never global, so they add nothing to your own backend.
790
+
791
+ A signal you left unset is Struct's: with a tracer provider but no logger
792
+ provider, for example, Struct installs its logger provider and your app logs
793
+ reach Struct. Set up your own OpenTelemetry before `struct.init()` for any signal
794
+ you want to keep, because OpenTelemetry refuses a second provider.
795
+
796
+ Struct's GenAI spans use your SDK tracer provider, so they join your traces, reach your
797
+ backend and carry your resource, and your sampler and span processors apply to them: a
798
+ background agent run that starts its own trace can be sampled out of Struct too. Captured content is off by default.
799
+ In span-content modes it reaches every exporter on your provider; in `event_only`, chat messages
800
+ stay in Struct's logs, while agent prompt previews and tool arguments and results can reach your
801
+ backend. Filter span content in your pipeline; `redact_attributes` applies only to Struct's copy.
790
802
 
791
803
  Adding a reader to an existing meter provider needs opentelemetry-sdk 1.43 or
792
804
  later. On an older SDK, Struct logs one warning and your metrics are not sent
@@ -812,8 +824,9 @@ propagation is unchanged. An AWS instrumentor your own setup turns on keeps its
812
824
  propagator, and because both clients share botocore's request hook, its HTTP
813
825
  headers reach the other client's requests too. Logs, process metrics, thread context, AI spans and libraries
814
826
  ddtrace doesn't patch still go to Struct. With `DD_TRACE_OTEL_ENABLED=true`,
815
- ddtrace's OpenTelemetry provider isn't the OpenTelemetry SDK, so full-app
816
- mode attaches nothing (an INFO line says so) and only AI spans reach Struct.
827
+ ddtrace's OpenTelemetry provider isn't the OpenTelemetry SDK, so Struct attaches no
828
+ span exporter to it. AI spans go to Struct on Struct's own provider, and Struct installs
829
+ its provider for metrics and logs if you left those unset.
817
830
 
818
831
  ### Zero-code activation
819
832
 
@@ -863,8 +876,9 @@ exports are not logged. Pass
863
876
  `forward_core_logs=False` to keep Core's console output, or `core_logger=` to
864
877
  choose the logger. If you build your own `TelemetryConfig`, pass
865
878
  `logging=temporal.logging_config()` for the same logging. `tracing_interceptor()` (temporalio 1.11+) traces
866
- workflows and activities with Struct's tracer; a failing span processor never
867
- blocks a Temporal call or replaces its exception.
879
+ workflows and activities on the same provider as Struct's GenAI spans. On Struct's
880
+ provider a failing span processor never blocks a Temporal call or replaces its
881
+ exception; on yours, your processors run as they do for any library.
868
882
  Temporal server metrics are a Prometheus endpoint; scrape them with an
869
883
  OpenTelemetry Collector and export OTLP/HTTP to your Struct ingest endpoint
870
884
  with the `x-struct-ingest-key` header.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "struct-sdk"
7
- version = "0.4.22"
7
+ version = "0.5.2"
8
8
  description = "Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -31,6 +31,9 @@ dependencies = [
31
31
  # Stream proxies (struct_sdk.openai): isinstance-transparent, as in
32
32
  # OpenLLMetry and ddtrace. Already required by every OTel instrumentor.
33
33
  "wrapt>=1.16.0",
34
+ # Native capture runtime. Always installs: platforms without a native build
35
+ # get its pure py3-none-any wheel, which reports the capability unavailable.
36
+ "struct-sdk-native>=0.1.0,<0.2",
34
37
  ]
35
38
 
36
39
  [project.urls]
@@ -247,6 +250,10 @@ openai2 = [
247
250
  "llama-index-llms-anthropic",
248
251
  ]
249
252
 
253
+ [tool.uv.sources]
254
+ # The pure project; working on this SDK never needs Rust.
255
+ struct-sdk-native = { path = "../struct-sdk-native", editable = true }
256
+
250
257
  [tool.uv]
251
258
  conflicts = [[{ group = "dev" }, { group = "openai2" }]]
252
259
  override-dependencies = [
@@ -5,14 +5,13 @@ databases, queues, app logs (``logging`` and structlog) and process metrics,
5
5
  using the OpenTelemetry contrib instrumentors the customer has installed
6
6
  (``struct-sdk[auto]``).
7
7
 
8
- Ownership follows the host's global providers:
8
+ Ownership is decided for each signal on its own, from the host's global providers:
9
9
 
10
- * No tracer, meter or logger provider installed: Struct installs its
11
- providers globally and instruments supported libraries.
12
- * Any provider installed (Azure Monitor, the host's own OpenTelemetry): Struct
13
- adds its exporters to the host's SDK tracer, logger and meter providers, if
14
- any, and instruments no library — the host owns instrumentation, sampling and
15
- lifecycle.
10
+ * A signal the host left unset: Struct installs its provider globally, and turns
11
+ on the instrumentation for that signal.
12
+ * A signal the host set (Azure Monitor, its own OpenTelemetry): Struct adds its
13
+ exporter to the host's SDK provider, if it is one, and instruments nothing for
14
+ that signal — the host owns its instrumentation, sampling and lifecycle.
16
15
 
17
16
  In either mode Struct's own metrics (container CPU and memory, event-loop
18
17
  delay) run on a Struct-only meter provider that is never installed globally.
@@ -202,6 +201,11 @@ class FullAppState:
202
201
  # The provider for Struct's own instruments, in either mode; never global.
203
202
  struct_meter_provider: Optional[MeterProvider] = None
204
203
  runtime: Optional[_metrics.RuntimeMetrics] = None
204
+ attached_tracer_provider: Optional[TracerProvider] = None
205
+
206
+ def watch_running_loop(self) -> None:
207
+ if self.runtime is not None:
208
+ self.runtime.watch_running_loop()
205
209
 
206
210
  def shutdown(self, timeout_millis: int) -> None:
207
211
  if self.restore_logging_config is not None:
@@ -226,9 +230,40 @@ class FullAppState:
226
230
  _contain_logged(lambda: _metrics.shut_down_once(provider, timeout_millis), site="auto.metrics.shutdown")
227
231
 
228
232
 
229
- def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
233
+ def attach_host_tracing(sdk: "StructSDK") -> None:
234
+ """Attach Struct to the host's SDK tracer provider, if it has one, and use that provider for the
235
+ GenAI spans (PDR-20261105-1224), as any library would. Runs before the GenAI patches ask for
236
+ their tracers. A failure here leaves the GenAI spans on Struct's own provider."""
230
237
  state = FullAppState()
231
238
  sdk._full_app = state
239
+ host = trace.get_tracer_provider()
240
+ if not isinstance(host, TracerProvider):
241
+ return
242
+ from struct_sdk import core
243
+ from struct_sdk._operation_details import OperationDetailsProcessor
244
+
245
+ budget = sdk._shutdown_timeout_seconds
246
+ # In this order: the metadata stamps a span before Struct's exporter copies it, and an
247
+ # operation.details record is written as its span ends.
248
+ for extra in (core._MetadataSpanProcessor(), OperationDetailsProcessor(sdk)):
249
+ host.add_span_processor(_HostAttachedSpanProcessor(extra, budget))
250
+ processor = _HostAttachedSpanProcessor(
251
+ _span_processor(sdk._endpoint, {"x-struct-ingest-key": sdk._ingest_key}),
252
+ budget,
253
+ watch_loop=state.watch_running_loop,
254
+ exports=True,
255
+ )
256
+ _add_to_host(host.add_span_processor, processor)
257
+ state.host_processors.append(processor)
258
+ state.attached_tracer_provider = host
259
+ sdk._ai_tracer_provider = host
260
+
261
+
262
+ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
263
+ """Decide each signal on its own (PDR-20261105-1224): attach to a signal the host set, and
264
+ install Struct's provider for one it left unset."""
265
+ state = sdk._full_app if sdk._full_app is not None else FullAppState()
266
+ sdk._full_app = state
232
267
  tracer_provider = sdk._tracer_provider
233
268
  logger_provider = sdk._logger_provider
234
269
  if tracer_provider is None or logger_provider is None:
@@ -238,76 +273,94 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
238
273
  host_tracer_provider = trace.get_tracer_provider()
239
274
  host_meter_provider = metrics.get_meter_provider()
240
275
  host_logger_provider = _logs.get_logger_provider()
241
- host_has_providers = not (
242
- isinstance(host_tracer_provider, trace.ProxyTracerProvider)
243
- and _is_unset(host_meter_provider)
244
- and _is_unset(host_logger_provider)
245
- )
246
276
  options = _with_env_disabled(options)
247
- if host_has_providers:
248
- budget = sdk._shutdown_timeout_seconds
249
- if _enabled(options, METRICS):
250
- def attach_metrics() -> None:
251
- if isinstance(host_meter_provider, MeterProvider):
252
- state.host_metric_reader = _metrics.attach_host_reader(host_meter_provider, sdk._endpoint, headers)
253
- if state.host_metric_reader is not None:
254
- state.host_meter_provider = host_meter_provider
255
- _start_struct_metrics(state, sdk._endpoint, tracer_provider, headers)
256
-
257
- _safe(attach_metrics, site="auto.metrics")
258
- if isinstance(host_tracer_provider, TracerProvider):
277
+ owns_traces = isinstance(host_tracer_provider, trace.ProxyTracerProvider)
278
+ no_host = owns_traces and _is_unset(host_meter_provider) and _is_unset(host_logger_provider)
279
+ # Next to a host's setup, a signal the app turned off stays unset. With no host, Struct's
280
+ # providers are the app's pipeline and are global either way.
281
+ owns_metrics = _is_unset(host_meter_provider) and (no_host or _enabled(options, METRICS))
282
+ owns_logs = _is_unset(host_logger_provider) and (no_host or _enabled(options, LOGGING))
283
+ budget = sdk._shutdown_timeout_seconds
284
+
285
+ if isinstance(host_tracer_provider, TracerProvider) and state.attached_tracer_provider is not host_tracer_provider:
286
+ # A provider set up after the GenAI patches took their tracers (importing a library can do
287
+ # that), or one whose first attach failed: its spans still reach Struct, and the GenAI
288
+ # spans stay on Struct's provider.
289
+ def attach_spans() -> None:
259
290
  processor = _HostAttachedSpanProcessor(
260
- _span_processor(sdk._endpoint, headers),
261
- budget,
262
- watch_loop=state.runtime.watch_running_loop if state.runtime is not None else None,
291
+ _span_processor(sdk._endpoint, headers), budget, watch_loop=state.watch_running_loop, exports=True
263
292
  )
264
- host_tracer_provider.add_span_processor(processor)
293
+ _add_to_host(host_tracer_provider.add_span_processor, processor)
265
294
  state.host_processors.append(processor)
266
- if isinstance(host_logger_provider, LoggerProvider) and _enabled(options, LOGGING):
267
- log_processor = _ExportPathFilteringLogProcessor(
268
- _log_processor(sdk._endpoint, headers), budget
295
+ state.attached_tracer_provider = host_tracer_provider
296
+
297
+ _safe(attach_spans, site="auto.host_spans.attach")
298
+
299
+ if owns_traces:
300
+ trace.set_tracer_provider(tracer_provider)
301
+ if owns_metrics:
302
+ # Struct is the app's own pipeline here, so OpenTelemetry's records about
303
+ # collections (an app callback that raises) stay where the app expects them.
304
+ with _new_metric_reader(sdk._endpoint, headers, isolate_collection=False) as reader:
305
+ meter_provider = MeterProvider(
306
+ resource=tracer_provider.resource,
307
+ metric_readers=[reader],
308
+ # StructSDK's bounded shutdown owns exit; the provider's own atexit hook
309
+ # would block for its 30s default on a dead collector.
310
+ shutdown_on_exit=False,
269
311
  )
270
- host_logger_provider.add_log_record_processor(log_processor)
271
- state.host_processors.append(log_processor)
272
- attached = len(state.host_processors) + (state.host_metric_reader is not None)
273
- if attached:
274
- logger.debug("Host OpenTelemetry providers present; full-app mode attached %d exporters", attached)
275
- elif not isinstance(host_logger_provider, LoggerProvider) and not isinstance(host_meter_provider, MeterProvider):
276
- logger.info(
277
- "Struct full-app mode attached nothing: the host's OpenTelemetry providers (%s) are "
278
- "not OpenTelemetry SDK providers, for example ddtrace with DD_TRACE_OTEL_ENABLED. "
279
- "AI spans still go to Struct.",
280
- type(host_tracer_provider).__name__,
281
- )
282
- return
312
+ sdk._meter_provider = meter_provider
313
+ metrics.set_meter_provider(meter_provider)
314
+ if owns_logs:
315
+ _logs.set_logger_provider(logger_provider)
283
316
 
284
- trace.set_tracer_provider(tracer_provider)
285
- # Struct is the app's own pipeline here, so OpenTelemetry's records about
286
- # collections (an app callback that raises) stay where the app expects them.
287
- with _new_metric_reader(sdk._endpoint, headers, isolate_collection=False) as reader:
288
- meter_provider = MeterProvider(
289
- resource=tracer_provider.resource,
290
- metric_readers=[reader],
291
- # StructSDK's bounded shutdown owns exit; the provider's own atexit hook
292
- # would block for its 30s default on a dead collector.
293
- shutdown_on_exit=False,
294
- )
295
- sdk._meter_provider = meter_provider
296
- metrics.set_meter_provider(meter_provider)
297
- _logs.set_logger_provider(logger_provider)
298
317
  if _enabled(options, METRICS):
299
- _safe(lambda: _start_struct_metrics(state, sdk._endpoint, tracer_provider, headers), site="auto.metrics")
300
-
301
- _instrument_libraries(tracer_provider, meter_provider, options)
302
- if _enabled(options, AZURE_SDK):
318
+ def attach_metrics() -> None:
319
+ if isinstance(host_meter_provider, MeterProvider):
320
+ state.host_metric_reader = _metrics.attach_host_reader(host_meter_provider, sdk._endpoint, headers)
321
+ if state.host_metric_reader is not None:
322
+ state.host_meter_provider = host_meter_provider
323
+ _start_struct_metrics(state, sdk._endpoint, tracer_provider, headers)
324
+
325
+ _safe(attach_metrics, site="auto.metrics")
326
+ if isinstance(host_logger_provider, LoggerProvider) and _enabled(options, LOGGING):
327
+ log_processor = _ExportPathFilteringLogProcessor(_log_processor(sdk._endpoint, headers), budget)
328
+ _add_to_host(host_logger_provider.add_log_record_processor, log_processor)
329
+ state.host_processors.append(log_processor)
330
+
331
+ signals = frozenset(
332
+ name for name, owned in (("traces", owns_traces), ("metrics", owns_metrics), ("logs", owns_logs)) if owned
333
+ )
334
+ _instrument_libraries(tracer_provider, metrics.get_meter_provider(), options, signals)
335
+ if owns_traces and _enabled(options, AZURE_SDK):
303
336
  _safe(_instrument_azure_sdk, site="auto.azure_sdk")
304
- if _enabled(options, LOGGING):
337
+ if owns_logs and _enabled(options, LOGGING):
305
338
  def bridge() -> None:
306
339
  state.log_handler = _bridge_logging(logger_provider)
307
340
  state.restore_logging_config = _keep_through_logging_config(state.log_handler)
308
341
 
309
342
  _safe(bridge, site="auto.logging")
310
343
 
344
+ if len(signals) == 3:
345
+ return
346
+ attached = len(state.host_processors) + (state.host_metric_reader is not None)
347
+ if signals:
348
+ # A host that sets one of these up after init() is refused by OpenTelemetry.
349
+ logger.info(
350
+ "Struct full-app mode installed its provider for %s, which the host left unset. "
351
+ "Set up your own OpenTelemetry before struct.init() to keep a signal for yourself.",
352
+ ", ".join(sorted(signals)),
353
+ )
354
+ elif attached:
355
+ logger.debug("Host OpenTelemetry providers present; full-app mode attached %d exporters", attached)
356
+ else:
357
+ logger.info(
358
+ "Struct full-app mode attached nothing: the host's OpenTelemetry providers (%s) are "
359
+ "not OpenTelemetry SDK providers, for example ddtrace with DD_TRACE_OTEL_ENABLED. "
360
+ "AI spans still go to Struct.",
361
+ type(host_tracer_provider).__name__,
362
+ )
363
+
311
364
 
312
365
  def _start_struct_metrics(
313
366
  state: FullAppState, endpoint: str, tracer_provider: TracerProvider, headers: dict[str, str]
@@ -379,12 +432,20 @@ def _contrib_can_check_dependencies() -> bool:
379
432
  return not too_old
380
433
 
381
434
 
435
+ def _signal_of(name: str) -> str:
436
+ """The signal an instrumentor records. Struct turns one on only where that signal is its own."""
437
+ if name == "system_metrics":
438
+ return "metrics"
439
+ return "logs" if name in ("structlog", "exceptions") else "traces"
440
+
441
+
382
442
  def _instrument_libraries(
383
443
  tracer_provider: TracerProvider,
384
- meter_provider: MeterProvider,
444
+ meter_provider: Any,
385
445
  options: Mapping[str, Mapping[str, Any]],
446
+ signals: frozenset[str],
386
447
  ) -> None:
387
- if not _contrib_can_check_dependencies():
448
+ if not signals or not _contrib_can_check_dependencies():
388
449
  return
389
450
  available = {ep.name: ep for ep in _instrumentor_entry_points()}
390
451
  ddtrace_owned = _ddtrace_instrumented()
@@ -392,7 +453,7 @@ def _instrument_libraries(
392
453
  beside_ddtrace: list[str] = []
393
454
  for name in SUPPORTED_INSTRUMENTATIONS:
394
455
  entry_point = available.get(name)
395
- if entry_point is None or not _enabled(options, name):
456
+ if entry_point is None or not _enabled(options, name) or _signal_of(name) not in signals:
396
457
  continue
397
458
  owned_by_ddtrace = _left_to_ddtrace(name, ddtrace_owned)
398
459
  if owned_by_ddtrace and name not in _QUIET_NEXT_TO_DDTRACE:
@@ -564,7 +625,7 @@ def _target_installed(entry_point: Any) -> bool:
564
625
  def _instrument_one(
565
626
  entry_point: Any,
566
627
  tracer_provider: TracerProvider,
567
- meter_provider: MeterProvider,
628
+ meter_provider: Any,
568
629
  kwargs: dict[str, Any],
569
630
  quiet: bool = False,
570
631
  ) -> bool:
@@ -792,15 +853,31 @@ def _shut_down_within(processor: Any, budget_seconds: float) -> None:
792
853
  worker.join(budget_seconds)
793
854
 
794
855
 
856
+ def _add_to_host(add: Callable[[Any], None], processor: Any) -> None:
857
+ """Hand an exporting processor to a host provider. Its worker is already running, so one the
858
+ host refused is closed here, within the processor's budget: nothing else will."""
859
+ try:
860
+ add(processor)
861
+ except Exception:
862
+ processor.shutdown()
863
+ raise
864
+
865
+
795
866
  class _HostAttachedSpanProcessor(SpanProcessor):
796
867
  """Struct's span processor on a host TracerProvider, whose own processor
797
868
  chain does not isolate faults: anything raised here would reach the
798
869
  customer's span calls."""
799
870
 
800
871
  def __init__(
801
- self, inner: SpanProcessor, budget_seconds: float, *, watch_loop: Optional[Callable[[], None]] = None
872
+ self,
873
+ inner: SpanProcessor,
874
+ budget_seconds: float,
875
+ *,
876
+ watch_loop: Optional[Callable[[], None]] = None,
877
+ exports: bool = False,
802
878
  ) -> None:
803
879
  self._inner = inner
880
+ self.exports = exports # False for the processors that only enrich the host's spans
804
881
  self._budget_seconds = budget_seconds
805
882
  # Lets the event-loop delay probe find the loops the host's spans run on.
806
883
  self._watch_loop = watch_loop
@@ -21,8 +21,8 @@ in full-app mode. Struct fills the two gaps:
21
21
  own ``chat`` span. AutoGen's Anthropic client
22
22
  needs nothing: it goes through the anthropic SDK, which Struct's Anthropic
23
23
  patch already records with full usage.
24
- - **Sessions.** A span processor on Struct's tracer provider stamps the
25
- enclosing ``struct.agent()`` session on ``autogen-core`` spans as they start.
24
+ - **Sessions.** A span processor on the provider Struct's GenAI spans use stamps
25
+ the enclosing ``struct.agent()`` session on ``autogen-core`` spans as they start.
26
26
 
27
27
  Content follows ``ContentCaptureMode`` like the provider patches (SDK-PY-11): a
28
28
  call's ``gen_ai.input.messages`` (``SystemMessage``s included, as chat history),
@@ -119,7 +119,7 @@ def patch(sdk: StructSDK) -> None:
119
119
  if original is not None and not getattr(original, "__struct_wrapped__", False):
120
120
  BaseOpenAIChatCompletionClient.create = _wrap(original, tracer, sdk) # type: ignore[method-assign]
121
121
  _wrapped.append((BaseOpenAIChatCompletionClient, original))
122
- provider = getattr(sdk, "_tracer_provider", None)
122
+ provider = sdk.ai_tracer_provider
123
123
  if _processor is None and provider is not None and hasattr(provider, "add_span_processor"):
124
124
  _processor = _SessionProcessor()
125
125
  provider.add_span_processor(_processor)
@@ -3,8 +3,9 @@
3
3
  Users call struct.init() once at startup. The SDK auto-instruments any
4
4
  supported libraries that are installed (anthropic, claude_agent_sdk,
5
5
  langchain_core, openai, openai-agents) and, by default, runs full-app mode (see
6
- ``struct_sdk._auto``). ``auto_instrument=False`` keeps only the AI-library
7
- instrumentation on isolated providers.
6
+ ``struct_sdk._auto``). The AI spans use the host's SDK tracer provider when it
7
+ has one. ``auto_instrument=False`` keeps only
8
+ the AI-library instrumentation on isolated providers.
8
9
 
9
10
  OTel GenAI Semantic Conventions v1.37+ compliant.
10
11
  """
@@ -110,8 +111,8 @@ AgentMetadataValue = Union[
110
111
  tuple of one scalar type, or None (inherits the enclosing value)."""
111
112
 
112
113
  # The enclosing struct.agent() scopes' metadata, merged (inner wins). The
113
- # _MetadataSpanProcessor stamps it on every span started on Struct's provider
114
- # inside the scope ([SDK-PY-25]). Never Baggage: it is propagated in-process
114
+ # _MetadataSpanProcessor stamps it on every span started on the provider the GenAI
115
+ # spans use, inside the scope ([SDK-PY-25]). Never Baggage: it is propagated in-process
115
116
  # only and exported as span attributes, never sent on outgoing request headers.
116
117
  _current_metadata: contextvars.ContextVar[Optional["_MetadataFrame"]] = contextvars.ContextVar("_current_metadata", default=None)
117
118
 
@@ -901,6 +902,12 @@ def _detected_attributes() -> dict[str, Any]:
901
902
  return {key: value for key, value in detected.items() if value}
902
903
 
903
904
 
905
+ # The standard key, and the one semantic conventions 1.27.0 deprecated in its favour. Struct
906
+ # writes both until a later release drops the old one (PDR-20261105-1213).
907
+ _ENVIRONMENT_KEY = "deployment.environment.name"
908
+ _DEPRECATED_ENVIRONMENT_KEY = "deployment.environment"
909
+
910
+
904
911
  def _build_resource(
905
912
  service_name: Optional[str], service_version: Optional[str], environment: Optional[str]
906
913
  ) -> Resource:
@@ -912,7 +919,8 @@ def _build_resource(
912
919
  for key, value in (
913
920
  ("service.name", service_name),
914
921
  ("service.version", service_version),
915
- ("deployment.environment", environment),
922
+ (_ENVIRONMENT_KEY, environment),
923
+ (_DEPRECATED_ENVIRONMENT_KEY, environment),
916
924
  )
917
925
  if value is not None
918
926
  }
@@ -928,8 +936,12 @@ def _build_resource(
928
936
  defaults["service.name"] = "default-agent"
929
937
  if "service.version" not in attributes:
930
938
  defaults["service.version"] = "0.0.0"
931
- if "deployment.environment" not in attributes:
932
- defaults["deployment.environment"] = attributes.get("deployment.environment.name", "development")
939
+ # Either key fills the other, and an empty one counts as missing, as conditions read it;
940
+ # two different values from the environment are both kept.
941
+ given = attributes.get(_ENVIRONMENT_KEY) or attributes.get(_DEPRECATED_ENVIRONMENT_KEY) or "development"
942
+ for key in (_ENVIRONMENT_KEY, _DEPRECATED_ENVIRONMENT_KEY):
943
+ if not attributes.get(key):
944
+ defaults[key] = given
933
945
  if "service.instance.id" not in attributes:
934
946
  defaults["service.instance.id"] = str(uuid.uuid4())
935
947
  return resource.merge(Resource(defaults)) if defaults else resource
@@ -941,6 +953,8 @@ class StructSDK:
941
953
  def __init__(self):
942
954
  self._initialized = False
943
955
  self._tracer_provider: Optional[TracerProvider] = None
956
+ # The provider the GenAI spans use when it isn't Struct's: the host's (SDK-PY-95).
957
+ self._ai_tracer_provider: Optional[TracerProvider] = None
944
958
  self._logger_provider: Optional[LoggerProvider] = None
945
959
  # Set only in full-app mode (auto_instrument=True).
946
960
  self._meter_provider: Optional[MeterProvider] = None
@@ -996,7 +1010,8 @@ class StructSDK:
996
1010
  service_version: Version string. Defaults to ``service.version`` in
997
1011
  ``OTEL_RESOURCE_ATTRIBUTES``, else "0.0.0".
998
1012
  environment: Deployment environment (development, staging,
999
- production). Defaults to ``deployment.environment`` in
1013
+ production). Written as ``deployment.environment.name`` and the
1014
+ deprecated ``deployment.environment``. Defaults to either key in
1000
1015
  ``OTEL_RESOURCE_ATTRIBUTES``, else "development".
1001
1016
  endpoint: Struct ingestion endpoint. Override for self-hosted or local dev.
1002
1017
  shutdown_timeout_seconds: Maximum time the SDK's atexit shutdown is
@@ -1014,11 +1029,12 @@ class StructSDK:
1014
1029
  clients, databases, queues, app logs and process metrics
1015
1030
  (instrumentors come from ``struct-sdk[auto]``). Call init()
1016
1031
  before importing framework classes or creating your web app,
1017
- and once per worker in pre-fork servers. If any OpenTelemetry
1018
- provider is already installed, Struct adds its exporters to
1019
- that setup (span and log processors, one metric reader) and
1020
- instruments no library; its own container and event-loop
1021
- metrics run on a meter provider that is never global.
1032
+ and once per worker in pre-fork servers. Struct decides each
1033
+ signal separately: it attaches exporters to host providers
1034
+ (span and log processors, one metric reader) and installs its
1035
+ provider and instrumentation for signals the host left unset.
1036
+ Its own container and event-loop metrics run on a meter
1037
+ provider that is never global.
1022
1038
  ``False`` keeps only the AI-library instrumentation on
1023
1039
  isolated providers.
1024
1040
  instrumentation_options: Per-library settings for full-app mode,
@@ -1076,11 +1092,12 @@ class StructSDK:
1076
1092
  # --- TracerProvider ---
1077
1093
  span_processor = _span_processor(endpoint, headers)
1078
1094
 
1079
- # Isolated TracerProvider — NOT set as the global (full-app
1080
- # mode may install it afterwards).
1095
+ # Struct's own TracerProvider — NOT set as the global (full-app
1096
+ # mode installs it when the host left traces unset). On a host's
1097
+ # SDK provider, the GenAI spans use that one instead (SDK-PY-95).
1081
1098
  resource = _build_resource(service_name, service_version, environment)
1082
1099
  self._service_name = str(resource.attributes["service.name"])
1083
- self._environment = str(resource.attributes["deployment.environment"])
1100
+ self._environment = str(resource.attributes[_ENVIRONMENT_KEY])
1084
1101
  self._full_app_requested = auto_instrument
1085
1102
  # shutdown_on_exit=False on every provider: the atexit
1086
1103
  # _shutdown below is bounded by shutdown_timeout_seconds, while
@@ -1109,6 +1126,10 @@ class StructSDK:
1109
1126
  global _init_pid
1110
1127
  _init_pid = os.getpid()
1111
1128
 
1129
+ if auto_instrument:
1130
+ from struct_sdk import _auto
1131
+
1132
+ _safe(lambda: _auto.attach_host_tracing(self), site="init.attach_host_tracing")
1112
1133
  self._auto_instrument(instrumentation_options or {})
1113
1134
  except Exception:
1114
1135
  logger.warning(
@@ -1189,11 +1210,18 @@ class StructSDK:
1189
1210
  ", ".join(sorted(left_to_ddtrace)),
1190
1211
  )
1191
1212
 
1213
+ @property
1214
+ def ai_tracer_provider(self) -> Optional[TracerProvider]:
1215
+ """The provider the GenAI spans use: the host's SDK provider in attach mode, else
1216
+ Struct's, which owned mode installs as the global (SDK-PY-95)."""
1217
+ return self._ai_tracer_provider if self._ai_tracer_provider is not None else self._tracer_provider
1218
+
1192
1219
  def get_tracer(self, name: str = "struct-sdk") -> trace.Tracer:
1193
- """Get an OTel tracer from our isolated provider."""
1194
- if self._tracer_provider is None:
1220
+ """Get an OTel tracer for Struct's GenAI spans."""
1221
+ provider = self.ai_tracer_provider
1222
+ if provider is None:
1195
1223
  raise RuntimeError("Call struct.init() before using the SDK")
1196
- return self._tracer_provider.get_tracer(name, _SDK_VERSION)
1224
+ return provider.get_tracer(name, _SDK_VERSION)
1197
1225
 
1198
1226
  def get_logger(self, name: str = "struct-sdk") -> Any:
1199
1227
  """Get an OTel logger from our isolated provider."""
@@ -128,6 +128,9 @@ _struct_span_processor: Any = None # Struct's provider's span pipeline, set by
128
128
  # ends (1.40+).
129
129
  _AGENT_SPAN_ATTR = "_struct_agent_span"
130
130
  _ENDING_HOOK = "_on_ending" in getattr(getattr(SdkSpan.end, "__code__", None), "co_names", ())
131
+ # Set while Struct's guarded tracer starts a span: on a host's provider, how the session processor
132
+ # tells Struct's pydantic-ai spans from the host's own instrumentation (SDK-PY-43).
133
+ _starting_guarded_span: contextvars.ContextVar[bool] = contextvars.ContextVar("_starting_guarded_span", default=False)
131
134
  _wrapped: list[tuple[Any, str, Any]] = []
132
135
  _pending_models: list[tuple[str, tuple[str, ...]]] = []
133
136
  _lock = threading.Lock()
@@ -155,7 +158,7 @@ def patch(sdk: StructSDK) -> None:
155
158
  if _wrapped or _processor is not None:
156
159
  return
157
160
  _content_sdk = sdk
158
- tracer_provider = sdk._tracer_provider
161
+ tracer_provider = sdk.ai_tracer_provider
159
162
  if tracer_provider is None:
160
163
  return
161
164
 
@@ -201,7 +204,7 @@ def patch(sdk: StructSDK) -> None:
201
204
  except ImportError:
202
205
  pass
203
206
 
204
- _processor = _SessionProcessor()
207
+ _processor = _SessionProcessor(guarded_only=tracer_provider is not sdk._tracer_provider)
205
208
  tracer_provider.add_span_processor(_processor)
206
209
  _struct_span_processor = getattr(tracer_provider, "_active_span_processor", None)
207
210
 
@@ -260,7 +263,7 @@ def _settings(settings_cls: Any, sdk: StructSDK) -> Any:
260
263
  from opentelemetry.metrics import NoOpMeterProvider
261
264
 
262
265
  kwargs: dict[str, Any] = {
263
- "tracer_provider": _GuardedTracerProvider(sdk._tracer_provider),
266
+ "tracer_provider": _GuardedTracerProvider(sdk.ai_tracer_provider),
264
267
  "meter_provider": NoOpMeterProvider(),
265
268
  # pydantic-ai writes messages, tool arguments and results as span
266
269
  # attributes; in event modes Struct's guarded spans move the chat
@@ -487,7 +490,7 @@ def _contained_error_status(original: Any) -> Any:
487
490
 
488
491
 
489
492
  class _GuardedTracerProvider(TracerProvider):
490
- """Struct's provider, handing out guarded tracers."""
493
+ """The provider Struct's GenAI spans use, handing out guarded tracers."""
491
494
 
492
495
  def __init__(self, provider: Any) -> None:
493
496
  self._provider = provider
@@ -519,18 +522,22 @@ class _GuardedTracer(Tracer):
519
522
  def start() -> None:
520
523
  capped = _capped_attributes(attributes)
521
524
  kept, diverted = _split_content(capped, chat=bool(capped) and capped.get("gen_ai.operation.name") == "chat")
522
- started.append(
523
- self._tracer.start_span(
524
- name,
525
- context,
526
- kind,
527
- kept,
528
- links,
529
- start_time,
530
- record_exception,
531
- set_status_on_exception,
525
+ guarded = _starting_guarded_span.set(True)
526
+ try:
527
+ started.append(
528
+ self._tracer.start_span(
529
+ name,
530
+ context,
531
+ kind,
532
+ kept,
533
+ links,
534
+ start_time,
535
+ record_exception,
536
+ set_status_on_exception,
537
+ )
532
538
  )
533
- )
539
+ finally:
540
+ _starting_guarded_span.reset(guarded)
534
541
  _buffer(started[0], diverted)
535
542
 
536
543
  _contain(start, "pydantic_ai.start_span")
@@ -671,6 +678,7 @@ class _GuardedSpan(Span):
671
678
 
672
679
  # Content pydantic-ai records only on spans: the run's whole history and result.
673
680
  _SPAN_ONLY_CONTENT = frozenset({"pydantic_ai.all_messages", "final_result"})
681
+ _TOOL_DEFINITIONS = "gen_ai.tool.definitions"
674
682
 
675
683
 
676
684
  def _text_off_spans() -> bool:
@@ -688,10 +696,16 @@ def _is_chat(span: Any) -> bool:
688
696
  def _split_content(attributes: Any, *, chat: bool) -> tuple[Any, dict[str, Any]]:
689
697
  """``attributes`` split into what the span keeps and what goes to the chat call's
690
698
  ``operation.details`` event, by the content mode (SDK-PY-46). Outside a content
691
- mode pydantic-ai writes no messages, and what it does write stays on the span."""
699
+ mode pydantic-ai writes no messages, but it always writes the tool definitions:
700
+ opt-in in the GenAI conventions, about 100 KB per call with a large tool list, and
701
+ recorded only in a content mode by Struct's other integrations."""
692
702
  sdk = _content_sdk
693
- if not attributes or sdk is None or not sdk.capture_content:
703
+ if not attributes or sdk is None:
694
704
  return attributes, {}
705
+ if not sdk.capture_content:
706
+ if _TOOL_DEFINITIONS not in attributes:
707
+ return attributes, {}
708
+ return {key: value for key, value in dict(attributes).items() if key != _TOOL_DEFINITIONS}, {}
695
709
  kept: dict[str, Any] = {}
696
710
  diverted: dict[str, Any] = {}
697
711
  for key, value in dict(attributes).items():
@@ -821,7 +835,7 @@ def _reaches_struct(span: Any) -> bool:
821
835
  from struct_sdk._auto import _HostAttachedSpanProcessor
822
836
 
823
837
  processors = getattr(pipeline, "_span_processors", ())
824
- return any(isinstance(processor, _HostAttachedSpanProcessor) for processor in processors)
838
+ return any(isinstance(processor, _HostAttachedSpanProcessor) and processor.exports for processor in processors)
825
839
 
826
840
 
827
841
  def _suppress() -> Any:
@@ -937,24 +951,26 @@ def _platform_provider_attributes(original: Any) -> Any:
937
951
 
938
952
  class _SessionProcessor(SpanProcessor):
939
953
  """Stamps the enclosing ``struct.agent()`` session on pydantic-ai spans as
940
- they start (pydantic-ai has already set its own conversation id)."""
954
+ they start (pydantic-ai has already set its own conversation id). On a host's
955
+ provider (``guarded_only``), only on the spans Struct's settings started: the
956
+ host's own pydantic-ai instrumentation keeps its conversation ids."""
941
957
 
942
- def __init__(self) -> None:
958
+ def __init__(self, *, guarded_only: bool = False) -> None:
943
959
  self.enabled = True
960
+ self._guarded_only = guarded_only
944
961
 
945
962
  def on_start(self, span: Any, parent_context: Any = None) -> None:
946
963
  if self.enabled:
947
964
  _contain(lambda: self._stamp(span), "pydantic_ai.session")
948
965
 
949
- @staticmethod
950
- def _stamp(span: Any) -> None:
966
+ def _stamp(self, span: Any) -> None:
951
967
  scope = getattr(span, "instrumentation_scope", None)
952
968
  if getattr(scope, "name", None) != _SCOPE:
953
969
  return
954
970
  from struct_sdk.core import _current_agent_span, _current_session_id
955
971
 
956
972
  session_id = _current_session_id.get(None)
957
- if session_id:
973
+ if session_id and (_starting_guarded_span.get() or not self._guarded_only):
958
974
  span.set_attribute("gen_ai.conversation.id", session_id)
959
975
  # The struct.agent() span this call belongs to, held on the call's own span: a
960
976
  # stream may end it in another task or scope (SDK-PY-9).
@@ -15,13 +15,13 @@ Usage::
15
15
  )
16
16
 
17
17
  Core metrics (task slots, schedule-to-start latency, poll results, sticky
18
- cache, ...) go to Struct's ingest; workflow and activity spans use Struct's
19
- tracer provider whether or not full-app mode installed it globally. Core's own
18
+ cache, ...) go to Struct's ingest; workflow and activity spans use the provider
19
+ Struct's GenAI spans use. Core's own
20
20
  log lines (WARN and above from Temporal's crates, ERROR from others) go to the
21
21
  Python logger ``temporalio.core`` instead of the console, so they follow the
22
22
  app's logging setup: its levels, handlers and propagation. They reach Struct
23
- through whatever log bridge is connected to it (full-app owned mode adds one on
24
- the root logger; attach mode relies on the host's).
23
+ through whatever log bridge is connected to it: Struct's on the root logger where
24
+ Struct owns logs, the host's where the host owns them.
25
25
  """
26
26
 
27
27
  from __future__ import annotations
@@ -140,6 +140,11 @@ def telemetry_config(
140
140
  if not sdk._initialized or sdk._tracer_provider is None:
141
141
  return TelemetryConfig()
142
142
  instance_id = str(sdk._tracer_provider.resource.attributes.get("service.instance.id", ""))
143
+ # A caller's environment under either key fills the other, and an empty one counts as missing,
144
+ # as in OTEL_RESOURCE_ATTRIBUTES at init(): a default beside it would become the value conditions read.
145
+ environment_keys = ("deployment.environment.name", "deployment.environment")
146
+ tags = {key: value for key, value in (global_tags or {}).items() if value or key not in environment_keys}
147
+ environment = tags.get(environment_keys[0]) or tags.get(environment_keys[1]) or sdk._environment
143
148
  return TelemetryConfig(
144
149
  logging=logging_config(forward_core_logs=forward_core_logs, core_logger=core_logger),
145
150
  metrics=OpenTelemetryConfig(
@@ -152,9 +157,10 @@ def telemetry_config(
152
157
  ),
153
158
  global_tags={
154
159
  "service.name": sdk._service_name,
155
- "deployment.environment": sdk._environment,
160
+ "deployment.environment": environment,
161
+ "deployment.environment.name": environment,
156
162
  "service.instance.id": instance_id,
157
- **(global_tags or {}),
163
+ **tags,
158
164
  },
159
165
  attach_service_name=False,
160
166
  )
@@ -166,8 +172,8 @@ def tracing_interceptor(
166
172
  sdk: Optional["StructSDK"] = None,
167
173
  ) -> "TracingInterceptor":
168
174
  """Temporal client/worker interceptor that traces workflows and activities
169
- on Struct's tracer provider. Before ``struct.init()`` succeeds it traces
170
- nothing."""
175
+ on the provider Struct's GenAI spans use. Before ``struct.init()`` succeeds it
176
+ traces nothing."""
171
177
  from temporalio.contrib.opentelemetry import TracingInterceptor
172
178
 
173
179
  sdk = _resolve(sdk)
File without changes
File without changes