s1144662 commited on
Commit
62f94f2
·
verified ·
1 Parent(s): 2c27ada

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -18
app.py CHANGED
@@ -5,27 +5,33 @@ import pandas as pd
5
  from typing import Optional
6
  from smolagents import CodeAgent, OpenAIServerModel, tool
7
 
8
- # --- 關鍵修改:手定義搜尋工具,繞過 smolagents 的檢查錯誤 ---
9
  try:
10
  from duckduckgo_search import DDGS
11
  except ImportError:
12
- # 萬一真的沒裝到,這邊做最後一道防線
13
  os.system('pip install duckduckgo-search==6.4.2')
14
  from duckduckgo_search import DDGS
15
 
16
  @tool
17
  def web_search(query: str) -> str:
18
  """
19
- Performs a web search to find information about specific facts, events, or data.
20
-
21
  Args:
22
  query: The search query string.
23
  """
 
24
  try:
25
- results = DDGS().text(query, max_results=5)
 
 
 
 
26
  return str(results)
27
  except Exception as e:
28
- return f"Search error: {str(e)}"
 
 
29
  # -----------------------------------------------------------
30
 
31
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -43,7 +49,6 @@ class GroqAgent:
43
  api_key=self.api_key
44
  )
45
 
46
- # 使用我們手動定義的 web_search 工具
47
  self.agent = CodeAgent(
48
  tools=[web_search],
49
  model=model,
@@ -56,10 +61,12 @@ class GroqAgent:
56
  return "Error: GROQ_API_KEY not configured."
57
 
58
  try:
 
59
  prompt = f"""
60
- Answer the question concisely.
61
- If it's a factual question (dates, names, events), use the 'web_search' tool.
62
- If it refers to an image/video you can't see, try to infer from the text or search for the description.
 
63
 
64
  Question: {question}
65
  """
@@ -83,6 +90,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
83
  return f"❌ Init failed: {str(e)}", None
84
 
85
  try:
 
86
  response = requests.get(f"{api_url}/questions", timeout=30)
87
  questions = response.json()
88
  except Exception as e:
@@ -91,34 +99,43 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
91
  answers = []
92
  logs = []
93
 
94
- for item in questions:
 
95
  q = item.get("question")
96
  tid = item.get("task_id")
97
- print(f"Processing: {tid}...")
98
 
 
 
 
99
  ans = agent_wrapper(q)
 
100
  answers.append({"task_id": tid, "submitted_answer": ans})
101
- logs.append({"Task": tid, "Q": q[:50], "A": ans[:100]})
102
 
103
  try:
 
104
  res = requests.post(f"{api_url}/submit", json={
105
  "username": username,
106
  "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
107
  "answers": answers
108
- })
 
109
  data = res.json()
110
  score = data.get('score', 0)
111
- return f"Score: {score}%", pd.DataFrame(logs)
 
 
112
  except Exception as e:
113
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
114
 
115
- with gr.Blocks(title="Final Agent") as demo:
116
- gr.Markdown("# 🚀 Final Agent (Custom Tool Version)")
 
117
  with gr.Row():
118
  gr.LoginButton()
119
  btn = gr.Button("Run Evaluation", variant="primary")
120
  out = gr.Textbox(label="Status")
121
- tab = gr.DataFrame(label="Results")
122
  btn.click(run_and_submit_all, outputs=[out, tab])
123
 
124
  if __name__ == "__main__":
 
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.4.2')
14
  from duckduckgo_search import DDGS
15
 
16
  @tool
17
  def web_search(query: str) -> str:
18
  """
19
+ Performs a web search.
 
20
  Args:
21
  query: The search query string.
22
  """
23
+ print(f"🕵️ [Debug] Searching for: {query}") # 讓你知道它正在工作
24
  try:
25
+ # 關鍵修改:加上 timeout=15 (),並限制結果數量以加速
26
+ # backend='html' 通常比 api 模式更不容易被擋
27
+ results = DDGS(timeout=15).text(query, max_results=3)
28
+ if not results:
29
+ return "No search results found."
30
  return str(results)
31
  except Exception as e:
32
+ print(f"❌ [Error] Search failed: {e}")
33
+ return f"Search connection failed: {e}"
34
+
35
  # -----------------------------------------------------------
36
 
37
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
49
  api_key=self.api_key
50
  )
51
 
 
52
  self.agent = CodeAgent(
53
  tools=[web_search],
54
  model=model,
 
61
  return "Error: GROQ_API_KEY not configured."
62
 
63
  try:
64
+ # 簡化 Prompt 讓模型反應更快
65
  prompt = f"""
66
+ You are an expert agent. Answer the question concisely.
67
+ 1. Use 'web_search' for facts (dates, names, events).
68
+ 2. If search fails, make your best guess.
69
+ 3. Answer directly.
70
 
71
  Question: {question}
72
  """
 
90
  return f"❌ Init failed: {str(e)}", None
91
 
92
  try:
93
+ print("Fetching questions...")
94
  response = requests.get(f"{api_url}/questions", timeout=30)
95
  questions = response.json()
96
  except Exception as e:
 
99
  answers = []
100
  logs = []
101
 
102
+ total = len(questions)
103
+ for idx, item in enumerate(questions, 1):
104
  q = item.get("question")
105
  tid = item.get("task_id")
 
106
 
107
+ print(f"🚀 [{idx}/{total}] Processing task: {tid}...")
108
+
109
+ # 這裡會觸發 agent 思考
110
  ans = agent_wrapper(q)
111
+
112
  answers.append({"task_id": tid, "submitted_answer": ans})
113
+ logs.append({"Task": tid, "Status": "Done", "Answer Preview": ans[:50]})
114
 
115
  try:
116
+ print("Submitting answers...")
117
  res = requests.post(f"{api_url}/submit", json={
118
  "username": username,
119
  "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
120
  "answers": answers
121
+ }, timeout=60)
122
+
123
  data = res.json()
124
  score = data.get('score', 0)
125
+ msg = f"🎉 Final Score: {score}%" if score >= 30 else f"Score: {score}% (Try again!)"
126
+ return msg, pd.DataFrame(logs)
127
+
128
  except Exception as e:
129
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
130
 
131
+ with gr.Blocks(title="Final Agent (Timeout Optimized)") as demo:
132
+ gr.Markdown("# 🚀 Final Agent (Fast Version)")
133
+ gr.Markdown("Has timeout protection to prevent hanging.")
134
  with gr.Row():
135
  gr.LoginButton()
136
  btn = gr.Button("Run Evaluation", variant="primary")
137
  out = gr.Textbox(label="Status")
138
+ tab = gr.DataFrame(label="Progress Log")
139
  btn.click(run_and_submit_all, outputs=[out, tab])
140
 
141
  if __name__ == "__main__":