ryan33121 commited on
Commit
16e01a9
·
verified ·
1 Parent(s): ce4e5c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -5
app.py CHANGED
@@ -1,7 +1,11 @@
1
- from fastapi import FastAPI
 
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from llama_cpp import Llama
4
  from huggingface_hub import hf_hub_download
 
 
5
 
6
  app = FastAPI()
7
 
@@ -12,19 +16,45 @@ app.add_middleware(
12
  allow_headers=["*"],
13
  )
14
 
15
- # 1. Load the model (carefully)
16
  print("Loading model... this might take a minute.")
17
  MODEL_PATH = hf_hub_download(
18
  repo_id="Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
19
  filename="qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
20
  )
 
21
  llm = Llama(model_path=MODEL_PATH, n_ctx=512)
22
  print("Model finished loading.")
23
 
 
 
 
 
 
 
 
 
 
24
  @app.get("/")
25
  def read_root():
26
  return {"message": "The server is working and the model is loaded!"}
27
 
28
- @app.get("/check-model")
29
- def check_model():
30
- return {"status": "Model is active in memory."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from fastapi import FastAPI, HTTPException
3
+ from fastapi.responses import StreamingResponse
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from llama_cpp import Llama
6
  from huggingface_hub import hf_hub_download
7
+ from pydantic import BaseModel
8
+ from typing import List
9
 
10
  app = FastAPI()
11
 
 
16
  allow_headers=["*"],
17
  )
18
 
19
+ # 1. Load the model
20
  print("Loading model... this might take a minute.")
21
  MODEL_PATH = hf_hub_download(
22
  repo_id="Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
23
  filename="qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
24
  )
25
+ # Using n_ctx=512 to keep memory usage low and stable
26
  llm = Llama(model_path=MODEL_PATH, n_ctx=512)
27
  print("Model finished loading.")
28
 
29
+ # 2. Schemas
30
+ class ChatMessage(BaseModel):
31
+ role: str
32
+ content: str
33
+
34
+ class ChatRequest(BaseModel):
35
+ messages: List[ChatMessage]
36
+
37
+ # 3. Endpoints
38
  @app.get("/")
39
  def read_root():
40
  return {"message": "The server is working and the model is loaded!"}
41
 
42
+ @app.post("/v1/chat/completions")
43
+ async def chat_completion(request: ChatRequest):
44
+ try:
45
+ # Convert request to history format
46
+ history = [{"role": msg.role, "content": msg.content} for msg in request.messages]
47
+
48
+ def stream_generator():
49
+ response_stream = llm.create_chat_completion(
50
+ messages=history,
51
+ temperature=0.2,
52
+ stream=True
53
+ )
54
+ for chunk in response_stream:
55
+ yield f"data: {json.dumps(chunk)}\n\n"
56
+ yield "data: [DONE]\n\n"
57
+
58
+ return StreamingResponse(stream_generator(), media_type="text/event-stream")
59
+ except Exception as e:
60
+ raise HTTPException(status_code=500, detail=str(e))