Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,38 +5,44 @@ import pandas as pd
|
|
| 5 |
from typing import Optional
|
| 6 |
from smolagents import CodeAgent, OpenAIServerModel, tool
|
| 7 |
|
| 8 |
-
# --- 搜尋工具設定 ---
|
| 9 |
-
# 把原本 import DDGS 的地方刪掉,換成這個:
|
| 10 |
try:
|
| 11 |
-
from
|
| 12 |
except ImportError:
|
| 13 |
import os
|
| 14 |
-
os.system('pip install
|
| 15 |
-
from
|
| 16 |
|
| 17 |
@tool
|
| 18 |
def web_search(query: str) -> str:
|
| 19 |
"""
|
| 20 |
-
Search the web using
|
| 21 |
Args:
|
| 22 |
query: The search query string.
|
| 23 |
"""
|
| 24 |
-
print(f"🕵️ [Debug]
|
| 25 |
try:
|
| 26 |
-
#
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
results.append(f"Title: {j.title}\nDescription: {j.description}")
|
| 32 |
-
|
| 33 |
if not results:
|
| 34 |
-
return "No results found."
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
except Exception as e:
|
| 38 |
print(f"❌ Search Error: {e}")
|
| 39 |
-
return "Search failed
|
|
|
|
| 40 |
# -----------------------------------------------------------
|
| 41 |
|
| 42 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
@@ -48,17 +54,18 @@ class GroqAgent:
|
|
| 48 |
self.agent = None
|
| 49 |
return
|
| 50 |
|
| 51 |
-
#
|
| 52 |
model = OpenAIServerModel(
|
| 53 |
-
model_id="llama-3.
|
| 54 |
api_base="https://api.groq.com/openai/v1",
|
| 55 |
api_key=self.api_key
|
| 56 |
)
|
| 57 |
|
|
|
|
| 58 |
self.agent = CodeAgent(
|
| 59 |
tools=[web_search],
|
| 60 |
model=model,
|
| 61 |
-
max_steps=3,
|
| 62 |
verbosity_level=1
|
| 63 |
)
|
| 64 |
|
|
@@ -67,11 +74,12 @@ class GroqAgent:
|
|
| 67 |
return "Error: GROQ_API_KEY not configured."
|
| 68 |
|
| 69 |
try:
|
| 70 |
-
#
|
| 71 |
prompt = f"""
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
| 75 |
|
| 76 |
Question: {question}
|
| 77 |
"""
|
|
@@ -115,7 +123,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 115 |
ans = agent_wrapper(q)
|
| 116 |
|
| 117 |
answers.append({"task_id": tid, "submitted_answer": ans})
|
| 118 |
-
logs.append({"Task": tid, "Answer": ans[:
|
| 119 |
|
| 120 |
try:
|
| 121 |
print("Submitting...")
|
|
@@ -128,15 +136,14 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 128 |
data = res.json()
|
| 129 |
score = data.get('score', 0)
|
| 130 |
|
| 131 |
-
# 只要有一題對就是成功,通常文字搜尋題會對,圖片題會錯
|
| 132 |
msg = f"🎉 Final Score: {score}%"
|
| 133 |
return msg, pd.DataFrame(logs)
|
| 134 |
|
| 135 |
except Exception as e:
|
| 136 |
return f"Submit error: {str(e)}", pd.DataFrame(logs)
|
| 137 |
|
| 138 |
-
with gr.Blocks(title="Final Agent (
|
| 139 |
-
gr.Markdown("# 🚀 Final Agent (
|
| 140 |
with gr.Row():
|
| 141 |
gr.LoginButton()
|
| 142 |
btn = gr.Button("Run Evaluation", variant="primary")
|
|
|
|
| 5 |
from typing import Optional
|
| 6 |
from smolagents import CodeAgent, OpenAIServerModel, tool
|
| 7 |
|
| 8 |
+
# --- 搜尋工具設定 (防封鎖版) ---
|
|
|
|
| 9 |
try:
|
| 10 |
+
from duckduckgo_search import DDGS
|
| 11 |
except ImportError:
|
| 12 |
import os
|
| 13 |
+
os.system('pip install duckduckgo-search>=6.0.0')
|
| 14 |
+
from duckduckgo_search import DDGS
|
| 15 |
|
| 16 |
@tool
|
| 17 |
def web_search(query: str) -> str:
|
| 18 |
"""
|
| 19 |
+
Search the web for information using DuckDuckGo.
|
| 20 |
Args:
|
| 21 |
query: The search query string.
|
| 22 |
"""
|
| 23 |
+
print(f"🕵️ [Debug] Searching: {query}")
|
| 24 |
try:
|
| 25 |
+
# 關鍵修正:使用 backend='html' 比較不容易被擋
|
| 26 |
+
# 限制 max_results=3 避免資料太多模型讀不完
|
| 27 |
+
with DDGS() as ddgs:
|
| 28 |
+
results = ddgs.text(query, max_results=3, backend="html")
|
| 29 |
+
|
|
|
|
|
|
|
| 30 |
if not results:
|
| 31 |
+
return "No search results found. Try a different query."
|
| 32 |
+
|
| 33 |
+
# 整理結果成字串
|
| 34 |
+
formatted_results = []
|
| 35 |
+
for r in results:
|
| 36 |
+
title = r.get('title', 'No Title')
|
| 37 |
+
body = r.get('body', 'No Description')
|
| 38 |
+
formatted_results.append(f"Title: {title}\nSummary: {body}")
|
| 39 |
+
|
| 40 |
+
return "\n---\n".join(formatted_results)
|
| 41 |
|
| 42 |
except Exception as e:
|
| 43 |
print(f"❌ Search Error: {e}")
|
| 44 |
+
return f"Search failed due to error: {e}"
|
| 45 |
+
|
| 46 |
# -----------------------------------------------------------
|
| 47 |
|
| 48 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 54 |
self.agent = None
|
| 55 |
return
|
| 56 |
|
| 57 |
+
# 回到聰明的 70B 模型
|
| 58 |
model = OpenAIServerModel(
|
| 59 |
+
model_id="llama-3.3-70b-versatile",
|
| 60 |
api_base="https://api.groq.com/openai/v1",
|
| 61 |
api_key=self.api_key
|
| 62 |
)
|
| 63 |
|
| 64 |
+
# 使用我們強化的 web_search
|
| 65 |
self.agent = CodeAgent(
|
| 66 |
tools=[web_search],
|
| 67 |
model=model,
|
| 68 |
+
max_steps=3,
|
| 69 |
verbosity_level=1
|
| 70 |
)
|
| 71 |
|
|
|
|
| 74 |
return "Error: GROQ_API_KEY not configured."
|
| 75 |
|
| 76 |
try:
|
| 77 |
+
# 提示詞優化:告訴模型如果找不到就猜,避免卡死
|
| 78 |
prompt = f"""
|
| 79 |
+
You are a helpful assistant. Answer the question concisely.
|
| 80 |
+
1. Use 'web_search' to find facts (names, dates, numbers).
|
| 81 |
+
2. If the search tool returns 'No results', DO NOT retry endlessly. Just give your best guess based on the question context.
|
| 82 |
+
3. For image/audio questions, just search for the text description provided in the question.
|
| 83 |
|
| 84 |
Question: {question}
|
| 85 |
"""
|
|
|
|
| 123 |
ans = agent_wrapper(q)
|
| 124 |
|
| 125 |
answers.append({"task_id": tid, "submitted_answer": ans})
|
| 126 |
+
logs.append({"Task": tid, "Answer": str(ans)[:100]})
|
| 127 |
|
| 128 |
try:
|
| 129 |
print("Submitting...")
|
|
|
|
| 136 |
data = res.json()
|
| 137 |
score = data.get('score', 0)
|
| 138 |
|
|
|
|
| 139 |
msg = f"🎉 Final Score: {score}%"
|
| 140 |
return msg, pd.DataFrame(logs)
|
| 141 |
|
| 142 |
except Exception as e:
|
| 143 |
return f"Submit error: {str(e)}", pd.DataFrame(logs)
|
| 144 |
|
| 145 |
+
with gr.Blocks(title="Final Agent (Ultimate Fix)") as demo:
|
| 146 |
+
gr.Markdown("# 🚀 Final Agent (70B + Anti-Block Search)")
|
| 147 |
with gr.Row():
|
| 148 |
gr.LoginButton()
|
| 149 |
btn = gr.Button("Run Evaluation", variant="primary")
|