likki1715 commited on
Commit
4582aec
·
verified ·
1 Parent(s): d554102

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -52
app.py CHANGED
@@ -67,48 +67,31 @@ def run_python(code: str) -> str:
67
 
68
  class SmartAgent:
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>
@@ -118,18 +101,15 @@ 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
@@ -145,13 +125,13 @@ Rules for the answer:
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:
@@ -162,15 +142,13 @@ Rules for the answer:
162
  tool_result = f"Python output:\n{run_python(code)}"
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()
@@ -254,10 +232,10 @@ with gr.Blocks() as demo:
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
261
  2. Log in with your Hugging Face account below
262
  3. Click **Run Evaluation & Submit All Answers**
263
  """
 
67
 
68
  class SmartAgent:
69
  def __init__(self):
70
+ self.api_key = os.getenv("GEMINI_API_KEY")
71
+ if not self.api_key:
72
+ raise ValueError("GEMINI_API_KEY environment variable not set!")
73
+ # Gemini 1.5 Flash - FREE tier: 1500 requests/day, 1M tokens/min
74
+ self.api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={self.api_key}"
75
+ print("SmartAgent initialized with Gemini 1.5 Flash (FREE - 1500 req/day)")
 
 
 
 
76
 
77
  def call_llm(self, prompt: str) -> str:
78
  payload = {
79
+ "contents": [{"parts": [{"text": prompt}]}],
80
+ "generationConfig": {
 
81
  "temperature": 0.1,
82
+ "maxOutputTokens": 1024,
 
83
  }
84
  }
85
+ response = requests.post(self.api_url, json=payload, timeout=60)
86
  response.raise_for_status()
87
+ data = response.json()
88
+ return data["candidates"][0]["content"]["parts"][0]["text"].strip()
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  def __call__(self, question: str) -> str:
91
  print(f"\nQuestion: {question[:100]}...")
92
 
93
  system = """You are a precise AI assistant solving benchmark questions.
94
+
95
  You can use these tools by outputting exactly:
96
  SEARCH: <query>
97
  WIKIPEDIA: <query>
 
101
  ANSWER: <your answer>
102
 
103
  Rules for the answer:
104
+ - Numbers only (no units unless asked, no commas in numbers)
105
+ - Short phrases (no articles like a/the, no abbreviations for proper nouns)
106
+ - Comma-separated list if multiple items needed
107
+ - Exact match required - be very precise"""
108
+
109
+ conversation = f"{system}\n\nQuestion: {question}"
110
+
111
+ for iteration in range(6):
112
+ response = self.call_llm(conversation)
 
 
 
113
  print(f" LLM [{iteration}]: {response[:200]}")
114
 
115
  # Check for final answer
 
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:
 
142
  tool_result = f"Python output:\n{run_python(code)}"
143
 
144
  if tool_result:
145
+ conversation += f"\n\nAssistant: {response}\n\nTool Result: {tool_result}\n\nNow provide your ANSWER: <answer>"
 
146
  else:
147
+ conversation += f"\n\nAssistant: {response}\n\nProvide your final answer as: ANSWER: <answer>"
 
148
 
149
  # Final attempt
150
+ conversation += "\n\nGive only the final answer as: ANSWER: <answer>"
151
+ last = self.call_llm(conversation)
152
  answer_match = re.search(r'ANSWER:\s*(.+?)(?:\n|$)', last, re.IGNORECASE)
153
  if answer_match:
154
  return answer_match.group(1).strip()
 
232
  gr.Markdown("# 🤖 Smart Agent — GAIA Benchmark Runner")
233
  gr.Markdown(
234
  """
235
+ **Powered by Google Gemini 1.5 Flash (FREE - 1500 requests/day)**
236
 
237
  **Instructions:**
238
+ 1. Make sure `GEMINI_API_KEY` is set in your Space secrets
239
  2. Log in with your Hugging Face account below
240
  3. Click **Run Evaluation & Submit All Answers**
241
  """