为什么Claude要推MCP,来看看Function Calling

一般来说大模型基本是上知天文、下知地理无所不能的。但让大模型发个邮件试试,

那么在大模型发展到第二阶段也就是 Agent 阶段时,大模型需要调用第三方应用的场景就越来越多,发个邮件,问个天气等等。

目前来说实现的方案就是 OpenAI 的 Function Calling 和 Claude 的 MCP

而 Function Calling是openai自身模型能力的工具,适合需要快速接入OpenAI生态的场景。当然其核心思想(让大模型调用外部函数/API)也被多家厂商借鉴或实现类似功能。但没有统一的标准,所以 MCP 因应而生。

这里先来介绍一下 Function Calling,

一、Function Calling 介绍

那么在 2023 年的 6 月,由OpenAI 推出了"Function Calling"。Function Calling 就是为了解决此问题。通过 Function Calling,大模型能够通过结构化输入连接到外部系统,比如通过 API 进行交互,从而实现与外部世界的连接。

通过Function Calling AI 可以与外部工具和服务连接起来,这样 AI 的能力就非常的广阔。这样可以打造更智能、更强大的人工智能。

Function Calling 技术的不断发展,我们相信它将在未来的 AI 应用中发挥越来越重要的作用。

以下是官方对整个过程的描述:

那么具体来看看在大模型中实现函数调用的具体步骤:

二、Function Calling 实现

这是我模型的一个 Python 项目,

bash 复制代码
function_calling_project/
│── src/                
│   │── main.py         			# 主程序入口
│   │── ai_client.py   			  # OpenAI API 客户端
│   │── function_tools.py     # 定义可供模型调用的函数
│   │── handlers.py     			# 处理模型返回的函数调用

Step1:编写主程序

示例代码: main.py(主程序入口)

python 复制代码
from api_client import call_model
from handlers import handle_function_call
from tools import TOOLS

def main():
    input_messages = [{
        "role": "user",
        "content": "巴黎今天的天气如何?"
    }]

    response_output = call_model(input_messages, TOOLS)
    function_result = handle_function_call(response_output)

    if isinstance(function_result, dict):
        input_messages.append({
            "type": "function_call_output",
            "call_id": function_result["call_id"],
            "output": function_result["output"]
        })
        final_response = call_model(input_messages, TOOLS)
        print("最终响应:", final_response.output_text)
    else:
        print("处理失败:", function_result)

if __name__ == "__main__":
    main()

Step2:定义函数

首先,需要定义要调用的函数,它告诉模型它可以做什么以及期望什么样的输入参数。

📌 示例代码: function_tools.py(可提供给模型调用的函数)

python 复制代码
import requests

def get_weather(latitude, longitude):
    """获取指定坐标的天气数据"""
    response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m")
    data = response.json()
    return data['current']['temperature_2m']

TOOLS = [{
    "type": "function",
    "name": "get_weather",
    "description": "获取指定经纬度的当前气温(摄氏)。",
    "parameters": {
        "type": "object",
        "properties": {
            "latitude": {"type": "number"},
            "longitude": {"type": "number"}
        },
        "required": ["latitude", "longitude"],
        "additionalProperties": False
    },
    "strict": True
}]

Step3:函数定义传递给模型

调用模型时,需要将函数定义传递给模型。

📌 示例代码: ai_client.py(调用模型客户端程序)

ini 复制代码
from openai import OpenAI
client = OpenAI()

input_messages = [{
    "role": "user",
    "content": "巴黎今天的天气如何?"
}]

response = client.responses.create(
    model="gpt-4.1",
    input=input_messages,
    tools=tools
)

Step3:模型决定调用函数

让模型来决定是否需要触发调用函数,如果模型认为需要调用函数,它会返回相应的函数名称和函数需要输入参数。

📌 示例返回结果:

css 复制代码
[    {        "type": "function_call",        "id": "fc_12345xyz",        "call_id": "call_12345xyz",        "name": "get_weather",        "arguments": "{"latitude":48.8566,"longitude":2.3522}"    }]

📌 示例代码: handlers.py(处理函数调用逻辑)

python 复制代码
import json
from tools import get_weather

def handle_function_call(response_output):
    """解析模型的函数调用请求并执行"""
    if not response_output:
        return "未返回可用数据。"

    tool_call = response_output[0]  # 这里只处理第一个函数调用
    args = json.loads(tool_call['arguments'])

    if tool_call["name"] == "get_weather":
        result = get_weather(args["latitude"], args["longitude"])
        return {"call_id": tool_call["call_id"], "output": str(result)}

    return "无法识别的函数调用。"

Step4:执行函数

执行用户自己开发的函数或第三方函数,程序解析模型的响应并执行对应的函数代码。

📌 示例代码:handlers.py(处理函数调用逻辑)

css 复制代码
result = get_weather(args["latitude"], args["longitude"])
return {"call_id": tool_call["call_id"], "output": str(result)}

Step5:返回函数执行结果

将结果提供给模型,以便它可以将信息整合到最终响应中。

📌 示例代码:

scss 复制代码
final_response = call_model(input_messages, TOOLS)
print("最终响应:", final_response.output_text)

📌 示例最终输出:

复制代码
"巴黎当前的气温是 14°C。"

这就是在大模型中实现函数调用的完整过程!

三、总结

那我们来总结一下,就是用户把自己的函数定义给到模型,用户提问题后,模型看看要不要调用函数,当模型决定要调用函数时就生成函数需要的参数及格式,再调用函数并把结果合并,最终返回给用户。

那么这里有个比较关键的东西就是函数定义:

json 复制代码
{
    "type": "function",
    "name": "get_weather",
    "description": "获取指定经纬度的当前气温(摄氏)。",
    "parameters": {
        "type": "object",
        "properties": {
            "latitude": {"type": "number"},
            "longitude": {"type": "number"}
        }
    }
}

它会最模型决定是否要调用函数的关键, 每个函数都带有一个 description,用来告诉模型它的用途。 如果 description 明确提到天气查询,且匹配用户请求的意图,模型就可能决定调用这个函数。当然description 并不是唯一判断的依据,它还会结合其他因素。

虽然 Function Calling 实现了调取外部函数,但 Function Calling是OpenAI为自家模型设计的工具,最适合需要快速接入OpenAI生态的场景。虽然其核心思想(让大模型调用外部函数/API)被其他厂商借鉴,但各家实现方式不同,缺乏统一标准,这也正是 Claude 推出 MCP的原因

我是栈江湖,如果你喜欢此文章,不要忘记点赞+关注

相关推荐
Lambert2811 天前
MCP 史上最大升级:握手没了、会话没了,Java 生态的六个坑
ai编程·mcp
会周易的程序员1 天前
软件接入大模型实现 Agent —— 从原理到 C++ 落地完全指南
c++·人工智能·物联网·架构·agent·工业协议·mcp
梦想blog1 天前
Claude Code + Chrome MCP:让浏览器自动化测试更简单
前端·chrome·自动化·mcp
xrlfreedom2 天前
大厂 MCP 面试实录:基于 JSON Schema 与 RAG 的调用异常排查方案设计
json schema·mcp·rag 知识库
逸Y 仙X2 天前
MCP(模型控制协议)完全指南:从核心概念到实战开发
python·大模型·llm·ai编程·mcp
Behavior2 天前
Claude Code + chrome-devtools MCP:安装部署与实战全记录
claude·mcp
阿里云云原生2 天前
从 MCP 协议演进看网关架构变革:Higress v2.2.4 实践与验证报告
mcp
deepseek232 天前
MCP Gateway 架构实战:企业级 AI Agent 连接层的设计与选型
ai agent·企业架构·mcp
今日无bug2 天前
从「拿来主义」到「亲手造轮子」:2 种 MCP 文件服务器写法对比
前端·node.js·mcp
SeaDhdhdhdhdh3 天前
MCP Server 搭建与使用指南
java·ai·agent·mcp