File size: 9,603 Bytes
2021f39 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
#!/usr/bin/env python3
"""
OpenAI-compatible gateway and route registry.
Proxies /v1/chat/completions and /v1/completions to an upstream (e.g., vLLM).
Also exposes /routes with configured external URLs for client discovery.
"""
import os
import json
from typing import Dict, Any
import requests
import yaml
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
from prometheus_client import Counter, Histogram, make_asgi_app
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
def load_routes() -> Dict[str, Any]:
path = os.getenv("EXTERNAL_ROUTES_FILE", "nova/config/external_routes.yaml")
try:
with open(path, "r", encoding="utf-8") as f:
return yaml.safe_load(f) or {}
except Exception:
# Default routes with provided URLs
return {
"services": {
"primary_api": {
"candidates": [
"https://localhost:8080",
"https://charter-enjoying-manufacturers-fifteen.trycloudflare.com",
]
},
"tensorboard": {
"candidates": [
"http://localhost:6006",
"https://heel-thumbnails-dans-liked.trycloudflare.com",
]
},
"syncthing": {
"candidates": [
"http://localhost:8384",
"https://treasure-cash-integer-mae.trycloudflare.com",
]
},
"jupyter": {
"candidates": [
"http://localhost:1111",
"https://cottage-angels-blair-greeting.trycloudflare.com",
]
},
}
}
UPSTREAM = os.getenv("UPSTREAM_OPENAI_BASE", "http://127.0.0.1:8000").rstrip("/")
GRAPHRAG_BASE = os.getenv("GRAPHRAG_BASE", "http://127.0.0.1:7012").rstrip("/")
EMBED_BASE = os.getenv("EMBED_BASE", "http://127.0.0.1:7013").rstrip("/")
PORT = int(os.getenv("PORT", "8088"))
app = FastAPI(title="Nova Gateway", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
REQUESTS = Counter("gateway_requests_total", "Gateway requests", ["route"])
LATENCY = Histogram("gateway_request_latency_seconds", "Latency", ["route"])
# Basic OTel tracer to console (can be swapped for OTLP)
resource = Resource.create({"service.name": "nova-gateway"})
provider = TracerProvider(resource=resource)
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
@app.get("/health")
def health() -> Dict[str, Any]:
REQUESTS.labels(route="health").inc()
return {"status": "ok", "upstream": UPSTREAM, "port": PORT}
@app.get("/routes")
def routes() -> Dict[str, Any]:
REQUESTS.labels(route="routes").inc()
return load_routes()
def proxy_post(path: str, payload: Dict[str, Any], headers: Dict[str, str]) -> JSONResponse:
url = f"{UPSTREAM}{path}"
try:
with tracer.start_as_current_span("proxy_post"):
resp = requests.post(url, json=payload, headers=headers, timeout=120)
content_type = resp.headers.get("content-type", "application/json")
return JSONResponse(status_code=resp.status_code, content=resp.json() if 'json' in content_type else resp.text)
except Exception as e:
return JSONResponse(status_code=502, content={"error": f"upstream error: {e}"})
@app.post("/v1/chat/completions")
async def chat_completions(req: Request) -> JSONResponse:
with LATENCY.labels(route="chat").time():
REQUESTS.labels(route="chat").inc()
payload = await req.json()
headers = dict(req.headers)
return proxy_post("/v1/chat/completions", payload, headers)
@app.post("/v1/completions")
async def completions(req: Request) -> JSONResponse:
with LATENCY.labels(route="completions").time():
REQUESTS.labels(route="completions").inc()
payload = await req.json()
headers = dict(req.headers)
return proxy_post("/v1/completions", payload, headers)
@app.post("/v1/rag/completions")
async def rag_completions(req: Request) -> JSONResponse:
"""RAG-augmented completions. Expects body with {model, prompt, rag:{...}}.
rag: {collection, query_vector, seed_ids, top_k, depth}
"""
with LATENCY.labels(route="rag_completions").time():
REQUESTS.labels(route="rag_completions").inc()
body = await req.json()
model = body.get("model")
prompt = body.get("prompt", "")
rag = body.get("rag", {})
headers = dict(req.headers)
# Optional Dragonfly/Redis cache and embedding for query_text
cache_key = None
ctx = None
try:
import hashlib, json as _json
cache_key = "rag:" + hashlib.sha256(_json.dumps(rag, sort_keys=True).encode()).hexdigest()
import redis
r = redis.from_url(os.getenv("REDIS_URL", "redis://127.0.0.1:6379/0"))
cached = r.get(cache_key)
if cached:
ctx = _json.loads(cached)
else:
# Derive query_vector if only query_text is present
qv = rag.get("query_vector")
if qv is None and rag.get("query_text"):
try:
er = requests.post(f"{EMBED_BASE}/embed", json={"text": rag.get("query_text")}, timeout=5)
qv = er.json().get("vector") if er.status_code == 200 else None
except Exception:
qv = None
gr = requests.post(f"{GRAPHRAG_BASE}/graphrag", json={
"collection": rag.get("collection", "default"),
"query_vector": qv,
"seed_ids": rag.get("seed_ids", []),
"top_k": int(rag.get("top_k", 5)),
"depth": int(rag.get("depth", 1)),
}, timeout=10)
if gr.status_code == 200:
ctx = gr.json()
r.setex(cache_key, int(os.getenv("RAG_CACHE_TTL", "60")), _json.dumps(ctx).encode())
except Exception:
# Fallback without cache
try:
qv = rag.get("query_vector")
if qv is None and rag.get("query_text"):
try:
er = requests.post(f"{EMBED_BASE}/embed", json={"text": rag.get("query_text")}, timeout=5)
qv = er.json().get("vector") if er.status_code == 200 else None
except Exception:
qv = None
gr = requests.post(f"{GRAPHRAG_BASE}/graphrag", json={
"collection": rag.get("collection", "default"),
"query_vector": qv,
"seed_ids": rag.get("seed_ids", []),
"top_k": int(rag.get("top_k", 5)),
"depth": int(rag.get("depth", 1)),
}, timeout=10)
if gr.status_code == 200:
ctx = gr.json()
except Exception:
ctx = None
context_block = f"\n\n[CONTEXT]\n{json.dumps(ctx) if ctx else 'null'}\n\n"
augmented = {"model": model, "prompt": context_block + prompt}
return proxy_post("/v1/completions", augmented, headers)
@app.post("/v1/rag/chat/completions")
async def rag_chat_completions(req: Request) -> JSONResponse:
"""RAG-augmented chat. Adds a system message with context.
Expects body with {model, messages, rag:{...}}.
"""
with LATENCY.labels(route="rag_chat").time():
REQUESTS.labels(route="rag_chat").inc()
body = await req.json()
model = body.get("model")
messages = body.get("messages", [])
rag = body.get("rag", {})
headers = dict(req.headers)
ctx = None
try:
qv = rag.get("query_vector")
if qv is None and rag.get("query_text"):
try:
er = requests.post(f"{EMBED_BASE}/embed", json={"text": rag.get("query_text")}, timeout=5)
qv = er.json().get("vector") if er.status_code == 200 else None
except Exception:
qv = None
gr = requests.post(f"{GRAPHRAG_BASE}/graphrag", json={
"collection": rag.get("collection", "default"),
"query_vector": qv,
"seed_ids": rag.get("seed_ids", []),
"top_k": int(rag.get("top_k", 5)),
"depth": int(rag.get("depth", 1)),
}, timeout=10)
if gr.status_code == 200:
ctx = gr.json()
except Exception:
ctx = None
sys_msg = {"role": "system", "content": f"Context: {json.dumps(ctx) if ctx else 'null'}"}
augmented = {"model": model, "messages": [sys_msg] + messages}
return proxy_post("/v1/chat/completions", augmented, headers)
# Prometheus metrics
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=PORT)
|