LLM 如何把 What is 25 plus 17? 提取出表达式 25 + 17 并生成 tool_call
一、核心:文档字符串 + bind_tools 共同约束 LLM 完成转换 + tool_call
1. 工具 docstring 的作用(你这段注释就是关键指令)
python
运行
""" Evaluates basic mathematical expressions. Args: expression: A mathematical expression like "25 + 17" or "100 / 4" Returns: The calculated result as a string """这段内容会完整打包进工具 JSON Schema 发给 LLM,给模型两个硬性规则:
- 这个工具只能接收标准数字运算符表达式,不能接收英文句子;
- 示例明确告知格式:
"25 + 17"、"100 / 4",暗示plus要换成+、divided换成/。
2. bind_tools 强制模型输出结构化 tool_call
执行llm.bind_tools([calculator_tool])后:
- LLM 不再允许自由文字回答计算题;
- 必须输出
tool_calls数组,包含工具名、参数字典; - 参数
expression必须是纯算式字符串。
3. LLM 内部自动执行 4 步转换(无需手写代码处理文本)
输入 Prompt:
plaintext
Calculate the following using the calculator tool: What is 25 plus 17?步骤 1:意图识别
句子包含计算语义,匹配calculator_tool。
步骤 2:词汇映射(内置语言能力)
模型自动替换计算词汇:plus → +、minus → -、times → *、divided by → /
步骤 3:清洗无关文本
删除虚词、疑问词:What is、问号、空格修饰,只保留数字与运算符。 输入文本What is 25 plus 17?→ 内部处理为25 + 17。
步骤 4:组装标准 tool_call 结构
模型输出标准化 AIMessage,结构如下:
python
运行
AIMessage( content="", tool_calls=[ { "name": "calculator_tool", "args": {"expression": "25 + 17"}, "id": "auto-generated-uuid" } ] )二、代码层面如何取出25 + 17
python
运行
# 调用绑定工具的LLM,传入自然语言问句 prompt = "Calculate the following using the calculator tool: What is 25 plus 17?" response = llm_with_calculator.invoke(prompt) # 判断是否生成了工具调用 if response.tool_calls: # 获取第一条工具调用 call_info = response.tool_calls[0] # 直接提取LLM转换好的纯表达式 math_expr = call_info["args"]["expression"] print(math_expr) # 输出:25 + 17 # 直接传入工具执行计算 res = calculator_tool.invoke(call_info["args"])三、为什么不用自己写代码替换 plus→+?
- 语义泛化能力强复杂句子也能自动转换:
sum of 12, 34 and 5→"12 + 34 + 5"100 minus 6 multiplied by 7→"100 - 6 * 7" - Schema 强制规范输出 模型一定会输出标准算式,不会把英文问句塞进 expression,避免
eval语法报错; - docstring 示例起到示范作用 你写的
like "25 + 17"是给模型的格式示范,大幅降低转换出错概率。
四、补充:如果想进一步强化转换规则(可选优化 docstring)
把词汇替换规则写进工具描述,模型转换准确率更高:
python
运行
@tool def calculator_tool(expression: str) -> str: """ Evaluates basic mathematical expressions. Convert math words to operators automatically: plus → +, minus → -, times → *, divided by → / Args: expression: Pure math expression like "25 + 17" or "100 / 4", NO natural language sentences Returns: The calculated result as a string """