crystalbrain 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ """Python client for the CrystalBrain REST API: read and write the memory of your users."""
2
+
3
+ from .client import CrystalBrain, CrystalBrainError, Transport
4
+ from .types import * # noqa: F401,F403 (the generated TypedDicts)
5
+
6
+ __all__ = ["CrystalBrain", "CrystalBrainError", "Transport"]
7
+ __version__ = "0.1.0"
crystalbrain/client.py ADDED
@@ -0,0 +1,178 @@
1
+ """Client of the CrystalBrain REST API. The types come from the API's OpenAPI document (types.py, generated by
2
+ scripts/generate_types.py); only this thin client is written by hand. Reference: https://crystalbrain.ai/docs/api"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from typing import Any, Callable, Mapping, Unpack, cast
11
+
12
+ from .types import (
13
+ ArchiveMemoryInput, ArchiveMemoryResult, CreateBrainInput, CreateBrainResult, DeleteUserResult, GetAnalyticsInput,
14
+ GetAnalyticsResult, GetBrainInput, GetBrainResult, GetMemoryResult, GetUserResult, ListBrainsResultBrainsItem,
15
+ ListMemoriesInput, ListMemoriesResult, ListUsersInput, ListUsersResult, LogToolCallsInput, LogToolCallsResult,
16
+ MentionSkillInput, MentionSkillResult, MergeMemoriesInput, MergeMemoriesResult, ResolveContradictionInput,
17
+ ResolveContradictionResult, RestoreUserResult, SaveInput, SaveResult, SearchInput, SearchResult,
18
+ SimilarMemoriesResult, UndoMergeResult, UpdateMemoryInput, UpdateMemoryResult,
19
+ )
20
+
21
+ DEFAULT_BASE_URL = "https://crystalbrain.ai"
22
+
23
+ # A transport sends one request and returns (status, headers, body). The default one uses urllib; tests pass their own.
24
+ Transport = Callable[[str, str, Mapping[str, str], bytes | None], tuple[int, Mapping[str, str], bytes]]
25
+
26
+
27
+ class CrystalBrainError(Exception):
28
+ """An error answered by the API. `code` is stable (INVALID_API_KEY, INVALID_BODY, INVALID_QUERY, MTU_QUOTA_REACHED,
29
+ NOT_FOUND, INVALID_STATE, RATE_LIMITED, USER_ARCHIVED, NOT_A_USER, USER_DELETION_PENDING, EMBEDDING_UNAVAILABLE,
30
+ INTERNAL_ERROR…); the message can change."""
31
+
32
+ def __init__(self, status: int, code: str, message: str, retry_after: float | None = None, details: Any = None):
33
+ super().__init__(message)
34
+ self.status = status
35
+ self.code = code
36
+ self.message = message
37
+ self.retry_after = retry_after # seconds to wait, on RATE_LIMITED (Retry-After header)
38
+ self.details = details # field errors, on INVALID_BODY and INVALID_QUERY
39
+
40
+
41
+ def _urllib_transport(timeout: float) -> Transport:
42
+ def send(method: str, url: str, headers: Mapping[str, str], body: bytes | None) -> tuple[int, Mapping[str, str], bytes]:
43
+ req = urllib.request.Request(url, data=body, method=method, headers=dict(headers))
44
+ try:
45
+ with urllib.request.urlopen(req, timeout=timeout) as res:
46
+ return res.status, {k.lower(): v for k, v in res.headers.items()}, res.read()
47
+ except urllib.error.HTTPError as err:
48
+ return err.code, {k.lower(): v for k, v in err.headers.items()}, err.read()
49
+
50
+ return send
51
+
52
+
53
+ class CrystalBrain:
54
+ """Every call names a `user`: your customer's ID or name (omit it for your own account)."""
55
+
56
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 60, transport: Transport | None = None):
57
+ if not api_key:
58
+ raise ValueError("CrystalBrain: an api_key is required.")
59
+ self._api_key = api_key
60
+ self._base_url = base_url.rstrip("/")
61
+ self._send = transport or _urllib_transport(timeout)
62
+
63
+ def _call(self, method: str, path: str, *, query: Mapping[str, Any] | None = None, body: Mapping[str, Any] | None = None) -> Any:
64
+ url = self._base_url + path
65
+ params = {k: v for k, v in (query or {}).items() if v is not None}
66
+ if params:
67
+ url += "?" + urllib.parse.urlencode(params)
68
+ headers = {"Authorization": f"Bearer {self._api_key}", "Accept": "application/json", "User-Agent": "crystalbrain-python"}
69
+ data = None
70
+ if body is not None:
71
+ headers["Content-Type"] = "application/json"
72
+ data = json.dumps(body).encode()
73
+ status, res_headers, raw = self._send(method, url, headers, data)
74
+ try:
75
+ payload = json.loads(raw.decode() or "null")
76
+ except ValueError:
77
+ payload = None
78
+ if 200 <= status < 300:
79
+ return payload
80
+ err = payload if isinstance(payload, dict) else {}
81
+ retry = res_headers.get("retry-after")
82
+ raise CrystalBrainError(
83
+ status,
84
+ str(err.get("code", "HTTP_ERROR")),
85
+ str(err.get("error", f"CrystalBrain answered {status}")),
86
+ float(retry) if retry else None,
87
+ err.get("details"),
88
+ )
89
+
90
+ # Memory of one user
91
+
92
+ def search(self, **input: Unpack[SearchInput]) -> SearchResult:
93
+ """What CrystalBrain knows about one user for this request, with a ready-to-use context block for your LLM."""
94
+ return cast(SearchResult, self._call("POST", "/api/v1/search", body=input))
95
+
96
+ def save(self, **input: Unpack[SaveInput]) -> SaveResult:
97
+ """Saves something durable about one user. An unknown user is created."""
98
+ return cast(SaveResult, self._call("POST", "/api/v1/save", body=input))
99
+
100
+ def list_brains(self, user: str | None = None) -> list[ListBrainsResultBrainsItem]:
101
+ """The user's brains, then the brains opened to its groups (read only). Omit `user` for your own account."""
102
+ return cast(list[ListBrainsResultBrainsItem], self._call("GET", "/api/v1/brains", query={"user": user})["brains"])
103
+
104
+ def create_brain(self, **input: Unpack[CreateBrainInput]) -> CreateBrainResult:
105
+ """Creates a brain for one user, or returns the brain of that name it already has (created: False)."""
106
+ return cast(CreateBrainResult, self._call("POST", "/api/v1/brains", body=input))
107
+
108
+ def list_users(self, **input: Unpack[ListUsersInput]) -> ListUsersResult:
109
+ """One page of your users, by name. Call again with offset=page["next_offset"] until it is None."""
110
+ return cast(ListUsersResult, self._call("GET", "/api/v1/users", query=input))
111
+
112
+ def mention_skill(self, **input: Unpack[MentionSkillInput]) -> MentionSkillResult:
113
+ """Reports that your app used a skill; returns the skill's instructions when CrystalBrain has them."""
114
+ return cast(MentionSkillResult, self._call("POST", "/api/v1/skills", body=input))
115
+
116
+ def log_tool_calls(self, **input: Unpack[LogToolCallsInput]) -> LogToolCallsResult:
117
+ """Reports the tools your LLM called (one call, or up to 100 in `calls`)."""
118
+ return cast(LogToolCallsResult, self._call("POST", "/api/v1/tool-calls", body=input))
119
+
120
+ # Corrections
121
+
122
+ def update_memory(self, **input: Unpack[UpdateMemoryInput]) -> UpdateMemoryResult:
123
+ """Changes what you name on one memory of the user (title, content, type, tags, fields). The previous version is kept."""
124
+ return cast(UpdateMemoryResult, self._call("PATCH", "/api/v1/memory", body=input))
125
+
126
+ def archive_memory(self, **input: Unpack[ArchiveMemoryInput]) -> ArchiveMemoryResult:
127
+ """Archives one memory of the user (they asked you to forget it). Reversible from the dashboard."""
128
+ return cast(ArchiveMemoryResult, self._call("POST", "/api/v1/memory/archive", body=input))
129
+
130
+ # Permanent deletion (GDPR)
131
+
132
+ def delete_user(self, user: str) -> DeleteUserResult:
133
+ """Requests the permanent deletion of one user: access closed at once, data deleted 7 days later unless restore_user."""
134
+ return cast(DeleteUserResult, self._call("DELETE", "/api/v1/user", query={"user": user}))
135
+
136
+ def restore_user(self, user: str) -> RestoreUserResult:
137
+ """Cancels a deletion requested with delete_user, before it happens."""
138
+ return cast(RestoreUserResult, self._call("POST", "/api/v1/user/restore", body={"user": user}))
139
+
140
+ # Reads: they change no read counter and do not count the user as tracked
141
+
142
+ def get_user(self, user: str | None = None) -> GetUserResult:
143
+ """One user's profile, counts, latest AI activity and brains. Omit `user` for your own account."""
144
+ return cast(GetUserResult, self._call("GET", "/api/v1/user", query={"user": user}))
145
+
146
+ def get_brain(self, **input: Unpack[GetBrainInput]) -> GetBrainResult:
147
+ """One brain with its framing, summary, files, web pages, saved prompts and latest memory checks."""
148
+ return cast(GetBrainResult, self._call("GET", "/api/v1/brain", query=input))
149
+
150
+ def list_memories(self, **input: Unpack[ListMemoriesInput]) -> ListMemoriesResult:
151
+ """One page of a user's full memories, newest first. Call again with offset=page["next_offset"] until it is None."""
152
+ return cast(ListMemoriesResult, self._call("GET", "/api/v1/memories", query=input))
153
+
154
+ def get_memory(self, id: str) -> GetMemoryResult:
155
+ """One memory by ID, in full."""
156
+ return cast(GetMemoryResult, self._call("GET", "/api/v1/memory", query={"id": id}))
157
+
158
+ def get_analytics(self, **input: Unpack[GetAnalyticsInput]) -> GetAnalyticsResult:
159
+ """One page of a user's raw analytics rows of one kind over a period (default: the last 30 days)."""
160
+ return cast(GetAnalyticsResult, self._call("GET", "/api/v1/analytics", query=input))
161
+
162
+ # Review actions: every change is a reversible archive
163
+
164
+ def resolve_contradiction(self, **input: Unpack[ResolveContradictionInput]) -> ResolveContradictionResult:
165
+ """Keeps one memory of a contradiction (keep: its ID; the other is archived) or both (keep="both")."""
166
+ return cast(ResolveContradictionResult, self._call("POST", "/api/v1/contradictions/resolve", body=input))
167
+
168
+ def similar_memories(self, id: str, limit: int | None = None) -> SimilarMemoriesResult:
169
+ """The active memories of the same brain closest to one memory, most similar first: candidates for a merge."""
170
+ return cast(SimilarMemoriesResult, self._call("GET", "/api/v1/memory/similar", query={"id": id, "limit": limit}))
171
+
172
+ def merge_memories(self, **input: Unpack[MergeMemoriesInput]) -> MergeMemoriesResult:
173
+ """Replaces 2 to 10 active memories of one brain by the merged memory you wrote. Undo with undo_merge."""
174
+ return cast(MergeMemoriesResult, self._call("POST", "/api/v1/memories/merge", body=input))
175
+
176
+ def undo_merge(self, id: str) -> UndoMergeResult:
177
+ """Undoes a merge: its memories come back and the merged memory is archived. `id`: the merged memory."""
178
+ return cast(UndoMergeResult, self._call("POST", "/api/v1/memories/unmerge", body={"id": id}))
crystalbrain/py.typed ADDED
File without changes
crystalbrain/types.py ADDED
@@ -0,0 +1,569 @@
1
+ """Types of the CrystalBrain API, generated from its OpenAPI document by scripts/generate_types.py.
2
+ Do not edit: change the API (lib/apiSchemas.ts), update the snapshot, then run the script again."""
3
+
4
+ from typing import Any, Literal, NotRequired, Required, TypedDict
5
+
6
+ __all__ = ["ArchiveMemoryInput", "ArchiveMemoryResult", "CreateBrainInput", "CreateBrainResult", "CreateBrainResultUser", "DeleteUserInput", "DeleteUserResult", "DeleteUserResultUser", "Error", "GetAnalyticsInput", "GetAnalyticsResult", "GetAnalyticsResultUser", "GetBrainInput", "GetBrainResult", "GetBrainResultBrain", "GetBrainResultCounts", "GetBrainResultDocumentsItem", "GetBrainResultLastChecksItem", "GetBrainResultSavedPromptsItem", "GetBrainResultUser", "GetBrainResultWebPagesItem", "GetMemoryInput", "GetMemoryResult", "GetMemoryResultContradictionsItem", "GetMemoryResultContradictionsItemOther", "GetMemoryResultMergedFromItem", "GetMemoryResultUser", "GetUserInput", "GetUserResult", "GetUserResultBrainsItem", "GetUserResultCounts", "GetUserResultUser", "ListBrainsInput", "ListBrainsResult", "ListBrainsResultBrainsItem", "ListMemoriesInput", "ListMemoriesResult", "ListMemoriesResultBrain", "ListMemoriesResultMemoriesItem", "ListMemoriesResultUser", "ListUsersInput", "ListUsersResult", "ListUsersResultUsersItem", "LogToolCallsInput", "LogToolCallsInputCallsItem", "LogToolCallsResult", "MentionSkillInput", "MentionSkillResult", "MergeMemoriesInput", "MergeMemoriesResult", "ResolveContradictionInput", "ResolveContradictionResult", "RestoreUserInput", "RestoreUserResult", "RestoreUserResultUser", "SaveInput", "SaveResult", "SaveResultMemoriesItem", "SaveResultMemoriesItemDuplicateOf", "SearchInput", "SearchResult", "SearchResultEntriesItem", "SimilarMemoriesInput", "SimilarMemoriesResult", "SimilarMemoriesResultMemory", "SimilarMemoriesResultSimilarItem", "UndoMergeInput", "UndoMergeResult", "UpdateMemoryInput", "UpdateMemoryResult"]
7
+
8
+ Error = TypedDict("Error", {
9
+ "error": Required[str],
10
+ "code": Required[str],
11
+ }, total=False)
12
+
13
+ SearchInput = TypedDict("SearchInput", {
14
+ "query": Required[str],
15
+ "user": NotRequired[str],
16
+ "brain": NotRequired[str],
17
+ "types": NotRequired[list[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]]],
18
+ "tags": NotRequired[list[str]],
19
+ "limit": NotRequired[int],
20
+ "app": NotRequired[str],
21
+ }, total=False)
22
+
23
+ SearchResultEntriesItem = TypedDict("SearchResultEntriesItem", {
24
+ "id": Required[str],
25
+ "type": Required[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
26
+ "space": Required[str],
27
+ "title": Required[str],
28
+ "score": Required[float],
29
+ }, total=False)
30
+
31
+ SearchResult = TypedDict("SearchResult", {
32
+ "context_block": Required[str],
33
+ "entries": Required[list[SearchResultEntriesItem]],
34
+ }, total=False)
35
+
36
+ SaveInput = TypedDict("SaveInput", {
37
+ "user": NotRequired[str],
38
+ "brain": NotRequired[str],
39
+ "type": Required[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
40
+ "title": Required[str],
41
+ "content": Required[str],
42
+ "source_text": NotRequired[str],
43
+ "fields": NotRequired[dict[str, Any]],
44
+ "tags": NotRequired[list[str]],
45
+ "source_ref": NotRequired[str],
46
+ "app": NotRequired[str],
47
+ "sources": NotRequired[list[str]],
48
+ "skills": NotRequired[list[str]],
49
+ "tool_calls": NotRequired[list[str]],
50
+ }, total=False)
51
+
52
+ SaveResultMemoriesItemDuplicateOf = TypedDict("SaveResultMemoriesItemDuplicateOf", {
53
+ "id": Required[str],
54
+ "title": Required[str],
55
+ }, total=False)
56
+ """The existing memory it duplicates, when not saved"""
57
+
58
+ SaveResultMemoriesItem = TypedDict("SaveResultMemoriesItem", {
59
+ "saved": Required[bool],
60
+ "id": NotRequired[str],
61
+ "type": Required[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
62
+ "title": Required[str],
63
+ "duplicate_of": NotRequired[SaveResultMemoriesItemDuplicateOf],
64
+ }, total=False)
65
+
66
+ SaveResult = TypedDict("SaveResult", {
67
+ "saved": Required[bool],
68
+ "id": NotRequired[str],
69
+ "space": Required[str],
70
+ "user": Required[str],
71
+ "structured": Required[bool],
72
+ "memories": Required[list[SaveResultMemoriesItem]],
73
+ "message": NotRequired[str],
74
+ }, total=False)
75
+
76
+ ListBrainsInput = TypedDict("ListBrainsInput", {
77
+ "user": NotRequired[str],
78
+ }, total=False)
79
+
80
+ ListBrainsResultBrainsItem = TypedDict("ListBrainsResultBrainsItem", {
81
+ "id": Required[str],
82
+ "name": Required[str],
83
+ "description": Required[str | None],
84
+ "memories": Required[int],
85
+ "shared_by": NotRequired[str],
86
+ "read_only": NotRequired[bool],
87
+ }, total=False)
88
+
89
+ ListBrainsResult = TypedDict("ListBrainsResult", {
90
+ "brains": Required[list[ListBrainsResultBrainsItem]],
91
+ }, total=False)
92
+
93
+ CreateBrainInput = TypedDict("CreateBrainInput", {
94
+ "user": NotRequired[str],
95
+ "name": Required[str],
96
+ "description": NotRequired[str],
97
+ }, total=False)
98
+
99
+ CreateBrainResultUser = TypedDict("CreateBrainResultUser", {
100
+ "id": Required[str],
101
+ "name": Required[str],
102
+ }, total=False)
103
+
104
+ CreateBrainResult = TypedDict("CreateBrainResult", {
105
+ "id": Required[str],
106
+ "name": Required[str],
107
+ "description": Required[str | None],
108
+ "status": Required[str],
109
+ "user": Required[CreateBrainResultUser],
110
+ "created": Required[bool],
111
+ }, total=False)
112
+
113
+ ListUsersInput = TypedDict("ListUsersInput", {
114
+ "q": NotRequired[str],
115
+ "status": NotRequired[Literal["active", "archived", "all"]],
116
+ "offset": NotRequired[int],
117
+ "limit": NotRequired[int],
118
+ }, total=False)
119
+
120
+ ListUsersResultUsersItem = TypedDict("ListUsersResultUsersItem", {
121
+ "id": Required[str],
122
+ "name": Required[str],
123
+ "external_id": Required[str | None],
124
+ "email": Required[str | None],
125
+ "is_default": Required[bool],
126
+ "status": Required[Literal["active", "archived"]],
127
+ "created_at": Required[str],
128
+ }, total=False)
129
+
130
+ ListUsersResult = TypedDict("ListUsersResult", {
131
+ "total": Required[int],
132
+ "offset": Required[int],
133
+ "limit": Required[int],
134
+ "next_offset": Required[int | None],
135
+ "users": Required[list[ListUsersResultUsersItem]],
136
+ }, total=False)
137
+
138
+ GetUserInput = TypedDict("GetUserInput", {
139
+ "user": NotRequired[str],
140
+ }, total=False)
141
+
142
+ GetUserResultUser = TypedDict("GetUserResultUser", {
143
+ "id": Required[str],
144
+ "name": Required[str],
145
+ "external_id": Required[str | None],
146
+ "email": Required[str | None],
147
+ "is_default": Required[bool],
148
+ "status": Required[Literal["active", "archived"]],
149
+ "created_at": Required[str],
150
+ }, total=False)
151
+
152
+ GetUserResultCounts = TypedDict("GetUserResultCounts", {
153
+ "brains": Required[int],
154
+ "memories_active": Required[int],
155
+ "memories_archived": Required[int],
156
+ "documents": Required[int],
157
+ "web_pages": Required[int],
158
+ "open_contradictions": Required[int],
159
+ }, total=False)
160
+
161
+ GetUserResultBrainsItem = TypedDict("GetUserResultBrainsItem", {
162
+ "id": Required[str],
163
+ "name": Required[str],
164
+ "description": Required[str | None],
165
+ "status": Required[str],
166
+ "memories": Required[int],
167
+ "created_at": Required[str],
168
+ }, total=False)
169
+
170
+ GetUserResult = TypedDict("GetUserResult", {
171
+ "user": Required[GetUserResultUser],
172
+ "last_activity": Required[str | None],
173
+ "counts": Required[GetUserResultCounts],
174
+ "brains": Required[list[GetUserResultBrainsItem]],
175
+ }, total=False)
176
+
177
+ DeleteUserInput = TypedDict("DeleteUserInput", {
178
+ "user": Required[str],
179
+ }, total=False)
180
+
181
+ DeleteUserResultUser = TypedDict("DeleteUserResultUser", {
182
+ "id": Required[str],
183
+ "name": Required[str],
184
+ "external_id": Required[str | None],
185
+ }, total=False)
186
+
187
+ DeleteUserResult = TypedDict("DeleteUserResult", {
188
+ "user": Required[DeleteUserResultUser],
189
+ "status": Required[Literal["deletion_scheduled"]],
190
+ "deletion_requested_at": Required[str],
191
+ "deletion_on": Required[str],
192
+ "message": Required[str],
193
+ }, total=False)
194
+
195
+ RestoreUserInput = TypedDict("RestoreUserInput", {
196
+ "user": Required[str],
197
+ }, total=False)
198
+
199
+ RestoreUserResultUser = TypedDict("RestoreUserResultUser", {
200
+ "id": Required[str],
201
+ "name": Required[str],
202
+ "external_id": Required[str | None],
203
+ }, total=False)
204
+
205
+ RestoreUserResult = TypedDict("RestoreUserResult", {
206
+ "user": Required[RestoreUserResultUser],
207
+ "status": Required[Literal["active", "archived"]],
208
+ "message": Required[str],
209
+ }, total=False)
210
+
211
+ GetBrainInput = TypedDict("GetBrainInput", {
212
+ "brain": Required[str],
213
+ "user": NotRequired[str],
214
+ }, total=False)
215
+
216
+ GetBrainResultBrain = TypedDict("GetBrainResultBrain", {
217
+ "id": Required[str],
218
+ "name": Required[str],
219
+ "description": Required[str | None],
220
+ "summary": Required[str | None],
221
+ "framing": Required[str | None],
222
+ "framing_updated_at": Required[str | None],
223
+ "status": Required[str],
224
+ "check_schedule": Required[str],
225
+ "created_at": Required[str],
226
+ }, total=False)
227
+
228
+ GetBrainResultUser = TypedDict("GetBrainResultUser", {
229
+ "id": Required[str],
230
+ "name": Required[str],
231
+ }, total=False)
232
+
233
+ GetBrainResultCounts = TypedDict("GetBrainResultCounts", {
234
+ "memories_active": Required[int],
235
+ "memories_archived": Required[int],
236
+ }, total=False)
237
+
238
+ GetBrainResultDocumentsItem = TypedDict("GetBrainResultDocumentsItem", {
239
+ "id": Required[str],
240
+ "title": Required[str],
241
+ "mime": Required[str | None],
242
+ "size_bytes": Required[int | None],
243
+ "state": Required[str],
244
+ "error": Required[str | None],
245
+ "author": Required[str],
246
+ "times_read": Required[int],
247
+ "last_read_at": Required[str | None],
248
+ "created_at": Required[str],
249
+ }, total=False)
250
+
251
+ GetBrainResultWebPagesItem = TypedDict("GetBrainResultWebPagesItem", {
252
+ "id": Required[str],
253
+ "label": Required[str],
254
+ "url": Required[str],
255
+ "active": Required[bool],
256
+ "times_read": Required[int],
257
+ "created_at": Required[str],
258
+ }, total=False)
259
+
260
+ GetBrainResultSavedPromptsItem = TypedDict("GetBrainResultSavedPromptsItem", {
261
+ "id": Required[str],
262
+ "title": Required[str],
263
+ "body": Required[str],
264
+ "times_used": Required[int],
265
+ "created_at": Required[str],
266
+ }, total=False)
267
+
268
+ GetBrainResultLastChecksItem = TypedDict("GetBrainResultLastChecksItem", {
269
+ "id": Required[str],
270
+ "brain_id": Required[str],
271
+ "brain": Required[str | None],
272
+ "trigger": Required[Literal["scheduled", "manual"]],
273
+ "started_at": Required[str],
274
+ "finished_at": Required[str | None],
275
+ "status": Required[Literal["running", "done", "daily_limit", "time_limit", "error"]],
276
+ "memories_processed": Required[int],
277
+ "llm_calls": Required[int],
278
+ "input_tokens": Required[int],
279
+ "output_tokens": Required[int],
280
+ "contradictions_found": Required[int],
281
+ "duplicates_archived": Required[int],
282
+ "merges_made": Required[int],
283
+ "error": Required[str | None],
284
+ }, total=False)
285
+
286
+ GetBrainResult = TypedDict("GetBrainResult", {
287
+ "brain": Required[GetBrainResultBrain],
288
+ "user": Required[GetBrainResultUser],
289
+ "counts": Required[GetBrainResultCounts],
290
+ "documents": Required[list[GetBrainResultDocumentsItem]],
291
+ "web_pages": Required[list[GetBrainResultWebPagesItem]],
292
+ "saved_prompts": Required[list[GetBrainResultSavedPromptsItem]],
293
+ "last_checks": Required[list[GetBrainResultLastChecksItem]],
294
+ }, total=False)
295
+
296
+ ListMemoriesInput = TypedDict("ListMemoriesInput", {
297
+ "user": NotRequired[str],
298
+ "brain": NotRequired[str],
299
+ "type": NotRequired[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
300
+ "tag": NotRequired[str],
301
+ "status": NotRequired[Literal["active", "archived", "all"]],
302
+ "from": NotRequired[str],
303
+ "to": NotRequired[str],
304
+ "offset": NotRequired[int],
305
+ "limit": NotRequired[int],
306
+ }, total=False)
307
+
308
+ ListMemoriesResultUser = TypedDict("ListMemoriesResultUser", {
309
+ "id": Required[str],
310
+ "name": Required[str],
311
+ }, total=False)
312
+
313
+ ListMemoriesResultBrain = TypedDict("ListMemoriesResultBrain", {
314
+ "id": Required[str],
315
+ "name": Required[str],
316
+ }, total=False)
317
+
318
+ ListMemoriesResultMemoriesItem = TypedDict("ListMemoriesResultMemoriesItem", {
319
+ "id": Required[str],
320
+ "brain_id": Required[str],
321
+ "brain": Required[str | None],
322
+ "type": Required[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
323
+ "title": Required[str],
324
+ "content": Required[str],
325
+ "fields": Required[dict[str, Any]],
326
+ "tags": Required[list[str]],
327
+ "status": Required[Literal["active", "archived"]],
328
+ "author": Required[Literal["human", "ai"]],
329
+ "source": Required[str],
330
+ "source_ref": Required[str | None],
331
+ "app": Required[str | None],
332
+ "times_read": Required[int],
333
+ "last_read_at": Required[str | None],
334
+ "version": Required[int],
335
+ "valid_until": Required[str | None],
336
+ "created_at": Required[str],
337
+ "updated_at": Required[str],
338
+ }, total=False)
339
+
340
+ ListMemoriesResult = TypedDict("ListMemoriesResult", {
341
+ "user": Required[ListMemoriesResultUser | None],
342
+ "brain": Required[ListMemoriesResultBrain | None],
343
+ "total": Required[int],
344
+ "offset": Required[int],
345
+ "limit": Required[int],
346
+ "next_offset": Required[int | None],
347
+ "memories": Required[list[ListMemoriesResultMemoriesItem]],
348
+ }, total=False)
349
+
350
+ GetMemoryInput = TypedDict("GetMemoryInput", {
351
+ "id": Required[str],
352
+ }, total=False)
353
+
354
+ GetMemoryResultUser = TypedDict("GetMemoryResultUser", {
355
+ "id": Required[str],
356
+ "name": Required[str],
357
+ }, total=False)
358
+
359
+ GetMemoryResultMergedFromItem = TypedDict("GetMemoryResultMergedFromItem", {
360
+ "id": Required[str],
361
+ "title": Required[str],
362
+ "status": Required[str],
363
+ }, total=False)
364
+
365
+ GetMemoryResultContradictionsItemOther = TypedDict("GetMemoryResultContradictionsItemOther", {
366
+ "id": Required[str],
367
+ "title": Required[str],
368
+ "status": Required[str],
369
+ }, total=False)
370
+
371
+ GetMemoryResultContradictionsItem = TypedDict("GetMemoryResultContradictionsItem", {
372
+ "id": Required[str],
373
+ "status": Required[Literal["open", "resolved", "dismissed"]],
374
+ "reason": Required[str],
375
+ "detected_at": Required[str],
376
+ "resolved_at": Required[str | None],
377
+ "other": Required[GetMemoryResultContradictionsItemOther],
378
+ }, total=False)
379
+
380
+ GetMemoryResult = TypedDict("GetMemoryResult", {
381
+ "id": Required[str],
382
+ "brain_id": Required[str],
383
+ "brain": Required[str | None],
384
+ "type": Required[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
385
+ "title": Required[str],
386
+ "content": Required[str],
387
+ "fields": Required[dict[str, Any]],
388
+ "tags": Required[list[str]],
389
+ "status": Required[Literal["active", "archived"]],
390
+ "author": Required[Literal["human", "ai"]],
391
+ "source": Required[str],
392
+ "source_ref": Required[str | None],
393
+ "app": Required[str | None],
394
+ "times_read": Required[int],
395
+ "last_read_at": Required[str | None],
396
+ "version": Required[int],
397
+ "valid_until": Required[str | None],
398
+ "created_at": Required[str],
399
+ "updated_at": Required[str],
400
+ "user": Required[GetMemoryResultUser],
401
+ "raw_input": Required[str | None],
402
+ "duplicate_of": Required[str | None],
403
+ "merged_from": Required[list[GetMemoryResultMergedFromItem]],
404
+ "contradictions": Required[list[GetMemoryResultContradictionsItem]],
405
+ }, total=False)
406
+
407
+ UpdateMemoryInput = TypedDict("UpdateMemoryInput", {
408
+ "id": Required[str],
409
+ "user": NotRequired[str],
410
+ "title": NotRequired[str],
411
+ "content": NotRequired[str],
412
+ "type": NotRequired[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
413
+ "tags": NotRequired[list[str]],
414
+ "fields": NotRequired[dict[str, Any]],
415
+ "app": NotRequired[str],
416
+ }, total=False)
417
+
418
+ UpdateMemoryResult = TypedDict("UpdateMemoryResult", {
419
+ "id": Required[str],
420
+ "title": Required[str],
421
+ "brain_id": Required[str],
422
+ "brain": Required[str | None],
423
+ "changed": Required[bool],
424
+ "version": Required[int],
425
+ "message": NotRequired[str],
426
+ }, total=False)
427
+
428
+ GetAnalyticsInput = TypedDict("GetAnalyticsInput", {
429
+ "kind": Required[Literal["activity", "searches", "tool_calls", "skills", "checks", "contradictions", "merges"]],
430
+ "user": NotRequired[str],
431
+ "from": NotRequired[str],
432
+ "to": NotRequired[str],
433
+ "offset": NotRequired[int],
434
+ "limit": NotRequired[int],
435
+ }, total=False)
436
+
437
+ GetAnalyticsResultUser = TypedDict("GetAnalyticsResultUser", {
438
+ "id": Required[str],
439
+ "name": Required[str],
440
+ }, total=False)
441
+
442
+ GetAnalyticsResult = TypedDict("GetAnalyticsResult", {
443
+ "kind": Required[Literal["activity", "searches", "tool_calls", "skills", "checks", "contradictions", "merges"]],
444
+ "user": Required[GetAnalyticsResultUser | None],
445
+ "from": Required[str],
446
+ "to": Required[str],
447
+ "total": Required[int],
448
+ "offset": Required[int],
449
+ "limit": Required[int],
450
+ "next_offset": Required[int | None],
451
+ "rows": Required[list[dict[str, Any]]],
452
+ }, total=False)
453
+
454
+ ResolveContradictionInput = TypedDict("ResolveContradictionInput", {
455
+ "id": Required[str],
456
+ "keep": Required[str],
457
+ }, total=False)
458
+
459
+ ResolveContradictionResult = TypedDict("ResolveContradictionResult", {
460
+ "id": Required[str],
461
+ "status": Required[Literal["resolved", "dismissed"]],
462
+ "kept": Required[list[str]],
463
+ "archived": Required[str | None],
464
+ }, total=False)
465
+
466
+ SimilarMemoriesInput = TypedDict("SimilarMemoriesInput", {
467
+ "id": Required[str],
468
+ "limit": NotRequired[int],
469
+ }, total=False)
470
+
471
+ SimilarMemoriesResultMemory = TypedDict("SimilarMemoriesResultMemory", {
472
+ "id": Required[str],
473
+ "title": Required[str],
474
+ "brain_id": Required[str],
475
+ "brain": Required[str | None],
476
+ }, total=False)
477
+
478
+ SimilarMemoriesResultSimilarItem = TypedDict("SimilarMemoriesResultSimilarItem", {
479
+ "id": Required[str],
480
+ "type": Required[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
481
+ "title": Required[str],
482
+ "content": Required[str],
483
+ "score": Required[float],
484
+ }, total=False)
485
+
486
+ SimilarMemoriesResult = TypedDict("SimilarMemoriesResult", {
487
+ "memory": Required[SimilarMemoriesResultMemory],
488
+ "similar": Required[list[SimilarMemoriesResultSimilarItem]],
489
+ }, total=False)
490
+
491
+ MergeMemoriesInput = TypedDict("MergeMemoriesInput", {
492
+ "ids": Required[list[str]],
493
+ "title": Required[str],
494
+ "content": Required[str],
495
+ "type": NotRequired[Literal["fact", "preference", "instruction", "goal", "episode", "learning", "decision", "entity", "example", "procedure", "term", "constraint", "question"]],
496
+ "app": NotRequired[str],
497
+ }, total=False)
498
+
499
+ MergeMemoriesResult = TypedDict("MergeMemoriesResult", {
500
+ "id": Required[str],
501
+ "title": Required[str],
502
+ "brain_id": Required[str],
503
+ "brain": Required[str | None],
504
+ "merged_from": Required[list[str]],
505
+ }, total=False)
506
+
507
+ UndoMergeInput = TypedDict("UndoMergeInput", {
508
+ "id": Required[str],
509
+ }, total=False)
510
+
511
+ UndoMergeResult = TypedDict("UndoMergeResult", {
512
+ "id": Required[str],
513
+ "restored": Required[list[str]],
514
+ }, total=False)
515
+
516
+ ArchiveMemoryInput = TypedDict("ArchiveMemoryInput", {
517
+ "id": Required[str],
518
+ "user": NotRequired[str],
519
+ }, total=False)
520
+
521
+ ArchiveMemoryResult = TypedDict("ArchiveMemoryResult", {
522
+ "id": Required[str],
523
+ "title": Required[str],
524
+ "status": Required[Literal["archived"]],
525
+ "brain_id": Required[str],
526
+ "brain": Required[str | None],
527
+ }, total=False)
528
+
529
+ MentionSkillInput = TypedDict("MentionSkillInput", {
530
+ "name": Required[str],
531
+ "user": NotRequired[str],
532
+ "brain": NotRequired[str],
533
+ "app": NotRequired[str],
534
+ }, total=False)
535
+
536
+ MentionSkillResult = TypedDict("MentionSkillResult", {
537
+ "name": Required[str],
538
+ "known": Required[bool],
539
+ "description": Required[str | None],
540
+ "instructions": Required[str | None],
541
+ "mentions": Required[int],
542
+ "message": NotRequired[str],
543
+ }, total=False)
544
+
545
+ LogToolCallsInputCallsItem = TypedDict("LogToolCallsInputCallsItem", {
546
+ "tool": Required[str],
547
+ "model": NotRequired[str],
548
+ "mcp_server": NotRequired[str],
549
+ "status": NotRequired[Literal["ok", "error"]],
550
+ "duration_ms": NotRequired[int],
551
+ "called_at": NotRequired[str],
552
+ }, total=False)
553
+
554
+ LogToolCallsInput = TypedDict("LogToolCallsInput", {
555
+ "tool": NotRequired[str],
556
+ "model": NotRequired[str],
557
+ "mcp_server": NotRequired[str],
558
+ "status": NotRequired[Literal["ok", "error"]],
559
+ "duration_ms": NotRequired[int],
560
+ "called_at": NotRequired[str],
561
+ "calls": NotRequired[list[LogToolCallsInputCallsItem]],
562
+ "user": NotRequired[str],
563
+ "brain": NotRequired[str],
564
+ "app": NotRequired[str],
565
+ }, total=False)
566
+
567
+ LogToolCallsResult = TypedDict("LogToolCallsResult", {
568
+ "logged": Required[int],
569
+ }, total=False)
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: crystalbrain
3
+ Version: 0.1.0
4
+ Summary: Python client for the CrystalBrain REST API: read and write the memory of your users.
5
+ Project-URL: Homepage, https://crystalbrain.ai
6
+ Project-URL: Documentation, https://crystalbrain.ai/docs/api
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+
14
+ # crystalbrain (Python)
15
+
16
+ Python client for the [CrystalBrain](https://crystalbrain.ai) REST API: read and write the memory of your users from your own app. No dependency (standard library only), Python 3.11 or later. Every input and result is typed (TypedDicts generated from the API's OpenAPI document).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install crystalbrain
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ Create an API key on the Connections page of your CrystalBrain dashboard and keep it on your server.
27
+
28
+ ```python
29
+ import os
30
+ from crystalbrain import CrystalBrain, CrystalBrainError
31
+
32
+ cb = CrystalBrain(os.environ["CRYSTALBRAIN_API_KEY"])
33
+
34
+ # What CrystalBrain knows about a customer, as a context block for your LLM
35
+ result = cb.search(user="cus_123", app="my-app", query="What does this customer prefer?")
36
+ print(result["context_block"])
37
+
38
+ # Save something durable about the customer (an unknown user is created)
39
+ cb.save(user="cus_123", app="my-app", type="preference", title="Delivery on Saturdays", content="Prefers deliveries on Saturday mornings.")
40
+
41
+ # Correct or forget a memory (the previous version is kept)
42
+ memory_id = result["entries"][0]["id"]
43
+ cb.update_memory(id=memory_id, user="cus_123", app="my-app", content="Prefers deliveries on Sunday mornings.")
44
+ cb.archive_memory(id=memory_id, user="cus_123")
45
+
46
+ # Read everything, page by page
47
+ page = cb.list_memories(user="cus_123", limit=100)
48
+ while page["next_offset"] is not None:
49
+ page = cb.list_memories(user="cus_123", limit=100, offset=page["next_offset"])
50
+
51
+ # Errors carry a stable code
52
+ try:
53
+ cb.search(user="cus_123", query="hello")
54
+ except CrystalBrainError as err:
55
+ if err.code == "RATE_LIMITED":
56
+ print(f"retry in {err.retry_after} s")
57
+ ```
58
+
59
+ `user` is your customer's ID or name in your own app; omit it to work on your own account. Query parameters named like Python keywords go through a dict: `cb.get_analytics(user="cus_123", kind="searches", **{"from": "2026-10-01"})`.
60
+
61
+ | Method | API call |
62
+ |---|---|
63
+ | `search(**input)` | `POST /api/v1/search` |
64
+ | `save(**input)` | `POST /api/v1/save` |
65
+ | `list_brains(user=None)` | `GET /api/v1/brains` |
66
+ | `create_brain(**input)` | `POST /api/v1/brains` |
67
+ | `list_users(**input)` | `GET /api/v1/users` |
68
+ | `mention_skill(**input)` | `POST /api/v1/skills` |
69
+ | `log_tool_calls(**input)` | `POST /api/v1/tool-calls` |
70
+ | `update_memory(**input)` | `PATCH /api/v1/memory` |
71
+ | `archive_memory(**input)` | `POST /api/v1/memory/archive` |
72
+ | `delete_user(user)` | `DELETE /api/v1/user` |
73
+ | `restore_user(user)` | `POST /api/v1/user/restore` |
74
+ | `get_user(user=None)` | `GET /api/v1/user` |
75
+ | `get_brain(**input)` | `GET /api/v1/brain` |
76
+ | `list_memories(**input)` | `GET /api/v1/memories` |
77
+ | `get_memory(id)` | `GET /api/v1/memory` |
78
+ | `get_analytics(**input)` | `GET /api/v1/analytics` |
79
+ | `resolve_contradiction(**input)` | `POST /api/v1/contradictions/resolve` |
80
+ | `similar_memories(id, limit=None)` | `GET /api/v1/memory/similar` |
81
+ | `merge_memories(**input)` | `POST /api/v1/memories/merge` |
82
+ | `undo_merge(id)` | `POST /api/v1/memories/unmerge` |
83
+
84
+ Every field and error code: [API reference](https://crystalbrain.ai/docs/api).
85
+
86
+ ## Options
87
+
88
+ `CrystalBrain(api_key, base_url="https://crystalbrain.ai", timeout=60, transport=None)`. `transport` replaces the HTTP layer (tests): a function `(method, url, headers, body) -> (status, headers, body)`.
89
+
90
+ ## Development
91
+
92
+ - Types: `python scripts/generate_types.py` regenerates `src/crystalbrain/types.py` from `../typescript/openapi.json` (the API snapshot shared with the TypeScript SDK; update it there with `npm run spec`).
93
+ - Tests: `PYTHONPATH=src python -m unittest discover tests` (fake transport, no network).
94
+ - Publish: `python -m build` then `python -m twine upload dist/*` (needs a PyPI account).
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1,8 @@
1
+ crystalbrain/__init__.py,sha256=l4xwULh8P9bbV53J6Ar12YN4iUvQFePu4gtYp4x94LM,315
2
+ crystalbrain/client.py,sha256=upjaDhCh0yNsjjGAPcbWZnso89laiNil6ItDypinoZg,10415
3
+ crystalbrain/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ crystalbrain/types.py,sha256=0_OnAjq7zmP5rCap9sHM0ZoXJ9ZfB5k5PsPex8bqiS4,21739
5
+ crystalbrain-0.1.0.dist-info/METADATA,sha256=XCezHdzER9PvLu2tj5Qyfya4HGzUgKRAsOmqkzXmwVk,4187
6
+ crystalbrain-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ crystalbrain-0.1.0.dist-info/licenses/LICENSE,sha256=Z23_wqTcL4gvA0Rzj8IynC5fO6yWfHcKb92rq7AaFzc,1096
8
+ crystalbrain-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cutover Consulting
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.