qucelerate-ai-gateway 0.2.0__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.
@@ -0,0 +1,4 @@
1
+ .venv*/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
@@ -0,0 +1,32 @@
1
+ # Changelog: qucelerate-ai-gateway (Python)
2
+
3
+ All notable changes to this client. Each release has a `## <version>` section,
4
+ which becomes its GitHub release notes (`clients/release/changelog.py`).
5
+ Versions follow semantic versioning; the client implements the gateway's
6
+ inference contract 1.0.0.
7
+
8
+ ## 0.2.0
9
+
10
+ - Renamed for public release: the distribution is `qucelerate-ai-gateway` (was
11
+ `gateway-client`) and the import package `qucelerate_ai_gateway` (was `gateway_client`);
12
+ it is published to PyPI. The User-Agent is `qucelerate-ai-gateway-python/<version>`.
13
+ - Tool calling (D-032): `chat` and `chat_stream` take `tools` (`Tool` or dicts), `tool_choice` and
14
+ `parallel_tool_calls`; `Message` carries `tool_calls` and `tool_call_id`, and `MessageResponse`
15
+ the model's `tool_calls` (`ToolCall`), with `to_message()` to continue the conversation.
16
+ - Batches (OpenAI's Batch API shape): `upload_batch_file`, `create_batch`, `batch`,
17
+ `list_batches`, `cancel_batch` and `file_content`, sync and async. A batch is created
18
+ with an Idempotency-Key; its single read carries the gateway's `gateway` account
19
+ (native or emulated jobs, cost).
20
+
21
+ ## 0.1.0
22
+
23
+ The first release.
24
+
25
+ - A synchronous `Client` and an asyncio `AsyncClient` for chat, streaming chat
26
+ and embeddings. Python 3.9 or later; the only dependency is `httpx`.
27
+ - Streams yield typed events. Each unfinished event is capped at 16 MiB, and
28
+ the client timeout bounds how long a stream takes to start.
29
+ - Response bodies are capped at 64 MiB (configurable), and error bodies at 1 MiB.
30
+ - Errors carry the gateway's problem code, status, request id and `Retry-After`,
31
+ and retryable requests are retried with backoff.
32
+ - Passes the 25 conformance cases.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 QuCelerate
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.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.5
2
+ Name: qucelerate-ai-gateway
3
+ Version: 0.2.0
4
+ Summary: Client for the QuCelerate AI Gateway inference API (contract 1.0.0)
5
+ Project-URL: Homepage, https://gateway.qucelerate.com
6
+ Project-URL: Documentation, https://gateway.qucelerate.com
7
+ Project-URL: Source, https://github.com/qucelerate/ai-gateway/tree/main/clients/python
8
+ Project-URL: Issues, https://github.com/qucelerate/ai-gateway/issues
9
+ Project-URL: Changelog, https://github.com/qucelerate/ai-gateway/blob/main/clients/python/CHANGELOG.md
10
+ Author-email: QuCelerate <opensource@qucelerate.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: ai-gateway,client,inference,llm,openai
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: httpx<1,>=0.27
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=8; extra == 'test'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # qucelerate-ai-gateway (Python)
28
+
29
+ A client for the [QuCelerate AI Gateway](https://gateway.qucelerate.com)
30
+ inference API, contract 1.0.0: chat, streaming chat, and embeddings, with a
31
+ synchronous `Client` and an asyncio `AsyncClient`. Python 3.9 or later; its
32
+ one dependency is `httpx`. It is a transport wrapper: authorization, budgets,
33
+ routing, and settlement stay on the gateway.
34
+
35
+ ```sh
36
+ pip install qucelerate-ai-gateway
37
+ ```
38
+
39
+ ```python
40
+ import os
41
+ from qucelerate_ai_gateway import Client, ChoiceDelta
42
+
43
+ with Client("https://gateway.example.com", os.environ["GATEWAY_API_KEY"]) as client:
44
+ response = client.chat("chat-default", [{"role": "user", "content": "Say hello."}])
45
+ print(response.content, response.usage)
46
+
47
+ with client.chat_stream("chat-default", [{"role": "user", "content": "Say hello."}]) as stream:
48
+ for event in stream:
49
+ if isinstance(event, ChoiceDelta):
50
+ print(event.content_delta or "", end="")
51
+ ```
52
+
53
+ ```python
54
+ from qucelerate_ai_gateway import AsyncClient
55
+
56
+ async with AsyncClient("https://gateway.example.com", api_key) as client:
57
+ response = await client.embeddings("embedding-default", ["first", "second"])
58
+ vectors = response.vectors
59
+ async with await client.chat_stream("chat-default", messages) as stream:
60
+ async for event in stream:
61
+ ...
62
+ ```
63
+
64
+ `python examples/chat.py MODEL PROMPT` runs a chat and a stream against
65
+ `GATEWAY_URL` with `GATEWAY_API_KEY`.
66
+
67
+ ## Behavior
68
+
69
+ - **Idempotency.** Every call sends an `Idempotency-Key`: a generated UUID, or
70
+ the `idempotency_key=` you pass. Its retries reuse it, so the gateway never
71
+ runs or charges the call twice.
72
+ - **Retries.** Only when the gateway refused the request before reserving
73
+ anything (`rate_limit_exceeded`, `concurrency_limit_exceeded`,
74
+ `provider_circuit_open`), at most `max_retries` times (default 2), waiting
75
+ `Retry-After` (at most 60 seconds). Anything that may have reached a
76
+ provider raises, never retries. `clients/conformance/errors.json` lists every
77
+ code.
78
+ - **Errors.** All derive from `GatewayError`. `ProblemError` carries `status`,
79
+ `code` (an open string), `request_id` and `retry_after`; `HTTPError` is an
80
+ error response without a problem body; `StreamError` is a stream's terminal
81
+ `error` event; `ProtocolError` is a stream that closed early or sent an
82
+ event over 16 MiB;
83
+ `TransportError`, `DecodeError` and `ConfigError` cover the rest. A stream
84
+ exposes its `X-Request-Id` header as `stream.request_id`.
85
+ - **Compatibility.** Unknown response fields and stream events are ignored, as
86
+ contract 1.x requires.
87
+ - **Cancellation and timeouts.** Close the stream (or leave its `with` block)
88
+ to stop it; cancelling an `AsyncClient` call closes its connection.
89
+ Non-streaming calls time out after 120 seconds by default (`timeout=`).
90
+ - **Secrets.** The API key never appears in `repr()`.
91
+ - **Limits.** A successful non-streaming body over 64 MiB raises
92
+ `DecodeError` (`max_response_bytes=`); an error body is read up to 1 MiB; a
93
+ stream event over 16 MiB raises `ProtocolError`.
94
+
95
+ ## Tests
96
+
97
+ `pytest` runs `tests/test_conformance.py`, which serves every case of
98
+ `clients/conformance` from a local HTTP server to both clients and checks the
99
+ requests they send and what they return or raise.
@@ -0,0 +1,73 @@
1
+ # qucelerate-ai-gateway (Python)
2
+
3
+ A client for the [QuCelerate AI Gateway](https://gateway.qucelerate.com)
4
+ inference API, contract 1.0.0: chat, streaming chat, and embeddings, with a
5
+ synchronous `Client` and an asyncio `AsyncClient`. Python 3.9 or later; its
6
+ one dependency is `httpx`. It is a transport wrapper: authorization, budgets,
7
+ routing, and settlement stay on the gateway.
8
+
9
+ ```sh
10
+ pip install qucelerate-ai-gateway
11
+ ```
12
+
13
+ ```python
14
+ import os
15
+ from qucelerate_ai_gateway import Client, ChoiceDelta
16
+
17
+ with Client("https://gateway.example.com", os.environ["GATEWAY_API_KEY"]) as client:
18
+ response = client.chat("chat-default", [{"role": "user", "content": "Say hello."}])
19
+ print(response.content, response.usage)
20
+
21
+ with client.chat_stream("chat-default", [{"role": "user", "content": "Say hello."}]) as stream:
22
+ for event in stream:
23
+ if isinstance(event, ChoiceDelta):
24
+ print(event.content_delta or "", end="")
25
+ ```
26
+
27
+ ```python
28
+ from qucelerate_ai_gateway import AsyncClient
29
+
30
+ async with AsyncClient("https://gateway.example.com", api_key) as client:
31
+ response = await client.embeddings("embedding-default", ["first", "second"])
32
+ vectors = response.vectors
33
+ async with await client.chat_stream("chat-default", messages) as stream:
34
+ async for event in stream:
35
+ ...
36
+ ```
37
+
38
+ `python examples/chat.py MODEL PROMPT` runs a chat and a stream against
39
+ `GATEWAY_URL` with `GATEWAY_API_KEY`.
40
+
41
+ ## Behavior
42
+
43
+ - **Idempotency.** Every call sends an `Idempotency-Key`: a generated UUID, or
44
+ the `idempotency_key=` you pass. Its retries reuse it, so the gateway never
45
+ runs or charges the call twice.
46
+ - **Retries.** Only when the gateway refused the request before reserving
47
+ anything (`rate_limit_exceeded`, `concurrency_limit_exceeded`,
48
+ `provider_circuit_open`), at most `max_retries` times (default 2), waiting
49
+ `Retry-After` (at most 60 seconds). Anything that may have reached a
50
+ provider raises, never retries. `clients/conformance/errors.json` lists every
51
+ code.
52
+ - **Errors.** All derive from `GatewayError`. `ProblemError` carries `status`,
53
+ `code` (an open string), `request_id` and `retry_after`; `HTTPError` is an
54
+ error response without a problem body; `StreamError` is a stream's terminal
55
+ `error` event; `ProtocolError` is a stream that closed early or sent an
56
+ event over 16 MiB;
57
+ `TransportError`, `DecodeError` and `ConfigError` cover the rest. A stream
58
+ exposes its `X-Request-Id` header as `stream.request_id`.
59
+ - **Compatibility.** Unknown response fields and stream events are ignored, as
60
+ contract 1.x requires.
61
+ - **Cancellation and timeouts.** Close the stream (or leave its `with` block)
62
+ to stop it; cancelling an `AsyncClient` call closes its connection.
63
+ Non-streaming calls time out after 120 seconds by default (`timeout=`).
64
+ - **Secrets.** The API key never appears in `repr()`.
65
+ - **Limits.** A successful non-streaming body over 64 MiB raises
66
+ `DecodeError` (`max_response_bytes=`); an error body is read up to 1 MiB; a
67
+ stream event over 16 MiB raises `ProtocolError`.
68
+
69
+ ## Tests
70
+
71
+ `pytest` runs `tests/test_conformance.py`, which serves every case of
72
+ `clients/conformance` from a local HTTP server to both clients and checks the
73
+ requests they send and what they return or raise.
@@ -0,0 +1,24 @@
1
+ """GATEWAY_URL=... GATEWAY_API_KEY=gw_... python examples/chat.py chat-default "Say hello."
2
+
3
+ Sends one chat call and one streamed call and prints the answers."""
4
+
5
+ import os
6
+ import sys
7
+
8
+ from qucelerate_ai_gateway import ChoiceDelta, Client, ResponseCompleted
9
+
10
+ model = sys.argv[1] if len(sys.argv) > 1 else "chat-default"
11
+ prompt = sys.argv[2] if len(sys.argv) > 2 else "Say hello."
12
+ messages = [{"role": "user", "content": prompt}]
13
+
14
+ with Client(os.environ["GATEWAY_URL"], os.environ["GATEWAY_API_KEY"]) as client:
15
+ response = client.chat(model, messages, max_tokens=256)
16
+ print("chat:", response.content)
17
+ print("usage:", response.usage)
18
+ print("stream: ", end="")
19
+ with client.chat_stream(model, messages, max_tokens=256) as stream:
20
+ for event in stream:
21
+ if isinstance(event, ChoiceDelta):
22
+ print(event.content_delta or "", end="", flush=True)
23
+ elif isinstance(event, ResponseCompleted):
24
+ print("\nusage:", event.usage)
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "qucelerate-ai-gateway"
7
+ version = "0.2.0"
8
+ description = "Client for the QuCelerate AI Gateway inference API (contract 1.0.0)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = ["httpx>=0.27,<1"]
14
+ keywords = ["llm", "ai-gateway", "openai", "inference", "client"]
15
+ authors = [{ name = "QuCelerate", email = "opensource@qucelerate.com" }]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Framework :: AsyncIO",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://gateway.qucelerate.com"
28
+ Documentation = "https://gateway.qucelerate.com"
29
+ Source = "https://github.com/qucelerate/ai-gateway/tree/main/clients/python"
30
+ Issues = "https://github.com/qucelerate/ai-gateway/issues"
31
+ Changelog = "https://github.com/qucelerate/ai-gateway/blob/main/clients/python/CHANGELOG.md"
32
+
33
+ [project.optional-dependencies]
34
+ test = ["pytest>=8"]
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/qucelerate_ai_gateway"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
@@ -0,0 +1,59 @@
1
+ """A client for the Gateway inference API, contract 1.0.0.
2
+
3
+ from qucelerate_ai_gateway import Client
4
+
5
+ with Client("https://gateway.example.com", api_key) as client:
6
+ response = client.chat("chat-default", [{"role": "user", "content": "Say hello."}])
7
+ print(response.content)
8
+
9
+ The client is a transport wrapper: authorization, budgets, routing and
10
+ settlement stay on the gateway. Every call sends an Idempotency-Key (generated
11
+ unless you pass one) and retries automatically only when the gateway refused
12
+ the request before reserving anything.
13
+ """
14
+
15
+ __version__ = "0.2.0"
16
+
17
+ from ._async import AsyncChatStream, AsyncClient # noqa: E402
18
+ from ._client import ChatStream, Client # noqa: E402
19
+ from ._errors import ( # noqa: E402
20
+ ConfigError,
21
+ DecodeError,
22
+ GatewayError,
23
+ HTTPError,
24
+ ProblemError,
25
+ ProtocolError,
26
+ StreamError,
27
+ TransportError,
28
+ )
29
+ from ._types import ( # noqa: E402
30
+ Batch,
31
+ BatchCounts,
32
+ BatchList,
33
+ ChatResponse,
34
+ Choice,
35
+ ChoiceDelta,
36
+ ChoiceFinished,
37
+ Embedding,
38
+ EmbeddingResponse,
39
+ FileObject,
40
+ Message,
41
+ MessageResponse,
42
+ ResponseCompleted,
43
+ ResponseStarted,
44
+ SafetyAnnotation,
45
+ StreamEvent,
46
+ Tool,
47
+ ToolCall,
48
+ ToolCallDelta,
49
+ Usage,
50
+ UsageReport,
51
+ )
52
+
53
+ __all__ = [
54
+ "AsyncChatStream", "AsyncClient", "Batch", "BatchCounts", "BatchList", "ChatResponse", "ChatStream", "Choice", "ChoiceDelta",
55
+ "ChoiceFinished", "Client", "ConfigError", "DecodeError", "Embedding", "EmbeddingResponse",
56
+ "FileObject", "GatewayError", "HTTPError", "Message", "MessageResponse", "ProblemError", "ProtocolError",
57
+ "ResponseCompleted", "ResponseStarted", "SafetyAnnotation", "StreamError", "StreamEvent",
58
+ "Tool", "ToolCall", "ToolCallDelta", "TransportError", "Usage", "UsageReport", "__version__",
59
+ ]
@@ -0,0 +1,290 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections import deque
5
+ from typing import Any, AsyncIterator, Awaitable, Callable, Deque, Iterable, Mapping, Optional, Sequence, Tuple
6
+
7
+ import httpx
8
+
9
+ from . import _base
10
+ from ._client import _decode
11
+ from ._errors import TransportError
12
+ from ._types import Batch, BatchList, ChatResponse, EmbeddingResponse, FileObject, MessageLike, StreamEvent, ToolChoice, ToolLike
13
+
14
+
15
+ class AsyncClient:
16
+ """An asyncio client for the Gateway inference API, with the same calls
17
+ and behavior as `Client`. Use ``async with``, or ``await close()``.
18
+
19
+ Cancelling a call (for example with ``asyncio.wait_for``) closes its
20
+ connection.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ base_url: str,
26
+ api_key: str,
27
+ *,
28
+ max_retries: int = 2,
29
+ timeout: Optional[float] = None,
30
+ http_client: Optional[httpx.AsyncClient] = None,
31
+ max_response_bytes: int = _base.DEFAULT_MAX_RESPONSE_BYTES,
32
+ _sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
33
+ ) -> None:
34
+ self._settings = _base.Settings(base_url, api_key, max_retries, timeout, max_response_bytes)
35
+ self._http = http_client or httpx.AsyncClient(timeout=httpx.Timeout(self._settings.timeout, connect=10.0))
36
+ self._owns_http = http_client is None
37
+ self._sleep = _sleep
38
+
39
+ def __repr__(self) -> str:
40
+ return f"AsyncClient({self._settings!r})"
41
+
42
+ async def close(self) -> None:
43
+ if self._owns_http:
44
+ await self._http.aclose()
45
+
46
+ async def __aenter__(self) -> "AsyncClient":
47
+ return self
48
+
49
+ async def __aexit__(self, *exc: Any) -> None:
50
+ await self.close()
51
+
52
+ async def chat(
53
+ self,
54
+ model: str,
55
+ messages: Sequence[MessageLike],
56
+ *,
57
+ temperature: Optional[float] = None,
58
+ max_tokens: Optional[int] = None,
59
+ tools: Optional[Sequence[ToolLike]] = None,
60
+ tool_choice: Optional[ToolChoice] = None,
61
+ parallel_tool_calls: Optional[bool] = None,
62
+ idempotency_key: Optional[str] = None,
63
+ request_id: Optional[str] = None,
64
+ ) -> ChatResponse:
65
+ body = _base.chat_body(model, messages, temperature, max_tokens, tools, tool_choice, parallel_tool_calls)
66
+ response, content = await self._send(_base.CHAT_PATH, body, idempotency_key, request_id, stream=False)
67
+ return _decode(ChatResponse.from_dict, response, content)
68
+
69
+ async def embeddings(
70
+ self,
71
+ model: str,
72
+ input: Iterable[str],
73
+ *,
74
+ idempotency_key: Optional[str] = None,
75
+ request_id: Optional[str] = None,
76
+ ) -> EmbeddingResponse:
77
+ body = _base.embedding_body(model, input)
78
+ response, content = await self._send(
79
+ _base.EMBEDDINGS_PATH, body, idempotency_key, request_id, stream=False
80
+ )
81
+ return _decode(EmbeddingResponse.from_dict, response, content)
82
+
83
+ async def chat_stream(
84
+ self,
85
+ model: str,
86
+ messages: Sequence[MessageLike],
87
+ *,
88
+ temperature: Optional[float] = None,
89
+ max_tokens: Optional[int] = None,
90
+ tools: Optional[Sequence[ToolLike]] = None,
91
+ tool_choice: Optional[ToolChoice] = None,
92
+ parallel_tool_calls: Optional[bool] = None,
93
+ idempotency_key: Optional[str] = None,
94
+ request_id: Optional[str] = None,
95
+ ) -> "AsyncChatStream":
96
+ """Stream a chat completion: ``async for event in await client.chat_stream(...)``.
97
+ Use ``async with`` or iterate to the end to close it."""
98
+ body = _base.chat_body(model, messages, temperature, max_tokens, tools, tool_choice, parallel_tool_calls)
99
+ response, _ = await self._send(_base.STREAM_PATH, body, idempotency_key, request_id, stream=True)
100
+ return AsyncChatStream(response)
101
+
102
+ async def upload_batch_file(self, content: bytes, *, filename: str = "batch.jsonl", request_id: Optional[str] = None) -> FileObject:
103
+ """Upload a batch input file: JSONL, one request per line, each
104
+ ``{"custom_id", "method": "POST", "url", "body"}``."""
105
+ response, body = await self._plain(
106
+ "POST", _base.FILES_PATH, None, request_id, write=False,
107
+ files={"file": (filename, content, "application/jsonl")}, data={"purpose": "batch"},
108
+ )
109
+ return _decode(FileObject.from_dict, response, body)
110
+
111
+ async def create_batch(
112
+ self,
113
+ input_file_id: str,
114
+ *,
115
+ endpoint: str = "/v1/chat/completions",
116
+ metadata: Optional[Mapping[str, str]] = None,
117
+ idempotency_key: Optional[str] = None,
118
+ request_id: Optional[str] = None,
119
+ ) -> Batch:
120
+ """Create a batch from an uploaded file. The whole batch is checked,
121
+ routed and reserved when it is created, or refused with nothing
122
+ held. Retry with the same `idempotency_key` to get the same batch."""
123
+ response, body = await self._plain(
124
+ "POST", _base.BATCHES_PATH, idempotency_key, request_id, write=True,
125
+ json=_base.batch_body(input_file_id, endpoint, metadata),
126
+ )
127
+ return _decode(Batch.from_dict, response, body)
128
+
129
+ async def batch(self, batch_id: str, *, request_id: Optional[str] = None) -> Batch:
130
+ """A batch, with the gateway's account of how it runs and its cost."""
131
+ response, body = await self._plain("GET", f"{_base.BATCHES_PATH}/{_base.path_segment(batch_id)}", None, request_id, write=False)
132
+ return _decode(Batch.from_dict, response, body)
133
+
134
+ async def list_batches(self, *, after: Optional[str] = None, limit: Optional[int] = None, request_id: Optional[str] = None) -> BatchList:
135
+ """The API key's service account's batches, newest first."""
136
+ params = {key: value for key, value in (("after", after), ("limit", limit)) if value is not None}
137
+ response, body = await self._plain("GET", _base.BATCHES_PATH, None, request_id, write=False, params=params)
138
+ return _decode(BatchList.from_dict, response, body)
139
+
140
+ async def cancel_batch(self, batch_id: str, *, request_id: Optional[str] = None) -> Batch:
141
+ """Ask a batch to stop: lines not yet run end without a charge."""
142
+ response, body = await self._plain("POST", f"{_base.BATCHES_PATH}/{_base.path_segment(batch_id)}/cancel", None, request_id, write=False)
143
+ return _decode(Batch.from_dict, response, body)
144
+
145
+ async def file_content(self, file_id: str, *, request_id: Optional[str] = None) -> bytes:
146
+ """A file's content: a batch's output or error file is JSONL, one
147
+ line per request line, matched by `custom_id`."""
148
+ _, body = await self._plain("GET", f"{_base.FILES_PATH}/{_base.path_segment(file_id)}/content", None, request_id, write=False)
149
+ return body
150
+
151
+ async def _plain(
152
+ self,
153
+ method: str,
154
+ path: str,
155
+ idempotency_key: Optional[str],
156
+ request_id: Optional[str],
157
+ *,
158
+ write: bool,
159
+ **request: Any,
160
+ ) -> Tuple[httpx.Response, bytes]:
161
+ """A files or batches call, retried only as `_send` retries."""
162
+ headers = _base.plain_headers(self._settings, idempotency_key, request_id, write=write)
163
+ url = self._settings.base_url + path
164
+ retries = 0
165
+ while True:
166
+ try:
167
+ built = self._http.build_request(method, url, headers=headers, timeout=self._settings.timeout, **request)
168
+ response = await self._http.send(built, stream=True)
169
+ except httpx.HTTPError as error:
170
+ raise TransportError(str(error)) from error
171
+ limit = self._settings.max_response_bytes if response.is_success else _base.MAX_ERROR_BODY_BYTES
172
+ reader = _base.BodyReader(limit)
173
+ try:
174
+ async for chunk in response.aiter_bytes():
175
+ if not reader.add(chunk):
176
+ break
177
+ except httpx.HTTPError as error:
178
+ raise TransportError(str(error)) from error
179
+ finally:
180
+ await response.aclose()
181
+ if response.is_success:
182
+ if reader.exceeded:
183
+ raise _base.oversized(limit)
184
+ return response, reader.content()
185
+ error = _base.error_from(response.status_code, response.headers, reader.content())
186
+ wait = _base.retry_wait(error, retries, self._settings.max_retries)
187
+ if wait is None:
188
+ raise error
189
+ retries += 1
190
+ await self._sleep(wait)
191
+
192
+ async def _send(
193
+ self,
194
+ path: str,
195
+ body: Mapping[str, Any],
196
+ idempotency_key: Optional[str],
197
+ request_id: Optional[str],
198
+ *,
199
+ stream: bool,
200
+ ) -> Tuple[httpx.Response, bytes]:
201
+ headers, content = _base.prepare(self._settings, body, idempotency_key, request_id)
202
+ url = self._settings.base_url + path
203
+ retries = 0
204
+ while True:
205
+ request = self._http.build_request(
206
+ "POST", url, headers=headers, content=content,
207
+ timeout=_base.stream_timeout(self._settings.timeout) if stream else self._settings.timeout,
208
+ )
209
+ try:
210
+ response = await self._http.send(request, stream=True)
211
+ except httpx.HTTPError as error:
212
+ raise TransportError(str(error)) from error
213
+ if response.is_success and stream:
214
+ return response, b""
215
+ limit = self._settings.max_response_bytes if response.is_success else _base.MAX_ERROR_BODY_BYTES
216
+ reader = _base.BodyReader(limit)
217
+ try:
218
+ async for chunk in response.aiter_bytes():
219
+ if not reader.add(chunk):
220
+ break
221
+ except httpx.HTTPError as error:
222
+ raise TransportError(str(error)) from error
223
+ finally:
224
+ await response.aclose()
225
+ if response.is_success:
226
+ if reader.exceeded:
227
+ raise _base.oversized(limit)
228
+ return response, reader.content()
229
+ error = _base.error_from(response.status_code, response.headers, reader.content())
230
+ wait = _base.retry_wait(error, retries, self._settings.max_retries)
231
+ if wait is None:
232
+ raise error
233
+ retries += 1
234
+ await self._sleep(wait)
235
+
236
+
237
+ class AsyncChatStream:
238
+ """The events of a streamed chat completion, for ``async for``."""
239
+
240
+ def __init__(self, response: httpx.Response) -> None:
241
+ self._response = response
242
+ self.request_id: Optional[str] = response.headers.get("x-request-id")
243
+ self._decoder = _base.EventDecoder()
244
+ self._pending: Deque[StreamEvent] = deque()
245
+ self._chunks: Optional[AsyncIterator[bytes]] = None
246
+ self._error: Optional[Exception] = None
247
+
248
+ def __aiter__(self) -> "AsyncChatStream":
249
+ return self
250
+
251
+ async def __anext__(self) -> StreamEvent:
252
+ try:
253
+ return await self._next()
254
+ except BaseException:
255
+ await self.aclose()
256
+ raise
257
+
258
+ async def _next(self) -> StreamEvent:
259
+ while True:
260
+ if self._pending:
261
+ return self._pending.popleft()
262
+ if self._error is not None:
263
+ error, self._error = self._error, None
264
+ raise error
265
+ if self._decoder.done:
266
+ await self.aclose()
267
+ raise StopAsyncIteration
268
+ if self._chunks is None:
269
+ self._chunks = self._response.aiter_bytes()
270
+ try:
271
+ chunk = await self._chunks.__anext__()
272
+ except StopAsyncIteration:
273
+ self._decoder.end()
274
+ continue
275
+ except httpx.HTTPError as error:
276
+ raise TransportError(str(error)) from error
277
+ try:
278
+ self._pending.extend(self._decoder.feed(chunk))
279
+ except _base._PendingStreamError as pending:
280
+ self._pending.extend(pending.events)
281
+ self._error = pending.error
282
+
283
+ async def aclose(self) -> None:
284
+ await self._response.aclose()
285
+
286
+ async def __aenter__(self) -> "AsyncChatStream":
287
+ return self
288
+
289
+ async def __aexit__(self, *exc: Any) -> None:
290
+ await self.aclose()