Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,126 +1,90 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 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 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
allow_methods=["*"],
|
| 16 |
-
allow_headers=["*"],
|
| 17 |
-
)
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 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 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
except Exception as e:
|
| 32 |
-
print(f"Dataset initialization info: {e}")
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 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 |
-
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
|
| 108 |
-
|
|
|
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
-
|
|
|
|
| 123 |
|
| 124 |
-
@app.
|
| 125 |
-
async def
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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."}
|