Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647482 unmodified lines515253545556573 unmodified lines6162636465from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,toolimport datetimeimport requestsimport pytzimport yamlfrom tools.final_answer import FinalAnswerToolfrom Gradio_UI import GradioUI# Below is an example of a tool that does nothing. Amaze us with your creativity !@tooldef my_cutom_tool(arg1:str, arg2:int)-> str: #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 yetArgs:arg1: the first argumentarg2: the second argument"""return "What magic will you build ?"@tooldef 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 objecttz = pytz.timezone(timezone)# Get current time in that timezonelocal_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()model = HfApiModel(max_tokens=2096,temperature=0.5,model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloadedcustom_role_conversions=None,)# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)2 unmodified linesagent = CodeAgent(model=model,tools=[final_answer], ## add your tools here (don't remove final answer)max_steps=6,verbosity_level=1,grammar=None,3 unmodified linesprompt_templates=prompt_templates)GradioUI(agent).launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161172 unmodified lines1201211221231241251263 unmodified lines130131132133from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, toolimport datetimeimport requestsimport pytzimport yamlimport randomimport mathimport yfinance as yffrom forex_python.converter import CurrencyRatesfrom tools.final_answer import FinalAnswerToolfrom Gradio_UI import GradioUI# Example of a custom tooldef my_custom_tool(arg1: str, arg2: int) -> str:"""A tool that does nothing yetArgs:arg1: the first argumentarg2: the second argument"""return "What magic will you build?"@tooldef get_current_time_in_timezone(timezone: str) -> str:"""Fetches the current local time in a specified timezone.Args:timezone: A string representing a valid timezone (e.g., 'America/New_York')."""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)}"@tooldef calculator(expression: str) -> str:"""Evaluates a mathematical expression and returns the result.Args:expression: A string representing a valid mathematical expression (e.g., '2 + 3 * 4')."""try:result = eval(expression, {"__builtins__": None}, {"math": math})return f"The result of {expression} is: {result}"except Exception as e:return f"Error evaluating expression '{expression}': {str(e)}"@tooldef python_repl(command: str) -> str:"""Executes a Python command in a safe restricted environment.Args:command: A string representing a Python command (e.g., '2 ** 10')."""try:result = eval(command, {"__builtins__": None}, {"math": math})return f"Execution result: {result}"except Exception as e:return f"Error executing command '{command}': {str(e)}"@tooldef unit_converter(value: float, from_unit: str, to_unit: str) -> str:"""Converts a given value from one unit to another (supports length and weight).Args:value: The numerical value to be converted.from_unit: The unit to convert from (e.g., 'm', 'km', 'lb', 'kg').to_unit: The unit to convert to."""conversions = {('m', 'km'): lambda x: x / 1000,('km', 'm'): lambda x: x * 1000,('lb', 'kg'): lambda x: x * 0.453592,('kg', 'lb'): lambda x: x / 0.453592,}try:result = conversions[(from_unit, to_unit)](value)return f"{value} {from_unit} is equal to {result} {to_unit}"except KeyError:return "Conversion not supported."@tooldef stock_price_lookup(ticker: str) -> str:"""Fetches the latest stock price for a given ticker symbol.Args:ticker: The stock ticker symbol (e.g., 'AAPL' for Apple Inc.)."""try:stock = yf.Ticker(ticker)price = stock.history(period='1d')['Close'].iloc[-1]return f"The latest stock price of {ticker} is ${price:.2f}"except Exception as e:return f"Error fetching stock price for {ticker}: {str(e)}"@tooldef currency_converter(amount: float, from_currency: str, to_currency: str) -> str:"""Converts currency based on the latest exchange rates.Args:amount: The amount of money to be converted.from_currency: The currency to convert from (e.g., 'USD').to_currency: The currency to convert to (e.g., 'EUR')."""try:c = CurrencyRates()converted_amount = c.convert(from_currency, to_currency, amount)return f"{amount} {from_currency} is equal to {converted_amount:.2f} {to_currency}"except Exception as e:return f"Error converting currency from {from_currency} to {to_currency}: {str(e)}"final_answer = FinalAnswerTool()model = HfApiModel(max_tokens=2096,temperature=0.5,model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',custom_role_conversions=None,)# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)2 unmodified linesagent = CodeAgent(model=model,tools=[final_answer, calculator, python_repl, unit_converter, stock_price_lookup, currency_converter],max_steps=6,verbosity_level=1,grammar=None,3 unmodified linesprompt_templates=prompt_templates)GradioUI(agent).launch()
app.py+86-18