Update app.py
Browse files
app.py
CHANGED
|
@@ -43,47 +43,38 @@ def initialize_llm():
|
|
| 43 |
"""Initialize free local LLM with transformers pipeline"""
|
| 44 |
logger.info("π Initializing FREE local language model...")
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
]
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
device=device,
|
| 70 |
-
max_new_tokens=300,
|
| 71 |
-
truncation=True,
|
| 72 |
-
model_kwargs=model_kwargs
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
CONFIG["llm_model"] = model_name
|
| 76 |
-
CONFIG["model_type"] = model_type
|
| 77 |
-
logger.info(f"β
FREE LLM initialized: {model_name}")
|
| 78 |
-
logger.info(f" Device: {'GPU' if device == 0 else 'CPU'}")
|
| 79 |
-
return llm_client
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
def initialize_embeddings():
|
| 89 |
"""Initialize sentence transformer embeddings"""
|
|
@@ -363,32 +354,31 @@ def generate_llm_answer(
|
|
| 363 |
top_p = 0.97
|
| 364 |
repetition_penalty = 1.25
|
| 365 |
|
| 366 |
-
# Create
|
| 367 |
-
model_type = CONFIG.get("model_type", "
|
| 368 |
|
| 369 |
-
#
|
| 370 |
-
user_prompt = f"""
|
| 371 |
-
|
| 372 |
-
Fashion Knowledge:
|
| 373 |
-
{context_text[:1200]}
|
| 374 |
|
| 375 |
Question: {query}
|
| 376 |
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
try:
|
| 380 |
logger.info(f" β Calling {CONFIG['llm_model']} (temp={temperature}, tokens={max_tokens})...")
|
| 381 |
|
| 382 |
-
#
|
| 383 |
output = llm_client(
|
| 384 |
user_prompt,
|
| 385 |
-
|
| 386 |
-
temperature=0.
|
| 387 |
-
top_p=0.
|
| 388 |
-
repetition_penalty=1.15,
|
| 389 |
do_sample=True,
|
| 390 |
-
|
| 391 |
-
|
| 392 |
)
|
| 393 |
|
| 394 |
# Extract generated text
|
|
@@ -417,34 +407,7 @@ Output: """
|
|
| 417 |
return None
|
| 418 |
|
| 419 |
def synthesize_direct_answer(
|
| 420 |
-
|
| 421 |
-
retrieved_docs: List[Document]
|
| 422 |
-
) -> str:
|
| 423 |
-
"""
|
| 424 |
-
Enhanced fallback: Combine multiple documents intelligently
|
| 425 |
-
"""
|
| 426 |
-
logger.info(" β Using enhanced fallback synthesis")
|
| 427 |
-
|
| 428 |
-
if not retrieved_docs:
|
| 429 |
-
return "I don't have enough information to answer that question accurately. Please try rephrasing your question."
|
| 430 |
-
|
| 431 |
-
# Combine top 3 most relevant documents
|
| 432 |
-
top_docs = retrieved_docs[:3]
|
| 433 |
-
combined_content = []
|
| 434 |
-
|
| 435 |
-
for i, doc in enumerate(top_docs, 1):
|
| 436 |
-
content = doc.page_content.strip()
|
| 437 |
-
if len(content) > 200:
|
| 438 |
-
content = content[:200]
|
| 439 |
-
combined_content.append(f"{content}")
|
| 440 |
-
|
| 441 |
-
answer = " ".join(combined_content)
|
| 442 |
-
|
| 443 |
-
# Add context-aware prefix
|
| 444 |
-
answer = f"Based on fashion guidelines: {answer}"
|
| 445 |
-
|
| 446 |
-
return answer
|
| 447 |
-
|
| 448 |
def generate_answer_langchain(
|
| 449 |
query: str,
|
| 450 |
vectorstore,
|
|
@@ -507,12 +470,12 @@ def fashion_chatbot(message: str, history: List[List[str]]):
|
|
| 507 |
message.strip(),
|
| 508 |
vectorstore,
|
| 509 |
top_k=CONFIG["top_k"]
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
# Show generating indicator
|
| 517 |
yield f"π Generating answer ({len(retrieved_docs)} sources found)..."
|
| 518 |
|
|
@@ -552,12 +515,11 @@ def fashion_chatbot(message: str, history: List[List[str]]):
|
|
| 552 |
# ============================================================================
|
| 553 |
# INITIALIZE AND LAUNCH
|
| 554 |
# ============================================================================
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
def startup():
|
| 562 |
"""Initialize all models and load vector store"""
|
| 563 |
global llm_client, embeddings, vectorstore
|
|
|
|
| 43 |
"""Initialize free local LLM with transformers pipeline"""
|
| 44 |
logger.info("π Initializing FREE local language model...")
|
| 45 |
|
| 46 |
+
# Use FLAN-T5-Large - reliable, fast, and proven to work
|
| 47 |
+
model_name = "google/flan-t5-large"
|
|
|
|
| 48 |
|
| 49 |
+
try:
|
| 50 |
+
logger.info(f" Loading {model_name}...")
|
| 51 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 52 |
+
|
| 53 |
+
# T5 configuration
|
| 54 |
+
task = "text2text-generation"
|
| 55 |
+
model_type = "t5"
|
| 56 |
+
|
| 57 |
+
# Optimized for speed and quality
|
| 58 |
+
model_kwargs = {
|
| 59 |
+
"low_cpu_mem_usage": True,
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
llm_client = pipeline(
|
| 63 |
+
task,
|
| 64 |
+
model=model_name,
|
| 65 |
+
device=device,
|
| 66 |
+
model_kwargs=model_kwargs
|
| 67 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
CONFIG["llm_model"] = model_name
|
| 70 |
+
CONFIG["model_type"] = model_type
|
| 71 |
+
logger.info(f"β
LLM initialized: {model_name}")
|
| 72 |
+
logger.info(f" Device: {'GPU' if device == 0 else 'CPU'}")
|
| 73 |
+
return llm_client
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
logger.error(f"β Failed to load model: {str(e)}")
|
| 77 |
+
raise Exception(f"Failed to initialize LLM: {str(e)}")
|
| 78 |
|
| 79 |
def initialize_embeddings():
|
| 80 |
"""Initialize sentence transformer embeddings"""
|
|
|
|
| 354 |
top_p = 0.97
|
| 355 |
repetition_penalty = 1.25
|
| 356 |
|
| 357 |
+
# Create optimized T5 prompt
|
| 358 |
+
model_type = CONFIG.get("model_type", "t5")
|
| 359 |
|
| 360 |
+
# T5 format - simple and effective for good answers
|
| 361 |
+
user_prompt = f"""Answer this fashion question with detailed, specific advice using the context provided.
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
Question: {query}
|
| 364 |
|
| 365 |
+
Fashion Context:
|
| 366 |
+
{context_text[:1500]}
|
| 367 |
+
|
| 368 |
+
Provide a complete, detailed answer (150-250 words):"""
|
| 369 |
|
| 370 |
try:
|
| 371 |
logger.info(f" β Calling {CONFIG['llm_model']} (temp={temperature}, tokens={max_tokens})...")
|
| 372 |
|
| 373 |
+
# T5 optimized parameters for quality and speed
|
| 374 |
output = llm_client(
|
| 375 |
user_prompt,
|
| 376 |
+
max_length=300, # Good length for detailed answers
|
| 377 |
+
temperature=0.75, # Balanced creativity
|
| 378 |
+
top_p=0.92,
|
|
|
|
| 379 |
do_sample=True,
|
| 380 |
+
num_beams=2, # Light beam search for quality
|
| 381 |
+
early_stopping=True
|
| 382 |
)
|
| 383 |
|
| 384 |
# Extract generated text
|
|
|
|
| 407 |
return None
|
| 408 |
|
| 409 |
def synthesize_direct_answer(
|
| 410 |
+
# Removed synthetic fallback - only use LLM
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
def generate_answer_langchain(
|
| 412 |
query: str,
|
| 413 |
vectorstore,
|
|
|
|
| 470 |
message.strip(),
|
| 471 |
vectorstore,
|
| 472 |
top_k=CONFIG["top_k"]
|
| 473 |
+
# Step 3: If all attempts fail, return error
|
| 474 |
+
if not llm_answer:
|
| 475 |
+
logger.error(f" β All 4 LLM attempts failed")
|
| 476 |
+
return "I apologize, but I'm having trouble generating a response. Please try rephrasing your question or ask something else."
|
| 477 |
+
|
| 478 |
+
return llm_answer
|
| 479 |
# Show generating indicator
|
| 480 |
yield f"π Generating answer ({len(retrieved_docs)} sources found)..."
|
| 481 |
|
|
|
|
| 515 |
# ============================================================================
|
| 516 |
# INITIALIZE AND LAUNCH
|
| 517 |
# ============================================================================
|
| 518 |
+
# If LLM fails, show error
|
| 519 |
+
if not llm_answer:
|
| 520 |
+
logger.error(f" β All LLM attempts failed")
|
| 521 |
+
yield "I apologize, but I'm having trouble generating a response. Please try rephrasing your question."
|
| 522 |
+
return
|
|
|
|
| 523 |
def startup():
|
| 524 |
"""Initialize all models and load vector store"""
|
| 525 |
global llm_client, embeddings, vectorstore
|