🔧

Function Calling

函数调用 / 工具调用

📖 什么是 Function Calling?

Function Calling(函数调用)是LLM的一种超能力,让AI不仅能回答问题,还能主动调用外部工具和API来完成任务。

传统AI就像一个只会背书的学霸,知道很多但做不了实事。Function Calling 就像给AI装上了「手」和「工具箱」,让它能真正帮你干活!

💡 一句话理解

🧠 比喻

AI界的「万能打工仔」

你问AI「今天天气怎么样」,它不再只说「今天晴天」,而是真的帮你查天气API,然后告诉你。你让它查资料,它能真的去搜索;让它订餐厅,它能真的调用订餐系统。

⚙️ 原理讲解

Function Calling 的工作流程:

  1. 定义工具:开发者提前告诉AI有哪些可用的函数(如「查天气」「搜文章」)
  2. AI 决策:当用户请求需要工具时,AI决定调用哪个函数、传什么参数
  3. 执行调用:AI返回函数调用请求,程序实际执行函数
  4. 返回结果:函数执行结果返回给AI,AI再生成最终回答

💻 代码示例

以 OpenAI API 为例:

Python
from openai import OpenAI

client = OpenAI()

# 1. 定义可用函数
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取指定城市的天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称"}
            },
            "required": ["city"]
        }
    }
}]

# 2. 用户提问
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
    tools=tools
)

# 3. AI决定调用函数
tool_call = response.choices[0].message.tool_calls[0]
print(f"调用函数: {tool_call.function.name}")
print(f"参数: {tool_call.function.arguments}")  # {"city": "北京"}

# 4. 执行函数并返回结果
# (实际项目中这里调用真实的天气API)
weather_result = {"temp": "25°C", "condition": "晴"}

# 5. 将结果传给AI生成最终回答
final_response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "北京今天天气怎么样?"},
        {"role": "assistant", "tool_calls": [tool_call]},
        {"role": "tool", "content": str(weather_result)}
    ]
)
print(final_response.choices[0].message.content)

🎯 应用场景

🌤️ 查天气

实时获取天气信息

📅 日历管理

创建/查询日程

📧 发送邮件

自动发送邮件

🔍 网络搜索

实时联网搜索

💰 查股票

获取实时行情

🛒 电商下单

完成购物操作

🔗 相关术语