likki1715 commited on
Commit
d554102
·
verified ·
1 Parent(s): 49c8ecf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -34
app.py CHANGED
@@ -34,7 +34,10 @@ def wikipedia_search(query: str) -> str:
34
  if not results:
35
  return "No Wikipedia results found."
36
  title = results[0]["title"]
37
- summary_params = {"action": "query", "titles": title, "prop": "extracts", "exintro": True, "explaintext": True, "format": "json"}
 
 
 
38
  summary_response = requests.get(search_url, params=summary_params, timeout=10)
39
  summary_data = summary_response.json()
40
  pages = summary_data.get("query", {}).get("pages", {})
@@ -66,53 +69,70 @@ class SmartAgent:
66
  def __init__(self):
67
  self.hf_token = os.getenv("HF_TOKEN")
68
  if not self.hf_token:
69
- raise ValueError("HF_TOKEN environment variable not set!")
70
- # Use HF Inference Providers (new format)
71
- self.api_url = "https://api-inference.huggingface.co/v1/chat/completions"
72
- self.model = "Qwen/Qwen2.5-72B-Instruct"
73
  self.headers = {
74
  "Authorization": f"Bearer {self.hf_token}",
75
  "Content-Type": "application/json"
76
  }
77
- print(f"SmartAgent initialized with {self.model} (HF Inference API - FREE)")
78
 
79
- def call_llm(self, messages: list) -> str:
80
  payload = {
81
- "model": self.model,
82
- "messages": messages,
83
- "max_tokens": 1024,
84
- "temperature": 0.1,
 
 
 
85
  }
86
  response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=60)
87
  response.raise_for_status()
88
- return response.json()["choices"][0]["message"]["content"]
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  def __call__(self, question: str) -> str:
91
  print(f"\nQuestion: {question[:100]}...")
92
 
93
- system_prompt = """You are a precise AI assistant solving benchmark questions.
94
-
95
- You have access to these tools - call them by outputting exactly:
96
  SEARCH: <query>
97
  WIKIPEDIA: <query>
98
  PYTHON: <code>
99
 
100
- Rules:
101
- - Use tools to look up facts you are unsure about
102
- - After gathering info, output your final answer as: ANSWER: <your answer>
103
- - Answer must be a number, short phrase, or comma-separated list
104
- - No articles (a/the), no units unless asked, no explanations
105
- - The answer is checked by exact match so be precise"""
 
 
106
 
107
  messages = [
108
- {"role": "system", "content": system_prompt},
109
- {"role": "user", "content": question}
110
  ]
111
 
112
- for iteration in range(6):
113
- response = self.call_llm(messages)
114
- print(f" LLM: {response[:200]}")
 
115
 
 
116
  answer_match = re.search(r'ANSWER:\s*(.+?)(?:\n|$)', response, re.IGNORECASE)
117
  if answer_match:
118
  answer = answer_match.group(1).strip()
@@ -125,13 +145,13 @@ Rules:
125
  if search_match:
126
  query = search_match.group(1).strip()
127
  print(f" Tool: web_search({query})")
128
- tool_result = f"Search results for '{query}':\n{web_search(query)}"
129
 
130
  wiki_match = re.search(r'WIKIPEDIA:\s*(.+?)(?:\n|$)', response)
131
  if wiki_match:
132
  query = wiki_match.group(1).strip()
133
  print(f" Tool: wikipedia({query})")
134
- tool_result = f"Wikipedia results for '{query}':\n{wikipedia_search(query)}"
135
 
136
  python_match = re.search(r'PYTHON:\s*```(?:python)?\n?(.*?)```', response, re.DOTALL)
137
  if not python_match:
@@ -143,16 +163,18 @@ Rules:
143
 
144
  if tool_result:
145
  messages.append({"role": "assistant", "content": response})
146
- messages.append({"role": "user", "content": tool_result})
147
  else:
148
  messages.append({"role": "assistant", "content": response})
149
- messages.append({"role": "user", "content": "Please provide your final answer now using: ANSWER: <your answer>"})
150
 
151
- last_response = self.call_llm(messages)
152
- answer_match = re.search(r'ANSWER:\s*(.+?)(?:\n|$)', last_response, re.IGNORECASE)
 
 
153
  if answer_match:
154
  return answer_match.group(1).strip()
155
- return last_response.strip().split('\n')[0][:200]
156
 
157
 
158
  def run_and_submit_all(profile: gr.OAuthProfile | None):
@@ -232,7 +254,7 @@ with gr.Blocks() as demo:
232
  gr.Markdown("# 🤖 Smart Agent — GAIA Benchmark Runner")
233
  gr.Markdown(
234
  """
235
- **Powered by Qwen2.5-72B via HuggingFace Inference API (FREE)**
236
 
237
  **Instructions:**
238
  1. Make sure `HF_TOKEN` is set in your Space secrets
 
34
  if not results:
35
  return "No Wikipedia results found."
36
  title = results[0]["title"]
37
+ summary_params = {
38
+ "action": "query", "titles": title, "prop": "extracts",
39
+ "exintro": True, "explaintext": True, "format": "json"
40
+ }
41
  summary_response = requests.get(search_url, params=summary_params, timeout=10)
42
  summary_data = summary_response.json()
43
  pages = summary_data.get("query", {}).get("pages", {})
 
69
  def __init__(self):
70
  self.hf_token = os.getenv("HF_TOKEN")
71
  if not self.hf_token:
72
+ raise ValueError("HF_TOKEN not set!")
73
+ # mistralai/Mistral-7B-Instruct-v0.3 is free via HF Inference API (no credits needed)
74
+ self.api_url = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
 
75
  self.headers = {
76
  "Authorization": f"Bearer {self.hf_token}",
77
  "Content-Type": "application/json"
78
  }
79
+ print("SmartAgent initialized with Mistral-7B (FREE, no credits needed)")
80
 
81
+ def call_llm(self, prompt: str) -> str:
82
  payload = {
83
+ "inputs": prompt,
84
+ "parameters": {
85
+ "max_new_tokens": 512,
86
+ "temperature": 0.1,
87
+ "return_full_text": False,
88
+ "stop": ["</s>", "[INST]"]
89
+ }
90
  }
91
  response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=60)
92
  response.raise_for_status()
93
+ result = response.json()
94
+ if isinstance(result, list) and len(result) > 0:
95
+ return result[0].get("generated_text", "").strip()
96
+ return str(result)
97
+
98
+ def build_prompt(self, messages: list) -> str:
99
+ """Build Mistral instruction format prompt"""
100
+ prompt = "<s>"
101
+ for msg in messages:
102
+ if msg["role"] == "user":
103
+ prompt += f"[INST] {msg['content']} [/INST]"
104
+ elif msg["role"] == "assistant":
105
+ prompt += f" {msg['content']}</s>"
106
+ return prompt
107
 
108
  def __call__(self, question: str) -> str:
109
  print(f"\nQuestion: {question[:100]}...")
110
 
111
+ system = """You are a precise AI assistant solving benchmark questions.
112
+ You can use these tools by outputting exactly:
 
113
  SEARCH: <query>
114
  WIKIPEDIA: <query>
115
  PYTHON: <code>
116
 
117
+ After gathering enough info, give your final answer as:
118
+ ANSWER: <your answer>
119
+
120
+ Rules for the answer:
121
+ - Numbers only (no units unless asked)
122
+ - Short phrases (no articles like a/the)
123
+ - Comma-separated list if multiple items
124
+ - Exact match required, be precise"""
125
 
126
  messages = [
127
+ {"role": "user", "content": f"{system}\n\nQuestion: {question}"}
 
128
  ]
129
 
130
+ for iteration in range(5):
131
+ prompt = self.build_prompt(messages)
132
+ response = self.call_llm(prompt)
133
+ print(f" LLM [{iteration}]: {response[:200]}")
134
 
135
+ # Check for final answer
136
  answer_match = re.search(r'ANSWER:\s*(.+?)(?:\n|$)', response, re.IGNORECASE)
137
  if answer_match:
138
  answer = answer_match.group(1).strip()
 
145
  if search_match:
146
  query = search_match.group(1).strip()
147
  print(f" Tool: web_search({query})")
148
+ tool_result = f"Search results:\n{web_search(query)}"
149
 
150
  wiki_match = re.search(r'WIKIPEDIA:\s*(.+?)(?:\n|$)', response)
151
  if wiki_match:
152
  query = wiki_match.group(1).strip()
153
  print(f" Tool: wikipedia({query})")
154
+ tool_result = f"Wikipedia:\n{wikipedia_search(query)}"
155
 
156
  python_match = re.search(r'PYTHON:\s*```(?:python)?\n?(.*?)```', response, re.DOTALL)
157
  if not python_match:
 
163
 
164
  if tool_result:
165
  messages.append({"role": "assistant", "content": response})
166
+ messages.append({"role": "user", "content": f"{tool_result}\n\nNow provide your ANSWER: <answer>"})
167
  else:
168
  messages.append({"role": "assistant", "content": response})
169
+ messages.append({"role": "user", "content": "Provide your final answer as: ANSWER: <answer>"})
170
 
171
+ # Final attempt
172
+ messages.append({"role": "user", "content": "Give only the final answer as: ANSWER: <answer>"})
173
+ last = self.call_llm(self.build_prompt(messages))
174
+ answer_match = re.search(r'ANSWER:\s*(.+?)(?:\n|$)', last, re.IGNORECASE)
175
  if answer_match:
176
  return answer_match.group(1).strip()
177
+ return last.strip().split('\n')[0][:200]
178
 
179
 
180
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
254
  gr.Markdown("# 🤖 Smart Agent — GAIA Benchmark Runner")
255
  gr.Markdown(
256
  """
257
+ **Powered by Mistral-7B via HuggingFace Inference API (100% FREE - no credits needed)**
258
 
259
  **Instructions:**
260
  1. Make sure `HF_TOKEN` is set in your Space secrets