第 9 课 · Tool Calling

让 AI 自己决定"什么时候该用什么工具"——这是 Agent 的核心能力

问题:AI 本身能做什么?

AI 模型本身只能生成文字。它不能搜索网页、不能读文件、不能发邮件、不能执行代码。

那 Cline 是怎么做到的?

答案:Cline 给了 AI 一套"工具清单",AI 自己决定什么时候调用哪个工具。AI 说"我要读这个文件"→ Cline 替它读 → 把内容塞回给 AI → AI 继续思考。这就叫 Tool Calling。

这个循环长什么样

AI 思考
"我需要查天气"
→
调用工具
get_weather("北京")
→
得到结果
"25°C,晴"
→
AI 继续
"北京今天25度..."

AI 不执行工具——它只"说"要调用什么。真正执行的是你的代码。

实战代码:让 AI 会算数

AI 不擅长精确计算。但你给它一个计算器工具,它就完美了:

from openai import OpenAI
import json

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://api.deepseek.com"
)

# 定义工具:一个计算器
tools = [{
    "type": "function",
    "function": {
        "name": "calculator",
        "description": "计算数学表达式,如 '3*4+2'",
        "parameters": {
            "type": "object",
            "properties": {
                "expression": {"type": "string",
                    "description": "要计算的表达式"}
            },
            "required": ["expression"]
        }
    }
}]

# 问一个数学问题
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user",
        "content": "123 * 456 + 789 等于多少?"}],
    tools=tools
)

# AI 返回的不是文字,而是"我要用计算器"
msg = response.choices[0].message
if msg.tool_calls:
    tool_call = msg.tool_calls[0]
    print(f"AI 想调用: {tool_call.function.name}")
    args = json.loads(tool_call.function.arguments)
    print(f"参数: {args}")

    # 你执行计算
    result = eval(args["expression"])
    print(f"计算结果: {result}")

    # 把结果塞回给 AI
    response2 = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "user", "content": "123 * 456 + 789 等于多少?"},
            {"role": "assistant", "tool_calls": [tool_call]},
            {"role": "tool", "content": str(result)}
        ]
    )
    print(f"AI最终回复: {response2.choices[0].message.content}")

Tool Calling 跟 Agent 的关系

Agent 的本质就是一个带 Tool Calling 的自动循环:

AI 思考
→
调用工具
→
得到结果
→
再思考
→ ...直到任务完成

下节课你就会自己写出这个循环。

这一课你带走的 3 个概念

1 Tool Calling = AI"说"要调什么工具,你的代码执行,结果喂回给 AI

2 工具定义 = 描述 + 参数 schema,AI 看懂了就知道什么时候该用什么

3 Agent 的基础 = Tool Calling + 循环 = AI 自己干活

下一课:Agent 循环 · AI 自己干活的核心秘密