s1144662 commited on
Commit
d362c8f
·
verified ·
1 Parent(s): fb0f088

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -28
app.py CHANGED
@@ -2,46 +2,46 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- import time
6
  from typing import Optional
7
  from smolagents import CodeAgent, OpenAIServerModel, tool
8
 
9
- # --- 搜尋工具 (Lite 後門版) ---
10
  try:
11
  from duckduckgo_search import DDGS
12
  except ImportError:
13
  import os
14
- os.system('pip install duckduckgo-search>=6.0.0')
15
  from duckduckgo_search import DDGS
16
 
17
  @tool
18
  def web_search(query: str) -> str:
19
  """
20
- Performs a web search using the 'lite' backend to bypass rate limits.
21
  Args:
22
  query: The search query string.
23
  """
24
- print(f"🕵️ [Debug] Searching (Lite): {query}")
25
  try:
26
- # 關鍵修改:使用 backend='lite'
27
- # 這是最原始的 HTML 介面,極被封鎖
28
  with DDGS() as ddgs:
29
- results = ddgs.text(query, max_results=3, backend="lite")
30
 
31
  if not results:
32
- return "No results found."
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
- return "Search failed. Ignore this and guess based on your knowledge."
45
 
46
  # -----------------------------------------------------------
47
 
@@ -54,7 +54,7 @@ class GroqAgent:
54
  self.agent = None
55
  return
56
 
57
- # 堅持使用 Llama 3.3 (目前唯一活著且聰明的模型)
58
  model = OpenAIServerModel(
59
  model_id="llama-3.3-70b-versatile",
60
  api_base="https://api.groq.com/openai/v1",
@@ -64,7 +64,7 @@ class GroqAgent:
64
  self.agent = CodeAgent(
65
  tools=[web_search],
66
  model=model,
67
- max_steps=3,
68
  verbosity_level=1
69
  )
70
 
@@ -73,18 +73,18 @@ class GroqAgent:
73
  return "Error: GROQ_API_KEY not configured."
74
 
75
  try:
76
- # 提示詞:強調「如果 Lite 搜尋失敗就直接回答
77
  prompt = f"""
78
- You are a helpful assistant. Answer the question concisely.
79
- 1. Use 'web_search' to find facts.
80
- 2. If search returns "No results" or fails, DO NOT RETRY. Make your BEST GUESS from your training data immediately.
81
- 3. Answer directly.
82
 
83
  Question: {question}
84
  """
85
  return str(self.agent.run(prompt))
86
  except Exception as e:
87
- return f"Error: {str(e)[:150]}"
88
 
89
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
90
  if profile is None:
@@ -118,6 +118,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
118
 
119
  print(f"🚀 [{idx}/{total}] Task: {tid}")
120
 
 
121
  ans = agent_wrapper(q)
122
 
123
  answers.append({"task_id": tid, "submitted_answer": ans})
@@ -138,8 +139,8 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
138
  except Exception as e:
139
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
140
 
141
- with gr.Blocks(title="Final Agent (Lite Backend)") as demo:
142
- gr.Markdown("# 🚀 Final Agent (Lite Mode)")
143
  with gr.Row():
144
  gr.LoginButton()
145
  btn = gr.Button("Run Evaluation", variant="primary")
 
2
  import gradio as gr
3
  import requests
4
  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:
12
  import os
13
+ os.system('pip install ddgs')
14
  from duckduckgo_search import DDGS
15
 
16
  @tool
17
  def web_search(query: str) -> str:
18
  """
19
+ Search with strict length limits to prevent model hanging.
20
  Args:
21
  query: The search query string.
22
  """
23
+ print(f"🕵️ [Debug] Searching: {query}")
24
  try:
25
+ # 1. 使用 Lite 模式 (最快、不被擋)
26
+ # 2. 只抓 1 筆結果 (減資料量)
27
  with DDGS() as ddgs:
28
+ results = list(ddgs.text(query, max_results=1, backend="lite"))
29
 
30
  if not results:
31
+ return "No results. Guess the answer."
32
 
33
+ # 3. 關鍵修改:強制截斷文字!
34
+ # 只回傳前 400 個字,避免 70B 模型「噎住」
35
+ first_result = results[0]
36
+ title = first_result.get('title', '')
37
+ body = first_result.get('body', '')
38
+ summary = f"Title: {title}\nInfo: {body}"
39
+
40
+ return summary[:400] # <--- 這裡就是防卡死的關鍵
41
 
42
  except Exception as e:
43
+ print(f"❌ Error: {e}")
44
+ return "Search error. Guess answer."
45
 
46
  # -----------------------------------------------------------
47
 
 
54
  self.agent = None
55
  return
56
 
57
+ # 堅持使用 Llama 3.3 70B (它是唯一聰明能過關的)
58
  model = OpenAIServerModel(
59
  model_id="llama-3.3-70b-versatile",
60
  api_base="https://api.groq.com/openai/v1",
 
64
  self.agent = CodeAgent(
65
  tools=[web_search],
66
  model=model,
67
+ max_steps=2, # 減少步數,逼它快點回答
68
  verbosity_level=1
69
  )
70
 
 
73
  return "Error: GROQ_API_KEY not configured."
74
 
75
  try:
76
+ # 提示詞:極度簡化,逼它直接回答
77
  prompt = f"""
78
+ Task: Answer concisely.
79
+ 1. Search ONCE.
80
+ 2. If search fails, GUESS immediately.
81
+ 3. Do not overthink.
82
 
83
  Question: {question}
84
  """
85
  return str(self.agent.run(prompt))
86
  except Exception as e:
87
+ return f"Error: {str(e)[:100]}"
88
 
89
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
90
  if profile is None:
 
118
 
119
  print(f"🚀 [{idx}/{total}] Task: {tid}")
120
 
121
+ # 執行 Agent
122
  ans = agent_wrapper(q)
123
 
124
  answers.append({"task_id": tid, "submitted_answer": ans})
 
139
  except Exception as e:
140
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
141
 
142
+ with gr.Blocks(title="Final Agent (Truncated)") as demo:
143
+ gr.Markdown("# 🚀 Final Agent (Anti-Hang Version)")
144
  with gr.Row():
145
  gr.LoginButton()
146
  btn = gr.Button("Run Evaluation", variant="primary")