Final_Assignment / tools.py
benjipeng's picture
Create tools.py
61e2bd8 verified
raw
history blame
2.75 kB
import os
import requests
from duckduckgo_search import DDGS
# This is the base URL for the competition API, used to fetch files.
GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
def web_search(query: str) -> str:
"""
Performs a web search using the DuckDuckGo search engine and returns the top results.
Use this to find current information, facts, or to answer general knowledge questions.
Args:
query (str): The search query.
Returns:
str: A formatted string of the search results.
"""
print(f"Tool: Performing web search for '{query}'...")
try:
with DDGS() as ddgs:
results = [r for r in ddgs.text(query, max_results=5)]
return "\n".join([f"[{i+1}] {r['title']}: {r['body']}" for i, r in enumerate(results)]) if results else "No results found."
except Exception as e:
return f"Error during web search: {e}"
def read_file_from_api(task_id: str) -> str:
"""
Downloads and reads the content of a file associated with a specific task_id from the GAIA competition API.
Only use this tool when the user's question explicitly mentions a file or attachment.
Args:
task_id (str): The task ID associated with the file to download.
Returns:
str: The content of the file as a string, or an error message.
"""
print(f"Tool: Reading file for task_id '{task_id}'...")
file_url = f"{GAIA_API_URL}/files/{task_id}"
try:
response = requests.get(file_url, timeout=10)
response.raise_for_status()
# We assume the content is text-based (txt, csv, json, etc.)
return response.text
except requests.exceptions.RequestException as e:
return f"Error reading file from API: {e}"
def python_interpreter(code: str) -> str:
"""
Executes a given string of Python code and returns its standard output.
This tool is highly useful for calculations, data manipulation, or any complex logic.
The code runs in a restricted environment. Only print the final result.
Args:
code (str): A string containing valid Python code.
Returns:
str: The captured stdout from the executed code, or the error.
"""
print(f"Tool: Executing Python code:\n---\n{code}\n---")
# WARNING: Executing arbitrary code is a security risk.
# In a real-world application, this should be done in a sandboxed environment.
import io
import sys
from contextlib import redirect_stdout
try:
f = io.StringIO()
with redirect_stdout(f):
exec(code, {})
return f.getvalue()
except Exception as e:
return f"Error executing Python code: {type(e).__name__}: {e}"