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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -109
app.py CHANGED
@@ -1,126 +1,90 @@
1
  import os
2
- import json
3
- from fastapi import FastAPI
4
- from fastapi.middleware.cors import CORSMiddleware
5
  from pydantic import BaseModel
 
 
6
  from llama_cpp import Llama
7
- from huggingface_hub import HfApi, hf_hub_download
8
 
9
  app = FastAPI()
10
 
11
- app.add_middleware(
12
- CORSMiddleware,
13
- allow_origins=["*"],
14
- allow_credentials=True,
15
- allow_methods=["*"],
16
- allow_headers=["*"],
17
- )
18
 
19
- HF_TOKEN = os.getenv("HF_TOKEN")
20
- SPACE_ID = os.getenv("SPACE_ID", "anonymous/gemma-coder-api")
21
- USERNAME = SPACE_ID.split("/")[0]
22
- REPO_ID = f"{USERNAME}/agent-persistent-memory"
23
 
24
- api = HfApi(token=HF_TOKEN)
25
- MEMORY_FILE = "teachings.json"
26
- local_memory_path = f"./{MEMORY_FILE}"
27
 
28
- if HF_TOKEN:
29
- try:
30
- api.create_repo(repo_id=REPO_ID, repo_type="dataset", private=True, exist_ok=True)
31
- except Exception as e:
32
- print(f"Dataset initialization info: {e}")
33
 
34
- def load_memory_from_cloud():
35
- if not HF_TOKEN:
36
- return []
37
- try:
38
- downloaded_path = hf_hub_download(
39
- repo_id=REPO_ID,
40
- filename=MEMORY_FILE,
41
- repo_type="dataset",
42
- token=HF_TOKEN
43
- )
44
- with open(downloaded_path, "r") as f:
45
- return json.load(f)
46
- except Exception:
47
- return []
48
-
49
- def save_memory_to_cloud(memory_list):
50
- with open(local_memory_path, "w") as f:
51
- json.dump(memory_list, f, indent=4)
52
- if HF_TOKEN:
53
- try:
54
- api.upload_file(
55
- path_or_fileobj=local_memory_path,
56
- path_in_repo=MEMORY_FILE,
57
- repo_id=REPO_ID,
58
- repo_type="dataset"
59
- )
60
- except Exception as e:
61
- print(f"Cloud backup failed: {e}")
62
-
63
- print("Downloading model weights and allocating 16GB system RAM pool...")
64
- llm = Llama.from_pretrained(
65
- repo_id="yuxinlu1/gemma-4-12B-coder-fable5-composer2.5-v1-GGUF",
66
- filename="*Q4_K_M.gguf",
67
- n_ctx=4096
68
- )
69
- print("Gemma-4-12B-Coder loaded and ready!")
70
-
71
- class ChatInput(BaseModel):
72
- prompt: str
73
- temperature: float = 0.0
74
-
75
- class TeachingInput(BaseModel):
76
- category: str
77
- rule: str
78
-
79
- @app.post("/teach")
80
- async def teach_agent(data: TeachingInput):
81
- current_memory = load_memory_from_cloud()
82
- new_rule = {
83
- "id": len(current_memory) + 1,
84
- "category": data.category,
85
- "rule": data.rule
86
- }
87
- current_memory.append(new_rule)
88
- save_memory_to_cloud(current_memory)
89
- return {"success": True, "message": f"Successfully injected rule into category: {data.category}"}
90
-
91
- @app.post("/forget")
92
- async def forget_rule(rule_id: int):
93
- current_memory = load_memory_from_cloud()
94
- updated_memory = [r for r in current_memory if r["id"] != rule_id]
95
- save_memory_to_cloud(updated_memory)
96
- return {"success": True, "message": f"Purged rule ID {rule_id} from brain memory."}
97
-
98
- @app.post("/generate")
99
- async def generate_code(data: ChatInput):
100
- teachings = load_memory_from_cloud()
101
 
102
- system_instructions = "You are the world's most precise, slop-free AI coding agent.\n"
103
- system_instructions += "You must strictly follow these engineering laws established by your creator:\n"
 
104
 
105
- for item in teachings:
106
- system_instructions += f"- [{item['category'].upper()}]: {item['rule']}\n"
107
 
108
- system_instructions += "\nThink systematically in your open reasoning trace channel, then output flawless code."
 
109
 
 
 
 
 
110
  try:
111
- output = llm.create_chat_completion(
112
- messages=[
113
- {"role": "system", "content": system_instructions},
114
- {"role": "user", "content": data.prompt}
115
- ],
116
- temperature=data.temperature,
117
- max_tokens=2000
118
- )
119
- ai_response = output["choices"][0]["message"]["content"]
120
- return {"success": True, "code": ai_response, "rules_enforced": len(teachings)}
 
 
 
 
 
 
 
 
121
  except Exception as e:
122
- return {"success": False, "error": str(e)}
 
123
 
124
- @app.get("/")
125
- async def health_check():
126
- return {"status": "online", "engine": "Gemma-4-12B-Coder-Fable5"}
 
 
 
 
 
 
 
 
 
 
 
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
6
  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
29
+
30
+ class ChatRequest(BaseModel):
31
+ messages: List[ChatMessage]
32
+
33
+ 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))
76
+
77
 
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."}