nulltron commited on
Commit
34a3ef8
·
verified ·
1 Parent(s): 72082f2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -0
app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ from typing import List, Dict, Any
5
+ import uvicorn
6
+ from model_loader import get_local_llm_instance
7
+
8
+ app = FastAPI(title="Stateless Agent Pipeline")
9
+
10
+ # Enable global cross-origin resource sharing for frontend html access
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_credentials=True,
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ # Load model engine universally on runtime startup
20
+ try:
21
+ llm_instance = get_local_llm_instance()
22
+ except Exception as init_err:
23
+ print(f"[CRITICAL ERROR] Failed to load local weights: {init_err}")
24
+ llm_instance = None
25
+
26
+ # Validation structure for parsing the data packets cleanly
27
+ class ChatPayload(BaseModel):
28
+ user_id: str
29
+ user_message: str
30
+ current_chat_history: List[Dict[str, Any]] = []
31
+ user_files: Dict[str, Any] = {}
32
+
33
+ @app.get("/")
34
+ def read_root():
35
+ return {"status": "online", "engine": "Llama.cpp local cluster running flawlessly"}
36
+
37
+ @app.post("/chat")
38
+ async def chat_endpoint(payload: ChatPayload):
39
+ global llm_instance
40
+ if llm_instance is None:
41
+ raise HTTPException(status_code=500, detail="Local LLM instance cluster is offline.")
42
+
43
+ try:
44
+ user_query = payload.user_message
45
+
46
+ # Build strict system directives for clean output responses
47
+ system_instruction = (
48
+ "<|im_start|>system\n"
49
+ "You are a helpful, extremely fast AI assistant. "
50
+ "Respond cleanly, accurately and directly to the prompt. "
51
+ "Keep formatting minimal.<|im_end|>\n"
52
+ )
53
+
54
+ # Format chat history context string if it exists
55
+ history_context = ""
56
+ for turn in payload.current_chat_history[-4:]: # Keep only the last 4 exchanges to preserve fast RAM context
57
+ role = "user" if turn.get("role") == "user" else "assistant"
58
+ content = turn.get("content", "")
59
+ history_context += f"<|im_start|>{role}\n{content}<|im_end|>\n"
60
+
61
+ # Compile complete operational template string
62
+ final_prompt = f"{system_instruction}{history_context}<|im_start|>user\n{user_query}<|im_end|>\n<|im_start|>assistant\n"
63
+
64
+ # Run synchronous inference across CPU matrix
65
+ output = llm_instance(
66
+ final_prompt,
67
+ max_tokens=512, # Generation constraint for faster response times
68
+ stop=["<|im_end|>", "<|im_start|>", "user:", "assistant:"],
69
+ echo=False
70
+ )
71
+
72
+ generated_text = output["choices"][0]["text"].strip()
73
+
74
+ # Re-construct updated structural array history block
75
+ updated_history = payload.current_chat_history + [
76
+ {"role": "user", "content": user_query},
77
+ {"role": "assistant", "content": generated_text}
78
+ ]
79
+
80
+ return {
81
+ "updated_chat_history": updated_history,
82
+ "updated_files": payload.user_files
83
+ }
84
+
85
+ except Exception as exec_error:
86
+ raise HTTPException(status_code=500, detail=f"Inference Engine Error: {str(exec_error)}")
87
+
88
+ if __name__ == "__main__":
89
+ uvicorn.run(app, host="0.0.0.0", port=7860)