struct-sdk 0.5.23__tar.gz → 0.5.26__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.23 → struct_sdk-0.5.26}/PKG-INFO +6 -5
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/README.md +4 -3
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/pyproject.toml +15 -3
- struct_sdk-0.5.26/src/struct_sdk/_fork_safe_http.py +198 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_genai_content.py +62 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_observations/config.py +147 -255
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_observations/health.py +155 -88
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_observations/identity.py +2 -0
- struct_sdk-0.5.26/src/struct_sdk/_observations/native_events.py +557 -0
- struct_sdk-0.5.26/src/struct_sdk/_observations/outputs.py +68 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_observations/poller.py +85 -6
- struct_sdk-0.5.26/src/struct_sdk/_observations/routing.py +110 -0
- struct_sdk-0.5.26/src/struct_sdk/_observations/runtime.py +1424 -0
- struct_sdk-0.5.26/src/struct_sdk/_observations/self_metrics.py +143 -0
- struct_sdk-0.5.26/src/struct_sdk/_observations/uwsgi.py +135 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/anthropic.py +45 -19
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/core.py +280 -31
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/openai.py +98 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/pydantic_ai.py +60 -19
- struct_sdk-0.5.23/src/struct_sdk/_fork_safe_http.py +0 -71
- struct_sdk-0.5.23/src/struct_sdk/_observations/export.py +0 -921
- struct_sdk-0.5.23/src/struct_sdk/_observations/otlp_sender.py +0 -230
- struct_sdk-0.5.23/src/struct_sdk/_observations/outputs.py +0 -825
- struct_sdk-0.5.23/src/struct_sdk/_observations/providers.py +0 -81
- struct_sdk-0.5.23/src/struct_sdk/_observations/runtime.py +0 -640
- struct_sdk-0.5.23/src/struct_sdk/_observations/self_metrics.py +0 -79
- struct_sdk-0.5.23/src/struct_sdk/_observations/snapshot.py +0 -671
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/.gitignore +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/LICENSE +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/__init__.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_auto.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_container.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_distro.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_event_loop.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_metrics.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_observations/__init__.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_operation_details.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/_pool.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/ag2.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/autogen.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/claude_agent.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/crewai.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/gcp.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/google_genai.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/langchain.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/litellm.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/llamaindex.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/mcp.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/openai_agents.py +0 -0
- {struct_sdk-0.5.23 → struct_sdk-0.5.26}/src/struct_sdk/temporal.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: struct-sdk
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.26
|
|
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,7 +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
|
|
27
|
+
Requires-Dist: struct-sdk-native==0.2.0
|
|
28
28
|
Requires-Dist: wrapt>=1.16.0
|
|
29
29
|
Provides-Extra: anthropic
|
|
30
30
|
Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
|
|
@@ -194,7 +194,7 @@ async with struct.agent(name="checkout"):
|
|
|
194
194
|
| `crewai` (1.15.13+) | `invoke_agent`, `chat`, `execute_tool` | Crew kickoffs and agent executions, model calls (native providers or LiteLLM) and tool calls, from CrewAI's event bus. The provider SDK span under a CrewAI model call is suppressed. See [CrewAI](#crewai). |
|
|
195
195
|
| `autogen_ext` (AutoGen 0.7+) | `chat {model}` | AutoGen traces its own agents and tools; Struct adds a `chat` span for each non-streaming call through the OpenAI-family clients (`OpenAIChatCompletionClient`, Azure, OpenAI-compatible endpoints). In owned full-app mode, Struct also stamps the `struct.agent()` session on AutoGen's spans. AutoGen's Anthropic client is covered by the `anthropic` integration. See [AutoGen](#autogen). |
|
|
196
196
|
| `autogen` (AG2 0.x) | `chat {model}`, `execute_tool {name}` | Every `OpenAIWrapper.create` model call and `ConversableAgent` tool execution. AG2's own instrumentation, when you turn it on, owns those calls instead. See [AG2](#ag2). |
|
|
197
|
-
| `claude_agent_sdk` |
|
|
197
|
+
| `claude_agent_sdk` | Claude Code's own `claude_code.*` spans | Telemetry comes from Claude Code itself in the subprocess; ingest credentials are propagated to it via `ClaudeAgentOptions`. Subagents inherit the configuration. Struct stores these spans, logs and metrics as Claude Code emits them: they keep their `claude_code.*` names and carry no `gen_ai.*` attributes. |
|
|
198
198
|
| `langchain_core` `BaseChatModel` | `chat {model}` | When the underlying provider SDK is also instrumented (e.g. `ChatAnthropic` + `anthropic`), the provider's span is suppressed, so there is a single span. |
|
|
199
199
|
| `langchain_core` `BaseTool` | `execute_tool {name}` | `tool_call_id` extracted from the LangChain ToolCall when present. |
|
|
200
200
|
| `langchain_core` `BaseRetriever` | `retrieval {name}` | |
|
|
@@ -230,8 +230,9 @@ struct.init(ingest_key="pk-...", service_name="claude-agent")
|
|
|
230
230
|
|
|
231
231
|
from claude_agent_sdk import ClaudeAgentOptions, query
|
|
232
232
|
# Telemetry is generated by Claude Code itself in the subprocess and
|
|
233
|
-
# exported directly via OTLP
|
|
234
|
-
# credentials on ClaudeAgentOptions;
|
|
233
|
+
# exported directly via OTLP under Claude Code's own `claude_code.*` names.
|
|
234
|
+
# struct.init() configures the ingest credentials on ClaudeAgentOptions;
|
|
235
|
+
# subagents inherit them automatically.
|
|
235
236
|
```
|
|
236
237
|
|
|
237
238
|
#### pydantic-ai
|
|
@@ -77,7 +77,7 @@ async with struct.agent(name="checkout"):
|
|
|
77
77
|
| `crewai` (1.15.13+) | `invoke_agent`, `chat`, `execute_tool` | Crew kickoffs and agent executions, model calls (native providers or LiteLLM) and tool calls, from CrewAI's event bus. The provider SDK span under a CrewAI model call is suppressed. See [CrewAI](#crewai). |
|
|
78
78
|
| `autogen_ext` (AutoGen 0.7+) | `chat {model}` | AutoGen traces its own agents and tools; Struct adds a `chat` span for each non-streaming call through the OpenAI-family clients (`OpenAIChatCompletionClient`, Azure, OpenAI-compatible endpoints). In owned full-app mode, Struct also stamps the `struct.agent()` session on AutoGen's spans. AutoGen's Anthropic client is covered by the `anthropic` integration. See [AutoGen](#autogen). |
|
|
79
79
|
| `autogen` (AG2 0.x) | `chat {model}`, `execute_tool {name}` | Every `OpenAIWrapper.create` model call and `ConversableAgent` tool execution. AG2's own instrumentation, when you turn it on, owns those calls instead. See [AG2](#ag2). |
|
|
80
|
-
| `claude_agent_sdk` |
|
|
80
|
+
| `claude_agent_sdk` | Claude Code's own `claude_code.*` spans | Telemetry comes from Claude Code itself in the subprocess; ingest credentials are propagated to it via `ClaudeAgentOptions`. Subagents inherit the configuration. Struct stores these spans, logs and metrics as Claude Code emits them: they keep their `claude_code.*` names and carry no `gen_ai.*` attributes. |
|
|
81
81
|
| `langchain_core` `BaseChatModel` | `chat {model}` | When the underlying provider SDK is also instrumented (e.g. `ChatAnthropic` + `anthropic`), the provider's span is suppressed, so there is a single span. |
|
|
82
82
|
| `langchain_core` `BaseTool` | `execute_tool {name}` | `tool_call_id` extracted from the LangChain ToolCall when present. |
|
|
83
83
|
| `langchain_core` `BaseRetriever` | `retrieval {name}` | |
|
|
@@ -113,8 +113,9 @@ struct.init(ingest_key="pk-...", service_name="claude-agent")
|
|
|
113
113
|
|
|
114
114
|
from claude_agent_sdk import ClaudeAgentOptions, query
|
|
115
115
|
# Telemetry is generated by Claude Code itself in the subprocess and
|
|
116
|
-
# exported directly via OTLP
|
|
117
|
-
# credentials on ClaudeAgentOptions;
|
|
116
|
+
# exported directly via OTLP under Claude Code's own `claude_code.*` names.
|
|
117
|
+
# struct.init() configures the ingest credentials on ClaudeAgentOptions;
|
|
118
|
+
# subagents inherit them automatically.
|
|
118
119
|
```
|
|
119
120
|
|
|
120
121
|
#### pydantic-ai
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "struct-sdk"
|
|
7
|
-
version = "0.5.
|
|
7
|
+
version = "0.5.26"
|
|
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"
|
|
@@ -33,7 +33,7 @@ dependencies = [
|
|
|
33
33
|
"wrapt>=1.16.0",
|
|
34
34
|
# Native capture runtime. Always installs: platforms without a native build
|
|
35
35
|
# get its pure py3-none-any wheel, which reports the capability unavailable.
|
|
36
|
-
"struct-sdk-native
|
|
36
|
+
"struct-sdk-native==0.2.0",
|
|
37
37
|
]
|
|
38
38
|
|
|
39
39
|
[project.urls]
|
|
@@ -255,7 +255,19 @@ openai2 = [
|
|
|
255
255
|
struct-sdk-native = { path = "../struct-sdk-native", editable = true }
|
|
256
256
|
|
|
257
257
|
[tool.uv]
|
|
258
|
-
|
|
258
|
+
# The litellm extra needs openai<3 (current litellm releases pin it), like the
|
|
259
|
+
# openai2 group, so it cannot share the dev environment's openai 3. Without this the
|
|
260
|
+
# lock resolves dev + litellm to an old, vulnerable litellm that still
|
|
261
|
+
# accepted openai 3 (CVE-2026-37004, CVE-2026-42208, CVE-2026-49468).
|
|
262
|
+
conflicts = [
|
|
263
|
+
[{ group = "dev" }, { group = "openai2" }],
|
|
264
|
+
[{ group = "dev" }, { extra = "litellm" }],
|
|
265
|
+
]
|
|
266
|
+
# 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
|
|
268
|
+
# with the fixes for its 2026 CVEs, needs 3.11, so a 3.10 lock entry
|
|
269
|
+
# could only hold vulnerable Pillow 12.
|
|
270
|
+
environments = ["python_full_version >= '3.11'"]
|
|
259
271
|
override-dependencies = [
|
|
260
272
|
"cryptography>=50.0.0",
|
|
261
273
|
"langgraph>=1.2.0,<1.3.0",
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""HTTP sessions for the SDK's own requests, which a forked child can keep using and exit with.
|
|
2
|
+
|
|
3
|
+
Background threads send through these sessions, and each request holds its connection pool's locks
|
|
4
|
+
for a moment. When the host forks during that moment, the child's copies of those locks stay held
|
|
5
|
+
for good, since the thread that held them doesn't exist there. urllib3 takes them again to close a
|
|
6
|
+
pool, when the pool is collected and at exit, so the child would hang on its way out. The child
|
|
7
|
+
would also inherit the parent's open connections, and its next request could write to a socket
|
|
8
|
+
the parent is still using.
|
|
9
|
+
|
|
10
|
+
So after a fork, the child gives each session a fresh cookie jar and its pools fresh locks, then
|
|
11
|
+
discards the pools, closing the idle connections in them. Only the child's copies of those sockets
|
|
12
|
+
close; that sends nothing, so the parent's connections carry on. A connection a thread was using at
|
|
13
|
+
the fork isn't in a pool, so the child leaves it open and never uses it. The session itself stays
|
|
14
|
+
usable, and the child's next request opens a connection of its own.
|
|
15
|
+
|
|
16
|
+
On macOS, ``requests`` also reads the system proxy settings for every request, through Apple's
|
|
17
|
+
SystemConfiguration framework, which a process forked without exec can't use safely: the call can
|
|
18
|
+
hang or the process be killed. So a forked child there never makes it for the requests that resolve
|
|
19
|
+
their settings through `environment_settings` (the Observations poller, export branch and Rust
|
|
20
|
+
delivery's routing): it gives them what the process resolved for that URL before the fork, or
|
|
21
|
+
failing that the environment's proxy variables alone.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
import sys
|
|
29
|
+
import threading
|
|
30
|
+
import urllib.request
|
|
31
|
+
import weakref
|
|
32
|
+
from typing import Any, Callable, cast
|
|
33
|
+
from urllib.parse import urlsplit
|
|
34
|
+
|
|
35
|
+
import requests
|
|
36
|
+
import requests.cookies
|
|
37
|
+
import requests.utils
|
|
38
|
+
from requests.sessions import merge_setting
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger("struct_sdk")
|
|
41
|
+
|
|
42
|
+
# Sessions belong to requests, not to us, so they're tracked here rather than marked.
|
|
43
|
+
_sessions: weakref.WeakSet[requests.Session] = weakref.WeakSet()
|
|
44
|
+
|
|
45
|
+
# The proxies `requests` resolved for each origin (scheme, host, port) the SDK sends to, as of its
|
|
46
|
+
# last request before any fork: what a forked child on macOS reuses. Proxies depend only on the
|
|
47
|
+
# origin, so artifact downloads under one host share an entry; bounded all the same, oldest
|
|
48
|
+
# entry evicted first, and an evicted origin falls back to the proxy variables alone.
|
|
49
|
+
_resolved_proxies: dict[tuple[str, str, int | None], dict[str, str]] = {}
|
|
50
|
+
_MAX_RESOLVED = 64
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _origin(url: str) -> tuple[str, str, int | None]:
|
|
54
|
+
parsed = urlsplit(url)
|
|
55
|
+
return parsed.scheme, (parsed.hostname or ""), parsed.port
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# Set in a child after a fork: this process may not use the system proxy settings on macOS.
|
|
59
|
+
_forked = False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _environment_proxies(url: str) -> dict[str, str]:
|
|
63
|
+
"""The proxy variables alone, as ``requests`` reads them, without the system settings.
|
|
64
|
+
|
|
65
|
+
``requests`` reads ``NO_PROXY`` twice, with different precedence: its own check takes
|
|
66
|
+
``no_proxy`` unless that is empty, then ``NO_PROXY``; urllib's environment fallback takes
|
|
67
|
+
``no_proxy`` whenever it is set, so an empty one turns the fallback off."""
|
|
68
|
+
proxies = urllib.request.getproxies_environment()
|
|
69
|
+
environment_no_proxy = proxies.pop("no", None)
|
|
70
|
+
no_proxy = os.environ.get("no_proxy") or os.environ.get("NO_PROXY")
|
|
71
|
+
return {} if _bypassed(url, no_proxy, environment_no_proxy or "") else proxies
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# urllib's environment-only matching, which reads no system setting. Typeshed leaves it out.
|
|
75
|
+
_proxy_bypass_environment: Callable[[str, dict[str, str]], bool] = cast(
|
|
76
|
+
Any, urllib.request
|
|
77
|
+
).proxy_bypass_environment
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _bypassed(
|
|
81
|
+
url: str, no_proxy: str | None, environment_no_proxy: str | None = None
|
|
82
|
+
) -> bool:
|
|
83
|
+
"""Whether ``NO_PROXY`` exempts ``url``, as ``requests`` decides without the system settings
|
|
84
|
+
(``should_bypass_proxies``). First its own matching: an IPv4 host against address and CIDR
|
|
85
|
+
entries only; any other host by plain suffix, with or without its port. Then the environment
|
|
86
|
+
matching urllib applies once proxy variables are set: ``*`` as the whole value bypasses every
|
|
87
|
+
host; otherwise a name matches itself and its subdomains, case-insensitively, a leading dot
|
|
88
|
+
optional.
|
|
89
|
+
``environment_no_proxy`` is the value that fallback reads (urllib's ``no`` entry); left out,
|
|
90
|
+
it reads ``no_proxy`` too, as when ``requests`` is handed one."""
|
|
91
|
+
parsed = urlsplit(url)
|
|
92
|
+
host = parsed.hostname
|
|
93
|
+
if host is None:
|
|
94
|
+
return True
|
|
95
|
+
if environment_no_proxy is None:
|
|
96
|
+
environment_no_proxy = no_proxy
|
|
97
|
+
if no_proxy and _requests_bypass(parsed, host, no_proxy):
|
|
98
|
+
return True
|
|
99
|
+
if not environment_no_proxy:
|
|
100
|
+
return False
|
|
101
|
+
return bool(_proxy_bypass_environment(host, {"no": environment_no_proxy}))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _requests_bypass(parsed: Any, host: str, no_proxy: str) -> bool:
|
|
105
|
+
"""``requests``' own ``NO_PROXY`` check, before it consults urllib."""
|
|
106
|
+
entries = [entry for entry in no_proxy.replace(" ", "").split(",") if entry]
|
|
107
|
+
if requests.utils.is_ipv4_address(host):
|
|
108
|
+
for entry in entries:
|
|
109
|
+
if requests.utils.is_valid_cidr(entry):
|
|
110
|
+
if requests.utils.address_in_network(host, entry):
|
|
111
|
+
return True
|
|
112
|
+
elif host == entry:
|
|
113
|
+
return True
|
|
114
|
+
else:
|
|
115
|
+
with_port = f"{host}:{parsed.port}" if parsed.port else host
|
|
116
|
+
if any(host.endswith(entry) or with_port.endswith(entry) for entry in entries):
|
|
117
|
+
return True
|
|
118
|
+
return False
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def environment_settings(
|
|
122
|
+
session: requests.Session, url: str, stream: Any
|
|
123
|
+
) -> dict[str, Any]:
|
|
124
|
+
"""Proxies and CA bundle from the environment for ``url``, as ``requests`` resolves them for
|
|
125
|
+
``session`` (``merge_environment_settings``), except in a forked child on macOS, which never
|
|
126
|
+
reads the system proxy settings: it reuses the proxies resolved for ``url`` before the fork, or
|
|
127
|
+
takes the proxy variables alone."""
|
|
128
|
+
if not (_forked and sys.platform == "darwin"):
|
|
129
|
+
settings = session.merge_environment_settings(url, {}, stream, None, None)
|
|
130
|
+
origin = _origin(url)
|
|
131
|
+
_resolved_proxies.pop(origin, None)
|
|
132
|
+
while len(_resolved_proxies) >= _MAX_RESOLVED:
|
|
133
|
+
del _resolved_proxies[next(iter(_resolved_proxies))]
|
|
134
|
+
_resolved_proxies[origin] = dict(settings["proxies"])
|
|
135
|
+
return settings
|
|
136
|
+
known = _resolved_proxies.get(_origin(url))
|
|
137
|
+
proxies = dict(known) if known is not None else _environment_proxies(url)
|
|
138
|
+
verify = (
|
|
139
|
+
os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or None
|
|
140
|
+
)
|
|
141
|
+
if not session.trust_env:
|
|
142
|
+
proxies, verify = {}, None
|
|
143
|
+
return {
|
|
144
|
+
"proxies": merge_setting(proxies, session.proxies),
|
|
145
|
+
"stream": merge_setting(stream, session.stream),
|
|
146
|
+
"verify": merge_setting(verify, session.verify),
|
|
147
|
+
"cert": merge_setting(None, session.cert),
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def fork_safe_session() -> requests.Session:
|
|
152
|
+
"""A new session that a forked child releases cleanly. Every session the SDK owns uses this."""
|
|
153
|
+
session = requests.Session()
|
|
154
|
+
_sessions.add(session)
|
|
155
|
+
return session
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _release(session: requests.Session) -> None:
|
|
159
|
+
"""Give a session fresh locks, then discard its pools and close the idle connections in them."""
|
|
160
|
+
try:
|
|
161
|
+
# Every response passes through the cookie jar under its lock. Struct sends no cookies, so a
|
|
162
|
+
# fresh jar loses nothing.
|
|
163
|
+
session.cookies = requests.cookies.RequestsCookieJar()
|
|
164
|
+
for adapter in session.adapters.values():
|
|
165
|
+
managers = [
|
|
166
|
+
getattr(adapter, "poolmanager", None),
|
|
167
|
+
*getattr(adapter, "proxy_manager", {}).values(),
|
|
168
|
+
]
|
|
169
|
+
for manager in managers:
|
|
170
|
+
pools = getattr(manager, "pools", None)
|
|
171
|
+
if pools is None:
|
|
172
|
+
continue
|
|
173
|
+
pools.lock = threading.RLock()
|
|
174
|
+
for key in pools.keys():
|
|
175
|
+
connections = getattr(pools[key], "pool", None)
|
|
176
|
+
if connections is not None:
|
|
177
|
+
connections.mutex = threading.Lock()
|
|
178
|
+
connections.not_empty = threading.Condition(connections.mutex)
|
|
179
|
+
connections.not_full = threading.Condition(connections.mutex)
|
|
180
|
+
connections.all_tasks_done = threading.Condition(
|
|
181
|
+
connections.mutex
|
|
182
|
+
)
|
|
183
|
+
session.close()
|
|
184
|
+
except Exception: # noqa: BLE001 - this runs inside the host's fork
|
|
185
|
+
logger.debug(
|
|
186
|
+
"Struct SDK could not release an HTTP session after fork", exc_info=True
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _release_after_fork() -> None:
|
|
191
|
+
global _forked
|
|
192
|
+
_forked = True
|
|
193
|
+
for session in list(_sessions):
|
|
194
|
+
_release(session)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
if hasattr(os, "register_at_fork"):
|
|
198
|
+
os.register_at_fork(after_in_child=_release_after_fork)
|
|
@@ -613,3 +613,65 @@ def propagate_provider_to_parent(provider: Optional[str]) -> None:
|
|
|
613
613
|
stamp_provider_once(_current_agent_span.get(None), provider)
|
|
614
614
|
except Exception:
|
|
615
615
|
pass # Never break the application for telemetry
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
# ---------------------------------------------------------------------------
|
|
619
|
+
# Platform host predicates shared by the OpenAI and Anthropic integrations.
|
|
620
|
+
#
|
|
621
|
+
# Bedrock, Vertex and Snowflake each serve BOTH an OpenAI-compatible surface and
|
|
622
|
+
# the Anthropic Messages API on the same hosts, so both integrations need the
|
|
623
|
+
# same predicate — and pydantic_ai._platform() scans both rule sets and relies on
|
|
624
|
+
# them naming the same platform wherever they overlap. One copy here means they
|
|
625
|
+
# cannot drift (test_openai_and_anthropic_host_maps_agree_where_they_overlap
|
|
626
|
+
# still checks the assembled rule sets). Official endpoint host shapes only: a
|
|
627
|
+
# generic cloud host (API gateway, storage, an arbitrary *.amazonaws.com or
|
|
628
|
+
# *.googleapis.com proxy) is NOT platform routing and stays on the fallback.
|
|
629
|
+
# ---------------------------------------------------------------------------
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def is_bedrock_host(host: str) -> bool:
|
|
633
|
+
"""True for Bedrock's runtime endpoints, which serve both APIs.
|
|
634
|
+
|
|
635
|
+
AWS's endpoints page, verbatim: "bedrock-runtime.{region}.amazonaws.com
|
|
636
|
+
(recommended) ... The OpenAI-compatible APIs are called on the /openai/v1
|
|
637
|
+
paths of this endpoint rather than through the AWS SDKs", and
|
|
638
|
+
"bedrock-mantle.{region}.api.aws ... for making inference requests for
|
|
639
|
+
models hosted in Amazon Bedrock using the OpenAI-compatible endpoints and
|
|
640
|
+
the Anthropic Messages API". Without the OpenAI side of this rule, Bedrock
|
|
641
|
+
calls made with an unmodified OpenAI SDK reported first-party ``openai``:
|
|
642
|
+
seen in our own traces as ``global.openai.gpt-6-sol`` arriving with
|
|
643
|
+
``gen_ai.provider.name="openai"``.
|
|
644
|
+
|
|
645
|
+
Note the mantle host ends in ``.api.aws``, NOT ``.amazonaws.com``.
|
|
646
|
+
"""
|
|
647
|
+
if host.startswith(("bedrock-runtime.", "bedrock-runtime-fips.")) and (
|
|
648
|
+
host.endswith(".amazonaws.com") or host.endswith(".amazonaws.com.cn")
|
|
649
|
+
):
|
|
650
|
+
return True
|
|
651
|
+
return host.startswith("bedrock-mantle.") and host.endswith(".api.aws")
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def is_vertex_host(host: str) -> bool:
|
|
655
|
+
"""True for Vertex AI's endpoints, global and regional.
|
|
656
|
+
|
|
657
|
+
Google documents bringing an unmodified OpenAI client to Vertex by changing
|
|
658
|
+
only the base URL: ``base_url="https://aiplatform.googleapis.com/v1/projects/
|
|
659
|
+
{project_id}/locations/{location}/endpoints/openapi"`` and
|
|
660
|
+
``OPENAI_BASE_URL="https://${LOCATION}-aiplatform.googleapis.com/v1beta1/
|
|
661
|
+
projects/${PROJECT_ID}/locations/${LOCATION}/endpoints/openapi"`` (read
|
|
662
|
+
2026-11-17). A generic GCP host (``storage.googleapis.com``) is not routing.
|
|
663
|
+
"""
|
|
664
|
+
return host == "aiplatform.googleapis.com" or host.endswith("-aiplatform.googleapis.com")
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def is_snowflake_host(host: str) -> bool:
|
|
668
|
+
"""True for a Snowflake ACCOUNT host (open-enum extension ``snowflake``).
|
|
669
|
+
|
|
670
|
+
Snowflake Cortex serves BOTH its OpenAI-compatible Chat Completions surface
|
|
671
|
+
(``POST https://<account-identifier>.snowflakecomputing.com/api/v2/cortex/v1/
|
|
672
|
+
chat/completions``, which "follows the OpenAI specification") and an Anthropic
|
|
673
|
+
Messages surface on paths of the customer's own account host — "The Messages
|
|
674
|
+
API follows the Anthropic specification and supports Claude models only"
|
|
675
|
+
(read 2026-11-17). A suffix rule, never a bare ``snowflakecomputing.com``.
|
|
676
|
+
"""
|
|
677
|
+
return host.endswith(".snowflakecomputing.com")
|