Spaces:
Sleeping
Sleeping
RemanenetSpy commited on
Commit ·
410ad6c
1
Parent(s): 21ff283
Migrate: SQLite+ChromaDB → Neon PostgreSQL+pgvector (persistent cloud storage)
Browse files- .env.example +2 -3
- Dockerfile +1 -1
- api/main.py +14 -14
- chronos_core/memory_store.py +228 -280
- chronos_core/vector_store.py +150 -160
- render.yaml +2 -4
- requirements.txt +2 -2
.env.example
CHANGED
|
@@ -15,9 +15,8 @@ RAZORPAY_KEY_SECRET=secret_...
|
|
| 15 |
RAZORPAY_PLAN_BUILDER=plan_...
|
| 16 |
RAZORPAY_PLAN_SCALE=plan_...
|
| 17 |
|
| 18 |
-
# Database
|
| 19 |
-
|
| 20 |
-
CHROMA_PERSIST_DIR=./data/chroma
|
| 21 |
|
| 22 |
# Security
|
| 23 |
API_SECRET_KEY=change-me-to-a-random-secret
|
|
|
|
| 15 |
RAZORPAY_PLAN_BUILDER=plan_...
|
| 16 |
RAZORPAY_PLAN_SCALE=plan_...
|
| 17 |
|
| 18 |
+
# Database Connection
|
| 19 |
+
DATABASE_URL=postgresql://user:password@hostname:5432/dbname
|
|
|
|
| 20 |
|
| 21 |
# Security
|
| 22 |
API_SECRET_KEY=change-me-to-a-random-secret
|
Dockerfile
CHANGED
|
@@ -5,7 +5,7 @@ WORKDIR /app
|
|
| 5 |
# Install build dependencies for ChromaDB/SQLite
|
| 6 |
RUN apt-get update && apt-get install -y \
|
| 7 |
build-essential \
|
| 8 |
-
|
| 9 |
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
|
| 11 |
# Install python dependencies
|
|
|
|
| 5 |
# Install build dependencies for ChromaDB/SQLite
|
| 6 |
RUN apt-get update && apt-get install -y \
|
| 7 |
build-essential \
|
| 8 |
+
libpq-dev \
|
| 9 |
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
|
| 11 |
# Install python dependencies
|
api/main.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
| 2 |
Chronos OS — FastAPI Application
|
| 3 |
==================================
|
| 4 |
The API gateway for the Chronos Temporal AI Agent Ecosystem.
|
|
|
|
| 5 |
|
| 6 |
Endpoints:
|
| 7 |
POST /ingest — Universal event ingestion
|
|
@@ -9,7 +10,7 @@ Endpoints:
|
|
| 9 |
POST /connect — Register SaaS tools
|
| 10 |
GET /connectors — List connected tools
|
| 11 |
POST /agent/run — Execute agent with temporal memory
|
| 12 |
-
POST /billing/* —
|
| 13 |
"""
|
| 14 |
|
| 15 |
from __future__ import annotations
|
|
@@ -47,15 +48,13 @@ async def lifespan(app: FastAPI):
|
|
| 47 |
"""Initialize and tear down core services."""
|
| 48 |
logger.info("🕰️ Chronos OS starting up...")
|
| 49 |
|
| 50 |
-
# Initialize Memory Store (
|
| 51 |
-
|
| 52 |
-
memory_store = MemoryStore(db_path)
|
| 53 |
await memory_store.initialize()
|
| 54 |
|
| 55 |
-
# Initialize Vector Store (
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
await vector_store.initialize()
|
| 59 |
|
| 60 |
# Initialize SVO Parser (LiteLLM Mixture of Agents Router)
|
| 61 |
svo_parser = SVOParser()
|
|
@@ -63,7 +62,7 @@ async def lifespan(app: FastAPI):
|
|
| 63 |
# Register singletons for dependency injection
|
| 64 |
set_stores(memory_store, vector_store, svo_parser)
|
| 65 |
|
| 66 |
-
logger.info("✅ Chronos OS ready —
|
| 67 |
|
| 68 |
yield # App is running
|
| 69 |
|
|
@@ -84,13 +83,13 @@ app = FastAPI(
|
|
| 84 |
"Structured long-term memory for every agent and SaaS product. "
|
| 85 |
"Powered by SVO event tuples + dual calendar architecture."
|
| 86 |
),
|
| 87 |
-
version="0.
|
| 88 |
lifespan=lifespan,
|
| 89 |
docs_url="/docs",
|
| 90 |
redoc_url="/redoc",
|
| 91 |
)
|
| 92 |
|
| 93 |
-
# CORS — allow all origins for development
|
| 94 |
app.add_middleware(
|
| 95 |
CORSMiddleware,
|
| 96 |
allow_origins=["*"],
|
|
@@ -125,8 +124,9 @@ async def health_check():
|
|
| 125 |
"""Health check — verify Chronos OS is alive."""
|
| 126 |
return {
|
| 127 |
"service": "Chronos OS",
|
| 128 |
-
"version": "0.
|
| 129 |
"status": "operational",
|
|
|
|
| 130 |
"tagline": "Letters to the Future — for agents.",
|
| 131 |
"docs": "/docs",
|
| 132 |
}
|
|
@@ -147,8 +147,8 @@ async def detailed_health():
|
|
| 147 |
return {
|
| 148 |
"status": "healthy",
|
| 149 |
"stores": {
|
| 150 |
-
"
|
| 151 |
-
"
|
| 152 |
},
|
| 153 |
}
|
| 154 |
except Exception as e:
|
|
|
|
| 2 |
Chronos OS — FastAPI Application
|
| 3 |
==================================
|
| 4 |
The API gateway for the Chronos Temporal AI Agent Ecosystem.
|
| 5 |
+
Backend: Neon PostgreSQL + pgvector (persistent cloud storage).
|
| 6 |
|
| 7 |
Endpoints:
|
| 8 |
POST /ingest — Universal event ingestion
|
|
|
|
| 10 |
POST /connect — Register SaaS tools
|
| 11 |
GET /connectors — List connected tools
|
| 12 |
POST /agent/run — Execute agent with temporal memory
|
| 13 |
+
POST /billing/* — Razorpay checkout + usage
|
| 14 |
"""
|
| 15 |
|
| 16 |
from __future__ import annotations
|
|
|
|
| 48 |
"""Initialize and tear down core services."""
|
| 49 |
logger.info("🕰️ Chronos OS starting up...")
|
| 50 |
|
| 51 |
+
# Initialize Memory Store (Neon PostgreSQL via asyncpg pool)
|
| 52 |
+
memory_store = MemoryStore()
|
|
|
|
| 53 |
await memory_store.initialize()
|
| 54 |
|
| 55 |
+
# Initialize Vector Store (pgvector — shares the same pool)
|
| 56 |
+
vector_store = VectorStore()
|
| 57 |
+
await vector_store.initialize(pool=memory_store.pool)
|
|
|
|
| 58 |
|
| 59 |
# Initialize SVO Parser (LiteLLM Mixture of Agents Router)
|
| 60 |
svo_parser = SVOParser()
|
|
|
|
| 62 |
# Register singletons for dependency injection
|
| 63 |
set_stores(memory_store, vector_store, svo_parser)
|
| 64 |
|
| 65 |
+
logger.info("✅ Chronos OS ready — Neon PostgreSQL + pgvector online")
|
| 66 |
|
| 67 |
yield # App is running
|
| 68 |
|
|
|
|
| 83 |
"Structured long-term memory for every agent and SaaS product. "
|
| 84 |
"Powered by SVO event tuples + dual calendar architecture."
|
| 85 |
),
|
| 86 |
+
version="0.2.0",
|
| 87 |
lifespan=lifespan,
|
| 88 |
docs_url="/docs",
|
| 89 |
redoc_url="/redoc",
|
| 90 |
)
|
| 91 |
|
| 92 |
+
# CORS — allow all origins for development / Streamlit
|
| 93 |
app.add_middleware(
|
| 94 |
CORSMiddleware,
|
| 95 |
allow_origins=["*"],
|
|
|
|
| 124 |
"""Health check — verify Chronos OS is alive."""
|
| 125 |
return {
|
| 126 |
"service": "Chronos OS",
|
| 127 |
+
"version": "0.2.0",
|
| 128 |
"status": "operational",
|
| 129 |
+
"storage": "Neon PostgreSQL + pgvector",
|
| 130 |
"tagline": "Letters to the Future — for agents.",
|
| 131 |
"docs": "/docs",
|
| 132 |
}
|
|
|
|
| 147 |
return {
|
| 148 |
"status": "healthy",
|
| 149 |
"stores": {
|
| 150 |
+
"postgres_events": event_count,
|
| 151 |
+
"pgvector_embeddings": vector_count,
|
| 152 |
},
|
| 153 |
}
|
| 154 |
except Exception as e:
|
chronos_core/memory_store.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
"""
|
| 2 |
Chronos OS — Memory Store
|
| 3 |
==========================
|
| 4 |
-
Dual-calendar
|
| 5 |
• Event Calendar — structured SVO events with temporal indexing
|
| 6 |
• Turn Calendar — raw conversation turns for full context
|
| 7 |
|
| 8 |
Implements the Chronos research paper's dual-calendar architecture
|
| 9 |
for temporal-aware retrieval and multi-hop reasoning.
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
from __future__ import annotations
|
|
@@ -17,7 +18,7 @@ import os
|
|
| 17 |
from datetime import datetime
|
| 18 |
from typing import Optional
|
| 19 |
|
| 20 |
-
import
|
| 21 |
|
| 22 |
from .models import (
|
| 23 |
ConnectorRecord,
|
|
@@ -35,6 +36,8 @@ logger = logging.getLogger("chronos.memory_store")
|
|
| 35 |
# ---------------------------------------------------------------------------
|
| 36 |
|
| 37 |
_SCHEMA_SQL = """
|
|
|
|
|
|
|
| 38 |
-- Event Calendar: structured SVO events
|
| 39 |
CREATE TABLE IF NOT EXISTS events (
|
| 40 |
id TEXT PRIMARY KEY,
|
|
@@ -42,20 +45,20 @@ CREATE TABLE IF NOT EXISTS events (
|
|
| 42 |
subject TEXT NOT NULL,
|
| 43 |
verb TEXT NOT NULL,
|
| 44 |
object TEXT NOT NULL,
|
| 45 |
-
timestamp
|
| 46 |
-
datetime_start
|
| 47 |
-
datetime_end
|
| 48 |
-
entity_aliases
|
| 49 |
confidence REAL DEFAULT 1.0,
|
| 50 |
-
metadata_json
|
| 51 |
raw_text TEXT DEFAULT '',
|
| 52 |
-
created_at
|
| 53 |
);
|
| 54 |
|
| 55 |
-
CREATE INDEX IF NOT EXISTS idx_events_source
|
| 56 |
-
CREATE INDEX IF NOT EXISTS idx_events_timestamp
|
| 57 |
-
CREATE INDEX IF NOT EXISTS idx_events_subject
|
| 58 |
-
CREATE INDEX IF NOT EXISTS idx_events_verb
|
| 59 |
|
| 60 |
-- Turn Calendar: raw conversation turns
|
| 61 |
CREATE TABLE IF NOT EXISTS turns (
|
|
@@ -63,13 +66,13 @@ CREATE TABLE IF NOT EXISTS turns (
|
|
| 63 |
source_id TEXT NOT NULL,
|
| 64 |
role TEXT NOT NULL DEFAULT 'user',
|
| 65 |
content TEXT NOT NULL,
|
| 66 |
-
timestamp
|
| 67 |
-
event_ids
|
| 68 |
-
created_at
|
| 69 |
);
|
| 70 |
|
| 71 |
CREATE INDEX IF NOT EXISTS idx_turns_source ON turns(source_id);
|
| 72 |
-
CREATE INDEX IF NOT EXISTS idx_turns_timestamp ON turns(timestamp);
|
| 73 |
|
| 74 |
-- Connectors: registered SaaS tools
|
| 75 |
CREATE TABLE IF NOT EXISTS connectors (
|
|
@@ -79,9 +82,9 @@ CREATE TABLE IF NOT EXISTS connectors (
|
|
| 79 |
description TEXT DEFAULT '',
|
| 80 |
base_url TEXT NOT NULL,
|
| 81 |
auth_header TEXT,
|
| 82 |
-
endpoints
|
| 83 |
-
metadata
|
| 84 |
-
created_at
|
| 85 |
);
|
| 86 |
|
| 87 |
CREATE INDEX IF NOT EXISTS idx_connectors_source ON connectors(source_id);
|
|
@@ -94,8 +97,8 @@ CREATE TABLE IF NOT EXISTS api_keys (
|
|
| 94 |
events_used INTEGER DEFAULT 0,
|
| 95 |
orchestration_used INTEGER DEFAULT 0,
|
| 96 |
connectors_used INTEGER DEFAULT 0,
|
| 97 |
-
period_start
|
| 98 |
-
created_at
|
| 99 |
);
|
| 100 |
|
| 101 |
CREATE INDEX IF NOT EXISTS idx_apikeys_source ON api_keys(source_id);
|
|
@@ -104,40 +107,43 @@ CREATE INDEX IF NOT EXISTS idx_apikeys_source ON api_keys(source_id);
|
|
| 104 |
|
| 105 |
class MemoryStore:
|
| 106 |
"""
|
| 107 |
-
Async
|
| 108 |
-
|
| 109 |
"""
|
| 110 |
|
| 111 |
-
def __init__(self,
|
| 112 |
-
self.
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
self.
|
| 116 |
|
| 117 |
# ------------------------------------------------------------------
|
| 118 |
# Lifecycle
|
| 119 |
# ------------------------------------------------------------------
|
| 120 |
|
| 121 |
async def initialize(self) -> None:
|
| 122 |
-
"""Create
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
async def close(self) -> None:
|
| 131 |
-
"""Close the
|
| 132 |
-
if self.
|
| 133 |
-
await self.
|
| 134 |
-
self.
|
| 135 |
|
| 136 |
@property
|
| 137 |
-
def
|
| 138 |
-
if not self.
|
| 139 |
raise RuntimeError("MemoryStore not initialized. Call initialize() first.")
|
| 140 |
-
return self.
|
| 141 |
|
| 142 |
# ------------------------------------------------------------------
|
| 143 |
# Event Calendar
|
|
@@ -145,64 +151,59 @@ class MemoryStore:
|
|
| 145 |
|
| 146 |
async def insert_event(self, event: EventRecord) -> str:
|
| 147 |
"""Insert a structured SVO event into the Event Calendar."""
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
| 155 |
event.id,
|
| 156 |
event.source_id,
|
| 157 |
event.subject,
|
| 158 |
event.verb,
|
| 159 |
event.object,
|
| 160 |
-
event.timestamp
|
| 161 |
-
event.datetime_start
|
| 162 |
-
event.datetime_end
|
| 163 |
json.dumps(event.entity_aliases),
|
| 164 |
event.confidence,
|
| 165 |
json.dumps(event.metadata_json),
|
| 166 |
event.raw_text,
|
| 167 |
-
event.created_at
|
| 168 |
-
)
|
| 169 |
-
)
|
| 170 |
-
await self.db.commit()
|
| 171 |
return event.id
|
| 172 |
|
| 173 |
async def insert_events_batch(self, events: list[EventRecord]) -> list[str]:
|
| 174 |
-
"""Batch insert multiple events using
|
| 175 |
if not events:
|
| 176 |
return []
|
| 177 |
|
| 178 |
rows = [
|
| 179 |
(
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
event.object,
|
| 185 |
-
event.timestamp.isoformat(),
|
| 186 |
-
event.datetime_start.isoformat() if event.datetime_start else None,
|
| 187 |
-
event.datetime_end.isoformat() if event.datetime_end else None,
|
| 188 |
-
json.dumps(event.entity_aliases),
|
| 189 |
-
event.confidence,
|
| 190 |
-
json.dumps(event.metadata_json),
|
| 191 |
-
event.raw_text,
|
| 192 |
-
event.created_at.isoformat(),
|
| 193 |
)
|
| 194 |
-
for
|
| 195 |
]
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
| 206 |
return [e.id for e in events]
|
| 207 |
|
| 208 |
async def query_temporal(
|
|
@@ -213,28 +214,23 @@ class MemoryStore:
|
|
| 213 |
limit: int = 50,
|
| 214 |
) -> list[EventRecord]:
|
| 215 |
"""Query events by time range."""
|
| 216 |
-
conditions = []
|
| 217 |
-
|
| 218 |
|
| 219 |
if start:
|
| 220 |
-
conditions.append("timestamp >=
|
| 221 |
-
params.append(start.isoformat())
|
| 222 |
if end:
|
| 223 |
-
conditions.append("timestamp <=
|
| 224 |
-
params.append(end.isoformat())
|
| 225 |
if source_ids:
|
| 226 |
-
|
| 227 |
-
conditions.append(f"source_id IN ({placeholders})")
|
| 228 |
-
params.extend(source_ids)
|
| 229 |
|
| 230 |
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
| 231 |
-
query = f"SELECT * FROM events {where} ORDER BY timestamp DESC LIMIT ?"
|
| 232 |
params.append(limit)
|
|
|
|
| 233 |
|
| 234 |
-
async with self.
|
| 235 |
-
rows = await
|
| 236 |
-
|
| 237 |
-
return [self._row_to_event(row) for row in rows]
|
| 238 |
|
| 239 |
async def query_by_entity(
|
| 240 |
self,
|
|
@@ -243,25 +239,21 @@ class MemoryStore:
|
|
| 243 |
limit: int = 50,
|
| 244 |
) -> list[EventRecord]:
|
| 245 |
"""Find events involving a specific entity (subject or object)."""
|
| 246 |
-
conditions = [
|
| 247 |
-
"(subject LIKE ? OR object LIKE ? OR entity_aliases LIKE ?)"
|
| 248 |
-
]
|
| 249 |
pattern = f"%{entity}%"
|
| 250 |
-
|
|
|
|
|
|
|
| 251 |
|
| 252 |
if source_ids:
|
| 253 |
-
|
| 254 |
-
conditions.append(f"source_id IN ({placeholders})")
|
| 255 |
-
params.extend(source_ids)
|
| 256 |
|
| 257 |
-
where = f"WHERE {' AND '.join(conditions)}"
|
| 258 |
-
query = f"SELECT * FROM events {where} ORDER BY timestamp DESC LIMIT ?"
|
| 259 |
params.append(limit)
|
|
|
|
|
|
|
| 260 |
|
| 261 |
-
async with self.
|
| 262 |
-
rows = await
|
| 263 |
-
|
| 264 |
-
return [self._row_to_event(row) for row in rows]
|
| 265 |
|
| 266 |
async def multi_hop_query(
|
| 267 |
self,
|
|
@@ -272,71 +264,59 @@ class MemoryStore:
|
|
| 272 |
limit: int = 50,
|
| 273 |
) -> list[EventRecord]:
|
| 274 |
"""
|
| 275 |
-
Multi-hop temporal query: find events
|
| 276 |
-
|
| 277 |
"""
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
for entity in entities:
|
| 282 |
pattern = f"%{entity}%"
|
| 283 |
-
|
| 284 |
-
"(subject
|
| 285 |
)
|
| 286 |
-
params.
|
| 287 |
|
| 288 |
-
conditions = [f"({' OR '.join(
|
| 289 |
|
| 290 |
if start:
|
| 291 |
-
conditions.append("timestamp >=
|
| 292 |
-
params.append(start.isoformat())
|
| 293 |
if end:
|
| 294 |
-
conditions.append("timestamp <=
|
| 295 |
-
params.append(end.isoformat())
|
| 296 |
if source_ids:
|
| 297 |
-
|
| 298 |
-
conditions.append(f"source_id IN ({placeholders})")
|
| 299 |
-
params.extend(source_ids)
|
| 300 |
|
| 301 |
-
where = f"WHERE {' AND '.join(conditions)}"
|
| 302 |
-
query = f"SELECT * FROM events {where} ORDER BY timestamp ASC LIMIT ?"
|
| 303 |
params.append(limit)
|
|
|
|
|
|
|
| 304 |
|
| 305 |
-
async with self.
|
| 306 |
-
rows = await
|
| 307 |
-
|
| 308 |
-
return [self._row_to_event(row) for row in rows]
|
| 309 |
|
| 310 |
async def get_event(self, event_id: str) -> Optional[EventRecord]:
|
| 311 |
"""Fetch a single event by ID."""
|
| 312 |
-
async with self.
|
| 313 |
-
"SELECT * FROM events WHERE id =
|
| 314 |
-
) as cursor:
|
| 315 |
-
row = await cursor.fetchone()
|
| 316 |
return self._row_to_event(row) if row else None
|
| 317 |
|
| 318 |
async def get_events_by_ids(self, event_ids: list[str]) -> list[EventRecord]:
|
| 319 |
"""Fetch multiple events by their IDs."""
|
| 320 |
if not event_ids:
|
| 321 |
return []
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
return [self._row_to_event(row) for row in rows]
|
| 328 |
|
| 329 |
async def count_events(self, source_id: Optional[str] = None) -> int:
|
| 330 |
"""Count total events, optionally filtered by source."""
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
async with self.db.execute("SELECT COUNT(*) FROM events") as cursor:
|
| 338 |
-
row = await cursor.fetchone()
|
| 339 |
-
return row[0] if row else 0
|
| 340 |
|
| 341 |
# ------------------------------------------------------------------
|
| 342 |
# Turn Calendar
|
|
@@ -344,21 +324,17 @@ class MemoryStore:
|
|
| 344 |
|
| 345 |
async def insert_turn(self, turn: TurnRecord) -> str:
|
| 346 |
"""Insert a raw conversation turn into the Turn Calendar."""
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
turn.role.value,
|
| 355 |
-
turn.content,
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
turn.created_at.isoformat(),
|
| 359 |
-
),
|
| 360 |
-
)
|
| 361 |
-
await self.db.commit()
|
| 362 |
return turn.id
|
| 363 |
|
| 364 |
async def get_turns(
|
|
@@ -369,27 +345,23 @@ class MemoryStore:
|
|
| 369 |
limit: int = 50,
|
| 370 |
) -> list[TurnRecord]:
|
| 371 |
"""Query conversation turns."""
|
| 372 |
-
conditions = []
|
| 373 |
-
|
| 374 |
|
| 375 |
if source_id:
|
| 376 |
-
conditions.append("source_id =
|
| 377 |
-
params.append(source_id)
|
| 378 |
if start:
|
| 379 |
-
conditions.append("timestamp >=
|
| 380 |
-
params.append(start.isoformat())
|
| 381 |
if end:
|
| 382 |
-
conditions.append("timestamp <=
|
| 383 |
-
params.append(end.isoformat())
|
| 384 |
|
| 385 |
-
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
| 386 |
-
query = f"SELECT * FROM turns {where} ORDER BY timestamp DESC LIMIT ?"
|
| 387 |
params.append(limit)
|
|
|
|
|
|
|
| 388 |
|
| 389 |
-
async with self.
|
| 390 |
-
rows = await
|
| 391 |
-
|
| 392 |
-
return [self._row_to_turn(row) for row in rows]
|
| 393 |
|
| 394 |
# ------------------------------------------------------------------
|
| 395 |
# Connectors
|
|
@@ -397,124 +369,111 @@ class MemoryStore:
|
|
| 397 |
|
| 398 |
async def insert_connector(self, connector: ConnectorRecord) -> str:
|
| 399 |
"""Register a SaaS tool connector."""
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
|
|
|
|
|
|
| 412 |
json.dumps([ep.model_dump() for ep in connector.endpoints]),
|
| 413 |
-
json.dumps(connector.metadata),
|
| 414 |
-
|
| 415 |
-
),
|
| 416 |
-
)
|
| 417 |
-
await self.db.commit()
|
| 418 |
return connector.id
|
| 419 |
|
| 420 |
-
async def get_connectors(
|
| 421 |
-
self, source_id: Optional[str] = None
|
| 422 |
-
) -> list[ConnectorRecord]:
|
| 423 |
"""List registered connectors."""
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
return [self._row_to_connector(row) for row in rows]
|
| 433 |
|
| 434 |
async def get_connector(self, connector_id: str) -> Optional[ConnectorRecord]:
|
| 435 |
"""Fetch a single connector by ID."""
|
| 436 |
-
async with self.
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
return self._row_to_connector(row) if row else None
|
| 441 |
|
| 442 |
async def count_connectors(self, source_id: str) -> int:
|
| 443 |
"""Count connectors for a source."""
|
| 444 |
-
async with self.
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
return row[0] if row else 0
|
| 449 |
|
| 450 |
# ------------------------------------------------------------------
|
| 451 |
# API Keys & Usage
|
| 452 |
# ------------------------------------------------------------------
|
| 453 |
|
| 454 |
async def register_api_key(
|
| 455 |
-
self,
|
| 456 |
-
key_hash: str,
|
| 457 |
-
source_id: str,
|
| 458 |
-
tier: TierName = TierName.EXPLORER,
|
| 459 |
) -> None:
|
| 460 |
"""Register a new API key."""
|
| 461 |
-
now = datetime.utcnow()
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
|
|
|
|
|
|
|
|
|
| 470 |
|
| 471 |
async def get_usage(self, source_id: str) -> Optional[UsageStats]:
|
| 472 |
"""Get usage stats for a source."""
|
| 473 |
-
async with self.
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
if not row:
|
| 479 |
return None
|
| 480 |
-
|
| 481 |
return UsageStats(
|
| 482 |
source_id=row["source_id"],
|
| 483 |
tier=TierName(row["tier"]),
|
| 484 |
events_used=row["events_used"],
|
| 485 |
orchestration_used=row["orchestration_used"],
|
| 486 |
connectors_used=row["connectors_used"],
|
| 487 |
-
period_start=
|
| 488 |
)
|
| 489 |
|
| 490 |
async def increment_usage(
|
| 491 |
-
self,
|
| 492 |
-
source_id: str,
|
| 493 |
-
events: int = 0,
|
| 494 |
-
orchestration: int = 0,
|
| 495 |
) -> None:
|
| 496 |
"""Increment usage counters for a source."""
|
| 497 |
-
|
| 498 |
-
await
|
| 499 |
-
"
|
| 500 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
)
|
| 502 |
-
if orchestration > 0:
|
| 503 |
-
await self.db.execute(
|
| 504 |
-
"UPDATE api_keys SET orchestration_used = orchestration_used + ? WHERE source_id = ?",
|
| 505 |
-
(orchestration, source_id),
|
| 506 |
-
)
|
| 507 |
-
await self.db.commit()
|
| 508 |
|
| 509 |
async def validate_api_key(self, key_hash: str) -> Optional[dict]:
|
| 510 |
"""Validate an API key and return source info."""
|
| 511 |
-
async with self.
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
if row
|
| 516 |
-
return dict(row)
|
| 517 |
-
return None
|
| 518 |
|
| 519 |
# ------------------------------------------------------------------
|
| 520 |
# Row Converters
|
|
@@ -522,49 +481,38 @@ class MemoryStore:
|
|
| 522 |
|
| 523 |
@staticmethod
|
| 524 |
def _row_to_event(row) -> EventRecord:
|
| 525 |
-
"""Convert a database row to an EventRecord."""
|
| 526 |
return EventRecord(
|
| 527 |
id=row["id"],
|
| 528 |
source_id=row["source_id"],
|
| 529 |
subject=row["subject"],
|
| 530 |
verb=row["verb"],
|
| 531 |
object=row["object"],
|
| 532 |
-
timestamp=
|
| 533 |
-
datetime_start=
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
),
|
| 537 |
-
datetime_end=(
|
| 538 |
-
datetime.fromisoformat(row["datetime_end"])
|
| 539 |
-
if row["datetime_end"] else None
|
| 540 |
-
),
|
| 541 |
-
entity_aliases=json.loads(row["entity_aliases"] or "[]"),
|
| 542 |
confidence=row["confidence"],
|
| 543 |
-
metadata_json=json.loads(row["metadata_json"]
|
| 544 |
raw_text=row["raw_text"] or "",
|
| 545 |
-
created_at=
|
| 546 |
)
|
| 547 |
|
| 548 |
@staticmethod
|
| 549 |
def _row_to_turn(row) -> TurnRecord:
|
| 550 |
-
"""Convert a database row to a TurnRecord."""
|
| 551 |
return TurnRecord(
|
| 552 |
id=row["id"],
|
| 553 |
source_id=row["source_id"],
|
| 554 |
role=TurnRole(row["role"]),
|
| 555 |
content=row["content"],
|
| 556 |
-
timestamp=
|
| 557 |
-
event_ids=json.loads(row["event_ids"]
|
| 558 |
-
created_at=
|
| 559 |
)
|
| 560 |
|
| 561 |
@staticmethod
|
| 562 |
def _row_to_connector(row) -> ConnectorRecord:
|
| 563 |
-
"""Convert a database row to a ConnectorRecord."""
|
| 564 |
from .models import ConnectorEndpoint
|
| 565 |
-
endpoints_raw = json.loads(row["endpoints"]
|
| 566 |
-
endpoints = [ConnectorEndpoint(**ep) for ep in endpoints_raw]
|
| 567 |
-
|
| 568 |
return ConnectorRecord(
|
| 569 |
id=row["id"],
|
| 570 |
source_id=row["source_id"],
|
|
@@ -572,7 +520,7 @@ class MemoryStore:
|
|
| 572 |
description=row["description"] or "",
|
| 573 |
base_url=row["base_url"],
|
| 574 |
auth_header=row["auth_header"],
|
| 575 |
-
endpoints=
|
| 576 |
-
metadata=json.loads(row["metadata"]
|
| 577 |
-
created_at=
|
| 578 |
)
|
|
|
|
| 1 |
"""
|
| 2 |
Chronos OS — Memory Store
|
| 3 |
==========================
|
| 4 |
+
Dual-calendar PostgreSQL storage engine backed by Neon.
|
| 5 |
• Event Calendar — structured SVO events with temporal indexing
|
| 6 |
• Turn Calendar — raw conversation turns for full context
|
| 7 |
|
| 8 |
Implements the Chronos research paper's dual-calendar architecture
|
| 9 |
for temporal-aware retrieval and multi-hop reasoning.
|
| 10 |
+
Uses asyncpg connection pooling for high concurrency on Render.
|
| 11 |
"""
|
| 12 |
|
| 13 |
from __future__ import annotations
|
|
|
|
| 18 |
from datetime import datetime
|
| 19 |
from typing import Optional
|
| 20 |
|
| 21 |
+
import asyncpg
|
| 22 |
|
| 23 |
from .models import (
|
| 24 |
ConnectorRecord,
|
|
|
|
| 36 |
# ---------------------------------------------------------------------------
|
| 37 |
|
| 38 |
_SCHEMA_SQL = """
|
| 39 |
+
CREATE EXTENSION IF NOT EXISTS vector;
|
| 40 |
+
|
| 41 |
-- Event Calendar: structured SVO events
|
| 42 |
CREATE TABLE IF NOT EXISTS events (
|
| 43 |
id TEXT PRIMARY KEY,
|
|
|
|
| 45 |
subject TEXT NOT NULL,
|
| 46 |
verb TEXT NOT NULL,
|
| 47 |
object TEXT NOT NULL,
|
| 48 |
+
timestamp TIMESTAMPTZ NOT NULL,
|
| 49 |
+
datetime_start TIMESTAMPTZ,
|
| 50 |
+
datetime_end TIMESTAMPTZ,
|
| 51 |
+
entity_aliases JSONB DEFAULT '[]',
|
| 52 |
confidence REAL DEFAULT 1.0,
|
| 53 |
+
metadata_json JSONB DEFAULT '{}',
|
| 54 |
raw_text TEXT DEFAULT '',
|
| 55 |
+
created_at TIMESTAMPTZ NOT NULL
|
| 56 |
);
|
| 57 |
|
| 58 |
+
CREATE INDEX IF NOT EXISTS idx_events_source ON events(source_id);
|
| 59 |
+
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp DESC);
|
| 60 |
+
CREATE INDEX IF NOT EXISTS idx_events_subject ON events(subject);
|
| 61 |
+
CREATE INDEX IF NOT EXISTS idx_events_verb ON events(verb);
|
| 62 |
|
| 63 |
-- Turn Calendar: raw conversation turns
|
| 64 |
CREATE TABLE IF NOT EXISTS turns (
|
|
|
|
| 66 |
source_id TEXT NOT NULL,
|
| 67 |
role TEXT NOT NULL DEFAULT 'user',
|
| 68 |
content TEXT NOT NULL,
|
| 69 |
+
timestamp TIMESTAMPTZ NOT NULL,
|
| 70 |
+
event_ids JSONB DEFAULT '[]',
|
| 71 |
+
created_at TIMESTAMPTZ NOT NULL
|
| 72 |
);
|
| 73 |
|
| 74 |
CREATE INDEX IF NOT EXISTS idx_turns_source ON turns(source_id);
|
| 75 |
+
CREATE INDEX IF NOT EXISTS idx_turns_timestamp ON turns(timestamp DESC);
|
| 76 |
|
| 77 |
-- Connectors: registered SaaS tools
|
| 78 |
CREATE TABLE IF NOT EXISTS connectors (
|
|
|
|
| 82 |
description TEXT DEFAULT '',
|
| 83 |
base_url TEXT NOT NULL,
|
| 84 |
auth_header TEXT,
|
| 85 |
+
endpoints JSONB DEFAULT '[]',
|
| 86 |
+
metadata JSONB DEFAULT '{}',
|
| 87 |
+
created_at TIMESTAMPTZ NOT NULL
|
| 88 |
);
|
| 89 |
|
| 90 |
CREATE INDEX IF NOT EXISTS idx_connectors_source ON connectors(source_id);
|
|
|
|
| 97 |
events_used INTEGER DEFAULT 0,
|
| 98 |
orchestration_used INTEGER DEFAULT 0,
|
| 99 |
connectors_used INTEGER DEFAULT 0,
|
| 100 |
+
period_start TIMESTAMPTZ NOT NULL,
|
| 101 |
+
created_at TIMESTAMPTZ NOT NULL
|
| 102 |
);
|
| 103 |
|
| 104 |
CREATE INDEX IF NOT EXISTS idx_apikeys_source ON api_keys(source_id);
|
|
|
|
| 107 |
|
| 108 |
class MemoryStore:
|
| 109 |
"""
|
| 110 |
+
Async PostgreSQL dual-calendar memory store using asyncpg connection pool.
|
| 111 |
+
Backed by Neon — data persists across all redeploys.
|
| 112 |
"""
|
| 113 |
|
| 114 |
+
def __init__(self, dsn: Optional[str] = None):
|
| 115 |
+
self.dsn = dsn or os.getenv("DATABASE_URL")
|
| 116 |
+
if not self.dsn:
|
| 117 |
+
raise RuntimeError("DATABASE_URL environment variable is not set.")
|
| 118 |
+
self._pool: Optional[asyncpg.Pool] = None
|
| 119 |
|
| 120 |
# ------------------------------------------------------------------
|
| 121 |
# Lifecycle
|
| 122 |
# ------------------------------------------------------------------
|
| 123 |
|
| 124 |
async def initialize(self) -> None:
|
| 125 |
+
"""Create connection pool and apply schema migrations."""
|
| 126 |
+
self._pool = await asyncpg.create_pool(
|
| 127 |
+
self.dsn,
|
| 128 |
+
min_size=2,
|
| 129 |
+
max_size=10,
|
| 130 |
+
command_timeout=60,
|
| 131 |
+
)
|
| 132 |
+
async with self._pool.acquire() as conn:
|
| 133 |
+
await conn.execute(_SCHEMA_SQL)
|
| 134 |
+
logger.info("Memory store initialized (Neon PostgreSQL)")
|
| 135 |
|
| 136 |
async def close(self) -> None:
|
| 137 |
+
"""Close the connection pool."""
|
| 138 |
+
if self._pool:
|
| 139 |
+
await self._pool.close()
|
| 140 |
+
self._pool = None
|
| 141 |
|
| 142 |
@property
|
| 143 |
+
def pool(self) -> asyncpg.Pool:
|
| 144 |
+
if not self._pool:
|
| 145 |
raise RuntimeError("MemoryStore not initialized. Call initialize() first.")
|
| 146 |
+
return self._pool
|
| 147 |
|
| 148 |
# ------------------------------------------------------------------
|
| 149 |
# Event Calendar
|
|
|
|
| 151 |
|
| 152 |
async def insert_event(self, event: EventRecord) -> str:
|
| 153 |
"""Insert a structured SVO event into the Event Calendar."""
|
| 154 |
+
async with self.pool.acquire() as conn:
|
| 155 |
+
await conn.execute(
|
| 156 |
+
"""
|
| 157 |
+
INSERT INTO events
|
| 158 |
+
(id, source_id, subject, verb, object, timestamp,
|
| 159 |
+
datetime_start, datetime_end, entity_aliases,
|
| 160 |
+
confidence, metadata_json, raw_text, created_at)
|
| 161 |
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
| 162 |
+
ON CONFLICT (id) DO NOTHING
|
| 163 |
+
""",
|
| 164 |
event.id,
|
| 165 |
event.source_id,
|
| 166 |
event.subject,
|
| 167 |
event.verb,
|
| 168 |
event.object,
|
| 169 |
+
event.timestamp,
|
| 170 |
+
event.datetime_start,
|
| 171 |
+
event.datetime_end,
|
| 172 |
json.dumps(event.entity_aliases),
|
| 173 |
event.confidence,
|
| 174 |
json.dumps(event.metadata_json),
|
| 175 |
event.raw_text,
|
| 176 |
+
event.created_at,
|
| 177 |
+
)
|
|
|
|
|
|
|
| 178 |
return event.id
|
| 179 |
|
| 180 |
async def insert_events_batch(self, events: list[EventRecord]) -> list[str]:
|
| 181 |
+
"""Batch insert multiple events using COPY protocol — fastest possible."""
|
| 182 |
if not events:
|
| 183 |
return []
|
| 184 |
|
| 185 |
rows = [
|
| 186 |
(
|
| 187 |
+
e.id, e.source_id, e.subject, e.verb, e.object,
|
| 188 |
+
e.timestamp, e.datetime_start, e.datetime_end,
|
| 189 |
+
json.dumps(e.entity_aliases), e.confidence,
|
| 190 |
+
json.dumps(e.metadata_json), e.raw_text, e.created_at,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
)
|
| 192 |
+
for e in events
|
| 193 |
]
|
| 194 |
|
| 195 |
+
async with self.pool.acquire() as conn:
|
| 196 |
+
await conn.executemany(
|
| 197 |
+
"""
|
| 198 |
+
INSERT INTO events
|
| 199 |
+
(id, source_id, subject, verb, object, timestamp,
|
| 200 |
+
datetime_start, datetime_end, entity_aliases,
|
| 201 |
+
confidence, metadata_json, raw_text, created_at)
|
| 202 |
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
| 203 |
+
ON CONFLICT (id) DO NOTHING
|
| 204 |
+
""",
|
| 205 |
+
rows,
|
| 206 |
+
)
|
| 207 |
return [e.id for e in events]
|
| 208 |
|
| 209 |
async def query_temporal(
|
|
|
|
| 214 |
limit: int = 50,
|
| 215 |
) -> list[EventRecord]:
|
| 216 |
"""Query events by time range."""
|
| 217 |
+
conditions, params = [], []
|
| 218 |
+
i = 1
|
| 219 |
|
| 220 |
if start:
|
| 221 |
+
conditions.append(f"timestamp >= ${i}"); params.append(start); i += 1
|
|
|
|
| 222 |
if end:
|
| 223 |
+
conditions.append(f"timestamp <= ${i}"); params.append(end); i += 1
|
|
|
|
| 224 |
if source_ids:
|
| 225 |
+
conditions.append(f"source_id = ANY(${i})"); params.append(source_ids); i += 1
|
|
|
|
|
|
|
| 226 |
|
| 227 |
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
|
|
|
| 228 |
params.append(limit)
|
| 229 |
+
query = f"SELECT * FROM events {where} ORDER BY timestamp DESC LIMIT ${i}"
|
| 230 |
|
| 231 |
+
async with self.pool.acquire() as conn:
|
| 232 |
+
rows = await conn.fetch(query, *params)
|
| 233 |
+
return [self._row_to_event(r) for r in rows]
|
|
|
|
| 234 |
|
| 235 |
async def query_by_entity(
|
| 236 |
self,
|
|
|
|
| 239 |
limit: int = 50,
|
| 240 |
) -> list[EventRecord]:
|
| 241 |
"""Find events involving a specific entity (subject or object)."""
|
|
|
|
|
|
|
|
|
|
| 242 |
pattern = f"%{entity}%"
|
| 243 |
+
conditions = ["(subject ILIKE $1 OR object ILIKE $1 OR entity_aliases::text ILIKE $1)"]
|
| 244 |
+
params: list = [pattern]
|
| 245 |
+
i = 2
|
| 246 |
|
| 247 |
if source_ids:
|
| 248 |
+
conditions.append(f"source_id = ANY(${i})"); params.append(source_ids); i += 1
|
|
|
|
|
|
|
| 249 |
|
|
|
|
|
|
|
| 250 |
params.append(limit)
|
| 251 |
+
where = f"WHERE {' AND '.join(conditions)}"
|
| 252 |
+
query = f"SELECT * FROM events {where} ORDER BY timestamp DESC LIMIT ${i}"
|
| 253 |
|
| 254 |
+
async with self.pool.acquire() as conn:
|
| 255 |
+
rows = await conn.fetch(query, *params)
|
| 256 |
+
return [self._row_to_event(r) for r in rows]
|
|
|
|
| 257 |
|
| 258 |
async def multi_hop_query(
|
| 259 |
self,
|
|
|
|
| 264 |
limit: int = 50,
|
| 265 |
) -> list[EventRecord]:
|
| 266 |
"""
|
| 267 |
+
Multi-hop temporal query: find events connecting multiple entities.
|
| 268 |
+
The key Chronos differentiator.
|
| 269 |
"""
|
| 270 |
+
entity_parts, params = [], []
|
| 271 |
+
i = 1
|
|
|
|
| 272 |
for entity in entities:
|
| 273 |
pattern = f"%{entity}%"
|
| 274 |
+
entity_parts.append(
|
| 275 |
+
f"(subject ILIKE ${i} OR object ILIKE ${i} OR entity_aliases::text ILIKE ${i})"
|
| 276 |
)
|
| 277 |
+
params.append(pattern); i += 1
|
| 278 |
|
| 279 |
+
conditions = [f"({' OR '.join(entity_parts)})"]
|
| 280 |
|
| 281 |
if start:
|
| 282 |
+
conditions.append(f"timestamp >= ${i}"); params.append(start); i += 1
|
|
|
|
| 283 |
if end:
|
| 284 |
+
conditions.append(f"timestamp <= ${i}"); params.append(end); i += 1
|
|
|
|
| 285 |
if source_ids:
|
| 286 |
+
conditions.append(f"source_id = ANY(${i})"); params.append(source_ids); i += 1
|
|
|
|
|
|
|
| 287 |
|
|
|
|
|
|
|
| 288 |
params.append(limit)
|
| 289 |
+
where = f"WHERE {' AND '.join(conditions)}"
|
| 290 |
+
query = f"SELECT * FROM events {where} ORDER BY timestamp ASC LIMIT ${i}"
|
| 291 |
|
| 292 |
+
async with self.pool.acquire() as conn:
|
| 293 |
+
rows = await conn.fetch(query, *params)
|
| 294 |
+
return [self._row_to_event(r) for r in rows]
|
|
|
|
| 295 |
|
| 296 |
async def get_event(self, event_id: str) -> Optional[EventRecord]:
|
| 297 |
"""Fetch a single event by ID."""
|
| 298 |
+
async with self.pool.acquire() as conn:
|
| 299 |
+
row = await conn.fetchrow("SELECT * FROM events WHERE id = $1", event_id)
|
|
|
|
|
|
|
| 300 |
return self._row_to_event(row) if row else None
|
| 301 |
|
| 302 |
async def get_events_by_ids(self, event_ids: list[str]) -> list[EventRecord]:
|
| 303 |
"""Fetch multiple events by their IDs."""
|
| 304 |
if not event_ids:
|
| 305 |
return []
|
| 306 |
+
async with self.pool.acquire() as conn:
|
| 307 |
+
rows = await conn.fetch(
|
| 308 |
+
"SELECT * FROM events WHERE id = ANY($1)", event_ids
|
| 309 |
+
)
|
| 310 |
+
return [self._row_to_event(r) for r in rows]
|
|
|
|
| 311 |
|
| 312 |
async def count_events(self, source_id: Optional[str] = None) -> int:
|
| 313 |
"""Count total events, optionally filtered by source."""
|
| 314 |
+
async with self.pool.acquire() as conn:
|
| 315 |
+
if source_id:
|
| 316 |
+
return await conn.fetchval(
|
| 317 |
+
"SELECT COUNT(*) FROM events WHERE source_id = $1", source_id
|
| 318 |
+
)
|
| 319 |
+
return await conn.fetchval("SELECT COUNT(*) FROM events")
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
# ------------------------------------------------------------------
|
| 322 |
# Turn Calendar
|
|
|
|
| 324 |
|
| 325 |
async def insert_turn(self, turn: TurnRecord) -> str:
|
| 326 |
"""Insert a raw conversation turn into the Turn Calendar."""
|
| 327 |
+
async with self.pool.acquire() as conn:
|
| 328 |
+
await conn.execute(
|
| 329 |
+
"""
|
| 330 |
+
INSERT INTO turns (id, source_id, role, content, timestamp, event_ids, created_at)
|
| 331 |
+
VALUES ($1,$2,$3,$4,$5,$6,$7)
|
| 332 |
+
ON CONFLICT (id) DO NOTHING
|
| 333 |
+
""",
|
| 334 |
+
turn.id, turn.source_id, turn.role.value,
|
| 335 |
+
turn.content, turn.timestamp,
|
| 336 |
+
json.dumps(turn.event_ids), turn.created_at,
|
| 337 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
return turn.id
|
| 339 |
|
| 340 |
async def get_turns(
|
|
|
|
| 345 |
limit: int = 50,
|
| 346 |
) -> list[TurnRecord]:
|
| 347 |
"""Query conversation turns."""
|
| 348 |
+
conditions, params = [], []
|
| 349 |
+
i = 1
|
| 350 |
|
| 351 |
if source_id:
|
| 352 |
+
conditions.append(f"source_id = ${i}"); params.append(source_id); i += 1
|
|
|
|
| 353 |
if start:
|
| 354 |
+
conditions.append(f"timestamp >= ${i}"); params.append(start); i += 1
|
|
|
|
| 355 |
if end:
|
| 356 |
+
conditions.append(f"timestamp <= ${i}"); params.append(end); i += 1
|
|
|
|
| 357 |
|
|
|
|
|
|
|
| 358 |
params.append(limit)
|
| 359 |
+
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
| 360 |
+
query = f"SELECT * FROM turns {where} ORDER BY timestamp DESC LIMIT ${i}"
|
| 361 |
|
| 362 |
+
async with self.pool.acquire() as conn:
|
| 363 |
+
rows = await conn.fetch(query, *params)
|
| 364 |
+
return [self._row_to_turn(r) for r in rows]
|
|
|
|
| 365 |
|
| 366 |
# ------------------------------------------------------------------
|
| 367 |
# Connectors
|
|
|
|
| 369 |
|
| 370 |
async def insert_connector(self, connector: ConnectorRecord) -> str:
|
| 371 |
"""Register a SaaS tool connector."""
|
| 372 |
+
async with self.pool.acquire() as conn:
|
| 373 |
+
await conn.execute(
|
| 374 |
+
"""
|
| 375 |
+
INSERT INTO connectors
|
| 376 |
+
(id, source_id, name, description, base_url,
|
| 377 |
+
auth_header, endpoints, metadata, created_at)
|
| 378 |
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
| 379 |
+
ON CONFLICT (id) DO UPDATE SET
|
| 380 |
+
name=EXCLUDED.name, description=EXCLUDED.description,
|
| 381 |
+
base_url=EXCLUDED.base_url, auth_header=EXCLUDED.auth_header,
|
| 382 |
+
endpoints=EXCLUDED.endpoints, metadata=EXCLUDED.metadata
|
| 383 |
+
""",
|
| 384 |
+
connector.id, connector.source_id, connector.name,
|
| 385 |
+
connector.description, connector.base_url, connector.auth_header,
|
| 386 |
json.dumps([ep.model_dump() for ep in connector.endpoints]),
|
| 387 |
+
json.dumps(connector.metadata), connector.created_at,
|
| 388 |
+
)
|
|
|
|
|
|
|
|
|
|
| 389 |
return connector.id
|
| 390 |
|
| 391 |
+
async def get_connectors(self, source_id: Optional[str] = None) -> list[ConnectorRecord]:
|
|
|
|
|
|
|
| 392 |
"""List registered connectors."""
|
| 393 |
+
async with self.pool.acquire() as conn:
|
| 394 |
+
if source_id:
|
| 395 |
+
rows = await conn.fetch(
|
| 396 |
+
"SELECT * FROM connectors WHERE source_id = $1", source_id
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
rows = await conn.fetch("SELECT * FROM connectors")
|
| 400 |
+
return [self._row_to_connector(r) for r in rows]
|
|
|
|
| 401 |
|
| 402 |
async def get_connector(self, connector_id: str) -> Optional[ConnectorRecord]:
|
| 403 |
"""Fetch a single connector by ID."""
|
| 404 |
+
async with self.pool.acquire() as conn:
|
| 405 |
+
row = await conn.fetchrow(
|
| 406 |
+
"SELECT * FROM connectors WHERE id = $1", connector_id
|
| 407 |
+
)
|
| 408 |
return self._row_to_connector(row) if row else None
|
| 409 |
|
| 410 |
async def count_connectors(self, source_id: str) -> int:
|
| 411 |
"""Count connectors for a source."""
|
| 412 |
+
async with self.pool.acquire() as conn:
|
| 413 |
+
return await conn.fetchval(
|
| 414 |
+
"SELECT COUNT(*) FROM connectors WHERE source_id = $1", source_id
|
| 415 |
+
)
|
|
|
|
| 416 |
|
| 417 |
# ------------------------------------------------------------------
|
| 418 |
# API Keys & Usage
|
| 419 |
# ------------------------------------------------------------------
|
| 420 |
|
| 421 |
async def register_api_key(
|
| 422 |
+
self, key_hash: str, source_id: str, tier: TierName = TierName.EXPLORER,
|
|
|
|
|
|
|
|
|
|
| 423 |
) -> None:
|
| 424 |
"""Register a new API key."""
|
| 425 |
+
now = datetime.utcnow()
|
| 426 |
+
async with self.pool.acquire() as conn:
|
| 427 |
+
await conn.execute(
|
| 428 |
+
"""
|
| 429 |
+
INSERT INTO api_keys
|
| 430 |
+
(key_hash, source_id, tier, events_used, orchestration_used,
|
| 431 |
+
connectors_used, period_start, created_at)
|
| 432 |
+
VALUES ($1,$2,$3,0,0,0,$4,$4)
|
| 433 |
+
ON CONFLICT (key_hash) DO NOTHING
|
| 434 |
+
""",
|
| 435 |
+
key_hash, source_id, tier.value, now,
|
| 436 |
+
)
|
| 437 |
|
| 438 |
async def get_usage(self, source_id: str) -> Optional[UsageStats]:
|
| 439 |
"""Get usage stats for a source."""
|
| 440 |
+
async with self.pool.acquire() as conn:
|
| 441 |
+
row = await conn.fetchrow(
|
| 442 |
+
"SELECT * FROM api_keys WHERE source_id = $1", source_id
|
| 443 |
+
)
|
|
|
|
| 444 |
if not row:
|
| 445 |
return None
|
|
|
|
| 446 |
return UsageStats(
|
| 447 |
source_id=row["source_id"],
|
| 448 |
tier=TierName(row["tier"]),
|
| 449 |
events_used=row["events_used"],
|
| 450 |
orchestration_used=row["orchestration_used"],
|
| 451 |
connectors_used=row["connectors_used"],
|
| 452 |
+
period_start=row["period_start"],
|
| 453 |
)
|
| 454 |
|
| 455 |
async def increment_usage(
|
| 456 |
+
self, source_id: str, events: int = 0, orchestration: int = 0,
|
|
|
|
|
|
|
|
|
|
| 457 |
) -> None:
|
| 458 |
"""Increment usage counters for a source."""
|
| 459 |
+
async with self.pool.acquire() as conn:
|
| 460 |
+
await conn.execute(
|
| 461 |
+
"""
|
| 462 |
+
UPDATE api_keys SET
|
| 463 |
+
events_used = events_used + $1,
|
| 464 |
+
orchestration_used = orchestration_used + $2
|
| 465 |
+
WHERE source_id = $3
|
| 466 |
+
""",
|
| 467 |
+
events, orchestration, source_id,
|
| 468 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
|
| 470 |
async def validate_api_key(self, key_hash: str) -> Optional[dict]:
|
| 471 |
"""Validate an API key and return source info."""
|
| 472 |
+
async with self.pool.acquire() as conn:
|
| 473 |
+
row = await conn.fetchrow(
|
| 474 |
+
"SELECT * FROM api_keys WHERE key_hash = $1", key_hash
|
| 475 |
+
)
|
| 476 |
+
return dict(row) if row else None
|
|
|
|
|
|
|
| 477 |
|
| 478 |
# ------------------------------------------------------------------
|
| 479 |
# Row Converters
|
|
|
|
| 481 |
|
| 482 |
@staticmethod
|
| 483 |
def _row_to_event(row) -> EventRecord:
|
|
|
|
| 484 |
return EventRecord(
|
| 485 |
id=row["id"],
|
| 486 |
source_id=row["source_id"],
|
| 487 |
subject=row["subject"],
|
| 488 |
verb=row["verb"],
|
| 489 |
object=row["object"],
|
| 490 |
+
timestamp=row["timestamp"],
|
| 491 |
+
datetime_start=row["datetime_start"],
|
| 492 |
+
datetime_end=row["datetime_end"],
|
| 493 |
+
entity_aliases=json.loads(row["entity_aliases"]) if isinstance(row["entity_aliases"], str) else (row["entity_aliases"] or []),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
confidence=row["confidence"],
|
| 495 |
+
metadata_json=json.loads(row["metadata_json"]) if isinstance(row["metadata_json"], str) else (row["metadata_json"] or {}),
|
| 496 |
raw_text=row["raw_text"] or "",
|
| 497 |
+
created_at=row["created_at"],
|
| 498 |
)
|
| 499 |
|
| 500 |
@staticmethod
|
| 501 |
def _row_to_turn(row) -> TurnRecord:
|
|
|
|
| 502 |
return TurnRecord(
|
| 503 |
id=row["id"],
|
| 504 |
source_id=row["source_id"],
|
| 505 |
role=TurnRole(row["role"]),
|
| 506 |
content=row["content"],
|
| 507 |
+
timestamp=row["timestamp"],
|
| 508 |
+
event_ids=json.loads(row["event_ids"]) if isinstance(row["event_ids"], str) else (row["event_ids"] or []),
|
| 509 |
+
created_at=row["created_at"],
|
| 510 |
)
|
| 511 |
|
| 512 |
@staticmethod
|
| 513 |
def _row_to_connector(row) -> ConnectorRecord:
|
|
|
|
| 514 |
from .models import ConnectorEndpoint
|
| 515 |
+
endpoints_raw = json.loads(row["endpoints"]) if isinstance(row["endpoints"], str) else (row["endpoints"] or [])
|
|
|
|
|
|
|
| 516 |
return ConnectorRecord(
|
| 517 |
id=row["id"],
|
| 518 |
source_id=row["source_id"],
|
|
|
|
| 520 |
description=row["description"] or "",
|
| 521 |
base_url=row["base_url"],
|
| 522 |
auth_header=row["auth_header"],
|
| 523 |
+
endpoints=[ConnectorEndpoint(**ep) for ep in endpoints_raw],
|
| 524 |
+
metadata=json.loads(row["metadata"]) if isinstance(row["metadata"], str) else (row["metadata"] or {}),
|
| 525 |
+
created_at=row["created_at"],
|
| 526 |
)
|
chronos_core/vector_store.py
CHANGED
|
@@ -1,16 +1,19 @@
|
|
| 1 |
"""
|
| 2 |
Chronos OS — Vector Store
|
| 3 |
==========================
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
• ChromaDB → broad semantic recall (fuzzy)
|
| 7 |
-
• SQLite → precise temporal / entity filtering (deterministic)
|
| 8 |
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
from __future__ import annotations
|
| 13 |
|
|
|
|
| 14 |
import logging
|
| 15 |
import os
|
| 16 |
from datetime import datetime
|
|
@@ -23,122 +26,125 @@ logger = logging.getLogger("chronos.vector_store")
|
|
| 23 |
|
| 24 |
class VectorStore:
|
| 25 |
"""
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
as metadata for cross-store joins.
|
| 29 |
"""
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
self.
|
| 36 |
-
self.
|
| 37 |
|
| 38 |
# ------------------------------------------------------------------
|
| 39 |
# Lifecycle
|
| 40 |
# ------------------------------------------------------------------
|
| 41 |
|
| 42 |
-
async def initialize(self) -> None:
|
| 43 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
import asyncio
|
| 45 |
-
await asyncio.to_thread(self.
|
| 46 |
-
|
| 47 |
-
def _sync_initialize(self) -> None:
|
| 48 |
-
"""Synchronous ChromaDB initialization (called via to_thread)."""
|
| 49 |
-
import chromadb
|
| 50 |
-
from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
self.
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
model_name="all-MiniLM-L6-v2"
|
| 60 |
-
)
|
| 61 |
-
|
| 62 |
-
self._collection = self._client.get_or_create_collection(
|
| 63 |
-
name="chronos_events",
|
| 64 |
-
embedding_function=embedding_fn,
|
| 65 |
-
metadata={
|
| 66 |
-
"description": "Chronos temporal event embeddings",
|
| 67 |
-
"hnsw:space": "cosine",
|
| 68 |
-
},
|
| 69 |
-
)
|
| 70 |
-
count = self._collection.count()
|
| 71 |
-
logger.info(
|
| 72 |
-
f"Vector store initialized at {self.persist_dir} "
|
| 73 |
-
f"({count} existing embeddings)"
|
| 74 |
-
)
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
if
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
)
|
| 82 |
-
return self._collection
|
| 83 |
|
| 84 |
# ------------------------------------------------------------------
|
| 85 |
# Insert
|
| 86 |
# ------------------------------------------------------------------
|
| 87 |
|
| 88 |
async def add_event(self, event: EventRecord) -> None:
|
| 89 |
-
"""
|
| 90 |
-
Embed and store an event.
|
| 91 |
-
Uses ChromaDB's built-in embedding function (all-MiniLM-L6-v2 by default).
|
| 92 |
-
"""
|
| 93 |
import asyncio
|
| 94 |
-
|
| 95 |
-
# Build the text to embed: combine SVO + raw for richer semantics
|
| 96 |
embed_text = self._build_embed_text(event)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
"
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
| 112 |
|
| 113 |
async def add_events_batch(self, events: list[EventRecord]) -> None:
|
| 114 |
-
"""
|
| 115 |
if not events:
|
| 116 |
return
|
| 117 |
-
|
| 118 |
import asyncio
|
| 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 |
# Search
|
|
@@ -154,48 +160,63 @@ class VectorStore:
|
|
| 154 |
end_time: Optional[datetime] = None,
|
| 155 |
) -> list[dict]:
|
| 156 |
"""
|
| 157 |
-
|
| 158 |
Returns list of {id, distance, metadata} dicts.
|
| 159 |
-
|
| 160 |
-
Privacy: when owner_id is set, only events belonging to that
|
| 161 |
-
owner are returned (tenant isolation).
|
| 162 |
"""
|
| 163 |
import asyncio
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
source_ids, start_time, end_time, owner_id
|
| 168 |
-
)
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
"n_results": min(n_results, self.collection.count() or 1),
|
| 173 |
-
}
|
| 174 |
-
if where_filter:
|
| 175 |
-
kwargs["where"] = where_filter
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
if
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
async def count(self) -> int:
|
| 196 |
-
"""Get total number of embeddings."""
|
| 197 |
-
|
| 198 |
-
|
| 199 |
|
| 200 |
# ------------------------------------------------------------------
|
| 201 |
# Helpers
|
|
@@ -203,39 +224,8 @@ class VectorStore:
|
|
| 203 |
|
| 204 |
@staticmethod
|
| 205 |
def _build_embed_text(event: EventRecord) -> str:
|
| 206 |
-
"""Build
|
| 207 |
-
parts = [
|
| 208 |
-
f"{event.subject} {event.verb} {event.object}",
|
| 209 |
-
]
|
| 210 |
if event.raw_text:
|
| 211 |
parts.append(event.raw_text)
|
| 212 |
return " | ".join(parts)
|
| 213 |
-
|
| 214 |
-
@staticmethod
|
| 215 |
-
def _build_where_filter(
|
| 216 |
-
source_ids: Optional[list[str]] = None,
|
| 217 |
-
start_time: Optional[datetime] = None,
|
| 218 |
-
end_time: Optional[datetime] = None,
|
| 219 |
-
owner_id: Optional[str] = None,
|
| 220 |
-
) -> Optional[dict]:
|
| 221 |
-
"""Build a ChromaDB WHERE filter with tenant isolation."""
|
| 222 |
-
conditions = []
|
| 223 |
-
|
| 224 |
-
# Tenant isolation: owner_id takes priority
|
| 225 |
-
if owner_id:
|
| 226 |
-
conditions.append({"owner_id": {"$eq": owner_id}})
|
| 227 |
-
elif source_ids and len(source_ids) == 1:
|
| 228 |
-
conditions.append({"source_id": {"$eq": source_ids[0]}})
|
| 229 |
-
elif source_ids and len(source_ids) > 1:
|
| 230 |
-
conditions.append({"source_id": {"$in": source_ids}})
|
| 231 |
-
|
| 232 |
-
if start_time:
|
| 233 |
-
conditions.append({"timestamp": {"$gte": start_time.isoformat()}})
|
| 234 |
-
if end_time:
|
| 235 |
-
conditions.append({"timestamp": {"$lte": end_time.isoformat()}})
|
| 236 |
-
|
| 237 |
-
if not conditions:
|
| 238 |
-
return None
|
| 239 |
-
if len(conditions) == 1:
|
| 240 |
-
return conditions[0]
|
| 241 |
-
return {"$and": conditions}
|
|
|
|
| 1 |
"""
|
| 2 |
Chronos OS — Vector Store
|
| 3 |
==========================
|
| 4 |
+
pgvector semantic search layer backed by Neon PostgreSQL.
|
| 5 |
+
Replaces ChromaDB while keeping the same API surface.
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
Dual-retrieval pipeline:
|
| 8 |
+
• pgvector → broad semantic recall (cosine similarity, fuzzy)
|
| 9 |
+
• PostgreSQL → precise temporal / entity filtering (deterministic)
|
| 10 |
+
|
| 11 |
+
Embeddings: all-MiniLM-L6-v2 (384 dims) via sentence-transformers.
|
| 12 |
"""
|
| 13 |
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
+
import json
|
| 17 |
import logging
|
| 18 |
import os
|
| 19 |
from datetime import datetime
|
|
|
|
| 26 |
|
| 27 |
class VectorStore:
|
| 28 |
"""
|
| 29 |
+
pgvector-backed semantic search over Chronos events.
|
| 30 |
+
Shares the same asyncpg pool as the MemoryStore for efficiency.
|
|
|
|
| 31 |
"""
|
| 32 |
|
| 33 |
+
EMBEDDING_DIM = 384 # all-MiniLM-L6-v2
|
| 34 |
+
|
| 35 |
+
def __init__(self, pool=None):
|
| 36 |
+
# Pool is injected by api/main.py after MemoryStore initializes
|
| 37 |
+
self._pool = pool
|
| 38 |
+
self._model = None
|
| 39 |
|
| 40 |
# ------------------------------------------------------------------
|
| 41 |
# Lifecycle
|
| 42 |
# ------------------------------------------------------------------
|
| 43 |
|
| 44 |
+
async def initialize(self, pool=None) -> None:
|
| 45 |
+
"""Create the vectors table and HNSW index if not present."""
|
| 46 |
+
if pool:
|
| 47 |
+
self._pool = pool
|
| 48 |
+
|
| 49 |
+
if not self._pool:
|
| 50 |
+
raise RuntimeError("VectorStore requires an asyncpg pool.")
|
| 51 |
+
|
| 52 |
+
async with self._pool.acquire() as conn:
|
| 53 |
+
await conn.execute(f"""
|
| 54 |
+
CREATE TABLE IF NOT EXISTS event_vectors (
|
| 55 |
+
event_id TEXT PRIMARY KEY REFERENCES events(id) ON DELETE CASCADE,
|
| 56 |
+
source_id TEXT NOT NULL,
|
| 57 |
+
owner_id TEXT NOT NULL,
|
| 58 |
+
embedding vector({self.EMBEDDING_DIM}) NOT NULL,
|
| 59 |
+
embed_text TEXT NOT NULL,
|
| 60 |
+
timestamp TIMESTAMPTZ NOT NULL
|
| 61 |
+
);
|
| 62 |
+
CREATE INDEX IF NOT EXISTS idx_vectors_source
|
| 63 |
+
ON event_vectors(source_id);
|
| 64 |
+
CREATE INDEX IF NOT EXISTS idx_vectors_owner
|
| 65 |
+
ON event_vectors(owner_id);
|
| 66 |
+
""")
|
| 67 |
+
|
| 68 |
+
# Load embedding model in background thread
|
| 69 |
import asyncio
|
| 70 |
+
await asyncio.to_thread(self._load_model)
|
| 71 |
+
logger.info(f"Vector store initialized (pgvector {self.EMBEDDING_DIM}d)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
def _load_model(self) -> None:
|
| 74 |
+
"""Load the sentence-transformer model (cached after first call)."""
|
| 75 |
+
if self._model is not None:
|
| 76 |
+
return
|
| 77 |
+
from sentence_transformers import SentenceTransformer
|
| 78 |
+
self._model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 79 |
+
logger.info("Embedding model loaded: all-MiniLM-L6-v2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
def _embed(self, text: str) -> list[float]:
|
| 82 |
+
"""Embed text using sentence-transformers."""
|
| 83 |
+
if self._model is None:
|
| 84 |
+
self._load_model()
|
| 85 |
+
return self._model.encode(text, normalize_embeddings=True).tolist()
|
|
|
|
|
|
|
| 86 |
|
| 87 |
# ------------------------------------------------------------------
|
| 88 |
# Insert
|
| 89 |
# ------------------------------------------------------------------
|
| 90 |
|
| 91 |
async def add_event(self, event: EventRecord) -> None:
|
| 92 |
+
"""Embed and store a single event vector."""
|
|
|
|
|
|
|
|
|
|
| 93 |
import asyncio
|
|
|
|
|
|
|
| 94 |
embed_text = self._build_embed_text(event)
|
| 95 |
+
embedding = await asyncio.to_thread(self._embed, embed_text)
|
| 96 |
+
owner_id = event.metadata_json.get("owner_id", event.source_id)
|
| 97 |
+
|
| 98 |
+
async with self._pool.acquire() as conn:
|
| 99 |
+
await conn.execute(
|
| 100 |
+
"""
|
| 101 |
+
INSERT INTO event_vectors
|
| 102 |
+
(event_id, source_id, owner_id, embedding, embed_text, timestamp)
|
| 103 |
+
VALUES ($1, $2, $3, $4::vector, $5, $6)
|
| 104 |
+
ON CONFLICT (event_id) DO UPDATE SET
|
| 105 |
+
embedding = EXCLUDED.embedding,
|
| 106 |
+
embed_text = EXCLUDED.embed_text
|
| 107 |
+
""",
|
| 108 |
+
event.id, event.source_id, owner_id,
|
| 109 |
+
f"[{','.join(str(x) for x in embedding)}]",
|
| 110 |
+
embed_text, event.timestamp,
|
| 111 |
+
)
|
| 112 |
|
| 113 |
async def add_events_batch(self, events: list[EventRecord]) -> None:
|
| 114 |
+
"""Embed and store multiple events — embeddings computed in parallel."""
|
| 115 |
if not events:
|
| 116 |
return
|
|
|
|
| 117 |
import asyncio
|
| 118 |
|
| 119 |
+
embed_texts = [self._build_embed_text(e) for e in events]
|
| 120 |
+
# Encode all at once (sentence-transformers batches efficiently)
|
| 121 |
+
embeddings = await asyncio.to_thread(
|
| 122 |
+
lambda: self._model.encode(embed_texts, normalize_embeddings=True, batch_size=32).tolist()
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
rows = [
|
| 126 |
+
(
|
| 127 |
+
e.id, e.source_id,
|
| 128 |
+
e.metadata_json.get("owner_id", e.source_id),
|
| 129 |
+
f"[{','.join(str(x) for x in emb)}]",
|
| 130 |
+
txt, e.timestamp,
|
| 131 |
+
)
|
| 132 |
+
for e, emb, txt in zip(events, embeddings, embed_texts)
|
| 133 |
]
|
| 134 |
|
| 135 |
+
async with self._pool.acquire() as conn:
|
| 136 |
+
await conn.executemany(
|
| 137 |
+
"""
|
| 138 |
+
INSERT INTO event_vectors
|
| 139 |
+
(event_id, source_id, owner_id, embedding, embed_text, timestamp)
|
| 140 |
+
VALUES ($1, $2, $3, $4::vector, $5, $6)
|
| 141 |
+
ON CONFLICT (event_id) DO UPDATE SET
|
| 142 |
+
embedding = EXCLUDED.embedding,
|
| 143 |
+
embed_text = EXCLUDED.embed_text
|
| 144 |
+
""",
|
| 145 |
+
rows,
|
| 146 |
+
)
|
| 147 |
+
logger.info(f"Batch added {len(events)} event vectors to pgvector")
|
| 148 |
|
| 149 |
# ------------------------------------------------------------------
|
| 150 |
# Search
|
|
|
|
| 160 |
end_time: Optional[datetime] = None,
|
| 161 |
) -> list[dict]:
|
| 162 |
"""
|
| 163 |
+
Cosine similarity search over embedded events.
|
| 164 |
Returns list of {id, distance, metadata} dicts.
|
| 165 |
+
Privacy: owner_id enforces strict tenant isolation.
|
|
|
|
|
|
|
| 166 |
"""
|
| 167 |
import asyncio
|
| 168 |
|
| 169 |
+
query_embedding = await asyncio.to_thread(self._embed, query)
|
| 170 |
+
vec_str = f"[{','.join(str(x) for x in query_embedding)}]"
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
conditions, params = [], [vec_str]
|
| 173 |
+
i = 2
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
# Tenant isolation
|
| 176 |
+
if owner_id:
|
| 177 |
+
conditions.append(f"owner_id = ${i}"); params.append(owner_id); i += 1
|
| 178 |
+
elif source_ids:
|
| 179 |
+
conditions.append(f"source_id = ANY(${i})"); params.append(source_ids); i += 1
|
| 180 |
|
| 181 |
+
if start_time:
|
| 182 |
+
conditions.append(f"timestamp >= ${i}"); params.append(start_time); i += 1
|
| 183 |
+
if end_time:
|
| 184 |
+
conditions.append(f"timestamp <= ${i}"); params.append(end_time); i += 1
|
| 185 |
+
|
| 186 |
+
params.append(n_results)
|
| 187 |
+
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
| 188 |
+
|
| 189 |
+
query_sql = f"""
|
| 190 |
+
SELECT event_id,
|
| 191 |
+
(embedding <=> $1::vector) AS distance,
|
| 192 |
+
source_id, owner_id, embed_text, timestamp
|
| 193 |
+
FROM event_vectors
|
| 194 |
+
{where}
|
| 195 |
+
ORDER BY embedding <=> $1::vector
|
| 196 |
+
LIMIT ${i}
|
| 197 |
+
"""
|
| 198 |
|
| 199 |
+
async with self._pool.acquire() as conn:
|
| 200 |
+
rows = await conn.fetch(query_sql, *params)
|
| 201 |
+
|
| 202 |
+
return [
|
| 203 |
+
{
|
| 204 |
+
"id": r["event_id"],
|
| 205 |
+
"distance": float(r["distance"]),
|
| 206 |
+
"metadata": {
|
| 207 |
+
"source_id": r["source_id"],
|
| 208 |
+
"owner_id": r["owner_id"],
|
| 209 |
+
"timestamp": r["timestamp"].isoformat(),
|
| 210 |
+
},
|
| 211 |
+
"document": r["embed_text"],
|
| 212 |
+
}
|
| 213 |
+
for r in rows
|
| 214 |
+
]
|
| 215 |
|
| 216 |
async def count(self) -> int:
|
| 217 |
+
"""Get total number of stored embeddings."""
|
| 218 |
+
async with self._pool.acquire() as conn:
|
| 219 |
+
return await conn.fetchval("SELECT COUNT(*) FROM event_vectors")
|
| 220 |
|
| 221 |
# ------------------------------------------------------------------
|
| 222 |
# Helpers
|
|
|
|
| 224 |
|
| 225 |
@staticmethod
|
| 226 |
def _build_embed_text(event: EventRecord) -> str:
|
| 227 |
+
"""Build rich text for embedding: SVO + raw text."""
|
| 228 |
+
parts = [f"{event.subject} {event.verb} {event.object}"]
|
|
|
|
|
|
|
| 229 |
if event.raw_text:
|
| 230 |
parts.append(event.raw_text)
|
| 231 |
return " | ".join(parts)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
render.yaml
CHANGED
|
@@ -9,9 +9,7 @@ services:
|
|
| 9 |
sync: false
|
| 10 |
- key: CEREBRAS_API_KEY
|
| 11 |
sync: false
|
| 12 |
-
- key:
|
| 13 |
-
|
| 14 |
-
- key: CHROMA_PERSIST_DIR
|
| 15 |
-
value: ./data/chroma
|
| 16 |
- key: API_SECRET_KEY
|
| 17 |
generateValue: true
|
|
|
|
| 9 |
sync: false
|
| 10 |
- key: CEREBRAS_API_KEY
|
| 11 |
sync: false
|
| 12 |
+
- key: DATABASE_URL
|
| 13 |
+
sync: false
|
|
|
|
|
|
|
| 14 |
- key: API_SECRET_KEY
|
| 15 |
generateValue: true
|
requirements.txt
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
fastapi>=0.115.0
|
| 2 |
uvicorn[standard]>=0.34.0
|
| 3 |
pydantic>=2.10.0
|
| 4 |
-
|
| 5 |
-
|
| 6 |
groq>=0.13.0
|
| 7 |
litellm>=1.60.0
|
| 8 |
langgraph>=0.4.0
|
|
|
|
| 1 |
fastapi>=0.115.0
|
| 2 |
uvicorn[standard]>=0.34.0
|
| 3 |
pydantic>=2.10.0
|
| 4 |
+
asyncpg>=0.30.0
|
| 5 |
+
pgvector>=0.3.2
|
| 6 |
groq>=0.13.0
|
| 7 |
litellm>=1.60.0
|
| 8 |
langgraph>=0.4.0
|