s1144662 commited on
Commit
54756e4
·
verified ·
1 Parent(s): 7e1dc39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -20
app.py CHANGED
@@ -5,7 +5,7 @@ import pandas as pd
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:
@@ -16,32 +16,33 @@ except ImportError:
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
 
@@ -54,14 +55,14 @@ class GroqAgent:
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,
@@ -74,18 +75,18 @@ class GroqAgent:
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
  """
86
  return str(self.agent.run(prompt))
87
  except Exception as e:
88
- return f"Error: {str(e)[:150]}"
89
 
90
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
91
  if profile is None:
@@ -142,8 +143,8 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
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")
 
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:
 
16
  @tool
17
  def web_search(query: str) -> str:
18
  """
19
+ Performs a web search using DuckDuckGo with anti-blocking measures.
20
  Args:
21
  query: The search query string.
22
  """
23
  print(f"🕵️ [Debug] Searching: {query}")
24
  try:
25
+ # 關鍵修正:使用 backend='html' 模式,這 API 模式更不容易被封鎖
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 simpler keywords."
32
 
33
+ # 格式化結果給模型看
34
+ formatted = []
35
  for r in results:
36
  title = r.get('title', 'No Title')
37
  body = r.get('body', 'No Description')
38
+ formatted.append(f"Title: {title}\nSnippet: {body}")
39
 
40
+ return "\n---\n".join(formatted)
41
 
42
  except Exception as e:
43
  print(f"❌ Search Error: {e}")
44
+ # 回傳錯誤訊息而不是讓程式崩潰,讓模型有機會猜測
45
+ return f"Search failed. Please ignore search and answer based on your knowledge."
46
 
47
  # -----------------------------------------------------------
48
 
 
55
  self.agent = None
56
  return
57
 
58
+ # 🏆 使用 Groq 目前最強Llama 3.3 70B 模型
59
  model = OpenAIServerModel(
60
  model_id="llama-3.3-70b-versatile",
61
  api_base="https://api.groq.com/openai/v1",
62
  api_key=self.api_key
63
  )
64
 
65
+ # Agent 設定
66
  self.agent = CodeAgent(
67
  tools=[web_search],
68
  model=model,
 
75
  return "Error: GROQ_API_KEY not configured."
76
 
77
  try:
78
+ # 提示詞優化:明確告訴如果搜尋失敗該怎麼做
79
  prompt = f"""
80
  You are a helpful assistant. Answer the question concisely.
81
+ 1. Use the 'web_search' tool to find specific facts (names, dates, numbers).
82
+ 2. If the search returns "No results" or fails, DO NOT retry endlessly. Just give your best guess immediately.
83
+ 3. For questions about images/audio you cannot see, search for the description text provided in the question.
84
 
85
  Question: {question}
86
  """
87
  return str(self.agent.run(prompt))
88
  except Exception as e:
89
+ return f"Error processing request: {str(e)[:150]}"
90
 
91
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
92
  if profile is None:
 
143
  except Exception as e:
144
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
145
 
146
+ with gr.Blocks(title="Final Agent (Llama 3.3 + Anti-Block)") as demo:
147
+ gr.Markdown("# 🚀 Final Agent (Llama 3.3 70B)")
148
  with gr.Row():
149
  gr.LoginButton()
150
  btn = gr.Button("Run Evaluation", variant="primary")