desp-sdk 0.5.7__py3-none-any.whl

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.
@@ -0,0 +1,205 @@
1
+ """
2
+ Interpreter-start bootstrap for LLM usage capture, run by desp_sdk_usage.pth.
3
+
4
+ Lives outside desp_sdk: importing desp_sdk loads httpx (~90 ms), and the
5
+ .pth runs in every interpreter of the environment. This module costs nothing
6
+ when capture is off, and defers the rest until the app imports httpx or httpx2:
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from os import environ
13
+
14
+ # Type-only imports: loading typing / collections at runtime costs ~3-8 ms in
15
+ # every interpreter. mypy treats any name TYPE_CHECKING as true.
16
+ TYPE_CHECKING = False
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Callable, Sequence
19
+ from importlib.machinery import ModuleSpec
20
+ from types import ModuleType
21
+
22
+ # Mirrors desp_sdk._config; importing it here would load desp_sdk.
23
+ _API_KEY_ENV = "DESP_API_KEY"
24
+ _LLM_USAGE_ENV = "DESP_LLM_USAGE"
25
+ _OFF = "off"
26
+
27
+ # Mirrors desp_sdk.usage._httpx_patch.TARGETS. httpx2: what openai>=3 sends through.
28
+ _TARGETS = ("httpx", "httpx2")
29
+
30
+ # Importing the SDK first loads httpx from inside desp_sdk._http, where
31
+ # activating would hit its partially initialized modules; activate after it.
32
+ _SDK = "desp_sdk"
33
+ _HOOKED = (*_TARGETS, _SDK)
34
+
35
+ # Loading the SDK imports httpx, which re-enters _activate(); see there.
36
+ _busy = False
37
+
38
+
39
+ def _enabled() -> bool:
40
+ """
41
+ Cheap pre-check of the config; activate() re-checks it.
42
+
43
+ Returns:
44
+ True when the key is set and the kill switch is not.
45
+ """
46
+ if environ.get(_LLM_USAGE_ENV, "").strip().lower() == _OFF:
47
+ return False
48
+ return bool(environ.get(_API_KEY_ENV))
49
+
50
+
51
+ def _activate() -> None:
52
+ """
53
+ Load the SDK and start capture. Never raises: the app's import must not break.
54
+
55
+ Returns:
56
+ None.
57
+ """
58
+ global _busy
59
+
60
+ # Re-entry while the SDK loads (it imports httpx): skip; the outer call
61
+ # patches every target loaded by then.
62
+ if _busy:
63
+ return
64
+
65
+ _busy = True
66
+ try:
67
+ from desp_sdk.usage._activate import activate
68
+
69
+ activate()
70
+ except Exception: # noqa: BLE001, S110 - the app's import must not break; no logging set up yet
71
+ pass
72
+ finally:
73
+ _busy = False
74
+
75
+
76
+ def _exec_busy(exec_module: Callable[[ModuleType], None], module: ModuleType) -> None:
77
+ """
78
+ Execute a module with _activate() deferred, as while the SDK loads.
79
+
80
+ Args:
81
+ exec_module: The loader's original exec_module.
82
+ module: The module to execute.
83
+ Returns:
84
+ None.
85
+ """
86
+ global _busy
87
+
88
+ outer = _busy
89
+ _busy = True
90
+ try:
91
+ exec_module(module)
92
+ finally:
93
+ _busy = outer
94
+
95
+
96
+ def _all_loaded() -> bool:
97
+ """
98
+ Whether every target package is imported.
99
+
100
+ Returns:
101
+ True when none is left to wait for.
102
+ """
103
+ return all(name in sys.modules for name in _TARGETS)
104
+
105
+
106
+ class _HttpxHook:
107
+ """
108
+ Import hook: lets the normal finders locate each target (httpx, httpx2),
109
+ then runs _activate() right after its module code has executed. Leaves
110
+ sys.meta_path once every target is loaded.
111
+ """
112
+
113
+ def __init__(self) -> None:
114
+ """
115
+ Start with no lookup in progress.
116
+
117
+ Returns:
118
+ None.
119
+ """
120
+ self._resolving: set[str] = set()
121
+
122
+ def find_spec(
123
+ self,
124
+ fullname: str,
125
+ path: Sequence[str] | None,
126
+ target: ModuleType | None = None,
127
+ ) -> ModuleSpec | None:
128
+ """
129
+ Intercept target and SDK imports only.
130
+
131
+ Args:
132
+ fullname: The module being imported.
133
+ path: The parent package's path (None for top-level).
134
+ target: The module being reloaded, if any.
135
+ Returns:
136
+ httpx's real spec with activation chained after its execution,
137
+ or None to let other finders handle the import.
138
+ """
139
+ if fullname not in _HOOKED or fullname in self._resolving:
140
+ return None
141
+
142
+ # Mark the lookup, so the find_spec below does not recurse into us.
143
+ from importlib.util import find_spec
144
+
145
+ self._resolving.add(fullname)
146
+ try:
147
+ spec = find_spec(fullname)
148
+ finally:
149
+ self._resolving.discard(fullname)
150
+
151
+ loader = spec.loader if spec else None
152
+ exec_module = getattr(loader, "exec_module", None)
153
+ if spec is None or exec_module is None:
154
+ return spec
155
+
156
+ def exec_then_activate(module: ModuleType) -> None:
157
+ if fullname == _SDK:
158
+ _exec_busy(exec_module, module)
159
+ else:
160
+ exec_module(module)
161
+ _activate()
162
+ self._retire()
163
+
164
+ try:
165
+ loader.exec_module = exec_then_activate # type: ignore[union-attr, method-assign]
166
+ except AttributeError:
167
+ pass
168
+ return spec
169
+
170
+ def _retire(self) -> None:
171
+ """
172
+ Leave sys.meta_path once no target is left to wait for.
173
+
174
+ Returns:
175
+ None.
176
+ """
177
+ if not _all_loaded():
178
+ return
179
+
180
+ try:
181
+ sys.meta_path.remove(self)
182
+ except ValueError:
183
+ pass
184
+
185
+
186
+ def _boot() -> None:
187
+ """
188
+ Arm capture: now for targets already loaded, else on their first import.
189
+
190
+ Returns:
191
+ None.
192
+ """
193
+ if not _enabled():
194
+ return
195
+
196
+ if any(name in sys.modules for name in _TARGETS):
197
+ _activate()
198
+
199
+ if _all_loaded():
200
+ return
201
+
202
+ sys.meta_path.insert(0, _HttpxHook())
203
+
204
+
205
+ _boot()
desp_sdk/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from ._config import DespConfigError
6
+ from ._errors import DespError
7
+ from ._http import (
8
+ DEFAULT_TIMEOUT_SECONDS,
9
+ DespApiError,
10
+ DespConnectionError,
11
+ DespResponseError,
12
+ DespTimeoutError,
13
+ )
14
+ from .client import DespClient, emit_delta, emit_delta_strict
15
+ from .health import get_health
16
+ from .langgraph_adapter import wrap_node
17
+ from .models import (
18
+ DeltaAck,
19
+ DeltaCreate,
20
+ SystemDecision,
21
+ TriggerPlanCreate,
22
+ TriggerPlanDecision,
23
+ TriggerPlanMode,
24
+ TriggerPlanOut,
25
+ )
26
+ from .serialization import to_jsonable
27
+ from .trigger_plans import request_trigger_plan
28
+
29
+ try:
30
+ __version__ = version("desp-sdk")
31
+ except PackageNotFoundError:
32
+ __version__ = "0.0.0"
33
+
34
+ __all__ = [
35
+ "DEFAULT_TIMEOUT_SECONDS",
36
+ "DeltaAck",
37
+ "DeltaCreate",
38
+ "DespApiError",
39
+ "DespClient",
40
+ "DespConfigError",
41
+ "DespConnectionError",
42
+ "DespError",
43
+ "DespResponseError",
44
+ "DespTimeoutError",
45
+ "SystemDecision",
46
+ "TriggerPlanCreate",
47
+ "TriggerPlanDecision",
48
+ "TriggerPlanMode",
49
+ "TriggerPlanOut",
50
+ "__version__",
51
+ "emit_delta",
52
+ "emit_delta_strict",
53
+ "get_health",
54
+ "request_trigger_plan",
55
+ "to_jsonable",
56
+ "wrap_node",
57
+ ]
desp_sdk/_config.py ADDED
@@ -0,0 +1,43 @@
1
+ import os
2
+
3
+ from ._errors import DespError
4
+
5
+ BASE_URL_ENV = "DESP_BASE_URL"
6
+ DEFAULT_BASE_URL = "https://aether-server-production.up.railway.app"
7
+ API_KEY_ENV = "DESP_API_KEY"
8
+ LLM_USAGE_ENV = "DESP_LLM_USAGE"
9
+
10
+
11
+ class DespConfigError(DespError, ValueError):
12
+ """Raised when the API key cannot be resolved."""
13
+
14
+
15
+ def resolve_base_url(base_url: str | None) -> str:
16
+ """
17
+ Resolve the base URL: argument, then DESP_BASE_URL, then production.
18
+ The overrides exist for local and staging deployments.
19
+
20
+ Args:
21
+ base_url: The base URL to resolve.
22
+ Returns:
23
+ The resolved base URL.
24
+ """
25
+ value = base_url or os.environ.get(BASE_URL_ENV) or DEFAULT_BASE_URL
26
+ return value.rstrip("/")
27
+
28
+
29
+ def resolve_api_key(api_key: str | None) -> str:
30
+ """
31
+ Resolve the API key from the environment or the provided API key.
32
+
33
+ Args:
34
+ api_key: The API key to resolve.
35
+ Returns:
36
+ The resolved API key.
37
+ """
38
+ value = api_key or os.environ.get(API_KEY_ENV)
39
+ if not value:
40
+ raise DespConfigError(
41
+ f"No DESP API key: pass api_key=... or set {API_KEY_ENV}."
42
+ )
43
+ return value
desp_sdk/_errors.py ADDED
@@ -0,0 +1,14 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class DespError(Exception):
5
+ """
6
+ Base for every SDK error. Catch it to handle all SDK failures at once:
7
+
8
+ DespError
9
+ ├── DespConfigError missing base URL / API key
10
+ ├── DespApiError non-2xx response (3xx / 4xx / 5xx)
11
+ ├── DespTimeoutError no answer within the timeout
12
+ ├── DespConnectionError refused, DNS, TLS, protocol
13
+ └── DespResponseError 2xx body is not the expected JSON shape
14
+ """
desp_sdk/_http.py ADDED
@@ -0,0 +1,277 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ from ._config import DespConfigError
8
+ from ._errors import DespError
9
+
10
+ DEFAULT_TIMEOUT_SECONDS = 5.0
11
+
12
+ _NO_CONTENT_STATUS = 204
13
+ _MAX_PORT = 65535
14
+ _SCHEMES = frozenset({"http", "https"})
15
+
16
+
17
+ class DespApiError(DespError):
18
+ """Raised for any non-2xx response."""
19
+
20
+ def __init__(self, status_code: int, code: str, message: str) -> None:
21
+ super().__init__(f"{code}: {message}")
22
+ self.status_code = status_code
23
+ self.code = code
24
+ self.message = message
25
+
26
+ def __reduce__(self) -> tuple[Any, ...]:
27
+ return type(self), (self.status_code, self.code, self.message), self.__dict__
28
+
29
+
30
+ class DespTimeoutError(DespError):
31
+ """Raised when DESP does not answer within the timeout."""
32
+
33
+ def __init__(self, method: str, url: str, timeout: float) -> None:
34
+ """
35
+ Build the error from the request that timed out.
36
+
37
+ Args:
38
+ method: The HTTP method of the request.
39
+ url: The full URL of the request.
40
+ timeout: The timeout, in seconds, that was exceeded.
41
+ Returns:
42
+ None.
43
+ """
44
+ super().__init__(f"{method} {url} timed out after {timeout}s")
45
+ self.method = method
46
+ self.url = url
47
+ self.timeout = timeout
48
+
49
+ def __reduce__(self) -> tuple[Any, ...]:
50
+ return type(self), (self.method, self.url, self.timeout), self.__dict__
51
+
52
+
53
+ class DespConnectionError(DespError):
54
+ """Raised when DESP cannot be reached (refused, DNS, TLS, protocol)."""
55
+
56
+ def __init__(self, method: str, url: str) -> None:
57
+ """
58
+ Build the error from the request that failed.
59
+
60
+ Args:
61
+ method: The HTTP method of the request.
62
+ url: The full URL of the request.
63
+ Returns:
64
+ None.
65
+ """
66
+ super().__init__(f"{method} {url} failed: DESP unreachable")
67
+ self.method = method
68
+ self.url = url
69
+
70
+ def __reduce__(self) -> tuple[Any, ...]:
71
+ return type(self), (self.method, self.url), self.__dict__
72
+
73
+
74
+ class DespResponseError(DespError, ValueError):
75
+ """Raised when a 2xx response body is not the JSON shape the SDK expects."""
76
+
77
+ def __init__(self, method: str, url: str, detail: str) -> None:
78
+ """
79
+ Build the error from the request whose response could not be decoded.
80
+
81
+ Args:
82
+ method: The HTTP method of the request.
83
+ url: The full URL of the request.
84
+ detail: Why the response body was rejected.
85
+ Returns:
86
+ None.
87
+ """
88
+ super().__init__(f"{method} {url} returned an invalid response: {detail}")
89
+ self.method = method
90
+ self.url = url
91
+ self.detail = detail
92
+
93
+ def __reduce__(self) -> tuple[Any, ...]:
94
+ return type(self), (self.method, self.url, self.detail), self.__dict__
95
+
96
+
97
+ def _to_api_error(response: httpx.Response) -> DespApiError:
98
+ """
99
+ Convert a response to an DespApiError.
100
+
101
+ Args:
102
+ response: The response to convert.
103
+ Returns:
104
+ The DespApiError.
105
+ """
106
+ try:
107
+ error = response.json()["error"]
108
+ return DespApiError(response.status_code, error["code"], error["message"])
109
+ except (KeyError, TypeError, ValueError):
110
+ location = response.headers.get("Location")
111
+ if response.is_redirect and location:
112
+ return DespApiError(
113
+ response.status_code, "http_redirect",
114
+ f"redirected to {location}; set the base URL to the final address",
115
+ )
116
+ return DespApiError(response.status_code, "http_error", response.text)
117
+
118
+
119
+ def _validate_url(base_url: str, url: str) -> None:
120
+ """
121
+ Reject a base URL httpx cannot send to. httpx raises InvalidURL (not an
122
+ httpx.HTTPError) for a malformed URL, an out-of-range port only fails
123
+ at connect time as a bare OverflowError, and a missing http(s):// scheme
124
+ (e.g. "aether:8004") surfaces as UnsupportedProtocol, which would look
125
+ like DESP being unreachable.
126
+
127
+ Args:
128
+ base_url: The base URL as configured, for the error message.
129
+ url: The full URL of the request.
130
+ Returns:
131
+ None.
132
+ """
133
+ try:
134
+ parsed = httpx.URL(url)
135
+ port = parsed.port
136
+ except httpx.InvalidURL as exc:
137
+ raise DespConfigError(f"Invalid DESP base URL {base_url!r}: {exc}") from exc
138
+ if parsed.scheme not in _SCHEMES or not parsed.host:
139
+ raise DespConfigError(
140
+ f"Invalid DESP base URL {base_url!r}: expected http://host[:port] or https://host[:port]"
141
+ )
142
+ if port is not None and port > _MAX_PORT:
143
+ raise DespConfigError(f"Invalid DESP base URL {base_url!r}: port {port} out of range")
144
+
145
+
146
+ def _auth_headers(api_key: str | None) -> dict[str, str] | None:
147
+ """
148
+ Build the Bearer header, rejecting a key that cannot go in an HTTP header.
149
+ httpx raises a bare UnicodeEncodeError for non-ASCII (e.g. a pasted
150
+ zero-width or non-breaking space), and a stray newline or trailing space
151
+ (e.g. from a .env line) only surfaces as a protocol error that looks like
152
+ DESP being unreachable.
153
+
154
+ Args:
155
+ api_key: The system API key, or None to send no Authorization header.
156
+ Returns:
157
+ The headers to send, or None when there is no key.
158
+ """
159
+ if not api_key:
160
+ return None
161
+ if not (api_key.isascii() and api_key.isprintable()) or api_key != api_key.strip():
162
+ raise DespConfigError(
163
+ "Invalid DESP API key: it contains non-ASCII or control characters, "
164
+ "or leading/trailing whitespace (check for stray whitespace or copy-paste artifacts)."
165
+ )
166
+ return {"Authorization": f"Bearer {api_key}"}
167
+
168
+
169
+ async def request(
170
+ base_url: str,
171
+ method: str,
172
+ path: str,
173
+ *,
174
+ json: Any = None,
175
+ params: dict[str, Any] | None = None,
176
+ api_key: str | None = None,
177
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
178
+ ) -> Any:
179
+ """
180
+ Call one DESP route and return its decoded JSON body (None for a
181
+ 204 or otherwise empty response). Raises DespConfigError when base_url
182
+ is not a valid URL or api_key cannot be sent as a header, DespApiError on any non-2xx
183
+ (including an unfollowed 3xx redirect),
184
+ DespTimeoutError when DESP does not answer within the timeout,
185
+ DespConnectionError when DESP cannot be reached, DespResponseError
186
+ when a 2xx body is not valid JSON.
187
+
188
+ Args:
189
+ base_url: The base URL of the DESP API.
190
+ method: The HTTP method to use.
191
+ path: The path of the DESP API route.
192
+ json: The JSON body to send.
193
+ params: The query parameters to send.
194
+ api_key: The system API key (aeth_<key_id>_<secret>), sent as a Bearer token.
195
+ timeout: The timeout for the request.
196
+ Returns:
197
+ The decoded JSON body.
198
+ """
199
+
200
+ url = f"{base_url.rstrip('/')}{path}"
201
+ _validate_url(base_url, url)
202
+ headers = _auth_headers(api_key)
203
+
204
+ # Hide httpx from callers: they catch SDK errors only.
205
+ try:
206
+ async with httpx.AsyncClient(timeout=timeout) as client:
207
+ response = await client.request(method, url, json=json, params=params, headers=headers)
208
+ except httpx.TimeoutException as exc:
209
+ raise DespTimeoutError(method, url, timeout) from exc
210
+ except httpx.HTTPError as exc:
211
+ raise DespConnectionError(method, url) from exc
212
+
213
+ return _decode_body(method, url, response)
214
+
215
+
216
+ def request_sync(
217
+ base_url: str,
218
+ method: str,
219
+ path: str,
220
+ *,
221
+ json: Any = None,
222
+ api_key: str | None = None,
223
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
224
+ ) -> Any:
225
+ """
226
+ Blocking twin of request(), for background threads with no event loop.
227
+ Also works during interpreter shutdown, where asyncio's DNS executor
228
+ refuses new work. Raises the same errors as request().
229
+
230
+ Args:
231
+ base_url: The base URL of the DESP API.
232
+ method: The HTTP method to use.
233
+ path: The path of the DESP API route.
234
+ json: The JSON body to send.
235
+ api_key: The system API key (aeth_<key_id>_<secret>), sent as a Bearer token.
236
+ timeout: The timeout for the request.
237
+ Returns:
238
+ The decoded JSON body.
239
+ """
240
+ url = f"{base_url.rstrip('/')}{path}"
241
+ _validate_url(base_url, url)
242
+ headers = _auth_headers(api_key)
243
+
244
+ # Hide httpx from callers: they catch SDK errors only.
245
+ try:
246
+ with httpx.Client(timeout=timeout) as client:
247
+ response = client.request(method, url, json=json, headers=headers)
248
+ except httpx.TimeoutException as exc:
249
+ raise DespTimeoutError(method, url, timeout) from exc
250
+ except httpx.HTTPError as exc:
251
+ raise DespConnectionError(method, url) from exc
252
+
253
+ return _decode_body(method, url, response)
254
+
255
+
256
+ def _decode_body(method: str, url: str, response: httpx.Response) -> Any:
257
+ """
258
+ Turn a finished response into its JSON body, or raise the matching SDK error.
259
+
260
+ Args:
261
+ method: The HTTP method of the request.
262
+ url: The full URL of the request.
263
+ response: The response to decode.
264
+ Returns:
265
+ The decoded JSON body, or None for a 204 or empty body.
266
+ """
267
+ # httpx does not follow redirects, so a 3xx must not pass as success.
268
+ if not response.is_success:
269
+ raise _to_api_error(response)
270
+
271
+ if response.status_code == _NO_CONTENT_STATUS or not response.content:
272
+ return None
273
+
274
+ try:
275
+ return response.json()
276
+ except ValueError as exc:
277
+ raise DespResponseError(method, url, "body is not valid JSON") from exc