File size: 1,855 Bytes
db4e4bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CAD_LLM1 — HF Space Proxy: humut/CAD_LLM1
General mechanical parts + mining equipment"""
import os, json, httpx
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

app = FastAPI(title="CAD_LLM1")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

HF_SPACE = os.getenv("HF_SPACE", "humut/CAD_LLM1")
HF_TOKEN = os.getenv("HF_TOKEN", "")
MODEL_NAME = os.getenv("MODEL_NAME", "cad_llm1")

with open("config.json") as f:
    CONFIG = json.load(f)


class ChatRequest(BaseModel):
    message: str
    history: list[dict] = []


@app.get("/health")
async def health():
    return {"status": "ok", "model": MODEL_NAME, "hf_space": HF_SPACE}


@app.get("/config")
async def config():
    return CONFIG


@app.post("/chat")
async def chat(req: ChatRequest):
    if not HF_TOKEN:
        return {"response": f"[{MODEL_NAME}] No HF_TOKEN configured. Prompt: {req.message}", "dsl": ""}
    try:
        async with httpx.AsyncClient(timeout=120) as client:
            resp = await client.post(
                f"https://api-inference.huggingface.co/models/{HF_SPACE}",
                headers={"Authorization": f"Bearer {HF_TOKEN}"},
                json={"inputs": req.message, "parameters": {"max_new_tokens": 512, "temperature": 0.7}}
            )
            if resp.status_code == 200:
                data = resp.json()
                raw = data[0].get("generated_text", "") if isinstance(data, list) else str(data)
                return {"response": raw, "model": MODEL_NAME}
    except Exception as e:
        return {"response": f"[{MODEL_NAME}] Error: {str(e)}", "dsl": ""}
    return {"response": f"[{MODEL_NAME}] No response from HF", "dsl": ""}


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