struct-sdk 0.5.26__tar.gz → 0.5.27__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 (44) hide show
  1. struct_sdk-0.5.27/PKG-INFO +171 -0
  2. struct_sdk-0.5.27/PYPI.md +54 -0
  3. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/README.md +54 -20
  4. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/pyproject.toml +5 -4
  5. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/anthropic.py +9 -29
  6. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/core.py +65 -7
  7. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/google_genai.py +2 -7
  8. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/langchain.py +3 -13
  9. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/litellm.py +2 -7
  10. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/llamaindex.py +4 -10
  11. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/mcp.py +3 -3
  12. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/openai.py +144 -55
  13. struct_sdk-0.5.26/PKG-INFO +0 -1070
  14. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/.gitignore +0 -0
  15. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/LICENSE +0 -0
  16. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/__init__.py +0 -0
  17. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_auto.py +0 -0
  18. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_container.py +0 -0
  19. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_distro.py +0 -0
  20. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_event_loop.py +0 -0
  21. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_fork_safe_http.py +0 -0
  22. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_genai_content.py +0 -0
  23. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_metrics.py +0 -0
  24. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/__init__.py +0 -0
  25. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/config.py +0 -0
  26. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/health.py +0 -0
  27. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/identity.py +0 -0
  28. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/native_events.py +0 -0
  29. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/outputs.py +0 -0
  30. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/poller.py +0 -0
  31. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/routing.py +0 -0
  32. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/runtime.py +0 -0
  33. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/self_metrics.py +0 -0
  34. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_observations/uwsgi.py +0 -0
  35. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_operation_details.py +0 -0
  36. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/_pool.py +0 -0
  37. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/ag2.py +0 -0
  38. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/autogen.py +0 -0
  39. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/claude_agent.py +0 -0
  40. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/crewai.py +0 -0
  41. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/gcp.py +0 -0
  42. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/openai_agents.py +0 -0
  43. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/pydantic_ai.py +0 -0
  44. {struct_sdk-0.5.26 → struct_sdk-0.5.27}/src/struct_sdk/temporal.py +0 -0
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.5
2
+ Name: struct-sdk
3
+ Version: 0.5.27
4
+ Summary: Python SDK for OTel auto-instrumentation and live instrumentation on Struct.
5
+ Project-URL: Homepage, https://struct.ai
6
+ Project-URL: Documentation, https://docs.struct.ai/observability/instrumentation/python
7
+ Project-URL: Issues, https://struct.ai/support
8
+ Author-email: Struct <support@struct.ai>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agent,ai,anthropic,langchain,observability,openai,opentelemetry,struct,tracing
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: System :: Monitoring
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: opentelemetry-api>=1.45.1
25
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
26
+ Requires-Dist: opentelemetry-sdk>=1.27.0
27
+ Requires-Dist: struct-sdk-native==0.2.0
28
+ Requires-Dist: wrapt>=1.16.0
29
+ Provides-Extra: anthropic
30
+ Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
31
+ Provides-Extra: auto
32
+ Requires-Dist: opentelemetry-instrumentation-aio-pika; extra == 'auto'
33
+ Requires-Dist: opentelemetry-instrumentation-aiohttp-client; extra == 'auto'
34
+ Requires-Dist: opentelemetry-instrumentation-aiohttp-server; extra == 'auto'
35
+ Requires-Dist: opentelemetry-instrumentation-aiokafka; extra == 'auto'
36
+ Requires-Dist: opentelemetry-instrumentation-aiopg; extra == 'auto'
37
+ Requires-Dist: opentelemetry-instrumentation-asyncpg; extra == 'auto'
38
+ Requires-Dist: opentelemetry-instrumentation-botocore; extra == 'auto'
39
+ Requires-Dist: opentelemetry-instrumentation-cassandra; extra == 'auto'
40
+ Requires-Dist: opentelemetry-instrumentation-celery; extra == 'auto'
41
+ Requires-Dist: opentelemetry-instrumentation-confluent-kafka; extra == 'auto'
42
+ Requires-Dist: opentelemetry-instrumentation-django; extra == 'auto'
43
+ Requires-Dist: opentelemetry-instrumentation-falcon; extra == 'auto'
44
+ Requires-Dist: opentelemetry-instrumentation-fastapi; extra == 'auto'
45
+ Requires-Dist: opentelemetry-instrumentation-flask; extra == 'auto'
46
+ Requires-Dist: opentelemetry-instrumentation-grpc; extra == 'auto'
47
+ Requires-Dist: opentelemetry-instrumentation-httpx; extra == 'auto'
48
+ Requires-Dist: opentelemetry-instrumentation-jinja2; extra == 'auto'
49
+ Requires-Dist: opentelemetry-instrumentation-kafka-python; extra == 'auto'
50
+ Requires-Dist: opentelemetry-instrumentation-logging; extra == 'auto'
51
+ Requires-Dist: opentelemetry-instrumentation-mysql; extra == 'auto'
52
+ Requires-Dist: opentelemetry-instrumentation-mysqlclient; extra == 'auto'
53
+ Requires-Dist: opentelemetry-instrumentation-pika; extra == 'auto'
54
+ Requires-Dist: opentelemetry-instrumentation-psycopg; extra == 'auto'
55
+ Requires-Dist: opentelemetry-instrumentation-psycopg2; extra == 'auto'
56
+ Requires-Dist: opentelemetry-instrumentation-pymemcache; extra == 'auto'
57
+ Requires-Dist: opentelemetry-instrumentation-pymongo; extra == 'auto'
58
+ Requires-Dist: opentelemetry-instrumentation-pymssql; extra == 'auto'
59
+ Requires-Dist: opentelemetry-instrumentation-pymysql; extra == 'auto'
60
+ Requires-Dist: opentelemetry-instrumentation-pyramid; extra == 'auto'
61
+ Requires-Dist: opentelemetry-instrumentation-redis; extra == 'auto'
62
+ Requires-Dist: opentelemetry-instrumentation-requests; extra == 'auto'
63
+ Requires-Dist: opentelemetry-instrumentation-sqlalchemy; extra == 'auto'
64
+ Requires-Dist: opentelemetry-instrumentation-sqlite3; extra == 'auto'
65
+ Requires-Dist: opentelemetry-instrumentation-starlette; extra == 'auto'
66
+ Requires-Dist: opentelemetry-instrumentation-system-metrics; extra == 'auto'
67
+ Requires-Dist: opentelemetry-instrumentation-threading; extra == 'auto'
68
+ Requires-Dist: opentelemetry-instrumentation-tornado; extra == 'auto'
69
+ Requires-Dist: opentelemetry-instrumentation-tortoiseorm; extra == 'auto'
70
+ Requires-Dist: opentelemetry-instrumentation-urllib; extra == 'auto'
71
+ Requires-Dist: opentelemetry-instrumentation-urllib3; extra == 'auto'
72
+ Requires-Dist: opentelemetry-instrumentation>=0.51b0; extra == 'auto'
73
+ Requires-Dist: opentelemetry-resource-detector-containerid; extra == 'auto'
74
+ Provides-Extra: autogen
75
+ Requires-Dist: autogen-agentchat>=0.7.0; extra == 'autogen'
76
+ Requires-Dist: autogen-ext[openai]>=0.7.0; extra == 'autogen'
77
+ Provides-Extra: azure
78
+ Requires-Dist: azure-core-tracing-opentelemetry>=1.0.0b11; extra == 'azure'
79
+ Provides-Extra: claude-agent-sdk
80
+ Requires-Dist: claude-agent-sdk>=0.2.121; extra == 'claude-agent-sdk'
81
+ Requires-Dist: mcp<2,>=1.30.0; extra == 'claude-agent-sdk'
82
+ Provides-Extra: demo
83
+ Requires-Dist: langchain-anthropic>=1.4.6; extra == 'demo'
84
+ Requires-Dist: langchain-core>=1.3.3; extra == 'demo'
85
+ Requires-Dist: langchain-openai>=0.2.0; extra == 'demo'
86
+ Requires-Dist: langchain>=1.3.9; extra == 'demo'
87
+ Requires-Dist: langgraph>=0.2.0; extra == 'demo'
88
+ Requires-Dist: python-dotenv>=1.0.0; extra == 'demo'
89
+ Provides-Extra: dev
90
+ Requires-Dist: pytest-asyncio>=1.3.0; extra == 'dev'
91
+ Requires-Dist: pytest>=9.0.3; extra == 'dev'
92
+ Requires-Dist: ruff>=0.5; extra == 'dev'
93
+ Requires-Dist: ty==0.0.100; extra == 'dev'
94
+ Provides-Extra: exceptions
95
+ Requires-Dist: opentelemetry-instrumentation-exceptions; extra == 'exceptions'
96
+ Provides-Extra: google-genai
97
+ Requires-Dist: google-genai>=1.12.1; extra == 'google-genai'
98
+ Provides-Extra: langchain
99
+ Requires-Dist: langchain-core>=1.3.3; extra == 'langchain'
100
+ Provides-Extra: litellm
101
+ Requires-Dist: litellm[mcp]>=1.70.0; extra == 'litellm'
102
+ Provides-Extra: llamaindex
103
+ Requires-Dist: llama-index-core>=0.13.0; extra == 'llamaindex'
104
+ Provides-Extra: mcp
105
+ Requires-Dist: mcp>=1.28.1; extra == 'mcp'
106
+ Provides-Extra: openai
107
+ Requires-Dist: openai>=1.66.0; extra == 'openai'
108
+ Provides-Extra: openai-agents
109
+ Requires-Dist: openai-agents>=0.20.0; extra == 'openai-agents'
110
+ Provides-Extra: pydantic-ai
111
+ Requires-Dist: pydantic-ai-slim>=2.53.0; extra == 'pydantic-ai'
112
+ Provides-Extra: structlog
113
+ Requires-Dist: opentelemetry-instrumentation-structlog; extra == 'structlog'
114
+ Provides-Extra: temporal
115
+ Requires-Dist: temporalio>=1.11.0; extra == 'temporal'
116
+ Description-Content-Type: text/markdown
117
+
118
+ # Struct Python SDK
119
+
120
+ Collect logs, metrics, and traces from Python services with OpenTelemetry. Once
121
+ the SDK is running, use Struct Observations to add telemetry without editing
122
+ application code or redeploying.
123
+
124
+ ## Set up a service
125
+
126
+ ```bash
127
+ pip install "struct-sdk[auto]"
128
+ ```
129
+
130
+ Create an ingest key and store it as `STRUCT_INGEST_KEY` in your service's
131
+ environment. Initialize the SDK once at process startup, before importing
132
+ instrumented libraries.
133
+
134
+ ```python
135
+ import os
136
+ from struct_sdk import struct
137
+
138
+ struct.init(
139
+ ingest_key=os.environ["STRUCT_INGEST_KEY"],
140
+ service_name="checkout-api",
141
+ environment="production",
142
+ )
143
+ ```
144
+
145
+ The SDK supports Python 3.10 and later. [Python setup guide](https://docs.struct.ai/observability/instrumentation/python)
146
+
147
+ ## Supported libraries
148
+
149
+ The `auto` extra provides OpenTelemetry instrumentation for installed libraries.
150
+
151
+ | Area | Libraries |
152
+ | --- | --- |
153
+ | Web frameworks | Django, Falcon, FastAPI, Flask, Pyramid, Starlette, Tornado, aiohttp |
154
+ | HTTP and RPC | Requests, HTTPX, aiohttp, urllib, urllib3, gRPC |
155
+ | Databases and caches | psycopg, psycopg2, aiopg, asyncpg, MySQL Connector/Python, PyMySQL, mysqlclient, pymssql, sqlite3, PyMongo, Cassandra, Redis, pymemcache, Tortoise ORM |
156
+ | Messaging and jobs | Celery, pika, aio-pika, aiokafka, confluent-kafka, kafka-python |
157
+ | Cloud and runtime | Boto3/botocore, aiobotocore, Python logging and threading, Jinja2 |
158
+
159
+ SQLAlchemy tracing is opt-in. Additional integrations include structlog, the
160
+ Azure SDK, Google Cloud gRPC clients, and Temporal.
161
+
162
+ Supported AI integrations include Anthropic, OpenAI, Google GenAI, LiteLLM,
163
+ Pydantic AI, LangChain, LangGraph, LlamaIndex, CrewAI, AutoGen, AG2, MCP clients,
164
+ the OpenAI Agents SDK, and the Claude Agent SDK.
165
+
166
+ ## Add telemetry to a running service
167
+
168
+ Publish an Observation through the Struct CLI or ask your coding agent to set
169
+ 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)
@@ -0,0 +1,54 @@
1
+ # Struct Python SDK
2
+
3
+ Collect logs, metrics, and traces from Python services with OpenTelemetry. Once
4
+ the SDK is running, use Struct Observations to add telemetry without editing
5
+ application code or redeploying.
6
+
7
+ ## Set up a service
8
+
9
+ ```bash
10
+ pip install "struct-sdk[auto]"
11
+ ```
12
+
13
+ Create an ingest key and store it as `STRUCT_INGEST_KEY` in your service's
14
+ environment. Initialize the SDK once at process startup, before importing
15
+ instrumented libraries.
16
+
17
+ ```python
18
+ import os
19
+ from struct_sdk import struct
20
+
21
+ struct.init(
22
+ ingest_key=os.environ["STRUCT_INGEST_KEY"],
23
+ service_name="checkout-api",
24
+ environment="production",
25
+ )
26
+ ```
27
+
28
+ The SDK supports Python 3.10 and later. [Python setup guide](https://docs.struct.ai/observability/instrumentation/python)
29
+
30
+ ## Supported libraries
31
+
32
+ The `auto` extra provides OpenTelemetry instrumentation for installed libraries.
33
+
34
+ | Area | Libraries |
35
+ | --- | --- |
36
+ | Web frameworks | Django, Falcon, FastAPI, Flask, Pyramid, Starlette, Tornado, aiohttp |
37
+ | HTTP and RPC | Requests, HTTPX, aiohttp, urllib, urllib3, gRPC |
38
+ | Databases and caches | psycopg, psycopg2, aiopg, asyncpg, MySQL Connector/Python, PyMySQL, mysqlclient, pymssql, sqlite3, PyMongo, Cassandra, Redis, pymemcache, Tortoise ORM |
39
+ | Messaging and jobs | Celery, pika, aio-pika, aiokafka, confluent-kafka, kafka-python |
40
+ | Cloud and runtime | Boto3/botocore, aiobotocore, Python logging and threading, Jinja2 |
41
+
42
+ SQLAlchemy tracing is opt-in. Additional integrations include structlog, the
43
+ Azure SDK, Google Cloud gRPC clients, and Temporal.
44
+
45
+ Supported AI integrations include Anthropic, OpenAI, Google GenAI, LiteLLM,
46
+ Pydantic AI, LangChain, LangGraph, LlamaIndex, CrewAI, AutoGen, AG2, MCP clients,
47
+ the OpenAI Agents SDK, and the Claude Agent SDK.
48
+
49
+ ## Add telemetry to a running service
50
+
51
+ Publish an Observation through the Struct CLI or ask your coding agent to set
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)
@@ -1,20 +1,56 @@
1
- # struct-sdk
1
+ # Struct Python SDK
2
2
 
3
- OpenTelemetry instrumentation for AI agents in Python. Captures spans,
4
- token usage, and message content from the Anthropic SDK, the OpenAI SDK
5
- (Responses API), google-genai (Gemini), LiteLLM, pydantic-ai, the OpenAI Agents SDK, MCP clients, the Claude Agent SDK,
6
- LangChain / LangGraph, LlamaIndex, CrewAI, Microsoft AutoGen, and AG2, and exports them to [struct.ai](https://struct.ai) for observability.
7
-
8
- A TypeScript version is available as
9
- [`@struct-ai/sdk`](https://www.npmjs.com/package/@struct-ai/sdk). Both
10
- SDKs produce structurally identical traces, so a single agent system can
11
- mix languages without a fragmented view.
3
+ Collect logs, metrics, and traces from your Python services. Once the SDK is
4
+ running, publish **Observations** to add telemetry without editing application
5
+ code or redeploying. For example, capture the order ID and payment provider
6
+ when checkout fails.
12
7
 
13
8
  ## Install
14
9
 
15
10
  ```bash
16
- pip install struct-sdk
17
- # optional — the SDK auto-instruments these if present
11
+ pip install "struct-sdk[auto]"
12
+ ```
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.
16
+
17
+ ## Quickstart
18
+
19
+ Create an ingest key and set it as `STRUCT_INGEST_KEY` in your service's
20
+ environment. Call `struct.init()` once at process startup, before importing
21
+ the libraries you want to instrument.
22
+
23
+ ```python
24
+ import os
25
+ from struct_sdk import struct
26
+
27
+ struct.init(
28
+ ingest_key=os.environ["STRUCT_INGEST_KEY"],
29
+ service_name="checkout-api",
30
+ environment="production",
31
+ )
32
+ ```
33
+
34
+ The setup guide covers ingest keys, automatic instrumentation, and checking
35
+ which signals reached Struct. [Python setup guide](https://docs.struct.ai/observability/instrumentation/python)
36
+
37
+ ## Add telemetry to a running service
38
+
39
+ An Observation specifies which function to watch, when to capture, and which
40
+ values to send as a structured event, span, or metric. Ask your coding agent
41
+ to publish an Observation or use the Struct CLI. After the running SDK picks
42
+ up the configuration, it captures data on subsequent calls to the function.
43
+
44
+ Use a signed ingest key with access to the service and environment to read
45
+ Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
46
+
47
+ ## AI agent tracing
48
+
49
+ The SDK also uses OpenTelemetry to trace agent runs, model calls, and tool
50
+ calls, with token usage for supported providers. Install the libraries your
51
+ application uses.
52
+
53
+ ```bash
18
54
  pip install anthropic
19
55
  pip install openai
20
56
  pip install pydantic-ai-slim
@@ -27,13 +63,8 @@ pip install langchain-core langgraph
27
63
  pip install llama-index-core llama-index-llms-openai # or the provider integration you use
28
64
  ```
29
65
 
30
- Requires Python 3.10+.
31
-
32
- ## Quickstart
33
-
34
- Get an ingest key from
35
- [app.struct.ai/settings?tab=ingest-keys](https://app.struct.ai/settings?tab=ingest-keys),
36
- then call `struct.init()` once at startup and wrap your agent loop:
66
+ Use `struct.agent()` and `struct.tool()` to define agent and tool boundaries
67
+ when using an LLM client directly.
37
68
 
38
69
  ```python
39
70
  import os
@@ -62,12 +93,15 @@ async with struct.agent(name="checkout"):
62
93
  result = await search(query="...")
63
94
  ```
64
95
 
96
+ For JavaScript and TypeScript services, see
97
+ [`@struct-ai/sdk`](https://www.npmjs.com/package/@struct-ai/sdk).
98
+
65
99
  ## What gets traced
66
100
 
67
101
  | Library | Span type | Notes |
68
102
  |---|---|---|
69
103
  | `anthropic` | `chat {model}` | Cache-token accounting; streaming chats with tool-use reconstruction. Bedrock and Vertex variants supported if installed. |
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. |
104
+ | `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). Non-streaming `chat.completions.parse()` and the older `beta.chat.completions.parse()` entry point are traced on sync and async clients, including Azure. `responses.parse()` is not traced. |
71
105
  | `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
106
  | `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
107
  | `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). |
@@ -4,9 +4,9 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "struct-sdk"
7
- version = "0.5.26"
8
- description = "Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry"
9
- readme = "README.md"
7
+ version = "0.5.27"
8
+ description = "Python SDK for OTel auto-instrumentation and live instrumentation on Struct."
9
+ readme = "PYPI.md"
10
10
  requires-python = ">=3.10"
11
11
  license = { text = "Apache-2.0" }
12
12
  authors = [{ name = "Struct", email = "support@struct.ai" }]
@@ -38,7 +38,7 @@ dependencies = [
38
38
 
39
39
  [project.urls]
40
40
  Homepage = "https://struct.ai"
41
- Documentation = "https://struct.ai/docs"
41
+ Documentation = "https://docs.struct.ai/observability/instrumentation/python"
42
42
  Issues = "https://struct.ai/support"
43
43
 
44
44
  [project.entry-points.opentelemetry_distro]
@@ -298,6 +298,7 @@ packages = ["src/struct_sdk"]
298
298
  include = [
299
299
  "src/struct_sdk/**/*.py",
300
300
  "README.md",
301
+ "PYPI.md",
301
302
  "LICENSE",
302
303
  "pyproject.toml",
303
304
  ]
@@ -57,7 +57,7 @@ from struct_sdk._genai_content import (
57
57
  from struct_sdk._operation_details import record_content
58
58
 
59
59
  if TYPE_CHECKING:
60
- from struct_sdk.core import StructSDK
60
+ from struct_sdk.core import StructSDK, _PendingToolCallQueue
61
61
 
62
62
  logger = logging.getLogger("struct_sdk.anthropic")
63
63
 
@@ -506,17 +506,6 @@ class _StreamAccumulator:
506
506
  )
507
507
 
508
508
 
509
- def _ambient_pending_tool_calls() -> dict[str, list[str]]:
510
- """The current context's tool-use queue, created (as a non-streaming call does)
511
- when no agent scope set one."""
512
- from struct_sdk.core import _pending_tool_calls
513
- pending = _pending_tool_calls.get(None)
514
- if pending is None:
515
- pending = {}
516
- _pending_tool_calls.set(pending)
517
- return pending
518
-
519
-
520
509
  class _RawStreamTelemetry:
521
510
  """Owns the ``chat`` span of one raw stream; ``end`` is idempotent and
522
511
  thread-safe (garbage collection may finalize on any thread)."""
@@ -526,6 +515,8 @@ class _RawStreamTelemetry:
526
515
  # The creating call's tool-use queue, created here when none exists (as the
527
516
  # non-streaming path does on response): child tasks that pull events, and
528
517
  # whatever context finally ends the stream, all feed THIS queue.
518
+ from struct_sdk.core import _ambient_pending_tool_calls
519
+
529
520
  pending = _ambient_pending_tool_calls()
530
521
  # The creating call's context: the stream may end (or be collected) in
531
522
  # another request's, whose session must not label this one's events.
@@ -534,7 +525,7 @@ class _RawStreamTelemetry:
534
525
  self._otel_logger, self._provider = otel_logger, provider
535
526
  self._acc: Optional[_StreamAccumulator] = _StreamAccumulator(
536
527
  keep_text=bool(sdk.emit_events or sdk.emit_span_content))
537
- self._pending_tool_calls: Optional[dict[str, list[str]]] = pending
528
+ self._pending_tool_calls: Optional[_PendingToolCallQueue] = pending
538
529
  self._lock = threading.Lock()
539
530
  # Armed only once every hook is in place: a half-installed stream leaves
540
531
  # the span to create(), and these hooks must then never end it again.
@@ -1125,30 +1116,19 @@ def _iter_tool_uses(content_blocks: Any) -> list[tuple[str, str]]:
1125
1116
  def _record_pending_tool_calls(content_blocks: Any, into: Any = _AMBIENT) -> None:
1126
1117
  """Push every tool_use (name, id) from the response into the SDK contextvar.
1127
1118
 
1128
- ``into`` selects a captured queue: the creating agent scope's dictionary or
1129
- the ambient dictionary created for a raw stream outside an agent. The default
1119
+ ``into`` selects a captured queue: the creating agent scope's queue or
1120
+ the ambient queue created for a raw stream outside an agent. The default
1130
1121
  uses the current context's queue; passing None skips recording.
1131
1122
 
1132
1123
  Always runs (not gated on content-capture mode) — the linkage between a
1133
1124
  chat span and its child execute_tool spans is structural, not content.
1134
1125
  """
1135
- from struct_sdk.core import _pending_tool_calls
1126
+ from struct_sdk.core import _ambient_pending_tool_calls
1136
1127
  pairs = _iter_tool_uses(content_blocks)
1137
1128
  if not pairs or into is None:
1138
1129
  return
1139
- if into is not _AMBIENT:
1140
- for name, tool_id in pairs:
1141
- into.setdefault(name, []).append(tool_id)
1142
- return
1143
- pending = _pending_tool_calls.get()
1144
- if pending is None:
1145
- # No active agent scope — initialise a transient dict in the current
1146
- # context so a @struct.tool() call outside of @struct.agent() still
1147
- # gets the linkage. (Will not be reset automatically; that's fine.)
1148
- pending = {}
1149
- _pending_tool_calls.set(pending)
1150
- for name, tool_id in pairs:
1151
- pending.setdefault(name, []).append(tool_id)
1130
+ pending = _ambient_pending_tool_calls() if into is _AMBIENT else into
1131
+ pending.enqueue(pairs)
1152
1132
 
1153
1133
 
1154
1134
  def _native_usage(response: Any) -> dict[str, int]:
@@ -194,7 +194,67 @@ def _active_metadata() -> Mapping[str, AttributeValue]:
194
194
  # execute_tool spans to the originating tool_use.id without forcing callers
195
195
  # to pass tool_call_id= explicitly. Customers who already pass it keep
196
196
  # working unchanged (explicit override wins).
197
- _pending_tool_calls: contextvars.ContextVar[Optional[dict[str, list[str]]]] = contextvars.ContextVar("_pending_tool_calls", default=None)
197
+ class _PendingToolCallQueue(dict[str, list[str]]):
198
+ """FIFO state shared by copied contexts; mutate only via enqueue/consume.
199
+
200
+ The lock belongs to the queue, not the context or provider. It covers only
201
+ local bookkeeping, never provider I/O or telemetry export.
202
+ Inherited queues are unavailable in a forked child: their lock may belong
203
+ to a vanished thread, and their IDs belong to the parent's in-flight work.
204
+ """
205
+
206
+ def __init__(self) -> None:
207
+ super().__init__()
208
+ self._pid = os.getpid()
209
+ self._lock = threading.Lock()
210
+ self.overflowed = False
211
+
212
+ def enqueue(self, pairs: list[tuple[str, str]], *, limit: Optional[int] = None) -> None:
213
+ if os.getpid() != self._pid:
214
+ return
215
+ with self._lock:
216
+ if self.overflowed:
217
+ return
218
+ if limit is not None and sum(map(len, self.values())) + len(pairs) > limit:
219
+ # Once positions are ambiguous, every provider must leave this
220
+ # shared scope disabled so a later tool cannot get a shifted ID.
221
+ self.overflowed = True
222
+ self.clear()
223
+ return
224
+ for name, call_id in pairs:
225
+ self.setdefault(name, []).append(call_id)
226
+
227
+ def consume(self, name: str, call_id: Optional[str] = None) -> Optional[str]:
228
+ if os.getpid() != self._pid:
229
+ return None
230
+ with self._lock:
231
+ ids = self.get(name)
232
+ if not ids:
233
+ return None
234
+ if call_id is None:
235
+ call_id = ids.pop(0)
236
+ elif call_id in ids:
237
+ ids.remove(call_id)
238
+ else:
239
+ return None
240
+ # Remove the entry with its last ID. No producer can prune a stale
241
+ # snapshot after another thread has repopulated the name.
242
+ if not ids:
243
+ del self[name]
244
+ return call_id
245
+
246
+
247
+ _pending_tool_calls: contextvars.ContextVar[Optional[_PendingToolCallQueue]] = (
248
+ contextvars.ContextVar("_pending_tool_calls", default=None)
249
+ )
250
+
251
+
252
+ def _ambient_pending_tool_calls() -> _PendingToolCallQueue:
253
+ pending = _pending_tool_calls.get()
254
+ if pending is None:
255
+ pending = _PendingToolCallQueue()
256
+ _pending_tool_calls.set(pending)
257
+ return pending
198
258
 
199
259
  # ---------------------------------------------------------------------------
200
260
  # OTel GenAI suppression key
@@ -2072,7 +2132,7 @@ class _AgentContext:
2072
2132
  self._session_token: Optional[contextvars.Token[Optional[str]]] = None
2073
2133
  self._conversation_token: Optional[contextvars.Token[Optional[str]]] = None
2074
2134
  self._agent_span_token: Optional[contextvars.Token[Optional[trace.Span]]] = None
2075
- self._pending_tool_token: Optional[contextvars.Token[Optional[dict[str, list[str]]]]] = None
2135
+ self._pending_tool_token: Optional[contextvars.Token[Optional[_PendingToolCallQueue]]] = None
2076
2136
  self._manual_token: Optional[contextvars.Token[Optional[trace.Span]]] = None
2077
2137
  self._metadata_token: Optional[contextvars.Token[Optional[_MetadataFrame]]] = None
2078
2138
  self._metadata_frame: Optional[_MetadataFrame] = None
@@ -2251,7 +2311,7 @@ class _AgentContext:
2251
2311
  self._agent_span_token = _current_agent_span.set(self._span)
2252
2312
  # Fresh pending-tool-calls dict scoped to this agent run, so tool_use
2253
2313
  # ids from an outer agent cannot leak in or out.
2254
- self._pending_tool_token = _pending_tool_calls.set({})
2314
+ self._pending_tool_token = _pending_tool_calls.set(_PendingToolCallQueue())
2255
2315
  # Signal to the LangChain handler that a manual struct.agent() owns
2256
2316
  # this scope. The handler will suppress its own invoke_agent span for
2257
2317
  # the same top-level chain (parent_run_id is None) and parent its
@@ -2533,10 +2593,8 @@ class _ToolContext:
2533
2593
  # the caller left it unset.
2534
2594
  if self._tool_call_id is None:
2535
2595
  pending = _pending_tool_calls.get()
2536
- if pending:
2537
- ids = pending.get(tool_name)
2538
- if ids:
2539
- self._tool_call_id = ids.pop(0)
2596
+ if pending is not None:
2597
+ self._tool_call_id = pending.consume(tool_name)
2540
2598
  if self._tool_call_id:
2541
2599
  self._span.set_attribute("gen_ai.tool.call.id", self._tool_call_id)
2542
2600
  # Propagate session context
@@ -427,7 +427,7 @@ def _queue_tool_calls(candidate: Any) -> None:
427
427
  """Queue function-call ids for ``struct.tool()`` (SDK-PY-14). The Gemini API
428
428
  often omits them; only calls that carry one are queued. Reads the raw parts,
429
429
  so it costs no content mapping when content is not captured."""
430
- from struct_sdk.core import _pending_tool_calls
430
+ from struct_sdk.core import _ambient_pending_tool_calls
431
431
 
432
432
  calls: list[tuple[str, str]] = []
433
433
  for part in _get(_get(candidate, "content"), "parts") or []:
@@ -439,12 +439,7 @@ def _queue_tool_calls(candidate: Any) -> None:
439
439
  calls.append((name, call_id))
440
440
  if not calls:
441
441
  return
442
- pending = _pending_tool_calls.get()
443
- if pending is None:
444
- pending = {}
445
- _pending_tool_calls.set(pending)
446
- for name, call_id in calls:
447
- pending.setdefault(name, []).append(call_id)
442
+ _ambient_pending_tool_calls().enqueue(calls)
448
443
 
449
444
 
450
445
  # ---------------------------------------------------------------------------
@@ -1842,24 +1842,14 @@ def _extract_tool_call_id_from_inputs(inputs: Optional[dict[str, Any]]) -> Optio
1842
1842
 
1843
1843
 
1844
1844
  def _push_pending_tool_calls(pairs: list[tuple[str, str]]) -> None:
1845
- from struct_sdk.core import _pending_tool_calls
1846
- pending = _pending_tool_calls.get()
1847
- if pending is None:
1848
- pending = {}
1849
- _pending_tool_calls.set(pending)
1850
- for name, call_id in pairs:
1851
- pending.setdefault(name, []).append(call_id)
1845
+ from struct_sdk.core import _ambient_pending_tool_calls
1846
+ _ambient_pending_tool_calls().enqueue(pairs)
1852
1847
 
1853
1848
 
1854
1849
  def _pop_pending_tool_call_id(name: str) -> Optional[str]:
1855
1850
  from struct_sdk.core import _pending_tool_calls
1856
1851
  pending = _pending_tool_calls.get(None)
1857
- if not pending:
1858
- return None
1859
- ids = pending.get(name)
1860
- if not ids:
1861
- return None
1862
- return ids.pop(0)
1852
+ return pending.consume(name) if pending is not None else None
1863
1853
 
1864
1854
 
1865
1855
  def _propagate_user_prompt(agent_span: trace.Span, messages: list[Any]) -> None:
@@ -466,16 +466,11 @@ def _tool_call_ids(message: Any) -> list[tuple[str, str]]:
466
466
 
467
467
  def _queue_tool_calls(calls: list[tuple[str, str]]) -> None:
468
468
  """Queue tool-call ids for ``struct.tool()`` (SDK-PY-14)."""
469
- from struct_sdk.core import _pending_tool_calls
469
+ from struct_sdk.core import _ambient_pending_tool_calls
470
470
 
471
471
  if not calls:
472
472
  return
473
- pending = _pending_tool_calls.get()
474
- if pending is None:
475
- pending = {}
476
- _pending_tool_calls.set(pending)
477
- for name, call_id in calls:
478
- pending.setdefault(name, []).append(call_id)
473
+ _ambient_pending_tool_calls().enqueue(calls)
479
474
 
480
475
 
481
476
  def _tool_definitions(tools: Any, functions: Any) -> list[dict[str, Any]]:
@@ -1233,14 +1233,13 @@ def _consume_tool_call(name: str, call_id: str) -> None:
1233
1233
  from struct_sdk.core import _pending_tool_calls
1234
1234
 
1235
1235
  pending = _pending_tool_calls.get()
1236
- ids = pending.get(name) if pending else None
1237
- if ids and call_id in ids:
1238
- ids.remove(call_id)
1236
+ if pending is not None:
1237
+ pending.consume(name, call_id)
1239
1238
 
1240
1239
 
1241
1240
  def _queue_tool_calls(parts: list[dict[str, Any]]) -> None:
1242
1241
  """Queue tool-call ids for ``struct.tool()`` (SDK-PY-14)."""
1243
- from struct_sdk.core import _pending_tool_calls
1242
+ from struct_sdk.core import _ambient_pending_tool_calls
1244
1243
 
1245
1244
  calls = [
1246
1245
  (p["name"], p["id"])
@@ -1249,12 +1248,7 @@ def _queue_tool_calls(parts: list[dict[str, Any]]) -> None:
1249
1248
  ]
1250
1249
  if not calls:
1251
1250
  return
1252
- pending = _pending_tool_calls.get()
1253
- if pending is None:
1254
- pending = {}
1255
- _pending_tool_calls.set(pending)
1256
- for name, call_id in calls:
1257
- pending.setdefault(name, []).append(call_id)
1251
+ _ambient_pending_tool_calls().enqueue(calls)
1258
1252
 
1259
1253
 
1260
1254
  # ---------------------------------------------------------------------------
@@ -324,9 +324,9 @@ def _set_request_attrs(
324
324
  if name:
325
325
  span.set_attribute("gen_ai.tool.name", name)
326
326
  pending = _pending_tool_calls.get()
327
- queued = pending.get(name) if pending else None
328
- if queued:
329
- span.set_attribute("gen_ai.tool.call.id", queued.pop(0))
327
+ call_id = pending.consume(name) if pending is not None else None
328
+ if call_id:
329
+ span.set_attribute("gen_ai.tool.call.id", call_id)
330
330
  session_id = _current_session_id.get(None)
331
331
  if session_id:
332
332
  span.set_attribute("gen_ai.conversation.id", session_id)