|
|
|
|
|
""" |
|
|
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: |
|
|
|
|
|
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"]) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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: |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
metrics_app = make_asgi_app() |
|
|
app.mount("/metrics", metrics_app) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
uvicorn.run(app, host="0.0.0.0", port=PORT) |
|
|
|