Spaces:
Sleeping
Sleeping
meh
Browse files
app.py
CHANGED
|
@@ -110,7 +110,7 @@ class KnowledgeBaseTool(Tool):
|
|
| 110 |
|
| 111 |
class WikipediaSearchTool(Tool):
|
| 112 |
name = "wikipedia_search"
|
| 113 |
-
description = "Search Wikipedia for information"
|
| 114 |
inputs = {"query": {"type": "string", "description": "The search query for Wikipedia"}}
|
| 115 |
output_type = "string"
|
| 116 |
|
|
@@ -119,19 +119,50 @@ class WikipediaSearchTool(Tool):
|
|
| 119 |
self.is_initialized = True
|
| 120 |
|
| 121 |
def forward(self, query: str) -> str:
|
| 122 |
-
"""Search Wikipedia with
|
| 123 |
try:
|
| 124 |
import requests
|
|
|
|
|
|
|
| 125 |
wiki_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
|
| 126 |
-
response = requests.get(wiki_url, timeout=
|
| 127 |
if response.status_code == 200:
|
| 128 |
data = response.json()
|
| 129 |
if 'extract' in data and data['extract']:
|
| 130 |
-
return f"Wikipedia: {data['extract'][:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
print(f"Wikipedia search failed: {e}")
|
| 133 |
|
| 134 |
-
return f"Wikipedia search unavailable for '{query}'.
|
| 135 |
|
| 136 |
# --- Mathematical Tools ---
|
| 137 |
class MathTool(Tool):
|
|
@@ -394,12 +425,12 @@ class SlpMultiAgent:
|
|
| 394 |
|
| 395 |
manager_agent = CodeAgent(
|
| 396 |
model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
|
| 397 |
-
tools=[GoogleSearchTool(), MathTool()],
|
| 398 |
name="ManagerAgent",
|
| 399 |
-
description="Answer questions using
|
| 400 |
-
additional_authorized_imports=["re", "math", "
|
| 401 |
verbosity_level=0,
|
| 402 |
-
max_steps=
|
| 403 |
)
|
| 404 |
|
| 405 |
# Create a task for the agent run with retry mechanism for rate limits
|
|
@@ -414,16 +445,19 @@ class SlpMultiAgent:
|
|
| 414 |
lambda: manager_agent.run(f"""
|
| 415 |
Question: {short_question}
|
| 416 |
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
-
|
|
|
|
| 420 |
<code>
|
| 421 |
-
#
|
| 422 |
-
result =
|
| 423 |
-
#
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
final_answer("your answer")
|
| 427 |
</code>
|
| 428 |
""")
|
| 429 |
)
|
|
@@ -458,10 +492,14 @@ class SlpMultiAgent:
|
|
| 458 |
]
|
| 459 |
|
| 460 |
for pattern in final_answer_patterns:
|
| 461 |
-
match = re.search(pattern, result, re.IGNORECASE)
|
| 462 |
if match:
|
| 463 |
clean_answer = match.group(1).strip('"\'')
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
# If no final_answer found, try to extract the last meaningful line
|
| 467 |
lines = result.strip().split('\n')
|
|
|
|
| 110 |
|
| 111 |
class WikipediaSearchTool(Tool):
|
| 112 |
name = "wikipedia_search"
|
| 113 |
+
description = "Search Wikipedia for detailed information on topics, people, places, events"
|
| 114 |
inputs = {"query": {"type": "string", "description": "The search query for Wikipedia"}}
|
| 115 |
output_type = "string"
|
| 116 |
|
|
|
|
| 119 |
self.is_initialized = True
|
| 120 |
|
| 121 |
def forward(self, query: str) -> str:
|
| 122 |
+
"""Search Wikipedia with multiple approaches."""
|
| 123 |
try:
|
| 124 |
import requests
|
| 125 |
+
|
| 126 |
+
# Try direct page lookup first
|
| 127 |
wiki_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
|
| 128 |
+
response = requests.get(wiki_url, timeout=5)
|
| 129 |
if response.status_code == 200:
|
| 130 |
data = response.json()
|
| 131 |
if 'extract' in data and data['extract']:
|
| 132 |
+
return f"Wikipedia: {data['extract'][:800]}"
|
| 133 |
+
|
| 134 |
+
# Try search API if direct lookup fails
|
| 135 |
+
search_url = "https://en.wikipedia.org/w/api.php"
|
| 136 |
+
search_params = {
|
| 137 |
+
'action': 'query',
|
| 138 |
+
'format': 'json',
|
| 139 |
+
'list': 'search',
|
| 140 |
+
'srsearch': query,
|
| 141 |
+
'srlimit': 3
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
search_response = requests.get(search_url, params=search_params, timeout=5)
|
| 145 |
+
if search_response.status_code == 200:
|
| 146 |
+
search_data = search_response.json()
|
| 147 |
+
if 'query' in search_data and 'search' in search_data['query']:
|
| 148 |
+
results = search_data['query']['search']
|
| 149 |
+
if results:
|
| 150 |
+
# Get the first result's content
|
| 151 |
+
first_title = results[0]['title']
|
| 152 |
+
content_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + first_title.replace(" ", "_")
|
| 153 |
+
content_response = requests.get(content_url, timeout=5)
|
| 154 |
+
if content_response.status_code == 200:
|
| 155 |
+
content_data = content_response.json()
|
| 156 |
+
if 'extract' in content_data and content_data['extract']:
|
| 157 |
+
return f"Wikipedia ({first_title}): {content_data['extract'][:800]}"
|
| 158 |
+
|
| 159 |
+
# Fallback to search snippet
|
| 160 |
+
return f"Wikipedia search results: {results[0]['snippet'][:400]}"
|
| 161 |
+
|
| 162 |
except Exception as e:
|
| 163 |
print(f"Wikipedia search failed: {e}")
|
| 164 |
|
| 165 |
+
return f"Wikipedia search unavailable for '{query}'. Try using google_search() instead."
|
| 166 |
|
| 167 |
# --- Mathematical Tools ---
|
| 168 |
class MathTool(Tool):
|
|
|
|
| 425 |
|
| 426 |
manager_agent = CodeAgent(
|
| 427 |
model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
|
| 428 |
+
tools=[GoogleSearchTool(), WikipediaSearchTool(), DuckDuckGoSearchTool(), MathTool()],
|
| 429 |
name="ManagerAgent",
|
| 430 |
+
description="Answer questions using search tools and math.",
|
| 431 |
+
additional_authorized_imports=["re", "math", "requests"],
|
| 432 |
verbosity_level=0,
|
| 433 |
+
max_steps=4
|
| 434 |
)
|
| 435 |
|
| 436 |
# Create a task for the agent run with retry mechanism for rate limits
|
|
|
|
| 445 |
lambda: manager_agent.run(f"""
|
| 446 |
Question: {short_question}
|
| 447 |
|
| 448 |
+
Instructions:
|
| 449 |
+
1. For Wikipedia questions, use wikipedia_search() first
|
| 450 |
+
2. For other factual questions, try google_search() or web_search()
|
| 451 |
+
3. For math problems, use math_calculator()
|
| 452 |
+
4. Give a specific, direct answer
|
| 453 |
|
| 454 |
+
Format:
|
| 455 |
+
Thoughts: [brief reasoning]
|
| 456 |
<code>
|
| 457 |
+
# Search for information
|
| 458 |
+
result = wikipedia_search("search term") # or google_search() or web_search()
|
| 459 |
+
# Extract the specific answer from results
|
| 460 |
+
final_answer("specific answer only")
|
|
|
|
|
|
|
| 461 |
</code>
|
| 462 |
""")
|
| 463 |
)
|
|
|
|
| 492 |
]
|
| 493 |
|
| 494 |
for pattern in final_answer_patterns:
|
| 495 |
+
match = re.search(pattern, result, re.IGNORECASE | re.DOTALL)
|
| 496 |
if match:
|
| 497 |
clean_answer = match.group(1).strip('"\'')
|
| 498 |
+
# Clean up common artifacts
|
| 499 |
+
clean_answer = re.sub(r'^[\s\n]*', '', clean_answer)
|
| 500 |
+
clean_answer = re.sub(r'[\s\n]*$', '', clean_answer)
|
| 501 |
+
if clean_answer and not clean_answer.startswith('If you have'):
|
| 502 |
+
return clean_answer
|
| 503 |
|
| 504 |
# If no final_answer found, try to extract the last meaningful line
|
| 505 |
lines = result.strip().split('\n')
|