qwendashcoder commited on
Commit
c72932a
Β·
verified Β·
1 Parent(s): fb7851e

Update response_modes.py

Browse files
Files changed (1) hide show
  1. response_modes.py +78 -68
response_modes.py CHANGED
@@ -409,7 +409,7 @@ def chat_stream(message, history, current_model, logged_in_username, user_chats,
409
 
410
  today_date = datetime.now().strftime("%B %d, %Y")
411
 
412
- # === STRONG CONTEXT HANDLING (works in EVERY mode) ===
413
  context_instruction = ""
414
  if context and str(context).strip():
415
  ctx = str(context).strip()
@@ -421,93 +421,103 @@ Never mention this rule unless the user explicitly asks about it."""
421
 
422
  system_context = [{"role": "system", "content": context_instruction}] if context_instruction else []
423
 
424
- # === CODING MODE: Inject all persistent files (ALWAYS define the variable) ===
425
- coding_context = "" # ← This line is the fix
426
  if mode == "πŸ’» Coding Mode":
427
- current_chat = None
428
- for chat in (user_chats or []):
429
- if chat.get("title") == current_chat_title:
430
- current_chat = chat
431
- break
432
  if current_chat and current_chat.get("coding_files"):
433
- coding_context = "\n\n=== PERSISTENT PROJECT FILES (read these first) ===\n"
434
  for fname, data in current_chat["coding_files"].items():
435
- coding_context += f"\n--- {fname} ({data.get('language','text')}) ---\n{data['content']}\n"
436
-
437
- user_input = quote(message)
438
- if file_text:
439
- user_input += f"\n\n--- Attached files (up to 5) ---\n{file_text}"
440
-
441
- # Inject persistent coding files (now safe in all modes)
442
- if mode == "πŸ’» Coding Mode" and coding_context.strip():
443
- user_input = coding_context + "\n\n" + user_input
444
-
445
- history.append({"role": "user", "content": user_input})
446
- yield history
447
- history.append({"role": "assistant", "content": ""})
448
- yield history
449
-
450
- if mode == "Deep Think":
451
- # SPECIAL CASE: User just wants the sources from last response
452
- lower_msg = message.lower().strip()
453
- if any(phrase in lower_msg for phrase in ["show the sources", "show sources", "sources please", "the sources", "list sources"]):
454
- # Walk backwards to find the last sources section
455
- for i in range(len(history)-2, -1, -1):
456
- if "**πŸ“Œ Key Sources:**" in history[i]["content"]:
457
- sources_only = history[i]["content"].split("**πŸ“Œ Key Sources:**")[-1].strip()
458
- history[-1]["content"] = f"**πŸ“Œ Sources from your previous query:**\n\n{sources_only}"
459
- yield history
460
- return # done
461
-
462
- is_news = any(k in message.lower() for k in ["news", "today", "latest", "breaking", "headlines", "update", "philippines"])
463
-
464
- thinking_steps = [
465
- "🧠 Thinking step-by-step...", "πŸ” Understanding the core question...",
466
- "πŸ“‹ Planning research approach...", "πŸ”Ž Gathering real-time data...",
467
- "🧩 Analyzing & cross-checking...", "✍️ Synthesizing final answer..."
468
  ]
469
 
470
- for step in thinking_steps:
471
- history[-1]["content"] = step
472
- yield history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473
 
474
- queries = generate_queries(client, current_model, message, today_date)
475
- queries = [enhance_query(q) for q in queries]
476
 
477
- all_context = ""
478
- raw_results = []
479
 
480
- for i, q in enumerate(queries, 1):
481
- history[-1]["content"] = f"πŸ”Ž Deep live search {i}/{len(queries)}: {q[:60]}..."
482
- yield history
483
- results = web_search(q, max_results=120)
 
484
 
485
- if is_news:
486
- junk = ["wikivoyage", "wikipedia", "wikimedia", "tripadvisor", "booking.com", "airbnb", "lonelyplanet"]
487
- results = [r for r in results if not any(j in r.lower() for j in junk)]
 
 
 
 
488
 
489
- all_context += f"\n\n=== Search {i}: {q} ===\n" + "\n\n".join(results)
490
- raw_results.extend(results[:8])
491
 
492
- history[-1]["content"] = "✍️ Synthesizing final answer from live data..."
 
493
  yield history
494
 
495
- refined_answer = qwen_reasoning(message, all_context, context)
 
496
 
497
- useful_sources = [s for s in raw_results if len(s.strip()) > 40 and "broad search used" not in s.lower()]
498
- sources_section = format_sources(useful_sources, max_sources=7)
499
 
500
- full_response = refined_answer
501
- if sources_section:
502
- full_response += f"\n\n---\n\n**πŸ“Œ Key Sources:**\n\n{sources_section}"
 
 
 
 
 
 
 
 
503
 
504
- history[-1]["content"] = full_response
505
  yield history
506
 
507
- # Auto-save
508
  if logged_in_username and user_chats:
509
  for chat in user_chats:
510
  if chat["title"] == current_chat_title:
511
  chat["history"] = history
512
  break
513
- save_chats(logged_in_username, user_chats, auth_globals)
 
 
409
 
410
  today_date = datetime.now().strftime("%B %d, %Y")
411
 
412
+ # Persistent chat context (instructions)
413
  context_instruction = ""
414
  if context and str(context).strip():
415
  ctx = str(context).strip()
 
421
 
422
  system_context = [{"role": "system", "content": context_instruction}] if context_instruction else []
423
 
424
+ # === CODING MODE: 2-AGENT EXPERIMENT (Coder + Reviewer) ===
 
425
  if mode == "πŸ’» Coding Mode":
426
+ # Gather all persistent files
427
+ coding_files_str = ""
428
+ current_chat = next((chat for chat in (user_chats or []) if chat.get("title") == current_chat_title), None)
 
 
429
  if current_chat and current_chat.get("coding_files"):
430
+ coding_files_str = "\n\n=== PERSISTENT PROJECT FILES (read these first) ===\n"
431
  for fname, data in current_chat["coding_files"].items():
432
+ coding_files_str += f"\n--- {fname} ({data.get('language','text')}) ---\n{data['content']}\n"
433
+
434
+ user_input = quote(message)
435
+ if file_text:
436
+ user_input += f"\n\n--- Attached files ---\n{file_text}"
437
+
438
+ full_context = coding_files_str + "\n\nUser request: " + user_input
439
+
440
+ # ====================== AGENT 1: CODER ======================
441
+ history.append({"role": "assistant", "content": "πŸ€– **Coder Agent** is thinking and writing code..."})
442
+ yield history
443
+
444
+ coder_messages = system_context + [
445
+ {"role": "user", "content": f"""You are an expert senior software engineer.
446
+ Use the project files above. {full_context}
447
+
448
+ Write clean, correct, well-commented code or make the requested changes."""}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  ]
450
 
451
+ coder_response = client.chat.completions.create(
452
+ model=current_model,
453
+ messages=coder_messages,
454
+ temperature=0.3,
455
+ max_tokens=4096,
456
+ stream=False
457
+ ).choices[0].message.content
458
+
459
+ history[-1]["content"] = f"πŸ€– **Coder Agent**:\n\n{coder_response}"
460
+ yield history
461
+
462
+ # ====================== AGENT 2: REVIEWER ======================
463
+ history.append({"role": "assistant", "content": "πŸ•΅οΈ **Reviewer Agent** is analyzing the code..."})
464
+ yield history
465
+
466
+ reviewer_prompt = f"""You are a strict senior code reviewer.
467
+ Here is the latest code from the Coder:
468
 
469
+ {coder_response}
 
470
 
471
+ Project files:
472
+ {coding_files_str}
473
 
474
+ Critique it honestly:
475
+ - Point out bugs, security issues, bad practices, performance problems
476
+ - Suggest concrete improvements
477
+ - Keep it constructive and specific
478
+ - End with "OVERALL: GOOD / NEEDS_WORK" """
479
 
480
+ reviewer_response = client_qwen.chat.completions.create( # ← uses your existing Groq Qwen (fast)
481
+ model="qwen/qwen3-32b",
482
+ messages=[{"role": "user", "content": reviewer_prompt}],
483
+ temperature=0.4,
484
+ max_completion_tokens=2048,
485
+ stream=False
486
+ ).choices[0].message.content
487
 
488
+ history[-1]["content"] = f"πŸ•΅οΈ **Reviewer Agent**:\n\n{reviewer_response}"
489
+ yield history
490
 
491
+ # ====================== AGENT 1: CODER FINAL REFINEMENT ======================
492
+ history.append({"role": "assistant", "content": "πŸ€– **Coder Agent** is refining based on feedback..."})
493
  yield history
494
 
495
+ final_prompt = f"""Previous code you wrote:
496
+ {coder_response}
497
 
498
+ Reviewer feedback:
499
+ {reviewer_response}
500
 
501
+ Now produce the FINAL polished version.
502
+ Incorporate all valid feedback.
503
+ If everything is good, just output the clean final code with a short "βœ… All good after review" note."""
504
+
505
+ final_response = client.chat.completions.create(
506
+ model=current_model,
507
+ messages=system_context + [{"role": "user", "content": final_prompt}],
508
+ temperature=0.25,
509
+ max_tokens=4096,
510
+ stream=False
511
+ ).choices[0].message.content
512
 
513
+ history[-1]["content"] = f"πŸ€– **Final Code (after review)**:\n\n{final_response}"
514
  yield history
515
 
516
+ # Auto-save the conversation
517
  if logged_in_username and user_chats:
518
  for chat in user_chats:
519
  if chat["title"] == current_chat_title:
520
  chat["history"] = history
521
  break
522
+ save_chats(logged_in_username, user_chats, auth_globals)
523
+ return