modelsaar 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.
Files changed (54) hide show
  1. modelsaar/__init__.py +13 -0
  2. modelsaar/adapters/__init__.py +27 -0
  3. modelsaar/adapters/base.py +274 -0
  4. modelsaar/adapters/ollama.py +317 -0
  5. modelsaar/adapters/openai_compat.py +296 -0
  6. modelsaar/catalogue/__init__.py +72 -0
  7. modelsaar/catalogue/starter.yaml +435 -0
  8. modelsaar/cli.py +880 -0
  9. modelsaar/clientconfig/__init__.py +364 -0
  10. modelsaar/config.py +631 -0
  11. modelsaar/doctor.py +233 -0
  12. modelsaar/evaluation/__init__.py +1 -0
  13. modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
  14. modelsaar/evaluation/harness.py +768 -0
  15. modelsaar/evaluation/judge.py +173 -0
  16. modelsaar/evaluation/sandbox.py +341 -0
  17. modelsaar/evaluation/scoring.py +233 -0
  18. modelsaar/learning.py +227 -0
  19. modelsaar/lifecycle.py +208 -0
  20. modelsaar/pipelines.py +439 -0
  21. modelsaar/probes.py +526 -0
  22. modelsaar/protocol/__init__.py +1 -0
  23. modelsaar/protocol/anthropic.py +401 -0
  24. modelsaar/protocol/decisions.py +229 -0
  25. modelsaar/protocol/openai.py +322 -0
  26. modelsaar/protocol/responses.py +560 -0
  27. modelsaar/protocol/sse.py +181 -0
  28. modelsaar/registry.py +229 -0
  29. modelsaar/responses_store.py +117 -0
  30. modelsaar/routing/__init__.py +1 -0
  31. modelsaar/routing/admission.py +359 -0
  32. modelsaar/routing/affinity.py +131 -0
  33. modelsaar/routing/cascade.py +53 -0
  34. modelsaar/routing/classifier.py +298 -0
  35. modelsaar/routing/decision.py +85 -0
  36. modelsaar/routing/eligibility.py +158 -0
  37. modelsaar/routing/requirements.py +290 -0
  38. modelsaar/routing/router.py +1026 -0
  39. modelsaar/routing/scoring.py +179 -0
  40. modelsaar/routing/tokens.py +114 -0
  41. modelsaar/runtime.py +82 -0
  42. modelsaar/security.py +63 -0
  43. modelsaar/server.py +1546 -0
  44. modelsaar/static/status.html +95 -0
  45. modelsaar/store.py +208 -0
  46. modelsaar/testing/__init__.py +1 -0
  47. modelsaar/testing/fakebackend.py +661 -0
  48. modelsaar-0.2.0.dist-info/METADATA +285 -0
  49. modelsaar-0.2.0.dist-info/RECORD +54 -0
  50. modelsaar-0.2.0.dist-info/WHEEL +5 -0
  51. modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
  52. modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
  53. modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
  54. modelsaar-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,181 @@
1
+ """Incremental Server-Sent-Events parsing and relay helpers.
2
+
3
+ The relay forwards upstream SSE frames to the client one *complete* event at
4
+ a time, tolerating partial network frames and multi-byte UTF-8 boundaries. It
5
+ never re-chunks or concatenates streams from different deployments.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Iterator
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+
16
+ @dataclass
17
+ class SSEEvent:
18
+ raw: bytes # the complete frame including trailing blank line
19
+ data: str | None = None # joined data lines (without "data:" prefix)
20
+ event: str | None = None
21
+
22
+ def json(self) -> dict[str, Any] | None:
23
+ if self.data is None or self.data.strip() == "[DONE]":
24
+ return None
25
+ try:
26
+ v = json.loads(self.data)
27
+ return v if isinstance(v, dict) else None
28
+ except json.JSONDecodeError:
29
+ return None
30
+
31
+ @property
32
+ def is_done(self) -> bool:
33
+ return self.data is not None and self.data.strip() == "[DONE]"
34
+
35
+ @property
36
+ def kind(self) -> str:
37
+ """Classify the frame for completion validation:
38
+ ``comment`` — no data field (SSE comments, keepalives, event-only frames); ignorable.
39
+ ``done`` — the ``[DONE]`` sentinel.
40
+ ``chunk`` — a JSON object shaped like a chat completion chunk (``choices`` list), a usage-only
41
+ frame (``usage`` object, possibly with empty ``choices``) or an upstream error object.
42
+ ``malformed`` — data that is not JSON, not an object, or an object with none of those keys.
43
+ Only ``chunk`` frames are evidence of a completion; ``malformed`` frames invalidate the stream."""
44
+ if self.data is None:
45
+ return "comment"
46
+ if self.is_done:
47
+ return "done"
48
+ try:
49
+ v = json.loads(self.data)
50
+ except json.JSONDecodeError:
51
+ return "malformed"
52
+ if not isinstance(v, dict):
53
+ return "malformed"
54
+ if isinstance(v.get("choices"), list) or isinstance(v.get("usage"), dict) or "error" in v:
55
+ return "chunk"
56
+ return "malformed"
57
+
58
+
59
+ @dataclass
60
+ class SSEParser:
61
+ """Feed bytes, get complete events. Keeps partial frames buffered."""
62
+
63
+ _buf: bytes = b""
64
+ events_seen: int = 0
65
+
66
+ def feed(self, chunk: bytes) -> Iterator[SSEEvent]:
67
+ self._buf += chunk
68
+ while True:
69
+ # A frame ends at a blank line: \n\n or \r\n\r\n
70
+ idx_n = self._buf.find(b"\n\n")
71
+ idx_rn = self._buf.find(b"\r\n\r\n")
72
+ candidates = [i for i in (idx_n, idx_rn) if i != -1]
73
+ if not candidates:
74
+ return
75
+ if idx_rn != -1 and (idx_n == -1 or idx_rn < idx_n):
76
+ end = idx_rn + 4
77
+ else:
78
+ end = idx_n + 2
79
+ frame = self._buf[:end]
80
+ self._buf = self._buf[end:]
81
+ self.events_seen += 1
82
+ yield self._parse(frame)
83
+
84
+ def flush(self) -> Iterator[SSEEvent]:
85
+ """Emit whatever is buffered as a final (possibly incomplete) frame."""
86
+ if self._buf.strip():
87
+ frame = self._buf
88
+ self._buf = b""
89
+ frame = frame.rstrip(b"\r\n") + b"\n\n"
90
+ yield self._parse(frame)
91
+
92
+ @staticmethod
93
+ def _parse(frame: bytes) -> SSEEvent:
94
+ data_lines: list[str] = []
95
+ event: str | None = None
96
+ text = frame.decode("utf-8", errors="replace")
97
+ for line in text.splitlines():
98
+ if line.startswith("data:"):
99
+ data_lines.append(line[5:].lstrip(" "))
100
+ elif line.startswith("event:"):
101
+ event = line[6:].strip()
102
+ data = "\n".join(data_lines) if data_lines else None
103
+ return SSEEvent(raw=frame, data=data, event=event)
104
+
105
+
106
+ def rewrite_model_field(ev: SSEEvent, model_name: str) -> bytes:
107
+ """Return the frame bytes with chunk['model'] replaced, or the raw frame if not JSON."""
108
+ obj = ev.json()
109
+ if obj is None or "model" not in obj:
110
+ return ev.raw
111
+ obj["model"] = model_name
112
+ return b"data: " + json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + b"\n\n"
113
+
114
+
115
+ @dataclass
116
+ class StreamObserver:
117
+ """Tracks what the relay has seen for diagnostics and admission accounting."""
118
+
119
+ first_byte_at: float | None = None
120
+ events: int = 0
121
+ content_chunks: int = 0
122
+ reasoning_chunks: int = 0
123
+ tool_call_deltas: int = 0
124
+ finish_reason: str | None = None
125
+ usage: dict[str, Any] | None = None
126
+ saw_done: bool = False
127
+ error: str | None = None
128
+ tool_call_indexes: set[int] = field(default_factory=set)
129
+ valid_chunks: int = 0 # frames that are completion chunks / usage frames / error objects
130
+ comments: int = 0 # keepalives and comments (ignored for validation)
131
+ malformed: int = 0 # data frames that are not a completion structure
132
+ malformed_sample: str = ""
133
+
134
+ def completion_problem(self) -> str | None:
135
+ """Why the observed stream is not a validated completion, or None when it is one.
136
+ A completion needs at least one completion chunk, no malformed data frame, and either a
137
+ finish_reason or the [DONE] sentinel. Comments/keepalives and usage-only frames are fine."""
138
+ if self.error is not None:
139
+ return f"upstream emitted an error event: {self.error[:160]}"
140
+ if self.malformed:
141
+ return f"upstream emitted {self.malformed} malformed SSE data frame(s) (first: {self.malformed_sample!r})"
142
+ if not self.valid_chunks:
143
+ return "upstream stream contained no completion chunk"
144
+ if not self.saw_done and self.finish_reason is None:
145
+ return "upstream stream ended without a finish_reason or [DONE] (truncated)"
146
+ return None
147
+
148
+ def observe(self, ev: SSEEvent) -> None:
149
+ self.events += 1
150
+ kind = ev.kind
151
+ if kind == "done":
152
+ self.saw_done = True
153
+ return
154
+ if kind == "comment":
155
+ self.comments += 1
156
+ return
157
+ if kind == "malformed":
158
+ self.malformed += 1
159
+ if not self.malformed_sample:
160
+ self.malformed_sample = (ev.data or "")[:80]
161
+ return
162
+ self.valid_chunks += 1
163
+ obj = ev.json()
164
+ if not obj:
165
+ return
166
+ if "error" in obj:
167
+ self.error = str(obj["error"])
168
+ if obj.get("usage"):
169
+ self.usage = obj["usage"]
170
+ for ch in obj.get("choices") or []:
171
+ if ch.get("finish_reason"):
172
+ self.finish_reason = ch["finish_reason"]
173
+ delta = ch.get("delta") or {}
174
+ if delta.get("content"):
175
+ self.content_chunks += 1
176
+ if delta.get("reasoning_content") or delta.get("reasoning"):
177
+ self.reasoning_chunks += 1
178
+ for tc in delta.get("tool_calls") or []:
179
+ self.tool_call_deltas += 1
180
+ if isinstance(tc.get("index"), int):
181
+ self.tool_call_indexes.add(tc["index"])
modelsaar/registry.py ADDED
@@ -0,0 +1,229 @@
1
+ """Deployment registry.
2
+
3
+ The routing unit is an exact *deployment*: a model served by a specific
4
+ backend with a specific runtime, template, quantization, context and
5
+ resource pool. The registry keeps distinct states (configured, discovered,
6
+ available, loaded, healthy) and three-state capabilities with provenance.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import time
14
+ from dataclasses import asdict, dataclass, field
15
+ from typing import Any, Literal
16
+
17
+ Tri = Literal["supported", "unsupported", "unknown"]
18
+ Role = Literal["generative", "embedding", "decision", "ocr", "rerank", "guardrail"]
19
+
20
+ CAPABILITY_KEYS = (
21
+ "tools",
22
+ "tool_choice_required",
23
+ "parallel_tools",
24
+ "json_schema",
25
+ "json_object",
26
+ "streaming",
27
+ "vision",
28
+ "audio_in",
29
+ "video_in",
30
+ "thinking",
31
+ "continuation",
32
+ )
33
+
34
+
35
+ @dataclass
36
+ class CapValue:
37
+ value: Tri = "unknown"
38
+ # "source_claim" (backend metadata / model card), "probe", "operator", "adapter"
39
+ provenance: str = "none"
40
+ checked_at: float | None = None
41
+ note: str = ""
42
+
43
+ def as_dict(self) -> dict[str, Any]:
44
+ return asdict(self)
45
+
46
+
47
+ @dataclass
48
+ class Measurement:
49
+ """Measured latency/quality evidence for a deployment (per fingerprint)."""
50
+
51
+ task: str
52
+ quality: float | None = None # 0..1 measured success rate
53
+ samples: int = 0
54
+ p50_ms: float | None = None
55
+ p95_ms: float | None = None
56
+ ttft_ms: float | None = None
57
+ load_ms: float | None = None
58
+ source: str = "eval" # eval | probe | live
59
+ measured_at: float | None = None
60
+ # Measurement conditions (hardware/context/generation settings/workload) so a number is never
61
+ # read outside the conditions it was taken under.
62
+ conditions: dict[str, Any] = field(default_factory=dict)
63
+
64
+
65
+ @dataclass
66
+ class Deployment:
67
+ id: str # "<backend_id>/<model_name>"
68
+ backend_id: str
69
+ backend_type: str
70
+ model: str
71
+ role: Role = "generative"
72
+ publisher: str = ""
73
+ family: str = ""
74
+ parameter_size: str = ""
75
+ quantization: str = ""
76
+ digest: str = ""
77
+ # Checkpoint identity: a weights digest from the runtime or an operator declaration. Empty
78
+ # means unknown; a bare model-name match is never an identity.
79
+ identity: str = ""
80
+ identity_source: str = ""
81
+ # Execution endpoint (scheme://host:port/path of the backend base URL). Part of the
82
+ # fingerprint: the same backend id and model name on another server is other evidence.
83
+ endpoint: str = ""
84
+ runtime: str = ""
85
+ runtime_version: str = ""
86
+ template_hash: str = ""
87
+ context_length: int | None = None
88
+ max_output_tokens: int | None = None
89
+ embedding_dimensions: int | None = None
90
+ resource_pool: str | None = None
91
+ locality: Literal["local", "remote", "unknown"] = "unknown"
92
+ locality_evidence: str = ""
93
+ capabilities: dict[str, CapValue] = field(default_factory=lambda: {k: CapValue() for k in CAPABILITY_KEYS})
94
+ tags: list[str] = field(default_factory=list)
95
+ catalogue_id: str | None = None
96
+ memory_gb_estimate: float | None = None
97
+ memory_estimate_provenance: str = ""
98
+ intended_use_note: str = ""
99
+ enabled: bool = True
100
+ # Observed state
101
+ configured: bool = False
102
+ discovered: bool = False
103
+ available_on_disk: bool = False
104
+ loaded: bool = False
105
+ loaded_observed_at: float | None = None
106
+ healthy: bool = False
107
+ health_checked_at: float | None = None
108
+ last_error: str = ""
109
+ # Evidence
110
+ quality_prior: dict[str, float] = field(default_factory=dict)
111
+ quality_prior_provenance: str = "uncalibrated"
112
+ measurements: dict[str, Measurement] = field(default_factory=dict)
113
+ fingerprint: str = ""
114
+ discovered_at: float | None = None
115
+ raw_metadata: dict[str, Any] = field(default_factory=dict)
116
+
117
+ # ------------------------------------------------------------------ #
118
+ def compute_fingerprint(self) -> str:
119
+ # Intrinsic identity only. The *served* context length and residency change whenever a
120
+ # runtime loads/unloads a model (Ollama reports it only while loaded); they affect eligibility
121
+ # per request but do not change what the checkpoint can do, so they must not invalidate evidence.
122
+ parts = self.fingerprint_inputs()
123
+ s = json.dumps(parts, sort_keys=True)
124
+ self.fingerprint = hashlib.sha256(s.encode()).hexdigest()[:16]
125
+ return self.fingerprint
126
+
127
+ def cap(self, key: str) -> Tri:
128
+ cv = self.capabilities.get(key)
129
+ return cv.value if cv else "unknown"
130
+
131
+ def set_cap(self, key: str, value: Tri, provenance: str, note: str = "") -> None:
132
+ self.capabilities[key] = CapValue(value=value, provenance=provenance, checked_at=time.time(), note=note)
133
+
134
+ def is_eligible_base(self) -> bool:
135
+ return self.enabled and self.healthy
136
+
137
+ def fingerprint_inputs(self) -> dict[str, Any]:
138
+ """Checkpoint identity + serving configuration that affects capabilities. Empty values are
139
+ unknown and are shown as such in `modelsaar discover` / the admin status."""
140
+ return {
141
+ "backend": self.backend_id,
142
+ "endpoint": self.endpoint,
143
+ "model": self.model,
144
+ "digest": self.digest,
145
+ "identity": self.identity,
146
+ "runtime": self.runtime,
147
+ "runtime_version": self.runtime_version,
148
+ "template": self.template_hash,
149
+ "quant": self.quantization,
150
+ "pool": self.resource_pool,
151
+ }
152
+
153
+ def summary(self) -> dict[str, Any]:
154
+ return {
155
+ "id": self.id,
156
+ "backend": self.backend_id,
157
+ "backend_type": self.backend_type,
158
+ "model": self.model,
159
+ "role": self.role,
160
+ "family": self.family,
161
+ "parameter_size": self.parameter_size,
162
+ "quantization": self.quantization,
163
+ "identity": self.identity,
164
+ "identity_source": self.identity_source,
165
+ "endpoint": self.endpoint,
166
+ "fingerprint_inputs": {k: (v if v not in ("", None) else "unknown") for k, v in self.fingerprint_inputs().items()},
167
+ "context_length": self.context_length,
168
+ "context_source": self.raw_metadata.get("num_ctx_source") or self.raw_metadata.get("context_source") or "",
169
+ "max_output_tokens": self.max_output_tokens,
170
+ "locality": self.locality,
171
+ "locality_evidence": self.locality_evidence,
172
+ "resource_pool": self.resource_pool,
173
+ "capabilities": {k: v.as_dict() for k, v in self.capabilities.items()},
174
+ "tags": self.tags,
175
+ "catalogue_id": self.catalogue_id,
176
+ "memory_gb_estimate": self.memory_gb_estimate,
177
+ "memory_estimate_provenance": self.memory_estimate_provenance,
178
+ "enabled": self.enabled,
179
+ "state": {
180
+ "configured": self.configured,
181
+ "discovered": self.discovered,
182
+ "available_on_disk": self.available_on_disk,
183
+ "loaded": self.loaded,
184
+ "healthy": self.healthy,
185
+ "last_error": self.last_error,
186
+ },
187
+ "quality_prior": self.quality_prior,
188
+ "quality_prior_provenance": self.quality_prior_provenance,
189
+ "measurements": {k: asdict(v) for k, v in self.measurements.items()},
190
+ "fingerprint": self.fingerprint,
191
+ "intended_use_note": self.intended_use_note,
192
+ }
193
+
194
+
195
+ class Registry:
196
+ """In-memory registry of deployments keyed by id. Replaced atomically on refresh."""
197
+
198
+ def __init__(self) -> None:
199
+ self._deployments: dict[str, Deployment] = {}
200
+ self.version: int = 0
201
+ self.refreshed_at: float | None = None
202
+
203
+ def replace(self, deployments: list[Deployment]) -> None:
204
+ self._deployments = {d.id: d for d in deployments}
205
+ self.version += 1
206
+ self.refreshed_at = time.time()
207
+
208
+ def get(self, dep_id: str) -> Deployment | None:
209
+ return self._deployments.get(dep_id)
210
+
211
+ def all(self) -> list[Deployment]:
212
+ return list(self._deployments.values())
213
+
214
+ def by_backend(self, backend_id: str) -> list[Deployment]:
215
+ return [d for d in self._deployments.values() if d.backend_id == backend_id]
216
+
217
+ def snapshot(self) -> list[dict[str, Any]]:
218
+ return [d.summary() for d in self._deployments.values()]
219
+
220
+
221
+ def merge_capabilities(dep: Deployment, caps: dict[str, Tri], provenance: str, note: str = "") -> None:
222
+ """Merge capability values respecting provenance priority: operator > probe > adapter > source_claim."""
223
+ priority = {"none": 0, "source_claim": 1, "adapter": 2, "probe": 3, "operator": 4}
224
+ for k, v in caps.items():
225
+ if k not in CAPABILITY_KEYS:
226
+ continue
227
+ cur = dep.capabilities.get(k, CapValue())
228
+ if priority.get(provenance, 0) >= priority.get(cur.provenance, 0):
229
+ dep.set_cap(k, v, provenance, note)
@@ -0,0 +1,117 @@
1
+ """Opt-in local response store: the *stateful* part of the Responses API, implemented as real state.
2
+
3
+ Off by default (``protocols.responses_store.enabled: false``) — then ``store: true`` and
4
+ ``previous_response_id`` are refused and nothing is kept, as before. When an operator enables it:
5
+
6
+ * ``store: true`` persists the finished response object and that turn's input in the gateway's own state
7
+ database (mode 0600), scoped to the calling API key and bounded by a TTL. This is **content at rest**:
8
+ it is the one place where the gateway keeps prompts and answers, which is why it is opt-in, per request,
9
+ time-limited and deletable (``DELETE /v1/responses/{id}``).
10
+ * ``previous_response_id`` continues from a stored response of the same caller: the stored turns are
11
+ replayed as ordinary conversation history (text and tool calls) in front of the new input, and the
12
+ request is then routed, filtered and admitted like any other — nothing is renamed to look stateful.
13
+ A reference that is unknown, expired or owned by another key is ``404``; a chain longer than
14
+ ``max_chain`` is refused.
15
+ * Not state the gateway has: the Conversations API, background runs, hosted tools, encrypted reasoning.
16
+ Stored reasoning items are returned on retrieval but are **not** replayed into the next turn.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import time
23
+ from typing import Any
24
+
25
+ from .config import ResponsesStoreConfig
26
+ from .store import Store
27
+
28
+ _SCHEMA = """
29
+ CREATE TABLE IF NOT EXISTS responses (
30
+ id TEXT PRIMARY KEY, caller TEXT NOT NULL, created_at REAL NOT NULL, expires_at REAL NOT NULL,
31
+ previous_id TEXT, deployment TEXT, messages TEXT NOT NULL, response TEXT NOT NULL);
32
+ """
33
+
34
+
35
+ class ResponseStoreError(Exception):
36
+ def __init__(self, message: str, status: int, code: str, param: str | None = None) -> None:
37
+ super().__init__(message)
38
+ self.message, self.status, self.code, self.param = message, status, code, param
39
+
40
+
41
+ def output_to_messages(resp: dict[str, Any]) -> list[dict[str, Any]]:
42
+ """A stored response's output as chat history: one assistant message (text + tool calls)."""
43
+ text, calls = "", []
44
+ for item in resp.get("output") or []:
45
+ if item.get("type") == "message":
46
+ text += "".join(p.get("text", "") for p in item.get("content") or [] if p.get("type") == "output_text")
47
+ elif item.get("type") == "function_call":
48
+ calls.append({"id": item.get("call_id"), "type": "function", "function": {"name": item.get("name"), "arguments": item.get("arguments") or "{}"}})
49
+ if not text and not calls:
50
+ return []
51
+ msg: dict[str, Any] = {"role": "assistant", "content": text or None}
52
+ if calls:
53
+ msg["tool_calls"] = calls
54
+ return [msg]
55
+
56
+
57
+ class ResponseStore:
58
+ def __init__(self, store: Store | None, cfg: ResponsesStoreConfig) -> None:
59
+ self.store, self.cfg = store, cfg
60
+ if self.enabled:
61
+ with store._lock: # type: ignore[union-attr]
62
+ store._conn.executescript(_SCHEMA) # type: ignore[union-attr]
63
+ store._conn.commit() # type: ignore[union-attr]
64
+
65
+ @property
66
+ def enabled(self) -> bool:
67
+ return bool(self.cfg.enabled and self.store is not None)
68
+
69
+ def _q(self, sql: str, args: tuple = ()) -> list[tuple]:
70
+ with self.store._lock: # type: ignore[union-attr]
71
+ rows = self.store._conn.execute(sql, args).fetchall() # type: ignore[union-attr]
72
+ self.store._conn.commit() # type: ignore[union-attr]
73
+ return rows
74
+
75
+ def _row(self, rid: str, caller: str) -> tuple | None:
76
+ self._q("DELETE FROM responses WHERE expires_at < ?", (time.time(),))
77
+ rows = self._q("SELECT id, previous_id, deployment, messages, response FROM responses WHERE id=? AND caller=?", (rid, caller))
78
+ return rows[0] if rows else None
79
+
80
+ def get(self, rid: str, caller: str) -> dict[str, Any] | None:
81
+ row = self._row(rid, caller)
82
+ return json.loads(row[4]) if row else None
83
+
84
+ def delete(self, rid: str, caller: str) -> bool:
85
+ if not self._row(rid, caller):
86
+ return False
87
+ self._q("DELETE FROM responses WHERE id=? AND caller=?", (rid, caller))
88
+ return True
89
+
90
+ def history(self, rid: str, caller: str) -> tuple[list[dict[str, Any]], str]:
91
+ """Conversation history up to and including response ``rid`` (oldest first) and the chain's root id."""
92
+ chain: list[tuple] = []
93
+ cur: str | None = rid
94
+ while cur:
95
+ row = self._row(cur, caller)
96
+ if row is None:
97
+ raise ResponseStoreError(
98
+ f"previous_response_id {cur!r} was not found for this API key (never stored, deleted, or older than "
99
+ f"protocols.responses_store.ttl_s={self.cfg.ttl_s:g}s); send the conversation in `input` instead",
100
+ 404, "previous_response_not_found", "previous_response_id",
101
+ ) # fmt: skip
102
+ chain.append(row)
103
+ if len(chain) > self.cfg.max_chain:
104
+ raise ResponseStoreError(f"response chain is longer than protocols.responses_store.max_chain={self.cfg.max_chain}", 400, "response_chain_too_long", "previous_response_id")
105
+ cur = row[1]
106
+ msgs: list[dict[str, Any]] = []
107
+ for row in reversed(chain):
108
+ msgs.extend(json.loads(row[3]))
109
+ msgs.extend(output_to_messages(json.loads(row[4])))
110
+ return msgs, chain[-1][0]
111
+
112
+ def save(self, caller: str, resp: dict[str, Any], turn_messages: list[dict[str, Any]], previous_id: str | None, deployment: str | None) -> None:
113
+ blob, msgs = json.dumps(resp, ensure_ascii=False), json.dumps(turn_messages, ensure_ascii=False)
114
+ if len(blob) + len(msgs) > self.cfg.max_bytes:
115
+ raise ResponseStoreError(f"response is larger than protocols.responses_store.max_bytes={self.cfg.max_bytes}; it was answered but not stored", 413, "response_too_large_to_store")
116
+ now = time.time()
117
+ self._q("INSERT OR REPLACE INTO responses VALUES (?,?,?,?,?,?,?,?)", (resp["id"], caller, now, now + self.cfg.ttl_s, previous_id, deployment, msgs, blob))
@@ -0,0 +1 @@
1
+ """Routing pipeline: requirements -> eligibility -> classification -> ranking -> decision."""