maxwellmogambi commited on
Commit
a3cbdc6
·
verified ·
1 Parent(s): de2c0ee

Update tools/unit_conversion.py

Browse files
Files changed (1) hide show
  1. tools/unit_conversion.py +30 -23
tools/unit_conversion.py CHANGED
@@ -1,26 +1,33 @@
1
- class UnitConverter:
2
- def __init__(self):
3
- self.conversion_factors = {
4
- ("miles", "kilometers"): 1.60934,
5
- ("kilometers", "miles"): 0.621371,
6
- ("pounds", "kilograms"): 0.453592,
7
- ("kilograms", "pounds"): 2.20462,
8
- ("celsius", "fahrenheit"): lambda c: (c * 9/5) + 32,
9
- ("fahrenheit", "celsius"): lambda f: (f - 32) * 5/9
10
- }
11
 
12
- def convert(self, value, from_unit, to_unit):
13
- key = (from_unit.lower(), to_unit.lower())
 
 
 
 
 
 
 
 
 
 
14
 
15
- if key in self.conversion_factors:
16
- conversion = self.conversion_factors[key]
17
- result = conversion(value) if callable(conversion) else value * conversion
18
- return f"{value} {from_unit} is {result:.2f} {to_unit}."
19
- else:
20
- return "Sorry, conversion not supported."
21
 
22
- # Example usage
23
- if __name__ == "__main__":
24
- converter = UnitConverter()
25
- print(converter.convert(5, "miles", "kilometers")) # 5 miles is 8.05 kilometers.
26
- print(converter.convert(100, "celsius", "fahrenheit")) # 100°C is 212°F.
 
 
 
 
 
 
 
1
+ from smolagents import tool
 
 
 
 
 
 
 
 
 
2
 
3
+ @tool
4
+ def unit_conversion(value: float, from_unit: str, to_unit: str) -> str:
5
+ """A tool for converting units like distance, weight, and temperature.
6
+
7
+ Args:
8
+ value: The numerical value to convert.
9
+ from_unit: The unit of the input value (e.g., 'miles', 'kilograms', 'celsius').
10
+ to_unit: The desired unit (e.g., 'kilometers', 'pounds', 'fahrenheit').
11
+
12
+ Returns:
13
+ A string describing the converted value.
14
+ """
15
 
16
+ conversion_factors = {
17
+ ("miles", "kilometers"): 1.60934,
18
+ ("kilometers", "miles"): 0.621371,
19
+ ("kilograms", "pounds"): 2.20462,
20
+ ("pounds", "kilograms"): 0.453592,
21
+ }
22
 
23
+ # Temperature conversions
24
+ if from_unit == "celsius" and to_unit == "fahrenheit":
25
+ result = (value * 9/5) + 32
26
+ elif from_unit == "fahrenheit" and to_unit == "celsius":
27
+ result = (value - 32) * 5/9
28
+ elif (from_unit, to_unit) in conversion_factors:
29
+ result = value * conversion_factors[(from_unit, to_unit)]
30
+ else:
31
+ return f"Sorry, conversion from {from_unit} to {to_unit} is not supported."
32
+
33
+ return f"{value} {from_unit} is {round(result, 2)} {to_unit}."