bosaj commited on
Commit
5e5b4e1
·
unverified ·
1 Parent(s): 2ddff3f

feat: add OpenAI-compatible /v1/chat/completions endpoint

Browse files
Files changed (1) hide show
  1. app.py +46 -0
app.py CHANGED
@@ -188,6 +188,52 @@ async def chat_api(request: Request):
188
  except Exception as e:
189
  return JSONResponse(status_code=500, content={"error": str(e), "status": "error"})
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  @app.get("/api/health")
192
  async def health_check():
193
  return JSONResponse(content={
 
188
  except Exception as e:
189
  return JSONResponse(status_code=500, content={"error": str(e), "status": "error"})
190
 
191
+ @app.post("/v1/chat/completions")
192
+ async def chat_completions(request: Request):
193
+ import time
194
+ try:
195
+ body = await request.json()
196
+ messages = body.get("messages", [])
197
+ model = body.get("model", PRIMARY_MODEL)
198
+ max_tokens = int(body.get("max_tokens", 512))
199
+ temperature = float(body.get("temperature", 0.7))
200
+
201
+ user_msg = ""
202
+ history = []
203
+ for m in messages:
204
+ if m.get("role") == "user":
205
+ user_msg = m.get("content", "")
206
+ elif m.get("role") == "assistant":
207
+ history.append((user_msg, m.get("content", "")))
208
+
209
+ full_text = ""
210
+ for chunk in predict(user_msg, history, model, max_tokens, temperature):
211
+ full_text = chunk
212
+
213
+ return JSONResponse(content={
214
+ "id": f"chatcmpl-{int(time.time())}",
215
+ "object": "chat.completion",
216
+ "created": int(time.time()),
217
+ "model": model,
218
+ "choices": [
219
+ {
220
+ "index": 0,
221
+ "message": {
222
+ "role": "assistant",
223
+ "content": full_text
224
+ },
225
+ "finish_reason": "stop"
226
+ }
227
+ ],
228
+ "usage": {
229
+ "prompt_tokens": len(user_msg.split()),
230
+ "completion_tokens": len(full_text.split()),
231
+ "total_tokens": len(user_msg.split()) + len(full_text.split())
232
+ }
233
+ })
234
+ except Exception as e:
235
+ return JSONResponse(status_code=500, content={"error": str(e)})
236
+
237
  @app.get("/api/health")
238
  async def health_check():
239
  return JSONResponse(content={