Files
loki/scripts/embed-server.py
T
CatoandClaude Fable 5.1 95c40a9cd8 refactor: rename the product from FleetCrown to Loki (#695)
The product, its assistant, the repo, the host and every unit on the box now
share one name. 638 files, ~3,000 mentions: UI copy, config, env keys
(FLEETCROWN_* -> LOKI_*), systemd units (fleetcrown-* -> loki-*), docs,
articles, the deploy workflow other repos reuse, and nine file names.

- Three article slugs carried the old name and had been shared; permanent
  redirects keep those links alive (next.config.ts).
- test-no-retired-name.sh now also forbids the old product name across the
  whole repo, so the rename cannot creep back through templates and examples.
- ASSISTANT_STACK collapses the product and the assistant into one entry,
  because they are now the same name.

Infra was cut over ahead of this merge: /opt/loki, loki-* units, the `loki`
database and role, loki.orangecat.ch (old host 308s to it; /api, /widget,
/embed keep proxying), GitHub repos bitbaum/loki and bitbaum/loki-releases.
The Resend sending domain stays fleetcrown.orangecat.ch until the new domain
is verified in DNS.


Claude-Session: https://claude.ai/code/session_016YJVAanfj8keVSXyZnTemh

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:13:10 -07:00

72 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Local OpenAI-compatible embeddings server for Loki'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()