my_calculator_tool.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # my_calculator_tool.py
  2. import ast
  3. import operator
  4. import math
  5. from hello_agents import ToolRegistry
  6. def my_calculate(expression: str) -> str:
  7. """简单的数学计算函数"""
  8. if not expression.strip():
  9. return "计算表达式不能为空"
  10. # 支持的基本运算
  11. operators = {
  12. ast.Add: operator.add, # +
  13. ast.Sub: operator.sub, # -
  14. ast.Mult: operator.mul, # *
  15. ast.Div: operator.truediv, # /
  16. }
  17. # 支持的基本函数
  18. functions = {
  19. 'sqrt': math.sqrt,
  20. 'pi': math.pi,
  21. }
  22. try:
  23. node = ast.parse(expression, mode='eval')
  24. result = _eval_node(node.body, operators, functions)
  25. return str(result)
  26. except:
  27. return "计算失败,请检查表达式格式"
  28. def _eval_node(node, operators, functions):
  29. """简化的表达式求值"""
  30. if isinstance(node, ast.Constant):
  31. return node.value
  32. elif isinstance(node, ast.BinOp):
  33. left = _eval_node(node.left, operators, functions)
  34. right = _eval_node(node.right, operators, functions)
  35. op = operators.get(type(node.op))
  36. return op(left, right)
  37. elif isinstance(node, ast.Call):
  38. func_name = node.func.id
  39. if func_name in functions:
  40. args = [_eval_node(arg, operators, functions) for arg in node.args]
  41. return functions[func_name](*args)
  42. elif isinstance(node, ast.Name):
  43. if node.id in functions:
  44. return functions[node.id]
  45. def create_calculator_registry():
  46. """创建包含计算器的工具注册表"""
  47. registry = ToolRegistry()
  48. # 注册计算器函数
  49. registry.register_function(
  50. name="my_calculator",
  51. description="简单的数学计算工具,支持基本运算(+,-,*,/)和sqrt函数",
  52. func=my_calculate
  53. )
  54. return registry