Hivra commited on
Commit
6d886e2
·
verified ·
1 Parent(s): 6ab9ff8

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +92 -33
app/main.py CHANGED
@@ -1,33 +1,92 @@
1
- from fastapi import FastAPI
2
- from pydantic import BaseModel
3
- from gradio_client import Client
4
-
5
- # Configure your Gradio Space ID and default endpoint
6
- SPACE_ID = "prithivMLmods/SAMBANOVA"
7
- DEFAULT_API = "/chat"
8
-
9
- client = Client(SPACE_ID)
10
-
11
- def chat_with_gradio(message: str, api_name: str = DEFAULT_API):
12
- """
13
- Send a chat message to the Gradio API and return the response.
14
- """
15
- try:
16
- return client.predict(message=message, api_name=api_name)
17
- except Exception as e:
18
- return {"error": str(e)}
19
-
20
- app = FastAPI()
21
-
22
- class ChatRequest(BaseModel):
23
- message: str
24
- api_name: str = DEFAULT_API
25
-
26
- @app.post("/chat")
27
- async def chat_endpoint(req: ChatRequest):
28
- return {"reply": chat_with_gradio(req.message, req.api_name)}
29
-
30
- if __name__ == "__main__":
31
- import uvicorn
32
- print(f"Starting server on http://0.0.0.0:7860 using {SPACE_ID}{DEFAULT_API}")
33
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Request
2
+ from fastapi.responses import StreamingResponse, JSONResponse
3
+ from pydantic import BaseModel
4
+ from gradio_client import Client
5
+ import time
6
+ import json
7
+
8
+ # Configure your Gradio Space ID and default endpoint
9
+ SPACE_ID = "prithivMLmods/SAMBANOVA"
10
+ DEFAULT_API = "/chat"
11
+
12
+ client = Client(SPACE_ID)
13
+
14
+
15
+ def chat_with_gradio(message: str, api_name: str = DEFAULT_API):
16
+ """
17
+ Send a chat message to the Gradio API and return the response.
18
+ """
19
+ try:
20
+ return client.predict(message=message, api_name=api_name)
21
+ except Exception as e:
22
+ raise RuntimeError(f"Gradio API error: {e}")
23
+
24
+
25
+ class ChatRequest(BaseModel):
26
+ message: str
27
+ api_name: str = DEFAULT_API
28
+
29
+ app = FastAPI()
30
+
31
+ @app.post("/chat")
32
+ async def chat_endpoint(req: ChatRequest):
33
+ """Forward chat requests to the Gradio API."""
34
+ try:
35
+ reply = chat_with_gradio(req.message, req.api_name)
36
+ return {"reply": reply}
37
+ except RuntimeError as e:
38
+ raise HTTPException(status_code=502, detail=str(e))
39
+
40
+ @app.post("/v1/chat/completions")
41
+ async def openai_chat_completions(request: Request):
42
+ """
43
+ OpenAI-compatible chat completions endpoint that forwards to Gradio.
44
+ Supports both streaming and non-streaming.
45
+ """
46
+ body = await request.json()
47
+ messages = body.get("messages")
48
+ model = body.get("model")
49
+ stream = body.get("stream", False)
50
+
51
+ if not messages or not isinstance(messages, list):
52
+ raise HTTPException(status_code=400, detail="`messages` must be a list of dicts.")
53
+
54
+ user_msg = messages[-1].get("content", "")
55
+
56
+ # Call Gradio
57
+ try:
58
+ reply = chat_with_gradio(user_msg, DEFAULT_API)
59
+ except RuntimeError as e:
60
+ raise HTTPException(status_code=502, detail=str(e))
61
+
62
+ # Build usage (simple token count by words)
63
+ prompt_tokens = sum(len(m.get("content", "").split()) for m in messages)
64
+ completion_tokens = len(str(reply).split())
65
+ usage = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": prompt_tokens + completion_tokens}
66
+
67
+ if stream:
68
+ # Stream word by word as OpenAI SSE
69
+ def event_generator():
70
+ for word in str(reply).split():
71
+ chunk = {"choices": [{"delta": {"content": word+" "}, "index": 0, "finish_reason": None}]}
72
+ yield f"data: {json.dumps(chunk)}\n\n"
73
+ time.sleep(0.05)
74
+ # send done
75
+ done = {"choices": [{"delta": {}, "index": 0, "finish_reason": "stop"}]}
76
+ yield f"data: {json.dumps(done)}\n\n"
77
+ return StreamingResponse(event_generator(), media_type="text/event-stream")
78
+ else:
79
+ response = {
80
+ "id": f"chatcmpl-{int(time.time())}",
81
+ "object": "chat.completion",
82
+ "created": int(time.time()),
83
+ "model": model,
84
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}],
85
+ "usage": usage
86
+ }
87
+ return JSONResponse(response)
88
+
89
+ if __name__ == "__main__":
90
+ import uvicorn
91
+ print(f"Starting server on http://0.0.0.0:7860 using {SPACE_ID}{DEFAULT_API} and OpenAI-compatible endpoint /v1/chat/completions")
92
+ uvicorn.run(app, host="0.0.0.0", port=7860)