1. 核心定义
1.1 Function Calling
Function Calling(函数调用)是一种让大语言模型与外部系统进行结构化交互的机制。
开发者先向模型声明:
- 有哪些函数可以调用;
- 每个函数的用途;
- 每个函数需要哪些参数;
- 参数的数据类型和约束。
模型根据用户的自然语言问题:
- 判断是否需要调用函数;
- 选择合适的函数;
- 从用户问题中提取参数;
- 生成结构化的函数调用请求;
- 由应用程序真正执行函数;
- 将执行结果重新返回给模型;
- 模型根据结果继续调用工具或生成最终回答。
可以概括为:
自然语言 ↓ LLM ↓ 选择 Function ↓ 生成结构化参数 ↓ 应用程序执行 Function ↓ 获取真实数据 ↓ 结果返回 LLM ↓ 生成最终回答专业定义:
Function Calling 是一种结构化的 LLM-外部系统交互机制:开发者向模型声明可调用能力及其参数 Schema,模型依据用户意图选择适当函数并生成结构化调用参数,应用侧负责执行实际函数,并将执行结果反馈给模型,由模型继续推理、调用其他工具或生成最终响应。
2. Tool Calling 与 Function Calling
2.1 Tool Calling
Tool Calling(工具调用)是一个更大的概念。
Tool Calling ├── Function Calling ├── Web Search ├── File Search ├── Code Execution ├── Computer Use ├── MCP └── 其他外部工具因此:
Function Calling 是 Tool Calling 的一种。
Function Calling 一般负责调用开发者自己定义的:
Python Function REST API Database Search Service 企业内部接口 业务系统3. 为什么需要 Function Calling
LLM 本质上是:
Token ↓ LLM ↓ Token它本身不能天然获得:
- 实时天气;
- 数据库最新数据;
- 用户余额;
- 企业内部数据;
- 当前订单状态;
- 电站实时发电量;
- Kafka 状态;
- 外部 API 信息。
例如用户问:
查询合肥现在的天气普通 LLM:
用户 ↓ LLM ↓ 根据模型已有知识回答可能无法得到实时信息。
加入 Function Calling:
用户 ↓ LLM ↓ get_weather(city="合肥") ↓ 天气 API ↓ 实时天气 ↓ LLM ↓ 最终答案因此 Function Calling 让 LLM 从:
只能生成文本升级为:
可以利用外部能力完成任务这是从Chatbot 向 Agent 演进的关键基础技术之一。
4. Function Calling 最重要的理解
LLM 通常不直接执行你的 Python 函数
例如:
def get_weather(city): ...模型通常不会自己进入 Python 环境执行:
get_weather("合肥")正确流程是:
LLM ↓ 生成调用请求 { "name": "get_weather", "arguments": { "city": "合肥" } } ↓ 你的 Python 程序 ↓ 解析 arguments ↓ 执行 get_weather("合肥") ↓ 返回执行结果 ↓ LLM因此职责划分是:
LLM 负责
理解用户问题 + 判断是否需要 Tool + 选择 Tool + 生成参数 + 理解 Tool Result应用程序负责
参数校验 + 真正调用 Function / API + 权限控制 + 错误处理 + 把 Tool Result 返回模型5. Function Calling 本质上解决两个问题
5.1 自然语言 → 结构化操作
用户:
查询101176电站最近7天发电量模型可能转换为:
{ "name": "get_station_power", "arguments": { "ps_id": "101176", "start_date": "2026-08-06", "end_date": "2026-08-12" } }本质:
Natural Language ↓ Structured Arguments5.2 LLM → 外部世界
加入工具后:
LLM ├── 查询数据库 ├── 调用 REST API ├── 搜索网页 ├── 查询文件 ├── 执行代码 ├── 发送邮件 ├── 操作业务系统 └── 调企业内部服务因此 Function Calling 可以看作:
LLM 与现实业务系统之间的桥梁。
6. Tool Schema
为了让模型知道有哪些工具,开发者需要定义Tool Schema。
例如:
{ "type": "function", "name": "get_weather", "description": "查询指定城市当前天气", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "需要查询天气的城市" } }, "required": [ "city" ], "additionalProperties": false }, "strict": true }主要组成:
Tool Schema ├── name ├── description ├── parameters │ ├── type │ ├── properties │ ├── required │ └── additionalProperties └── strict7.name
表示工具名称:
"name": "get_weather"推荐:
get_weather get_station_power get_station_devices get_station_revenue search_customer不推荐:
func1 tool2 query do_something原因:
Tool Name 本身也是模型理解工具用途的重要信息。
8.description
例如:
"description": "查询指定城市当前天气"模型选择工具主要依赖:
用户问题 + Tool Name + Tool Description + Parameter Description + System Prompt + 上下文例如两个工具:
get_station_info get_station_power差的描述:
get_station_info:查询电站 get_station_power:查询电站很容易选错。
更合理:
get_station_info: 查询电站名称、地址、装机容量等基础信息。 get_station_power: 查询指定电站在指定时间范围内的发电量。 不用于设备、收益或基础信息查询。这是所谓:
Tool Description Engineering
不仅要告诉模型:
什么时候使用最好还告诉它:
什么时候不要使用9. Parameters
Parameters 描述函数需要哪些输入。
例如:
def query_station_power( ps_id: str, start_date: str, end_date: str ): ...对应 Schema:
{ "type": "object", "properties": { "ps_id": { "type": "string", "description": "电站ID" }, "start_date": { "type": "string", "description": "开始日期,格式为 YYYY-MM-DD" }, "end_date": { "type": "string", "description": "结束日期,格式为 YYYY-MM-DD" } }, "required": [ "ps_id", "start_date", "end_date" ], "additionalProperties": false }用户:
查询电站101176上周的发电量模型负责转换成:
{ "ps_id": "101176", "start_date": "2026-08-03", "end_date": "2026-08-09" }10. 一个完整 Python 示例
10.1 第一步:定义业务函数
def get_weather(city: str): weather_database = { "合肥": { "temperature": 32, "weather": "晴" }, "北京": { "temperature": 30, "weather": "多云" } } return weather_database.get( city, {"error": "未找到该城市"} )它只是一个普通 Python 函数。
10.2 第二步:定义 Tool Schema
tools = [ { "type": "function", "name": "get_weather", "description": "查询指定城市当前天气", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称,例如合肥、北京" } }, "required": ["city"], "additionalProperties": False }, "strict": True } ]10.3 第三步:请求模型
from openai import OpenAI import json client = OpenAI() input_messages = [ { "role": "user", "content": "合肥现在天气怎么样?" } ] response = client.responses.create( model="gpt-5.6", input=input_messages, tools=tools )模型此时可能不会直接回答,而是产生:
{ "type": "function_call", "name": "get_weather", "arguments": "{\"city\":\"合肥\"}", "call_id": "call_xxx" }11. 执行模型生成的 Function Call
程序检查模型返回:
for item in response.output: if item.type == "function_call": print(item.name) print(item.arguments)得到:
get_weather {"city":"合肥"}解析参数:
arguments = json.loads(item.arguments)结果:
{ "city": "合肥" }执行真正函数:
result = get_weather(**arguments)等价于:
result = get_weather(city="合肥")得到:
{ "temperature": 32, "weather": "晴" }12. 将 Tool Result 返回模型
需要告诉模型:
你刚刚要求调用的工具已经执行完了, 下面是执行结果。例如:
input_messages += response.output input_messages.append({ "type": "function_call_output", "call_id": item.call_id, "output": json.dumps( result, ensure_ascii=False ) })再请求一次模型:
final_response = client.responses.create( model="gpt-5.6", input=input_messages, tools=tools ) print(final_response.output_text)最终可能输出:
合肥当前天气晴,气温约32℃。13. Function Calling 的完整闭环
① 用户 │ │ “合肥天气怎么样?” ▼ ② LLM │ │ 判断需要实时天气 │ │ get_weather(city="合肥") ▼ ③ Python程序 │ │ 解析参数 ▼ ④ get_weather() │ │ 调天气API ▼ ⑤ Tool Result │ │ {"temperature":32,"weather":"晴"} ▼ ⑥ Python程序 │ │ 返回 function_call_output ▼ ⑦ LLM │ │ 理解查询结果 ▼ ⑧ 用户 “合肥当前晴,32℃。”所以 Function Calling 的典型模式是:
LLM ↓ Tool ↓ LLM而不是:
User ↓ LLM ↓ Answer14. Function Calling 与 Agent Loop
单次 Function Calling:
LLM ↓ Tool ↓ LLM ↓ Answer真正 Agent:
用户 ↓ LLM ↓ Tool A ↓ LLM ↓ Tool B ↓ LLM ↓ Tool C ↓ LLM ↓ Final Answer可以抽象成:
while not task_finished: response = call_llm() if response.has_tool_call: result = execute_tool() add_tool_result(result) else: return response.final_answer因此:
Agent 本质上经常就是围绕 Tool Calling 构建的循环执行系统。
15. Function Dispatcher
实际项目不可能只有一个工具。
例如:
FUNCTION_MAP = { "get_weather": get_weather, "get_station_power": get_station_power, "get_station_devices": get_station_devices, "get_station_revenue": get_station_revenue, }统一执行:
def call_function(name, arguments): if name not in FUNCTION_MAP: raise ValueError( f"Unknown function: {name}" ) function = FUNCTION_MAP[name] return function(**arguments)结构:
LLM ↓ Function Name ↓ Function Dispatcher ↓ FUNCTION_MAP ↓ 真正业务函数这就是:
Function Dispatcher / Tool Dispatcher
16. 多 Tool 场景
真实 Agent 一般会挂很多工具:
Agent ├── get_station_info ├── get_station_power ├── get_station_devices ├── get_station_revenue ├── search_document ├── query_database └── web_search用户:
查询101176电站最近7天发电量LLM:
get_station_power用户:
查询101176有哪些逆变器LLM:
get_station_devices用户:
查询101176最近15天收益LLM:
get_station_revenue这里 LLM 承担:
Tool Routing(工具路由)
17. Tool Routing
Tool Routing 可以表示为:
User Query ↓ LLM ↓ Tool Selection ┌─────────┼─────────┐ ↓ ↓ ↓ Tool A Tool B Tool C工具选择是否准确,很大程度取决于:
Tool Name + Description + Parameter Schema + Prompt + Context18. Tool Choice
开发者还可以控制模型调用工具的策略。
auto
模型自己判断:
要不要调用工具 + 调用哪个工具例如:
用户:你好 LLM: 直接回答但:
用户:查询101176昨天发电量 LLM: 调用 get_station_powerrequired
要求这一轮必须使用工具。
适用于:
实时数据查询 企业内部数据查询 数据库查询 金融数据 业务系统数据避免模型没有查询真实数据就直接生成答案。
19. Parallel Tool Calling
模型可以一次生成多个 Tool Call。
例如:
比较北京、上海和合肥今天的天气串行:
北京 ↓ 上海 ↓ 合肥并行:
LLM ┌──────┼──────┐ ↓ ↓ ↓ 北京 上海 合肥 ↓ ↓ ↓ └──────┼──────┘ ↓ Result这叫:
Parallel Tool Calling
适合互相独立的多个工具任务。
20. Function Calling 与普通 API 调用
传统程序:
if intent == "weather": get_weather() elif intent == "power": get_power() elif intent == "device": get_device()开发者需要自己实现:
关键词 规则 正则 分类器 Intent DetectionFunction Calling:
用户自然语言 ↓ LLM ↓ Intent Understanding ↓ Tool Selection ↓ Argument Extraction ↓ API因此:
Function Calling不是取代 API。
而是:
利用 LLM 判断什么时候调用哪个 API,以及需要传递什么参数。
21. Function Calling 与 RAG
RAG
主要解决:
获取外部知识。
例如:
用户 ↓ Retrieval ↓ Vector Database ↓ Documents ↓ LLM ↓ Answer适合:
公司的年假制度是什么?Function Calling
主要解决:
调用外部能力。
例如:
查询余额 查询发电量 发送邮件 创建工单 操作数据库 调用企业 API可以粗略理解:
RAG ≈ KnowledgeFunction Calling ≈ Action / Capability但 RAG 本身也可以被封装成 Tool:
search_knowledge_base()让 Agent 自己决定什么时候检索。
于是形成:
Agent ↓ Function Calling ↓ search_knowledge_base() ↓ RAG这就是 Agentic RAG 的基础之一。
22. Function Calling 与 MCP
Function Calling:
LLM ↓ Tool Schema ↓ 你的程序 ↓ Function问题是每一个应用可能都要自己实现 Tool 接入逻辑。
MCP:
MCP Server / | \ ↓ ↓ ↓ Tool A Tool B Tool C ↑ │ Agent可以简单记:
Function Calling = 模型“怎么调用工具”而:
MCP = 工具“如何标准化提供给 Agent”所以二者并不冲突。
通常可以组合:
Agent ↓ MCP Client ↓ MCP Server ↓ Tool ↓ 底层 API / Database23. Function Calling 常见工程问题
23.1 Tool Selection Error
用户:
查询电站收益模型:
get_station_power选错了 Tool。
解决方向:
- 优化 Tool Name;
- 优化 Tool Description;
- 明确工具边界;
- 增加 Routing Prompt;
- 建立 Tool Selection Eval。
24. Argument Extraction Error
用户:
查询101176最近7天发电量模型生成:
{ "ps_id": "101716" }参数提取错误。
需要:
Schema Validation Parameter Validation Business Validation25. 参数缺失
API 需要:
ps_id start_date end_date模型只给:
{ "ps_id": "101176" }生产系统不能直接调用 API。
需要:
LLM Output ↓ Schema Validation ↓ Business Validation ↓ Tool Execution26. Tool Error
工具可能返回:
HTTP 500 Timeout Permission Denied API Unavailable Database Error Invalid Parameter不应该直接让 Agent 崩溃。
应该:
Tool ↓ Error ↓ 结构化 Error Result ↓ LLM ↓ 判断: ├── Retry ├── Change Tool ├── Change Arguments └── 告诉用户27. 无限 Tool Loop
Agent 可能出现:
LLM ↓ Tool ↓ LLM ↓ Tool ↓ LLM ↓ Tool ↓ ...因此生产系统应该设置:
max_steps max_tool_calls retry_limit timeout token_limit cost_limit28. 企业级 Function Calling 架构
一个更加完整的生产系统通常是:
User ↓ Agent / LLM ↓ Tool Selection ↓ Schema Validation ↓ Business Validation ↓ Permission ↓ Tool Dispatcher / | \ ↓ ↓ ↓ REST API SQL Search ↓ ↓ ↓ \ | / ↓ Result Normalize ↓ Error Handling ↓ Retry ↓ Tracing ↓ LLM ↓ Answer这已经属于:
Agent Tool Infrastructure
而不是简单 Function Calling Demo。
29. Function Calling 的核心模块
可以把完整系统拆成:
Function Calling System │ ├── Tool Definition │ ├── Tool Name │ ├── Description │ └── JSON Schema │ ├── Tool Routing │ ├── Intent Understanding │ └── Tool Selection │ ├── Argument Generation │ ├── Entity Extraction │ ├── Date Parsing │ └── Parameter Filling │ ├── Validation │ ├── Schema Validation │ └── Business Validation │ ├── Tool Execution │ ├── Dispatcher │ ├── REST API │ ├── Database │ └── Search │ ├── Error Handling │ ├── Retry │ ├── Timeout │ └── Fallback │ ├── Agent Loop │ └── Observability ├── Logging ├── Tracing └── Evaluation30. 从 Function Calling 到 Agent
整个演进过程可以这样理解:
阶段1 LLM Chat阶段2 LLM + Function Calling阶段3 LLM + Multiple Tools + Tool Routing阶段4 LLM + Tool Calling + Agent Loop阶段5 Agent + RAG + Memory + MCP + Workflow阶段6 Production Agent + Tracing + Evals + Guardrails + Sandbox + Long-Horizon Execution31. 最重要的一条执行链路
学习 Function Calling 时,真正需要掌握的是:
用户自然语言 ↓ LLM理解意图 ↓ Tool Selection ↓ Argument Extraction ↓ JSON Schema ↓ Schema Validation ↓ Business Validation ↓ Tool Dispatcher ↓ REST API / SQL / Search ↓ Tool Result ↓ 返回LLM ↓ 继续Tool Calling ↓ 或者 ↓ Final Answer32. 一句话理解几个核心概念
| 概念 | 一句话理解 |
|---|---|
| Tool Calling | LLM 使用外部能力的总称 |
| Function Calling | LLM 选择函数并生成结构化参数 |
| Tool Schema | 告诉 LLM 工具是什么、怎么调用 |
| Tool Description | 告诉模型什么时候该用这个工具 |
| Parameter Schema | 规定工具需要哪些参数 |
| Tool Routing | 从多个工具中选择正确工具 |
| Argument Extraction | 从自然语言中提取调用参数 |
| Dispatcher | 将模型生成的 Tool Call 映射到真实函数 |
| Tool Result | 工具真实执行后返回的数据 |
| Agent Loop | LLM 与 Tool 多轮循环直到完成任务 |
| Parallel Tool Calling | 一次并行调用多个独立工具 |
| RAG | 给模型获取外部知识 |
| MCP | 标准化 Agent 与 Tool 的连接方式 |
| Guardrail | 控制 Agent 可以做什么 |
| Tracing | 记录整个 Agent / Tool 调用过程 |
| Eval | 评估工具选择、参数、任务完成情况 |
33. 最终记忆版
如果只记一个公式:
Function Calling = Tool Definition + Tool Selection + Argument Generation + Tool Execution + Tool Result如果再往 Agent 扩展:
Agent = LLM + Tool Calling + Agent Loop + State + Memory + Workflow + Error Handling + Tracing + Evals而 Function Calling 最核心的思想就是:
LLM 不负责真正执行外部业务,而负责理解自然语言、选择合适的外部能力并生成结构化调用参数;应用程序负责真正执行工具,再把真实结果交回 LLM。
所以学习 Agent 时,建议先彻底掌握:
Tool Schema ↓ Tool Selection ↓ Argument Extraction ↓ Function Dispatcher ↓ Tool Result ↓ Agent Loop这几个概念理解清楚之后,再学习MCP、LangGraph、Agentic RAG、Memory、Multi-Agent会容易很多。