Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
# filename: okemo_backend.py
|
| 2 |
-
# OkemoLLM backend (refactored, syntax-fixed):
|
| 3 |
# - Loads GPT with EXACT hyperparameters from checkpoint
|
| 4 |
# - Uses web search ONLY when user input contains "<WEB>"
|
| 5 |
# - Keeps weight tying, online learning, and public APIs compatible
|
| 6 |
# - Clearer structure, improved robustness, fully typed
|
|
|
|
| 7 |
|
| 8 |
import os
|
| 9 |
import re
|
|
@@ -244,19 +245,31 @@ def save_checkpoint(model: GPT, optimizer: optim.Optimizer, voc: Voc, path: str)
|
|
| 244 |
print(f"ERROR: Failed to save checkpoint: {e}")
|
| 245 |
|
| 246 |
# ---------------------
|
| 247 |
-
# Web search (only with <WEB>)
|
| 248 |
# ---------------------
|
| 249 |
def perform_web_search(query: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
if not TAVILY_API_KEY:
|
| 251 |
return ""
|
| 252 |
try:
|
| 253 |
resp = requests.post(
|
| 254 |
"https://api.tavily.com/search",
|
| 255 |
-
|
|
|
|
| 256 |
timeout=8,
|
| 257 |
)
|
| 258 |
resp.raise_for_status()
|
| 259 |
data = resp.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
results = data.get("results", [])
|
| 261 |
snippets: List[str] = []
|
| 262 |
for r in results[:3]:
|
|
@@ -264,7 +277,9 @@ def perform_web_search(query: str) -> str:
|
|
| 264 |
snippet = (r.get("content") or "").strip()
|
| 265 |
url = (r.get("url") or "").strip()
|
| 266 |
if title or snippet:
|
| 267 |
-
|
|
|
|
|
|
|
| 268 |
return to_ascii(" | ".join(snippets))
|
| 269 |
except Exception as e:
|
| 270 |
print(f"Search failed: {e}")
|
|
@@ -278,6 +293,7 @@ def should_search(user_text: str) -> bool:
|
|
| 278 |
# ---------------------
|
| 279 |
def generate_response(prompt: str, search_context: str = "", conversation_context: str = "") -> Iterator[str]:
|
| 280 |
"""Generator function that yields the generated word tokens."""
|
|
|
|
| 281 |
prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
|
| 282 |
context_prefix = f"{conversation_context} " if conversation_context else ""
|
| 283 |
full_input = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text}{prompt}"
|
|
@@ -571,6 +587,7 @@ with gr.Blocks(title="OkemoLLM") as demo:
|
|
| 571 |
|
| 572 |
def add_user_message_to_history(message: str, history: Optional[List[List[Optional[str]]]], file_ref: Optional[Any], web_enabled: bool):
|
| 573 |
history = history or []
|
|
|
|
| 574 |
return history + [[message, None]], "..."
|
| 575 |
|
| 576 |
msg.submit(
|
|
@@ -607,6 +624,7 @@ with gr.Blocks(title="OkemoLLM") as demo:
|
|
| 607 |
updated_history = chat_value or []
|
| 608 |
updated_history.append([msg_value, None])
|
| 609 |
# Call generator and return the final state
|
|
|
|
| 610 |
final_history, status_msg = list(on_submit(msg_value, updated_history, uploaded_file_value, web_enabled_value))[-1]
|
| 611 |
return final_history, status_msg
|
| 612 |
|
|
@@ -655,4 +673,4 @@ with gr.Blocks(title="OkemoLLM") as demo:
|
|
| 655 |
)
|
| 656 |
|
| 657 |
if __name__ == "__main__":
|
| 658 |
-
demo.queue(api_open=True).launch(ssr_mode=False)
|
|
|
|
| 1 |
# filename: okemo_backend.py
|
| 2 |
+
# OkemoLLM backend (refactored, syntax-fixed, and <WEB> search improved for accuracy):
|
| 3 |
# - Loads GPT with EXACT hyperparameters from checkpoint
|
| 4 |
# - Uses web search ONLY when user input contains "<WEB>"
|
| 5 |
# - Keeps weight tying, online learning, and public APIs compatible
|
| 6 |
# - Clearer structure, improved robustness, fully typed
|
| 7 |
+
# - **Improved Tavily search to prioritize summarized answer for better accuracy.**
|
| 8 |
|
| 9 |
import os
|
| 10 |
import re
|
|
|
|
| 245 |
print(f"ERROR: Failed to save checkpoint: {e}")
|
| 246 |
|
| 247 |
# ---------------------
|
| 248 |
+
# Web search (only with <WEB>) - IMPROVED FOR ACCURACY
|
| 249 |
# ---------------------
|
| 250 |
def perform_web_search(query: str) -> str:
|
| 251 |
+
"""
|
| 252 |
+
Performs a Tavily web search, prioritizing the summarized 'answer' for accuracy.
|
| 253 |
+
If no answer is provided, falls back to concatenating snippets.
|
| 254 |
+
"""
|
| 255 |
if not TAVILY_API_KEY:
|
| 256 |
return ""
|
| 257 |
try:
|
| 258 |
resp = requests.post(
|
| 259 |
"https://api.tavily.com/search",
|
| 260 |
+
# MODIFIED: Set 'include_answer' to True for a summarized answer, reduce 'max_results' to 3.
|
| 261 |
+
json={"api_key": TAVILY_API_KEY, "query": query, "include_answer": True, "max_results": 3},
|
| 262 |
timeout=8,
|
| 263 |
)
|
| 264 |
resp.raise_for_status()
|
| 265 |
data = resp.json()
|
| 266 |
+
|
| 267 |
+
# 1. Prioritize the AI-generated answer from Tavily
|
| 268 |
+
answer = data.get("answer", "").strip()
|
| 269 |
+
if answer:
|
| 270 |
+
return to_ascii(answer)
|
| 271 |
+
|
| 272 |
+
# 2. Fallback to manually compiling snippets if no answer is provided
|
| 273 |
results = data.get("results", [])
|
| 274 |
snippets: List[str] = []
|
| 275 |
for r in results[:3]:
|
|
|
|
| 277 |
snippet = (r.get("content") or "").strip()
|
| 278 |
url = (r.get("url") or "").strip()
|
| 279 |
if title or snippet:
|
| 280 |
+
# Use a cleaner format for the LLM to digest
|
| 281 |
+
snippets.append(f"Title: {title}, Content: {snippet}")
|
| 282 |
+
|
| 283 |
return to_ascii(" | ".join(snippets))
|
| 284 |
except Exception as e:
|
| 285 |
print(f"Search failed: {e}")
|
|
|
|
| 293 |
# ---------------------
|
| 294 |
def generate_response(prompt: str, search_context: str = "", conversation_context: str = "") -> Iterator[str]:
|
| 295 |
"""Generator function that yields the generated word tokens."""
|
| 296 |
+
# Prefix text is now the concise answer or the compiled snippets
|
| 297 |
prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
|
| 298 |
context_prefix = f"{conversation_context} " if conversation_context else ""
|
| 299 |
full_input = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text}{prompt}"
|
|
|
|
| 587 |
|
| 588 |
def add_user_message_to_history(message: str, history: Optional[List[List[Optional[str]]]], file_ref: Optional[Any], web_enabled: bool):
|
| 589 |
history = history or []
|
| 590 |
+
# The user message is added to history, AI response slot is None for streaming
|
| 591 |
return history + [[message, None]], "..."
|
| 592 |
|
| 593 |
msg.submit(
|
|
|
|
| 624 |
updated_history = chat_value or []
|
| 625 |
updated_history.append([msg_value, None])
|
| 626 |
# Call generator and return the final state
|
| 627 |
+
# Note: We must consume the generator to get the final state for the API
|
| 628 |
final_history, status_msg = list(on_submit(msg_value, updated_history, uploaded_file_value, web_enabled_value))[-1]
|
| 629 |
return final_history, status_msg
|
| 630 |
|
|
|
|
| 673 |
)
|
| 674 |
|
| 675 |
if __name__ == "__main__":
|
| 676 |
+
demo.queue(api_open=True).launch(ssr_mode=False)
|