This repository was archived by the owner on Jun 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathschemas.py
More file actions
289 lines (222 loc) · 8.85 KB
/
schemas.py
File metadata and controls
289 lines (222 loc) · 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
Request / response models for the XMem v1 API.
Every public endpoint has an explicit pair of Pydantic models so that
OpenAPI docs, input validation, and serialization are fully type-safe.
"""
from __future__ import annotations
from datetime import datetime
from enum import Enum
import re
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, field_validator
def normalize_user_id(value: Any) -> str:
"""Convert friendly user input into XMem's canonical storage id."""
text = str(value or "").strip()
text = re.sub(r"[^A-Za-z0-9_.@-]+", "_", text)
text = re.sub(r"_+", "_", text).strip("_")
return text[:256]
class UserScopedModel(BaseModel):
"""Base model for requests that scope data to a user."""
@field_validator("user_id", mode="before", check_fields=False)
@classmethod
def normalize_user_id_field(cls, v: Any) -> str:
return normalize_user_id(v)
# ── Shared envelope ────────────────────────────────────────────────────────
class StatusEnum(str, Enum):
OK = "ok"
ERROR = "error"
class APIResponse(BaseModel):
"""Standard wrapper returned by every endpoint."""
status: StatusEnum = StatusEnum.OK
request_id: Optional[str] = None
data: Optional[Any] = None
error: Optional[str] = None
elapsed_ms: Optional[float] = None
# ── Health ─────────────────────────────────────────────────────────────────
class HealthResponse(BaseModel):
status: str
pipelines_ready: bool
version: str = "1.0.0"
uptime_seconds: Optional[float] = None
error: Optional[str] = None
# ── Ingest (save memory) ──────────────────────────────────────────────────
class IngestRequest(UserScopedModel):
"""Store a new memory from a conversation turn."""
user_query: str = Field(
..., min_length=1, max_length=10_000,
description="The user's message to memorize",
)
agent_response: str = Field(
default="", max_length=10_000,
description="The assistant's reply (used for summary extraction)",
)
user_id: str = Field(
..., min_length=1, max_length=256,
description="User identifier. Friendly names are normalized internally.",
)
session_datetime: str = Field(
default="",
description="ISO-8601 datetime context for temporal event extraction",
)
image_url: str = Field(
default="", max_length=50_000,
description="URL or base64 data-URI of an attached image",
)
effort_level: str = Field(
default="low",
description="'low' (fast, single pass) or 'high' (chunked parallel extraction)",
)
@field_validator("user_query")
@classmethod
def strip_query(cls, v: str) -> str:
return v.strip()
class OperationDetail(BaseModel):
type: str
content: str
reason: str
class WeaverSummary(BaseModel):
succeeded: int = 0
skipped: int = 0
failed: int = 0
class DomainResult(BaseModel):
confidence: float = 0.0
operations: List[OperationDetail] = Field(default_factory=list)
weaver: Optional[WeaverSummary] = None
class IngestResponse(BaseModel):
model: str = ""
classification: List[Any] = Field(default_factory=list)
profile: Optional[DomainResult] = None
temporal: Optional[DomainResult] = None
summary: Optional[DomainResult] = None
image: Optional[DomainResult] = None
class BatchIngestRequest(BaseModel):
"""Store multiple new memories in a single batch."""
items: List[IngestRequest] = Field(
..., min_length=1, max_length=100,
description="List of conversation turns to ingest"
)
class BatchIngestResponse(BaseModel):
"""Response for a batch ingest operation."""
results: List[IngestResponse] = Field(default_factory=list)
# ── Retrieve (answer a question from memory) ──────────────────────────────
class RetrieveRequest(UserScopedModel):
"""Ask a question answered from stored memories."""
query: str = Field(
..., min_length=1, max_length=5_000,
description="The question to answer from memory",
)
user_id: str = Field(
..., min_length=1, max_length=256,
)
top_k: int = Field(default=5, ge=1, le=50)
@field_validator("query")
@classmethod
def strip_query(cls, v: str) -> str:
return v.strip()
class SourceRecord(BaseModel):
domain: str
content: str
score: float = 0.0
metadata: Dict[str, Any] = Field(default_factory=dict)
class RetrieveResponse(BaseModel):
model: str = ""
answer: str = ""
sources: List[SourceRecord] = Field(default_factory=list)
confidence: float = 0.0
# ── Search (raw vector / graph search without LLM answer) ─────────────────
class SearchRequest(UserScopedModel):
"""Raw semantic search across memory domains."""
query: str = Field(
..., min_length=1, max_length=5_000,
)
user_id: str = Field(
..., min_length=1, max_length=256,
)
domains: List[str] = Field(
default=["profile", "temporal", "summary", "snippet"],
description="Which memory domains to search",
)
top_k: int = Field(default=10, ge=1, le=100)
answer: bool = Field(
default=False,
description="When true, synthesize an LLM answer from the raw hits.",
)
org_id: Optional[str] = Field(
default=None,
min_length=1,
max_length=256,
description="Required when including the code domain.",
)
repo: str = Field(
default="",
max_length=256,
description="Optional repository scope for code search.",
)
@field_validator("domains")
@classmethod
def validate_domains(cls, v: List[str]) -> List[str]:
allowed = {"profile", "temporal", "summary", "snippet", "code"}
for d in v:
if d not in allowed:
raise ValueError(f"Invalid domain '{d}'. Allowed: {allowed}")
return v
@field_validator("query")
@classmethod
def strip_search_query(cls, v: str) -> str:
return v.strip()
class SearchResponse(BaseModel):
results: List[SourceRecord] = Field(default_factory=list)
total: int = 0
answer: str = ""
model: str = ""
confidence: float = 0.0
latency: Dict[str, Dict[str, float]] = Field(default_factory=dict)
# ── Scrape (extract from shared chat links) ────────────────────────────────
class ScrapeRequest(BaseModel):
"""Request to scrape a shared AI chat link."""
url: str = Field(
..., min_length=1, max_length=2000,
description="Public share link (ChatGPT, Claude, Gemini)"
)
class MessagePair(BaseModel):
user_query: str
agent_response: str
class ScrapeResponse(BaseModel):
pairs: List[MessagePair] = Field(default_factory=list)
error: Optional[str] = None
# ── Code retrieval (IDE mode) ─────────────────────────────────────────────
class CodeQueryRequest(UserScopedModel):
"""Query a codebase via the code retrieval pipeline."""
org_id: str = Field(..., min_length=1, max_length=256)
repo: str = Field(..., min_length=1, max_length=256)
query: str = Field(..., min_length=1, max_length=5_000)
user_id: str = Field(default="", max_length=256)
top_k: int = Field(default=10, ge=1, le=50)
@field_validator("query")
@classmethod
def strip_code_query(cls, v: str) -> str:
return v.strip()
class CodeQueryResponse(BaseModel):
answer: str = ""
sources: List[SourceRecord] = Field(default_factory=list)
confidence: float = 0.0
class ExecuteToolRequest(UserScopedModel):
"""Execute a specific raw code retrieval tool natively."""
org_id: str = Field(..., min_length=1, max_length=256)
repo: str = Field(..., min_length=1, max_length=256)
tool_name: str = Field(..., min_length=1, max_length=128)
tool_args: Dict[str, Any] = Field(default_factory=dict)
user_id: str = Field(default="", max_length=256)
top_k: int = Field(default=10, ge=1, le=50)
class ExecuteToolResponse(BaseModel):
records: List[SourceRecord] = Field(default_factory=list)
class DirectoryNode(BaseModel):
name: str
type: str = "file"
path: str = ""
children: List["DirectoryNode"] = Field(default_factory=list)
class DirectoryTreeResponse(BaseModel):
repo: str
tree: DirectoryNode
class RepoListResponse(BaseModel):
repos: List[str] = Field(default_factory=list)