|
from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool, LiteLLMModel |
|
import datetime |
|
import requests |
|
import pytz |
|
import yaml |
|
import os |
|
import tempfile |
|
from tools.final_answer import FinalAnswerTool |
|
from tools.visit_webpage import VisitWebpageTool |
|
from smolagents import GradioUI |
|
import gradio as gr |
|
import json |
|
import os |
|
from typing import Dict, List, Optional, Union, Any |
|
import re |
|
|
|
''' |
|
# Below is an example of a tool that does nothing. Amaze us with your creativity ! |
|
@tool |
|
def my_custom_tool(x:str, y:int)-> int: #it's import to specify the return type |
|
#Keep this format for the description / args / args description but feel free to modify the tool |
|
"""A tool that does nothing yet |
|
Args: |
|
arg1: the first argument |
|
arg2: the second argument |
|
""" |
|
return "What magic will you build ?" |
|
@tool |
|
def get_current_time_in_timezone(timezone: str) -> str: |
|
"""A tool that fetches the current local time in a specified timezone. |
|
Args: |
|
timezone: A string representing a valid timezone (e.g., 'America/New_York'). |
|
""" |
|
try: |
|
# Create timezone object |
|
tz = pytz.timezone(timezone) |
|
# Get current time in that timezone |
|
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") |
|
return f"The current local time in {timezone} is: {local_time}" |
|
except Exception as e: |
|
return f"Error fetching time for timezone '{timezone}': {str(e)}" |
|
''' |
|
@tool |
|
def create_document(text: str, format: str = "docx") -> str: |
|
"""Creates a document with the provided text and allows download. |
|
|
|
Args: |
|
text: The text content to write to the document. |
|
format: The output format, either 'docx', 'pdf', or 'txt'. |
|
""" |
|
try: |
|
|
|
temp_dir = tempfile.mkdtemp() |
|
|
|
if format.lower() == "txt": |
|
txt_path = os.path.join(temp_dir, "generated_document.txt") |
|
with open(txt_path, "w", encoding="utf-8") as f: |
|
f.write(text) |
|
return txt_path |
|
|
|
elif format.lower() in ["docx", "pdf"]: |
|
try: |
|
import docx |
|
from docx.shared import Pt |
|
except ImportError: |
|
return (f"ERROR: To create DOCX or PDF files, the 'python-docx' package is required. " |
|
f"Please install it (e.g., 'pip install python-docx'). " |
|
f"You can try creating a 'txt' file instead by specifying format='txt'.") |
|
|
|
|
|
doc = docx.Document() |
|
doc.add_heading('Generated Document', 0) |
|
style = doc.styles['Normal'] |
|
font = style.font |
|
font.name = 'Calibri' |
|
font.size = Pt(11) |
|
|
|
for paragraph in text.split('\n'): |
|
if paragraph.strip(): |
|
doc.add_paragraph(paragraph) |
|
|
|
docx_path = os.path.join(temp_dir, "generated_document.docx") |
|
doc.save(docx_path) |
|
|
|
if format.lower() == "pdf": |
|
try: |
|
from docx2pdf import convert |
|
pdf_path = os.path.join(temp_dir, "generated_document.pdf") |
|
convert(docx_path, pdf_path) |
|
|
|
return pdf_path |
|
except ImportError: |
|
return (f"ERROR: PDF conversion requires the 'docx2pdf' package. " |
|
f"Please install it (e.g., 'pip install docx2pdf'). " |
|
f"Document saved as DOCX instead at: {docx_path}") |
|
except Exception as e_pdf: |
|
return f"Error converting DOCX to PDF: {str(e_pdf)}. Document saved as DOCX at: {docx_path}" |
|
|
|
return docx_path |
|
|
|
else: |
|
return f"Error: Unsupported format '{format}'. Supported formats are 'docx', 'pdf', 'txt'." |
|
|
|
except Exception as e: |
|
|
|
return f"Error creating document: {str(e)}" |
|
|
|
|
|
@tool |
|
def get_file_download_link(file_path: str) -> str: |
|
"""Creates a download link for a file. |
|
|
|
Args: |
|
file_path: Path to the file that should be made available for download |
|
""" |
|
if not os.path.exists(file_path): |
|
return f"Error: File not found at {file_path}" |
|
|
|
|
|
_, file_extension = os.path.splitext(file_path) |
|
mime_types = { |
|
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', |
|
'.pdf': 'application/pdf', |
|
'.txt': 'text/plain', |
|
} |
|
mime_type = mime_types.get(file_extension.lower(), 'application/octet-stream') |
|
|
|
|
|
return f"File ready for download: {os.path.basename(file_path)} ({mime_type})" |
|
|
|
|
|
final_answer = FinalAnswerTool() |
|
|
|
visit_webpage=VisitWebpageTool() |
|
|
|
|
|
|
|
|
|
model = LiteLLMModel( |
|
model_id="gemini/gemini-2.0-flash", |
|
api_key=os.getenv("GEMINI_KEY"), |
|
max_tokens=8192, |
|
temperature=0.7 |
|
) |
|
|
|
|
|
|
|
|
|
|
|
with open("prompts.yaml", 'r') as stream: |
|
prompt_templates = yaml.safe_load(stream) |
|
|
|
|
|
|
|
agent = CodeAgent( |
|
model=model, |
|
tools=[final_answer,visit_webpage,create_document,get_file_download_link], |
|
max_steps=6, |
|
verbosity_level=1, |
|
prompt_templates=prompt_templates |
|
) |
|
|
|
|
|
class CustomGradioUI(GradioUI): |
|
def build_interface(self): |
|
with gr.Blocks() as interface: |
|
with gr.Row(): |
|
with gr.Column(scale=1): |
|
gr.Markdown("# AI Assistant") |
|
|
|
chatbot = gr.Chatbot(height=600) |
|
msg = gr.Textbox( |
|
placeholder="Ask me anything...", |
|
container=False, |
|
scale=7, |
|
) |
|
|
|
|
|
download_btn = gr.Button("Download File", visible=False) |
|
file_output = gr.File(label="Generated Document", visible=False) |
|
|
|
|
|
self._latest_file_path = None |
|
|
|
def respond(message, chat_history): |
|
agent_response = self.agent.run(message) |
|
chat_history.append((message, agent_response)) |
|
|
|
show_download = False |
|
|
|
|
|
|
|
|
|
|
|
|
|
paths = re.findall(r'/tmp/[^/]+/generated_document\.(docx|pdf|txt)', agent_response) |
|
if paths: |
|
self._latest_file_path = paths[0] |
|
show_download = True |
|
else: |
|
self._latest_file_path = None |
|
|
|
return chat_history, gr.Button.update(visible=show_download), gr.File.update(visible=False) |
|
|
|
def prepare_download(): |
|
if self._latest_file_path and os.path.exists(self._latest_file_path): |
|
return gr.File.update(value=self._latest_file_path, visible=True) |
|
|
|
gr.Warning("File not available for download. It might have been temporary or an error occurred.") |
|
return gr.File.update(visible=False) |
|
|
|
|
|
msg.submit(respond, [msg, chatbot], [chatbot, download_btn, file_output]) |
|
download_btn.click(prepare_download, [], [file_output]) |
|
|
|
gr.Markdown("Powered by smolagents and Qwen") |
|
|
|
return interface |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
CustomGradioUI(agent).launch() |