MCP+Agent 工作流
本文档介绍 AI Agent 开发中的核心概念:Function Calling、Agent 智能体、MCP 协议与 A2A 协议。
一、Function Calling(函数调用)
1.1 定义与作用
Function Calling 由 OpenAI 等公司推动,允许大语言模型与外部工具连接,将自然语言转换为 API 调用。这解决了大模型在训练结束后知识更新停滞的问题。
通过调用外部工具和服务,Function Calling 帮助大模型解决实时性问题,如"今天温度多少度"、"大盘收盘点数"等。
1.2 工作原理
用户 → LLM识别需求 → 选择函数 → 准备参 数 → 调用函数 → 整合回答 → 用户
以天气查询为例:
| 步骤 | 描述 |
|---|---|
| 第一步 | 识别需求:这是一个关于实时天气的问题,需要调用外部 API |
| 第二步 | 选择函数:从可用函数中选择 get_current_weather |
| 第三步 | 准备参数:{"location": "北京", "unit": "celsius"} |
| 第四步 | 调用函数:系统使用这些参数调用实际的天气 API |
| 第五步 | 整合回答:"北京今天晴朗,23°C,湿度45%,最高26°C,最低18°C" |
1.3 优点与局限
| 优点 | 局限 |
|---|---|
| 实现简单,适合单一模型少量功能 | 缺乏跨模型一致性 |
| 一键将模型输出对接到代码逻辑 | 每个 LLM 供应商接口格式略有差异 |
| 逻辑直观 | 无状态性:模型仅生成调用规范,实际执行由外部系统完成 |
1.4 Function Calling 代码示例
以下是一个使用 OpenAI Function Calling 进行天气查询的完整示例:
import json
from openai import OpenAI
client = OpenAI(api_key="your-api-key")
# 定义可用函数
functions = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取指定位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如:北京、东京"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["location"]
}
}
}
]
def get_current_weather(location, unit="celsius"):
"""模拟天气查询 API"""
return f"{location}今天晴朗,23°C,湿度45%"
# 用户请求
messages = [{"role": "user", "content": "北京今天温度多少度?"}]
# 第一次调用:让模型决定是否调用函数
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=functions
)
assistant_message = response.choices[0].message
print(f"模型回复: {assistant_message}")
# 如果模型选择调用函数
if assistant_message.tool_calls:
tool_call = assistant_message.tool_calls[0]
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
# 执行函数
if function_name == "get_current_weather":
result = get_current_weather(**function_args)
# 将函数结果返回给模型
messages.append(assistant_message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
# 第二次调用:整合结果生成最终回答
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(f"最终回答: {final_response.choices[0].message.content}")
二、Agent 智能体
2.1 定义
将 Agent 视为人工智能大脑,它使用 LLM 进行推理、计划和采取行动。
- 功能:具备自主决策能力的 AI 系统,通过结合 LLM 的核心推理能力、工具调用(Tools)、记忆(Memory)和规划(Planning)等模块,完成复杂任务。
- 本质:是一个多组件协同的"代理",能动态选择工具、迭代执行直至目标达成。
2.2 核心特点
| 特点 | 说明 |
|---|---|
| 自治性 | 自主决定何时调用工具、如何组合结果 |
| 多步迭代 | 通过"思考-行动-观察"循环处理复杂问题 |
| 组件架构 | 规划模块、工具库、记忆机制协同工作 |