AI Agent 工具调用实战:MCP 协议与 Function Calling 深度解析前言工具调用(Tool Calling)是 AI Agent 的核心能力,让大模型能够与外部世界交互。本文将深入对比 MCP(Model Context Protocol)协议与 OpenAI Function Calling 两种主流方案,帮助你选择最适合的技术栈。一、工具调用的本质1.1 为什么需要工具调用?大语言模型本身是被动的,它只能处理文本输入输出。工具调用让模型能够:查询实时数据:搜索网络、查询数据库执行操作:发送邮件、调用 API处理复杂任务:多步骤工作流、代码执行1.2 工具调用的核心流程┌─────────────────────────────────────────────────────┐ │ 工具调用流程 │ ├─────────────────────────────────────────────────────┤ │ │ │ 用户请求 → 模型分析 → 选择工具 → 生成参数 │ │ ↓ ↓ │ │ 返回结果 ← 执行工具 ← 验证参数 ← 解析参数 │ │ │ └─────────────────────────────────────────────────────┘1.3 两种主流方案对比特性MCP 协议Function Calling提出者AnthropicOpenAI设计理念标准化协议API 集成工具发现自动发现手动注册跨模型支持✅ 支持❌ 仅 OpenAI复杂度较高较低生态成熟度快速发展成熟稳定二、OpenAI Function Calling 实战2.1 基本用法fromopenaiimportOpenAI client=OpenAI()# 定义工具tools=[{"type":"function","function":{"name":"get_weather","description":"获取指定城市的天气信息","parameters":{"type":"object","properties":{"city":{"type":"string","description":"城市名称,如:北京、上海"},"unit":{"type":"string","enum":["celsius","fahrenheit"],"description":"温度单位"}},"required":["city"]}}},{"type":"function","function":{"name":"search_web","description":"搜索网络获取信息","parameters":{"type":"object","properties":{"query":{"type":"string","description":"搜索关键词"}},"required":["query"]}}}]# 发送请求response=client.chat.completions.create(model="gpt-4-turbo",messages=[{"role":"user","content":"北京今天天气怎么样?"}],tools=tools,tool_choice="auto"# auto, required, none)# 处理工具调用message=response.choices[0].messageifmessage.tool_calls:fortool_callinmessage.tool_calls:function_name=tool_call.function.name arguments=json.loads(tool_call.function.arguments)print(f"调用工具:{function_name}")print(f"参数:{arguments}")# 执行工具iffunction_name=="get_weather":result=get_weather(**arguments)# 将结果返回给模型messages.append(message)messages.append({"role":"tool","tool_call_id":tool_call.id,"content":str(result)})# 继续对话final_response=client.chat.completions.create(model="gpt-4-turbo",messages=messages)2.2 多工具并行调用# GPT-4 支持并行调用多个工具response=client.chat.completions.create(model="gpt-4-turbo",messages=[{"role":"user","content":"比较北京和上海今天的天气"}],tools=tools,parallel_tool_calls=