计算器工具集成
将计算器功能集成到 Claude 对话中
🌐 查看英文原文 | 源码 Notebook
使用计算器工具与 Claude 交互
在本教程中,我们将演示如何为 Claude 提供一个简单的计算器工具,它可以根据用户输入执行算术运算。我们将定义计算器工具并展示 Claude 如何与之交互来解决数学问题。
第一步:设置环境
首先,让我们安装所需的库并设置 Claude API 客户端。
%pip install anthropicfrom anthropic import Anthropic
client = Anthropic()
MODEL_NAME = "claude-opus-4-1"第二步:定义计算器工具
我们将定义一个简单的计算器工具,可以执行基本的算术运算。该工具接受一个数学表达式作为输入并返回结果。
请注意,我们在输出的表达式上调用了 eval。这是不良实践,不应在一般情况下使用,但我们出于演示目的这样做。
import re
def calculate(expression):
# Remove any non-digit or non-operator characters from the expression
expression = re.sub(r"[^0-9+\-*/().]", "", expression)
try:
# Evaluate the expression using the built-in eval() function
# Note: eval is used here for demonstration purposes only.
# In production, use a safer alternative like ast.literal_eval or a math parser.
result = eval(expression) # noqa: S307
return str(result)
except (SyntaxError, ZeroDivisionError, NameError, TypeError, OverflowError):
return "Error: Invalid expression"
tools = [
{
"name": "calculator",
"description": "A simple calculator that performs basic arithmetic operations.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate (e.g., '2 + 3 * 4').",
}
},
"required": ["expression"],
},
}
]在这个示例中,我们定义了一个 calculate 函数,它接受一个数学表达式作为输入,使用正则表达式移除任何非数字或非运算符字符,然后使用内置的 eval() 函数来计算表达式。如果计算成功,结果以字符串形式返回。如果计算过程中发生错误,则返回一条错误消息。
然后我们定义了计算器工具,其输入模式期望一个类型为字符串的 expression 属性。
第三步:与 Claude 交互
现在,让我们看看 Claude 如何与计算器工具交互来解决数学问题。
def process_tool_call(tool_name, tool_input):
if tool_name == "calculator":
return calculate(tool_input["expression"])
def chat_with_claude(user_message):
print(f"\n{'=' * 50}\nUser Message: {user_message}\n{'=' * 50}")
message = client.messages.create(
model=MODEL_NAME,
max_tokens=4096,
messages=[{"role": "user", "content": user_message}],
tools=tools,
)
print("\nInitial Response:")
print(f"Stop Reason: {message.stop_reason}")
print(f"Content: {message.content}")
if message.stop_reason == "tool_use":
tool_use = next(block for block in message.content if block.type == "tool_use")
tool_name = tool_use.name
tool_input = tool_use.input
print(f"\nTool Used: {tool_name}")
print(f"Tool Input: {tool_input}")
tool_result = process_tool_call(tool_name, tool_input)
print(f"Tool Result: {tool_result}")
response = client.messages.create(
model=MODEL_NAME,
max_tokens=4096,
messages=[
{"role": "user", "content": user_message},
{"role": "assistant", "content": message.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": tool_result,
}
],
},
],
tools=tools,
)
else:
response = message
final_response = next(
(block.text for block in response.content if hasattr(block, "text")),
None,
)
print(response.content)
print(f"\nFinal Response: {final_response}")
return final_response第四步:试一试!
现在 Claude 已经可以使用计算器了,让我们给它几个数学问题试试。
chat_with_claude("What is the result of 1,984,135 * 9,343,116?")
chat_with_claude("Calculate (12851 - 593) * 301 + 76")
chat_with_claude("What is 15910385 divided by 193053?")
==================================================
User Message: What is the result of 1,984,135 * 9,343,116?
==================================================
Initial Response:
Stop Reason: tool_use
Content: [ContentBlock(text='<thinking>\nThe calculator function is the relevant tool to answer this request, since it involves evaluating a mathematical expression.\n\nThe required parameter for the calculator function is:\nexpression: The mathematical expression to evaluate.\n\nThe human has directly provided the full expression to evaluate in their request: "1,984,135 * 9,343,116". This contains all the information needed for the required expression parameter.\n\nSo I have the necessary information to invoke the calculator tool.\n</thinking>', type='text'), ContentBlockToolUse(id='toolu_01V2mzqp5qkB5QucRFjJUJLD', input={'expression': '1984135 * 9343116'}, name='calculator', type='tool_use')]
Tool Used: calculator
Tool Input: {'expression': '1984135 * 9343116'}
Tool Result: 18538003464660
[ContentBlock(text='Therefore, the result of 1,984,135 * 9,343,116 is 18,538,003,464,660.', type='text')]
Final Response: Therefore, the result of 1,984,135 * 9,343,116 is 18,538,003,464,660.
==================================================
User Message: Calculate (12851 - 593) * 301 + 76
==================================================
Initial Response:
Stop Reason: tool_use
Content: [ContentBlock(text='<thinking>\nThe user has provided a mathematical expression to be evaluated: (12851 - 593) * 301 + 76\nThis can be handled by the calculator tool. Let\'s check if the required "expression" parameter is provided:\nexpression: "(12851 - 593) * 301 + 76" - This is directly provided by the user.\nSince the required parameter is present, we can proceed with calling the calculator tool.\n</thinking>', type='text'), ContentBlockToolUse(id='toolu_01Mrrfy9adBzzxvhfZwnyJAe', input={'expression': '(12851 - 593) * 301 + 76'}, name='calculator', type='tool_use')]
Tool Used: calculator
Tool Input: {'expression': '(12851 - 593) * 301 + 76'}
Tool Result: 3689734
[ContentBlock(text='So the final result of evaluating the expression (12851 - 593) * 301 + 76 is 3689734.', type='text')]
Final Response: So the final result of evaluating the expression (12851 - 593) * 301 + 76 is 3689734.
==================================================
User Message: What is 15910385 divided by 193053?
==================================================
Initial Response:
Stop Reason: tool_use
Content: [ContentBlock(text='<thinking>\nThe calculator function is the appropriate tool to answer this request, since it can perform basic arithmetic operations like division.\n\nThe calculator function requires a single parameter:\n- expression: The mathematical expression to evaluate\n\nIn this case, the user has provided the full expression to evaluate (15910385 divided by 193053). Since all the required information has been provided, we can proceed with calling the calculator function.\n</thinking>', type='text'), ContentBlockToolUse(id='toolu_01BfnN4LKp7oPRgmRzWeYdBG', input={'expression': '15910385 / 193053'}, name='calculator', type='tool_use')]
Tool Used: calculator
Tool Input: {'expression': '15910385 / 193053'}
Tool Result: 82.41459599177428
[ContentBlock(text='So 15910385 divided by 193053 equals 82.41459599177428.', type='text')]
Final Response: So 15910385 divided by 193053 equals 82.41459599177428.
'So 15910385 divided by 193053 equals 82.41459599177428.'
Tip
中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。