File size: 1,491 Bytes
dba13be
b3f7a0d
dba13be
 
c27b5bf
dba13be
c27b5bf
dba13be
c27b5bf
a3cbdc6
dba13be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3f7a0d
dba13be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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}."