mobrobro's picture
Update app.py
d14c0a6 verified
raw
history blame
6.88 kB
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# Below is an example of a tool that does nothing. Amaze us with your creativity !
@tool
def animal_battle(animal1: str, animal2: str) -> str:
"""A tool that takes two animals and decides who would win in a fight and why
Args:
animal1: the first animal
animal2: the second animal
Returns:
str: A description of the battle outcome and reasoning
"""
# Dictionary of animals and their characteristics
animal_stats = {
"lion": {"strength": 9, "speed": 8, "size": 7, "weapons": "claws and teeth", "habitat": "savanna", "intelligence": 7},
"elephant": {"strength": 10, "speed": 5, "size": 10, "weapons": "tusks and trunk", "habitat": "savanna/forest", "intelligence": 9},
"gorilla": {"strength": 8, "speed": 6, "size": 6, "weapons": "strength and arms", "habitat": "forest", "intelligence": 8},
"tiger": {"strength": 9, "speed": 9, "size": 7, "weapons": "claws and teeth", "habitat": "jungle", "intelligence": 7},
"bear": {"strength": 9, "speed": 6, "size": 8, "weapons": "claws and strength", "habitat": "forest", "intelligence": 7},
"wolf": {"strength": 6, "speed": 8, "size": 5, "weapons": "teeth and pack tactics", "habitat": "forest", "intelligence": 8},
"rhinoceros": {"strength": 9, "speed": 6, "size": 9, "weapons": "horn and bulk", "habitat": "savanna", "intelligence": 6},
"hippopotamus": {"strength": 9, "speed": 5, "size": 9, "weapons": "jaws and bulk", "habitat": "water/land", "intelligence": 6},
"crocodile": {"strength": 8, "speed": 7, "size": 7, "weapons": "jaws and ambush", "habitat": "water", "intelligence": 5},
"anaconda": {"strength": 7, "speed": 6, "size": 6, "weapons": "constriction", "habitat": "water/jungle", "intelligence": 4},
"cheetah": {"strength": 6, "speed": 10, "size": 5, "weapons": "speed and agility", "habitat": "savanna", "intelligence": 7},
"kangaroo": {"strength": 7, "speed": 7, "size": 6, "weapons": "kicks and balance", "habitat": "grassland", "intelligence": 6},
"komodo dragon": {"strength": 6, "speed": 6, "size": 5, "weapons": "bacteria and venom", "habitat": "islands", "intelligence": 4},
"eagle": {"strength": 5, "speed": 9, "size": 4, "weapons": "talons and beak", "habitat": "air", "intelligence": 7},
}
animal1 = animal1.lower()
animal2 = animal2.lower()
# Check if both animals are in our database
if animal1 not in animal_stats or animal2 not in animal_stats:
return f"Sorry, I don't have enough information about {'both' if animal1 not in animal_stats and animal2 not in animal_stats else animal1 if animal1 not in animal_stats else animal2} to determine the outcome."
# Calculate total combat score with weighted attributes
def calculate_combat_score(animal):
stats = animal_stats[animal]
return (stats["strength"] * 1.5 +
stats["speed"] * 1.2 +
stats["size"] * 1.3 +
stats["intelligence"] * 0.8)
score1 = calculate_combat_score(animal1)
score2 = calculate_combat_score(animal2)
# Consider habitat advantage
def has_habitat_advantage(attacker, defender):
attacker_habitat = animal_stats[attacker]["habitat"]
defender_habitat = animal_stats[defender]["habitat"]
if "water" in attacker_habitat and "water" not in defender_habitat:
return True
if "air" in attacker_habitat and "air" not in defender_habitat:
return True
return False
# Adjust scores based on habitat advantage
if has_habitat_advantage(animal1, animal2):
score1 *= 1.2
if has_habitat_advantage(animal2, animal1):
score2 *= 1.2
# Determine winner and create detailed response
if abs(score1 - score2) < 2:
return f"It would be a close battle between the {animal1} and {animal2}! Both have their advantages: " \
f"the {animal1} with its {animal_stats[animal1]['weapons']}, and " \
f"the {animal2} with its {animal_stats[animal2]['weapons']}."
winner = animal1 if score1 > score2 else animal2
loser = animal2 if score1 > score2 else animal1
winner_stats = animal_stats[winner]
# Create detailed battle description
advantages = []
if winner_stats["strength"] > animal_stats[loser]["strength"]:
advantages.append("superior strength")
if winner_stats["speed"] > animal_stats[loser]["speed"]:
advantages.append("greater speed")
if winner_stats["size"] > animal_stats[loser]["size"]:
advantages.append("larger size")
if winner_stats["intelligence"] > animal_stats[loser]["intelligence"]:
advantages.append("better tactical ability")
advantages_text = ", ".join(advantages[:-1]) + f" and {advantages[-1]}" if len(advantages) > 1 else advantages[0]
return f"The {winner} would win against the {loser}! With its {winner_stats['weapons']}, " \
f"{advantages_text}, the {winner} has the clear advantage in this battle."
@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)}"
final_answer = FinalAnswerTool()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()