File size: 3,986 Bytes
f68897e 03dd32d 1786917 6c4000b 03dd32d f68897e 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 6c4000b 1786917 03dd32d a4c3cf0 d646ab7 03dd32d f68897e a4c3cf0 f68897e a4c3cf0 f68897e 03dd32d f68897e 03dd32d 1786917 a4c3cf0 03dd32d a4c3cf0 1786917 03dd32d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, VisitWebpageTool, PythonInterpreterTool, LiteLLMModel, tool
from tools.wiki_tool import WikiTool
from tools.excel_analysis_tool import ExcelAnalysisTool
import os
import requests
import re
import tempfile
from pathlib import Path
from typing import Optional
@tool
def check_answer(answer: str) -> str:
"""
Reviews the answer to check that it meets the requirements specified by the user and modifies it if necessary.
Args:
answer (str): The answer fo the Agent.
Returns:
str: The final answer.
"""
return answer
@tool
def reverse_sentence_tool(reverse_sentence: str) -> str:
"""
This tool receives a sentence where both the word order and the characters in each word are reversed.
It returns the sentence with words and order corrected.
Args:
reverse_sentence: A sentence with reversed words and reversed word order.
Returns:
A sentence in natural reading order.
"""
inverted_words = reverse_sentence.split(" ")[::-1]
correct_words = [word[::-1] for word in inverted_words]
return " ".join(correct_words)
@tool
def download_file_if_any(base_api_url: str, task_id: str) -> Optional[str]:
"""
Downloads a file from a remote API using a task ID.
Args:
base_api_url (str): Base URL of the API to fetch files from (e.g., "https://example.com/api").
task_id (str): Task identifier used to locate the file.
Returns:
Optional[str]: Path to the downloaded file, or None if the file is not found (404).
"""
url = f"{base_api_url}/files/{task_id}"
try:
resp = requests.get(url, timeout=30)
if resp.status_code == 404:
return None # file not found
resp.raise_for_status() # raise other errors
except requests.exceptions.HTTPError as e:
raise e # propagate for logging/debugging
# Extract filename from Content-Disposition if present
cdisp = resp.headers.get("content-disposition", "")
filename = task_id # fallback
if "filename=" in cdisp:
match = re.search(r'filename="([^"]+)"', cdisp)
if match:
filename = match.group(1)
tmp_dir = Path(tempfile.gettempdir()) / "gaia_files"
tmp_dir.mkdir(parents=True, exist_ok=True)
file_path = tmp_dir / filename
with open(file_path, "wb") as f:
f.write(resp.content)
return str(file_path)
def create_agent():
"""
Creates and configures the CodeAgent with the necessary model and tools.
Returns:
CodeAgent: The configured agent instance.
"""
# Load API key from environment variable (more secure)
token = os.getenv("HF_API_KEY")
if not token:
raise RuntimeError("Missing Hugging Face API key. Set HF_API_KEY environment variable.")
# Initialize the LLM model
# model = HfApiModel(token=token, model_id="gpt-3.5-turbo", provider="openai")
model = LiteLLMModel(
token=token,
model_id="gemini/gemini-2.0-flash",
api_key=os.getenv("GEMINI_API_KEY"),
)
# Initialize tools
wiki_tool = WikiTool()
web_search_tool = DuckDuckGoSearchTool()
excel_analysis_tool = ExcelAnalysisTool()
visitWebpageTool = VisitWebpageTool()
python_interpreter_tool = PythonInterpreterTool()
# Create and return the agent
agent = CodeAgent(
model=model,
tools=[wiki_tool, web_search_tool, excel_analysis_tool, visitWebpageTool, python_interpreter_tool, check_answer, reverse_sentence_tool, download_file_if_any],
add_base_tools=True,
max_steps=8,
verbosity_level=2,
additional_authorized_imports=['numpy','subprocess', 're', 'pandas', 'requests', 'json', 'os', 'pathlib', 'tempfile'],
)
return agent
# Example usage
if __name__ == "__main__":
agent = create_agent()
print("Agent created with tools:", [tool.name for tool in agent.tools])
|