Spaces:
Sleeping
Sleeping
GAJJALAASHOKKUMARREDDY commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,11 +16,20 @@ from fastapi.responses import StreamingResponse
|
|
| 16 |
|
| 17 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# ================== CONFIG =================
|
| 22 |
|
| 23 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 24 |
|
| 25 |
INTENT_MODEL_NAME = "Ashok7582/intent"
|
| 26 |
PHI_MODEL_NAME = "Ashok7582/phi"
|
|
@@ -31,132 +40,234 @@ MAX_TOKENS_HARD_LIMIT = 4096
|
|
| 31 |
DEFAULT_TEMPERATURE = 0.7
|
| 32 |
STREAM_DELAY = 0.02
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# ================== APP SETUP =================
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
async def load_models():
|
|
|
|
| 37 |
global intent_tokenizer, intent_model, phi_tokenizer, phi_model
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
# Load intent classifier
|
| 42 |
try:
|
|
|
|
| 43 |
intent_tokenizer = AutoTokenizer.from_pretrained(INTENT_MODEL_NAME)
|
| 44 |
intent_model = AutoModelForSequenceClassification.from_pretrained(INTENT_MODEL_NAME)
|
| 45 |
intent_model.to(DEVICE).eval()
|
| 46 |
print(f"β
Intent model loaded: {INTENT_MODEL_NAME}")
|
| 47 |
except Exception as e:
|
| 48 |
-
print("β Failed to load intent model:
|
| 49 |
traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
# Load Phi model
|
| 52 |
try:
|
|
|
|
| 53 |
phi_tokenizer = AutoTokenizer.from_pretrained(PHI_MODEL_NAME)
|
| 54 |
phi_model = AutoModelForCausalLM.from_pretrained(PHI_MODEL_NAME)
|
| 55 |
phi_model.to(DEVICE).eval()
|
| 56 |
print(f"β
Phi model loaded: {PHI_MODEL_NAME}")
|
| 57 |
except Exception as e:
|
| 58 |
-
print("β Failed to load phi model:
|
| 59 |
traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
@app.on_event("startup")
|
| 62 |
async def startup_event():
|
|
|
|
| 63 |
await load_models()
|
| 64 |
|
| 65 |
-
app = FastAPI(title="AI Assistant (IntentβPhiβToolβPhi)")
|
| 66 |
-
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
| 67 |
-
|
| 68 |
# ================== HELPERS =================
|
| 69 |
|
| 70 |
def sanitize_input(text: str) -> str:
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
def _safe_json_extract(text: str) -> Dict[str, Any]:
|
|
|
|
| 74 |
try:
|
|
|
|
| 75 |
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
return {}
|
| 79 |
|
| 80 |
# ================== PIPELINE =================
|
| 81 |
|
| 82 |
async def generate_reply(prompt: str, files: List[UploadFile], max_tokens: int, temperature: float) -> str:
|
|
|
|
| 83 |
prompt = sanitize_input(prompt)
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
# --- Intent Classification ---
|
| 86 |
intent_label = "unknown"
|
| 87 |
try:
|
| 88 |
if intent_model and intent_tokenizer:
|
| 89 |
-
inputs = intent_tokenizer(prompt, return_tensors="pt", truncation=True).to(DEVICE)
|
| 90 |
with torch.no_grad():
|
| 91 |
logits = intent_model(**inputs).logits
|
| 92 |
pred = int(torch.argmax(logits, dim=-1).cpu().numpy()[0])
|
| 93 |
intent_label = intent_model.config.id2label.get(pred, str(pred))
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
-
print("β οΈ Intent classification error:
|
| 96 |
|
| 97 |
# --- Phi Tool Decision ---
|
| 98 |
tool_decision_json = {}
|
| 99 |
try:
|
| 100 |
-
decision_prompt = (
|
| 101 |
-
"You are an AI that decides whether a tool is required.\n"
|
| 102 |
-
"Return ONLY valid JSON:\n"
|
| 103 |
-
"{ \"use_tool\": true or false, \"tool\": \"web_search\" or null, \"args\": {\"query\": \"...\"} }\n"
|
| 104 |
-
f"Intent: {intent_label}\nPrompt: {prompt}"
|
| 105 |
-
)
|
| 106 |
if phi_model and phi_tokenizer:
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
with torch.no_grad():
|
| 109 |
-
out = phi_model.generate(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
raw = phi_tokenizer.decode(out[0], skip_special_tokens=True)
|
|
|
|
| 111 |
tool_decision_json = _safe_json_extract(raw) or {}
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
-
print("β οΈ Tool decision error:
|
| 114 |
|
| 115 |
# --- Tool Execution ---
|
| 116 |
tool_output = ""
|
| 117 |
-
use_tool = bool(tool_decision_json.get("use_tool"))
|
| 118 |
tool_name = tool_decision_json.get("tool") if use_tool else None
|
| 119 |
-
tool_args = tool_decision_json.get("args"
|
| 120 |
|
| 121 |
if use_tool and tool_name == "web_search":
|
| 122 |
try:
|
| 123 |
q = tool_args.get("query", prompt)
|
|
|
|
| 124 |
tool_output = web_search(q)
|
|
|
|
| 125 |
except Exception as e:
|
| 126 |
-
print("β οΈ Tool execution error:
|
| 127 |
tool_output = f"Search results error for: {q}"
|
| 128 |
|
| 129 |
# --- File Context (optional) ---
|
| 130 |
file_text = ""
|
| 131 |
if files:
|
|
|
|
| 132 |
for f in files:
|
| 133 |
try:
|
| 134 |
-
content_bytes = await f.read(MAX_FILE_SIZE+1)
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
# --- Phi Final Response ---
|
| 140 |
reply = ""
|
| 141 |
try:
|
| 142 |
if phi_model and phi_tokenizer:
|
| 143 |
-
system_msg =
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
user_msg =
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
with torch.no_grad():
|
| 154 |
-
out = phi_model.generate(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
reply = phi_tokenizer.decode(out[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
except Exception as e:
|
| 157 |
-
print("β Final Phi generation error:
|
|
|
|
|
|
|
| 158 |
|
| 159 |
-
return reply
|
| 160 |
|
| 161 |
# ================== STREAMING ENDPOINT =================
|
| 162 |
|
|
@@ -167,31 +278,117 @@ async def analyze(
|
|
| 167 |
max_tokens: int = Form(MAX_TOKENS_DEFAULT),
|
| 168 |
temperature: float = Form(DEFAULT_TEMPERATURE),
|
| 169 |
):
|
|
|
|
|
|
|
|
|
|
| 170 |
if not prompt and not files:
|
| 171 |
-
raise HTTPException(
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
async def streamer():
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
# ================== HEALTH & CONFIG =================
|
| 185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
@app.get("/health")
|
| 187 |
async def health():
|
|
|
|
| 188 |
return {
|
| 189 |
-
"status": "ok",
|
|
|
|
| 190 |
"intent_loaded": intent_model is not None,
|
| 191 |
"phi_loaded": phi_model is not None,
|
| 192 |
-
"device": DEVICE
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
}
|
| 194 |
|
| 195 |
@app.get("/api/config")
|
| 196 |
async def config():
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM
|
| 18 |
|
| 19 |
+
# Import the tools module
|
| 20 |
+
try:
|
| 21 |
+
from tools import web_search
|
| 22 |
+
print("β
Tools module imported successfully")
|
| 23 |
+
except ImportError as e:
|
| 24 |
+
print(f"β οΈ Could not import tools module: {e}")
|
| 25 |
+
# Create a dummy web_search function as fallback
|
| 26 |
+
def web_search(query: str) -> str:
|
| 27 |
+
return f"Search results for: {query} (tools module not available)"
|
| 28 |
|
| 29 |
# ================== CONFIG =================
|
| 30 |
|
| 31 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 32 |
+
print(f"π§ Using device: {DEVICE}")
|
| 33 |
|
| 34 |
INTENT_MODEL_NAME = "Ashok7582/intent"
|
| 35 |
PHI_MODEL_NAME = "Ashok7582/phi"
|
|
|
|
| 40 |
DEFAULT_TEMPERATURE = 0.7
|
| 41 |
STREAM_DELAY = 0.02
|
| 42 |
|
| 43 |
+
# Global model variables
|
| 44 |
+
intent_tokenizer = None
|
| 45 |
+
intent_model = None
|
| 46 |
+
phi_tokenizer = None
|
| 47 |
+
phi_model = None
|
| 48 |
+
|
| 49 |
# ================== APP SETUP =================
|
| 50 |
|
| 51 |
+
app = FastAPI(title="AI Assistant (IntentβPhiβToolβPhi)", version="1.0.0")
|
| 52 |
+
|
| 53 |
+
app.add_middleware(
|
| 54 |
+
CORSMiddleware,
|
| 55 |
+
allow_origins=["*"],
|
| 56 |
+
allow_credentials=True,
|
| 57 |
+
allow_methods=["*"],
|
| 58 |
+
allow_headers=["*"]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# ================== MODEL LOADING =================
|
| 62 |
+
|
| 63 |
async def load_models():
|
| 64 |
+
"""Load and initialize the ML models"""
|
| 65 |
global intent_tokenizer, intent_model, phi_tokenizer, phi_model
|
| 66 |
+
|
| 67 |
+
print("π Loading models...")
|
| 68 |
+
|
| 69 |
# Load intent classifier
|
| 70 |
try:
|
| 71 |
+
print(f"π₯ Loading intent model: {INTENT_MODEL_NAME}")
|
| 72 |
intent_tokenizer = AutoTokenizer.from_pretrained(INTENT_MODEL_NAME)
|
| 73 |
intent_model = AutoModelForSequenceClassification.from_pretrained(INTENT_MODEL_NAME)
|
| 74 |
intent_model.to(DEVICE).eval()
|
| 75 |
print(f"β
Intent model loaded: {INTENT_MODEL_NAME}")
|
| 76 |
except Exception as e:
|
| 77 |
+
print(f"β Failed to load intent model: {e}")
|
| 78 |
traceback.print_exc()
|
| 79 |
+
# Create dummy model for fallback
|
| 80 |
+
intent_tokenizer = None
|
| 81 |
+
intent_model = None
|
| 82 |
|
| 83 |
# Load Phi model
|
| 84 |
try:
|
| 85 |
+
print(f"π₯ Loading Phi model: {PHI_MODEL_NAME}")
|
| 86 |
phi_tokenizer = AutoTokenizer.from_pretrained(PHI_MODEL_NAME)
|
| 87 |
phi_model = AutoModelForCausalLM.from_pretrained(PHI_MODEL_NAME)
|
| 88 |
phi_model.to(DEVICE).eval()
|
| 89 |
print(f"β
Phi model loaded: {PHI_MODEL_NAME}")
|
| 90 |
except Exception as e:
|
| 91 |
+
print(f"β Failed to load phi model: {e}")
|
| 92 |
traceback.print_exc()
|
| 93 |
+
# Create dummy model for fallback
|
| 94 |
+
phi_tokenizer = None
|
| 95 |
+
phi_model = None
|
| 96 |
+
|
| 97 |
+
print("β
Model loading complete")
|
| 98 |
|
| 99 |
@app.on_event("startup")
|
| 100 |
async def startup_event():
|
| 101 |
+
"""Load models on application startup"""
|
| 102 |
await load_models()
|
| 103 |
|
|
|
|
|
|
|
|
|
|
| 104 |
# ================== HELPERS =================
|
| 105 |
|
| 106 |
def sanitize_input(text: str) -> str:
|
| 107 |
+
"""Clean and sanitize user input"""
|
| 108 |
+
if not isinstance(text, str):
|
| 109 |
+
return ""
|
| 110 |
+
return text.strip()
|
| 111 |
|
| 112 |
def _safe_json_extract(text: str) -> Dict[str, Any]:
|
| 113 |
+
"""Extract JSON from text safely"""
|
| 114 |
try:
|
| 115 |
+
# Look for JSON pattern
|
| 116 |
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 117 |
+
if match:
|
| 118 |
+
json_str = match.group(0)
|
| 119 |
+
# Clean up common JSON issues
|
| 120 |
+
json_str = json_str.replace("'", '"')
|
| 121 |
+
json_str = re.sub(r'([{,]\s*)(\w+)(\s*:)', r'\1"\2"\3', json_str)
|
| 122 |
+
return json.loads(json_str)
|
| 123 |
+
return {}
|
| 124 |
+
except json.JSONDecodeError as e:
|
| 125 |
+
print(f"β οΈ JSON decode error: {e}")
|
| 126 |
+
# Try to find simple boolean pattern
|
| 127 |
+
if "true" in text.lower():
|
| 128 |
+
return {"use_tool": True, "tool": "web_search", "args": {"query": ""}}
|
| 129 |
+
return {}
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print(f"β οΈ Error extracting JSON: {e}")
|
| 132 |
return {}
|
| 133 |
|
| 134 |
# ================== PIPELINE =================
|
| 135 |
|
| 136 |
async def generate_reply(prompt: str, files: List[UploadFile], max_tokens: int, temperature: float) -> str:
|
| 137 |
+
"""Main 3-turn pipeline: Intent β Tool Decision β Final Response"""
|
| 138 |
prompt = sanitize_input(prompt)
|
| 139 |
+
|
| 140 |
+
print(f"π― Processing prompt: '{prompt[:50]}...'")
|
| 141 |
+
|
| 142 |
# --- Intent Classification ---
|
| 143 |
intent_label = "unknown"
|
| 144 |
try:
|
| 145 |
if intent_model and intent_tokenizer:
|
| 146 |
+
inputs = intent_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(DEVICE)
|
| 147 |
with torch.no_grad():
|
| 148 |
logits = intent_model(**inputs).logits
|
| 149 |
pred = int(torch.argmax(logits, dim=-1).cpu().numpy()[0])
|
| 150 |
intent_label = intent_model.config.id2label.get(pred, str(pred))
|
| 151 |
+
print(f"π§ Intent detected: {intent_label}")
|
| 152 |
except Exception as e:
|
| 153 |
+
print(f"β οΈ Intent classification error: {e}")
|
| 154 |
|
| 155 |
# --- Phi Tool Decision ---
|
| 156 |
tool_decision_json = {}
|
| 157 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
if phi_model and phi_tokenizer:
|
| 159 |
+
decision_prompt = f"""You are an AI that decides whether a tool is required.
|
| 160 |
+
Return ONLY valid JSON format:
|
| 161 |
+
{{ "use_tool": true or false, "tool": "web_search" or null, "args": {{"query": "..."}} }}
|
| 162 |
+
|
| 163 |
+
User prompt: {prompt}
|
| 164 |
+
Intent: {intent_label}
|
| 165 |
+
|
| 166 |
+
Should we use a tool? Respond with JSON:"""
|
| 167 |
+
|
| 168 |
+
inputs = phi_tokenizer(decision_prompt, return_tensors="pt", truncation=True, max_length=512).to(DEVICE)
|
| 169 |
with torch.no_grad():
|
| 170 |
+
out = phi_model.generate(
|
| 171 |
+
**inputs,
|
| 172 |
+
max_new_tokens=128,
|
| 173 |
+
temperature=0.1,
|
| 174 |
+
do_sample=True,
|
| 175 |
+
pad_token_id=phi_tokenizer.eos_token_id
|
| 176 |
+
)
|
| 177 |
raw = phi_tokenizer.decode(out[0], skip_special_tokens=True)
|
| 178 |
+
print(f"π€ Tool decision raw: {raw}")
|
| 179 |
tool_decision_json = _safe_json_extract(raw) or {}
|
| 180 |
+
print(f"π§ Tool decision parsed: {tool_decision_json}")
|
| 181 |
except Exception as e:
|
| 182 |
+
print(f"β οΈ Tool decision error: {e}")
|
| 183 |
|
| 184 |
# --- Tool Execution ---
|
| 185 |
tool_output = ""
|
| 186 |
+
use_tool = bool(tool_decision_json.get("use_tool", False))
|
| 187 |
tool_name = tool_decision_json.get("tool") if use_tool else None
|
| 188 |
+
tool_args = tool_decision_json.get("args", {})
|
| 189 |
|
| 190 |
if use_tool and tool_name == "web_search":
|
| 191 |
try:
|
| 192 |
q = tool_args.get("query", prompt)
|
| 193 |
+
print(f"π Executing web search for: '{q}'")
|
| 194 |
tool_output = web_search(q)
|
| 195 |
+
print(f"β
Search results received ({len(tool_output)} chars)")
|
| 196 |
except Exception as e:
|
| 197 |
+
print(f"β οΈ Tool execution error: {e}")
|
| 198 |
tool_output = f"Search results error for: {q}"
|
| 199 |
|
| 200 |
# --- File Context (optional) ---
|
| 201 |
file_text = ""
|
| 202 |
if files:
|
| 203 |
+
print(f"π Processing {len(files)} file(s)")
|
| 204 |
for f in files:
|
| 205 |
try:
|
| 206 |
+
content_bytes = await f.read(MAX_FILE_SIZE + 1)
|
| 207 |
+
if len(content_bytes) > MAX_FILE_SIZE:
|
| 208 |
+
print(f"β οΈ File {f.filename} too large, skipping")
|
| 209 |
+
continue
|
| 210 |
+
file_text += f"\n--- File: {f.filename} ---\n"
|
| 211 |
+
try:
|
| 212 |
+
file_text += content_bytes.decode('utf-8', errors='ignore')
|
| 213 |
+
except:
|
| 214 |
+
file_text += f"[Binary file: {f.filename}, size: {len(content_bytes)} bytes]"
|
| 215 |
+
file_text += "\n"
|
| 216 |
+
print(f"β
Processed file: {f.filename}")
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print(f"β οΈ Error reading file {f.filename}: {e}")
|
| 219 |
|
| 220 |
# --- Phi Final Response ---
|
| 221 |
reply = ""
|
| 222 |
try:
|
| 223 |
if phi_model and phi_tokenizer:
|
| 224 |
+
system_msg = """You are a helpful AI assistant named GAKR AI.
|
| 225 |
+
Use tool results and file context if provided.
|
| 226 |
+
Always format your output in Markdown with proper headings, bullet points, tables, and code blocks when appropriate.
|
| 227 |
+
Be concise but thorough in your responses."""
|
| 228 |
+
|
| 229 |
+
user_msg = f"""User query: {prompt}
|
| 230 |
+
|
| 231 |
+
Context:
|
| 232 |
+
- Intent: {intent_label}
|
| 233 |
+
- Tool output: {tool_output if tool_output else "No tool used"}
|
| 234 |
+
- File context: {file_text if file_text else "No files provided"}
|
| 235 |
+
|
| 236 |
+
Please provide a helpful response in Markdown format:"""
|
| 237 |
+
|
| 238 |
+
full_prompt = f"{system_msg}\n\n{user_msg}"
|
| 239 |
+
|
| 240 |
+
inputs = phi_tokenizer(
|
| 241 |
+
full_prompt,
|
| 242 |
+
return_tensors="pt",
|
| 243 |
+
truncation=True,
|
| 244 |
+
max_length=2048
|
| 245 |
+
).to(DEVICE)
|
| 246 |
+
|
| 247 |
with torch.no_grad():
|
| 248 |
+
out = phi_model.generate(
|
| 249 |
+
**inputs,
|
| 250 |
+
max_new_tokens=max_tokens,
|
| 251 |
+
temperature=temperature,
|
| 252 |
+
do_sample=temperature > 0,
|
| 253 |
+
pad_token_id=phi_tokenizer.eos_token_id,
|
| 254 |
+
repetition_penalty=1.1
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
reply = phi_tokenizer.decode(out[0], skip_special_tokens=True)
|
| 258 |
+
|
| 259 |
+
# Remove the prompt part from the response
|
| 260 |
+
if reply.startswith(full_prompt):
|
| 261 |
+
reply = reply[len(full_prompt):].strip()
|
| 262 |
+
|
| 263 |
+
print(f"β
Generated response ({len(reply)} chars)")
|
| 264 |
+
|
| 265 |
except Exception as e:
|
| 266 |
+
print(f"β Final Phi generation error: {e}")
|
| 267 |
+
traceback.print_exc()
|
| 268 |
+
reply = "**Sorry, I encountered an error while generating the response.**"
|
| 269 |
|
| 270 |
+
return reply if reply.strip() else "**I couldn't generate a response for that query. Please try again.**"
|
| 271 |
|
| 272 |
# ================== STREAMING ENDPOINT =================
|
| 273 |
|
|
|
|
| 278 |
max_tokens: int = Form(MAX_TOKENS_DEFAULT),
|
| 279 |
temperature: float = Form(DEFAULT_TEMPERATURE),
|
| 280 |
):
|
| 281 |
+
"""
|
| 282 |
+
Main analysis endpoint with streaming support
|
| 283 |
+
"""
|
| 284 |
if not prompt and not files:
|
| 285 |
+
raise HTTPException(
|
| 286 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 287 |
+
detail="Empty prompt and no files provided"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
# Validate parameters
|
| 291 |
+
if max_tokens > MAX_TOKENS_HARD_LIMIT:
|
| 292 |
+
max_tokens = MAX_TOKENS_HARD_LIMIT
|
| 293 |
+
|
| 294 |
+
if temperature < 0.1 or temperature > 2.0:
|
| 295 |
+
temperature = DEFAULT_TEMPERATURE
|
| 296 |
+
|
| 297 |
+
print(f"π¨ API request - Prompt: '{prompt[:50]}...', Files: {len(files) if files else 0}")
|
| 298 |
+
|
| 299 |
async def streamer():
|
| 300 |
+
"""Stream the response as Server-Sent Events"""
|
| 301 |
+
try:
|
| 302 |
+
# Generate the full response
|
| 303 |
+
full_text = await generate_reply(prompt, files or [], max_tokens, temperature)
|
| 304 |
+
|
| 305 |
+
# Split into chunks for streaming
|
| 306 |
+
chunk_size = 100
|
| 307 |
+
for i in range(0, len(full_text), chunk_size):
|
| 308 |
+
chunk = full_text[i:i + chunk_size]
|
| 309 |
+
yield f"data: {json.dumps({'type': 'chunk', 'data': {'text': chunk}}, ensure_ascii=False)}\n\n"
|
| 310 |
+
await asyncio.sleep(STREAM_DELAY)
|
| 311 |
+
|
| 312 |
+
# Send completion signal
|
| 313 |
+
yield f"data: {json.dumps({'type': 'done'}, ensure_ascii=False)}\n\n"
|
| 314 |
+
|
| 315 |
+
except Exception as e:
|
| 316 |
+
error_msg = str(e)[:200]
|
| 317 |
+
print(f"β Streaming error: {error_msg}")
|
| 318 |
+
yield f"data: {json.dumps({'type': 'error', 'data': error_msg}, ensure_ascii=False)}\n\n"
|
| 319 |
+
|
| 320 |
+
return StreamingResponse(
|
| 321 |
+
streamer(),
|
| 322 |
+
media_type="text/event-stream",
|
| 323 |
+
headers={
|
| 324 |
+
"Cache-Control": "no-cache",
|
| 325 |
+
"X-Accel-Buffering": "no" # Important for streaming
|
| 326 |
+
}
|
| 327 |
+
)
|
| 328 |
|
| 329 |
# ================== HEALTH & CONFIG =================
|
| 330 |
|
| 331 |
+
@app.get("/")
|
| 332 |
+
async def root():
|
| 333 |
+
"""Root endpoint with API info"""
|
| 334 |
+
return {
|
| 335 |
+
"message": "GAKR AI Assistant API",
|
| 336 |
+
"version": "1.0.0",
|
| 337 |
+
"endpoints": {
|
| 338 |
+
"/api/analyze": "POST - Main analysis endpoint with streaming",
|
| 339 |
+
"/health": "GET - Health check",
|
| 340 |
+
"/api/config": "GET - Configuration info"
|
| 341 |
+
}
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
@app.get("/health")
|
| 345 |
async def health():
|
| 346 |
+
"""Health check endpoint"""
|
| 347 |
return {
|
| 348 |
+
"status": "ok" if intent_model and phi_model else "degraded",
|
| 349 |
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 350 |
"intent_loaded": intent_model is not None,
|
| 351 |
"phi_loaded": phi_model is not None,
|
| 352 |
+
"device": DEVICE,
|
| 353 |
+
"models": {
|
| 354 |
+
"intent": INTENT_MODEL_NAME,
|
| 355 |
+
"phi": PHI_MODEL_NAME
|
| 356 |
+
}
|
| 357 |
}
|
| 358 |
|
| 359 |
@app.get("/api/config")
|
| 360 |
async def config():
|
| 361 |
+
"""Configuration endpoint"""
|
| 362 |
+
return {
|
| 363 |
+
"intent_model": INTENT_MODEL_NAME,
|
| 364 |
+
"phi_model": PHI_MODEL_NAME,
|
| 365 |
+
"max_file_size_mb": MAX_FILE_SIZE // (1024 * 1024),
|
| 366 |
+
"max_tokens_default": MAX_TOKENS_DEFAULT,
|
| 367 |
+
"max_tokens_hard_limit": MAX_TOKENS_HARD_LIMIT,
|
| 368 |
+
"default_temperature": DEFAULT_TEMPERATURE
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
# ================== ERROR HANDLERS =================
|
| 372 |
+
|
| 373 |
+
@app.exception_handler(HTTPException)
|
| 374 |
+
async def http_exception_handler(request: Request, exc: HTTPException):
|
| 375 |
+
"""Handle HTTP exceptions"""
|
| 376 |
+
return {
|
| 377 |
+
"error": exc.detail,
|
| 378 |
+
"status_code": exc.status_code
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
@app.exception_handler(Exception)
|
| 382 |
+
async def generic_exception_handler(request: Request, exc: Exception):
|
| 383 |
+
"""Handle generic exceptions"""
|
| 384 |
+
print(f"β Unhandled exception: {exc}")
|
| 385 |
+
traceback.print_exc()
|
| 386 |
+
return {
|
| 387 |
+
"error": "Internal server error",
|
| 388 |
+
"status_code": status.HTTP_500_INTERNAL_SERVER_ERROR
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
if __name__ == "__main__":
|
| 392 |
+
print("π Starting GAKR AI Assistant...")
|
| 393 |
+
print(f"π Working directory: {os.getcwd()}")
|
| 394 |
+
print(f"π Python version: {os.sys.version}")
|