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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -30
app.py CHANGED
@@ -3,10 +3,17 @@ from fastapi import FastAPI, HTTPException
3
  from pydantic import BaseModel
4
  from typing import List, Dict
5
  from pymongo import MongoClient
 
6
  from llama_cpp import Llama
7
 
8
  app = FastAPI()
9
 
 
 
 
 
 
 
10
  # 1. Connect to MongoDB using the secret from Space Settings
11
  MONGO_URI = os.getenv("MONGO_URI")
12
  if not MONGO_URI:
@@ -20,24 +27,25 @@ except Exception as e:
20
  raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
21
 
22
 
23
- # 2. Dynamic Model Loading Layer
24
- # This looks for any GGUF file in your root folder automatically so typos can't break it
25
- MODEL_PATH = "./gemma-4-12b-coder.gguf"
26
 
27
  if not os.path.exists(MODEL_PATH):
28
- gguf_files = [f for f in os.listdir(".") if f.endswith(".gguf")]
29
- if gguf_files:
30
- MODEL_PATH = f"./{gguf_files[0]}"
31
- else:
32
- raise FileNotFoundError("Could not find any .gguf model weights inside the root directory!")
 
 
33
 
34
- print("Downloading model weights and allocating 16GB system RAM pool...")
35
  llm = Llama(
36
  model_path=MODEL_PATH,
37
- n_ctx=2048, # The maximum size of your temporary context window
38
- n_threads=4 # Optimal thread count for CPU execution
39
  )
40
- print("Gemma-4-12B-Coder loaded and ready!")
41
 
42
 
43
  # 3. Data Schemas for Incoming Requests
@@ -55,8 +63,8 @@ class KnowledgeItem(BaseModel):
55
  # 4. Helper Function to Assemble the Permanent Brain Layer
56
  def compile_permanent_knowledge() -> str:
57
  base_instruction = (
58
- "You are Gemma-4-12B-Coder, an elite development assistant. "
59
- "Adhere strictly to the following custom rules and core project guidelines:\n"
60
  )
61
 
62
  try:
@@ -67,7 +75,7 @@ def compile_permanent_knowledge() -> str:
67
  rules = []
68
 
69
  if not rules:
70
- return base_instruction + "- Always prioritize clean, modular, and optimized code execution."
71
 
72
  return base_instruction + "\n".join(f"- {rule}" for rule in rules)
73
 
@@ -76,37 +84,37 @@ def compile_permanent_knowledge() -> str:
76
 
77
  @app.get("/")
78
  async def root_health_check():
79
- """Handles the automatic infrastructure ping from Hugging Face."""
80
- return {"status": "healthy", "model": "Gemma-4-12B-Coder Active"}
81
 
82
 
83
  @app.post("/v1/chat/completions")
84
  async def chat_completion(request: ChatRequest):
85
  """
86
- Stateless endpoint. Processes full conversational streams,
87
- answers, and completely drops user data from memory.
88
  """
89
  try:
90
- # Step A: Inject the fresh, permanent teaching layer from MongoDB Atlas
91
  system_prompt = compile_permanent_knowledge()
92
 
93
- # Step B: Build your absolute temporary context structure for this exact turn
94
  temporary_context = [
95
  {"role": "system", "content": system_prompt}
96
  ]
97
 
98
- # Step C: Append the array of user messages passed up from your frontend UI
99
  for msg in request.messages:
100
  temporary_context.append({"role": msg.role, "content": msg.content})
101
 
102
- # Step D: Execute the raw text inference inside your local RAM engine
103
  response = llm.create_chat_completion(
104
  messages=temporary_context,
105
- temperature=0.2, # Low temperature guarantees deterministic, structured code output
106
  max_tokens=1024
107
  )
108
 
109
- # Step E: Ship the result back. The temporary_context array drops completely out of RAM.
110
  return response
111
 
112
  except Exception as e:
@@ -116,14 +124,14 @@ async def chat_completion(request: ChatRequest):
116
  @app.post("/admin/teach")
117
  async def add_permanent_knowledge(item: KnowledgeItem):
118
  """
119
- Write new rules directly to your external cluster.
120
- This bypasses container builds and persists through any server updates.
121
  """
122
  if not item.text.strip():
123
- raise HTTPException(status_code=400, detail="Text field cannot be left blank.")
124
 
125
  try:
126
  knowledge_col.insert_one({"text": item.text.strip()})
127
- return {"status": "success", "detail": "Custom knowledge committed permanently."}
128
  except Exception as e:
129
- raise HTTPException(status_code=500, detail=f"Database write operation failed: {str(e)}")
 
3
  from pydantic import BaseModel
4
  from typing import List, Dict
5
  from pymongo import MongoClient
6
+ from huggingface_hub import hf_hub_download
7
  from llama_cpp import Llama
8
 
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
+ # ---------------------------
16
+
17
  # 1. Connect to MongoDB using the secret from Space Settings
18
  MONGO_URI = os.getenv("MONGO_URI")
19
  if not MONGO_URI:
 
27
  raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
28
 
29
 
30
+ # 2. Automatic Cloud Download & Load Layer
31
+ MODEL_PATH = f"./{MODEL_FILENAME}"
 
32
 
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:
40
+ raise RuntimeError(f"Failed to automatically pull weights from Hugging Face Hub: {str(e)}")
41
 
42
+ print("Allocating system RAM pool and pinning LLM matrix...")
43
  llm = Llama(
44
  model_path=MODEL_PATH,
45
+ n_ctx=2048, # Total token capacity for system instructions + chat history
46
+ n_threads=4 # Balanced CPU core assignment for Hugging Face Spaces
47
  )
48
+ print("Model engine loaded and ready to process streams!")
49
 
50
 
51
  # 3. Data Schemas for Incoming Requests
 
63
  # 4. Helper Function to Assemble the Permanent Brain Layer
64
  def compile_permanent_knowledge() -> str:
65
  base_instruction = (
66
+ "You are an elite, production-grade programming AI assistant. "
67
+ "Adhere strictly to the following custom developer rules and ecosystem guidelines:\n"
68
  )
69
 
70
  try:
 
75
  rules = []
76
 
77
  if not rules:
78
+ return base_instruction + "- Always prioritize writing clean, highly optimized, and modular architecture."
79
 
80
  return base_instruction + "\n".join(f"- {rule}" for rule in rules)
81
 
 
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:
 
124
  @app.post("/admin/teach")
125
  async def add_permanent_knowledge(item: KnowledgeItem):
126
  """
127
+ Write permanent rules directly to your external cloud cluster.
128
+ Survives restarts, crashes, code updates, and sleeps forever.
129
  """
130
  if not item.text.strip():
131
+ raise HTTPException(status_code=400, detail="Knowledge string cannot be empty.")
132
 
133
  try:
134
  knowledge_col.insert_one({"text": item.text.strip()})
135
+ return {"status": "success", "detail": "Custom guideline committed securely to cloud cluster."}
136
  except Exception as e:
137
+ raise HTTPException(status_code=500, detail=f"Database write execution failed: {str(e)}")