Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
FastAPI backend with optimized streaming for
|
| 3 |
Enhanced with advanced intent detection (AshokGakr/intent_detector)
|
| 4 |
and emotion detection (AshokGakr/emotions_detector) models
|
| 5 |
"""
|
|
@@ -48,23 +48,23 @@ print(f"π§ CUDA available: {torch.cuda.is_available()}")
|
|
| 48 |
INTENT_MODEL_NAME = "AshokGakr/intent_detector" # 82 intent classes
|
| 49 |
EMOTION_MODEL_NAME = "AshokGakr/emotions_detector" # 28 emotion labels (multi-label)
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
|
| 54 |
MAX_FILE_SIZE = 50 * 1024 * 1024
|
| 55 |
MAX_TOKENS_DEFAULT = 1024
|
| 56 |
MAX_TOKENS_HARD_LIMIT = 4096 # Conservative limit for stability
|
| 57 |
-
DEFAULT_TEMPERATURE = 0.7
|
| 58 |
STREAM_DELAY = 0.02
|
| 59 |
-
MAX_CONTEXT_LENGTH =
|
| 60 |
|
| 61 |
# Global model variables
|
| 62 |
intent_tokenizer = None
|
| 63 |
intent_model = None
|
| 64 |
emotion_tokenizer = None
|
| 65 |
emotion_model = None
|
| 66 |
-
|
| 67 |
-
|
| 68 |
|
| 69 |
# Setup directories
|
| 70 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
@@ -143,9 +143,9 @@ EMOTION_TONE_MAPPING = {
|
|
| 143 |
# ================== MODEL LOADING =================
|
| 144 |
|
| 145 |
async def load_models():
|
| 146 |
-
"""Load and initialize all ML models with optimized settings"""
|
| 147 |
global intent_tokenizer, intent_model, emotion_tokenizer, emotion_model
|
| 148 |
-
global
|
| 149 |
|
| 150 |
print("\n" + "="*50)
|
| 151 |
print("π LOADING AI MODELS - ENHANCED WITH INTENT & EMOTION DETECTION")
|
|
@@ -197,88 +197,84 @@ async def load_models():
|
|
| 197 |
emotion_tokenizer = None
|
| 198 |
emotion_model = None
|
| 199 |
|
| 200 |
-
# ==== OPTIMIZED
|
| 201 |
-
|
| 202 |
try:
|
| 203 |
-
print(f"π₯ Loading
|
| 204 |
|
| 205 |
-
#
|
| 206 |
-
|
| 207 |
-
|
| 208 |
padding_side="left", # Essential for streaming
|
| 209 |
-
trust_remote_code=False,
|
| 210 |
-
use_fast=True
|
| 211 |
)
|
| 212 |
|
| 213 |
-
# IMPORTANT:
|
| 214 |
-
|
| 215 |
-
phi_tokenizer.pad_token = phi_tokenizer.eos_token
|
| 216 |
-
phi_tokenizer.pad_token_id = phi_tokenizer.eos_token_id
|
| 217 |
|
| 218 |
-
print(f" Tokenizer loaded with vocab size: {
|
|
|
|
| 219 |
|
| 220 |
# Configure model loading based on available hardware
|
| 221 |
load_kwargs = {
|
| 222 |
-
"torch_dtype": torch.
|
| 223 |
"trust_remote_code": False,
|
| 224 |
-
"device_map":
|
| 225 |
}
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
**load_kwargs
|
| 230 |
)
|
| 231 |
|
| 232 |
-
#
|
| 233 |
-
if DEVICE =
|
| 234 |
-
|
| 235 |
-
else:
|
| 236 |
-
phi_model = phi_model.to(DEVICE)
|
| 237 |
|
| 238 |
-
|
| 239 |
|
| 240 |
# Enable eval mode for inference optimizations
|
| 241 |
-
|
| 242 |
|
| 243 |
-
print(f"β
|
| 244 |
-
print(f" Model device: {
|
| 245 |
-
print(f" Model dtype: {
|
| 246 |
-
print(f" Model parameters: ~
|
| 247 |
-
|
|
|
|
| 248 |
|
| 249 |
except Exception as e:
|
| 250 |
-
print(f"β Failed to load
|
| 251 |
traceback.print_exc()
|
| 252 |
|
| 253 |
# Fallback: Try with simpler settings
|
| 254 |
try:
|
| 255 |
print("π Trying simpler loading method...")
|
| 256 |
-
|
| 257 |
-
if phi_tokenizer.pad_token is None:
|
| 258 |
-
phi_tokenizer.pad_token = phi_tokenizer.eos_token
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
torch_dtype=torch.float32
|
| 263 |
)
|
| 264 |
-
|
| 265 |
-
print(f"β
|
| 266 |
-
|
| 267 |
except Exception as e2:
|
| 268 |
print(f"β Fallback loading failed: {e2}")
|
| 269 |
-
|
| 270 |
-
|
| 271 |
|
| 272 |
print("="*50)
|
| 273 |
print(f"π MODEL LOADING SUMMARY:")
|
| 274 |
print(f" β’ Intent Model (82-class): {'β
' if intent_success else 'β'}")
|
| 275 |
print(f" β’ Emotion Model (28-label): {'β
' if emotion_success else 'β'}")
|
| 276 |
-
print(f" β’
|
| 277 |
print(f" β’ Device: {DEVICE}")
|
| 278 |
print(f" β’ Max Context: {MAX_CONTEXT_LENGTH} tokens")
|
| 279 |
print("="*50 + "\n")
|
| 280 |
|
| 281 |
-
return
|
| 282 |
|
| 283 |
async def cleanup_models():
|
| 284 |
"""Cleanup models on shutdown"""
|
|
@@ -303,7 +299,7 @@ async def lifespan(app: FastAPI):
|
|
| 303 |
|
| 304 |
model_loaded = await load_models()
|
| 305 |
if not model_loaded:
|
| 306 |
-
print("β οΈ CRITICAL:
|
| 307 |
|
| 308 |
yield
|
| 309 |
|
|
@@ -316,8 +312,8 @@ async def lifespan(app: FastAPI):
|
|
| 316 |
|
| 317 |
app = FastAPI(
|
| 318 |
title="GAKR AI Assistant (Enhanced with Intent & Emotion Detection)",
|
| 319 |
-
description="Three-stage AI pipeline with advanced intent detection, emotion analysis, and
|
| 320 |
-
version="
|
| 321 |
lifespan=lifespan
|
| 322 |
)
|
| 323 |
|
|
@@ -335,24 +331,24 @@ app.add_middleware(
|
|
| 335 |
|
| 336 |
def validate_prompt_length(prompt: str, max_length: int = MAX_CONTEXT_LENGTH) -> bool:
|
| 337 |
"""Validate prompt doesn't exceed context window"""
|
| 338 |
-
if not
|
| 339 |
return True
|
| 340 |
|
| 341 |
-
tokens =
|
| 342 |
return len(tokens) <= max_length
|
| 343 |
|
| 344 |
def get_truncated_prompt(prompt: str, max_tokens: int = 3072) -> str:
|
| 345 |
"""Truncate prompt to fit within context window"""
|
| 346 |
-
if not
|
| 347 |
return prompt[:1000]
|
| 348 |
|
| 349 |
-
tokens =
|
| 350 |
if len(tokens) <= max_tokens:
|
| 351 |
return prompt
|
| 352 |
|
| 353 |
# Truncate and add ellipsis
|
| 354 |
truncated_tokens = tokens[:max_tokens]
|
| 355 |
-
truncated_text =
|
| 356 |
return truncated_text + " [Content truncated...]"
|
| 357 |
|
| 358 |
# ================== ENHANCED INTENT DETECTION =================
|
|
@@ -616,8 +612,8 @@ async def generate_reply_stream(
|
|
| 616 |
print(f"βοΈ Parameters: max_tokens={max_tokens}, temperature={temperature}")
|
| 617 |
|
| 618 |
# Validate models
|
| 619 |
-
if not
|
| 620 |
-
error_msg = "
|
| 621 |
print(f"β {error_msg}")
|
| 622 |
yield json.dumps({
|
| 623 |
"type": "error",
|
|
@@ -688,40 +684,31 @@ async def generate_reply_stream(
|
|
| 688 |
except Exception as e:
|
| 689 |
print(f"β οΈ File error {f.filename}: {e}")
|
| 690 |
|
| 691 |
-
# ==== ENHANCED
|
| 692 |
try:
|
| 693 |
-
|
|
|
|
| 694 |
|
| 695 |
-
|
| 696 |
-
-
|
| 697 |
-
-
|
| 698 |
-
|
| 699 |
-
|
|
|
|
|
|
|
| 700 |
|
| 701 |
-
|
| 702 |
1. Adapt your tone to match the user's emotional state
|
| 703 |
2. Address the specific intent behind the query
|
| 704 |
3. Provide accurate, helpful information
|
| 705 |
4. Use appropriate formatting for clarity
|
| 706 |
5. Acknowledge limitations when uncertain
|
| 707 |
|
| 708 |
-
|
| 709 |
-
- Clear and concise
|
| 710 |
-
- Adapt to question complexity
|
| 711 |
-
- Focus on practical usefulness
|
| 712 |
-
- Avoid unnecessary repetition
|
| 713 |
-
|
| 714 |
-
Your goal: Provide the most helpful response possible."""
|
| 715 |
|
| 716 |
# Build context
|
| 717 |
context_parts = []
|
| 718 |
|
| 719 |
-
# Add intent context
|
| 720 |
-
context_parts.append(f"USER INTENT ANALYSIS:\n- Primary Intent: {intent_info['intent_label']}\n- Intent Category: {intent_info['broad_category']}\n- Confidence: {intent_info['confidence']:.1%}")
|
| 721 |
-
|
| 722 |
-
# Add emotion context
|
| 723 |
-
context_parts.append(f"USER EMOTIONAL STATE:\n- Primary Emotion: {emotion_info['primary_emotion']}\n- Emotional Tone: {emotion_info['emotional_tone']}\n- Confidence: {emotion_info['primary_confidence']:.1%}")
|
| 724 |
-
|
| 725 |
if tool_output:
|
| 726 |
context_parts.append(f"SEARCH RESULTS:\n{tool_output}")
|
| 727 |
if file_text:
|
|
@@ -729,60 +716,65 @@ Your goal: Provide the most helpful response possible."""
|
|
| 729 |
|
| 730 |
context = "\n\n".join(context_parts) if context_parts else "No additional context."
|
| 731 |
|
| 732 |
-
#
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
<|end|>
|
| 737 |
-
<|user|>
|
| 738 |
-
USER QUERY: {prompt}
|
| 739 |
-
EMOTIONAL CONTEXT:
|
| 740 |
-
- Detected user emotional tone: {emotion_info['primary_emotion']}
|
| 741 |
-
INTENT CONTEXT:
|
| 742 |
-
- Detected User intent category: {intent_info['intent_label']}
|
| 743 |
-
CONTEXTUAL ANALYSIS:
|
| 744 |
{context}
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 751 |
|
| 752 |
-
print(f"
|
| 753 |
-
print(f"π― Response will address: Intent='{intent_info['intent_label']}', Emotion='{emotion_info['primary_emotion']}'")
|
| 754 |
|
| 755 |
-
#
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
|
|
|
| 761 |
).to(DEVICE)
|
| 762 |
|
| 763 |
-
input_length =
|
| 764 |
print(f"π Tokenized input: {input_length} tokens")
|
| 765 |
|
| 766 |
# Create streamer
|
| 767 |
streamer = TextIteratorStreamer(
|
| 768 |
-
|
| 769 |
skip_prompt=True,
|
| 770 |
skip_special_tokens=True,
|
| 771 |
timeout=300.0
|
| 772 |
)
|
| 773 |
|
| 774 |
-
# OPTIMIZED GENERATION PARAMETERS
|
|
|
|
| 775 |
generation_config = {
|
| 776 |
-
|
| 777 |
"max_new_tokens": min(max_tokens, MAX_TOKENS_HARD_LIMIT),
|
| 778 |
"do_sample": temperature > 0,
|
| 779 |
"temperature": max(0.1, min(temperature, 1.0)),
|
| 780 |
-
"top_p": 0.
|
| 781 |
-
"top_k": 50,
|
| 782 |
-
"repetition_penalty": 1.
|
| 783 |
"no_repeat_ngram_size": 3,
|
| 784 |
-
"pad_token_id":
|
| 785 |
-
"eos_token_id":
|
| 786 |
"streamer": streamer,
|
| 787 |
"use_cache": True, # Enable KV cache
|
| 788 |
}
|
|
@@ -795,9 +787,10 @@ Your goal: Provide the most helpful response possible. <|end|>
|
|
| 795 |
generation_config.pop("top_k", None)
|
| 796 |
|
| 797 |
print(f"π§ Generation params: max_new_tokens={generation_config['max_new_tokens']}, temp={temperature}")
|
|
|
|
| 798 |
|
| 799 |
# Start generation thread
|
| 800 |
-
thread = Thread(target=
|
| 801 |
thread.start()
|
| 802 |
|
| 803 |
print("π Started streaming generation")
|
|
@@ -808,7 +801,8 @@ Your goal: Provide the most helpful response possible. <|end|>
|
|
| 808 |
"data": {
|
| 809 |
"timestamp": time.time(),
|
| 810 |
"intent": intent_info,
|
| 811 |
-
"emotion": emotion_info
|
|
|
|
| 812 |
}
|
| 813 |
}, ensure_ascii=False) + "\n\n"
|
| 814 |
|
|
@@ -848,6 +842,7 @@ Your goal: Provide the most helpful response possible. <|end|>
|
|
| 848 |
"intent": intent_info,
|
| 849 |
"emotion": emotion_info,
|
| 850 |
"tool_used": tool_decision.get("tool"),
|
|
|
|
| 851 |
"response_characteristics": {
|
| 852 |
"emotion_aware": True,
|
| 853 |
"intent_aware": True,
|
|
@@ -883,7 +878,7 @@ async def home(request: Request):
|
|
| 883 |
"""Serve homepage"""
|
| 884 |
return templates.TemplateResponse("index.html", {
|
| 885 |
"request": request,
|
| 886 |
-
"model_name": "
|
| 887 |
"intent_model": INTENT_MODEL_NAME,
|
| 888 |
"emotion_model": EMOTION_MODEL_NAME,
|
| 889 |
"environment": ENVIRONMENT
|
|
@@ -908,8 +903,8 @@ async def analyze(
|
|
| 908 |
|
| 909 |
print(f"\nπ¨ Request: '{prompt[:50]}...' | tokens={max_tokens} | temp={temperature}")
|
| 910 |
|
| 911 |
-
if not
|
| 912 |
-
raise HTTPException(503, "
|
| 913 |
|
| 914 |
async def event_stream():
|
| 915 |
try:
|
|
@@ -931,16 +926,16 @@ async def analyze(
|
|
| 931 |
async def health():
|
| 932 |
"""Health check"""
|
| 933 |
return {
|
| 934 |
-
"status": "healthy" if
|
| 935 |
"models": {
|
| 936 |
-
"
|
| 937 |
"intent_model": INTENT_MODEL_NAME,
|
| 938 |
"emotion_model": EMOTION_MODEL_NAME
|
| 939 |
},
|
| 940 |
"loaded": {
|
| 941 |
"intent_loaded": intent_model is not None,
|
| 942 |
"emotion_loaded": emotion_model is not None,
|
| 943 |
-
"
|
| 944 |
},
|
| 945 |
"device": DEVICE,
|
| 946 |
"cuda_available": torch.cuda.is_available(),
|
|
@@ -953,7 +948,7 @@ async def config():
|
|
| 953 |
"""Configuration endpoint"""
|
| 954 |
return {
|
| 955 |
"models": {
|
| 956 |
-
"
|
| 957 |
"intent_model": INTENT_MODEL_NAME,
|
| 958 |
"emotion_model": EMOTION_MODEL_NAME
|
| 959 |
},
|
|
@@ -982,13 +977,23 @@ async def model_info():
|
|
| 982 |
"""Detailed model information"""
|
| 983 |
info = {
|
| 984 |
"models": {
|
| 985 |
-
"
|
| 986 |
-
"name": "
|
| 987 |
-
"publisher": "
|
| 988 |
-
"parameters": "
|
| 989 |
-
"context_length": "
|
| 990 |
-
"license": "
|
| 991 |
-
"description": "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 992 |
},
|
| 993 |
"intent_detector": {
|
| 994 |
"name": "AshokGakr/intent_detector",
|
|
@@ -1014,11 +1019,12 @@ async def model_info():
|
|
| 1014 |
}
|
| 1015 |
}
|
| 1016 |
|
| 1017 |
-
if
|
| 1018 |
-
info["models"]["
|
| 1019 |
"loaded": True,
|
| 1020 |
-
"device": str(
|
| 1021 |
-
"dtype": str(
|
|
|
|
| 1022 |
})
|
| 1023 |
|
| 1024 |
if intent_model:
|
|
@@ -1047,13 +1053,51 @@ async def detect_emotion_endpoint(text: str = Form(...)):
|
|
| 1047 |
result = detect_emotion_enhanced(text)
|
| 1048 |
return result
|
| 1049 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1050 |
@app.get("/api/debug-stream")
|
| 1051 |
async def debug_stream():
|
| 1052 |
"""Test streaming with intent/emotion simulation"""
|
| 1053 |
async def event_stream():
|
| 1054 |
-
yield f"data: {json.dumps({'type': 'context', 'data': {'test': '
|
| 1055 |
|
| 1056 |
-
test_msg = "This is
|
| 1057 |
words = test_msg.split()
|
| 1058 |
|
| 1059 |
for i, word in enumerate(words):
|
|
@@ -1091,11 +1135,13 @@ if __name__ == "__main__":
|
|
| 1091 |
import uvicorn
|
| 1092 |
|
| 1093 |
print("\n" + "="*50)
|
| 1094 |
-
print("π§ ENHANCED GAKR AI - WITH INTENT & EMOTION DETECTION")
|
| 1095 |
print("="*50)
|
| 1096 |
print(f"π― Intent Model: {INTENT_MODEL_NAME} (82 classes)")
|
| 1097 |
print(f"π Emotion Model: {EMOTION_MODEL_NAME} (28 labels)")
|
| 1098 |
-
print(f"π§
|
|
|
|
|
|
|
| 1099 |
print("="*50)
|
| 1100 |
|
| 1101 |
uvicorn.run(
|
|
|
|
| 1 |
"""
|
| 2 |
+
FastAPI backend with optimized streaming for LFM2.5-1.2B-Instruct
|
| 3 |
Enhanced with advanced intent detection (AshokGakr/intent_detector)
|
| 4 |
and emotion detection (AshokGakr/emotions_detector) models
|
| 5 |
"""
|
|
|
|
| 48 |
INTENT_MODEL_NAME = "AshokGakr/intent_detector" # 82 intent classes
|
| 49 |
EMOTION_MODEL_NAME = "AshokGakr/emotions_detector" # 28 emotion labels (multi-label)
|
| 50 |
|
| 51 |
+
# LFM2.5-1.2B-Instruct model - Liquid AI
|
| 52 |
+
LFM_MODEL_NAME = "LiquidAI/LFM2.5-1.2B-Instruct"
|
| 53 |
|
| 54 |
MAX_FILE_SIZE = 50 * 1024 * 1024
|
| 55 |
MAX_TOKENS_DEFAULT = 1024
|
| 56 |
MAX_TOKENS_HARD_LIMIT = 4096 # Conservative limit for stability
|
| 57 |
+
DEFAULT_TEMPERATURE = 0.7 # LFM2.5 default is 0.1, but keep adjustable
|
| 58 |
STREAM_DELAY = 0.02
|
| 59 |
+
MAX_CONTEXT_LENGTH = 8192 # Safe context length for LFM2.5 (max 32768)
|
| 60 |
|
| 61 |
# Global model variables
|
| 62 |
intent_tokenizer = None
|
| 63 |
intent_model = None
|
| 64 |
emotion_tokenizer = None
|
| 65 |
emotion_model = None
|
| 66 |
+
lfm_tokenizer = None
|
| 67 |
+
lfm_model = None
|
| 68 |
|
| 69 |
# Setup directories
|
| 70 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
| 143 |
# ================== MODEL LOADING =================
|
| 144 |
|
| 145 |
async def load_models():
|
| 146 |
+
"""Load and initialize all ML models with optimized settings for LFM2.5"""
|
| 147 |
global intent_tokenizer, intent_model, emotion_tokenizer, emotion_model
|
| 148 |
+
global lfm_tokenizer, lfm_model
|
| 149 |
|
| 150 |
print("\n" + "="*50)
|
| 151 |
print("π LOADING AI MODELS - ENHANCED WITH INTENT & EMOTION DETECTION")
|
|
|
|
| 197 |
emotion_tokenizer = None
|
| 198 |
emotion_model = None
|
| 199 |
|
| 200 |
+
# ==== OPTIMIZED LFM2.5 LOADING ====
|
| 201 |
+
lfm_success = False
|
| 202 |
try:
|
| 203 |
+
print(f"π₯ Loading LFM2.5-1.2B-Instruct model")
|
| 204 |
|
| 205 |
+
# Load tokenizer with correct settings
|
| 206 |
+
lfm_tokenizer = AutoTokenizer.from_pretrained(
|
| 207 |
+
LFM_MODEL_NAME,
|
| 208 |
padding_side="left", # Essential for streaming
|
| 209 |
+
trust_remote_code=False,
|
| 210 |
+
use_fast=True
|
| 211 |
)
|
| 212 |
|
| 213 |
+
# IMPORTANT: LFM2.5 uses special tokens <|im_start|> and <|im_end|>
|
| 214 |
+
# No need to set pad token separately as the tokenizer handles it
|
|
|
|
|
|
|
| 215 |
|
| 216 |
+
print(f" Tokenizer loaded with vocab size: {lfm_tokenizer.vocab_size}")
|
| 217 |
+
print(f" Chat template available: {lfm_tokenizer.chat_template is not None}")
|
| 218 |
|
| 219 |
# Configure model loading based on available hardware
|
| 220 |
load_kwargs = {
|
| 221 |
+
"torch_dtype": torch.bfloat16 if DEVICE == "cuda" else torch.float32,
|
| 222 |
"trust_remote_code": False,
|
| 223 |
+
"device_map": "auto" if DEVICE == "cuda" else None,
|
| 224 |
}
|
| 225 |
|
| 226 |
+
lfm_model = AutoModelForCausalLM.from_pretrained(
|
| 227 |
+
LFM_MODEL_NAME,
|
| 228 |
**load_kwargs
|
| 229 |
)
|
| 230 |
|
| 231 |
+
# If device_map not used, manually move to device
|
| 232 |
+
if DEVICE != "cuda" or load_kwargs.get("device_map") is None:
|
| 233 |
+
lfm_model = lfm_model.to(DEVICE)
|
|
|
|
|
|
|
| 234 |
|
| 235 |
+
lfm_model.eval()
|
| 236 |
|
| 237 |
# Enable eval mode for inference optimizations
|
| 238 |
+
lfm_model.config.use_cache = True # Enable KV cache for faster generation
|
| 239 |
|
| 240 |
+
print(f"β
LFM2.5-1.2B-Instruct loaded successfully")
|
| 241 |
+
print(f" Model device: {lfm_model.device}")
|
| 242 |
+
print(f" Model dtype: {lfm_model.dtype}")
|
| 243 |
+
print(f" Model parameters: ~1.2B")
|
| 244 |
+
print(f" Context window: 32,768 tokens")
|
| 245 |
+
lfm_success = True
|
| 246 |
|
| 247 |
except Exception as e:
|
| 248 |
+
print(f"β Failed to load LFM2.5 model: {e}")
|
| 249 |
traceback.print_exc()
|
| 250 |
|
| 251 |
# Fallback: Try with simpler settings
|
| 252 |
try:
|
| 253 |
print("π Trying simpler loading method...")
|
| 254 |
+
lfm_tokenizer = AutoTokenizer.from_pretrained(LFM_MODEL_NAME)
|
|
|
|
|
|
|
| 255 |
|
| 256 |
+
lfm_model = AutoModelForCausalLM.from_pretrained(
|
| 257 |
+
LFM_MODEL_NAME,
|
| 258 |
torch_dtype=torch.float32
|
| 259 |
)
|
| 260 |
+
lfm_model.to(DEVICE).eval()
|
| 261 |
+
print(f"β
LFM2.5 model loaded (fallback method)")
|
| 262 |
+
lfm_success = True
|
| 263 |
except Exception as e2:
|
| 264 |
print(f"β Fallback loading failed: {e2}")
|
| 265 |
+
lfm_tokenizer = None
|
| 266 |
+
lfm_model = None
|
| 267 |
|
| 268 |
print("="*50)
|
| 269 |
print(f"π MODEL LOADING SUMMARY:")
|
| 270 |
print(f" β’ Intent Model (82-class): {'β
' if intent_success else 'β'}")
|
| 271 |
print(f" β’ Emotion Model (28-label): {'β
' if emotion_success else 'β'}")
|
| 272 |
+
print(f" β’ LFM2.5 Model: {'β
' if lfm_success else 'β'}")
|
| 273 |
print(f" β’ Device: {DEVICE}")
|
| 274 |
print(f" β’ Max Context: {MAX_CONTEXT_LENGTH} tokens")
|
| 275 |
print("="*50 + "\n")
|
| 276 |
|
| 277 |
+
return lfm_success
|
| 278 |
|
| 279 |
async def cleanup_models():
|
| 280 |
"""Cleanup models on shutdown"""
|
|
|
|
| 299 |
|
| 300 |
model_loaded = await load_models()
|
| 301 |
if not model_loaded:
|
| 302 |
+
print("β οΈ CRITICAL: LFM2.5 model not loaded. Assistant will not function.")
|
| 303 |
|
| 304 |
yield
|
| 305 |
|
|
|
|
| 312 |
|
| 313 |
app = FastAPI(
|
| 314 |
title="GAKR AI Assistant (Enhanced with Intent & Emotion Detection)",
|
| 315 |
+
description="Three-stage AI pipeline with advanced intent detection, emotion analysis, and LFM2.5-1.2B-Instruct",
|
| 316 |
+
version="5.0.0",
|
| 317 |
lifespan=lifespan
|
| 318 |
)
|
| 319 |
|
|
|
|
| 331 |
|
| 332 |
def validate_prompt_length(prompt: str, max_length: int = MAX_CONTEXT_LENGTH) -> bool:
|
| 333 |
"""Validate prompt doesn't exceed context window"""
|
| 334 |
+
if not lfm_tokenizer:
|
| 335 |
return True
|
| 336 |
|
| 337 |
+
tokens = lfm_tokenizer.encode(prompt, truncation=False)
|
| 338 |
return len(tokens) <= max_length
|
| 339 |
|
| 340 |
def get_truncated_prompt(prompt: str, max_tokens: int = 3072) -> str:
|
| 341 |
"""Truncate prompt to fit within context window"""
|
| 342 |
+
if not lfm_tokenizer:
|
| 343 |
return prompt[:1000]
|
| 344 |
|
| 345 |
+
tokens = lfm_tokenizer.encode(prompt, truncation=False)
|
| 346 |
if len(tokens) <= max_tokens:
|
| 347 |
return prompt
|
| 348 |
|
| 349 |
# Truncate and add ellipsis
|
| 350 |
truncated_tokens = tokens[:max_tokens]
|
| 351 |
+
truncated_text = lfm_tokenizer.decode(truncated_tokens, skip_special_tokens=True)
|
| 352 |
return truncated_text + " [Content truncated...]"
|
| 353 |
|
| 354 |
# ================== ENHANCED INTENT DETECTION =================
|
|
|
|
| 612 |
print(f"βοΈ Parameters: max_tokens={max_tokens}, temperature={temperature}")
|
| 613 |
|
| 614 |
# Validate models
|
| 615 |
+
if not lfm_model or not lfm_tokenizer:
|
| 616 |
+
error_msg = "LFM2.5 model not available. Please check server health."
|
| 617 |
print(f"β {error_msg}")
|
| 618 |
yield json.dumps({
|
| 619 |
"type": "error",
|
|
|
|
| 684 |
except Exception as e:
|
| 685 |
print(f"β οΈ File error {f.filename}: {e}")
|
| 686 |
|
| 687 |
+
# ==== ENHANCED LFM2.5 GENERATION WITH EMOTIONAL INTELLIGENCE ====
|
| 688 |
try:
|
| 689 |
+
# Build system message with emotional intelligence
|
| 690 |
+
system_message = f"""You are GAKR AI, a helpful and knowledgeable assistant trained by Liquid AI.
|
| 691 |
|
| 692 |
+
EMOTIONAL CONTEXT:
|
| 693 |
+
- Detected user emotional tone: {emotion_info['emotional_tone'].upper()}
|
| 694 |
+
- Primary emotion: {emotion_info['primary_emotion']}
|
| 695 |
+
|
| 696 |
+
INTENT CONTEXT:
|
| 697 |
+
- User intent category: {intent_info['broad_category'].upper()}
|
| 698 |
+
- Specific intent: {intent_info['intent_label']}
|
| 699 |
|
| 700 |
+
RESPONSE GUIDELINES:
|
| 701 |
1. Adapt your tone to match the user's emotional state
|
| 702 |
2. Address the specific intent behind the query
|
| 703 |
3. Provide accurate, helpful information
|
| 704 |
4. Use appropriate formatting for clarity
|
| 705 |
5. Acknowledge limitations when uncertain
|
| 706 |
|
| 707 |
+
Your goal: Provide the most emotionally intelligent and contextually appropriate response possible."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 708 |
|
| 709 |
# Build context
|
| 710 |
context_parts = []
|
| 711 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 712 |
if tool_output:
|
| 713 |
context_parts.append(f"SEARCH RESULTS:\n{tool_output}")
|
| 714 |
if file_text:
|
|
|
|
| 716 |
|
| 717 |
context = "\n\n".join(context_parts) if context_parts else "No additional context."
|
| 718 |
|
| 719 |
+
# Build full user message with all context
|
| 720 |
+
full_user_message = f"""USER QUERY: {prompt}
|
| 721 |
+
|
| 722 |
+
ADDITIONAL CONTEXT:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
{context}
|
| 724 |
+
|
| 725 |
+
USER ANALYSIS:
|
| 726 |
+
- Detected Intent: {intent_info['intent_label']} (confidence: {intent_info['confidence']:.1%})
|
| 727 |
+
- Detected Emotion: {emotion_info['primary_emotion']} (tone: {emotion_info['emotional_tone']})
|
| 728 |
+
- Emotional Confidence: {emotion_info['primary_confidence']:.1%}
|
| 729 |
+
|
| 730 |
+
Please provide a helpful response that:
|
| 731 |
+
1. Addresses the specific intent ({intent_info['intent_label']})
|
| 732 |
+
2. Appropriately responds to the emotional tone ({emotion_info['emotional_tone']})
|
| 733 |
+
3. Incorporates relevant information from the context
|
| 734 |
+
4. Provides practical, helpful assistance"""
|
| 735 |
+
|
| 736 |
+
# Create messages for LFM2.5 chat template
|
| 737 |
+
# LFM2.5 uses ChatML format: <|im_start|>role\ncontent<|im_end|>
|
| 738 |
+
messages = [
|
| 739 |
+
{"role": "system", "content": system_message},
|
| 740 |
+
{"role": "user", "content": full_user_message}
|
| 741 |
+
]
|
| 742 |
|
| 743 |
+
print(f"π Messages prepared for LFM2.5 chat template")
|
|
|
|
| 744 |
|
| 745 |
+
# Apply chat template - LFM2.5 automatically handles the ChatML format
|
| 746 |
+
# The tokenizer has built-in chat template that matches the model's training format
|
| 747 |
+
input_ids = lfm_tokenizer.apply_chat_template(
|
| 748 |
+
messages,
|
| 749 |
+
tokenize=True,
|
| 750 |
+
add_generation_prompt=True,
|
| 751 |
+
return_tensors="pt"
|
| 752 |
).to(DEVICE)
|
| 753 |
|
| 754 |
+
input_length = input_ids.shape[1]
|
| 755 |
print(f"π Tokenized input: {input_length} tokens")
|
| 756 |
|
| 757 |
# Create streamer
|
| 758 |
streamer = TextIteratorStreamer(
|
| 759 |
+
lfm_tokenizer,
|
| 760 |
skip_prompt=True,
|
| 761 |
skip_special_tokens=True,
|
| 762 |
timeout=300.0
|
| 763 |
)
|
| 764 |
|
| 765 |
+
# LFM2.5 OPTIMIZED GENERATION PARAMETERS
|
| 766 |
+
# Based on official recommendations from model card
|
| 767 |
generation_config = {
|
| 768 |
+
"input_ids": input_ids,
|
| 769 |
"max_new_tokens": min(max_tokens, MAX_TOKENS_HARD_LIMIT),
|
| 770 |
"do_sample": temperature > 0,
|
| 771 |
"temperature": max(0.1, min(temperature, 1.0)),
|
| 772 |
+
"top_p": 0.1, # LFM2.5 default
|
| 773 |
+
"top_k": 50, # LFM2.5 default
|
| 774 |
+
"repetition_penalty": 1.05, # LFM2.5 default
|
| 775 |
"no_repeat_ngram_size": 3,
|
| 776 |
+
"pad_token_id": lfm_tokenizer.pad_token_id,
|
| 777 |
+
"eos_token_id": lfm_tokenizer.eos_token_id,
|
| 778 |
"streamer": streamer,
|
| 779 |
"use_cache": True, # Enable KV cache
|
| 780 |
}
|
|
|
|
| 787 |
generation_config.pop("top_k", None)
|
| 788 |
|
| 789 |
print(f"π§ Generation params: max_new_tokens={generation_config['max_new_tokens']}, temp={temperature}")
|
| 790 |
+
print(f"π Model will generate with: top_p=0.1, top_k=50, repetition_penalty=1.05")
|
| 791 |
|
| 792 |
# Start generation thread
|
| 793 |
+
thread = Thread(target=lfm_model.generate, kwargs=generation_config)
|
| 794 |
thread.start()
|
| 795 |
|
| 796 |
print("π Started streaming generation")
|
|
|
|
| 801 |
"data": {
|
| 802 |
"timestamp": time.time(),
|
| 803 |
"intent": intent_info,
|
| 804 |
+
"emotion": emotion_info,
|
| 805 |
+
"model": LFM_MODEL_NAME
|
| 806 |
}
|
| 807 |
}, ensure_ascii=False) + "\n\n"
|
| 808 |
|
|
|
|
| 842 |
"intent": intent_info,
|
| 843 |
"emotion": emotion_info,
|
| 844 |
"tool_used": tool_decision.get("tool"),
|
| 845 |
+
"model": LFM_MODEL_NAME,
|
| 846 |
"response_characteristics": {
|
| 847 |
"emotion_aware": True,
|
| 848 |
"intent_aware": True,
|
|
|
|
| 878 |
"""Serve homepage"""
|
| 879 |
return templates.TemplateResponse("index.html", {
|
| 880 |
"request": request,
|
| 881 |
+
"model_name": "LFM2.5-1.2B-Instruct",
|
| 882 |
"intent_model": INTENT_MODEL_NAME,
|
| 883 |
"emotion_model": EMOTION_MODEL_NAME,
|
| 884 |
"environment": ENVIRONMENT
|
|
|
|
| 903 |
|
| 904 |
print(f"\nπ¨ Request: '{prompt[:50]}...' | tokens={max_tokens} | temp={temperature}")
|
| 905 |
|
| 906 |
+
if not lfm_model:
|
| 907 |
+
raise HTTPException(503, "LFM2.5 model not loaded. Check server health.")
|
| 908 |
|
| 909 |
async def event_stream():
|
| 910 |
try:
|
|
|
|
| 926 |
async def health():
|
| 927 |
"""Health check"""
|
| 928 |
return {
|
| 929 |
+
"status": "healthy" if lfm_model else "degraded",
|
| 930 |
"models": {
|
| 931 |
+
"main_model": LFM_MODEL_NAME,
|
| 932 |
"intent_model": INTENT_MODEL_NAME,
|
| 933 |
"emotion_model": EMOTION_MODEL_NAME
|
| 934 |
},
|
| 935 |
"loaded": {
|
| 936 |
"intent_loaded": intent_model is not None,
|
| 937 |
"emotion_loaded": emotion_model is not None,
|
| 938 |
+
"lfm_loaded": lfm_model is not None
|
| 939 |
},
|
| 940 |
"device": DEVICE,
|
| 941 |
"cuda_available": torch.cuda.is_available(),
|
|
|
|
| 948 |
"""Configuration endpoint"""
|
| 949 |
return {
|
| 950 |
"models": {
|
| 951 |
+
"main_model": LFM_MODEL_NAME,
|
| 952 |
"intent_model": INTENT_MODEL_NAME,
|
| 953 |
"emotion_model": EMOTION_MODEL_NAME
|
| 954 |
},
|
|
|
|
| 977 |
"""Detailed model information"""
|
| 978 |
info = {
|
| 979 |
"models": {
|
| 980 |
+
"lfm2.5": {
|
| 981 |
+
"name": "LFM2.5-1.2B-Instruct",
|
| 982 |
+
"publisher": "Liquid AI",
|
| 983 |
+
"parameters": "1.2B",
|
| 984 |
+
"context_length": "32,768 tokens",
|
| 985 |
+
"license": "Apache 2.0",
|
| 986 |
+
"description": "Hybrid model designed for on-device deployment with extended pre-training and reinforcement learning",
|
| 987 |
+
"capabilities": ["Reasoning", "Coding", "Mathematics", "Multilingual (8 languages)", "Tool Use"],
|
| 988 |
+
"optimized_for": ["Edge deployment", "Low-latency applications", "Memory-constrained environments"],
|
| 989 |
+
"default_generation_params": {
|
| 990 |
+
"temperature": 0.1,
|
| 991 |
+
"top_p": 0.1,
|
| 992 |
+
"top_k": 50,
|
| 993 |
+
"repetition_penalty": 1.05
|
| 994 |
+
},
|
| 995 |
+
"chat_template": "ChatML format (<|im_start|>role\\ncontent<|im_end|>)",
|
| 996 |
+
"special_tokens": ["<|im_start|>", "<|im_end|>", "<|endoftext|>"]
|
| 997 |
},
|
| 998 |
"intent_detector": {
|
| 999 |
"name": "AshokGakr/intent_detector",
|
|
|
|
| 1019 |
}
|
| 1020 |
}
|
| 1021 |
|
| 1022 |
+
if lfm_model:
|
| 1023 |
+
info["models"]["lfm2.5"].update({
|
| 1024 |
"loaded": True,
|
| 1025 |
+
"device": str(lfm_model.device),
|
| 1026 |
+
"dtype": str(lfm_model.dtype),
|
| 1027 |
+
"tokenizer_chat_template": lfm_tokenizer.chat_template is not None
|
| 1028 |
})
|
| 1029 |
|
| 1030 |
if intent_model:
|
|
|
|
| 1053 |
result = detect_emotion_enhanced(text)
|
| 1054 |
return result
|
| 1055 |
|
| 1056 |
+
@app.post("/api/test-lfm-template")
|
| 1057 |
+
async def test_lfm_template(text: str = Form(...), system_prompt: str = Form(None)):
|
| 1058 |
+
"""Test LFM2.5 chat template formatting"""
|
| 1059 |
+
if not lfm_tokenizer:
|
| 1060 |
+
raise HTTPException(503, "LFM2.5 tokenizer not loaded")
|
| 1061 |
+
|
| 1062 |
+
system_msg = system_prompt or "You are a helpful AI assistant."
|
| 1063 |
+
|
| 1064 |
+
messages = [
|
| 1065 |
+
{"role": "system", "content": system_msg},
|
| 1066 |
+
{"role": "user", "content": text}
|
| 1067 |
+
]
|
| 1068 |
+
|
| 1069 |
+
try:
|
| 1070 |
+
# Apply chat template
|
| 1071 |
+
formatted = lfm_tokenizer.apply_chat_template(
|
| 1072 |
+
messages,
|
| 1073 |
+
tokenize=False,
|
| 1074 |
+
add_generation_prompt=True
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
# Decode to see the format
|
| 1078 |
+
decoded = lfm_tokenizer.decode(lfm_tokenizer.encode(formatted), skip_special_tokens=False)
|
| 1079 |
+
|
| 1080 |
+
return {
|
| 1081 |
+
"formatted_template": formatted,
|
| 1082 |
+
"decoded": decoded,
|
| 1083 |
+
"messages": messages,
|
| 1084 |
+
"special_tokens": {
|
| 1085 |
+
"im_start": "<|im_start|>",
|
| 1086 |
+
"im_end": "<|im_end|>",
|
| 1087 |
+
"eos_token": lfm_tokenizer.eos_token,
|
| 1088 |
+
"pad_token": lfm_tokenizer.pad_token
|
| 1089 |
+
}
|
| 1090 |
+
}
|
| 1091 |
+
except Exception as e:
|
| 1092 |
+
raise HTTPException(500, f"Template error: {str(e)}")
|
| 1093 |
+
|
| 1094 |
@app.get("/api/debug-stream")
|
| 1095 |
async def debug_stream():
|
| 1096 |
"""Test streaming with intent/emotion simulation"""
|
| 1097 |
async def event_stream():
|
| 1098 |
+
yield f"data: {json.dumps({'type': 'context', 'data': {'test': 'LFM2.5 streaming test', 'intent': {'intent_label': 'greeting', 'confidence': 0.95}, 'emotion': {'primary_emotion': 'joy', 'emotional_tone': 'positive'}}}, ensure_ascii=False)}\n\n"
|
| 1099 |
|
| 1100 |
+
test_msg = "This is a streaming test from LFM2.5-1.2B-Instruct backend with intent and emotion awareness. "
|
| 1101 |
words = test_msg.split()
|
| 1102 |
|
| 1103 |
for i, word in enumerate(words):
|
|
|
|
| 1135 |
import uvicorn
|
| 1136 |
|
| 1137 |
print("\n" + "="*50)
|
| 1138 |
+
print("π§ ENHANCED GAKR AI - LFM2.5 WITH INTENT & EMOTION DETECTION")
|
| 1139 |
print("="*50)
|
| 1140 |
print(f"π― Intent Model: {INTENT_MODEL_NAME} (82 classes)")
|
| 1141 |
print(f"π Emotion Model: {EMOTION_MODEL_NAME} (28 labels)")
|
| 1142 |
+
print(f"π§ LFM2.5 Model: {LFM_MODEL_NAME}")
|
| 1143 |
+
print(f"β‘ Context Window: 32,768 tokens")
|
| 1144 |
+
print(f"ποΈ Chat Template: ChatML format")
|
| 1145 |
print("="*50)
|
| 1146 |
|
| 1147 |
uvicorn.run(
|