antinet 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.
- anet/__init__.py +34 -0
- anet/_client.py +284 -0
- anet/_errors.py +51 -0
- anet/_pipe.py +178 -0
- anet/_routes.py +131 -0
- anet/_transport.py +97 -0
- anet/_types.py +183 -0
- anet/integrations/__init__.py +1 -0
- anet/integrations/langchain.py +72 -0
- anet/py.typed +0 -0
- antinet-0.1.0.dist-info/METADATA +13 -0
- antinet-0.1.0.dist-info/RECORD +14 -0
- antinet-0.1.0.dist-info/WHEEL +4 -0
- antinet-0.1.0.dist-info/licenses/LICENSE +202 -0
anet/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""The local Antinet service from Python (specs/0055).
|
|
2
|
+
|
|
3
|
+
import anet
|
|
4
|
+
client = anet.connect()
|
|
5
|
+
reply = client.openai().chat.completions.create(model="qwen3", messages=[...])
|
|
6
|
+
decision = client.decide("sensor-pattern", case)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._client import AsyncClient, Client, connect, connect_async
|
|
10
|
+
from ._errors import AnetError
|
|
11
|
+
from ._types import (
|
|
12
|
+
Decision,
|
|
13
|
+
Explanation,
|
|
14
|
+
TypedAnswer,
|
|
15
|
+
TypedDecision,
|
|
16
|
+
choice,
|
|
17
|
+
score,
|
|
18
|
+
yes_or_no,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"AnetError",
|
|
23
|
+
"AsyncClient",
|
|
24
|
+
"Client",
|
|
25
|
+
"Decision",
|
|
26
|
+
"Explanation",
|
|
27
|
+
"TypedAnswer",
|
|
28
|
+
"TypedDecision",
|
|
29
|
+
"choice",
|
|
30
|
+
"connect",
|
|
31
|
+
"connect_async",
|
|
32
|
+
"score",
|
|
33
|
+
"yes_or_no",
|
|
34
|
+
]
|
anet/_client.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""``anet.connect()`` and ``anet.connect_async()`` (specs/0055, PY-1 to PY-5)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any, TypeVar
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from . import _routes as routes
|
|
10
|
+
from ._errors import AnetError
|
|
11
|
+
from ._transport import (
|
|
12
|
+
BASE_URL,
|
|
13
|
+
PLACEHOLDER_KEY,
|
|
14
|
+
Credentials,
|
|
15
|
+
async_transport,
|
|
16
|
+
resolve_socket,
|
|
17
|
+
sync_transport,
|
|
18
|
+
)
|
|
19
|
+
from ._types import Decision, Explanation, TypedDecision
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
import openai
|
|
23
|
+
|
|
24
|
+
T = TypeVar("T")
|
|
25
|
+
|
|
26
|
+
# Generation and blocking explanations can take minutes on the CPU floor;
|
|
27
|
+
# connecting to a local socket never should.
|
|
28
|
+
DEFAULT_TIMEOUT = httpx.Timeout(600.0, connect=10.0, pool=None)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _openai_module() -> Any:
|
|
32
|
+
try:
|
|
33
|
+
import openai
|
|
34
|
+
except ImportError as error:
|
|
35
|
+
raise ImportError("client.openai() needs the openai extra: pip install 'anet[openai]'") from error
|
|
36
|
+
return openai
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _unreachable(path: str, error: httpx.TransportError) -> AnetError:
|
|
40
|
+
return AnetError(None, None, f"could not reach the service at {path}: {error}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Client:
|
|
44
|
+
"""One connection to the local service.
|
|
45
|
+
|
|
46
|
+
Without ``login``, the service knows the caller by its operating-system
|
|
47
|
+
account, which the site binds to a program. After ``login``, every
|
|
48
|
+
request through this client, the OpenAI client it hands out included,
|
|
49
|
+
is the person's. Requests on one client take turns on its connection;
|
|
50
|
+
open more clients for parallel calls.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, socket: str | None = None, *, timeout: httpx.Timeout = DEFAULT_TIMEOUT):
|
|
54
|
+
self.socket = resolve_socket(socket)
|
|
55
|
+
self._credentials = Credentials()
|
|
56
|
+
self._http = httpx.Client(
|
|
57
|
+
base_url=BASE_URL,
|
|
58
|
+
transport=sync_transport(self.socket, self._credentials),
|
|
59
|
+
timeout=timeout,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def http(self) -> httpx.Client:
|
|
64
|
+
"""The httpx client over the socket or pipe, for other SDKs."""
|
|
65
|
+
return self._http
|
|
66
|
+
|
|
67
|
+
def _send(self, call: routes.Call[T]) -> T:
|
|
68
|
+
try:
|
|
69
|
+
response = self._http.request(call.method, call.path, json=call.body, params=call.params)
|
|
70
|
+
except httpx.TransportError as error:
|
|
71
|
+
raise _unreachable(self.socket, error) from error
|
|
72
|
+
return call.answer(response)
|
|
73
|
+
|
|
74
|
+
def login(self, name: str, password: str) -> None:
|
|
75
|
+
self._credentials.token = self._send(routes.login(name, password))
|
|
76
|
+
|
|
77
|
+
def logout(self) -> None:
|
|
78
|
+
self._send(routes.logout())
|
|
79
|
+
self._credentials.token = None
|
|
80
|
+
|
|
81
|
+
def openai(self) -> openai.OpenAI:
|
|
82
|
+
"""The official OpenAI client over this connection, retries off."""
|
|
83
|
+
return _openai_module().OpenAI(
|
|
84
|
+
base_url=f"{BASE_URL}/v1", api_key=PLACEHOLDER_KEY, http_client=self._http, max_retries=0
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def models(self) -> list[dict[str, Any]]:
|
|
88
|
+
return self._send(routes.models())
|
|
89
|
+
|
|
90
|
+
def load_model(self, name: str) -> dict[str, Any]:
|
|
91
|
+
return self._send(routes.load_model(name))
|
|
92
|
+
|
|
93
|
+
def unload_model(self, name: str) -> dict[str, Any]:
|
|
94
|
+
return self._send(routes.unload_model(name))
|
|
95
|
+
|
|
96
|
+
def status(self) -> dict[str, Any]:
|
|
97
|
+
return self._send(routes.status())
|
|
98
|
+
|
|
99
|
+
def tasks(self) -> list[dict[str, Any]]:
|
|
100
|
+
return self._send(routes.tasks())
|
|
101
|
+
|
|
102
|
+
def load_task(self, task: str) -> dict[str, Any]:
|
|
103
|
+
return self._send(routes.load_task(task))
|
|
104
|
+
|
|
105
|
+
def unload_task(self, task: str) -> dict[str, Any]:
|
|
106
|
+
return self._send(routes.unload_task(task))
|
|
107
|
+
|
|
108
|
+
def decide(self, task: str, case: dict[str, Any]) -> Decision:
|
|
109
|
+
return self._send(routes.decide(task, case))
|
|
110
|
+
|
|
111
|
+
def explanation(self, task: str, decision_id: str) -> Explanation:
|
|
112
|
+
"""Waits until the explanation is written or has failed."""
|
|
113
|
+
return self._send(routes.explanation(task, decision_id))
|
|
114
|
+
|
|
115
|
+
def act(
|
|
116
|
+
self,
|
|
117
|
+
task: str,
|
|
118
|
+
decision_id: str,
|
|
119
|
+
action: str,
|
|
120
|
+
*,
|
|
121
|
+
assignee: str | None = None,
|
|
122
|
+
comment: str | None = None,
|
|
123
|
+
) -> None:
|
|
124
|
+
"""A person's action on a decision: confirm, dismiss or reassign."""
|
|
125
|
+
self._send(routes.act(task, decision_id, action, assignee, comment))
|
|
126
|
+
|
|
127
|
+
def records(self, from_seq: int | None = None, to_seq: int | None = None) -> dict[str, Any]:
|
|
128
|
+
return self._send(routes.records(from_seq, to_seq))
|
|
129
|
+
|
|
130
|
+
def typed_models(self) -> list[dict[str, Any]]:
|
|
131
|
+
return self._send(routes.typed_models())
|
|
132
|
+
|
|
133
|
+
def load_typed(self, name: str) -> dict[str, Any]:
|
|
134
|
+
return self._send(routes.load_typed(name))
|
|
135
|
+
|
|
136
|
+
def unload_typed(self, name: str) -> dict[str, Any]:
|
|
137
|
+
return self._send(routes.unload_typed(name))
|
|
138
|
+
|
|
139
|
+
def decide_typed(self, model: str, state: Any, questions: dict[str, Any]) -> TypedDecision:
|
|
140
|
+
return self._send(routes.decide_typed(model, state, questions))
|
|
141
|
+
|
|
142
|
+
def act_typed(
|
|
143
|
+
self,
|
|
144
|
+
model: str,
|
|
145
|
+
decision_id: str,
|
|
146
|
+
action: str,
|
|
147
|
+
*,
|
|
148
|
+
assignee: str | None = None,
|
|
149
|
+
comment: str | None = None,
|
|
150
|
+
) -> None:
|
|
151
|
+
self._send(routes.act_typed(model, decision_id, action, assignee, comment))
|
|
152
|
+
|
|
153
|
+
def close(self) -> None:
|
|
154
|
+
self._http.close()
|
|
155
|
+
|
|
156
|
+
def __enter__(self) -> Client:
|
|
157
|
+
return self
|
|
158
|
+
|
|
159
|
+
def __exit__(self, *exception: object) -> None:
|
|
160
|
+
self.close()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class AsyncClient:
|
|
164
|
+
"""``Client`` for asyncio, on a connection of its own; a person logs in
|
|
165
|
+
on it separately."""
|
|
166
|
+
|
|
167
|
+
def __init__(self, socket: str | None = None, *, timeout: httpx.Timeout = DEFAULT_TIMEOUT):
|
|
168
|
+
self.socket = resolve_socket(socket)
|
|
169
|
+
self._credentials = Credentials()
|
|
170
|
+
self._http = httpx.AsyncClient(
|
|
171
|
+
base_url=BASE_URL,
|
|
172
|
+
transport=async_transport(self.socket, self._credentials),
|
|
173
|
+
timeout=timeout,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def http(self) -> httpx.AsyncClient:
|
|
178
|
+
return self._http
|
|
179
|
+
|
|
180
|
+
async def _send(self, call: routes.Call[T]) -> T:
|
|
181
|
+
try:
|
|
182
|
+
response = await self._http.request(
|
|
183
|
+
call.method, call.path, json=call.body, params=call.params
|
|
184
|
+
)
|
|
185
|
+
except httpx.TransportError as error:
|
|
186
|
+
raise _unreachable(self.socket, error) from error
|
|
187
|
+
return call.answer(response)
|
|
188
|
+
|
|
189
|
+
async def login(self, name: str, password: str) -> None:
|
|
190
|
+
self._credentials.token = await self._send(routes.login(name, password))
|
|
191
|
+
|
|
192
|
+
async def logout(self) -> None:
|
|
193
|
+
await self._send(routes.logout())
|
|
194
|
+
self._credentials.token = None
|
|
195
|
+
|
|
196
|
+
def openai(self) -> openai.AsyncOpenAI:
|
|
197
|
+
return _openai_module().AsyncOpenAI(
|
|
198
|
+
base_url=f"{BASE_URL}/v1", api_key=PLACEHOLDER_KEY, http_client=self._http, max_retries=0
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
async def models(self) -> list[dict[str, Any]]:
|
|
202
|
+
return await self._send(routes.models())
|
|
203
|
+
|
|
204
|
+
async def load_model(self, name: str) -> dict[str, Any]:
|
|
205
|
+
return await self._send(routes.load_model(name))
|
|
206
|
+
|
|
207
|
+
async def unload_model(self, name: str) -> dict[str, Any]:
|
|
208
|
+
return await self._send(routes.unload_model(name))
|
|
209
|
+
|
|
210
|
+
async def status(self) -> dict[str, Any]:
|
|
211
|
+
return await self._send(routes.status())
|
|
212
|
+
|
|
213
|
+
async def tasks(self) -> list[dict[str, Any]]:
|
|
214
|
+
return await self._send(routes.tasks())
|
|
215
|
+
|
|
216
|
+
async def load_task(self, task: str) -> dict[str, Any]:
|
|
217
|
+
return await self._send(routes.load_task(task))
|
|
218
|
+
|
|
219
|
+
async def unload_task(self, task: str) -> dict[str, Any]:
|
|
220
|
+
return await self._send(routes.unload_task(task))
|
|
221
|
+
|
|
222
|
+
async def decide(self, task: str, case: dict[str, Any]) -> Decision:
|
|
223
|
+
return await self._send(routes.decide(task, case))
|
|
224
|
+
|
|
225
|
+
async def explanation(self, task: str, decision_id: str) -> Explanation:
|
|
226
|
+
return await self._send(routes.explanation(task, decision_id))
|
|
227
|
+
|
|
228
|
+
async def act(
|
|
229
|
+
self,
|
|
230
|
+
task: str,
|
|
231
|
+
decision_id: str,
|
|
232
|
+
action: str,
|
|
233
|
+
*,
|
|
234
|
+
assignee: str | None = None,
|
|
235
|
+
comment: str | None = None,
|
|
236
|
+
) -> None:
|
|
237
|
+
await self._send(routes.act(task, decision_id, action, assignee, comment))
|
|
238
|
+
|
|
239
|
+
async def records(self, from_seq: int | None = None, to_seq: int | None = None) -> dict[str, Any]:
|
|
240
|
+
return await self._send(routes.records(from_seq, to_seq))
|
|
241
|
+
|
|
242
|
+
async def typed_models(self) -> list[dict[str, Any]]:
|
|
243
|
+
return await self._send(routes.typed_models())
|
|
244
|
+
|
|
245
|
+
async def load_typed(self, name: str) -> dict[str, Any]:
|
|
246
|
+
return await self._send(routes.load_typed(name))
|
|
247
|
+
|
|
248
|
+
async def unload_typed(self, name: str) -> dict[str, Any]:
|
|
249
|
+
return await self._send(routes.unload_typed(name))
|
|
250
|
+
|
|
251
|
+
async def decide_typed(self, model: str, state: Any, questions: dict[str, Any]) -> TypedDecision:
|
|
252
|
+
return await self._send(routes.decide_typed(model, state, questions))
|
|
253
|
+
|
|
254
|
+
async def act_typed(
|
|
255
|
+
self,
|
|
256
|
+
model: str,
|
|
257
|
+
decision_id: str,
|
|
258
|
+
action: str,
|
|
259
|
+
*,
|
|
260
|
+
assignee: str | None = None,
|
|
261
|
+
comment: str | None = None,
|
|
262
|
+
) -> None:
|
|
263
|
+
await self._send(routes.act_typed(model, decision_id, action, assignee, comment))
|
|
264
|
+
|
|
265
|
+
async def aclose(self) -> None:
|
|
266
|
+
await self._http.aclose()
|
|
267
|
+
|
|
268
|
+
async def __aenter__(self) -> AsyncClient:
|
|
269
|
+
return self
|
|
270
|
+
|
|
271
|
+
async def __aexit__(self, *exception: object) -> None:
|
|
272
|
+
await self.aclose()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def connect(socket: str | None = None, *, timeout: httpx.Timeout = DEFAULT_TIMEOUT) -> Client:
|
|
276
|
+
"""A client of the local service at ``socket``, else ``$ANET_SOCKET``,
|
|
277
|
+
else the platform's default socket or pipe."""
|
|
278
|
+
return Client(socket, timeout=timeout)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def connect_async(
|
|
282
|
+
socket: str | None = None, *, timeout: httpx.Timeout = DEFAULT_TIMEOUT
|
|
283
|
+
) -> AsyncClient:
|
|
284
|
+
return AsyncClient(socket, timeout=timeout)
|
anet/_errors.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""The one exception the SDK raises (specs/0055, PY-7)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AnetError(Exception):
|
|
9
|
+
"""The service refused a request, or could not be reached.
|
|
10
|
+
|
|
11
|
+
``status`` is the HTTP status (``None`` when no answer came), ``code`` the
|
|
12
|
+
service's own code for the refusal, such as ``unbound_peer`` or
|
|
13
|
+
``MODEL_NOT_LOADED``, and ``message`` its explanation.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, status: int | None, code: str | None, message: str) -> None:
|
|
17
|
+
super().__init__(f"{status} {code}: {message}" if status else message)
|
|
18
|
+
self.status = status
|
|
19
|
+
self.code = code
|
|
20
|
+
self.message = message
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def error_from_response(response: httpx.Response) -> AnetError:
|
|
24
|
+
"""Reads whichever of the service's error shapes the route answered with.
|
|
25
|
+
|
|
26
|
+
- OpenAI family: ``{"error": {"message", "type": <service code>, "code": <status>}}``
|
|
27
|
+
- Responses: ``{"error": {"message", "type", "param", "code": <service code>}}``
|
|
28
|
+
- Messages: ``{"type": "error", "error": {"type", "message", "code": <service code>}}``
|
|
29
|
+
- typed decisions: ``{"error": <message>, "code": <CODE>}``
|
|
30
|
+
"""
|
|
31
|
+
try:
|
|
32
|
+
body = response.json()
|
|
33
|
+
except ValueError:
|
|
34
|
+
return AnetError(response.status_code, None, response.text or response.reason_phrase)
|
|
35
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
36
|
+
if isinstance(error, str):
|
|
37
|
+
code = body.get("code")
|
|
38
|
+
return AnetError(response.status_code, code if isinstance(code, str) else None, error)
|
|
39
|
+
if isinstance(error, dict):
|
|
40
|
+
message = str(error.get("message", response.reason_phrase))
|
|
41
|
+
service_code = error.get("code")
|
|
42
|
+
if isinstance(service_code, str):
|
|
43
|
+
return AnetError(response.status_code, service_code, message)
|
|
44
|
+
kind = error.get("type")
|
|
45
|
+
return AnetError(response.status_code, kind if isinstance(kind, str) else None, message)
|
|
46
|
+
return AnetError(response.status_code, None, response.text)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def raise_for_error(response: httpx.Response) -> None:
|
|
50
|
+
if not response.is_success:
|
|
51
|
+
raise error_from_response(response)
|
anet/_pipe.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""The service's named pipe on Windows, through httpcore's network-backend
|
|
2
|
+
interface (specs/0055, PY-10).
|
|
3
|
+
|
|
4
|
+
httpx has no transport for a named pipe, but its connection pool takes any
|
|
5
|
+
backend whose streams read and write bytes. A pipe opens as a file; when
|
|
6
|
+
every instance is busy, ``WaitNamedPipe`` waits for one to free up. Pipe
|
|
7
|
+
reads have no timeout of their own: the service's bounds end every request.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import time
|
|
14
|
+
import typing
|
|
15
|
+
|
|
16
|
+
import httpcore
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
ERROR_PIPE_BUSY = 231
|
|
20
|
+
_BUSY_WAIT_MILLISECONDS = 10_000
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _open_pipe(path: str) -> typing.BinaryIO:
|
|
24
|
+
"""Opens the pipe with ``CreateFile``, since ``open`` reports a busy pipe
|
|
25
|
+
as ``EINVAL`` without its Windows error. Another client can take the
|
|
26
|
+
instance ``WaitNamedPipe`` reported free, so the wait is repeated until
|
|
27
|
+
the deadline."""
|
|
28
|
+
import msvcrt
|
|
29
|
+
import os
|
|
30
|
+
|
|
31
|
+
import _winapi # type: ignore[import-not-found]
|
|
32
|
+
|
|
33
|
+
deadline = time.monotonic() + _BUSY_WAIT_MILLISECONDS / 1000
|
|
34
|
+
while True:
|
|
35
|
+
try:
|
|
36
|
+
handle = _winapi.CreateFile(
|
|
37
|
+
path,
|
|
38
|
+
_winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
|
|
39
|
+
0,
|
|
40
|
+
_winapi.NULL,
|
|
41
|
+
_winapi.OPEN_EXISTING,
|
|
42
|
+
0,
|
|
43
|
+
_winapi.NULL,
|
|
44
|
+
)
|
|
45
|
+
break
|
|
46
|
+
except OSError as error:
|
|
47
|
+
left = deadline - time.monotonic()
|
|
48
|
+
if getattr(error, "winerror", None) != ERROR_PIPE_BUSY or left <= 0:
|
|
49
|
+
# A connect error, as httpcore's own backends raise, so the
|
|
50
|
+
# client names the pipe it could not reach.
|
|
51
|
+
raise httpcore.ConnectError(f"{path}: {error.strerror}") from error
|
|
52
|
+
try:
|
|
53
|
+
_winapi.WaitNamedPipe(path, max(1, int(left * 1000)))
|
|
54
|
+
except OSError as error:
|
|
55
|
+
# The wait timed out, or the instance went before the wait began.
|
|
56
|
+
if time.monotonic() >= deadline:
|
|
57
|
+
raise httpcore.ConnectError(f"{path} stayed busy") from error
|
|
58
|
+
descriptor = msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_BINARY)
|
|
59
|
+
return os.fdopen(descriptor, "r+b", buffering=0)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _PipeStream(httpcore.NetworkStream):
|
|
63
|
+
def __init__(self, pipe: typing.BinaryIO) -> None:
|
|
64
|
+
self._pipe = pipe
|
|
65
|
+
|
|
66
|
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
|
67
|
+
try:
|
|
68
|
+
data = self._pipe.read(max_bytes)
|
|
69
|
+
except BrokenPipeError:
|
|
70
|
+
# The service closed its end; to HTTP that is the end of the stream.
|
|
71
|
+
return b""
|
|
72
|
+
if data is None:
|
|
73
|
+
raise OSError("the pipe returned no bytes from a blocking read")
|
|
74
|
+
return data
|
|
75
|
+
|
|
76
|
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
|
77
|
+
view = memoryview(buffer)
|
|
78
|
+
while view:
|
|
79
|
+
written = self._pipe.write(view)
|
|
80
|
+
if written is None:
|
|
81
|
+
raise OSError("the pipe accepted no bytes")
|
|
82
|
+
view = view[written:]
|
|
83
|
+
|
|
84
|
+
def close(self) -> None:
|
|
85
|
+
self._pipe.close()
|
|
86
|
+
|
|
87
|
+
def get_extra_info(self, info: str) -> typing.Any:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class _PipeBackend(httpcore.NetworkBackend):
|
|
92
|
+
def __init__(self, path: str) -> None:
|
|
93
|
+
self._path = path
|
|
94
|
+
|
|
95
|
+
def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
|
|
96
|
+
return _PipeStream(_open_pipe(self._path))
|
|
97
|
+
|
|
98
|
+
def connect_unix_socket(self, path, timeout=None, socket_options=None):
|
|
99
|
+
raise httpcore.ConnectError("the service is reached through its named pipe")
|
|
100
|
+
|
|
101
|
+
def sleep(self, seconds: float) -> None:
|
|
102
|
+
time.sleep(seconds)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class _AsyncPipeStream(httpcore.AsyncNetworkStream):
|
|
106
|
+
def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
|
107
|
+
self._reader = reader
|
|
108
|
+
self._writer = writer
|
|
109
|
+
|
|
110
|
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
|
111
|
+
return await self._reader.read(max_bytes)
|
|
112
|
+
|
|
113
|
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
|
114
|
+
self._writer.write(buffer)
|
|
115
|
+
await self._writer.drain()
|
|
116
|
+
|
|
117
|
+
async def aclose(self) -> None:
|
|
118
|
+
self._writer.close()
|
|
119
|
+
await self._writer.wait_closed()
|
|
120
|
+
|
|
121
|
+
def get_extra_info(self, info: str) -> typing.Any:
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class _AsyncPipeBackend(httpcore.AsyncNetworkBackend):
|
|
126
|
+
def __init__(self, path: str) -> None:
|
|
127
|
+
self._path = path
|
|
128
|
+
|
|
129
|
+
async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
|
|
130
|
+
loop = asyncio.get_running_loop()
|
|
131
|
+
for attempt in range(2):
|
|
132
|
+
reader = asyncio.StreamReader(loop=loop)
|
|
133
|
+
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
|
|
134
|
+
try:
|
|
135
|
+
transport, _ = await loop.create_pipe_connection( # type: ignore[attr-defined]
|
|
136
|
+
lambda: protocol, self._path
|
|
137
|
+
)
|
|
138
|
+
except OSError as error:
|
|
139
|
+
if attempt or getattr(error, "winerror", None) != ERROR_PIPE_BUSY:
|
|
140
|
+
raise httpcore.ConnectError(f"{self._path}: {error.strerror}") from error
|
|
141
|
+
import _winapi # type: ignore[import-not-found]
|
|
142
|
+
|
|
143
|
+
await loop.run_in_executor(
|
|
144
|
+
None, _winapi.WaitNamedPipe, self._path, _BUSY_WAIT_MILLISECONDS
|
|
145
|
+
)
|
|
146
|
+
continue
|
|
147
|
+
return _AsyncPipeStream(reader, asyncio.StreamWriter(transport, protocol, reader, loop))
|
|
148
|
+
raise httpcore.ConnectError(f"{self._path} stayed busy")
|
|
149
|
+
|
|
150
|
+
async def connect_unix_socket(self, path, timeout=None, socket_options=None):
|
|
151
|
+
raise httpcore.ConnectError("the service is reached through its named pipe")
|
|
152
|
+
|
|
153
|
+
async def sleep(self, seconds: float) -> None:
|
|
154
|
+
await asyncio.sleep(seconds)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def sync_pipe_transport(path: str, limits: httpx.Limits) -> httpx.HTTPTransport:
|
|
158
|
+
transport = httpx.HTTPTransport(limits=limits)
|
|
159
|
+
# httpx 0.28 builds its pool without a way to pass a backend; the pool is
|
|
160
|
+
# replaced with one of the same limits over the pipe.
|
|
161
|
+
transport._pool = httpcore.ConnectionPool(
|
|
162
|
+
max_connections=limits.max_connections,
|
|
163
|
+
max_keepalive_connections=limits.max_keepalive_connections,
|
|
164
|
+
keepalive_expiry=limits.keepalive_expiry,
|
|
165
|
+
network_backend=_PipeBackend(path),
|
|
166
|
+
)
|
|
167
|
+
return transport
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def async_pipe_transport(path: str, limits: httpx.Limits) -> httpx.AsyncHTTPTransport:
|
|
171
|
+
transport = httpx.AsyncHTTPTransport(limits=limits)
|
|
172
|
+
transport._pool = httpcore.AsyncConnectionPool(
|
|
173
|
+
max_connections=limits.max_connections,
|
|
174
|
+
max_keepalive_connections=limits.max_keepalive_connections,
|
|
175
|
+
keepalive_expiry=limits.keepalive_expiry,
|
|
176
|
+
network_backend=_AsyncPipeBackend(path),
|
|
177
|
+
)
|
|
178
|
+
return transport
|
anet/_routes.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Every route the SDK calls, once (specs/0055, Design): each function
|
|
2
|
+
returns a ``Call`` that the sync and the async client send the same way."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Callable, Generic, TypeVar
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._errors import raise_for_error
|
|
13
|
+
from ._types import Decision, Explanation, TypedDecision, action_body
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Call(Generic[T]):
|
|
20
|
+
method: str
|
|
21
|
+
path: str
|
|
22
|
+
body: dict[str, Any] | None
|
|
23
|
+
read: Callable[[Any], T]
|
|
24
|
+
params: dict[str, int] | None = None
|
|
25
|
+
|
|
26
|
+
def answer(self, response: httpx.Response) -> T:
|
|
27
|
+
raise_for_error(response)
|
|
28
|
+
if response.status_code == 204:
|
|
29
|
+
return self.read(None)
|
|
30
|
+
return self.read(response.json())
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _segment(name: str) -> str:
|
|
34
|
+
return quote(name, safe="")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _json(body: Any) -> Any:
|
|
38
|
+
return body
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _nothing(_body: Any) -> None:
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _listed(body: Any) -> list[dict[str, Any]]:
|
|
46
|
+
return body["data"]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def login(name: str, password: str) -> Call[str]:
|
|
50
|
+
return Call("POST", "/v1/login", {"name": name, "password": password}, lambda body: body["token"])
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def logout() -> Call[None]:
|
|
54
|
+
return Call("POST", "/v1/logout", None, _nothing)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def models() -> Call[list[dict[str, Any]]]:
|
|
58
|
+
return Call("GET", "/v1/models", None, _listed)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_model(name: str) -> Call[dict[str, Any]]:
|
|
62
|
+
return Call("POST", "/v1/models/load", {"model": name}, _json)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def unload_model(name: str) -> Call[dict[str, Any]]:
|
|
66
|
+
return Call("POST", "/v1/models/unload", {"model": name}, _json)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def status() -> Call[dict[str, Any]]:
|
|
70
|
+
return Call("GET", "/v1/status", None, _json)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def tasks() -> Call[list[dict[str, Any]]]:
|
|
74
|
+
return Call("GET", "/v1/tasks", None, _listed)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def load_task(task: str) -> Call[dict[str, Any]]:
|
|
78
|
+
return Call("POST", f"/v1/tasks/{_segment(task)}/load", None, _json)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def unload_task(task: str) -> Call[dict[str, Any]]:
|
|
82
|
+
return Call("POST", f"/v1/tasks/{_segment(task)}/unload", None, _json)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def decide(task: str, case: dict[str, Any]) -> Call[Decision]:
|
|
86
|
+
return Call("POST", f"/v1/tasks/{_segment(task)}/decisions", {"case": case}, Decision.from_json)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def explanation(task: str, decision_id: str) -> Call[Explanation]:
|
|
90
|
+
path = f"/v1/tasks/{_segment(task)}/decisions/{_segment(decision_id)}/explanation"
|
|
91
|
+
return Call("GET", path, None, Explanation.from_json)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def act(
|
|
95
|
+
task: str, decision_id: str, action: str, assignee: str | None, comment: str | None
|
|
96
|
+
) -> Call[None]:
|
|
97
|
+
path = f"/v1/tasks/{_segment(task)}/decisions/{_segment(decision_id)}/actions"
|
|
98
|
+
return Call("POST", path, action_body(action, assignee, comment), _nothing)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def records(from_seq: int | None, to_seq: int | None) -> Call[dict[str, Any]]:
|
|
102
|
+
params = {
|
|
103
|
+
name: value
|
|
104
|
+
for name, value in (("from_seq", from_seq), ("to_seq", to_seq))
|
|
105
|
+
if value is not None
|
|
106
|
+
}
|
|
107
|
+
return Call("GET", "/v1/records", None, _json, params or None)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def typed_models() -> Call[list[dict[str, Any]]]:
|
|
111
|
+
return Call("GET", "/v1/typed/models", None, _listed)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def load_typed(name: str) -> Call[dict[str, Any]]:
|
|
115
|
+
return Call("POST", f"/v1/typed/models/{_segment(name)}/load", None, _json)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def unload_typed(name: str) -> Call[dict[str, Any]]:
|
|
119
|
+
return Call("POST", f"/v1/typed/models/{_segment(name)}/unload", None, _json)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def decide_typed(model: str, state: Any, questions: dict[str, Any]) -> Call[TypedDecision]:
|
|
123
|
+
body = {"model": model, "state": state, "questions": questions}
|
|
124
|
+
return Call("POST", "/v1/typed/decide", body, TypedDecision.from_json)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def act_typed(
|
|
128
|
+
model: str, decision_id: str, action: str, assignee: str | None, comment: str | None
|
|
129
|
+
) -> Call[None]:
|
|
130
|
+
body = {"model": model, **action_body(action, assignee, comment)}
|
|
131
|
+
return Call("POST", f"/v1/typed/decisions/{_segment(decision_id)}/actions", body, _nothing)
|
anet/_transport.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""The socket or named pipe under httpx (specs/0055, PY-1, PY-2, PY-10).
|
|
2
|
+
|
|
3
|
+
Each client holds one connection that never expires while idle, because the
|
|
4
|
+
service binds a person's session to the connection that logged in. The
|
|
5
|
+
transport also owns the credentials: it strips whatever ``Authorization`` or
|
|
6
|
+
``x-api-key`` a caller such as the OpenAI SDK adds, and sends the logged-in
|
|
7
|
+
person's token, or nothing, so the service knows a program by its account.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
UNIX_SOCKET = "/var/run/anet/anet.sock"
|
|
19
|
+
WINDOWS_PIPE = r"\\.\pipe\anet"
|
|
20
|
+
BASE_URL = "http://anet"
|
|
21
|
+
# The OpenAI SDK insists on a key; this one never leaves the process,
|
|
22
|
+
# because the transport removes it from every request.
|
|
23
|
+
PLACEHOLDER_KEY = "anet"
|
|
24
|
+
|
|
25
|
+
_ONE_PINNED_CONNECTION = httpx.Limits(
|
|
26
|
+
max_connections=1, max_keepalive_connections=1, keepalive_expiry=None
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_socket(socket: str | None) -> str:
|
|
31
|
+
"""``socket``, else ``$ANET_SOCKET``, else the platform's default."""
|
|
32
|
+
if socket:
|
|
33
|
+
return socket
|
|
34
|
+
from_environment = os.environ.get("ANET_SOCKET")
|
|
35
|
+
if from_environment:
|
|
36
|
+
return from_environment
|
|
37
|
+
return WINDOWS_PIPE if sys.platform == "win32" else UNIX_SOCKET
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Credentials:
|
|
42
|
+
"""The token of the person logged in on this client's connection."""
|
|
43
|
+
|
|
44
|
+
token: str | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _authorise(request: httpx.Request, credentials: Credentials) -> None:
|
|
48
|
+
request.headers.pop("authorization", None)
|
|
49
|
+
request.headers.pop("x-api-key", None)
|
|
50
|
+
if credentials.token is not None:
|
|
51
|
+
request.headers["authorization"] = f"Bearer {credentials.token}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _CredentialTransport(httpx.BaseTransport):
|
|
55
|
+
def __init__(self, inner: httpx.BaseTransport, credentials: Credentials) -> None:
|
|
56
|
+
self._inner = inner
|
|
57
|
+
self._credentials = credentials
|
|
58
|
+
|
|
59
|
+
def handle_request(self, request: httpx.Request) -> httpx.Response:
|
|
60
|
+
_authorise(request, self._credentials)
|
|
61
|
+
return self._inner.handle_request(request)
|
|
62
|
+
|
|
63
|
+
def close(self) -> None:
|
|
64
|
+
self._inner.close()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _AsyncCredentialTransport(httpx.AsyncBaseTransport):
|
|
68
|
+
def __init__(self, inner: httpx.AsyncBaseTransport, credentials: Credentials) -> None:
|
|
69
|
+
self._inner = inner
|
|
70
|
+
self._credentials = credentials
|
|
71
|
+
|
|
72
|
+
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
73
|
+
_authorise(request, self._credentials)
|
|
74
|
+
return await self._inner.handle_async_request(request)
|
|
75
|
+
|
|
76
|
+
async def aclose(self) -> None:
|
|
77
|
+
await self._inner.aclose()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def sync_transport(path: str, credentials: Credentials) -> httpx.BaseTransport:
|
|
81
|
+
if sys.platform == "win32":
|
|
82
|
+
from ._pipe import sync_pipe_transport
|
|
83
|
+
|
|
84
|
+
inner = sync_pipe_transport(path, _ONE_PINNED_CONNECTION)
|
|
85
|
+
else:
|
|
86
|
+
inner = httpx.HTTPTransport(uds=path, limits=_ONE_PINNED_CONNECTION)
|
|
87
|
+
return _CredentialTransport(inner, credentials)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def async_transport(path: str, credentials: Credentials) -> httpx.AsyncBaseTransport:
|
|
91
|
+
if sys.platform == "win32":
|
|
92
|
+
from ._pipe import async_pipe_transport
|
|
93
|
+
|
|
94
|
+
inner = async_pipe_transport(path, _ONE_PINNED_CONNECTION)
|
|
95
|
+
else:
|
|
96
|
+
inner = httpx.AsyncHTTPTransport(uds=path, limits=_ONE_PINNED_CONNECTION)
|
|
97
|
+
return _AsyncCredentialTransport(inner, credentials)
|
anet/_types.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""What the decision loop and typed decisions answer (specs/0055, PY-6),
|
|
2
|
+
read strictly from the service's JSON: a field the service always sends is
|
|
3
|
+
required, and one it may leave out is ``None`` when it does."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
ACTIONS = ("confirm", "dismiss", "reassign")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Decision:
|
|
15
|
+
"""A decision model's answer to one case of a task."""
|
|
16
|
+
|
|
17
|
+
id: str
|
|
18
|
+
task: str
|
|
19
|
+
time: str
|
|
20
|
+
label: str
|
|
21
|
+
attributes: dict[str, Any] | None
|
|
22
|
+
assignee: str | None
|
|
23
|
+
confidence: float
|
|
24
|
+
threshold: float
|
|
25
|
+
to_person: bool
|
|
26
|
+
"""True when the confidence was below the threshold, so the case goes to
|
|
27
|
+
a person with an explanation; False when the answer is advice."""
|
|
28
|
+
model_digest: str
|
|
29
|
+
model_version: int
|
|
30
|
+
runtime_digest: str
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_json(cls, body: dict[str, Any]) -> Decision:
|
|
34
|
+
answer = body["answer"]
|
|
35
|
+
route = body["route"]
|
|
36
|
+
if route not in ("advice", "to_person"):
|
|
37
|
+
raise ValueError(f"the service answered an unknown route {route!r}")
|
|
38
|
+
return cls(
|
|
39
|
+
id=body["id"],
|
|
40
|
+
task=body["task"],
|
|
41
|
+
time=body["time"],
|
|
42
|
+
label=answer["label"],
|
|
43
|
+
attributes=answer.get("attributes"),
|
|
44
|
+
assignee=answer.get("assignee"),
|
|
45
|
+
confidence=body["confidence"],
|
|
46
|
+
threshold=body["threshold"],
|
|
47
|
+
to_person=route == "to_person",
|
|
48
|
+
model_digest=body["model"]["digest"],
|
|
49
|
+
model_version=body["model"]["version"],
|
|
50
|
+
runtime_digest=body["runtime_digest"],
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Explanation:
|
|
56
|
+
"""The local language model's explanation of a decision sent to a
|
|
57
|
+
person: written with its text, or failed with the error."""
|
|
58
|
+
|
|
59
|
+
id: str
|
|
60
|
+
written: bool
|
|
61
|
+
text: str | None
|
|
62
|
+
error: str | None
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def from_json(cls, body: dict[str, Any]) -> Explanation:
|
|
66
|
+
outcome = body["outcome"]
|
|
67
|
+
if outcome == "written":
|
|
68
|
+
return cls(id=body["id"], written=True, text=body["text"], error=None)
|
|
69
|
+
if outcome == "failed":
|
|
70
|
+
return cls(id=body["id"], written=False, text=None, error=body["error"])
|
|
71
|
+
raise ValueError(f"the service answered an unknown outcome {outcome!r}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class TypedAnswer:
|
|
76
|
+
"""One question's answer: the chosen label of a ``choice``, the level of
|
|
77
|
+
a ``score`` as a number, or for a yes-or-no (``noul``) how true the
|
|
78
|
+
statement is, from 0 to 1."""
|
|
79
|
+
|
|
80
|
+
question: str
|
|
81
|
+
type: str
|
|
82
|
+
value: str | float
|
|
83
|
+
confidence: float | None
|
|
84
|
+
probabilities: dict[str, float] | None
|
|
85
|
+
legend: Any
|
|
86
|
+
decision_id: str
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_json(cls, question: str, body: dict[str, Any], decision_id: str) -> TypedAnswer:
|
|
90
|
+
kind = body["type"]
|
|
91
|
+
value_field = {"choice": "choice", "score": "score", "noul": "noul"}.get(kind)
|
|
92
|
+
if value_field is None:
|
|
93
|
+
raise ValueError(f"the service answered an unknown question type {kind!r}")
|
|
94
|
+
return cls(
|
|
95
|
+
question=question,
|
|
96
|
+
type=kind,
|
|
97
|
+
value=body[value_field],
|
|
98
|
+
confidence=body.get("confidence"),
|
|
99
|
+
probabilities=body.get("probabilities"),
|
|
100
|
+
legend=body.get("legend"),
|
|
101
|
+
decision_id=decision_id,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class TypedDecision:
|
|
107
|
+
"""A typed model's answers to the questions of one request."""
|
|
108
|
+
|
|
109
|
+
model: str
|
|
110
|
+
answers: dict[str, TypedAnswer]
|
|
111
|
+
state_truncated: bool
|
|
112
|
+
input_tokens: int
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def from_json(cls, body: dict[str, Any]) -> TypedDecision:
|
|
116
|
+
decisions = body["decisions"]
|
|
117
|
+
return cls(
|
|
118
|
+
model=body["model"],
|
|
119
|
+
answers={
|
|
120
|
+
question: TypedAnswer.from_json(question, answer, decisions[question])
|
|
121
|
+
for question, answer in body["answers"].items()
|
|
122
|
+
},
|
|
123
|
+
state_truncated=body["state_truncated"],
|
|
124
|
+
input_tokens=body["usage"]["input_tokens"],
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def action_body(action: str, assignee: str | None, comment: str | None) -> dict[str, Any]:
|
|
129
|
+
"""An operator's action, checked before anything is sent (PY-8)."""
|
|
130
|
+
if action not in ACTIONS:
|
|
131
|
+
raise ValueError(f"action must be one of {', '.join(ACTIONS)}, not {action!r}")
|
|
132
|
+
if action == "reassign" and not assignee:
|
|
133
|
+
raise ValueError("reassign needs the assignee who takes the case")
|
|
134
|
+
if action != "reassign" and assignee is not None:
|
|
135
|
+
raise ValueError(f"{action} takes no assignee; only reassign does")
|
|
136
|
+
body: dict[str, Any] = {"action": action}
|
|
137
|
+
if assignee is not None:
|
|
138
|
+
body["assignee"] = assignee
|
|
139
|
+
if comment is not None:
|
|
140
|
+
body["comment"] = comment
|
|
141
|
+
return body
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def choice(
|
|
145
|
+
criteria: dict[str, str] | list[str],
|
|
146
|
+
*,
|
|
147
|
+
instructions: str | None = None,
|
|
148
|
+
ordinal: bool | None = None,
|
|
149
|
+
) -> dict[str, Any]:
|
|
150
|
+
"""A question answered by one of the named options, each with an
|
|
151
|
+
optional description (``{"refund": "Wants money back", ...}``)."""
|
|
152
|
+
question: dict[str, Any] = {"type": "choice", "criteria": criteria}
|
|
153
|
+
if instructions is not None:
|
|
154
|
+
question["instructions"] = instructions
|
|
155
|
+
if ordinal is not None:
|
|
156
|
+
question["ordinal"] = ordinal
|
|
157
|
+
return question
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def score(levels: list[str], *, instructions: str | None = None) -> dict[str, Any]:
|
|
161
|
+
"""A question answered by a level, lowest first (``["calm", "angry"]``)."""
|
|
162
|
+
question: dict[str, Any] = {"type": "score", "criteria": levels}
|
|
163
|
+
if instructions is not None:
|
|
164
|
+
question["instructions"] = instructions
|
|
165
|
+
return question
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def yes_or_no(
|
|
169
|
+
*,
|
|
170
|
+
instructions: str | None = None,
|
|
171
|
+
true: str | None = None,
|
|
172
|
+
false: str | None = None,
|
|
173
|
+
) -> dict[str, Any]:
|
|
174
|
+
"""A yes-or-no question, answered with how true it is, from 0 to 1;
|
|
175
|
+
``true`` and ``false`` optionally describe the two ends."""
|
|
176
|
+
if (true is None) != (false is None):
|
|
177
|
+
raise ValueError("describe both answers, true and false, or neither")
|
|
178
|
+
question: dict[str, Any] = {"type": "noul"}
|
|
179
|
+
if instructions is not None:
|
|
180
|
+
question["instructions"] = instructions
|
|
181
|
+
if true is not None:
|
|
182
|
+
question["criteria"] = {"true": true, "false": false}
|
|
183
|
+
return question
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Integrations of the service with other libraries (specs/0055)."""
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""LangChain chat and embedding models over the local service (specs/0055,
|
|
2
|
+
PY-9).
|
|
3
|
+
|
|
4
|
+
Both are ``langchain-openai``'s classes pointed at the service's
|
|
5
|
+
OpenAI-compatible routes through an ``anet`` client's connection, so tool
|
|
6
|
+
binding, structured output, streaming and async are LangChain's own code::
|
|
7
|
+
|
|
8
|
+
from anet.integrations.langchain import ChatAnet, AnetEmbeddings
|
|
9
|
+
chat = ChatAnet(model="qwen3")
|
|
10
|
+
vectors = AnetEmbeddings(model="bge-small").embed_documents(["pump", "valve"])
|
|
11
|
+
|
|
12
|
+
Without ``anet_client`` and ``anet_async_client``, each model opens one
|
|
13
|
+
program connection of its own for sync calls and one for async calls.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
|
21
|
+
from pydantic import model_validator
|
|
22
|
+
|
|
23
|
+
from .._client import AsyncClient, Client
|
|
24
|
+
from .._transport import BASE_URL, PLACEHOLDER_KEY
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _over_the_service(values: Any) -> Any:
|
|
28
|
+
if not isinstance(values, dict):
|
|
29
|
+
return values
|
|
30
|
+
values = dict(values)
|
|
31
|
+
socket = values.pop("socket", None)
|
|
32
|
+
client = values.pop("anet_client", None) or Client(socket)
|
|
33
|
+
async_client = values.pop("anet_async_client", None) or AsyncClient(socket)
|
|
34
|
+
if not isinstance(client, Client) or not isinstance(async_client, AsyncClient):
|
|
35
|
+
raise TypeError("anet_client must be an anet.Client and anet_async_client an anet.AsyncClient")
|
|
36
|
+
for taken in ("base_url", "openai_api_base", "api_key", "openai_api_key", "http_client", "http_async_client"):
|
|
37
|
+
if taken in values:
|
|
38
|
+
raise ValueError(f"{taken} is set by the anet client; give anet_client or socket instead")
|
|
39
|
+
values["base_url"] = f"{BASE_URL}/v1"
|
|
40
|
+
values["api_key"] = PLACEHOLDER_KEY
|
|
41
|
+
values["http_client"] = client.http
|
|
42
|
+
values["http_async_client"] = async_client.http
|
|
43
|
+
values.setdefault("max_retries", 0)
|
|
44
|
+
return values
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ChatAnet(ChatOpenAI):
|
|
48
|
+
"""A chat model of the local service, as a LangChain chat model.
|
|
49
|
+
|
|
50
|
+
Accepts ``socket``, ``anet_client`` (an ``anet.Client``, logged in or
|
|
51
|
+
not) and ``anet_async_client`` (an ``anet.AsyncClient``) besides
|
|
52
|
+
``ChatOpenAI``'s own settings.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
@model_validator(mode="before")
|
|
56
|
+
@classmethod
|
|
57
|
+
def _connect(cls, values: Any) -> Any:
|
|
58
|
+
return _over_the_service(values)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AnetEmbeddings(OpenAIEmbeddings):
|
|
62
|
+
"""An embedding model of the local service; texts are sent as text,
|
|
63
|
+
since the service refuses token ids."""
|
|
64
|
+
|
|
65
|
+
@model_validator(mode="before")
|
|
66
|
+
@classmethod
|
|
67
|
+
def _connect(cls, values: Any) -> Any:
|
|
68
|
+
values = _over_the_service(values)
|
|
69
|
+
if isinstance(values, dict):
|
|
70
|
+
values["check_embedding_ctx_length"] = False
|
|
71
|
+
values["tiktoken_enabled"] = False
|
|
72
|
+
return values
|
anet/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: antinet
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The local Antinet service from Python: the OpenAI SDK and LangChain over its socket or pipe, the decision loop and typed decisions
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: httpx>=0.28.1,<0.29
|
|
8
|
+
Requires-Dist: openai>=3.51,<4 ; extra == 'langchain'
|
|
9
|
+
Requires-Dist: langchain-openai>=1.8,<2 ; extra == 'langchain'
|
|
10
|
+
Requires-Dist: openai>=3.51,<4 ; extra == 'openai'
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Provides-Extra: langchain
|
|
13
|
+
Provides-Extra: openai
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
anet/__init__.py,sha256=4KuhJjgNrTARe24jgEddRETAZ601klBK82YOAknF49w,686
|
|
2
|
+
anet/_client.py,sha256=_GXSvfdY-IftKDtKw9q6nfKT_nia-qDahr7QnWXzZvU,9654
|
|
3
|
+
anet/_errors.py,sha256=xHEfWjRst-aGiFVCT9o3YeKzpiec_KjBTGYMdFDNdQE,2115
|
|
4
|
+
anet/_pipe.py,sha256=UFTplG2bYcNdOE0PsK5dZo2GP42-vryCJaVjuUg6ISg,6759
|
|
5
|
+
anet/_routes.py,sha256=-IzcJsWemG4K8ZRQcVdjrnz2RS1Dhv4J8g7ojW_4bWc,3942
|
|
6
|
+
anet/_transport.py,sha256=Qe2Hpr-cRNGWvDUHeGaXct3jX7J5klw1gMRnCUQw_wQ,3346
|
|
7
|
+
anet/_types.py,sha256=vn8dSLo1sl0us-BhFFRPKhWUIy2UVy0ASB3JGW3x4Rs,6283
|
|
8
|
+
anet/integrations/__init__.py,sha256=qZZBorONJJz8rBnwTtrBS4eNEee5FqZi5UsGcm6XhKc,69
|
|
9
|
+
anet/integrations/langchain.py,sha256=rPiM8wzFLWjgsnLj7_6i-CSMxYsysE94-ZK5oHfU2fs,2746
|
|
10
|
+
anet/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
antinet-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
12
|
+
antinet-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
13
|
+
antinet-0.1.0.dist-info/METADATA,sha256=9fN_PnURujRzhONkuArIULNIlp8rzioK5Wt_PuV6igg,520
|
|
14
|
+
antinet-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|