File size: 2,045 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
#!/usr/bin/env python3
"""
Gorilla LLM bridge: forwards requests to a configured Gorilla LLM API.
Environment:
- GORILLA_BASE: base URL of Gorilla LLM (e.g., http(s)://host:port)
- PORT: listen port (default 8089)
Endpoints:
- POST /gorilla/chat -> forwards body to {GORILLA_BASE}/v1/chat/completions
- POST /gorilla/completions -> forwards body to {GORILLA_BASE}/v1/completions
"""

import os
from typing import Dict, Any

import requests
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn

PORT = int(os.getenv("PORT", "8089"))
GORILLA_BASE = os.getenv("GORILLA_BASE", "").rstrip("/")

app = FastAPI(title="Gorilla Bridge", version="0.1.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/health")
def health() -> Dict[str, Any]:
    return {"status": "ok", "gorilla_base": GORILLA_BASE, "port": PORT}


def forward(path: str, payload: Dict[str, Any], headers: Dict[str, str]) -> JSONResponse:
    if not GORILLA_BASE:
        return JSONResponse(status_code=503, content={"error": "GORILLA_BASE not configured"})
    url = f"{GORILLA_BASE}{path}"
    try:
        resp = requests.post(url, json=payload, headers=headers, timeout=120)
        return JSONResponse(status_code=resp.status_code, content=resp.json())
    except Exception as e:
        return JSONResponse(status_code=502, content={"error": f"gorilla upstream error: {e}"})


@app.post("/gorilla/chat")
async def gorilla_chat(req: Request) -> JSONResponse:
    payload = await req.json()
    headers = dict(req.headers)
    return forward("/v1/chat/completions", payload, headers)


@app.post("/gorilla/completions")
async def gorilla_completions(req: Request) -> JSONResponse:
    payload = await req.json()
    headers = dict(req.headers)
    return forward("/v1/completions", payload, headers)


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=PORT)