Final_Assignment / agent.py
Svetlana
feat: implement an agent
7cb927e
raw
history blame
2.06 kB
import gradio as gr
import random
import os
from smolagents import DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool, LiteLLMModel
from tools import DownloadTaskAttachmentTool, VisitWebpageTool
class MyAgent:
def __init__(self):
self.agent = CodeAgent(
model=LiteLLMModel(model_id="openrouter/meta-llama/llama-4-maverick:free", api_key=os.getenv("OPENROUTER_KEY")),
tools=[DuckDuckGoSearchTool(), WikipediaSearchTool(), VisitWebpageTool(), DownloadTaskAttachmentTool()],
add_base_tools=True,
additional_authorized_imports=['pandas', 'numpy', 'csv', 'subprocess', 'exec']
)
print("MyAgent initialized.")
def __call__(self, question: str) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
agent_answer = self.agent.run(question)
print(f"Agent answer: {agent_answer}")
return agent_answer
def download_file(self, task_id: str) -> str:
"""
Downloads a file associated with the given task ID.
Returns the file path where the file is saved locally.
"""
file_url = f"{DEFAULT_API_URL}/files/{task_id}"
local_file_path = f"downloads/{task_id}.file"
print(f"Downloading file for task ID {task_id} from {file_url}...")
try:
response = requests.get(file_url, stream=True, timeout=15)
response.raise_for_status()
os.makedirs("downloads", exist_ok=True)
with open(local_file_path, "wb") as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
print(f"File downloaded successfully: {local_file_path}")
return local_file_path
except requests.exceptions.RequestException as e:
print(f"Error downloading file for task {task_id}: {e}")
raise
def launch_ui(self):
GradioUI(self.agent).launch()
# if __name__ == "__main__":
# my_agent = MyAgent()
# my_agent.launch_ui()