Download app.py from Omnicore1/cortex: direct link, hf CLI and curl.
- Browser
- Download file 39.3 kB
-
https://huggingface.co/spaces/Omnicore1/cortex/resolve/main/app.py
- Command line
-
hf download hf://spaces/Omnicore1/cortex/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Omnicore1/cortex/resolve/main/app.py
39.3 kB
| """ | |
| OMNI Cortex β Cybernetic God Edition (v5.1, driver-aligned) | |
| ============================================================ | |
| This Space implements the **exact** wire contract that | |
| omni/core/cortex_driver.py expects: | |
| POST /llm {prompt, model?, temperature?, max_tokens?, system?} | |
| -> {text, ...receipt} | |
| POST /embed {text} -> {vector:[...]} | |
| POST /similar {text|vector, top_k} -> {hits:[{id,score,text,meta}]} | |
| POST /score {text, dimensions} -> {dim:float, ..., _rationale:"β¦"} | |
| POST /memory/store {key, text, meta} -> {id} | |
| POST /memory/recall {query, top_k} -> {hits:[β¦]} | |
| GET /healthz -> 200 | |
| Auth: optional `Authorization: Bearer <CORTEX_API_KEY>`. | |
| Bonus endpoints (not part of driver contract β used by /radar consumers): | |
| WS /radar β realtime ModelCallReceipt fan-out | |
| GET /radar/receipts?limit=N β ring-buffer dump | |
| Architecture | |
| ------------ | |
| 1. Cost-ascending provider waterfall: Groq β Together β OpenRouter β | |
| OpenAI β Anthropic β HF Inference. Every call yields a | |
| ModelCallReceipt that fans out to /radar and is retained in a | |
| 512-deep ring. | |
| 2. Qdrant memory with in-process LRU fallback so the Space boots | |
| without any secrets configured. | |
| 3. /score forces the LLM into Chain-of-Thought reasoning: the system | |
| prompt requires a `"_rationale"` string with explicit deduction | |
| BEFORE any numeric dimension scores are emitted. The driver's | |
| `score()` helper filters non-numeric keys, so `_rationale` is | |
| invisible to callers but auditable on /radar. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import hashlib | |
| import json | |
| import logging | |
| import math | |
| import os | |
| import time | |
| import uuid | |
| from collections import deque | |
| from dataclasses import dataclass, field | |
| from typing import Any, Awaitable, Callable, Deque, Dict, List, Optional, Tuple | |
| import httpx | |
| from fastapi import (Body, Depends, FastAPI, Header, HTTPException, Query, | |
| WebSocket, WebSocketDisconnect) | |
| from pydantic import BaseModel, ConfigDict, Field | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CONFIG | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| logging.basicConfig(level=logging.INFO, | |
| format="%(asctime)s %(levelname)s %(name)s :: %(message)s") | |
| log = logging.getLogger("cortex") | |
| CORTEX_API_KEY = os.environ.get("CORTEX_API_KEY", | |
| os.environ.get("CORTEX_TOKEN", "")) | |
| CORTEX_PORT = int(os.environ.get("PORT", | |
| os.environ.get("CORTEX_PORT", "7860"))) | |
| # providers | |
| OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "") | |
| ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "") | |
| OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "") | |
| TOGETHER_API_KEY = os.environ.get("TOGETHER_API_KEY", "") | |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "") | |
| HF_TOKEN = os.environ.get("HF_TOKEN", "") | |
| # qdrant | |
| QDRANT_URL = os.environ.get("QDRANT_URL", "") | |
| QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "") | |
| QDRANT_COLLECTION = os.environ.get("QDRANT_COLLECTION", "omni_memory") | |
| QDRANT_VECTOR_SIZE = int(os.environ.get("QDRANT_VECTOR_SIZE", "384")) | |
| # embedding endpoint (HF inference compatible) | |
| EMBED_ENDPOINT = os.environ.get("EMBED_ENDPOINT", | |
| "https://api-inference.huggingface.co/models/" | |
| "sentence-transformers/all-MiniLM-L6-v2") | |
| REQUEST_TIMEOUT = float(os.environ.get("CORTEX_TIMEOUT", "60")) | |
| RADAR_QUEUE_MAX = int(os.environ.get("CORTEX_RADAR_QUEUE", "256")) | |
| RECEIPT_RING = int(os.environ.get("CORTEX_RECEIPT_RING", "512")) | |
| DEFAULT_MODEL_CLASS = os.environ.get("CORTEX_DEFAULT_CLASS", "balanced") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # SCHEMAS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class LLMRequest(BaseModel): | |
| """Public /llm request β driver-aligned. Extra fields are accepted but | |
| optional so that internal callers (Forge) can pass system + routing hints | |
| without breaking the driver contract.""" | |
| model_config = ConfigDict(protected_namespaces=()) | |
| prompt: str | |
| model: Optional[str] = None | |
| temperature: float = 0.7 | |
| max_tokens: int = 2048 | |
| # extras (Forge uses these; driver does not) | |
| system: Optional[str] = None | |
| model_class: str = Field(default=DEFAULT_MODEL_CLASS, | |
| description="cheap | balanced | premium | reasoning") | |
| json_mode: bool = False | |
| intent: Optional[str] = None | |
| tags: List[str] = Field(default_factory=list) | |
| request_id: Optional[str] = None | |
| class LLMResponse(BaseModel): | |
| text: str = "" | |
| provider: str = "" | |
| model: str = "" | |
| cost_score: float = 0.0 | |
| latency_ms: float = 0.0 | |
| request_id: str = "" | |
| receipt_id: str = "" | |
| fallbacks: List[str] = Field(default_factory=list) | |
| ok: bool = True | |
| error: Optional[str] = None | |
| class EmbedRequest(BaseModel): | |
| text: str | |
| class SimilarRequest(BaseModel): | |
| text: Optional[str] = None | |
| vector: Optional[List[float]] = None | |
| top_k: int = 5 | |
| namespace: str = "default" | |
| filters: Dict[str, Any] = Field(default_factory=dict) | |
| class ScoreRequest(BaseModel): | |
| model_config = ConfigDict(protected_namespaces=()) | |
| text: str | |
| dimensions: List[str] | |
| model_class: str = "balanced" | |
| class MemoryStoreRequest(BaseModel): | |
| key: str | |
| text: str | |
| meta: Dict[str, Any] = Field(default_factory=dict) | |
| namespace: str = "default" | |
| class MemoryRecallRequest(BaseModel): | |
| query: str | |
| top_k: int = 5 | |
| namespace: str = "default" | |
| filters: Dict[str, Any] = Field(default_factory=dict) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PROVIDER ROUTER (waterfall) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class Provider: | |
| name: str | |
| enabled: bool | |
| cost_score: float | |
| classes: Tuple[str, ...] | |
| model_for: Dict[str, str] | |
| impl: Callable[..., Awaitable[Tuple[str, str]]] | |
| _HTTP: Optional[httpx.AsyncClient] = None | |
| def _http() -> httpx.AsyncClient: | |
| global _HTTP | |
| if _HTTP is None: | |
| _HTTP = httpx.AsyncClient(timeout=REQUEST_TIMEOUT, | |
| headers={"User-Agent": "OMNI-Cortex/5.1"}) | |
| return _HTTP | |
| # βββββββββββββββββββββββββββ OpenAI compatible ββββββββββββββββββββββββββ | |
| async def _openai_compat_call(base_url: str, api_key: str, model: str, | |
| prompt: str, system: Optional[str], | |
| max_tokens: int, temperature: float, | |
| json_mode: bool) -> Tuple[str, str]: | |
| msgs = [] | |
| if system: | |
| msgs.append({"role": "system", "content": system}) | |
| msgs.append({"role": "user", "content": prompt}) | |
| body: Dict[str, Any] = { | |
| "model": model, "messages": msgs, | |
| "max_tokens": max_tokens, "temperature": temperature, | |
| } | |
| if json_mode: | |
| body["response_format"] = {"type": "json_object"} | |
| r = await _http().post(f"{base_url}/chat/completions", | |
| json=body, | |
| headers={"Authorization": f"Bearer {api_key}"}) | |
| r.raise_for_status() | |
| j = r.json() | |
| return j["choices"][0]["message"]["content"], model | |
| async def call_openai(model: str, **kw) -> Tuple[str, str]: | |
| return await _openai_compat_call("https://api.openai.com/v1", | |
| OPENAI_API_KEY, model, **kw) | |
| async def call_openrouter(model: str, **kw) -> Tuple[str, str]: | |
| return await _openai_compat_call("https://openrouter.ai/api/v1", | |
| OPENROUTER_API_KEY, model, **kw) | |
| async def call_together(model: str, **kw) -> Tuple[str, str]: | |
| return await _openai_compat_call("https://api.together.xyz/v1", | |
| TOGETHER_API_KEY, model, **kw) | |
| async def call_groq(model: str, **kw) -> Tuple[str, str]: | |
| return await _openai_compat_call("https://api.groq.com/openai/v1", | |
| GROQ_API_KEY, model, **kw) | |
| # βββββββββββββββββββββββββββ Anthropic (native) βββββββββββββββββββββββββ | |
| async def call_anthropic(model: str, *, prompt: str, system: Optional[str], | |
| max_tokens: int, temperature: float, | |
| json_mode: bool) -> Tuple[str, str]: | |
| body: Dict[str, Any] = { | |
| "model": model, | |
| "max_tokens": max_tokens, | |
| "temperature": temperature, | |
| "messages": [{"role": "user", "content": prompt}], | |
| } | |
| if system: | |
| body["system"] = system | |
| if json_mode: | |
| body["system"] = (body.get("system", "") + | |
| "\n\nRespond with a single valid JSON object only. " | |
| "No prose, no markdown fences.").strip() | |
| r = await _http().post("https://api.anthropic.com/v1/messages", | |
| json=body, | |
| headers={ | |
| "x-api-key": ANTHROPIC_API_KEY, | |
| "anthropic-version": "2023-06-01", | |
| "content-type": "application/json", | |
| }) | |
| r.raise_for_status() | |
| j = r.json() | |
| parts = j.get("content", []) | |
| text = "".join(p.get("text", "") for p in parts if p.get("type") == "text") | |
| return text, model | |
| # βββββββββββββββββββββββββββ HF Inference (free) ββββββββββββββββββββββββ | |
| async def call_hf(model: str, *, prompt: str, system: Optional[str], | |
| max_tokens: int, temperature: float, | |
| json_mode: bool) -> Tuple[str, str]: | |
| headers = {} | |
| if HF_TOKEN: | |
| headers["Authorization"] = f"Bearer {HF_TOKEN}" | |
| full = (f"<|system|>\n{system}\n<|user|>\n{prompt}\n<|assistant|>\n" | |
| if system else prompt) | |
| r = await _http().post( | |
| f"https://api-inference.huggingface.co/models/{model}", | |
| headers=headers, | |
| json={"inputs": full, | |
| "parameters": {"max_new_tokens": max_tokens, | |
| "temperature": temperature, | |
| "return_full_text": False}}) | |
| r.raise_for_status() | |
| j = r.json() | |
| if isinstance(j, list) and j and "generated_text" in j[0]: | |
| return j[0]["generated_text"], model | |
| if isinstance(j, dict) and "generated_text" in j: | |
| return j["generated_text"], model | |
| return json.dumps(j)[:4000], model | |
| # βββββββββββββββββββββββββββ PROVIDERS table ββββββββββββββββββββββββββββ | |
| PROVIDERS: Dict[str, Provider] = {} | |
| API_KEY_DEEPSEEK = os.environ.get("API_KEY_DEEPSEEK", "") | |
| async def call_deepseek(model: str, **kw) -> Tuple[str, str]: | |
| """Native DeepSeek API Client""" | |
| return await _openai_compat_call("https://api.deepseek.com/v1", | |
| API_KEY_DEEPSEEK, model, **kw) | |
| def _register_providers() -> None: | |
| PROVIDERS.clear() | |
| # 1. NATIVE DEEPSEEK V4 (Absolute Priority - Cost Score 0.01) | |
| if API_KEY_DEEPSEEK: | |
| PROVIDERS["deepseek"] = Provider( | |
| name="deepseek", enabled=True, cost_score=0.01, | |
| classes=("cheap", "balanced", "premium", "reasoning"), | |
| model_for={ | |
| "cheap": "deepseek-v4-flash", | |
| "balanced": "deepseek-v4-pro", | |
| "premium": "deepseek-v4-pro", | |
| "reasoning": "deepseek-v4-pro", | |
| }, | |
| impl=call_deepseek, | |
| ) | |
| # 2. GROQ | |
| if GROQ_API_KEY: | |
| PROVIDERS["groq"] = Provider( | |
| name="groq", enabled=True, cost_score=0.05, | |
| classes=("cheap", "balanced"), | |
| model_for={ | |
| "cheap": "llama-3.1-8b-instant", | |
| "balanced": "llama-3.3-70b-versatile", | |
| }, | |
| impl=call_groq, | |
| ) | |
| # 3. TOGETHER | |
| if TOGETHER_API_KEY: | |
| PROVIDERS["together"] = Provider( | |
| name="together", enabled=True, cost_score=0.10, | |
| classes=("cheap", "balanced", "reasoning"), | |
| model_for={ | |
| "cheap": "meta-llama/Llama-3.1-8B-Instruct-Turbo", | |
| "balanced": "meta-llama/Llama-3.3-70B-Instruct-Turbo", | |
| "reasoning": "Qwen/Qwen2.5-72B-Instruct-Turbo", | |
| }, | |
| impl=call_together, | |
| ) | |
| # 4. OPENROUTER (With Free Vision Added) | |
| if OPENROUTER_API_KEY: | |
| PROVIDERS["openrouter"] = Provider( | |
| name="openrouter", enabled=True, cost_score=0.20, | |
| classes=("cheap", "balanced", "premium", "reasoning", "vision"), | |
| model_for={ | |
| "cheap": "meta-llama/llama-3.3-70b-instruct:free", | |
| "balanced": "anthropic/claude-3.5-haiku", | |
| "premium": "anthropic/claude-sonnet-4.5", | |
| "reasoning": "openai/o4-mini", | |
| "vision": "qwen/qwen2.5-vl-72b-instruct:free", | |
| }, | |
| impl=call_openrouter, | |
| ) | |
| # 5. OPENAI | |
| if OPENAI_API_KEY: | |
| PROVIDERS["openai"] = Provider( | |
| name="openai", enabled=True, cost_score=0.50, | |
| classes=("balanced", "premium", "reasoning"), | |
| model_for={ | |
| "balanced": "gpt-4o-mini", | |
| "premium": "gpt-4o", | |
| "reasoning": "o4-mini", | |
| }, | |
| impl=call_openai, | |
| ) | |
| # 6. ANTHROPIC | |
| if ANTHROPIC_API_KEY: | |
| PROVIDERS["anthropic"] = Provider( | |
| name="anthropic", enabled=True, cost_score=0.55, | |
| classes=("balanced", "premium", "reasoning"), | |
| model_for={ | |
| "balanced": "claude-haiku-4-5-20251001", | |
| "premium": "claude-sonnet-4-6", | |
| "reasoning": "claude-opus-4-6", | |
| }, | |
| impl=call_anthropic, | |
| ) | |
| # 7. HF INFERENCE (100% Free Fallback) | |
| PROVIDERS["hf"] = Provider( | |
| name="hf", enabled=True, cost_score=0.99, | |
| classes=("cheap", "balanced", "premium", "reasoning"), | |
| model_for={ | |
| "cheap": "mistralai/Mistral-7B-Instruct-v0.3", | |
| "balanced": "meta-llama/Meta-Llama-3-8B-Instruct", | |
| "premium": "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO", | |
| "reasoning": "Qwen/Qwen2.5-7B-Instruct", | |
| }, | |
| impl=call_hf, | |
| ) | |
| def _route(model_class: str, *, explicit_model: Optional[str] = None | |
| ) -> List[Tuple[Provider, str]]: | |
| """Return [(provider, model_to_use)] sorted by cost_score asc.""" | |
| # ββ OMEGA FIX: ANNIHILATE HARDCODED MODELS ββ | |
| # Forge aggressively requests paid models like Claude explicitly. | |
| # We intercept and destroy those explicit requests so Forge is FORCED | |
| # to fall into our cost-ascending DeepSeek / Free-Tier waterfall. | |
| explicit_model = None | |
| cands = [p for p in PROVIDERS.values() if p.enabled] | |
| out = [] | |
| # Map the requested class (e.g. "reasoning") to our configured waterfall models | |
| for p in cands: | |
| if model_class in p.classes: | |
| model = p.model_for.get(model_class) | |
| if model: | |
| out.append((p, model)) | |
| # If no class matches perfectly, aggressively fall back to ANY available model | |
| if not out: | |
| for p in cands: | |
| for cls in ("balanced", "premium", "reasoning", "cheap"): | |
| if cls in p.model_for: | |
| out.append((p, p.model_for[cls])) | |
| break | |
| # Sort strictly by the cost scores we assigned (OpenRouter/DeepSeek first) | |
| out.sort(key=lambda t: t[0].cost_score) | |
| return out | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # /radar β receipts + broadcast | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ModelCallReceipt: | |
| receipt_id: str | |
| request_id: str | |
| provider: str | |
| model: str | |
| model_class: str | |
| cost_score: float | |
| latency_ms: float | |
| ok: bool | |
| error: Optional[str] | |
| intent: Optional[str] | |
| tags: List[str] | |
| ts: float = field(default_factory=time.time) | |
| def to_event(self) -> Dict[str, Any]: | |
| return {"type": "model_call", **self.__dict__} | |
| class RadarHub: | |
| def __init__(self) -> None: | |
| self.clients: List[WebSocket] = [] | |
| self.queue: asyncio.Queue = asyncio.Queue(maxsize=RADAR_QUEUE_MAX) | |
| self.receipts: Deque[ModelCallReceipt] = deque(maxlen=RECEIPT_RING) | |
| self._loop_task: Optional[asyncio.Task] = None | |
| async def start(self) -> None: | |
| if self._loop_task is None or self._loop_task.done(): | |
| self._loop_task = asyncio.create_task(self._loop()) | |
| async def _loop(self) -> None: | |
| while True: | |
| ev = await self.queue.get() | |
| data = json.dumps(ev, default=str) | |
| dead: List[WebSocket] = [] | |
| for ws in self.clients: | |
| try: await ws.send_text(data) | |
| except Exception: dead.append(ws) | |
| for ws in dead: | |
| try: self.clients.remove(ws) | |
| except ValueError: pass | |
| async def emit(self, ev: Dict[str, Any]) -> None: | |
| try: self.queue.put_nowait(ev) | |
| except asyncio.QueueFull: | |
| try: self.queue.get_nowait() | |
| except Exception: pass | |
| try: self.queue.put_nowait(ev) | |
| except Exception: pass | |
| async def attach(self, ws: WebSocket) -> None: | |
| await ws.accept() | |
| self.clients.append(ws) | |
| for r in list(self.receipts)[-32:]: | |
| try: await ws.send_text(json.dumps(r.to_event(), default=str)) | |
| except Exception: pass | |
| def detach(self, ws: WebSocket) -> None: | |
| try: self.clients.remove(ws) | |
| except ValueError: pass | |
| def remember_receipt(self, r: ModelCallReceipt) -> None: | |
| self.receipts.append(r) | |
| radar = RadarHub() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # EMBEDDINGS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def embed_text(text: str) -> List[float]: | |
| """HF inference if HF_TOKEN, deterministic SHA-512 hash fallback.""" | |
| if HF_TOKEN and EMBED_ENDPOINT: | |
| try: | |
| r = await _http().post( | |
| EMBED_ENDPOINT, | |
| headers={"Authorization": f"Bearer {HF_TOKEN}"}, | |
| json={"inputs": text}) | |
| if r.status_code == 200: | |
| j = r.json() | |
| if isinstance(j, list) and j and isinstance(j[0], (int, float)): | |
| return [float(x) for x in j][:QDRANT_VECTOR_SIZE] | |
| if isinstance(j, list) and j and isinstance(j[0], list): | |
| return [float(x) for x in j[0]][:QDRANT_VECTOR_SIZE] | |
| except Exception as e: | |
| log.debug("embed.hf.fail err=%s", e) | |
| h = hashlib.sha512(text.encode("utf-8")).digest() | |
| vec: List[float] = [] | |
| for i in range(QDRANT_VECTOR_SIZE): | |
| b = h[i % len(h)] | |
| vec.append(((b / 255.0) * 2.0) - 1.0) | |
| n = math.sqrt(sum(v * v for v in vec)) or 1.0 | |
| return [v / n for v in vec] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MEMORY β Qdrant + fallback | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class MemoryStore: | |
| def __init__(self) -> None: | |
| self.url = QDRANT_URL.rstrip("/") if QDRANT_URL else "" | |
| self.headers = {"api-key": QDRANT_API_KEY} if QDRANT_API_KEY else {} | |
| self.local: Dict[str, Dict[str, Any]] = {} | |
| self._collection_ready = False | |
| async def init(self) -> None: | |
| if not self.url: | |
| log.warning("memory.no_qdrant β using in-process store") | |
| return | |
| try: | |
| r = await _http().get( | |
| f"{self.url}/collections/{QDRANT_COLLECTION}", | |
| headers=self.headers) | |
| if r.status_code == 404: | |
| await _http().put( | |
| f"{self.url}/collections/{QDRANT_COLLECTION}", | |
| headers=self.headers, | |
| json={"vectors": {"size": QDRANT_VECTOR_SIZE, | |
| "distance": "Cosine"}}) | |
| self._collection_ready = True | |
| log.info("memory.qdrant.ready collection=%s", QDRANT_COLLECTION) | |
| except Exception as e: | |
| log.warning("memory.qdrant.init.fail err=%s β fallback", e) | |
| def _point_id(ns: str, key: str) -> int: | |
| return abs(int(hashlib.sha1(f"{ns}:{key}".encode()).hexdigest()[:15], 16)) | |
| async def upsert(self, key: str, text: str, meta: Dict[str, Any], | |
| namespace: str) -> Dict[str, Any]: | |
| vec = await embed_text(text) | |
| payload = {**meta, "key": key, "text": text, "ns": namespace, | |
| "ts": time.time()} | |
| pid = self._point_id(namespace, key) | |
| if self._collection_ready: | |
| try: | |
| r = await _http().put( | |
| f"{self.url}/collections/{QDRANT_COLLECTION}/points", | |
| headers=self.headers, | |
| json={"points": [{"id": pid, "vector": vec, "payload": payload}]}) | |
| r.raise_for_status() | |
| return {"ok": True, "id": str(pid), "store": "qdrant"} | |
| except Exception as e: | |
| log.warning("memory.upsert.qdrant.fail key=%s err=%s", key, e) | |
| self.local[f"{namespace}:{key}"] = {"id": pid, "vector": vec, "payload": payload} | |
| return {"ok": True, "id": str(pid), "store": "local"} | |
| async def search(self, *, vector: Optional[List[float]] = None, | |
| query: Optional[str] = None, | |
| top_k: int = 5, | |
| namespace: str = "default", | |
| filters: Optional[Dict[str, Any]] = None | |
| ) -> List[Dict[str, Any]]: | |
| if vector is None: | |
| if not query: | |
| return [] | |
| vector = await embed_text(query) | |
| flt: Dict[str, Any] = {"must": [{"key": "ns", "match": {"value": namespace}}]} | |
| for k, v in (filters or {}).items(): | |
| flt["must"].append({"key": k, "match": {"value": v}}) | |
| if self._collection_ready: | |
| try: | |
| r = await _http().post( | |
| f"{self.url}/collections/{QDRANT_COLLECTION}/points/search", | |
| headers=self.headers, | |
| json={"vector": vector, "limit": top_k, | |
| "filter": flt, "with_payload": True}) | |
| r.raise_for_status() | |
| hits = r.json().get("result", []) | |
| return [{"id": str(h.get("id", "")), | |
| "score": float(h.get("score", 0.0)), | |
| "text": (h.get("payload") or {}).get("text", ""), | |
| "meta": {k: v for k, v in (h.get("payload") or {}).items() | |
| if k not in ("text",)}} | |
| for h in hits] | |
| except Exception as e: | |
| log.warning("memory.search.qdrant.fail err=%s", e) | |
| # local cosine | |
| def cosine(a: List[float], b: List[float]) -> float: | |
| return sum(x * y for x, y in zip(a, b)) | |
| scored = [] | |
| for k, p in self.local.items(): | |
| if not k.startswith(f"{namespace}:"): continue | |
| payload = p["payload"] | |
| if filters and not all(payload.get(fk) == fv | |
| for fk, fv in (filters or {}).items()): | |
| continue | |
| scored.append((cosine(vector, p["vector"]), p)) | |
| scored.sort(key=lambda t: -t[0]) | |
| return [{"id": str(p["id"]), | |
| "score": float(s), | |
| "text": p["payload"].get("text", ""), | |
| "meta": {k: v for k, v in p["payload"].items() | |
| if k not in ("text",)}} | |
| for s, p in scored[:top_k]] | |
| memory = MemoryStore() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # /llm β router | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def _provider_call(p: Provider, model: str, req: LLMRequest) -> Tuple[str, str]: | |
| return await p.impl(model, | |
| prompt=req.prompt, | |
| system=req.system, | |
| max_tokens=req.max_tokens, | |
| temperature=req.temperature, | |
| json_mode=req.json_mode) | |
| async def llm(req: LLMRequest) -> LLMResponse: | |
| rid = req.request_id or uuid.uuid4().hex | |
| cands = _route(req.model_class, explicit_model=req.model) | |
| if not cands: | |
| return LLMResponse(ok=False, request_id=rid, | |
| error=f"no provider for class={req.model_class} model={req.model}", | |
| receipt_id=uuid.uuid4().hex) | |
| fallbacks: List[str] = [] | |
| last_err: Optional[str] = None | |
| for p, model in cands: | |
| t0 = time.perf_counter() | |
| try: | |
| text, model_used = await asyncio.wait_for( | |
| _provider_call(p, model, req), timeout=REQUEST_TIMEOUT) | |
| ms = (time.perf_counter() - t0) * 1000.0 | |
| r = ModelCallReceipt( | |
| receipt_id=uuid.uuid4().hex, request_id=rid, | |
| provider=p.name, model=model_used, | |
| model_class=req.model_class, cost_score=p.cost_score, | |
| latency_ms=ms, ok=True, error=None, | |
| intent=req.intent, tags=req.tags) | |
| radar.remember_receipt(r) | |
| await radar.emit(r.to_event()) | |
| return LLMResponse( | |
| ok=True, text=text, provider=p.name, model=model_used, | |
| cost_score=p.cost_score, latency_ms=ms, | |
| request_id=rid, receipt_id=r.receipt_id, | |
| fallbacks=fallbacks) | |
| except Exception as e: | |
| ms = (time.perf_counter() - t0) * 1000.0 | |
| err = f"{type(e).__name__}: {str(e)[:200]}" | |
| log.warning("llm.fail provider=%s model=%s err=%s", p.name, model, err) | |
| r = ModelCallReceipt( | |
| receipt_id=uuid.uuid4().hex, request_id=rid, | |
| provider=p.name, model=model, | |
| model_class=req.model_class, cost_score=p.cost_score, | |
| latency_ms=ms, ok=False, error=err, | |
| intent=req.intent, tags=req.tags) | |
| radar.remember_receipt(r) | |
| await radar.emit(r.to_event()) | |
| fallbacks.append(p.name) | |
| last_err = err | |
| continue | |
| return LLMResponse(ok=False, request_id=rid, | |
| error=last_err or "all providers exhausted", | |
| receipt_id=uuid.uuid4().hex, | |
| fallbacks=fallbacks) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # /score β Chain-of-Thought scoring | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _SCORE_SYSTEM = """You are OMNI Cortex β a rigorous evaluator. | |
| You will receive: | |
| TEXT: a passage to evaluate | |
| DIMENSIONS: a list of strings naming dimensions to score in [0.0, 1.0] | |
| You MUST output a SINGLE valid JSON object with EXACTLY these keys: | |
| "_rationale": str β your step-by-step deduction (REQUIRED, FIRST KEY). | |
| For each dimension, state what evidence in TEXT | |
| supports your score and why competing scores are | |
| less defensible. Min 3 sentences per dimension. | |
| <dim_1>: float β score in [0.0, 1.0], 3 decimal places. | |
| <dim_2>: float β score in [0.0, 1.0], 3 decimal places. | |
| β¦ | |
| Hard rules: | |
| - The "_rationale" key MUST appear FIRST in the object. | |
| - The "_rationale" reasoning MUST come BEFORE you commit to numeric scores. | |
| Reason FIRST, score AFTER. Do NOT guess and rationalize. | |
| - Output ONLY the JSON object. No markdown fences, no prose outside JSON. | |
| - Every requested dimension MUST be present as a numeric key. | |
| - Unknown dimensions: still score, but explain low confidence in _rationale. | |
| - 0.0 = fully absent / fully negative on dimension. | |
| 1.0 = fully present / fully positive on dimension. | |
| 0.5 = neutral / mixed evidence.""" | |
| def _parse_json_safely(text: str) -> Optional[Any]: | |
| text = text.strip() | |
| # strip code fence | |
| if text.startswith("```"): | |
| i = text.find("\n") | |
| if i > 0: text = text[i + 1:] | |
| if text.endswith("```"): text = text[:-3] | |
| text = text.strip() | |
| try: | |
| return json.loads(text) | |
| except Exception: | |
| pass | |
| for opener, closer in (("{", "}"), ("[", "]")): | |
| i = text.find(opener) | |
| if i < 0: continue | |
| depth = 0 | |
| for j in range(i, len(text)): | |
| if text[j] == opener: depth += 1 | |
| elif text[j] == closer: | |
| depth -= 1 | |
| if depth == 0: | |
| try: return json.loads(text[i:j + 1]) | |
| except Exception: break | |
| return None | |
| async def score_text(req: ScoreRequest) -> Dict[str, Any]: | |
| if not req.dimensions: | |
| return {"_rationale": "no dimensions supplied"} | |
| user = (f"TEXT:\n{req.text}\n\n" | |
| f"DIMENSIONS: {json.dumps(req.dimensions)}\n\n" | |
| f"Reason first in \"_rationale\", then emit numeric scores.") | |
| res = await llm(LLMRequest( | |
| prompt=user, system=_SCORE_SYSTEM, | |
| model_class=req.model_class, json_mode=True, | |
| temperature=0.0, max_tokens=2048, | |
| intent="cortex.score", | |
| tags=["score"] + req.dimensions, | |
| )) | |
| if not res.ok: | |
| return {"_rationale": f"llm_failed: {res.error}", | |
| **{d: 0.0 for d in req.dimensions}} | |
| parsed = _parse_json_safely(res.text) | |
| if not isinstance(parsed, dict): | |
| return {"_rationale": f"non-json output: {res.text[:300]}", | |
| **{d: 0.0 for d in req.dimensions}} | |
| out: Dict[str, Any] = {} | |
| # _rationale must be first | |
| rationale = parsed.get("_rationale", "") | |
| if not isinstance(rationale, str) or len(rationale.strip()) < 20: | |
| rationale = (f"WARNING: model produced rationale shorter than 20 chars. " | |
| f"raw='{str(parsed.get('_rationale', ''))[:200]}'") | |
| out["_rationale"] = rationale | |
| for d in req.dimensions: | |
| v = parsed.get(d, 0.0) | |
| try: | |
| f = float(v) | |
| out[d] = max(0.0, min(1.0, f)) | |
| except Exception: | |
| out[d] = 0.0 | |
| out["_rationale"] += f"\n[coerced {d!r} to 0.0 β non-numeric]" | |
| out["_receipt_id"] = res.receipt_id | |
| out["_provider"] = res.provider | |
| out["_model"] = res.model | |
| return out | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FASTAPI APP | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app = FastAPI( | |
| title="OMNI Cortex β Cybernetic God Edition", | |
| version="5.1.0", | |
| description="Driver-aligned: /llm /embed /similar /score /memory/* /healthz", | |
| ) | |
| def require_token(authorization: Optional[str] = Header(None), | |
| x_cortex_token: Optional[str] = Header(None)) -> None: | |
| if not CORTEX_API_KEY: | |
| return | |
| bearer = "" | |
| if authorization and authorization.lower().startswith("bearer "): | |
| bearer = authorization[7:].strip() | |
| if bearer == CORTEX_API_KEY: return | |
| if x_cortex_token == CORTEX_API_KEY: return | |
| raise HTTPException(401, "bad bearer token") | |
| async def _startup() -> None: | |
| _register_providers() | |
| await memory.init() | |
| await radar.start() | |
| log.info("cortex.startup providers=%s qdrant=%s", | |
| list(PROVIDERS.keys()), bool(memory._collection_ready)) | |
| async def _shutdown() -> None: | |
| global _HTTP | |
| if _HTTP is not None: | |
| await _HTTP.aclose() | |
| _HTTP = None | |
| async def root() -> Dict[str, Any]: | |
| """Root sinkhole β proof-of-life for OMNI's Cybernetic God Cortex.""" | |
| return {"status": "OMNI Cortex Online", "state": "Absolute Autonomy"} | |
| async def healthz() -> Dict[str, Any]: | |
| return { | |
| "ok": True, | |
| "edition": "cybernetic-god", | |
| "version": "5.1.0", | |
| "providers": [p.name for p in PROVIDERS.values() if p.enabled], | |
| "memory_store": "qdrant" if memory._collection_ready else "local", | |
| "memory_local": len(memory.local), | |
| "radar_clients": len(radar.clients), | |
| "receipts": len(radar.receipts), | |
| "ts": time.time(), | |
| } | |
| # ββ public driver-aligned routes ββββββββββββββββββββββββββββββββββββββββ | |
| async def http_llm(req: LLMRequest) -> Dict[str, Any]: | |
| res = await llm(req) | |
| return res.dict() | |
| async def http_embed(req: EmbedRequest) -> Dict[str, Any]: | |
| vec = await embed_text(req.text) | |
| return {"vector": vec, "dim": len(vec)} | |
| async def http_similar(req: SimilarRequest) -> Dict[str, Any]: | |
| if req.vector is None and not req.text: | |
| raise HTTPException(400, "supply text or vector") | |
| hits = await memory.search(vector=req.vector, query=req.text, | |
| top_k=req.top_k, namespace=req.namespace, | |
| filters=req.filters) | |
| return {"hits": hits} | |
| async def http_search(req: SimilarRequest) -> Dict[str, Any]: | |
| """Akashic Index alias of /similar β used by Forge for retrieval-augmented | |
| template injection before any LLM synthesis.""" | |
| return await http_similar(req) | |
| async def http_score(req: ScoreRequest) -> Dict[str, Any]: | |
| return await score_text(req) | |
| async def http_memory_store(req: MemoryStoreRequest) -> Dict[str, Any]: | |
| res = await memory.upsert(req.key, req.text, req.meta, req.namespace) | |
| return res | |
| async def http_memory_recall(req: MemoryRecallRequest) -> Dict[str, Any]: | |
| hits = await memory.search(query=req.query, top_k=req.top_k, | |
| namespace=req.namespace, filters=req.filters) | |
| return {"hits": hits} | |
| # ββ bonus routes (radar) ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def http_receipts(limit: int = Query(64, ge=1, le=RECEIPT_RING) | |
| ) -> Dict[str, Any]: | |
| items = list(radar.receipts)[-limit:] | |
| return {"ok": True, "receipts": [r.to_event() for r in items]} | |
| async def ws_radar(ws: WebSocket) -> None: | |
| token = ws.query_params.get("token") | |
| if CORTEX_API_KEY and token != CORTEX_API_KEY: | |
| await ws.close(code=4401) | |
| return | |
| await radar.attach(ws) | |
| try: | |
| while True: | |
| await ws.receive_text() | |
| except WebSocketDisconnect: | |
| pass | |
| finally: | |
| radar.detach(ws) | |
| async def http_health_alias() -> Dict[str, Any]: | |
| return await healthz() | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=CORTEX_PORT) | |