from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, load_tool, tool import datetime import pytz import yaml from tools.final_answer import FinalAnswerTool import gradio as gr # ----- Tools ----- @tool def my_custom_tool(arg1: str, arg2: int) -> str: """A tool that creates a personalized greeting repeated multiple times.""" greeting = f"Hello, {arg1}!" return " ".join([greeting] * arg2) @tool def get_current_time_in_timezone(timezone: str) -> str: """Fetches the current local time in a specified timezone.""" try: tz = pytz.timezone(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)}" final_answer = FinalAnswerTool() # Load prompt templates with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) # Load additional tools from Hugging Face Hub image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) # ----- Function to initialize agent dynamically ----- def initialize_agent(api_key: str): model = OpenAIServerModel( max_tokens=2096, temperature=0.5, model_id="gpt-4o", custom_role_conversions=None, openai_api_key=api_key # Pass the user-provided API key ) agent = CodeAgent( model=model, tools=[my_custom_tool, get_current_time_in_timezone, final_answer], max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) return agent # ----- Gradio UI ----- def launch_agent(api_key: str): agent = initialize_agent(api_key) return GradioUI(agent).launch(share=True) # Interface for the user to enter their OpenAI API key iface = gr.Interface( fn=launch_agent, inputs=gr.Textbox(label="Enter your OpenAI API Key", type="password"), outputs="text", title="Custom SmolAgent App", description="Enter your OpenAI API key to use the agent." ) iface.launch()