struct-sdk 0.5.26__tar.gz → 0.5.28__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- struct_sdk-0.5.28/PKG-INFO +175 -0
- struct_sdk-0.5.28/PYPI.md +55 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/README.md +54 -20
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/pyproject.toml +14 -9
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/anthropic.py +45 -33
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/autogen.py +45 -12
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/core.py +175 -40
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/google_genai.py +2 -7
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/langchain.py +3 -13
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/litellm.py +3 -8
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/llamaindex.py +4 -10
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/mcp.py +3 -3
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/openai.py +144 -55
- struct_sdk-0.5.26/PKG-INFO +0 -1070
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/.gitignore +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/LICENSE +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/__init__.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_auto.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_container.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_distro.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_event_loop.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_fork_safe_http.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_genai_content.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_metrics.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/__init__.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/config.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/health.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/identity.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/native_events.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/outputs.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/poller.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/routing.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/runtime.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/self_metrics.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_observations/uwsgi.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_operation_details.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/_pool.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/ag2.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/claude_agent.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/crewai.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/gcp.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/openai_agents.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/pydantic_ai.py +0 -0
- {struct_sdk-0.5.26 → struct_sdk-0.5.28}/src/struct_sdk/temporal.py +0 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: struct-sdk
|
|
3
|
+
Version: 0.5.28
|
|
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: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Topic :: System :: Monitoring
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Requires-Dist: opentelemetry-api>=1.45.1
|
|
26
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0
|
|
27
|
+
Requires-Dist: opentelemetry-sdk>=1.27.0
|
|
28
|
+
Requires-Dist: struct-sdk-native==0.2.1
|
|
29
|
+
Requires-Dist: wrapt>=1.17.3
|
|
30
|
+
Provides-Extra: anthropic
|
|
31
|
+
Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
|
|
32
|
+
Provides-Extra: auto
|
|
33
|
+
Requires-Dist: opentelemetry-instrumentation-aio-pika; extra == 'auto'
|
|
34
|
+
Requires-Dist: opentelemetry-instrumentation-aiohttp-client; extra == 'auto'
|
|
35
|
+
Requires-Dist: opentelemetry-instrumentation-aiohttp-server; extra == 'auto'
|
|
36
|
+
Requires-Dist: opentelemetry-instrumentation-aiokafka; extra == 'auto'
|
|
37
|
+
Requires-Dist: opentelemetry-instrumentation-aiopg; extra == 'auto'
|
|
38
|
+
Requires-Dist: opentelemetry-instrumentation-asyncpg; extra == 'auto'
|
|
39
|
+
Requires-Dist: opentelemetry-instrumentation-botocore; extra == 'auto'
|
|
40
|
+
Requires-Dist: opentelemetry-instrumentation-cassandra; extra == 'auto'
|
|
41
|
+
Requires-Dist: opentelemetry-instrumentation-celery; extra == 'auto'
|
|
42
|
+
Requires-Dist: opentelemetry-instrumentation-confluent-kafka; extra == 'auto'
|
|
43
|
+
Requires-Dist: opentelemetry-instrumentation-django; extra == 'auto'
|
|
44
|
+
Requires-Dist: opentelemetry-instrumentation-falcon; extra == 'auto'
|
|
45
|
+
Requires-Dist: opentelemetry-instrumentation-fastapi; extra == 'auto'
|
|
46
|
+
Requires-Dist: opentelemetry-instrumentation-flask; extra == 'auto'
|
|
47
|
+
Requires-Dist: opentelemetry-instrumentation-grpc; extra == 'auto'
|
|
48
|
+
Requires-Dist: opentelemetry-instrumentation-httpx; extra == 'auto'
|
|
49
|
+
Requires-Dist: opentelemetry-instrumentation-jinja2; extra == 'auto'
|
|
50
|
+
Requires-Dist: opentelemetry-instrumentation-kafka-python; extra == 'auto'
|
|
51
|
+
Requires-Dist: opentelemetry-instrumentation-logging; extra == 'auto'
|
|
52
|
+
Requires-Dist: opentelemetry-instrumentation-mysql; extra == 'auto'
|
|
53
|
+
Requires-Dist: opentelemetry-instrumentation-mysqlclient; extra == 'auto'
|
|
54
|
+
Requires-Dist: opentelemetry-instrumentation-pika; extra == 'auto'
|
|
55
|
+
Requires-Dist: opentelemetry-instrumentation-psycopg; extra == 'auto'
|
|
56
|
+
Requires-Dist: opentelemetry-instrumentation-psycopg2; extra == 'auto'
|
|
57
|
+
Requires-Dist: opentelemetry-instrumentation-pymemcache; extra == 'auto'
|
|
58
|
+
Requires-Dist: opentelemetry-instrumentation-pymongo; extra == 'auto'
|
|
59
|
+
Requires-Dist: opentelemetry-instrumentation-pymssql; extra == 'auto'
|
|
60
|
+
Requires-Dist: opentelemetry-instrumentation-pymysql; extra == 'auto'
|
|
61
|
+
Requires-Dist: opentelemetry-instrumentation-pyramid; extra == 'auto'
|
|
62
|
+
Requires-Dist: opentelemetry-instrumentation-redis; extra == 'auto'
|
|
63
|
+
Requires-Dist: opentelemetry-instrumentation-requests; extra == 'auto'
|
|
64
|
+
Requires-Dist: opentelemetry-instrumentation-sqlalchemy; extra == 'auto'
|
|
65
|
+
Requires-Dist: opentelemetry-instrumentation-sqlite3; extra == 'auto'
|
|
66
|
+
Requires-Dist: opentelemetry-instrumentation-starlette; extra == 'auto'
|
|
67
|
+
Requires-Dist: opentelemetry-instrumentation-system-metrics; extra == 'auto'
|
|
68
|
+
Requires-Dist: opentelemetry-instrumentation-threading; extra == 'auto'
|
|
69
|
+
Requires-Dist: opentelemetry-instrumentation-tornado; extra == 'auto'
|
|
70
|
+
Requires-Dist: opentelemetry-instrumentation-tortoiseorm; extra == 'auto'
|
|
71
|
+
Requires-Dist: opentelemetry-instrumentation-urllib; extra == 'auto'
|
|
72
|
+
Requires-Dist: opentelemetry-instrumentation-urllib3; extra == 'auto'
|
|
73
|
+
Requires-Dist: opentelemetry-instrumentation>=0.51b0; extra == 'auto'
|
|
74
|
+
Requires-Dist: opentelemetry-resource-detector-containerid; extra == 'auto'
|
|
75
|
+
Provides-Extra: autogen
|
|
76
|
+
Requires-Dist: autogen-agentchat>=0.7.0; extra == 'autogen'
|
|
77
|
+
Requires-Dist: autogen-ext[openai]>=0.7.0; extra == 'autogen'
|
|
78
|
+
Provides-Extra: azure
|
|
79
|
+
Requires-Dist: azure-core-tracing-opentelemetry>=1.0.0b11; extra == 'azure'
|
|
80
|
+
Provides-Extra: claude-agent-sdk
|
|
81
|
+
Requires-Dist: claude-agent-sdk>=0.2.121; extra == 'claude-agent-sdk'
|
|
82
|
+
Requires-Dist: mcp<2,>=1.30.0; extra == 'claude-agent-sdk'
|
|
83
|
+
Provides-Extra: demo
|
|
84
|
+
Requires-Dist: langchain-anthropic>=1.4.6; extra == 'demo'
|
|
85
|
+
Requires-Dist: langchain-core>=1.3.3; extra == 'demo'
|
|
86
|
+
Requires-Dist: langchain-openai>=0.2.0; extra == 'demo'
|
|
87
|
+
Requires-Dist: langchain>=1.3.9; extra == 'demo'
|
|
88
|
+
Requires-Dist: langgraph>=0.2.0; extra == 'demo'
|
|
89
|
+
Requires-Dist: python-dotenv>=1.0.0; extra == 'demo'
|
|
90
|
+
Provides-Extra: dev
|
|
91
|
+
Requires-Dist: pytest-asyncio>=1.3.0; extra == 'dev'
|
|
92
|
+
Requires-Dist: pytest>=9.0.3; extra == 'dev'
|
|
93
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
94
|
+
Requires-Dist: ty==0.0.100; extra == 'dev'
|
|
95
|
+
Provides-Extra: exceptions
|
|
96
|
+
Requires-Dist: opentelemetry-instrumentation-exceptions; extra == 'exceptions'
|
|
97
|
+
Provides-Extra: google-genai
|
|
98
|
+
Requires-Dist: google-genai>=1.12.1; extra == 'google-genai'
|
|
99
|
+
Provides-Extra: langchain
|
|
100
|
+
Requires-Dist: langchain-core>=1.3.3; extra == 'langchain'
|
|
101
|
+
Provides-Extra: litellm
|
|
102
|
+
Requires-Dist: litellm[mcp]>=1.70.0; extra == 'litellm'
|
|
103
|
+
Requires-Dist: litellm[mcp]>=1.93.0; (python_version >= '3.14') and extra == 'litellm'
|
|
104
|
+
Provides-Extra: llamaindex
|
|
105
|
+
Requires-Dist: llama-index-core>=0.13.0; extra == 'llamaindex'
|
|
106
|
+
Provides-Extra: mcp
|
|
107
|
+
Requires-Dist: mcp>=1.28.1; extra == 'mcp'
|
|
108
|
+
Provides-Extra: openai
|
|
109
|
+
Requires-Dist: openai>=1.66.0; extra == 'openai'
|
|
110
|
+
Provides-Extra: openai-agents
|
|
111
|
+
Requires-Dist: openai-agents>=0.20.0; extra == 'openai-agents'
|
|
112
|
+
Provides-Extra: pydantic-ai
|
|
113
|
+
Requires-Dist: pydantic-ai-slim>=2.53.0; extra == 'pydantic-ai'
|
|
114
|
+
Provides-Extra: structlog
|
|
115
|
+
Requires-Dist: opentelemetry-instrumentation-structlog; extra == 'structlog'
|
|
116
|
+
Provides-Extra: temporal
|
|
117
|
+
Requires-Dist: temporalio>=1.11.0; extra == 'temporal'
|
|
118
|
+
Requires-Dist: temporalio>=1.19.0; (python_version >= '3.14') and extra == 'temporal'
|
|
119
|
+
Description-Content-Type: text/markdown
|
|
120
|
+
|
|
121
|
+
# Struct Python SDK
|
|
122
|
+
|
|
123
|
+
Collect logs, metrics, and traces from Python services with OpenTelemetry. Once
|
|
124
|
+
the SDK is running, use Struct Observations to add telemetry without editing
|
|
125
|
+
application code or redeploying.
|
|
126
|
+
|
|
127
|
+
## Set up a service
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
pip install "struct-sdk[auto]"
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Create an ingest key and store it as `STRUCT_INGEST_KEY` in your service's
|
|
134
|
+
environment. Initialize the SDK once at process startup, before importing
|
|
135
|
+
instrumented libraries.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
import os
|
|
139
|
+
from struct_sdk import struct
|
|
140
|
+
|
|
141
|
+
struct.init(
|
|
142
|
+
ingest_key=os.environ["STRUCT_INGEST_KEY"],
|
|
143
|
+
service_name="checkout-api",
|
|
144
|
+
environment="production",
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The SDK supports Python 3.10 and later. [Python setup guide](https://docs.struct.ai/observability/instrumentation/python)
|
|
149
|
+
|
|
150
|
+
## Supported libraries
|
|
151
|
+
|
|
152
|
+
The `auto` extra provides OpenTelemetry instrumentation for installed libraries.
|
|
153
|
+
|
|
154
|
+
| Area | Libraries |
|
|
155
|
+
| --- | --- |
|
|
156
|
+
| Web frameworks | Django, Falcon, FastAPI, Flask, Pyramid, Starlette, Tornado, aiohttp |
|
|
157
|
+
| HTTP and RPC | Requests, HTTPX, aiohttp, urllib, urllib3, gRPC |
|
|
158
|
+
| Databases and caches | psycopg, psycopg2, aiopg, asyncpg, MySQL Connector/Python, PyMySQL, mysqlclient, pymssql, sqlite3, PyMongo, Cassandra, Redis, pymemcache, Tortoise ORM |
|
|
159
|
+
| Messaging and jobs | Celery, pika, aio-pika, aiokafka, confluent-kafka, kafka-python |
|
|
160
|
+
| Cloud and runtime | Boto3/botocore, aiobotocore, Python logging and threading, Jinja2 |
|
|
161
|
+
|
|
162
|
+
SQLAlchemy tracing is opt-in. Additional integrations include structlog, the
|
|
163
|
+
Azure SDK, Google Cloud gRPC clients, and Temporal.
|
|
164
|
+
|
|
165
|
+
Supported AI integrations include Anthropic, OpenAI, Google GenAI, LiteLLM,
|
|
166
|
+
Pydantic AI, LangChain, LangGraph, LlamaIndex, CrewAI, AutoGen, AG2, MCP clients,
|
|
167
|
+
the OpenAI Agents SDK, and the Claude Agent SDK.
|
|
168
|
+
|
|
169
|
+
## Add telemetry to a running service
|
|
170
|
+
|
|
171
|
+
Publish an Observation through the Struct CLI or ask your coding agent to set
|
|
172
|
+
one up. An Observation tells the running SDK where to capture events, spans,
|
|
173
|
+
or metrics. Live capture requires a supported native runtime on CPython 3.12,
|
|
174
|
+
3.13, or 3.14 (3.14.5 or later; free-threaded builds aren't supported) and a key
|
|
175
|
+
with access to Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
|
|
@@ -0,0 +1,55 @@
|
|
|
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
|
+
3.13, or 3.14 (3.14.5 or later; free-threaded builds aren't supported) and a key
|
|
55
|
+
with access to Observation configuration. [Observations guide](https://docs.struct.ai/observability/observations/overview)
|
|
@@ -1,20 +1,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Struct Python SDK
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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
|
-
|
|
11
|
+
pip install "struct-sdk[auto]"
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The SDK requires Python 3.10 or later. Observations require the native runtime on
|
|
15
|
+
CPython 3.12, 3.13, or 3.14 (3.14.5 or later); free-threaded builds aren't supported.
|
|
16
|
+
|
|
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
|
-
|
|
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 `
|
|
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.
|
|
8
|
-
description = "
|
|
9
|
-
readme = "
|
|
7
|
+
version = "0.5.28"
|
|
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" }]
|
|
@@ -21,6 +21,7 @@ classifiers = [
|
|
|
21
21
|
"Programming Language :: Python :: 3.11",
|
|
22
22
|
"Programming Language :: Python :: 3.12",
|
|
23
23
|
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Programming Language :: Python :: 3.14",
|
|
24
25
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
26
|
"Topic :: System :: Monitoring",
|
|
26
27
|
]
|
|
@@ -30,15 +31,16 @@ dependencies = [
|
|
|
30
31
|
"opentelemetry-exporter-otlp-proto-http>=1.27.0",
|
|
31
32
|
# Stream proxies (struct_sdk.openai): isinstance-transparent, as in
|
|
32
33
|
# OpenLLMetry and ddtrace. Already required by every OTel instrumentor.
|
|
33
|
-
|
|
34
|
+
# 1.17.3 is the first release with CPython 3.14 wheels.
|
|
35
|
+
"wrapt>=1.17.3",
|
|
34
36
|
# Native capture runtime. Always installs: platforms without a native build
|
|
35
37
|
# get its pure py3-none-any wheel, which reports the capability unavailable.
|
|
36
|
-
"struct-sdk-native==0.2.
|
|
38
|
+
"struct-sdk-native==0.2.1",
|
|
37
39
|
]
|
|
38
40
|
|
|
39
41
|
[project.urls]
|
|
40
42
|
Homepage = "https://struct.ai"
|
|
41
|
-
Documentation = "https://struct.ai/
|
|
43
|
+
Documentation = "https://docs.struct.ai/observability/instrumentation/python"
|
|
42
44
|
Issues = "https://struct.ai/support"
|
|
43
45
|
|
|
44
46
|
[project.entry-points.opentelemetry_distro]
|
|
@@ -70,7 +72,8 @@ google-genai = ["google-genai>=1.12.1"]
|
|
|
70
72
|
# suite runs against. Recent LiteLLM releases import their MCP client (mcp 2.x)
|
|
71
73
|
# whenever a completion passes ``tools``, and fail without it; LiteLLM's own
|
|
72
74
|
# ``mcp`` extra installs it (releases without that extra ignore it).
|
|
73
|
-
|
|
75
|
+
# LiteLLM releases before 1.93.0 refuse Python 3.14.
|
|
76
|
+
litellm = ["litellm[mcp]>=1.70.0", "litellm[mcp]>=1.93.0; python_version >= '3.14'"]
|
|
74
77
|
# LlamaIndex's instrumentation dispatcher and agent workflows; 0.13.0 is the
|
|
75
78
|
# first release whose workflow agents run their own steps.
|
|
76
79
|
llamaindex = ["llama-index-core>=0.13.0"]
|
|
@@ -135,7 +138,8 @@ structlog = ["opentelemetry-instrumentation-structlog"]
|
|
|
135
138
|
exceptions = ["opentelemetry-instrumentation-exceptions"]
|
|
136
139
|
azure = ["azure-core-tracing-opentelemetry>=1.0.0b11"]
|
|
137
140
|
# TracingInterceptor(always_create_workflow_spans=...) exists from 1.11.0 onward.
|
|
138
|
-
|
|
141
|
+
# CPython 3.14 needs 1.19.0 or later.
|
|
142
|
+
temporal = ["temporalio>=1.11.0", "temporalio>=1.19.0; python_version >= '3.14'"]
|
|
139
143
|
demo = [
|
|
140
144
|
"langchain>=1.3.9",
|
|
141
145
|
"langchain-core>=1.3.3",
|
|
@@ -264,7 +268,7 @@ conflicts = [
|
|
|
264
268
|
[{ group = "dev" }, { extra = "litellm" }],
|
|
265
269
|
]
|
|
266
270
|
# Lock development environments on Python 3.11+ only; CI runs every suite on
|
|
267
|
-
# 3.12. Published metadata still allows 3.10. Pillow 13, the first release
|
|
271
|
+
# 3.12 and 3.14. Published metadata still allows 3.10. Pillow 13, the first release
|
|
268
272
|
# with the fixes for its 2026 CVEs, needs 3.11, so a 3.10 lock entry
|
|
269
273
|
# could only hold vulnerable Pillow 12.
|
|
270
274
|
environments = ["python_full_version >= '3.11'"]
|
|
@@ -298,6 +302,7 @@ packages = ["src/struct_sdk"]
|
|
|
298
302
|
include = [
|
|
299
303
|
"src/struct_sdk/**/*.py",
|
|
300
304
|
"README.md",
|
|
305
|
+
"PYPI.md",
|
|
301
306
|
"LICENSE",
|
|
302
307
|
"pyproject.toml",
|
|
303
308
|
]
|
|
@@ -26,6 +26,7 @@ import functools
|
|
|
26
26
|
import inspect
|
|
27
27
|
import json
|
|
28
28
|
import logging
|
|
29
|
+
import re
|
|
29
30
|
import threading
|
|
30
31
|
from types import SimpleNamespace
|
|
31
32
|
from typing import TYPE_CHECKING, Any, Callable, Generator, Optional, cast
|
|
@@ -57,7 +58,7 @@ from struct_sdk._genai_content import (
|
|
|
57
58
|
from struct_sdk._operation_details import record_content
|
|
58
59
|
|
|
59
60
|
if TYPE_CHECKING:
|
|
60
|
-
from struct_sdk.core import StructSDK
|
|
61
|
+
from struct_sdk.core import StructSDK, _PendingToolCallQueue
|
|
61
62
|
|
|
62
63
|
logger = logging.getLogger("struct_sdk.anthropic")
|
|
63
64
|
|
|
@@ -407,6 +408,40 @@ def _attached_telemetry(stream: Any) -> Any:
|
|
|
407
408
|
_TEXT_BUDGET = _MAX_FIELD_SIZE + 1
|
|
408
409
|
"""Characters of text or reasoning one content block retains: one over the
|
|
409
410
|
exported field cap, so truncation (and its marker) still applies downstream."""
|
|
411
|
+
_MAX_TOOL_INPUT_DEPTH = 10_000
|
|
412
|
+
_JSON_STRUCTURE = re.compile(r'[\\"\[\]{}]')
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _parse_tool_input(raw: str) -> Any:
|
|
416
|
+
"""Tool arguments as JSON, or the raw text when malformed or nested deeper than
|
|
417
|
+
``_MAX_TOOL_INPUT_DEPTH``, where json stops on CPython 3.12 and 3.13: from 3.14
|
|
418
|
+
json's nesting is bounded only by the C stack. The depth check is one pass over
|
|
419
|
+
the structural characters; brackets inside strings do not count."""
|
|
420
|
+
if not raw:
|
|
421
|
+
return {}
|
|
422
|
+
if raw.count("[") + raw.count("{") > _MAX_TOOL_INPUT_DEPTH:
|
|
423
|
+
depth, in_string, escaped_at = 0, False, -1
|
|
424
|
+
for match in _JSON_STRUCTURE.finditer(raw):
|
|
425
|
+
char, at = match.group(), match.start()
|
|
426
|
+
if in_string:
|
|
427
|
+
if at == escaped_at:
|
|
428
|
+
continue
|
|
429
|
+
if char == "\\":
|
|
430
|
+
escaped_at = at + 1
|
|
431
|
+
elif char == '"':
|
|
432
|
+
in_string = False
|
|
433
|
+
elif char == '"':
|
|
434
|
+
in_string = True
|
|
435
|
+
elif char in "[{":
|
|
436
|
+
depth += 1
|
|
437
|
+
if depth > _MAX_TOOL_INPUT_DEPTH:
|
|
438
|
+
return raw
|
|
439
|
+
elif char in "]}":
|
|
440
|
+
depth -= 1
|
|
441
|
+
try:
|
|
442
|
+
return json.loads(raw)
|
|
443
|
+
except (ValueError, RecursionError):
|
|
444
|
+
return raw
|
|
410
445
|
|
|
411
446
|
|
|
412
447
|
class _StreamAccumulator:
|
|
@@ -495,10 +530,7 @@ class _StreamAccumulator:
|
|
|
495
530
|
for key, value in self._blocks[index].items() if key != "budget"}
|
|
496
531
|
raw = entry.pop("json", None)
|
|
497
532
|
if raw is not None:
|
|
498
|
-
|
|
499
|
-
entry["input"] = json.loads(raw) if raw else {}
|
|
500
|
-
except (ValueError, RecursionError):
|
|
501
|
-
entry["input"] = raw # malformed or too deep: keep the raw arguments
|
|
533
|
+
entry["input"] = _parse_tool_input(raw)
|
|
502
534
|
content.append(SimpleNamespace(**entry))
|
|
503
535
|
return SimpleNamespace(
|
|
504
536
|
id=self.id, model=self.model, stop_reason=self.stop_reason, content=content,
|
|
@@ -506,17 +538,6 @@ class _StreamAccumulator:
|
|
|
506
538
|
)
|
|
507
539
|
|
|
508
540
|
|
|
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
541
|
class _RawStreamTelemetry:
|
|
521
542
|
"""Owns the ``chat`` span of one raw stream; ``end`` is idempotent and
|
|
522
543
|
thread-safe (garbage collection may finalize on any thread)."""
|
|
@@ -526,6 +547,8 @@ class _RawStreamTelemetry:
|
|
|
526
547
|
# The creating call's tool-use queue, created here when none exists (as the
|
|
527
548
|
# non-streaming path does on response): child tasks that pull events, and
|
|
528
549
|
# whatever context finally ends the stream, all feed THIS queue.
|
|
550
|
+
from struct_sdk.core import _ambient_pending_tool_calls
|
|
551
|
+
|
|
529
552
|
pending = _ambient_pending_tool_calls()
|
|
530
553
|
# The creating call's context: the stream may end (or be collected) in
|
|
531
554
|
# another request's, whose session must not label this one's events.
|
|
@@ -534,7 +557,7 @@ class _RawStreamTelemetry:
|
|
|
534
557
|
self._otel_logger, self._provider = otel_logger, provider
|
|
535
558
|
self._acc: Optional[_StreamAccumulator] = _StreamAccumulator(
|
|
536
559
|
keep_text=bool(sdk.emit_events or sdk.emit_span_content))
|
|
537
|
-
self._pending_tool_calls: Optional[
|
|
560
|
+
self._pending_tool_calls: Optional[_PendingToolCallQueue] = pending
|
|
538
561
|
self._lock = threading.Lock()
|
|
539
562
|
# Armed only once every hook is in place: a half-installed stream leaves
|
|
540
563
|
# the span to create(), and these hooks must then never end it again.
|
|
@@ -1125,30 +1148,19 @@ def _iter_tool_uses(content_blocks: Any) -> list[tuple[str, str]]:
|
|
|
1125
1148
|
def _record_pending_tool_calls(content_blocks: Any, into: Any = _AMBIENT) -> None:
|
|
1126
1149
|
"""Push every tool_use (name, id) from the response into the SDK contextvar.
|
|
1127
1150
|
|
|
1128
|
-
``into`` selects a captured queue: the creating agent scope's
|
|
1129
|
-
the ambient
|
|
1151
|
+
``into`` selects a captured queue: the creating agent scope's queue or
|
|
1152
|
+
the ambient queue created for a raw stream outside an agent. The default
|
|
1130
1153
|
uses the current context's queue; passing None skips recording.
|
|
1131
1154
|
|
|
1132
1155
|
Always runs (not gated on content-capture mode) — the linkage between a
|
|
1133
1156
|
chat span and its child execute_tool spans is structural, not content.
|
|
1134
1157
|
"""
|
|
1135
|
-
from struct_sdk.core import
|
|
1158
|
+
from struct_sdk.core import _ambient_pending_tool_calls
|
|
1136
1159
|
pairs = _iter_tool_uses(content_blocks)
|
|
1137
1160
|
if not pairs or into is None:
|
|
1138
1161
|
return
|
|
1139
|
-
if into is
|
|
1140
|
-
|
|
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)
|
|
1162
|
+
pending = _ambient_pending_tool_calls() if into is _AMBIENT else into
|
|
1163
|
+
pending.enqueue(pairs)
|
|
1152
1164
|
|
|
1153
1165
|
|
|
1154
1166
|
def _native_usage(response: Any) -> dict[str, int]:
|
|
@@ -42,10 +42,12 @@ from __future__ import annotations
|
|
|
42
42
|
import functools
|
|
43
43
|
import json
|
|
44
44
|
import logging
|
|
45
|
+
import sys
|
|
45
46
|
import types
|
|
46
47
|
from collections.abc import Mapping
|
|
47
48
|
from typing import TYPE_CHECKING, Any, Generator, Optional
|
|
48
49
|
|
|
50
|
+
import wrapt
|
|
49
51
|
from opentelemetry import trace
|
|
50
52
|
from opentelemetry.sdk.trace import SpanProcessor
|
|
51
53
|
from opentelemetry.trace import StatusCode
|
|
@@ -78,8 +80,12 @@ _CHOICE_FINISH_REASONS = {
|
|
|
78
80
|
"content_filter": "content_filter",
|
|
79
81
|
}
|
|
80
82
|
|
|
83
|
+
_OPENAI_CLIENT_MODULE = "autogen_ext.models.openai"
|
|
84
|
+
|
|
81
85
|
_wrapped: list[tuple[type, Any]] = []
|
|
82
86
|
_processor: Optional[_SessionProcessor] = None
|
|
87
|
+
_pending_sdk: Optional["StructSDK"] = None
|
|
88
|
+
_import_hook_registered = False
|
|
83
89
|
|
|
84
90
|
|
|
85
91
|
class _SessionProcessor(SpanProcessor):
|
|
@@ -106,28 +112,55 @@ class _SessionProcessor(SpanProcessor):
|
|
|
106
112
|
|
|
107
113
|
|
|
108
114
|
def patch(sdk: StructSDK) -> None:
|
|
109
|
-
"""
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
"""Register the session processor, and wrap
|
|
116
|
+
``BaseOpenAIChatCompletionClient.create`` now if the app has loaded AutoGen's
|
|
117
|
+
OpenAI client, else when it does, so importing ``autogen_ext`` alone never
|
|
118
|
+
loads ``openai`` (SDK-PY-5). Raises ImportError if autogen-ext is not installed."""
|
|
119
|
+
global _processor, _pending_sdk, _import_hook_registered
|
|
120
|
+
import autogen_ext # noqa: F401
|
|
121
|
+
|
|
122
|
+
provider = sdk.ai_tracer_provider
|
|
123
|
+
if _processor is None and provider is not None and hasattr(provider, "add_span_processor"):
|
|
124
|
+
_processor = _SessionProcessor()
|
|
125
|
+
provider.add_span_processor(_processor)
|
|
126
|
+
if _OPENAI_CLIENT_MODULE in sys.modules:
|
|
127
|
+
_wrap_openai_client(sdk)
|
|
128
|
+
return
|
|
129
|
+
_pending_sdk = sdk
|
|
130
|
+
if not _import_hook_registered:
|
|
131
|
+
_import_hook_registered = True
|
|
132
|
+
try:
|
|
133
|
+
wrapt.register_post_import_hook(_on_openai_client_import, _OPENAI_CLIENT_MODULE)
|
|
134
|
+
except BaseException:
|
|
135
|
+
_pending_sdk = None
|
|
136
|
+
_import_hook_registered = False
|
|
137
|
+
raise
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _on_openai_client_import(module: types.ModuleType) -> None:
|
|
141
|
+
global _pending_sdk, _import_hook_registered
|
|
142
|
+
_import_hook_registered = False
|
|
143
|
+
sdk, _pending_sdk = _pending_sdk, None
|
|
144
|
+
if sdk is not None and sdk._initialized and not sdk._activation_cancelled:
|
|
145
|
+
_contain(lambda: _wrap_openai_client(sdk), "autogen.patch_on_import")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _wrap_openai_client(sdk: StructSDK) -> None:
|
|
113
149
|
from autogen_ext.models.openai import BaseOpenAIChatCompletionClient
|
|
114
150
|
|
|
115
151
|
if _wrapped:
|
|
116
152
|
return
|
|
117
|
-
tracer = sdk.get_tracer(_TRACER_NAME)
|
|
118
153
|
original = BaseOpenAIChatCompletionClient.__dict__.get("create")
|
|
119
154
|
if original is not None and not getattr(original, "__struct_wrapped__", False):
|
|
120
|
-
BaseOpenAIChatCompletionClient.create = _wrap(original,
|
|
155
|
+
BaseOpenAIChatCompletionClient.create = _wrap(original, sdk.get_tracer(_TRACER_NAME), sdk) # type: ignore[method-assign]
|
|
121
156
|
_wrapped.append((BaseOpenAIChatCompletionClient, original))
|
|
122
|
-
provider = sdk.ai_tracer_provider
|
|
123
|
-
if _processor is None and provider is not None and hasattr(provider, "add_span_processor"):
|
|
124
|
-
_processor = _SessionProcessor()
|
|
125
|
-
provider.add_span_processor(_processor)
|
|
126
157
|
|
|
127
158
|
|
|
128
159
|
def unpatch() -> None:
|
|
129
|
-
"""Restore ``create
|
|
130
|
-
|
|
160
|
+
"""Restore ``create``, cancel a pending wrap and deactivate the session processor.
|
|
161
|
+
Primarily for tests."""
|
|
162
|
+
global _processor, _pending_sdk
|
|
163
|
+
_pending_sdk = None
|
|
131
164
|
while _wrapped:
|
|
132
165
|
cls, original = _wrapped.pop()
|
|
133
166
|
setattr(cls, "create", original)
|