ryan33121 commited on
Commit
c82ed9e
·
verified ·
1 Parent(s): 1b74766

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -105
app.py CHANGED
@@ -4,160 +4,82 @@ from fastapi import FastAPI, HTTPException
4
  from fastapi.responses import StreamingResponse
5
  from fastapi.middleware.cors import CORSMiddleware
6
  from pydantic import BaseModel
7
- from typing import List, Dict
8
  from pymongo import MongoClient
9
  from huggingface_hub import hf_hub_download
10
  from llama_cpp import Llama
11
 
12
  app = FastAPI()
13
 
14
- # --- CORS SECURITY MIDDLEWARE LAYER ---
15
- # This permits browser-based applications (like Chatbox Web) to connect seamlessly
16
  app.add_middleware(
17
  CORSMiddleware,
18
- allow_origins=["*"], # Permits connections from any domain origin
19
- allow_credentials=False,
20
- allow_methods=["*"], # Permits all HTTP methods (GET, POST, OPTIONS, etc.)
21
- allow_headers=["*"], # Permits all network headers
22
  )
23
- # --------------------------------------
24
 
25
- # --- CONFIGURATION LAYER ---
26
  REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
27
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
28
- # ---------------------------
29
-
30
- # Global memory variable to cache your custom rules from MongoDB
31
  CACHED_SYSTEM_PROMPT = ""
32
 
33
- # 1. Connect to MongoDB using the secret from Space Settings
34
  MONGO_URI = os.getenv("MONGO_URI")
35
- if not MONGO_URI:
36
- raise RuntimeError("MONGO_URI secret is missing from Space Settings!")
37
-
38
- try:
39
  db_client = MongoClient(MONGO_URI)
40
  knowledge_col = db_client["ai_memory"]["knowledge"]
41
- except Exception as e:
42
- raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
43
 
44
-
45
- # 2. Helper Function to Sync Database to Fast System RAM
46
  def refresh_knowledge_cache():
47
- """Reads MongoDB once and saves everything to local RAM for instant access."""
48
  global CACHED_SYSTEM_PROMPT
49
- base_instruction = (
50
- "You are an elite, production-grade programming AI assistant. "
51
- "Adhere strictly to the following custom developer rules and ecosystem guidelines:\n"
52
- )
53
  try:
54
  saved_items = knowledge_col.find({})
55
  rules = [item["text"] for item in saved_items]
56
-
57
- if not rules:
58
- CACHED_SYSTEM_PROMPT = base_instruction + "- Always prioritize writing clean, highly optimized, and modular architecture."
59
- else:
60
- CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
61
-
62
- print("⚡ System RAM Cache successfully synchronized with MongoDB Atlas rules.")
63
- except Exception as e:
64
- print(f"⚠️ Warning: Could not update RAM cache from database: {e}")
65
- CACHED_SYSTEM_PROMPT = base_instruction
66
-
67
-
68
- # 3. Automatic Cloud Download & Load Layer
69
- MODEL_PATH = f"./{MODEL_FILENAME}"
70
 
71
- if not os.path.exists(MODEL_PATH):
72
- print(f"Model file not found locally. Downloading {MODEL_FILENAME} from HF Hub...")
73
- try:
74
- MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
75
- print("Download complete successfully!")
76
- except Exception as e:
77
- raise RuntimeError(f"Failed to automatically pull weights from Hugging Face Hub: {str(e)}")
78
-
79
- print("Allocating system RAM pool and pinning LLM matrix...")
80
  llm = Llama(
81
  model_path=MODEL_PATH,
82
- n_ctx=2048,
83
- n_threads=4,
84
- chat_format="chatml" # Forces the model to use ChatML formatting so it doesn't speak gibberish
85
  )
86
-
87
- # Populate the RAM cache immediately on server startup
88
  refresh_knowledge_cache()
89
- print("Model engine loaded and ready to process streams!")
90
-
91
 
92
- # 4. Data Schemas for Incoming Requests
93
  class ChatMessage(BaseModel):
94
  role: str
95
  content: str
96
 
97
  class ChatRequest(BaseModel):
98
  messages: List[ChatMessage]
99
-
100
- class KnowledgeItem(BaseModel):
101
- text: str
102
-
103
 
104
  # --- API ENDPOINTS ---
105
 
106
- @app.get("/")
107
- async def root_health_check():
108
- """Handles automatic framework pings from Hugging Face and Uptime monitors."""
109
- return {"status": "healthy", "engine": "Cached-Operational", "target": MODEL_FILENAME}
110
-
111
-
112
  @app.post("/v1/chat/completions")
113
  async def chat_completion(request: ChatRequest):
114
- """
115
- Ultra-fast streaming endpoint. Reads prompt guidelines instantly from
116
- system RAM cache instead of querying the database on every turn.
117
- """
118
  try:
119
- # Step A: Instantly use the cached rules from RAM (Zero database lag!)
120
- temporary_context = [
121
- {"role": "system", "content": CACHED_SYSTEM_PROMPT}
122
- ]
123
-
124
- # Step B: Load the history array sent from your frontend interface
125
  for msg in request.messages:
126
- temporary_context.append({"role": msg.role, "content": msg.content})
127
 
128
- # Step C: Background generator streams tokens back chunk-by-chunk
129
  def stream_generator():
 
130
  response_stream = llm.create_chat_completion(
131
- messages=temporary_context,
132
- temperature=0.1,
133
- max_tokens=1024,
134
  stream=True
135
  )
136
  for chunk in response_stream:
 
137
  yield f"data: {json.dumps(chunk)}\n\n"
138
-
139
- return StreamingResponse(stream_generator(), media_type="text/event-stream")
140
-
141
- except Exception as e:
142
- raise HTTPException(status_code=500, detail=str(e))
143
-
144
 
145
- @app.post("/admin/teach")
146
- async def add_permanent_knowledge(item: KnowledgeItem):
147
- """
148
- Writes new instructions to MongoDB AND instantly updates the live RAM cache
149
- so changes take effect immediately without requiring a server reboot.
150
- """
151
- if not item.text.strip():
152
- raise HTTPException(status_code=400, detail="Knowledge string cannot be empty.")
153
-
154
- try:
155
- # 1. Permanent commit to the external cloud database
156
- knowledge_col.insert_one({"text": item.text.strip()})
157
-
158
- # 2. Instantly refresh the local RAM pool so the next chat request knows about it
159
- refresh_knowledge_cache()
160
 
161
- return {"status": "success", "detail": "Custom guideline committed securely and cached in RAM."}
162
  except Exception as e:
163
- raise HTTPException(status_code=500, detail=f"Database write execution failed: {str(e)}")
 
4
  from fastapi.responses import StreamingResponse
5
  from fastapi.middleware.cors import CORSMiddleware
6
  from pydantic import BaseModel
7
+ from typing import List
8
  from pymongo import MongoClient
9
  from huggingface_hub import hf_hub_download
10
  from llama_cpp import Llama
11
 
12
  app = FastAPI()
13
 
 
 
14
  app.add_middleware(
15
  CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
 
19
  )
 
20
 
21
+ # --- CONFIGURATION ---
22
  REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
23
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
 
 
 
24
  CACHED_SYSTEM_PROMPT = ""
25
 
26
+ # 1. MongoDB Setup
27
  MONGO_URI = os.getenv("MONGO_URI")
28
+ if MONGO_URI:
 
 
 
29
  db_client = MongoClient(MONGO_URI)
30
  knowledge_col = db_client["ai_memory"]["knowledge"]
 
 
31
 
 
 
32
  def refresh_knowledge_cache():
 
33
  global CACHED_SYSTEM_PROMPT
 
 
 
 
34
  try:
35
  saved_items = knowledge_col.find({})
36
  rules = [item["text"] for item in saved_items]
37
+ CACHED_SYSTEM_PROMPT = "You are an expert coding assistant.\n" + "\n".join(f"- {rule}" for rule in rules)
38
+ except:
39
+ CACHED_SYSTEM_PROMPT = "You are an expert coding assistant."
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ # 2. Model Loading
42
+ MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
 
 
 
 
 
 
 
43
  llm = Llama(
44
  model_path=MODEL_PATH,
45
+ n_ctx=2048,
46
+ n_threads=4,
47
+ chat_format="chatml"
48
  )
 
 
49
  refresh_knowledge_cache()
 
 
50
 
51
+ # 3. Request Schemas
52
  class ChatMessage(BaseModel):
53
  role: str
54
  content: str
55
 
56
  class ChatRequest(BaseModel):
57
  messages: List[ChatMessage]
58
+ model: str = "Qwen" # Chatbox requires this field
 
 
 
59
 
60
  # --- API ENDPOINTS ---
61
 
 
 
 
 
 
 
62
  @app.post("/v1/chat/completions")
63
  async def chat_completion(request: ChatRequest):
 
 
 
 
64
  try:
65
+ # Construct message list
66
+ messages = [{"role": "system", "content": CACHED_SYSTEM_PROMPT}]
 
 
 
 
67
  for msg in request.messages:
68
+ messages.append({"role": msg.role, "content": msg.content})
69
 
 
70
  def stream_generator():
71
+ # Use streaming mode
72
  response_stream = llm.create_chat_completion(
73
+ messages=messages,
74
+ temperature=0.7,
 
75
  stream=True
76
  )
77
  for chunk in response_stream:
78
+ # Proper OpenAI-compatible SSE format
79
  yield f"data: {json.dumps(chunk)}\n\n"
80
+ yield "data: [DONE]\n\n"
 
 
 
 
 
81
 
82
+ return StreamingResponse(stream_generator(), media_type="text/event-stream")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
 
84
  except Exception as e:
85
+ raise HTTPException(status_code=500, detail=str(e))