Spaces:
Running

mgokg commited on
Commit
ee9e48f
·
verified ·
1 Parent(s): 60a7d1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -2
app.py CHANGED
@@ -313,7 +313,53 @@ def generate_with_history(input_text, history):
313
  return f"Error: {str(e)}", history
314
 
315
 
316
- # Gradio Blocks Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  with gr.Blocks() as demo:
318
  history_state = gr.State([])
319
 
@@ -330,5 +376,10 @@ with gr.Blocks() as demo:
330
  )
331
 
332
 
 
 
 
 
 
333
  if __name__ == "__main__":
334
- demo.launch()
 
313
  return f"Error: {str(e)}", history
314
 
315
 
316
+ import uvicorn
317
+ from fastapi import FastAPI, HTTPException
318
+ from pydantic import BaseModel, Field
319
+
320
+
321
+ # ---------- FastAPI ----------
322
+ api = FastAPI(title="LLM API")
323
+
324
+
325
+ class Message(BaseModel):
326
+ role: str
327
+ content: str
328
+
329
+
330
+ class ChatRequest(BaseModel):
331
+ message: str
332
+ history: list[Message] = Field(default_factory=list)
333
+
334
+
335
+ class ChatResponse(BaseModel):
336
+ answer: str
337
+ history: list[Message]
338
+
339
+
340
+ @api.post("/api/chat", response_model=ChatResponse)
341
+ def chat(req: ChatRequest):
342
+ # Plain `def` -> FastAPI runs it in a threadpool, so the blocking
343
+ # `requests` call doesn't block the event loop.
344
+ try:
345
+ answer, new_history = ask_openrouter(
346
+ req.message,
347
+ [m.model_dump() for m in req.history],
348
+ )
349
+ except gr.Error as e:
350
+ raise HTTPException(
351
+ status_code=502,
352
+ detail=getattr(e, "message", str(e)),
353
+ )
354
+ return ChatResponse(answer=answer, history=new_history)
355
+
356
+
357
+ @api.get("/health")
358
+ def health():
359
+ return {"status": "ok"}
360
+
361
+
362
+ # ---------- Gradio Blocks Interface ----------
363
  with gr.Blocks() as demo:
364
  history_state = gr.State([])
365
 
 
376
  )
377
 
378
 
379
+ # Mount Gradio into FastAPI. Routes defined on `api` above take
380
+ # precedence over the mount at "/".
381
+ app = gr.mount_gradio_app(api, demo, path="/")
382
+
383
+
384
  if __name__ == "__main__":
385
+ uvicorn.run(app, host="0.0.0.0", port=7860)