spm-client 0.2.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.
spm_client/__init__.py ADDED
@@ -0,0 +1,487 @@
1
+ """SPM-Maverick Python SDK.
2
+
3
+ Minimal client for the SPM-Polaris Gateway and MCP endpoints.
4
+ Design: transparent session state, typed errors, OpenAI-compatible chat.
5
+
6
+ Install (local dev):
7
+ pip install -e sdk/python
8
+
9
+ PyPI publish blocked by LEGAL_RELEASE_BLOCKER until legal sign-off.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import os
16
+ import uuid
17
+ from typing import Any, Iterator, Mapping
18
+
19
+ import httpx
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ __version__ = "0.1.0"
25
+ __all__ = [
26
+ "SpmClient",
27
+ "ChatSession",
28
+ "SpmError",
29
+ "AuthError",
30
+ "QuotaError",
31
+ "NotFoundError",
32
+ "ServerError",
33
+ ]
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # Typed error hierarchy
38
+ # ---------------------------------------------------------------------------
39
+
40
+
41
+ class SpmError(Exception):
42
+ """Base exception for all SPM client errors."""
43
+
44
+ def __init__(self, message: str, *, status_code: int | None = None, raw: Any = None) -> None:
45
+ super().__init__(message)
46
+ self.status_code = status_code
47
+ self.raw = raw
48
+
49
+
50
+ class AuthError(SpmError):
51
+ """Raised on 401/403 responses (invalid or missing API key)."""
52
+
53
+
54
+ class QuotaError(SpmError):
55
+ """Raised on 429 responses (rate limit or quota exceeded)."""
56
+
57
+
58
+ class NotFoundError(SpmError):
59
+ """Raised on 404 responses."""
60
+
61
+
62
+ class ServerError(SpmError):
63
+ """Raised on 5xx responses."""
64
+
65
+
66
+ def _format_error_message(resp: httpx.Response, base_msg: str) -> str:
67
+ """Augment a raw HTTP error with cause + fix guidance."""
68
+ status = resp.status_code
69
+ if status in {401, 403}:
70
+ return (
71
+ f"{base_msg}\n"
72
+ "Invalid or expired API key. Check SPM_API_KEY. "
73
+ "Rotate at [dashboard]/api-keys."
74
+ )
75
+ if status == 429:
76
+ retry_after_raw = resp.headers.get("Retry-After", "")
77
+ try:
78
+ retry_after = int(retry_after_raw)
79
+ retry_msg = f"{retry_after}s"
80
+ except (ValueError, TypeError):
81
+ retry_msg = "unknown"
82
+ return (
83
+ f"{base_msg}\n"
84
+ f"Rate limit exceeded. Retry after {retry_msg}. "
85
+ "See docs/rate-limiting."
86
+ )
87
+ if status >= 500:
88
+ corr_id = (
89
+ resp.headers.get("X-Correlation-Id")
90
+ or resp.headers.get("X-Request-Id", "unknown")
91
+ )
92
+ return (
93
+ f"{base_msg}\n"
94
+ f"Server error ({status}). Check service health at /health. "
95
+ f"Correlation ID: {corr_id}"
96
+ )
97
+ return base_msg
98
+
99
+
100
+ def _raise_for_status(resp: httpx.Response) -> None:
101
+ if resp.is_success:
102
+ return
103
+ try:
104
+ body = resp.json()
105
+ msg = body.get("error", {}).get("message", resp.text) if isinstance(body, dict) else resp.text
106
+ except Exception:
107
+ msg = resp.text or f"HTTP {resp.status_code}"
108
+ msg = _format_error_message(resp, msg)
109
+ if resp.status_code in {401, 403}:
110
+ raise AuthError(msg, status_code=resp.status_code, raw=resp.text)
111
+ if resp.status_code == 429:
112
+ raise QuotaError(msg, status_code=resp.status_code, raw=resp.text)
113
+ if resp.status_code == 404:
114
+ raise NotFoundError(msg, status_code=resp.status_code, raw=resp.text)
115
+ if resp.status_code >= 500:
116
+ raise ServerError(msg, status_code=resp.status_code, raw=resp.text)
117
+ raise SpmError(msg, status_code=resp.status_code, raw=resp.text)
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Client
122
+ # ---------------------------------------------------------------------------
123
+
124
+
125
+ class SpmClient:
126
+ """Low-level HTTP client for the SPM-Polaris Gateway.
127
+
128
+ Args:
129
+ api_key: Bearer key issued by the SPM-Polaris console.
130
+ base_url: Gateway base URL, e.g. ``https://api.example.com``.
131
+ timeout: Per-request timeout in seconds (default 120s for streaming).
132
+ """
133
+
134
+ @classmethod
135
+ def from_env(cls) -> "SpmClient":
136
+ """Create a client from environment variables.
137
+
138
+ Reads ``SPM_API_KEY`` and ``SPM_GATEWAY_URL``. Raises :class:`ValueError`
139
+ with an actionable message if any required variable is missing or empty.
140
+ """
141
+ api_key = os.environ.get("SPM_API_KEY", "").strip()
142
+ base_url = os.environ.get("SPM_GATEWAY_URL", "").strip()
143
+
144
+ missing: list[str] = []
145
+ if not api_key:
146
+ missing.append(" SPM_API_KEY — your API key from the SPM dashboard")
147
+ if not base_url:
148
+ missing.append(" SPM_GATEWAY_URL — e.g. http://localhost:18081 for local dev")
149
+
150
+ if missing:
151
+ raise ValueError(
152
+ "Cannot create SpmClient from environment. Missing variables:\n"
153
+ + "\n".join(missing)
154
+ + "\n\nSet these variables or pass api_key and base_url directly to SpmClient()."
155
+ )
156
+
157
+ return cls(api_key=api_key, base_url=base_url)
158
+
159
+ def __init__(
160
+ self,
161
+ api_key: str,
162
+ *,
163
+ base_url: str = "http://localhost:18081",
164
+ timeout: float = 120.0,
165
+ ) -> None:
166
+ self.api_key = api_key
167
+ self.base_url = base_url.rstrip("/")
168
+ self._http = httpx.Client(
169
+ base_url=self.base_url,
170
+ headers={"Authorization": f"Bearer {api_key}"},
171
+ timeout=timeout,
172
+ )
173
+
174
+ def close(self) -> None:
175
+ self._http.close()
176
+
177
+ def __enter__(self) -> "SpmClient":
178
+ return self
179
+
180
+ def __exit__(self, *_: Any) -> None:
181
+ self.close()
182
+
183
+ def health(self) -> dict[str, Any]:
184
+ """Return the gateway health status dict."""
185
+ resp = self._http.get("/health")
186
+ _raise_for_status(resp)
187
+ return resp.json()
188
+
189
+ def chat(
190
+ self,
191
+ messages: list[dict[str, str]],
192
+ *,
193
+ model: str = "gpt-4o-mini",
194
+ stream: bool = False,
195
+ **kwargs: Any,
196
+ ) -> dict[str, Any] | Iterator[str]:
197
+ """Send a chat-completion request.
198
+
199
+ When ``stream=True`` returns an iterator of raw SSE data lines.
200
+ When ``stream=False`` returns the decoded response dict.
201
+ """
202
+ payload: dict[str, Any] = {"model": model, "messages": messages, "stream": stream, **kwargs}
203
+ if stream:
204
+ return self._stream_chat(payload)
205
+ resp = self._http.post("/v1/chat/completions", json=payload)
206
+ _raise_for_status(resp)
207
+ return resp.json()
208
+
209
+ def _stream_chat(self, payload: dict[str, Any]) -> Iterator[str]:
210
+ with self._http.stream("POST", "/v1/chat/completions", json=payload) as resp:
211
+ _raise_for_status(resp)
212
+ for line in resp.iter_lines():
213
+ if line.startswith("data: "):
214
+ data = line[6:]
215
+ if data.strip() == "[DONE]":
216
+ break
217
+ yield data
218
+
219
+ # -- memory plane (/v2) ------------------------------------------------
220
+
221
+ def remember(
222
+ self,
223
+ text: str,
224
+ *,
225
+ idempotency_key: str,
226
+ source_id: str | None = None,
227
+ topic: str = "general",
228
+ source_kind: str = "",
229
+ source_timestamp: str = "",
230
+ user_partition: str = "",
231
+ ) -> dict[str, Any]:
232
+ """Store one observation. Repeating the key is idempotent."""
233
+ payload: dict[str, Any] = {"text": text, "idempotency_key": idempotency_key, "topic": topic}
234
+ if source_id:
235
+ payload["source_id"] = source_id
236
+ if source_kind:
237
+ payload["source_kind"] = source_kind
238
+ if source_timestamp:
239
+ payload["source_timestamp"] = source_timestamp
240
+ if user_partition:
241
+ payload["user_partition"] = user_partition
242
+ resp = self._http.post("/v2/ingest", json=payload)
243
+ _raise_for_status(resp)
244
+ return resp.json()
245
+
246
+ def remember_many(self, items: list[dict[str, Any]], *, stop_on_error: bool = False) -> dict[str, Any]:
247
+ """Ingest up to 500 observations; per-item outcomes are returned."""
248
+ if len(items) > 500:
249
+ raise ValueError("at most 500 items per call")
250
+ resp = self._http.post("/v2/ingest/batch", json={"items": items, "stop_on_error": stop_on_error})
251
+ _raise_for_status(resp)
252
+ return resp.json()
253
+
254
+ def recall(
255
+ self,
256
+ query: str,
257
+ *,
258
+ top_k: int = 20,
259
+ topics: list[str] | None = None,
260
+ since: str = "",
261
+ until: str = "",
262
+ user_partition: str = "",
263
+ ) -> dict[str, Any]:
264
+ """Recall evidence. Check ``gate_reason`` before trusting ``answer``."""
265
+ payload: dict[str, Any] = {"query": query, "top_k": top_k}
266
+ if topics:
267
+ payload["topics"] = topics
268
+ if since:
269
+ payload["since"] = since
270
+ if until:
271
+ payload["until"] = until
272
+ if user_partition:
273
+ payload["user_partition"] = user_partition
274
+ resp = self._http.post("/v2/recall", json=payload)
275
+ _raise_for_status(resp)
276
+ return resp.json()
277
+
278
+ def read(self, read_tokens: list[str], *, user_partition: str = "") -> dict[str, Any]:
279
+ """Resolve recall read tokens to chunked source text (tokens live ~300 s)."""
280
+ if len(read_tokens) > 32:
281
+ raise ValueError("at most 32 read tokens per call")
282
+ payload: dict[str, Any] = {"read_tokens": read_tokens}
283
+ if user_partition:
284
+ payload["user_partition"] = user_partition
285
+ resp = self._http.post("/v2/read", json=payload)
286
+ _raise_for_status(resp)
287
+ return resp.json()
288
+
289
+ def recall_text(self, query: str, **kwargs: Any) -> str:
290
+ """Recall and join the exact text of every readable evidence item."""
291
+ result = self.recall(query, **kwargs)
292
+ tokens = [ref["read_token"] for ref in result.get("evidence_refs", []) if ref.get("read_token")]
293
+ if not tokens:
294
+ return ""
295
+ spans = self.read(tokens, user_partition=kwargs.get("user_partition", "")).get("spans", [])
296
+ return "\n".join(
297
+ chunk.get("text", "")
298
+ for span in spans
299
+ for chunk in span.get("chunks", [])
300
+ )
301
+
302
+ def purge(self, *, source_id: str) -> dict[str, Any]:
303
+ """Delete one source; the response carries a signed receipt."""
304
+ resp = self._http.post("/v2/purge", json={"source_id": source_id})
305
+ _raise_for_status(resp)
306
+ return resp.json()
307
+
308
+ def partitions(self, *, prefix: str = "", limit: int = 200) -> dict[str, Any]:
309
+ resp = self._http.get("/v2/partitions", params={"prefix": prefix, "limit": limit})
310
+ _raise_for_status(resp)
311
+ return resp.json()
312
+
313
+ def export_partition(self, partition: str) -> dict[str, Any]:
314
+ resp = self._http.post(f"/v2/partitions/{partition}/export")
315
+ _raise_for_status(resp)
316
+ return resp.json()
317
+
318
+ def wipe_partition(self, partition: str) -> dict[str, Any]:
319
+ resp = self._http.post(f"/v2/partitions/{partition}/wipe")
320
+ _raise_for_status(resp)
321
+ return resp.json()
322
+
323
+ def export(self, *, user_partition: str = "") -> dict[str, Any]:
324
+ """Whole-scope portable bundle with a checksum."""
325
+ resp = self._http.post("/v2/export", json={"user_partition": user_partition})
326
+ _raise_for_status(resp)
327
+ return resp.json()
328
+
329
+ def import_bundle(
330
+ self, bundle: dict[str, Any], *, user_partition: str = "", conflict: str = "skip"
331
+ ) -> dict[str, Any]:
332
+ resp = self._http.post(
333
+ "/v2/import",
334
+ json={"bundle": bundle, "user_partition": user_partition, "conflict": conflict},
335
+ )
336
+ _raise_for_status(resp)
337
+ return resp.json()
338
+
339
+ def subscribe(
340
+ self, url: str, events: list[str]
341
+ ) -> dict[str, Any]:
342
+ """Register an HMAC-signed webhook; the secret is returned once."""
343
+ resp = self._http.post("/v2/events/subscriptions", json={"url": url, "events": events})
344
+ _raise_for_status(resp)
345
+ return resp.json()
346
+
347
+ def subscriptions(self) -> list[dict[str, Any]]:
348
+ resp = self._http.get("/v2/events/subscriptions")
349
+ _raise_for_status(resp)
350
+ return resp.json()
351
+
352
+ def unsubscribe(self, subscription_id: str) -> dict[str, Any]:
353
+ resp = self._http.delete(f"/v2/events/subscriptions/{subscription_id}")
354
+ _raise_for_status(resp)
355
+ return resp.json()
356
+
357
+ def replay_events(self, *, since_id: str = "") -> dict[str, Any]:
358
+ resp = self._http.post("/v2/events/replay", json={"since_id": since_id})
359
+ _raise_for_status(resp)
360
+ return resp.json()
361
+
362
+ def list_receipts(self, *, limit: int = 20, cursor: str | None = None) -> dict[str, Any]:
363
+ """List recent request receipts for audit and debugging.
364
+
365
+ Args:
366
+ limit: Maximum number of receipts to return.
367
+ cursor: Opaque pagination cursor from a previous response (cursor-based
368
+ pagination — the gateway does not accept an ``offset`` parameter).
369
+ """
370
+ params: dict[str, Any] = {"limit": limit}
371
+ if cursor is not None:
372
+ params["cursor"] = cursor
373
+ resp = self._http.get("/v1/spm/requests", params=params)
374
+ _raise_for_status(resp)
375
+ return resp.json()
376
+
377
+ def get_receipt(self, receipt_id: str) -> dict[str, Any]:
378
+ """Fetch a single request receipt by ID."""
379
+ resp = self._http.get(f"/v1/spm/requests/{receipt_id}")
380
+ _raise_for_status(resp)
381
+ return resp.json()
382
+
383
+ def session(
384
+ self, *, session_id: str | None = None, system_prompt: str | None = None
385
+ ) -> "ChatSession":
386
+ """Create a stateful chat session backed by this client."""
387
+ return ChatSession(client=self, session_id=session_id, system_prompt=system_prompt)
388
+
389
+
390
+ # ---------------------------------------------------------------------------
391
+ # Session
392
+ # ---------------------------------------------------------------------------
393
+
394
+
395
+ class ChatSession:
396
+ """Stateful chat session with transparent message history management.
397
+
398
+ Maintains the full conversation history so callers only need to pass
399
+ the latest user message. Memory is managed server-side; the session
400
+ only tracks the local message list for context formatting.
401
+
402
+ Args:
403
+ client: An :class:`SpmClient` instance.
404
+ session_id: Opaque identifier forwarded as ``X-Session-Id``. A UUID
405
+ is generated if not provided.
406
+ system_prompt: Optional system message prepended to every request.
407
+ """
408
+
409
+ def __init__(
410
+ self,
411
+ client: SpmClient,
412
+ *,
413
+ session_id: str | None = None,
414
+ system_prompt: str | None = None,
415
+ ) -> None:
416
+ self._client = client
417
+ self.session_id = session_id or str(uuid.uuid4())
418
+ self._history: list[dict[str, str]] = []
419
+ if system_prompt:
420
+ self._history.append({"role": "system", "content": system_prompt})
421
+
422
+ def send(self, content: str, *, model: str = "gpt-4o-mini", stream: bool = False, **kwargs: Any) -> str | Iterator[str]:
423
+ """Send a user message and return the assistant reply.
424
+
425
+ The history is updated automatically. When ``stream=True``, returns
426
+ an iterator of text chunks and the history is updated lazily on
427
+ exhaustion.
428
+ """
429
+ if stream:
430
+ # Append user message INSIDE the generator so a discarded iterator
431
+ # (caller breaks early) leaves history in a consistent state.
432
+ return self._stream_reply(content, model=model, **kwargs)
433
+ pending_user = {"role": "user", "content": content}
434
+ self._history.append(pending_user)
435
+ try:
436
+ result = self._client.chat(self._history, model=model, stream=False, **kwargs)
437
+ # Guard for tool-call responses where content may be None.
438
+ message = result.get("choices", [{}])[0].get("message", {})
439
+ reply: str = message.get("content") or ""
440
+ self._history.append({"role": "assistant", "content": reply})
441
+ return reply
442
+ except BaseException:
443
+ if self._history and self._history[-1] is pending_user:
444
+ self._history.pop()
445
+ raise
446
+
447
+ def _stream_reply(self, content: str, **kwargs: Any) -> Iterator[str]:
448
+ # Append user message only after the generator starts executing so that
449
+ # abandoning the iterator before first iteration is harmless.
450
+ self._history.append({"role": "user", "content": content})
451
+ chunks: list[str] = []
452
+ try:
453
+ for raw in self._client.chat(self._history, stream=True, **kwargs):
454
+ try:
455
+ data = json.loads(raw)
456
+ delta = data["choices"][0]["delta"].get("content", "")
457
+ if delta:
458
+ chunks.append(delta)
459
+ yield delta
460
+ except Exception:
461
+ logger.debug("stream parse error", exc_info=True)
462
+ continue
463
+ finally:
464
+ # Runs on normal exhaustion, early break (GeneratorExit), or
465
+ # any exception. If chunks is empty the assistant never replied
466
+ # (or was interrupted) — pop the user message so history stays
467
+ # in an alternating user/assistant pattern.
468
+ if chunks:
469
+ self._history.append({"role": "assistant", "content": "".join(chunks)})
470
+ elif self._history and self._history[-1] == {"role": "user", "content": content}:
471
+ self._history.pop()
472
+
473
+ @property
474
+ def history(self) -> list[dict[str, str]]:
475
+ """Return a copy of the current conversation history."""
476
+ return list(self._history)
477
+
478
+ def reset(self, *, keep_system: bool = True) -> None:
479
+ """Clear the conversation history.
480
+
481
+ Args:
482
+ keep_system: If True, retain the initial system message (default).
483
+ """
484
+ if keep_system and self._history and self._history[0]["role"] == "system":
485
+ self._history = [self._history[0]]
486
+ else:
487
+ self._history = []