spec2py-runtime 0.1.0__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,245 @@
1
+ """Server-sent events and NDJSON streams decoded into typed events.
2
+
3
+ ::
4
+
5
+ with client.completions.stream(prompt="hi") as events:
6
+ for event in events:
7
+ print(event.text)
8
+ """
9
+
10
+ import json
11
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
12
+ from dataclasses import dataclass
13
+ from types import TracebackType
14
+ from typing import Any, Literal, Self, cast
15
+
16
+ import httpx2
17
+ from pydantic import ValidationError
18
+
19
+ from ._exceptions import APIResponseValidationError, APIStatusError
20
+ from ._models import parse_value
21
+
22
+ __all__ = [
23
+ "AsyncStream",
24
+ "AsyncStreamManager",
25
+ "SSEDecoder",
26
+ "ServerSentEvent",
27
+ "Stream",
28
+ "StreamFormat",
29
+ "StreamManager",
30
+ ]
31
+
32
+ type StreamFormat = Literal["sse", "ndjson"]
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class ServerSentEvent:
37
+ """One raw event from a ``text/event-stream`` response."""
38
+
39
+ data: str
40
+ event: str = "message"
41
+ id: str | None = None
42
+ retry: int | None = None
43
+
44
+ def json(self) -> Any:
45
+ return json.loads(self.data)
46
+
47
+
48
+ class SSEDecoder:
49
+ """Incremental decoder for the WHATWG server-sent events line protocol."""
50
+
51
+ def __init__(self) -> None:
52
+ self._event: str | None = None
53
+ self._data: list[str] = []
54
+ self._last_id: str | None = None
55
+ self._retry: int | None = None
56
+
57
+ def decode(self, line: str) -> ServerSentEvent | None:
58
+ """Feed one line (without its terminator); return an event on a blank line."""
59
+ if not line:
60
+ if not self._data and self._event is None:
61
+ return None
62
+ event = ServerSentEvent(
63
+ data="\n".join(self._data),
64
+ event=self._event or "message",
65
+ id=self._last_id,
66
+ retry=self._retry,
67
+ )
68
+ self._event, self._data, self._retry = None, [], None
69
+ return event
70
+ if line.startswith(":"):
71
+ return None
72
+ name, _, value = line.partition(":")
73
+ value = value.removeprefix(" ")
74
+ match name:
75
+ case "event":
76
+ self._event = value
77
+ case "data":
78
+ self._data.append(value)
79
+ case "id" if "\0" not in value:
80
+ self._last_id = value
81
+ case "retry" if value.isdigit():
82
+ self._retry = int(value)
83
+ case _:
84
+ pass
85
+ return None
86
+
87
+ def flush(self) -> ServerSentEvent | None:
88
+ return self.decode("")
89
+
90
+
91
+ class _Decoding[T]:
92
+ def __init__(
93
+ self,
94
+ response: httpx2.Response,
95
+ *,
96
+ event_type: type[T],
97
+ stream_format: StreamFormat,
98
+ terminator: str | None,
99
+ strict: bool = True,
100
+ ) -> None:
101
+ self.response = response
102
+ self._event_type = event_type
103
+ self._format = stream_format
104
+ self._terminator = terminator
105
+ self._strict = strict
106
+
107
+ def _parse(self, data: str) -> T:
108
+ if self._event_type is str:
109
+ return cast(T, data)
110
+ body = json.loads(data)
111
+ try:
112
+ return parse_value(self._event_type, body, strict=self._strict)
113
+ except ValidationError as exc:
114
+ raise APIResponseValidationError(self.response, body, str(exc)) from exc
115
+
116
+ def _raise_error_event(self, sse: ServerSentEvent) -> None:
117
+ try:
118
+ body: object = sse.json()
119
+ except ValueError:
120
+ body = sse.data
121
+ raise APIStatusError(
122
+ "The server sent an error event.", response=self.response, body=body
123
+ )
124
+
125
+ def _handle_sse(self, sse: ServerSentEvent) -> tuple[bool, T | None]:
126
+ """Return ``(stop, event)`` for one raw event."""
127
+ if self._terminator is not None and sse.data == self._terminator:
128
+ return True, None
129
+ if sse.event == "error":
130
+ self._raise_error_event(sse)
131
+ if not sse.data:
132
+ return False, None
133
+ return False, self._parse(sse.data)
134
+
135
+
136
+ class Stream[T](_Decoding[T]):
137
+ """A synchronous iterator of typed events over an open streaming response."""
138
+
139
+ def __iter__(self) -> Iterator[T]:
140
+ if self._format == "ndjson":
141
+ for line in self.response.iter_lines():
142
+ if line.strip():
143
+ yield self._parse(line)
144
+ return
145
+ for sse in self.events():
146
+ stop, event = self._handle_sse(sse)
147
+ if stop:
148
+ return
149
+ if event is not None:
150
+ yield event
151
+
152
+ def events(self) -> Iterator[ServerSentEvent]:
153
+ """Iterate the raw server-sent events, undecoded."""
154
+ decoder = SSEDecoder()
155
+ for line in self.response.iter_lines():
156
+ if (sse := decoder.decode(line)) is not None:
157
+ yield sse
158
+ if (sse := decoder.flush()) is not None:
159
+ yield sse
160
+
161
+ def close(self) -> None:
162
+ self.response.close()
163
+
164
+ def __enter__(self) -> Self:
165
+ return self
166
+
167
+ def __exit__(self, *exc: object) -> None:
168
+ self.close()
169
+
170
+
171
+ class AsyncStream[T](_Decoding[T]):
172
+ """An asynchronous iterator of typed events over an open streaming response."""
173
+
174
+ async def __aiter__(self) -> AsyncIterator[T]:
175
+ if self._format == "ndjson":
176
+ async for line in self.response.aiter_lines():
177
+ if line.strip():
178
+ yield self._parse(line)
179
+ return
180
+ async for sse in self.events():
181
+ stop, event = self._handle_sse(sse)
182
+ if stop:
183
+ return
184
+ if event is not None:
185
+ yield event
186
+
187
+ async def events(self) -> AsyncIterator[ServerSentEvent]:
188
+ """Iterate the raw server-sent events, undecoded."""
189
+ decoder = SSEDecoder()
190
+ async for line in self.response.aiter_lines():
191
+ if (sse := decoder.decode(line)) is not None:
192
+ yield sse
193
+ if (sse := decoder.flush()) is not None:
194
+ yield sse
195
+
196
+ async def close(self) -> None:
197
+ await self.response.aclose()
198
+
199
+ async def __aenter__(self) -> Self:
200
+ return self
201
+
202
+ async def __aexit__(self, *exc: object) -> None:
203
+ await self.close()
204
+
205
+
206
+ class StreamManager[T]:
207
+ """Context manager that opens the stream on enter and closes it on exit."""
208
+
209
+ def __init__(self, open_stream: Callable[[], Stream[T]]) -> None:
210
+ self._open = open_stream
211
+ self._stream: Stream[T] | None = None
212
+
213
+ def __enter__(self) -> Stream[T]:
214
+ self._stream = self._open()
215
+ return self._stream
216
+
217
+ def __exit__(
218
+ self,
219
+ exc_type: type[BaseException] | None,
220
+ exc: BaseException | None,
221
+ tb: TracebackType | None,
222
+ ) -> None:
223
+ if self._stream is not None:
224
+ self._stream.close()
225
+
226
+
227
+ class AsyncStreamManager[T]:
228
+ """Async context manager that opens the stream on enter and closes it on exit."""
229
+
230
+ def __init__(self, open_stream: Callable[[], Awaitable[AsyncStream[T]]]) -> None:
231
+ self._open = open_stream
232
+ self._stream: AsyncStream[T] | None = None
233
+
234
+ async def __aenter__(self) -> AsyncStream[T]:
235
+ self._stream = await self._open()
236
+ return self._stream
237
+
238
+ async def __aexit__(
239
+ self,
240
+ exc_type: type[BaseException] | None,
241
+ exc: BaseException | None,
242
+ tb: TracebackType | None,
243
+ ) -> None:
244
+ if self._stream is not None:
245
+ await self._stream.close()
@@ -0,0 +1,71 @@
1
+ """Shared types: the ``NOT_GIVEN`` sentinel, request option aliases and file types."""
2
+
3
+ import os
4
+ from collections.abc import Mapping
5
+ from typing import IO, Final, Literal, TypeIs, final, override
6
+
7
+ import httpx2
8
+
9
+ __all__ = [
10
+ "NOT_GIVEN",
11
+ "Body",
12
+ "FileContent",
13
+ "FileTypes",
14
+ "Headers",
15
+ "NotGiven",
16
+ "Query",
17
+ "Timeout",
18
+ "TimeoutTypes",
19
+ "is_given",
20
+ ]
21
+
22
+
23
+ @final
24
+ class NotGiven:
25
+ """Marks a parameter the caller did not pass.
26
+
27
+ Distinct from ``None`` so that "omit this field" and "send null" stay different::
28
+
29
+ client.invoices.update("inv_1", memo=None) # sends {"memo": null}
30
+ client.invoices.update("inv_1") # sends {}
31
+ """
32
+
33
+ _instance: NotGiven | None = None
34
+
35
+ def __new__(cls) -> NotGiven:
36
+ if cls._instance is None:
37
+ cls._instance = super().__new__(cls)
38
+ return cls._instance
39
+
40
+ def __bool__(self) -> Literal[False]:
41
+ return False
42
+
43
+ @override
44
+ def __repr__(self) -> str:
45
+ return "NOT_GIVEN"
46
+
47
+ def __reduce__(self) -> str:
48
+ return "NOT_GIVEN"
49
+
50
+
51
+ NOT_GIVEN: Final = NotGiven()
52
+
53
+
54
+ def is_given[T](value: T | NotGiven) -> TypeIs[T]:
55
+ """Return ``True`` unless ``value`` is the ``NOT_GIVEN`` sentinel."""
56
+ return not isinstance(value, NotGiven)
57
+
58
+
59
+ type Timeout = httpx2.Timeout
60
+ type TimeoutTypes = float | httpx2.Timeout | None
61
+ type Headers = Mapping[str, str | NotGiven]
62
+ type Query = Mapping[str, object]
63
+ type Body = Mapping[str, object]
64
+
65
+ type FileContent = IO[bytes] | bytes | os.PathLike[str]
66
+ type FileTypes = (
67
+ FileContent
68
+ | tuple[str | None, FileContent]
69
+ | tuple[str | None, FileContent, str | None]
70
+ | tuple[str | None, FileContent, str | None, Mapping[str, str]]
71
+ )
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
File without changes
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.5
2
+ Name: spec2py-runtime
3
+ Version: 0.1.0
4
+ Summary: Runtime library for spec2py-generated API clients: transport, retries, auth, pagination, streaming and uploads on httpx2 and Pydantic v2.
5
+ Project-URL: Homepage, https://github.com/f4hy/spec2py
6
+ Author-email: Brendan Fahy <bmfahy@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Topic :: Internet :: WWW/HTTP
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.14
17
+ Requires-Dist: anyio>=4.6
18
+ Requires-Dist: httpx2>=2.13
19
+ Requires-Dist: pydantic>=2.12
20
+ Description-Content-Type: text/markdown
21
+
22
+ # spec2py-runtime
23
+
24
+ The runtime library behind clients generated by
25
+ [spec2py](https://github.com/f4hy/spec2py). Generated code only describes
26
+ operations; everything that happens at request time lives here, so a fix
27
+ arrives with a dependency upgrade instead of a regeneration.
28
+
29
+ | Area | Behaviour |
30
+ | --- | --- |
31
+ | Transport | httpx2, with pluggable `transport=` / `http_client=` for tests and custom stacks |
32
+ | Retries | Exponential backoff with jitter. Honours `Retry-After`, `retry-after-ms` and `x-should-retry`. Retries idempotent methods, and POSTs once an idempotency key is attached (generated automatically when the API declares an idempotency header). |
33
+ | Auth | `ApiKeyAuth` (header, query or cookie), `BearerAuth`, `BasicAuth`, `OAuth2ClientCredentials` (fetch, cache, refresh, retry on 401), `MultiAuth`, or any `httpx2.Auth` |
34
+ | Pagination | `CursorPagination`, `OffsetPagination`, `PageNumberPagination`, `LinkHeaderPagination`; `Page` / `AsyncPage` / `AsyncPaginator` iterate lazily and expose `.data` and `.next_cursor` |
35
+ | Streaming | SSE and NDJSON decoded into typed events (`Stream`, `AsyncStream`) |
36
+ | Uploads | Multipart from file objects, paths, bytes or `(name, content, type)` tuples |
37
+ | Errors | `APIError` → `APIStatusError` → `NotFoundError`, `RateLimitError`, ...; bodies parsed into declared models |
38
+ | Observability | `Hooks(on_request=..., on_response=...)` |
39
+ | Models | `BaseModel` with lenient parsing, `Tolerant` enums, lazy validator builds |
40
+
41
+ Requires Python 3.14.
42
+
43
+ ## Validation and compatibility
44
+
45
+ Responses reject missing required fields and invalid field values by default.
46
+ Unknown fields are retained and unknown enum values are tolerated. Set
47
+ `strict_response_validation=False` explicitly for best-effort parsing; its
48
+ results can contain raw values or missing attributes and need defensive handling.
49
+ Requests revalidate generated model instances, including nested instances.
50
+
51
+ The initial generator and generated clients require `spec2py-runtime>=0.1.0,<0.2.0`.
52
+ Within the 0.1 series, runtime patch releases preserve the generated-code API.
53
+ Breaking runtime changes require a new minor series and regeneration to adopt it.
54
+ When emission starts using a new runtime feature, raise the minimum patch version
55
+ in both the generator dependency and generated project metadata. Development
56
+ snapshots before 0.1.0 are not release candidates for this compatibility range.
@@ -0,0 +1,18 @@
1
+ spec2py_runtime/__init__.py,sha256=nu3MVnl7NtEC93jDgp-1eG5wgt525IpFPqLTNd8xWL4,3049
2
+ spec2py_runtime/_auth.py,sha256=ZjeeIAN8TCl120wObSNKPxSH0US-UtVFXh96Jp4a398,5981
3
+ spec2py_runtime/_client.py,sha256=Z4iVM1QVLs1rX9G5_VaRRp0JNs_o3xoxn6tyc7yw30U,28022
4
+ spec2py_runtime/_exceptions.py,sha256=pLQ7P62uT4Mp-lU0Ze8k0hcY_mrW3_u7WlVrh6byGKk,5041
5
+ spec2py_runtime/_files.py,sha256=u_rd4iy1974yfn_UDdHnNlhFwRPDb1lUj33d7YeB_tY,2933
6
+ spec2py_runtime/_models.py,sha256=pjYjya3iroZk9SyojN9_S1rx38x4az2cwTK_tlgO0ag,9507
7
+ spec2py_runtime/_pagination.py,sha256=Oe0fLsDXTdE5djGyBl2y1utjQTQvTyt0liwNWuZo4Co,8962
8
+ spec2py_runtime/_qs.py,sha256=GiQclnjREbInReN_iighL1atIgTKMouqUD-etoKMtqU,3203
9
+ spec2py_runtime/_response.py,sha256=SGE-Sux0iR2YkN7bgGaNbJ3W7fdiEQyAi52807xd36o,2700
10
+ spec2py_runtime/_retry.py,sha256=vGSsDauDoTY9ZwVpfeF-gQcjYBLOF3T9GXuG8yhmByo,2884
11
+ spec2py_runtime/_streaming.py,sha256=f6F4S9dgqJAvWufN1QlhAceMLwtWDTMRKLPS98Yjpe8,7389
12
+ spec2py_runtime/_types.py,sha256=1NPe49G6iIvBXtoCIogD7_8wRaAiSH9Qwsz5ChTYLJ0,1712
13
+ spec2py_runtime/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
14
+ spec2py_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ spec2py_runtime-0.1.0.dist-info/METADATA,sha256=lVs419IA4hyL0su5Cvx9XATg0E0uEPbks4hYwN4XkaA,3221
16
+ spec2py_runtime-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
17
+ spec2py_runtime-0.1.0.dist-info/licenses/LICENSE,sha256=kR6Vo12becqeQBoaV0Rse6SHB0wte_HiJiVza0qwu1k,1069
18
+ spec2py_runtime-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brendan Fahy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.