AshokGakr commited on
Commit
92a79ca
Β·
verified Β·
1 Parent(s): 7658d24

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -141
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- FastAPI backend with optimized streaming for Phi-3.5-mini-instruct
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
- # Phi-3.5-mini-instruct model - OFFICIAL MICROSOFT MODEL
52
- PHI_MODEL_NAME = "microsoft/Phi-3.5-mini-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
58
  STREAM_DELAY = 0.02
59
- MAX_CONTEXT_LENGTH = 4096 # Safe context length for Phi-3.5-mini
60
 
61
  # Global model variables
62
  intent_tokenizer = None
63
  intent_model = None
64
  emotion_tokenizer = None
65
  emotion_model = None
66
- phi_tokenizer = None
67
- phi_model = None
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 phi_tokenizer, phi_model
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 PHI-3.5 LOADING ====
201
- phi_success = False
202
  try:
203
- print(f"πŸ“₯ Loading Phi-3.5-mini-instruct model")
204
 
205
- # CRITICAL: Load tokenizer with correct settings
206
- phi_tokenizer = AutoTokenizer.from_pretrained(
207
- PHI_MODEL_NAME,
208
  padding_side="left", # Essential for streaming
209
- trust_remote_code=False, # Official model doesn't need this
210
- use_fast=True # Use fast tokenizer
211
  )
212
 
213
- # IMPORTANT: Phi-3.5 requires explicit pad token setting
214
- if phi_tokenizer.pad_token is None:
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: {phi_tokenizer.vocab_size}")
 
219
 
220
  # Configure model loading based on available hardware
221
  load_kwargs = {
222
- "torch_dtype": torch.float16 if DEVICE == "cuda" else torch.float32,
223
  "trust_remote_code": False,
224
- "device_map": None, # We'll handle device placement manually
225
  }
226
 
227
- phi_model = AutoModelForCausalLM.from_pretrained(
228
- PHI_MODEL_NAME,
229
  **load_kwargs
230
  )
231
 
232
- # Manual device placement for better control
233
- if DEVICE == "cuda":
234
- phi_model = phi_model.cuda()
235
- else:
236
- phi_model = phi_model.to(DEVICE)
237
 
238
- phi_model.eval()
239
 
240
  # Enable eval mode for inference optimizations
241
- phi_model.config.use_cache = True # Enable KV cache for faster generation
242
 
243
- print(f"βœ… Phi-3.5-mini-instruct loaded successfully")
244
- print(f" Model device: {phi_model.device}")
245
- print(f" Model dtype: {phi_model.dtype}")
246
- print(f" Model parameters: ~3.8B")
247
- phi_success = True
 
248
 
249
  except Exception as e:
250
- print(f"❌ Failed to load phi model: {e}")
251
  traceback.print_exc()
252
 
253
  # Fallback: Try with simpler settings
254
  try:
255
  print("πŸ”„ Trying simpler loading method...")
256
- phi_tokenizer = AutoTokenizer.from_pretrained(PHI_MODEL_NAME)
257
- if phi_tokenizer.pad_token is None:
258
- phi_tokenizer.pad_token = phi_tokenizer.eos_token
259
 
260
- phi_model = AutoModelForCausalLM.from_pretrained(
261
- PHI_MODEL_NAME,
262
  torch_dtype=torch.float32
263
  )
264
- phi_model.to(DEVICE).eval()
265
- print(f"βœ… Phi-3.5 model loaded (fallback method)")
266
- phi_success = True
267
  except Exception as e2:
268
  print(f"❌ Fallback loading failed: {e2}")
269
- phi_tokenizer = None
270
- phi_model = None
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" β€’ Phi-3.5 Model: {'βœ…' if phi_success else '❌'}")
277
  print(f" β€’ Device: {DEVICE}")
278
  print(f" β€’ Max Context: {MAX_CONTEXT_LENGTH} tokens")
279
  print("="*50 + "\n")
280
 
281
- return phi_success
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: Phi-3.5 model not loaded. Assistant will not function.")
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 Phi-3.5-mini-instruct",
320
- version="4.0.0",
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 phi_tokenizer:
339
  return True
340
 
341
- tokens = phi_tokenizer.encode(prompt, truncation=False)
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 phi_tokenizer:
347
  return prompt[:1000]
348
 
349
- tokens = phi_tokenizer.encode(prompt, truncation=False)
350
  if len(tokens) <= max_tokens:
351
  return prompt
352
 
353
  # Truncate and add ellipsis
354
  truncated_tokens = tokens[:max_tokens]
355
- truncated_text = phi_tokenizer.decode(truncated_tokens, skip_special_tokens=True)
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 phi_model or not phi_tokenizer:
620
- error_msg = "AI model not available. Please check server health."
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 PHI-3.5 GENERATION WITH EMOTIONAL INTELLIGENCE ====
692
  try:
693
- system_message = f"""You are GAKR AI, a helpful and knowledgeable assistant.
 
694
 
695
- RESPONSE APPROACH:
696
- - Start with the most direct answer
697
- - Provide supporting details when helpful
698
- - Use simple formatting (bullets, bold) for clarity
699
- - Be accurate and acknowledge uncertainty
 
 
700
 
701
- CORE PRINCIPLES:
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
- COMMUNICATION STYLE:
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
- # Format according to Phi-3.5 chat template with emotional intelligence
733
- chat_template = f"""<|system|>
734
- {system_message}
735
- IMPORTANT: You must stay in character as GAKR AI at all times.
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
- instruction = f"Match your tone to the user's {emotion_info['primary_emotion']} emotion and
746
- take a clear, goal-focused approach to handle the {intent_info['intent_label']} intent."
747
- Incorporates relevant information from the context
748
- Your goal: Provide the most helpful response possible. <|end|>
749
- <|assistant|>
750
- """
 
 
 
 
 
 
 
 
 
 
 
 
751
 
752
- print(f"πŸ” Prepared chat template length: {len(chat_template)} chars")
753
- print(f"🎯 Response will address: Intent='{intent_info['intent_label']}', Emotion='{emotion_info['primary_emotion']}'")
754
 
755
- # Tokenize with proper settings
756
- inputs = phi_tokenizer(
757
- chat_template,
758
- return_tensors="pt",
759
- truncation=True,
760
- max_length=MAX_CONTEXT_LENGTH - max_tokens,
 
761
  ).to(DEVICE)
762
 
763
- input_length = inputs['input_ids'].shape[1]
764
  print(f"πŸ” Tokenized input: {input_length} tokens")
765
 
766
  # Create streamer
767
  streamer = TextIteratorStreamer(
768
- phi_tokenizer,
769
  skip_prompt=True,
770
  skip_special_tokens=True,
771
  timeout=300.0
772
  )
773
 
774
- # OPTIMIZED GENERATION PARAMETERS FOR PHI-3.5
 
775
  generation_config = {
776
- **inputs,
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.9,
781
- "top_k": 50,
782
- "repetition_penalty": 1.1,
783
  "no_repeat_ngram_size": 3,
784
- "pad_token_id": phi_tokenizer.pad_token_id,
785
- "eos_token_id": phi_tokenizer.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=phi_model.generate, kwargs=generation_config)
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": "Phi-3.5-mini-instruct",
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 phi_model:
912
- raise HTTPException(503, "AI model not loaded. Check server health.")
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 phi_model else "degraded",
935
  "models": {
936
- "phi_model": PHI_MODEL_NAME,
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
- "phi_loaded": phi_model is not None
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
- "phi_model": PHI_MODEL_NAME,
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
- "phi_3.5": {
986
- "name": "Phi-3.5-mini-instruct",
987
- "publisher": "Microsoft",
988
- "parameters": "3.8B",
989
- "context_length": "128K tokens",
990
- "license": "MIT",
991
- "description": "Lightweight, state-of-the-art open model"
 
 
 
 
 
 
 
 
 
 
992
  },
993
  "intent_detector": {
994
  "name": "AshokGakr/intent_detector",
@@ -1014,11 +1019,12 @@ async def model_info():
1014
  }
1015
  }
1016
 
1017
- if phi_model:
1018
- info["models"]["phi_3.5"].update({
1019
  "loaded": True,
1020
- "device": str(phi_model.device),
1021
- "dtype": str(phi_model.dtype)
 
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': 'Enhanced streaming test', 'intent': {'intent_label': 'greeting', 'confidence': 0.95}, 'emotion': {'primary_emotion': 'joy', 'emotional_tone': 'positive'}}}, ensure_ascii=False)}\n\n"
1055
 
1056
- test_msg = "This is an enhanced streaming test with intent and emotion awareness. "
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"🧠 Phi Model: {PHI_MODEL_NAME}")
 
 
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(