ryan33121 commited on
Commit
82c5a00
·
verified ·
1 Parent(s): 7635c90

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"}