aex-brain 1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Weilue Luo
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,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: aex-brain
3
+ Version: 1.0.0
4
+ Summary: Typed Python client for Brain sessions, tools, checkpoints, and event streams
5
+ Author: AEX
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-Expression: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Classifier: Operating System :: OS Independent
12
+ License-File: LICENSE
13
+ Project-URL: Documentation, https://aexhq.github.io/brain/docs/sdks/python/
14
+ Project-URL: Issues, https://github.com/aexhq/brain/issues
15
+ Project-URL: Source, https://github.com/aexhq/brain
16
+
17
+ # Brain Python SDK
18
+
19
+ Install with `python -m pip install aex-brain==1.0.0`. Requires Python 3.11+;
20
+ there are no runtime dependencies. Import the client from `brain` and generated
21
+ `TypedDict` definitions from `brain.types`. The wheel includes PEP 561 type data.
22
+
23
+ ```python
24
+ import os
25
+ from contextlib import closing
26
+ from brain import Brain
27
+
28
+ brain = Brain('http://127.0.0.1:8080', os.environ['BRAIN_API_KEY'])
29
+ session = brain.create({
30
+ 'harness': 'pi', 'config': {'model': 'openai/gpt-4.1-mini', 'tools': []},
31
+ })
32
+ message = brain.send(session['id'], {'type': 'user.message', 'text': 'Hello!'})
33
+ with closing(brain.observe(session['id'])) as events:
34
+ for event in events:
35
+ if event['type'] == 'assistant.message':
36
+ print(event['data']['text'])
37
+ if event.get('input_id') != message['id']:
38
+ continue
39
+ if event['type'] == 'session.error':
40
+ raise RuntimeError(event['data']['message'])
41
+ if event['type'] == 'session.status' and event['data']['status'] == 'idle':
42
+ break
43
+ ```
44
+
45
+ This is a synchronous client. `timeout=30` configures the socket timeout, including
46
+ stream reads. Requests are never automatically retried. `BrainError` preserves the
47
+ HTTP status, server error code, and request ID. Closing the observer does not stop
48
+ execution; call `interrupt(session_id)` for that.
49
+
50
+ Pin the package and matching server image commit recorded by the release workflow.
51
+ [SDK reference](https://aexhq.github.io/brain/docs/sdks/python/) ·
52
+ [Server setup](https://aexhq.github.io/brain/docs/quickstart/)
53
+
@@ -0,0 +1,36 @@
1
+ # Brain Python SDK
2
+
3
+ Install with `python -m pip install aex-brain==1.0.0`. Requires Python 3.11+;
4
+ there are no runtime dependencies. Import the client from `brain` and generated
5
+ `TypedDict` definitions from `brain.types`. The wheel includes PEP 561 type data.
6
+
7
+ ```python
8
+ import os
9
+ from contextlib import closing
10
+ from brain import Brain
11
+
12
+ brain = Brain('http://127.0.0.1:8080', os.environ['BRAIN_API_KEY'])
13
+ session = brain.create({
14
+ 'harness': 'pi', 'config': {'model': 'openai/gpt-4.1-mini', 'tools': []},
15
+ })
16
+ message = brain.send(session['id'], {'type': 'user.message', 'text': 'Hello!'})
17
+ with closing(brain.observe(session['id'])) as events:
18
+ for event in events:
19
+ if event['type'] == 'assistant.message':
20
+ print(event['data']['text'])
21
+ if event.get('input_id') != message['id']:
22
+ continue
23
+ if event['type'] == 'session.error':
24
+ raise RuntimeError(event['data']['message'])
25
+ if event['type'] == 'session.status' and event['data']['status'] == 'idle':
26
+ break
27
+ ```
28
+
29
+ This is a synchronous client. `timeout=30` configures the socket timeout, including
30
+ stream reads. Requests are never automatically retried. `BrainError` preserves the
31
+ HTTP status, server error code, and request ID. Closing the observer does not stop
32
+ execution; call `interrupt(session_id)` for that.
33
+
34
+ Pin the package and matching server image commit recorded by the release workflow.
35
+ [SDK reference](https://aexhq.github.io/brain/docs/sdks/python/) ·
36
+ [Server setup](https://aexhq.github.io/brain/docs/quickstart/)
@@ -0,0 +1,110 @@
1
+ """Small synchronous Brain client. Requests are never automatically retried."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from collections.abc import Iterator
6
+ from typing import Any
7
+ from urllib.error import HTTPError
8
+ from urllib.parse import quote, urlencode
9
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
10
+
11
+ from .types import CreateSession, Event, EventList, Input, Session, SessionList, SyncStatus, ToolCatalog
12
+
13
+ __all__ = ["Brain", "BrainError"]
14
+
15
+
16
+ class BrainError(Exception):
17
+ def __init__(self, status: int, code: str, message: str, request_id: str | None = None):
18
+ super().__init__(message)
19
+ self.status, self.code, self.request_id = status, code, request_id
20
+
21
+
22
+ class _NoRedirect(HTTPRedirectHandler):
23
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
24
+ return None
25
+
26
+
27
+ class Brain:
28
+ def __init__(self, url: str, token: str, timeout: float = 30):
29
+ self.url, self.token, self.timeout = url.rstrip("/"), token, timeout
30
+ self._opener = build_opener(_NoRedirect())
31
+
32
+ def _open(self, method: str, path: str, body: Any = None, stream: bool = False):
33
+ headers = {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"}
34
+ if stream:
35
+ headers["Accept"] = "text/event-stream"
36
+ req = Request(self.url + path, data=None if body is None else json.dumps(body).encode(), headers=headers, method=method)
37
+ try:
38
+ return self._opener.open(req, timeout=self.timeout)
39
+ except HTTPError as error:
40
+ try:
41
+ payload = json.loads(error.read(1 << 20))
42
+ except (ValueError, UnicodeError):
43
+ payload = {}
44
+ finally:
45
+ error.close()
46
+ detail = payload.get("error", {})
47
+ raise BrainError(error.code, detail.get("code", "http_error"), detail.get("message", str(error)), payload.get("request_id")) from error
48
+
49
+ def _request(self, method: str, path: str, body: Any = None) -> Any:
50
+ with self._open(method, path, body) as response:
51
+ return json.load(response)
52
+
53
+ def create(self, config: CreateSession) -> Session:
54
+ return self._request("POST", "/sessions", config)
55
+
56
+ def get(self, session_id: str) -> Session:
57
+ return self._request("GET", f"/sessions/{quote(session_id, safe='')}")
58
+
59
+ def list(self, after: str = "", limit: int = 100) -> SessionList:
60
+ return self._request("GET", "/sessions?" + urlencode({"after": after, "limit": limit}))
61
+
62
+ def send(self, session_id: str, event: Input) -> Event:
63
+ return self._request("POST", f"/sessions/{quote(session_id, safe='')}/events", event)
64
+
65
+ def interrupt(self, session_id: str) -> None:
66
+ self.send(session_id, {"type": "user.interrupt"})
67
+
68
+ def resume(self, session_id: str) -> Session:
69
+ return self._request("POST", f"/sessions/{quote(session_id, safe='')}/resume")
70
+
71
+ def close(self, session_id: str) -> None:
72
+ self._request("POST", f"/sessions/{quote(session_id, safe='')}/close")
73
+
74
+ def flush(self, session_id: str) -> SyncStatus:
75
+ return self._request("POST", f"/sessions/{quote(session_id, safe='')}/flush")
76
+
77
+ def sync(self, session_id: str) -> SyncStatus:
78
+ return self._request("GET", f"/sessions/{quote(session_id, safe='')}/sync")
79
+
80
+ def restore(self, session_id: str, checkpoint: str) -> Session:
81
+ return self._request("POST", f"/sessions/{quote(session_id, safe='')}/restore", {"checkpoint": checkpoint})
82
+
83
+ def catalog(self) -> ToolCatalog:
84
+ return self._request("GET", "/catalog")
85
+
86
+ def history(self, session_id: str, after: str = "", limit: int = 100) -> EventList:
87
+ return self._request("GET", f"/sessions/{quote(session_id, safe='')}/events?" + urlencode({"after": after, "limit": limit}))
88
+
89
+ def observe(self, session_id: str, after: str = "") -> Iterator[Event]:
90
+ path = f"/sessions/{quote(session_id, safe='')}/events?" + urlencode({"after": after})
91
+ with self._open("GET", path, stream=True) as response:
92
+ data: list[str] = []
93
+ size = 0
94
+ while True:
95
+ line = response.readline((4 << 20) + 1)
96
+ size += len(line)
97
+ if size > 4 << 20:
98
+ raise ValueError("event exceeds client limit")
99
+ if not line:
100
+ if data:
101
+ raise ValueError("incomplete event stream")
102
+ return
103
+ text = line.decode().rstrip("\r\n")
104
+ if not text:
105
+ if data:
106
+ yield json.loads("\n".join(data))
107
+ data, size = [], 0
108
+ elif text.startswith("data:"):
109
+ data.append(text[5:].removeprefix(" "))
110
+
File without changes
@@ -0,0 +1,101 @@
1
+ # Generated by go run ./cmd/generate; do not edit.
2
+ from __future__ import annotations
3
+ from typing import Any, NotRequired, TypedDict
4
+
5
+ class Call(TypedDict):
6
+ id: str
7
+ name: str
8
+ arguments: Any
9
+
10
+ class Checkpoint(TypedDict):
11
+ id: str
12
+ offset: int
13
+ time: str
14
+
15
+ class Content(TypedDict):
16
+ type: str
17
+ text: NotRequired[str]
18
+ data: NotRequired[str]
19
+ mime_type: NotRequired[str]
20
+
21
+ class CreateSession(TypedDict):
22
+ harness: str
23
+ config: SessionConfig
24
+
25
+ class ErrorDetail(TypedDict):
26
+ code: str
27
+ message: str
28
+
29
+ class ErrorResponse(TypedDict):
30
+ error: ErrorDetail
31
+ request_id: str
32
+
33
+ class Event(TypedDict):
34
+ id: str
35
+ type: str
36
+ time: str
37
+ input_id: NotRequired[str]
38
+ data: Any
39
+ cursor: NotRequired[str]
40
+
41
+ class EventList(TypedDict):
42
+ events: list[Event]
43
+ next_cursor: str
44
+
45
+ class Input(TypedDict):
46
+ type: str
47
+ text: NotRequired[str]
48
+ delivery: NotRequired[str]
49
+ key: NotRequired[str]
50
+
51
+ class Restore(TypedDict):
52
+ checkpoint: str
53
+
54
+ class Result(TypedDict):
55
+ content: list[Content]
56
+ is_error: NotRequired[bool]
57
+ unknown_outcome: NotRequired[bool]
58
+
59
+ class Session(TypedDict):
60
+ id: str
61
+ harness: str
62
+ config: SessionConfig
63
+ status: str
64
+ created_at: str
65
+ updated_at: str
66
+ checkpoint: NotRequired[Checkpoint]
67
+
68
+ class SessionConfig(TypedDict):
69
+ model: str
70
+ reasoning_effort: NotRequired[str]
71
+ instructions: NotRequired[str]
72
+ tools: list[str]
73
+
74
+ class SessionList(TypedDict):
75
+ sessions: list[Session]
76
+
77
+ class Status(TypedDict):
78
+ status: str
79
+
80
+ class SyncStatus(TypedDict):
81
+ checkpoint: NotRequired[str]
82
+ history_bytes: int
83
+ resume_offset: int
84
+ native_checkpoint: NotRequired[str]
85
+ time: NotRequired[str]
86
+ pending: bool
87
+ error: NotRequired[str]
88
+
89
+ class Tool(TypedDict):
90
+ name: str
91
+ description: str
92
+ input_schema: Any
93
+ output_schema: NotRequired[Any]
94
+
95
+ class ToolCatalog(TypedDict):
96
+ tools: list[Tool]
97
+
98
+ class ToolResult(TypedDict):
99
+ call_id: str
100
+ result: Result
101
+
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["flit_core==3.12.0"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+ [project]
6
+ name = "aex-brain"
7
+ version = "1.0.0"
8
+ description = "Typed Python client for Brain sessions, tools, checkpoints, and event streams"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "AEX"}]
14
+ classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed", "Operating System :: OS Independent"]
15
+
16
+ [project.urls]
17
+ Documentation = "https://aexhq.github.io/brain/docs/sdks/python/"
18
+ Source = "https://github.com/aexhq/brain"
19
+ Issues = "https://github.com/aexhq/brain/issues"
20
+
21
+ [tool.flit.module]
22
+ name = "brain"
23
+
24
+ [tool.flit.sdist]
25
+ include = ["test_client.py"]
@@ -0,0 +1,34 @@
1
+ import io
2
+ import unittest
3
+ from urllib.error import HTTPError
4
+ from brain import Brain, BrainError
5
+
6
+
7
+ class ClientTests(unittest.TestCase):
8
+ def test_no_retry_and_error_identity(self):
9
+ client = Brain("http://brain.test", "token")
10
+ class Opener:
11
+ calls = 0
12
+ def open(self, request, **kwargs):
13
+ self.calls += 1
14
+ raise HTTPError(request.full_url, 429, "busy", {}, io.BytesIO(b'{"error":{"code":"overloaded","message":"busy"},"request_id":"request"}'))
15
+ opener = Opener()
16
+ client._opener = opener
17
+ with self.assertRaises(BrainError) as raised:
18
+ client.send("session", {"type": "user.message", "text": "hello"})
19
+ self.assertEqual(opener.calls, 1)
20
+ self.assertEqual(raised.exception.code, "overloaded")
21
+ self.assertEqual(raised.exception.request_id, "request")
22
+
23
+ def test_stream_comments_and_utf8(self):
24
+ client = Brain("http://brain.test", "token")
25
+ class Opener:
26
+ def open(self, request, **kwargs):
27
+ return io.BytesIO(': keepalive\n\ndata: {"id":"one","data":{"text":"你好"}}\n\n'.encode())
28
+ client._opener = Opener()
29
+ self.assertEqual(list(client.observe("session"))[0]["data"]["text"], "你好")
30
+
31
+
32
+ if __name__ == "__main__":
33
+ unittest.main()
34
+