Spaces:
Running on Zero
Running on Zero
Gemini grounded search tool + direct-answer fallback; drop DuckDuckGo
Browse files
app.py
CHANGED
|
@@ -5,7 +5,7 @@ import requests
|
|
| 5 |
import inspect
|
| 6 |
import pandas as pd
|
| 7 |
import spaces
|
| 8 |
-
from smolagents import CodeAgent, LiteLLMModel,
|
| 9 |
|
| 10 |
|
| 11 |
# (Keep Constants as is)
|
|
@@ -19,6 +19,41 @@ def _zero_gpu_keepalive():
|
|
| 19 |
return "ok"
|
| 20 |
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# --- Extra tools for the GAIA agent ---
|
| 23 |
@tool
|
| 24 |
def search_wikipedia(query: str) -> str:
|
|
@@ -150,13 +185,13 @@ class BasicAgent:
|
|
| 150 |
# Gemini via LiteLLM. gemini-2.5-flash and gemini-2.0-flash are retired
|
| 151 |
# for this key (Google returns 404), so use the current flash model.
|
| 152 |
model = LiteLLMModel(
|
| 153 |
-
model_id="gemini/
|
| 154 |
api_key=os.getenv("GEMINI_API_KEY"),
|
| 155 |
)
|
| 156 |
self.agent = CodeAgent(
|
| 157 |
-
tools=[
|
| 158 |
model=model,
|
| 159 |
-
max_steps=
|
| 160 |
)
|
| 161 |
print("BasicAgent initialized.")
|
| 162 |
|
|
@@ -168,14 +203,41 @@ class BasicAgent:
|
|
| 168 |
"When you know the answer, finish with exactly one line in this format: FINAL ANSWER: <your answer> "
|
| 169 |
"Do not add anything after that line."
|
| 170 |
)
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
print(f"Agent returning answer: {answer}")
|
| 177 |
return answer
|
| 178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
|
| 181 |
|
|
|
|
| 5 |
import inspect
|
| 6 |
import pandas as pd
|
| 7 |
import spaces
|
| 8 |
+
from smolagents import CodeAgent, LiteLLMModel, VisitWebpageTool, tool
|
| 9 |
|
| 10 |
|
| 11 |
# (Keep Constants as is)
|
|
|
|
| 19 |
return "ok"
|
| 20 |
|
| 21 |
|
| 22 |
+
# --- Gemini with Google Search grounding ---
|
| 23 |
+
# DuckDuckGo rate-limits requests coming from HF Spaces ("No results found"),
|
| 24 |
+
# so web search goes through Gemini's built-in Google Search grounding instead.
|
| 25 |
+
GEMINI_MODEL = "gemini-3.8-flash"
|
| 26 |
+
GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def gemini_grounded(prompt: str, timeout: int = 90) -> str:
|
| 30 |
+
"""Ask Gemini a question with Google Search grounding and return its text."""
|
| 31 |
+
resp = requests.post(
|
| 32 |
+
GEMINI_URL,
|
| 33 |
+
headers={"x-goog-api-key": os.getenv("GEMINI_API_KEY", ""), "Content-Type": "application/json"},
|
| 34 |
+
json={"contents": [{"parts": [{"text": prompt}]}], "tools": [{"google_search": {}}]},
|
| 35 |
+
timeout=timeout,
|
| 36 |
+
)
|
| 37 |
+
resp.raise_for_status()
|
| 38 |
+
parts = resp.json()["candidates"][0]["content"]["parts"]
|
| 39 |
+
return "".join(p.get("text", "") for p in parts).strip()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@tool
|
| 43 |
+
def google_search(query: str) -> str:
|
| 44 |
+
"""Search the web with Google (via Gemini grounding) and return a factual summary with key details.
|
| 45 |
+
Args:
|
| 46 |
+
query: The search query or factual question to look up.
|
| 47 |
+
"""
|
| 48 |
+
try:
|
| 49 |
+
return gemini_grounded(
|
| 50 |
+
"Search the web and give a factual, detailed answer with specific names, numbers and dates. "
|
| 51 |
+
"Query: " + query
|
| 52 |
+
)[:6000]
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return f"Search failed: {e}"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
# --- Extra tools for the GAIA agent ---
|
| 58 |
@tool
|
| 59 |
def search_wikipedia(query: str) -> str:
|
|
|
|
| 185 |
# Gemini via LiteLLM. gemini-2.5-flash and gemini-2.0-flash are retired
|
| 186 |
# for this key (Google returns 404), so use the current flash model.
|
| 187 |
model = LiteLLMModel(
|
| 188 |
+
model_id=f"gemini/{GEMINI_MODEL}",
|
| 189 |
api_key=os.getenv("GEMINI_API_KEY"),
|
| 190 |
)
|
| 191 |
self.agent = CodeAgent(
|
| 192 |
+
tools=[google_search, VisitWebpageTool(), search_wikipedia, read_file, get_youtube_transcript],
|
| 193 |
model=model,
|
| 194 |
+
max_steps=12,
|
| 195 |
)
|
| 196 |
print("BasicAgent initialized.")
|
| 197 |
|
|
|
|
| 203 |
"When you know the answer, finish with exactly one line in this format: FINAL ANSWER: <your answer> "
|
| 204 |
"Do not add anything after that line."
|
| 205 |
)
|
| 206 |
+
try:
|
| 207 |
+
result = self.agent.run(prompt)
|
| 208 |
+
except Exception as e:
|
| 209 |
+
print(f"Agent run failed: {e}")
|
| 210 |
+
result = None
|
| 211 |
+
answer = self._clean(result)
|
| 212 |
+
if self._is_junk(answer):
|
| 213 |
+
print(f"Agent answer unusable ({answer!r}); using grounded fallback.")
|
| 214 |
+
try:
|
| 215 |
+
answer = self._clean(gemini_grounded(
|
| 216 |
+
question
|
| 217 |
+
+ "\n\nResearch this carefully, then reply with ONLY the final answer on the last line as "
|
| 218 |
+
"'FINAL ANSWER: <answer>'. The answer must be a number, a few words, or a comma-separated list, "
|
| 219 |
+
"with no units or explanation unless the question asks for them."
|
| 220 |
+
))
|
| 221 |
+
except Exception as e:
|
| 222 |
+
print(f"Fallback failed: {e}")
|
| 223 |
print(f"Agent returning answer: {answer}")
|
| 224 |
return answer
|
| 225 |
|
| 226 |
+
@staticmethod
|
| 227 |
+
def _clean(result) -> str:
|
| 228 |
+
"""Pull the text after the last 'FINAL ANSWER:' and keep its first line."""
|
| 229 |
+
answer = "" if result is None else str(result).strip()
|
| 230 |
+
if "FINAL ANSWER:" in answer:
|
| 231 |
+
answer = answer.split("FINAL ANSWER:")[-1].strip()
|
| 232 |
+
return answer.split("\n")[0].strip().strip("*").strip()
|
| 233 |
+
|
| 234 |
+
@staticmethod
|
| 235 |
+
def _is_junk(answer: str) -> bool:
|
| 236 |
+
"""True for empty answers or obvious leftovers like 'None', 'Thought:' or '{answer}'."""
|
| 237 |
+
low = answer.lower()
|
| 238 |
+
return (not answer or low in ("none", "null", "thought:") or "{answer}" in low
|
| 239 |
+
or low.startswith("thought") or len(answer) > 200)
|
| 240 |
+
|
| 241 |
|
| 242 |
|
| 243 |
|