First_agent_template / tools /unit_conversion.py
maxwellmogambi's picture
Update tools/unit_conversion.py
c27b5bf verified
from smolagents.tools import Tool
class UnitConversionTool(Tool):
name = "unit_conversion"
description = "Converts between different units like distance, weight, and temperature."
inputs = {
"value": {"type": "number", "description": "The numerical value to convert."}, # Use "number" instead of "float"
"from_unit": {"type": "string", "description": "The unit of the input value (e.g., 'miles', 'kilograms', 'celsius')."},
"to_unit": {"type": "string", "description": "The target unit (e.g., 'kilometers', 'pounds', 'fahrenheit')."}
}
output_type = "string"
def forward(self, value: float, from_unit: str, to_unit: str) -> str:
"""Performs unit conversion."""
conversion_factors = {
("miles", "kilometers"): 1.60934,
("kilometers", "miles"): 0.621371,
("kilograms", "pounds"): 2.20462,
("pounds", "kilograms"): 0.453592,
}
# Temperature conversions
if from_unit == "celsius" and to_unit == "fahrenheit":
result = (value * 9/5) + 32
elif from_unit == "fahrenheit" and to_unit == "celsius":
result = (value - 32) * 5/9
elif (from_unit, to_unit) in conversion_factors:
result = value * conversion_factors[(from_unit, to_unit)]
else:
return f"Sorry, conversion from {from_unit} to {to_unit} is not supported."
return f"{value} {from_unit} is {round(result, 2)} {to_unit}."