statewave 0.7.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.
statewave/__init__.py ADDED
@@ -0,0 +1,47 @@
1
+ """Statewave Python SDK."""
2
+
3
+ __version__ = "0.7.0"
4
+
5
+ from statewave.client import AsyncStatewaveClient, StatewaveClient, RetryConfig, DEFAULT_RETRY, NO_RETRY
6
+ from statewave.exceptions import (
7
+ StatewaveAPIError,
8
+ StatewaveConnectionError,
9
+ StatewaveError,
10
+ StatewaveTimeoutError,
11
+ )
12
+ from statewave.models import (
13
+ BatchCreateResult,
14
+ CompileJob,
15
+ CompileResult,
16
+ ContextBundle,
17
+ DeleteResult,
18
+ Episode,
19
+ ListSubjectsResult,
20
+ Memory,
21
+ SearchResult,
22
+ SubjectSummary,
23
+ Timeline,
24
+ )
25
+
26
+ __all__ = [
27
+ "StatewaveClient",
28
+ "AsyncStatewaveClient",
29
+ "RetryConfig",
30
+ "DEFAULT_RETRY",
31
+ "NO_RETRY",
32
+ "StatewaveError",
33
+ "StatewaveAPIError",
34
+ "StatewaveConnectionError",
35
+ "StatewaveTimeoutError",
36
+ "Episode",
37
+ "Memory",
38
+ "CompileJob",
39
+ "CompileResult",
40
+ "SearchResult",
41
+ "ContextBundle",
42
+ "Timeline",
43
+ "DeleteResult",
44
+ "BatchCreateResult",
45
+ "SubjectSummary",
46
+ "ListSubjectsResult",
47
+ ]
statewave/client.py ADDED
@@ -0,0 +1,559 @@
1
+ """Typed Statewave API client — sync and async, with configurable retry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ import time
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from statewave.exceptions import (
13
+ StatewaveAPIError,
14
+ StatewaveConnectionError,
15
+ StatewaveTimeoutError,
16
+ )
17
+ from statewave.models import (
18
+ BatchCreateResult,
19
+ CompileJob,
20
+ CompileResult,
21
+ ContextBundle,
22
+ DeleteResult,
23
+ Episode,
24
+ ListSubjectsResult,
25
+ SearchResult,
26
+ Timeline,
27
+ )
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Retry configuration
32
+ # ---------------------------------------------------------------------------
33
+
34
+ @dataclass(frozen=True)
35
+ class RetryConfig:
36
+ """Retry configuration for transient failures.
37
+
38
+ Attributes:
39
+ max_retries: Maximum number of retry attempts (0 = no retries).
40
+ backoff_base: Base delay in seconds for exponential backoff.
41
+ backoff_max: Maximum delay cap in seconds.
42
+ jitter: Whether to add random jitter to backoff delays.
43
+ retry_on_status: HTTP status codes that trigger a retry.
44
+ """
45
+
46
+ max_retries: int = 3
47
+ backoff_base: float = 0.5
48
+ backoff_max: float = 30.0
49
+ jitter: bool = True
50
+ retry_on_status: frozenset[int] = frozenset({429, 500, 502, 503, 504})
51
+
52
+ def delay_for_attempt(self, attempt: int, retry_after: float | None = None) -> float:
53
+ """Calculate delay for a given attempt number (0-indexed)."""
54
+ if retry_after is not None:
55
+ return min(retry_after, self.backoff_max)
56
+ delay = self.backoff_base * (2 ** attempt)
57
+ delay = min(delay, self.backoff_max)
58
+ if self.jitter:
59
+ delay *= random.uniform(0.5, 1.5)
60
+ return delay
61
+
62
+
63
+ #: No retries — fail immediately on any error.
64
+ NO_RETRY = RetryConfig(max_retries=0)
65
+
66
+ #: Default retry config — 3 retries with 0.5s base backoff.
67
+ DEFAULT_RETRY = RetryConfig()
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Helpers
72
+ # ---------------------------------------------------------------------------
73
+
74
+ def _parse_error(resp: httpx.Response) -> StatewaveAPIError:
75
+ """Parse a structured error response from the Statewave API."""
76
+ try:
77
+ body = resp.json()
78
+ err = body.get("error", {})
79
+ return StatewaveAPIError(
80
+ status_code=resp.status_code,
81
+ code=err.get("code", "unknown"),
82
+ message=err.get("message", resp.reason_phrase or "Unknown error"),
83
+ details=err.get("details"),
84
+ request_id=err.get("request_id"),
85
+ )
86
+ except Exception:
87
+ return StatewaveAPIError(
88
+ status_code=resp.status_code,
89
+ code="unknown",
90
+ message=resp.reason_phrase or f"HTTP {resp.status_code}",
91
+ )
92
+
93
+
94
+ def _handle_transport_error(exc: Exception) -> None:
95
+ """Convert httpx transport exceptions to Statewave exceptions."""
96
+ if isinstance(exc, httpx.ConnectError):
97
+ raise StatewaveConnectionError(str(exc)) from exc
98
+ if isinstance(exc, httpx.TimeoutException):
99
+ raise StatewaveTimeoutError(str(exc)) from exc
100
+ raise StatewaveConnectionError(str(exc)) from exc
101
+
102
+
103
+ def _parse_retry_after(resp: httpx.Response) -> float | None:
104
+ """Extract Retry-After header value as seconds, if present."""
105
+ value = resp.headers.get("retry-after")
106
+ if not value:
107
+ return None
108
+ try:
109
+ return float(value)
110
+ except ValueError:
111
+ return None
112
+
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # Sync client
116
+ # ---------------------------------------------------------------------------
117
+
118
+ class StatewaveClient:
119
+ """Synchronous client for the Statewave API."""
120
+
121
+ def __init__(
122
+ self,
123
+ base_url: str = "http://localhost:8100",
124
+ timeout: float = 30.0,
125
+ *,
126
+ api_key: str | None = None,
127
+ tenant_id: str | None = None,
128
+ retry: RetryConfig | None = None,
129
+ ) -> None:
130
+ self._base_url = base_url.rstrip("/")
131
+ self._retry = retry if retry is not None else DEFAULT_RETRY
132
+ headers: dict[str, str] = {}
133
+ if api_key:
134
+ headers["X-API-Key"] = api_key
135
+ if tenant_id:
136
+ headers["X-Tenant-ID"] = tenant_id
137
+ self._http = httpx.Client(base_url=self._base_url, timeout=timeout, headers=headers)
138
+
139
+ # -- Episodes ----------------------------------------------------------
140
+
141
+ def create_episode(
142
+ self,
143
+ subject_id: str,
144
+ source: str,
145
+ type: str,
146
+ payload: dict[str, Any],
147
+ *,
148
+ metadata: dict[str, Any] | None = None,
149
+ provenance: dict[str, Any] | None = None,
150
+ ) -> Episode:
151
+ """Record a raw interaction episode."""
152
+ return self._request(
153
+ "POST",
154
+ "/v1/episodes",
155
+ json={
156
+ "subject_id": subject_id,
157
+ "source": source,
158
+ "type": type,
159
+ "payload": payload,
160
+ "metadata": metadata or {},
161
+ "provenance": provenance or {},
162
+ },
163
+ model=Episode,
164
+ )
165
+
166
+ def create_episodes_batch(
167
+ self,
168
+ episodes: list[dict[str, Any]],
169
+ ) -> BatchCreateResult:
170
+ """Record multiple episodes in a single request (max 100)."""
171
+ return self._request(
172
+ "POST",
173
+ "/v1/episodes/batch",
174
+ json={"episodes": episodes},
175
+ model=BatchCreateResult,
176
+ )
177
+
178
+ # -- Memories ----------------------------------------------------------
179
+
180
+ def compile_memories(self, subject_id: str) -> CompileResult:
181
+ """Compile memories from unprocessed episodes. Idempotent."""
182
+ return self._request(
183
+ "POST",
184
+ "/v1/memories/compile",
185
+ json={"subject_id": subject_id},
186
+ model=CompileResult,
187
+ )
188
+
189
+ def compile_memories_async(self, subject_id: str) -> CompileJob:
190
+ """Submit async compilation. Returns immediately with a job_id for polling.
191
+
192
+ Use `get_compile_status()` to poll for completion.
193
+ """
194
+ resp = self._http.request(
195
+ "POST", "/v1/memories/compile",
196
+ json={"subject_id": subject_id, "async": True},
197
+ )
198
+ if not resp.is_success:
199
+ raise _parse_error(resp)
200
+ return CompileJob.model_validate(resp.json())
201
+
202
+ def get_compile_status(self, job_id: str) -> CompileJob:
203
+ """Poll the status of an async compile job."""
204
+ return self._request(
205
+ "GET", f"/v1/memories/compile/{job_id}", model=CompileJob,
206
+ )
207
+
208
+ def compile_memories_wait(
209
+ self,
210
+ subject_id: str,
211
+ *,
212
+ poll_interval: float = 0.5,
213
+ timeout: float = 60.0,
214
+ ) -> CompileJob:
215
+ """Submit async compilation and poll until completion or timeout.
216
+
217
+ Convenience method that combines submit + polling.
218
+ Raises TimeoutError if job doesn't complete within timeout.
219
+ """
220
+ job = self.compile_memories_async(subject_id)
221
+ elapsed = 0.0
222
+ while elapsed < timeout:
223
+ time.sleep(poll_interval)
224
+ elapsed += poll_interval
225
+ job = self.get_compile_status(job.job_id)
226
+ if job.status in ("completed", "failed"):
227
+ return job
228
+ raise TimeoutError(f"Compile job {job.job_id} did not complete within {timeout}s")
229
+
230
+ def search_memories(
231
+ self,
232
+ subject_id: str,
233
+ *,
234
+ kind: str | None = None,
235
+ query: str | None = None,
236
+ semantic: bool = False,
237
+ limit: int = 20,
238
+ ) -> SearchResult:
239
+ """Search memories by kind, text query, or semantic similarity."""
240
+ params: dict[str, Any] = {"subject_id": subject_id, "limit": limit}
241
+ if kind:
242
+ params["kind"] = kind
243
+ if query:
244
+ params["q"] = query
245
+ if semantic:
246
+ params["semantic"] = "true"
247
+ return self._request("GET", "/v1/memories/search", params=params, model=SearchResult)
248
+
249
+ # -- Context -----------------------------------------------------------
250
+
251
+ def get_context(
252
+ self,
253
+ subject_id: str,
254
+ task: str,
255
+ *,
256
+ max_tokens: int | None = None,
257
+ ) -> ContextBundle:
258
+ """Assemble a ranked, token-bounded context bundle."""
259
+ body: dict[str, Any] = {"subject_id": subject_id, "task": task}
260
+ if max_tokens is not None:
261
+ body["max_tokens"] = max_tokens
262
+ return self._request("POST", "/v1/context", json=body, model=ContextBundle)
263
+
264
+ def get_context_string(
265
+ self,
266
+ subject_id: str,
267
+ task: str,
268
+ *,
269
+ max_tokens: int | None = None,
270
+ ) -> str:
271
+ """Return just the assembled context string, ready to inject into a prompt."""
272
+ bundle = self.get_context(subject_id, task, max_tokens=max_tokens)
273
+ return bundle.assembled_context
274
+
275
+ # -- Timeline ----------------------------------------------------------
276
+
277
+ def get_timeline(self, subject_id: str) -> Timeline:
278
+ """Get chronological subject timeline."""
279
+ return self._request(
280
+ "GET", "/v1/timeline", params={"subject_id": subject_id}, model=Timeline
281
+ )
282
+
283
+ # -- Subjects ----------------------------------------------------------
284
+
285
+ def delete_subject(self, subject_id: str) -> DeleteResult:
286
+ """Permanently delete all data for a subject."""
287
+ return self._request("DELETE", f"/v1/subjects/{subject_id}", model=DeleteResult)
288
+
289
+ def list_subjects(self, *, limit: int = 50, offset: int = 0) -> ListSubjectsResult:
290
+ """List all known subjects with episode/memory counts."""
291
+ return self._request(
292
+ "GET", "/v1/subjects",
293
+ params={"limit": limit, "offset": offset},
294
+ model=ListSubjectsResult,
295
+ )
296
+
297
+ # -- Lifecycle ---------------------------------------------------------
298
+
299
+ def close(self) -> None:
300
+ self._http.close()
301
+
302
+ def __enter__(self):
303
+ return self
304
+
305
+ def __exit__(self, *args):
306
+ self.close()
307
+
308
+ # -- Internal ----------------------------------------------------------
309
+
310
+ def _request(self, method: str, path: str, *, model: type, json: Any = None, params: Any = None):
311
+ last_exc: Exception | None = None
312
+ for attempt in range(self._retry.max_retries + 1):
313
+ try:
314
+ resp = self._http.request(method, path, json=json, params=params)
315
+ except httpx.HTTPStatusError:
316
+ raise
317
+ except Exception as exc:
318
+ # Connection/timeout error — retryable
319
+ if attempt < self._retry.max_retries:
320
+ last_exc = exc
321
+ time.sleep(self._retry.delay_for_attempt(attempt))
322
+ continue
323
+ _handle_transport_error(exc)
324
+
325
+ if resp.is_success:
326
+ return model.model_validate(resp.json())
327
+
328
+ # Check if retryable status
329
+ if resp.status_code in self._retry.retry_on_status and attempt < self._retry.max_retries:
330
+ retry_after = _parse_retry_after(resp)
331
+ time.sleep(self._retry.delay_for_attempt(attempt, retry_after))
332
+ continue
333
+
334
+ raise _parse_error(resp)
335
+
336
+ # Should not reach here, but just in case
337
+ if last_exc:
338
+ _handle_transport_error(last_exc)
339
+ raise StatewaveConnectionError("Retry attempts exhausted")
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Async client
344
+ # ---------------------------------------------------------------------------
345
+
346
+ class AsyncStatewaveClient:
347
+ """Async client for the Statewave API."""
348
+
349
+ def __init__(
350
+ self,
351
+ base_url: str = "http://localhost:8100",
352
+ timeout: float = 30.0,
353
+ *,
354
+ api_key: str | None = None,
355
+ tenant_id: str | None = None,
356
+ retry: RetryConfig | None = None,
357
+ ) -> None:
358
+ self._base_url = base_url.rstrip("/")
359
+ self._retry = retry if retry is not None else DEFAULT_RETRY
360
+ headers: dict[str, str] = {}
361
+ if api_key:
362
+ headers["X-API-Key"] = api_key
363
+ if tenant_id:
364
+ headers["X-Tenant-ID"] = tenant_id
365
+ self._http = httpx.AsyncClient(base_url=self._base_url, timeout=timeout, headers=headers)
366
+
367
+ # -- Episodes ----------------------------------------------------------
368
+
369
+ async def create_episode(
370
+ self,
371
+ subject_id: str,
372
+ source: str,
373
+ type: str,
374
+ payload: dict[str, Any],
375
+ *,
376
+ metadata: dict[str, Any] | None = None,
377
+ provenance: dict[str, Any] | None = None,
378
+ ) -> Episode:
379
+ """Record a raw interaction episode."""
380
+ return await self._request(
381
+ "POST",
382
+ "/v1/episodes",
383
+ json={
384
+ "subject_id": subject_id,
385
+ "source": source,
386
+ "type": type,
387
+ "payload": payload,
388
+ "metadata": metadata or {},
389
+ "provenance": provenance or {},
390
+ },
391
+ model=Episode,
392
+ )
393
+
394
+ async def create_episodes_batch(
395
+ self,
396
+ episodes: list[dict[str, Any]],
397
+ ) -> BatchCreateResult:
398
+ """Record multiple episodes in a single request (max 100)."""
399
+ return await self._request(
400
+ "POST",
401
+ "/v1/episodes/batch",
402
+ json={"episodes": episodes},
403
+ model=BatchCreateResult,
404
+ )
405
+
406
+ # -- Memories ----------------------------------------------------------
407
+
408
+ async def compile_memories(self, subject_id: str) -> CompileResult:
409
+ """Compile memories from unprocessed episodes. Idempotent."""
410
+ return await self._request(
411
+ "POST",
412
+ "/v1/memories/compile",
413
+ json={"subject_id": subject_id},
414
+ model=CompileResult,
415
+ )
416
+
417
+ async def compile_memories_async(self, subject_id: str) -> CompileJob:
418
+ """Submit async compilation. Returns immediately with a job_id for polling."""
419
+ resp = await self._http.request(
420
+ "POST", "/v1/memories/compile",
421
+ json={"subject_id": subject_id, "async": True},
422
+ )
423
+ if not resp.is_success:
424
+ raise _parse_error(resp)
425
+ return CompileJob.model_validate(resp.json())
426
+
427
+ async def get_compile_status(self, job_id: str) -> CompileJob:
428
+ """Poll the status of an async compile job."""
429
+ return await self._request(
430
+ "GET", f"/v1/memories/compile/{job_id}", model=CompileJob,
431
+ )
432
+
433
+ async def compile_memories_wait(
434
+ self,
435
+ subject_id: str,
436
+ *,
437
+ poll_interval: float = 0.5,
438
+ timeout: float = 60.0,
439
+ ) -> CompileJob:
440
+ """Submit async compilation and poll until completion or timeout."""
441
+ import asyncio as _asyncio
442
+
443
+ job = await self.compile_memories_async(subject_id)
444
+ elapsed = 0.0
445
+ while elapsed < timeout:
446
+ await _asyncio.sleep(poll_interval)
447
+ elapsed += poll_interval
448
+ job = await self.get_compile_status(job.job_id)
449
+ if job.status in ("completed", "failed"):
450
+ return job
451
+ raise TimeoutError(f"Compile job {job.job_id} did not complete within {timeout}s")
452
+
453
+ async def search_memories(
454
+ self,
455
+ subject_id: str,
456
+ *,
457
+ kind: str | None = None,
458
+ query: str | None = None,
459
+ semantic: bool = False,
460
+ limit: int = 20,
461
+ ) -> SearchResult:
462
+ """Search memories by kind, text query, or semantic similarity."""
463
+ params: dict[str, Any] = {"subject_id": subject_id, "limit": limit}
464
+ if kind:
465
+ params["kind"] = kind
466
+ if query:
467
+ params["q"] = query
468
+ if semantic:
469
+ params["semantic"] = "true"
470
+ return await self._request("GET", "/v1/memories/search", params=params, model=SearchResult)
471
+
472
+ # -- Context -----------------------------------------------------------
473
+
474
+ async def get_context(
475
+ self,
476
+ subject_id: str,
477
+ task: str,
478
+ *,
479
+ max_tokens: int | None = None,
480
+ ) -> ContextBundle:
481
+ """Assemble a ranked, token-bounded context bundle."""
482
+ body: dict[str, Any] = {"subject_id": subject_id, "task": task}
483
+ if max_tokens is not None:
484
+ body["max_tokens"] = max_tokens
485
+ return await self._request("POST", "/v1/context", json=body, model=ContextBundle)
486
+
487
+ async def get_context_string(
488
+ self,
489
+ subject_id: str,
490
+ task: str,
491
+ *,
492
+ max_tokens: int | None = None,
493
+ ) -> str:
494
+ """Return just the assembled context string, ready to inject into a prompt."""
495
+ bundle = await self.get_context(subject_id, task, max_tokens=max_tokens)
496
+ return bundle.assembled_context
497
+
498
+ # -- Timeline ----------------------------------------------------------
499
+
500
+ async def get_timeline(self, subject_id: str) -> Timeline:
501
+ """Get chronological subject timeline."""
502
+ return await self._request(
503
+ "GET", "/v1/timeline", params={"subject_id": subject_id}, model=Timeline
504
+ )
505
+
506
+ # -- Subjects ----------------------------------------------------------
507
+
508
+ async def delete_subject(self, subject_id: str) -> DeleteResult:
509
+ """Permanently delete all data for a subject."""
510
+ return await self._request("DELETE", f"/v1/subjects/{subject_id}", model=DeleteResult)
511
+
512
+ async def list_subjects(self, *, limit: int = 50, offset: int = 0) -> ListSubjectsResult:
513
+ """List all known subjects with episode/memory counts."""
514
+ return await self._request(
515
+ "GET", "/v1/subjects",
516
+ params={"limit": limit, "offset": offset},
517
+ model=ListSubjectsResult,
518
+ )
519
+
520
+ # -- Lifecycle ---------------------------------------------------------
521
+
522
+ async def close(self) -> None:
523
+ await self._http.aclose()
524
+
525
+ async def __aenter__(self):
526
+ return self
527
+
528
+ async def __aexit__(self, *args):
529
+ await self.close()
530
+
531
+ # -- Internal ----------------------------------------------------------
532
+
533
+ async def _request(self, method: str, path: str, *, model: type, json: Any = None, params: Any = None):
534
+ import asyncio
535
+
536
+ last_exc: Exception | None = None
537
+ for attempt in range(self._retry.max_retries + 1):
538
+ try:
539
+ resp = await self._http.request(method, path, json=json, params=params)
540
+ except Exception as exc:
541
+ if attempt < self._retry.max_retries:
542
+ last_exc = exc
543
+ await asyncio.sleep(self._retry.delay_for_attempt(attempt))
544
+ continue
545
+ _handle_transport_error(exc)
546
+
547
+ if resp.is_success:
548
+ return model.model_validate(resp.json())
549
+
550
+ if resp.status_code in self._retry.retry_on_status and attempt < self._retry.max_retries:
551
+ retry_after = _parse_retry_after(resp)
552
+ await asyncio.sleep(self._retry.delay_for_attempt(attempt, retry_after))
553
+ continue
554
+
555
+ raise _parse_error(resp)
556
+
557
+ if last_exc:
558
+ _handle_transport_error(last_exc)
559
+ raise StatewaveConnectionError("Retry attempts exhausted")
@@ -0,0 +1,53 @@
1
+ """Statewave SDK exceptions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class StatewaveError(Exception):
9
+ """Base exception for all Statewave SDK errors."""
10
+
11
+ def __init__(self, message: str) -> None:
12
+ self.message = message
13
+ super().__init__(message)
14
+
15
+
16
+ class StatewaveAPIError(StatewaveError):
17
+ """Raised when the Statewave API returns a non-2xx response.
18
+
19
+ Attributes:
20
+ status_code: HTTP status code from the server.
21
+ code: Error code from the structured error response (e.g. "validation_error").
22
+ message: Human-readable error message.
23
+ details: Optional additional error details.
24
+ request_id: Request ID from the server, if available.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ status_code: int,
30
+ code: str,
31
+ message: str,
32
+ details: Any | None = None,
33
+ request_id: str | None = None,
34
+ ) -> None:
35
+ self.status_code = status_code
36
+ self.code = code
37
+ self.details = details
38
+ self.request_id = request_id
39
+ super().__init__(f"[{status_code}] {code}: {message}")
40
+
41
+
42
+ class StatewaveConnectionError(StatewaveError):
43
+ """Raised when the SDK cannot connect to the Statewave server."""
44
+
45
+ def __init__(self, message: str = "Cannot connect to Statewave server") -> None:
46
+ super().__init__(message)
47
+
48
+
49
+ class StatewaveTimeoutError(StatewaveError):
50
+ """Raised when a request to the Statewave server times out."""
51
+
52
+ def __init__(self, message: str = "Request timed out") -> None:
53
+ super().__init__(message)
statewave/models.py ADDED
@@ -0,0 +1,96 @@
1
+ """Pydantic models matching the Statewave API contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from datetime import datetime
7
+ from typing import Any
8
+
9
+ from pydantic import BaseModel, Field
10
+
11
+
12
+ class Episode(BaseModel):
13
+ id: uuid.UUID
14
+ subject_id: str
15
+ source: str
16
+ type: str
17
+ payload: dict[str, Any]
18
+ metadata: dict[str, Any] = Field(default_factory=dict)
19
+ provenance: dict[str, Any] = Field(default_factory=dict)
20
+ created_at: datetime
21
+
22
+
23
+ class Memory(BaseModel):
24
+ id: uuid.UUID
25
+ subject_id: str
26
+ kind: str
27
+ content: str
28
+ summary: str = ""
29
+ confidence: float = 1.0
30
+ valid_from: datetime
31
+ valid_to: datetime | None = None
32
+ source_episode_ids: list[uuid.UUID] = Field(default_factory=list)
33
+ metadata: dict[str, Any] = Field(default_factory=dict)
34
+ status: str = "active"
35
+ created_at: datetime
36
+ updated_at: datetime
37
+
38
+
39
+ class CompileResult(BaseModel):
40
+ subject_id: str
41
+ memories_created: int
42
+ memories: list[Memory]
43
+
44
+
45
+ class SearchResult(BaseModel):
46
+ memories: list[Memory]
47
+
48
+
49
+ class ContextBundle(BaseModel):
50
+ subject_id: str
51
+ task: str
52
+ facts: list[Memory] = Field(default_factory=list)
53
+ episodes: list[Episode] = Field(default_factory=list)
54
+ procedures: list[Memory] = Field(default_factory=list)
55
+ provenance: dict[str, Any] = Field(default_factory=dict)
56
+ assembled_context: str = ""
57
+ token_estimate: int = 0
58
+
59
+
60
+ class Timeline(BaseModel):
61
+ subject_id: str
62
+ episodes: list[Episode]
63
+ memories: list[Memory]
64
+
65
+
66
+ class DeleteResult(BaseModel):
67
+ subject_id: str
68
+ episodes_deleted: int
69
+ memories_deleted: int
70
+
71
+
72
+ class BatchCreateResult(BaseModel):
73
+ episodes_created: int
74
+ episodes: list[Episode]
75
+
76
+
77
+ class SubjectSummary(BaseModel):
78
+ subject_id: str
79
+ episode_count: int
80
+ memory_count: int
81
+
82
+
83
+ class ListSubjectsResult(BaseModel):
84
+ subjects: list[SubjectSummary]
85
+ total: int
86
+
87
+
88
+ class CompileJob(BaseModel):
89
+ """Status of an async compile job."""
90
+
91
+ job_id: str
92
+ status: str # pending, running, completed, failed
93
+ subject_id: str
94
+ memories_created: int = 0
95
+ memories: list[Memory] = Field(default_factory=list)
96
+ error: str | None = None
statewave/py.typed ADDED
File without changes
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.4
2
+ Name: statewave
3
+ Version: 0.7.0
4
+ Summary: Statewave Python SDK — memory runtime for AI agents and applications
5
+ Project-URL: Homepage, https://statewave.ai
6
+ Project-URL: Documentation, https://statewave.ai
7
+ Project-URL: Repository, https://github.com/smaramwbc/statewave-py
8
+ Project-URL: Issues, https://github.com/smaramwbc/statewave-py/issues
9
+ Project-URL: Changelog, https://github.com/smaramwbc/statewave-py/blob/main/CHANGELOG.md
10
+ Author-email: Statewave <hello@statewave.ai>
11
+ License: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agents,ai,context,memory,sdk,statewave
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: httpx<1,>=0.27
25
+ Requires-Dist: pydantic<3,>=2.7
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest-asyncio<1,>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest<10,>=8; extra == 'dev'
29
+ Requires-Dist: ruff<1,>=0.4; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # statewave (Python SDK)
33
+
34
+ [![CI](https://github.com/smaramwbc/statewave-py/workflows/CI/badge.svg)](https://github.com/smaramwbc/statewave-py/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/statewave)](https://pypi.org/project/statewave/)
36
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
37
+
38
+ Statewave Python SDK — memory runtime for AI agents and applications. The TypeScript SDK lives at [`@statewavedev/sdk`](https://github.com/smaramwbc/statewave-ts).
39
+
40
+ > **Part of the Statewave ecosystem:** [Server](https://github.com/smaramwbc/statewave) · **Python SDK** · [TypeScript SDK](https://github.com/smaramwbc/statewave-ts) · [Connectors](https://github.com/smaramwbc/statewave-connectors) · [Docs](https://github.com/smaramwbc/statewave-docs) · [Examples](https://github.com/smaramwbc/statewave-examples) · [Website + demo](https://statewave.ai) · [Admin](https://github.com/smaramwbc/statewave-admin)
41
+ >
42
+ > 📋 **Issues & feature requests:** [statewave/issues](https://github.com/smaramwbc/statewave/issues) (centralized tracker)
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install statewave
48
+ ```
49
+
50
+ > Before public launch, this package was distributed as `statewave-py` on PyPI. The import path (`from statewave import ...`) is unchanged.
51
+
52
+ ## Quick start
53
+
54
+ ```python
55
+ from statewave import StatewaveClient
56
+
57
+ # Basic (no auth)
58
+ with StatewaveClient("http://localhost:8100") as sw:
59
+ ...
60
+
61
+ # With authentication and tenant
62
+ with StatewaveClient(
63
+ "http://localhost:8100",
64
+ api_key="your-key",
65
+ tenant_id="acme",
66
+ ) as sw:
67
+ # Record an episode
68
+ sw.create_episode(
69
+ subject_id="user-42",
70
+ source="support-chat",
71
+ type="conversation",
72
+ payload={
73
+ "messages": [
74
+ {"role": "user", "content": "My name is Alice and I work at Globex."},
75
+ {"role": "assistant", "content": "Welcome Alice!"},
76
+ ]
77
+ },
78
+ )
79
+
80
+ # Compile memories (idempotent)
81
+ result = sw.compile_memories("user-42")
82
+ print(f"Created {result.memories_created} memories")
83
+
84
+ # Retrieve ranked, token-bounded context
85
+ ctx = sw.get_context("user-42", task="Help with billing", max_tokens=300)
86
+ print(ctx.assembled_context)
87
+
88
+ # Batch ingestion (up to 100)
89
+ sw.create_episodes_batch([
90
+ {"subject_id": "user-42", "source": "crm", "type": "note", "payload": {"text": "Prefers email"}},
91
+ {"subject_id": "user-42", "source": "crm", "type": "note", "payload": {"text": "Enterprise plan"}},
92
+ ])
93
+
94
+ # Search memories by kind
95
+ facts = sw.search_memories("user-42", kind="profile_fact")
96
+ for m in facts.memories:
97
+ print(f" [{m.kind}] {m.content}")
98
+
99
+ # Semantic search (requires embeddings)
100
+ results = sw.search_memories("user-42", query="billing", semantic=True)
101
+
102
+ # List all known subjects
103
+ subjects = sw.list_subjects()
104
+ for s in subjects.subjects:
105
+ print(f" {s.subject_id}: {s.episode_count} episodes, {s.memory_count} memories")
106
+
107
+ # Get timeline
108
+ timeline = sw.get_timeline("user-42")
109
+ print(f"{len(timeline.episodes)} episodes, {len(timeline.memories)} memories")
110
+
111
+ # Delete all subject data
112
+ sw.delete_subject("user-42")
113
+ ```
114
+
115
+ ## Async client
116
+
117
+ ```python
118
+ from statewave import AsyncStatewaveClient
119
+
120
+ async with AsyncStatewaveClient("http://localhost:8100") as sw:
121
+ ctx = await sw.get_context("user-42", task="Help with billing")
122
+ print(ctx.assembled_context)
123
+ ```
124
+
125
+ ## Error handling
126
+
127
+ ```python
128
+ from statewave import StatewaveClient, StatewaveAPIError, StatewaveConnectionError
129
+
130
+ try:
131
+ sw = StatewaveClient("http://localhost:8100")
132
+ sw.compile_memories("user-42")
133
+ except StatewaveAPIError as e:
134
+ print(f"API error [{e.status_code}]: {e.code} — {e.message}")
135
+ print(f"Request ID: {e.request_id}")
136
+ except StatewaveConnectionError:
137
+ print("Cannot connect to Statewave server")
138
+ ```
139
+
140
+ ## Where does data go?
141
+
142
+ The SDK is a thin client over the Statewave HTTP API. What leaves the network is determined by the **server's** compiler and embedding configuration, not by the SDK:
143
+
144
+ - Default deployment (heuristic compiler, no embeddings) — nothing leaves your infrastructure.
145
+ - LLM compiler or hosted embeddings — the server sends content to the provider you configure.
146
+
147
+ See [Privacy & Data Flow](https://github.com/smaramwbc/statewave-docs/blob/main/architecture/privacy-and-data-flow.md) for the full breakdown.
148
+
149
+ ## Models
150
+
151
+ All response types are Pydantic models with full type hints:
152
+
153
+ - `Episode` — raw interaction record
154
+ - `Memory` — compiled memory with provenance
155
+ - `CompileResult` — compilation response
156
+ - `SearchResult` — search response
157
+ - `ContextBundle` — assembled context with facts, episodes, provenance
158
+ - `Timeline` — chronological subject history
159
+ - `DeleteResult` — deletion confirmation
160
+ - `BatchCreateResult` — batch ingestion response
161
+ - `SubjectSummary` — subject with episode/memory counts
162
+ - `ListSubjectsResult` — paginated subject listing
163
+
164
+ ## Running tests
165
+
166
+ ```bash
167
+ pip install -e ".[dev]"
168
+ pytest tests/ -v
169
+ ```
170
+
171
+ ## License
172
+
173
+ Apache-2.0
@@ -0,0 +1,9 @@
1
+ statewave/__init__.py,sha256=T-dPbhMZ3n8RIsvHnMRMx8-djfzuULMjSSGMtO9kCPc,971
2
+ statewave/client.py,sha256=78fD4NCXQhMB7eSgL2eXkzEpHI12ih5bxTTfAYqDVFw,19323
3
+ statewave/exceptions.py,sha256=O35A9KgpKMHiKgRdoJicfFakoVfJrEvhhem1h8GhS3M,1572
4
+ statewave/models.py,sha256=cuwBUa5_R_1dGYV215SWqa9ScAa_8UGETB000zxjqUk,2181
5
+ statewave/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ statewave-0.7.0.dist-info/METADATA,sha256=0tkKBVksjKGQkWKQHEf4a2ZDTBJG1LveEMrHTEMdyyk,6381
7
+ statewave-0.7.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ statewave-0.7.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
9
+ statewave-0.7.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.