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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -29
app.py CHANGED
@@ -7,22 +7,40 @@ from llama_cpp import Llama
7
 
8
  app = FastAPI()
9
 
10
- # 1. Connect to the MongoDB using the secret you just made
11
  MONGO_URI = os.getenv("MONGO_URI")
12
  if not MONGO_URI:
13
  raise RuntimeError("MONGO_URI secret is missing from Space Settings!")
14
 
15
- db_client = MongoClient(MONGO_URI)
16
- # This automatically creates a database named 'ai_memory' and a collection named 'knowledge'
17
- knowledge_col = db_client["ai_memory"]["knowledge"]
 
 
 
18
 
19
 
20
- # 2. YOUR EXISTING MODEL LOADING LOGIC HERE
21
- # Keep exactly whatever line you used to load Gemma-4-12B-Coder, for example:
22
- # llm = Llama(model_path="./gemma4-coding-Q4_K_M.gguf", n_ctx=2048)
23
 
 
 
 
 
 
 
24
 
25
- # Data schemas for validation
 
 
 
 
 
 
 
 
 
26
  class ChatMessage(BaseModel):
27
  role: str
28
  content: str
@@ -34,42 +52,62 @@ class KnowledgeItem(BaseModel):
34
  text: str
35
 
36
 
37
- # Helper function to gather everything you've taught it into one system prompt
38
  def compile_permanent_knowledge() -> str:
39
- base_instruction = "You are Gemma-4-12B-Coder. Adhere strictly to the following custom rules:\n"
 
 
 
40
 
41
- # Fetch every rule you've saved in MongoDB
42
- saved_items = knowledge_col.find({})
43
- rules = [item["text"] for item in saved_items]
 
 
 
44
 
45
  if not rules:
46
- return base_instruction + "- No custom rules added yet."
47
 
48
  return base_instruction + "\n".join(f"- {rule}" for rule in rules)
49
 
50
 
51
- # --- ENDPOINTS ---
 
 
 
 
 
 
52
 
53
  @app.post("/v1/chat/completions")
54
  async def chat_completion(request: ChatRequest):
 
 
 
 
55
  try:
56
- # Step A: Pull the absolute freshest knowledge from your cloud database
57
  system_prompt = compile_permanent_knowledge()
58
 
59
- # Step B: Build a temporary context window for this specific request
60
  temporary_context = [
61
  {"role": "system", "content": system_prompt}
62
  ]
63
 
64
- # Step C: Append the user's chat history passed from the frontend
65
  for msg in request.messages:
66
  temporary_context.append({"role": msg.role, "content": msg.content})
67
 
68
- # Step D: Run inference through your loaded model
69
- # response = llm.create_chat_completion(messages=temporary_context)
 
 
 
 
70
 
71
- # Step E: Return the answer. The temporary context clears from system RAM instantly.
72
- return {"status": "success", "message": "Context processed safely."}
73
 
74
  except Exception as e:
75
  raise HTTPException(status_code=500, detail=str(e))
@@ -78,13 +116,14 @@ async def chat_completion(request: ChatRequest):
78
  @app.post("/admin/teach")
79
  async def add_permanent_knowledge(item: KnowledgeItem):
80
  """
81
- Hit this endpoint to instantly teach Gemma new things.
82
- This writes directly to MongoDB Atlas, surviving resets forever.
83
  """
84
  if not item.text.strip():
85
- raise HTTPException(status_code=400, detail="Text cannot be empty.")
86
 
87
- # Insert new rule into your persistent cloud collection
88
- knowledge_col.insert_one({"text": item.text.strip()})
89
-
90
- return {"status": "success", "detail": "Knowledge recorded permanently."}
 
 
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:
13
  raise RuntimeError("MONGO_URI secret is missing from Space Settings!")
14
 
15
+ try:
16
+ db_client = MongoClient(MONGO_URI)
17
+ # This automatically sets up a database called 'ai_memory' and a collection called 'knowledge'
18
+ knowledge_col = db_client["ai_memory"]["knowledge"]
19
+ 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
44
  class ChatMessage(BaseModel):
45
  role: str
46
  content: str
 
52
  text: str
53
 
54
 
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:
63
+ saved_items = knowledge_col.find({})
64
+ rules = [item["text"] for item in saved_items]
65
+ except Exception as e:
66
+ print(f"Database reading warning: {e}")
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
 
74
 
75
+ # --- API ENDPOINTS ---
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:
113
  raise HTTPException(status_code=500, detail=str(e))
 
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)}")