ryan33121 commited on
Commit
351d332
·
verified ·
1 Parent(s): c82ed9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -20
app.py CHANGED
@@ -11,9 +11,11 @@ from llama_cpp import Llama
11
 
12
  app = FastAPI()
13
 
 
14
  app.add_middleware(
15
  CORSMiddleware,
16
  allow_origins=["*"],
 
17
  allow_methods=["*"],
18
  allow_headers=["*"],
19
  )
@@ -23,63 +25,73 @@ REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
23
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
24
  CACHED_SYSTEM_PROMPT = ""
25
 
26
- # 1. MongoDB Setup
27
  MONGO_URI = os.getenv("MONGO_URI")
28
- if MONGO_URI:
29
- db_client = MongoClient(MONGO_URI)
30
- knowledge_col = db_client["ai_memory"]["knowledge"]
 
 
31
 
32
  def refresh_knowledge_cache():
33
  global CACHED_SYSTEM_PROMPT
 
34
  try:
35
  saved_items = knowledge_col.find({})
36
  rules = [item["text"] for item in saved_items]
37
- CACHED_SYSTEM_PROMPT = "You are an expert coding assistant.\n" + "\n".join(f"- {rule}" for rule in rules)
38
  except:
39
- CACHED_SYSTEM_PROMPT = "You are an expert coding assistant."
40
 
41
- # 2. Model Loading
42
  MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
43
  llm = Llama(
44
  model_path=MODEL_PATH,
45
- n_ctx=2048,
46
  n_threads=4,
47
  chat_format="chatml"
48
  )
49
  refresh_knowledge_cache()
50
 
51
- # 3. Request Schemas
52
  class ChatMessage(BaseModel):
53
  role: str
54
  content: str
55
 
56
  class ChatRequest(BaseModel):
57
  messages: List[ChatMessage]
58
- model: str = "Qwen" # Chatbox requires this field
59
 
60
- # --- API ENDPOINTS ---
 
 
 
61
 
62
  @app.post("/v1/chat/completions")
63
  async def chat_completion(request: ChatRequest):
64
  try:
65
- # Construct message list
66
- messages = [{"role": "system", "content": CACHED_SYSTEM_PROMPT}]
67
  for msg in request.messages:
68
- messages.append({"role": msg.role, "content": msg.content})
69
 
70
  def stream_generator():
71
- # Use streaming mode
72
  response_stream = llm.create_chat_completion(
73
- messages=messages,
74
- temperature=0.7,
75
  stream=True
76
  )
77
  for chunk in response_stream:
78
- # Proper OpenAI-compatible SSE format
79
  yield f"data: {json.dumps(chunk)}\n\n"
80
- yield "data: [DONE]\n\n"
81
 
82
  return StreamingResponse(stream_generator(), media_type="text/event-stream")
83
-
 
 
 
 
 
 
 
 
84
  except Exception as e:
85
  raise HTTPException(status_code=500, detail=str(e))
 
11
 
12
  app = FastAPI()
13
 
14
+ # --- CORS SECURITY ---
15
  app.add_middleware(
16
  CORSMiddleware,
17
  allow_origins=["*"],
18
+ allow_credentials=True,
19
  allow_methods=["*"],
20
  allow_headers=["*"],
21
  )
 
25
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
26
  CACHED_SYSTEM_PROMPT = ""
27
 
28
+ # 1. MongoDB Initialization
29
  MONGO_URI = os.getenv("MONGO_URI")
30
+ if not MONGO_URI:
31
+ raise RuntimeError("MONGO_URI secret is missing!")
32
+
33
+ db_client = MongoClient(MONGO_URI)
34
+ knowledge_col = db_client["ai_memory"]["knowledge"]
35
 
36
  def refresh_knowledge_cache():
37
  global CACHED_SYSTEM_PROMPT
38
+ base_instruction = "You are an elite, production-grade programming AI assistant. Adhere to these guidelines:\n"
39
  try:
40
  saved_items = knowledge_col.find({})
41
  rules = [item["text"] for item in saved_items]
42
+ CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
43
  except:
44
+ CACHED_SYSTEM_PROMPT = base_instruction
45
 
46
+ # 2. Model Loading (with Memory Management)
47
  MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
48
  llm = Llama(
49
  model_path=MODEL_PATH,
50
+ n_ctx=2048, # Fix for Error 139
51
  n_threads=4,
52
  chat_format="chatml"
53
  )
54
  refresh_knowledge_cache()
55
 
56
+ # 3. Schemas
57
  class ChatMessage(BaseModel):
58
  role: str
59
  content: str
60
 
61
  class ChatRequest(BaseModel):
62
  messages: List[ChatMessage]
 
63
 
64
+ class KnowledgeItem(BaseModel):
65
+ text: str
66
+
67
+ # --- ENDPOINTS ---
68
 
69
  @app.post("/v1/chat/completions")
70
  async def chat_completion(request: ChatRequest):
71
  try:
72
+ history = [{"role": "system", "content": CACHED_SYSTEM_PROMPT}]
 
73
  for msg in request.messages:
74
+ history.append({"role": msg.role, "content": msg.content})
75
 
76
  def stream_generator():
 
77
  response_stream = llm.create_chat_completion(
78
+ messages=history,
79
+ temperature=0.1,
80
  stream=True
81
  )
82
  for chunk in response_stream:
 
83
  yield f"data: {json.dumps(chunk)}\n\n"
84
+ yield "data: [DONE]\n\n" # Required for Chatbox to finish loading
85
 
86
  return StreamingResponse(stream_generator(), media_type="text/event-stream")
87
+ except Exception as e:
88
+ raise HTTPException(status_code=500, detail=str(e))
89
+
90
+ @app.post("/admin/teach")
91
+ async def add_permanent_knowledge(item: KnowledgeItem):
92
+ try:
93
+ knowledge_col.insert_one({"text": item.text.strip()})
94
+ refresh_knowledge_cache()
95
+ return {"status": "success", "detail": "Knowledge updated."}
96
  except Exception as e:
97
  raise HTTPException(status_code=500, detail=str(e))