Spaces:
Sleeping
Sleeping
jesusgj
commited on
Commit
·
892cc72
1
Parent(s):
80ef074
Modified files
Browse files
agent.py
CHANGED
|
@@ -1,177 +1,275 @@
|
|
| 1 |
import os
|
| 2 |
-
import re
|
| 3 |
-
import requests
|
| 4 |
-
import serpapi
|
| 5 |
import time
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
-
from markdownify import markdownify
|
| 10 |
from requests.exceptions import RequestException
|
|
|
|
| 11 |
from llama_index.core import VectorStoreIndex, download_loader
|
| 12 |
from llama_index.core.schema import Document
|
| 13 |
-
from youtube_transcript_api import YouTubeTranscriptApi
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
webpage_cache = {}
|
| 17 |
-
MAX_RETRIES = 3
|
| 18 |
-
INITIAL_DELAY = 1 # seconds
|
| 19 |
|
| 20 |
-
def
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
load_dotenv()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
# 2. Define the tools
|
| 34 |
@tool
|
| 35 |
def query_webpage(url: str, query: str) -> str:
|
| 36 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
| 44 |
"""
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
webpage_cache[(url, query)] = str(response)
|
| 57 |
-
return str(response)
|
| 58 |
-
|
| 59 |
-
except Exception as e:
|
| 60 |
-
if i < MAX_RETRIES - 1:
|
| 61 |
-
delay = INITIAL_DELAY * (2 ** i)
|
| 62 |
-
print(f"Error querying webpage: {str(e)}. Retrying in {delay} seconds...")
|
| 63 |
-
time.sleep(delay)
|
| 64 |
-
else:
|
| 65 |
-
return f"An unexpected error occurred after multiple retries: {str(e)}"
|
| 66 |
|
|
|
|
| 67 |
@tool
|
| 68 |
-
def
|
| 69 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
response = query_engine.query(query)
|
| 90 |
-
webpage_cache[(video_id, query)] = str(response)
|
| 91 |
-
return str(response)
|
| 92 |
-
|
| 93 |
-
except Exception as e:
|
| 94 |
-
if i < MAX_RETRIES - 1:
|
| 95 |
-
delay = INITIAL_DELAY * (2 ** i)
|
| 96 |
-
print(f"Error querying YouTube video: {str(e)}. Retrying in {delay} seconds...")
|
| 97 |
-
time.sleep(delay)
|
| 98 |
-
else:
|
| 99 |
-
return f"An unexpected error occurred after multiple retries: {str(e)}"
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
query: The query to search for.
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
if query in search_cache:
|
| 112 |
-
return search_cache[query]
|
| 113 |
-
|
| 114 |
-
for i in range(MAX_RETRIES):
|
| 115 |
-
try:
|
| 116 |
-
client = serpapi.Client(api_key=os.environ.get("SERPAPI_API_KEY"))
|
| 117 |
-
results = client.search(q=query, engine="google")
|
| 118 |
-
if "ai_overview" in results:
|
| 119 |
-
ai_overview = results["ai_overview"]
|
| 120 |
-
output = ""
|
| 121 |
-
for block in ai_overview.get("text_blocks", []):
|
| 122 |
-
if block["type"] == "paragraph":
|
| 123 |
-
output += block["snippet"] + "\n\n"
|
| 124 |
-
elif block["type"] == "heading":
|
| 125 |
-
output += f"### {block['snippet']}\n\n"
|
| 126 |
-
elif block["type"] == "list":
|
| 127 |
-
for item in block["list"]:
|
| 128 |
-
output += f"- **{item['title']}** {item['snippet']}\n"
|
| 129 |
-
output += "\n"
|
| 130 |
-
if "references" in ai_overview:
|
| 131 |
-
output += "\n**References:**\n"
|
| 132 |
-
for ref in ai_overview["references"]:
|
| 133 |
-
output += f"- [{ref['title']}]({ref['link']})\n"
|
| 134 |
-
search_cache[query] = output
|
| 135 |
-
return output
|
| 136 |
-
elif "organic_results" in results:
|
| 137 |
-
result = str(results["organic_results"])
|
| 138 |
-
search_cache[query] = result
|
| 139 |
-
return result
|
| 140 |
-
else:
|
| 141 |
-
return "No results found."
|
| 142 |
-
except Exception as e:
|
| 143 |
-
if i < MAX_RETRIES - 1:
|
| 144 |
-
delay = INITIAL_DELAY * (2 ** i)
|
| 145 |
-
print(f"Error performing Google search: {str(e)}. Retrying in {delay} seconds...")
|
| 146 |
-
time.sleep(delay)
|
| 147 |
-
else:
|
| 148 |
-
return f"Error performing Google search after multiple retries: {str(e)}"
|
| 149 |
-
|
| 150 |
-
# 3. Define the agents
|
| 151 |
-
if model:
|
| 152 |
-
web_agent = ToolCallingAgent(
|
| 153 |
-
tools=[WebSearchTool(), query_webpage, query_youtube_video, google_search],
|
| 154 |
-
model=model,
|
| 155 |
-
max_steps=10,
|
| 156 |
-
name="web_search_agent",
|
| 157 |
-
description="Runs web searches for you.",
|
| 158 |
-
)
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
import time
|
| 3 |
+
import logging
|
| 4 |
+
import urllib.parse as urlparse
|
| 5 |
+
import io
|
| 6 |
+
import contextlib
|
| 7 |
+
from functools import lru_cache, wraps
|
| 8 |
+
|
| 9 |
+
# Add necessary imports for new tools
|
| 10 |
+
import chess
|
| 11 |
+
from stockfish import Stockfish
|
| 12 |
+
|
| 13 |
from dotenv import load_dotenv
|
|
|
|
| 14 |
from requests.exceptions import RequestException
|
| 15 |
+
import serpapi
|
| 16 |
from llama_index.core import VectorStoreIndex, download_loader
|
| 17 |
from llama_index.core.schema import Document
|
| 18 |
+
from youtube_transcript_api import YouTubeTranscriptApi, YouTubeTranscriptApiError
|
| 19 |
+
from smolagents import CodeAgent, ToolCallingAgent, WebSearchTool, tool
|
| 20 |
+
from smolagents import InferenceClientModel
|
| 21 |
|
| 22 |
+
# --- Configuration and Setup ---
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
def configure_logging():
|
| 25 |
+
"""Sets up basic logging configuration."""
|
| 26 |
+
logging.basicConfig(
|
| 27 |
+
level=logging.INFO,
|
| 28 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 29 |
+
datefmt="%Y-%m-%d %H:%M:%S"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def load_api_keys():
|
| 33 |
+
"""Loads API keys from a .env file."""
|
| 34 |
load_dotenv()
|
| 35 |
+
keys = {
|
| 36 |
+
'together': os.getenv('TOGETHER_API_KEY'),
|
| 37 |
+
'serpapi': os.getenv('SERPAPI_API_KEY'),
|
| 38 |
+
}
|
| 39 |
+
if not all(keys.values()):
|
| 40 |
+
raise ValueError("One or more API keys are missing. Please check your .env file.")
|
| 41 |
+
return keys
|
| 42 |
|
| 43 |
+
# --- Decorators ---
|
| 44 |
+
|
| 45 |
+
def retry(max_retries=3, initial_delay=1, backoff=2):
|
| 46 |
+
"""A robust retry decorator with exponential backoff."""
|
| 47 |
+
def decorator(func):
|
| 48 |
+
@wraps(func)
|
| 49 |
+
def wrapper(*args, **kwargs):
|
| 50 |
+
delay = initial_delay
|
| 51 |
+
# Define specific, retry-able exceptions
|
| 52 |
+
retryable_exceptions = (RequestException, SerpApiClientException, YouTubeTranscriptApiError)
|
| 53 |
+
for attempt in range(1, max_retries + 1):
|
| 54 |
+
try:
|
| 55 |
+
return func(*args, **kwargs)
|
| 56 |
+
except retryable_exceptions as e:
|
| 57 |
+
if attempt == max_retries:
|
| 58 |
+
logging.error(f"{func.__name__} failed after {attempt} attempts: {e}")
|
| 59 |
+
raise
|
| 60 |
+
logging.warning(f"Attempt {attempt} for {func.__name__} failed: {e}. Retrying in {delay} seconds...")
|
| 61 |
+
time.sleep(delay)
|
| 62 |
+
delay *= backoff
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logging.error(f"{func.__name__} failed with a non-retryable error: {e}")
|
| 65 |
+
raise
|
| 66 |
+
return wrapper
|
| 67 |
+
return decorator
|
| 68 |
+
|
| 69 |
+
# --- Main Agent Initialization (as called by app.py) ---
|
| 70 |
+
|
| 71 |
+
def initialize_agent():
|
| 72 |
+
"""
|
| 73 |
+
Initializes a multi-disciplinary agent with a toolset and reasoning framework
|
| 74 |
+
designed for the benchmark's question categories.
|
| 75 |
+
"""
|
| 76 |
+
api_keys = load_api_keys()
|
| 77 |
+
|
| 78 |
+
# --- Caching Layer for LlamaIndex ---
|
| 79 |
+
@lru_cache(maxsize=32)
|
| 80 |
+
@retry()
|
| 81 |
+
def get_webpage_index(url: str) -> VectorStoreIndex:
|
| 82 |
+
logging.info(f"Indexing webpage: {url}")
|
| 83 |
+
loader_cls = download_loader("BeautifulSoupWebReader")
|
| 84 |
+
loader = loader_cls()
|
| 85 |
+
docs = loader.load_data(urls=[url])
|
| 86 |
+
return VectorStoreIndex.from_documents(docs)
|
| 87 |
+
|
| 88 |
+
@lru_cache(maxsize=32)
|
| 89 |
+
@retry()
|
| 90 |
+
def get_youtube_index(video_id: str) -> VectorStoreIndex:
|
| 91 |
+
logging.info(f"Indexing YouTube video: {video_id}")
|
| 92 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
| 93 |
+
text = ' '.join([t['text'] for t in transcript])
|
| 94 |
+
doc = Document(text=text, doc_id=f"youtube_{video_id}")
|
| 95 |
+
return VectorStoreIndex.from_documents([doc])
|
| 96 |
+
|
| 97 |
+
# --- Specialized Tool Definitions ---
|
| 98 |
+
|
| 99 |
+
# 1. Web Search Tools
|
| 100 |
+
@tool
|
| 101 |
+
@retry()
|
| 102 |
+
def google_search(query: str) -> str:
|
| 103 |
+
"""Use for general knowledge questions, finding facts, or when you don't have a specific URL."""
|
| 104 |
+
client = serpapi.Client(api_key=api_keys['serpapi'])
|
| 105 |
+
results = client.search(q=query, engine="google")
|
| 106 |
+
if organic_results := results.get('organic_results'):
|
| 107 |
+
md = ["### Top Search Results"]
|
| 108 |
+
for res in organic_results[:5]:
|
| 109 |
+
md.append(f"- **{res.get('title', 'N/A')}**: {res.get('snippet', 'No snippet available.')}\n [Source]({res.get('link', '#')})")
|
| 110 |
+
return "\n\n".join(md)
|
| 111 |
+
return "No results found."
|
| 112 |
|
|
|
|
| 113 |
@tool
|
| 114 |
def query_webpage(url: str, query: str) -> str:
|
| 115 |
+
"""Use when you need to answer a specific question about the content of a single webpage URL."""
|
| 116 |
+
try:
|
| 117 |
+
index = get_webpage_index(url)
|
| 118 |
+
return str(index.as_query_engine().query(query))
|
| 119 |
+
except Exception as e:
|
| 120 |
+
return f"Error querying webpage {url}: {e}"
|
| 121 |
|
| 122 |
+
# 2. YouTube Tool
|
| 123 |
+
@tool
|
| 124 |
+
def query_youtube_video(video_url_or_id: str, query: str) -> str:
|
| 125 |
+
"""Use for questions about the content of a YouTube video. Accepts a full URL or a video ID."""
|
| 126 |
+
try:
|
| 127 |
+
video_id = video_url_or_id
|
| 128 |
+
if "youtube.com" in video_url_or_id or "youtu.be" in video_url_or_id:
|
| 129 |
+
parsed_url = urlparse.urlparse(video_url_or_id)
|
| 130 |
+
video_id = urlparse.parse_qs(parsed_url.query).get('v', [None])[0]
|
| 131 |
+
if not video_id:
|
| 132 |
+
video_id = parsed_url.path.lstrip('/')
|
| 133 |
+
if not video_id:
|
| 134 |
+
return "Error: Could not extract a valid YouTube video ID."
|
| 135 |
+
index = get_youtube_index(video_id)
|
| 136 |
+
return str(index.as_query_engine().query(query))
|
| 137 |
+
except YouTubeTranscriptApiError as e:
|
| 138 |
+
return f"Error fetching transcript for video {video_id}: {e}"
|
| 139 |
+
except Exception as e:
|
| 140 |
+
return f"Error querying YouTube video {video_id}: {e}"
|
| 141 |
|
| 142 |
+
# 3. Coding Tool
|
| 143 |
+
@tool
|
| 144 |
+
def run_python_code(code: str) -> str:
|
| 145 |
"""
|
| 146 |
+
Executes a string of Python code and returns its standard output.
|
| 147 |
+
Use this for coding challenges, calculations, or data manipulation.
|
| 148 |
+
The code is executed in a restricted environment; it cannot access external files.
|
| 149 |
+
"""
|
| 150 |
+
output = io.StringIO()
|
| 151 |
+
try:
|
| 152 |
+
with contextlib.redirect_stdout(output):
|
| 153 |
+
exec(code, {})
|
| 154 |
+
return output.getvalue()
|
| 155 |
+
except Exception as e:
|
| 156 |
+
return f"Error executing code: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
+
# 4. Chess Tool
|
| 159 |
@tool
|
| 160 |
+
def get_chess_move(fen: str) -> str:
|
| 161 |
+
"""
|
| 162 |
+
Finds the best chess move for a given board position in FEN format.
|
| 163 |
+
Use this exclusively for chess-related questions.
|
| 164 |
+
"""
|
| 165 |
+
# Path to stockfish can be set via env var for flexibility in HF Spaces
|
| 166 |
+
stockfish_path = os.getenv("STOCKFISH_PATH", "/usr/games/stockfish")
|
| 167 |
+
if not os.path.exists(stockfish_path):
|
| 168 |
+
return f"Error: Stockfish engine not found at {stockfish_path}. Please set STOCKFISH_PATH environment variable."
|
| 169 |
+
try:
|
| 170 |
+
stockfish = Stockfish(path=stockfish_path)
|
| 171 |
+
stockfish.set_fen_position(fen)
|
| 172 |
+
best_move = stockfish.get_best_move()
|
| 173 |
+
return best_move
|
| 174 |
+
except Exception as e:
|
| 175 |
+
return f"Error analyzing chess position: {e}"
|
| 176 |
|
| 177 |
+
# --- Model and Agent Initialization ---
|
| 178 |
+
|
| 179 |
+
try:
|
| 180 |
+
model = InferenceClientModel(
|
| 181 |
+
model_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 182 |
+
token=api_keys['together'],
|
| 183 |
+
provider="together"
|
| 184 |
+
)
|
| 185 |
+
logging.info("Model loaded successfully.")
|
| 186 |
+
except Exception as e:
|
| 187 |
+
logging.error(f"Failed to load model: {e}")
|
| 188 |
+
raise
|
| 189 |
|
| 190 |
+
# A single, powerful worker agent with a diverse toolset
|
| 191 |
+
worker_agent = ToolCallingAgent(
|
| 192 |
+
tools=[
|
| 193 |
+
google_search,
|
| 194 |
+
query_webpage,
|
| 195 |
+
query_youtube_video,
|
| 196 |
+
run_python_code,
|
| 197 |
+
get_chess_move,
|
| 198 |
+
],
|
| 199 |
+
model=model,
|
| 200 |
+
max_steps=5, # Sub-tasks should be short and focused
|
| 201 |
+
name="multi_tool_worker",
|
| 202 |
+
description="A specialized worker agent that can search the web, query videos, execute code, and play chess."
|
| 203 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
# The manager agent acts as a strategic dispatcher.
|
| 206 |
+
manager = CodeAgent(
|
| 207 |
+
model=model,
|
| 208 |
+
managed_agents=[worker_agent],
|
| 209 |
+
instructions="""
|
| 210 |
+
You are a master AI assistant responsible for answering a user's question. Your goal is to provide a single, precise, and final answer.
|
| 211 |
|
| 212 |
+
**Your Strategic Thought Process for GAIA Tasks:**
|
|
|
|
| 213 |
|
| 214 |
+
1. **ANALYZE THE QUESTION (Deep Understanding):**
|
| 215 |
+
* Carefully read and dissect the user's question. Identify all constraints, keywords, and the exact format required for the final answer (e.g., number, string, comma-separated list, specific units).
|
| 216 |
+
* Determine the core task: Is it a factual lookup, data extraction, code execution, video analysis, or a chess problem?
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
+
2. **FORMULATE A DETAILED PLAN (Multi-step if needed):**
|
| 219 |
+
* Based on your analysis, outline a step-by-step strategy. For complex questions (Level 2/3 GAIA), this plan might involve multiple tool calls and intermediate reasoning steps.
|
| 220 |
+
* **Prioritize Tools:**
|
| 221 |
+
* For general web searches or initial broad information gathering, prefer `WebSearchTool()`. It's often quicker for a first pass.
|
| 222 |
+
* If `WebSearchTool()` doesn't yield precise results, or if you need structured data (e.g., AI overviews, specific facts from search results), use `google_search` (SerpApi).
|
| 223 |
+
* For extracting specific information from a known webpage URL, use `query_webpage`.
|
| 224 |
+
* For questions about YouTube video content, use `query_youtube_video`.
|
| 225 |
+
* For computational tasks or code generation, use `run_python_code`.
|
| 226 |
+
* For chess problems, use `get_chess_move`.
|
| 227 |
+
* Consider potential pitfalls and how to recover (e.g., if a search yields no results, try a different query).
|
| 228 |
+
|
| 229 |
+
3. **EXECUTE AND ITERATE (Tool Delegation & Synthesis):**
|
| 230 |
+
* Delegate tasks to the `multi_tool_worker` agent, providing the exact tool and parameters.
|
| 231 |
+
* Carefully evaluate the output from each tool call.
|
| 232 |
+
* If the output is not sufficient, refine your query or try a different tool/approach. This is where iterative refinement and self-correction are crucial.
|
| 233 |
+
* Synthesize information from multiple sources if necessary to build the complete answer.
|
| 234 |
+
|
| 235 |
+
4. **FORMULATE THE FINAL ANSWER (Precision & Format):**
|
| 236 |
+
* Once you have definitively found the answer, format it *exactly* as requested in the original question.
|
| 237 |
+
* **DO NOT** add any extra text, explanations, or conversational filler. The final answer must be *only* the answer itself.
|
| 238 |
+
* Example: If the question asks for a number and the answer is "123", your output should be `FINAL ANSWER: 123`. If it asks for a string "New York", your output should be `FINAL ANSWER: New York`. If it asks for a comma-separated list "apple,banana", your output should be `FINAL ANSWER: apple,banana`.
|
| 239 |
+
"""
|
| 240 |
+
)
|
| 241 |
+
logging.info("Multi-task agent initialized successfully.")
|
| 242 |
+
return manager
|
| 243 |
+
|
| 244 |
+
# --- Main Execution Block for Local Testing ---
|
| 245 |
+
|
| 246 |
+
def main():
|
| 247 |
+
"""Main function for local testing of the agent."""
|
| 248 |
+
configure_logging()
|
| 249 |
+
try:
|
| 250 |
+
global SerpApiClientException
|
| 251 |
+
from serpapi.client import SerpApiClientException
|
| 252 |
+
|
| 253 |
+
agent = initialize_agent()
|
| 254 |
+
if agent:
|
| 255 |
+
# Example prompts for each category
|
| 256 |
+
prompts = {
|
| 257 |
+
"Web Search": "Who is the current CEO of OpenAI?",
|
| 258 |
+
"YouTube": "What is the main topic of the video https://www.youtube.com/watch?v=bZQun8Y4L2A regarding AI models?",
|
| 259 |
+
"Coding": "Write a Python script that calculates and prints the factorial of 5.",
|
| 260 |
+
"Chess": "What is the best move for the starting chess position? The FEN is 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'."
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
for category, prompt in prompts.items():
|
| 264 |
+
logging.info(f"\n--- Testing Category: {category} ---")
|
| 265 |
+
logging.info(f"Prompt: {prompt}")
|
| 266 |
+
response = agent.run(prompt)
|
| 267 |
+
logging.info(f"Agent's Final Answer: {response}")
|
| 268 |
+
logging.info("-" * (30 + len(category)))
|
| 269 |
+
|
| 270 |
+
except Exception as e:
|
| 271 |
+
logging.critical(f"An unhandled error occurred during local testing: {e}", exc_info=True)
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
# This allows you to test the agent's logic by running `python agent.py` locally.
|
| 275 |
+
main()
|