mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 17:47:39 +01:00
Captain-layer RAG — index what only FleetCrown sees across the fleet, never repo
code (the runtime retrieves that itself). Context injection becomes relevance-
ranked instead of profile-dump.
- Local embeddings: scripts/embed-server.py — fastembed BAAI/bge-small-en-v1.5
(384-dim) behind an OpenAI-compatible /v1/embeddings, on the box (no cloud key).
systemd fleetcrown-embed.service.
- src/lib/rag/embeddings.ts — provider-agnostic client (ported from OrangeCat's
convention; EMBEDDINGS_BASE_URL/MODEL/DIM, graceful-off when unset → local dev).
- knowledge_embeddings table (pgvector, vector(384), user_id-scoped) — Drizzle
schema + raw-SQL ingest/cosine-retrieve in db/queries/knowledge-embeddings.ts.
- scripts/reindex-knowledge.ts — backfill project profiles + dev-logs (P0).
- inject-core: dispatches now get a "Relevant context from your other projects"
block retrieved against the task, excluding the project it's for. The engine
under cross-project reference's suggested-references, and the first real fix
for the "memory is the weakest strut" gap.
- docs/architecture/{cross-project-reference,fleet-knowledge-rag}.md — specs.
Verified live on the box: retrieval is semantically accurate (bitcoin→orangecat,
refugee housing→aoz-housing). 24 chunks indexed across 21 projects. tsc=0, eslint=0.
72 lines
2.8 KiB
Python
72 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Local OpenAI-compatible embeddings server for FleetCrown's fleet-knowledge RAG.
|
|
|
|
No cloud key: runs BAAI/bge-small-en-v1.5 (384-dim) on CPU via fastembed/onnxruntime.
|
|
Speaks just enough of the OpenAI /v1/embeddings shape that our provider-agnostic
|
|
embeddings.ts can point EMBEDDINGS_BASE_URL at http://127.0.0.1:7997/v1 unchanged.
|
|
|
|
Bind: 127.0.0.1:7997 (loopback only — the box app + hosted runner reach it locally).
|
|
"""
|
|
import json
|
|
import os
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
from fastembed import TextEmbedding
|
|
|
|
MODEL_NAME = os.environ.get("EMBED_MODEL", "BAAI/bge-small-en-v1.5") # 384-dim
|
|
PORT = int(os.environ.get("EMBED_PORT", "7997"))
|
|
|
|
print(f"[embed] loading {MODEL_NAME} …", flush=True)
|
|
_model = TextEmbedding(model_name=MODEL_NAME)
|
|
# Warm + discover dimension.
|
|
_dim = len(next(iter(_model.embed(["warmup"]))).tolist())
|
|
print(f"[embed] ready: {MODEL_NAME} dim={_dim} on :{PORT}", flush=True)
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def _send(self, code: int, payload: dict) -> None:
|
|
body = json.dumps(payload).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def do_GET(self) -> None: # health + model list
|
|
if self.path.rstrip("/") in ("/health", "/v1/health"):
|
|
self._send(200, {"status": "ok", "model": MODEL_NAME, "dim": _dim})
|
|
elif self.path.rstrip("/") == "/v1/models":
|
|
self._send(200, {"object": "list", "data": [{"id": MODEL_NAME, "object": "model"}]})
|
|
else:
|
|
self._send(404, {"error": "not found"})
|
|
|
|
def do_POST(self) -> None:
|
|
if self.path.rstrip("/") != "/v1/embeddings":
|
|
self._send(404, {"error": "not found"})
|
|
return
|
|
try:
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
req = json.loads(self.rfile.read(length) or b"{}")
|
|
inp = req.get("input", "")
|
|
texts = [inp] if isinstance(inp, str) else list(inp)
|
|
if not texts:
|
|
self._send(400, {"error": "input required"})
|
|
return
|
|
vectors = [v.tolist() for v in _model.embed(texts)]
|
|
data = [{"object": "embedding", "index": i, "embedding": v} for i, v in enumerate(vectors)]
|
|
self._send(200, {
|
|
"object": "list",
|
|
"data": data,
|
|
"model": req.get("model", MODEL_NAME),
|
|
"usage": {"prompt_tokens": 0, "total_tokens": 0},
|
|
})
|
|
except Exception as e: # surface, don't crash the server
|
|
self._send(500, {"error": str(e)})
|
|
|
|
def log_message(self, *args) -> None: # quiet
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
|