ryan33121 commited on
Commit
188bb6e
·
verified ·
1 Parent(s): ca9af7b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -19
app.py CHANGED
@@ -1,14 +1,15 @@
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
 
 
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
@@ -16,14 +17,15 @@ app.add_middleware(
16
  allow_headers=["*"],
17
  )
18
 
19
- # 1. Load model with minimal resource allocation
20
- print("Loading model...")
 
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
 
26
- # Crucial: n_gpu_layers=0 forces CPU, n_threads=1 saves RAM
27
  llm = Llama(
28
  model_path=MODEL_PATH,
29
  n_ctx=512,
@@ -32,6 +34,7 @@ llm = Llama(
32
  )
33
  print("Model loaded successfully.")
34
 
 
35
  class ChatMessage(BaseModel):
36
  role: str
37
  content: str
@@ -39,29 +42,28 @@ class ChatMessage(BaseModel):
39
  class ChatRequest(BaseModel):
40
  messages: List[ChatMessage]
41
 
 
42
  @app.get("/")
43
  def read_root():
44
- return {"message": "Server is up!"}
45
 
46
  @app.post("/v1/chat/completions")
47
  async def chat_completion(request: ChatRequest):
48
- print("Received chat request...") # Check logs for this
49
  try:
 
50
  history = [{"role": msg.role, "content": msg.content} for msg in request.messages]
51
 
52
- def stream_generator():
53
- print("Starting inference...") # Check logs for this
54
- response_stream = llm.create_chat_completion(
55
- messages=history,
56
- temperature=0.2,
57
- stream=True
58
- )
59
- for chunk in response_stream:
60
- yield f"data: {json.dumps(chunk)}\n\n"
61
- yield "data: [DONE]\n\n"
62
- print("Inference finished.") # Check logs for this
63
-
64
- return StreamingResponse(stream_generator(), media_type="text/event-stream")
65
  except Exception as e:
66
  print(f"ERROR: {e}")
67
  raise HTTPException(status_code=500, detail=str(e))
 
1
  import json
2
  from fastapi import FastAPI, HTTPException
 
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from llama_cpp import Llama
5
  from huggingface_hub import hf_hub_download
6
  from pydantic import BaseModel
7
  from typing import List
8
 
9
+ # Initialize FastAPI
10
  app = FastAPI()
11
 
12
+ # Enable CORS for frontend communication
13
  app.add_middleware(
14
  CORSMiddleware,
15
  allow_origins=["*"],
 
17
  allow_headers=["*"],
18
  )
19
 
20
+ # Load the model
21
+ # We use n_ctx=512 to keep memory footprint low
22
+ print("Loading model... please wait.")
23
  MODEL_PATH = hf_hub_download(
24
  repo_id="Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
25
  filename="qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
26
  )
27
 
28
+ # Force CPU mode (n_gpu_layers=0) for maximum stability on Free Tier
29
  llm = Llama(
30
  model_path=MODEL_PATH,
31
  n_ctx=512,
 
34
  )
35
  print("Model loaded successfully.")
36
 
37
+ # Pydantic models for request validation
38
  class ChatMessage(BaseModel):
39
  role: str
40
  content: str
 
42
  class ChatRequest(BaseModel):
43
  messages: List[ChatMessage]
44
 
45
+ # Endpoints
46
  @app.get("/")
47
  def read_root():
48
+ return {"message": "Server is up and waiting for chat!"}
49
 
50
  @app.post("/v1/chat/completions")
51
  async def chat_completion(request: ChatRequest):
52
+ print("Received chat request...")
53
  try:
54
+ # Convert request to history format
55
  history = [{"role": msg.role, "content": msg.content} for msg in request.messages]
56
 
57
+ # Run inference with stream=False to ensure stable connection
58
+ response = llm.create_chat_completion(
59
+ messages=history,
60
+ temperature=0.2,
61
+ stream=False
62
+ )
63
+
64
+ print("Inference finished.")
65
+ return response
66
+
 
 
 
67
  except Exception as e:
68
  print(f"ERROR: {e}")
69
  raise HTTPException(status_code=500, detail=str(e))