ryan33121 commited on
Commit
f795cd0
·
verified ·
1 Parent(s): 551a58b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -18
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import os
 
2
  from fastapi import FastAPI, HTTPException
 
3
  from pydantic import BaseModel
4
  from typing import List, Dict
5
  from pymongo import MongoClient
@@ -9,7 +11,6 @@ from llama_cpp import Llama
9
  app = FastAPI()
10
 
11
  # --- CONFIGURATION LAYER ---
12
- # Change these two variables if you want to swap out the model engine later
13
  REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
14
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
15
  # ---------------------------
@@ -21,7 +22,6 @@ if not MONGO_URI:
21
 
22
  try:
23
  db_client = MongoClient(MONGO_URI)
24
- # This automatically sets up a database called 'ai_memory' and a collection called 'knowledge'
25
  knowledge_col = db_client["ai_memory"]["knowledge"]
26
  except Exception as e:
27
  raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
@@ -33,7 +33,6 @@ MODEL_PATH = f"./{MODEL_FILENAME}"
33
  if not os.path.exists(MODEL_PATH):
34
  print(f"Model file not found locally. Downloading {MODEL_FILENAME} from HF Hub...")
35
  try:
36
- # Pulls the raw GGUF weights directly into your working container directory
37
  MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
38
  print("Download complete successfully!")
39
  except Exception as e:
@@ -84,38 +83,45 @@ def compile_permanent_knowledge() -> str:
84
 
85
  @app.get("/")
86
  async def root_health_check():
87
- """Handles automatic framework pings from Hugging Face infrastructure."""
88
  return {"status": "healthy", "engine": "Operational", "target": MODEL_FILENAME}
89
 
90
 
91
  @app.post("/v1/chat/completions")
92
  async def chat_completion(request: ChatRequest):
93
  """
94
- Stateless chat completion layer. Processes full history streams,
95
- generates responses, and safely flushes conversational RAM context.
96
  """
97
  try:
98
- # Step A: Inject dynamic custom instructions pulled straight from MongoDB Atlas
99
  system_prompt = compile_permanent_knowledge()
100
 
101
- # Step B: Spin up a fresh, zero-persistence context window array
102
  temporary_context = [
103
  {"role": "system", "content": system_prompt}
104
  ]
105
 
106
- # Step C: Load the historical message history passed over from your client UI
107
  for msg in request.messages:
108
  temporary_context.append({"role": msg.role, "content": msg.content})
 
 
 
 
 
 
 
 
 
 
109
 
110
- # Step D: Hand the compiled array over to the llama-cpp execution matrix
111
- response = llm.create_chat_completion(
112
- messages=temporary_context,
113
- temperature=0.1, # Low temperature ensures highly structured, accurate code compilation
114
- max_tokens=1024
115
- )
116
-
117
- # Step E: Return payload. Temporary context array is discarded instantly from memory.
118
- return response
119
 
120
  except Exception as e:
121
  raise HTTPException(status_code=500, detail=str(e))
 
1
  import os
2
+ import json
3
  from fastapi import FastAPI, HTTPException
4
+ from fastapi.responses import StreamingResponse
5
  from pydantic import BaseModel
6
  from typing import List, Dict
7
  from pymongo import MongoClient
 
11
  app = FastAPI()
12
 
13
  # --- CONFIGURATION LAYER ---
 
14
  REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
15
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
16
  # ---------------------------
 
22
 
23
  try:
24
  db_client = MongoClient(MONGO_URI)
 
25
  knowledge_col = db_client["ai_memory"]["knowledge"]
26
  except Exception as e:
27
  raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
 
33
  if not os.path.exists(MODEL_PATH):
34
  print(f"Model file not found locally. Downloading {MODEL_FILENAME} from HF Hub...")
35
  try:
 
36
  MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
37
  print("Download complete successfully!")
38
  except Exception as e:
 
83
 
84
  @app.get("/")
85
  async def root_health_check():
86
+ """Handles automatic framework pings from Hugging Face and Uptime monitors."""
87
  return {"status": "healthy", "engine": "Operational", "target": MODEL_FILENAME}
88
 
89
 
90
  @app.post("/v1/chat/completions")
91
  async def chat_completion(request: ChatRequest):
92
  """
93
+ Streaming chat completion layer. Emits text chunk-by-chunk in real-time,
94
+ massively improving UI responsiveness for the user.
95
  """
96
  try:
97
+ # Step A: Pull your custom rules from your live MongoDB cluster
98
  system_prompt = compile_permanent_knowledge()
99
 
100
+ # Step B: Establish the baseline system architecture rules
101
  temporary_context = [
102
  {"role": "system", "content": system_prompt}
103
  ]
104
 
105
+ # Step C: Load the message array history coming from your client side application
106
  for msg in request.messages:
107
  temporary_context.append({"role": msg.role, "content": msg.content})
108
+
109
+ # Step D: Create a background generator function to stream tokens safely
110
+ def stream_generator():
111
+ # Triggering stream=True tells llama.cpp to yield chunks instead of blocking
112
+ response_stream = llm.create_chat_completion(
113
+ messages=temporary_context,
114
+ temperature=0.1,
115
+ max_tokens=1024,
116
+ stream=True
117
+ )
118
 
119
+ for chunk in response_stream:
120
+ # Format each piece as a Server-Sent Event (SSE) data string
121
+ yield f"data: {json.dumps(chunk)}\n\n"
122
+
123
+ # Step E: Return the live running generator straight to your frontend
124
+ return StreamingResponse(stream_generator(), media_type="text/event-stream")
 
 
 
125
 
126
  except Exception as e:
127
  raise HTTPException(status_code=500, detail=str(e))