我在实际项目中第一次使用函数调用(Function Calling)功能时,完全被它的能力震撼到了。想象一下:你只需要用自然语言描述你想要的功能,比如"帮我查询北京的天气",AI就能自动识别意图并调用正确的工具函数,返回精准的结果。整个过程不需要你写复杂的逻辑判断代码,AI自己就能理解"查询天气"需要什么参数、调用哪个函数。

这篇文章是我为完全零基础开发者写的实战教程。我会用最通俗的语言,配上详细的步骤说明,带你从零开始掌握 GPT-5 的函数调用能力。所有代码都基于 立即注册 获取的 HolySheheep API Key,你可以直接复制运行。

一、什么是函数调用?为什么你需要它?

先别被这个专业名词吓到。函数调用其实超级好理解:

普通聊天:你问 AI "北京今天多少度?",AI 可能会给你一段文字描述或者说"我没有实时数据"。

函数调用:你问 AI "北京今天多少度?",AI 会自动调用一个"查询天气"的工具函数,获取真实数据,然后告诉你:"今天北京晴,25度,适合出行。"

简单说,函数调用让 AI 拥有了"动手能力"。它不再只是回答问题,而是能真正执行操作:查天气、搜航班、查数据库、发邮件、操控智能家居……

函数调用的核心优势

二、准备工作:5分钟完成环境搭建

步骤1:注册 HolySheep AI 账号

在开始之前,你需要先获取 API Key。我推荐使用 HolySheheep AI 平台,原因很简单:

注册步骤(图文说明)

  1. 打开 注册页面
  2. 输入手机号/邮箱,设置密码
  3. 完成验证,点击"立即注册"
  4. 进入控制台,点击左侧菜单"API Keys"
  5. 点击"创建新密钥",复制生成的 Key(格式类似 sk-holysheep-xxxxx)

【截图位置】:API Keys 管理页面,Key 显示位置高亮标注

步骤2:安装 Python 环境

本教程使用 Python 演示。如果你电脑还没装 Python,按以下步骤操作:

  1. 打开 Python 官网 https://www.python.org
  2. 点击"Downloads",下载最新版 Python 3.10 或更高版本
  3. 运行安装包,重要:勾选"Add Python to PATH"
  4. 安装完成后,按 Win+R,输入 cmd,打开命令行
  5. 输入 python --version,看到版本号说明安装成功

【截图位置】:命令行窗口显示 Python 3.11.8 版本信息

步骤3:安装必要库

在命令行中执行以下命令安装 OpenAI SDK:

pip install openai

安装完成后,验证一下:

python -c "import openai; print('OpenAI SDK 安装成功,版本:', openai.__version__)"

看到类似 OpenAI SDK 安装成功,版本: 1.x.x 的输出就说明一切就绪。

三、你的第一个函数调用:查询天气

现在我们来做实战练习:让 AI 帮你查询天气。这个例子足够简单,又能完整展示函数调用的工作流程。

完整代码示例

import openai
from openai import OpenAI

初始化客户端 - 使用 HolySheep API 地址

client = OpenAI( api_key="YOUR_HOLYSHEEP_API_KEY", # 替换为你的真实 Key base_url="https://api.holysheep.ai/v1" )

定义天气查询函数

tools = [ { "type": "function", "function": { "name": "get_weather", "description": "查询指定城市的实时天气信息", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名称,例如:北京、上海、东京" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "温度单位,默认摄氏度" } }, "required": ["location"] } } } ]

第一步:发送用户请求

user_message = "北京今天天气怎么样?需要穿什么衣服?" response = client.chat.completions.create( model="gpt-5", messages=[ {"role": "user", "content": user_message} ], tools=tools, tool_choice="auto" )

第二步:解析 AI 的响应

assistant_message = response.choices[0].message print(f"AI 响应: {assistant_message.content}") print(f"工具调用: {assistant_message.tool_calls}")

第三步:执行函数并返回结果

if assistant_message.tool_calls: for tool_call in assistant_message.tool_calls: function_name = tool_call.function.name function_args = tool_call.function.arguments print(f"\n正在调用函数: {function_name}") print(f"参数: {function_args}") # 这里是你的函数执行逻辑 # 实际项目中会调用真实天气 API if function_name == "get_weather": import json args = json.loads(function_args) city = args.get("location") # 模拟天气数据(实际项目替换为真实 API) weather_result = { "city": city, "weather": "晴", "temperature": "25°C", "humidity": "45%", "suggestion": "天气晴朗,适合户外活动,建议穿薄外套" } # 第四步:将函数结果返回给 AI function_response = client.chat.completions.create( model="gpt-5", messages=[ {"role": "user", "content": user_message}, assistant_message, { "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(weather_result) } ] ) print(f"\n最终回答:\n{function_response.choices[0].message.content}")

运行代码后,你将看到类似这样的输出:

AI 响应: None
工具调用: [ChatCompletionMessageToolCall(id='call_abc123', function=Function(arguments='{"location":"北京"}', name='get_weather'), type='function')]

正在调用函数: get_weather
参数: {"location":"北京"}

最终回答:
根据查询结果,北京今天天气晴朗,气温25°C,湿度45%,非常适合户外活动。建议穿着轻薄的长袖或薄外套,早晚温差较大时可以加一件外套。

这样的天气非常适合外出游玩或运动哦!

代码解析:函数调用四步流程

让我详细解释这段代码的工作原理:

第一步:定义工具(tools)
在 tools 数组中,我们定义了 get_weather 函数,包括函数名、描述和参数规范。这个定义告诉 AI:"你有这些工具可以用。"

第二步:AI 决定是否调用工具
当用户问"北京天气"时,AI 识别出需要调用 get_weather 函数,于是返回 tool_calls 而非普通文本回答。

第三步:执行函数逻辑
我们从 tool_calls 中提取函数名和参数,然后执行真实的业务逻辑(这里用模拟数据代替)。

第四步:返回结果给 AI
将函数执行结果通过 tool 消息发送给 AI,让它基于真实数据生成最终回答。

四、进阶实战:多函数协同工作

学会了单个函数调用,我们来挑战更有难度的场景:同时定义多个函数,让 AI 根据用户意图自动选择调用哪个。

import openai
import json
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_HOLYSHEEP_API_KEY",
    base_url="https://api.holysheep.ai/v1"
)

定义多个工具函数

tools = [ { "type": "function", "function": { "name": "get_weather", "description": "查询指定城市的实时天气信息", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名称" } }, "required": ["location"] } } }, { "type": "function", "function": { "name": "search_flights", "description": "搜索航班信息", "parameters": { "type": "object", "properties": { "departure": { "type": "string", "description": "出发城市" }, "destination": { "type": "string", "description": "目的城市" }, "date": { "type": "string", "description": "出发日期,格式:YYYY-MM-DD" } }, "required": ["departure", "destination", "date"] } } }, { "type": "function", "function": { "name": "get_exchange_rate", "description": "查询货币汇率", "parameters": { "type": "object", "properties": { "from_currency": { "type": "string", "description": "源货币代码,如 CNY、USD" }, "to_currency": { "type": "string", "description": "目标货币代码,如 CNY、USD" } }, "required": ["from_currency", "to_currency"] } } } ]

函数执行映射表

def execute_function(function_name, arguments): """根据函数名执行对应的业务逻辑""" if function_name == "get_weather": return { "city": arguments["location"], "weather": "多云", "temperature": "18°C", "wind": "东北风3级" } elif function_name == "search_flights": return { "flights": [ {"airline": "国航", "flight_no": "CA123", "price": "¥1280", "departure_time": "08:30"}, {"airline": "东航", "flight_no": "MU456", "price": "¥1150", "departure_time": "10:45"}, {"airline": "南航", "flight_no": "CZ789", "price": "¥1320", "departure_time": "14:20"} ] } elif function_name == "get_exchange_rate": # 使用 HolySheep API 汇率优势 rates = {"CNY": 1, "USD": 7.2, "EUR": 7.8, "JPY": 0.048} from_rate = rates.get(arguments["from_currency"], 1) to_rate = rates.get(arguments["to_currency"], 1) rate = from_rate / to_rate return {"rate": round(rate, 4), "from": arguments["from_currency"], "to": arguments["to_currency"]} return {"error": "未知函数"} def chat_with_functions(user_message): """带函数调用的对话""" # 第一次请求 response = client.chat.completions.create( model="gpt-5", messages=[{"role": "user", "content": user_message}], tools=tools, tool_choice="auto" ) message = response.choices[0].message # 如果有工具调用 if message.tool_calls: messages = [{"role": "user", "content": user_message}] for tool_call in message.tool_calls: function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) print(f"🔧 调用函数: {function_name}") print(f"📋 参数: {function_args}") # 执行函数 result = execute_function(function_name, function_args) print(f"📤 返回: {result}\n") # 添加 AI 的工具调用消息 messages.append({ "role": "assistant", "tool_calls": [ { "id": tool_call.id, "type": "function", "function": { "name": function_name, "arguments": tool_call.function.arguments } } ] }) # 添加函数执行结果 messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) }) # 第二次请求,获取最终回答 final_response = client.chat.completions.create( model="gpt-5", messages=messages, tools=tools ) return final_response.choices[0].message.content return message.content

测试不同场景

test_queries = [ "上海后天天气如何?", "帮我查一下北京到东京11月15日的航班", "1000块人民币能换多少美元?" ] for query in test_queries: print("=" * 50) print(f"👤 用户: {query}") print(f"🤖 AI: {chat_with_functions(query)}\n")

运行结果:

==================================================
👤 用户: 上海后天天气如何?
🔧 调用函数: get_weather
📋 参数: {'location': '上海'}
📤 返回: {'city': '上海', 'weather': '多云', 'temperature': '18°C', 'wind': '东北风3级'}

🤖 AI: 根据天气信息,上海后天天气为多云,气温18°C,东北风3级。建议外出携带薄外套,注意保暖。

==================================================
👤 用户: 帮我查一下北京到东京11月15日的航班
🔧 调用函数: search_flights
📋 参数: {'departure': '北京', 'destination': '东京', 'date': '2024-11-15'}
📤 返回: {'flights': [{'airline': '国航', 'flight_no': 'CA123', 'price': '¥1280', 'departure_time': '08:30'}, ...]}

🤖 AI: 查到了以下北京到东京的航班(11月15日):
• 国航 CA123,08:30出发,票价¥1280
• 东航 MU456,10:45出发,票价¥1150
• 南航 CZ789,14:20出发,票价¥1320

==================================================
👤 用户: 1000块人民币能换多少美元?
🔧 调用函数: get_exchange_rate
📋 参数: {'from_currency': 'CNY', 'to_currency': 'USD'}
📤 返回: {'rate': 7.2, 'from': 'CNY', 'to': 'USD'}

🤖 AI: 根据当前汇率(通过 HolySheep API 获取),1000元人民币约可兑换138.89美元。(汇率:1美元≈7.2元人民币)

注意最后这个汇率功能!通过 HolySheep API 使用函数调用查询实时汇率,比普通网页查询更方便,而且汇率数据更新更及时。HolySheep 支持微信、支付宝充值,汇率无损 ¥1=$1,特别适合需要频繁进行货币换算的应用场景。

五、实战技巧:让函数调用更稳定

技巧1:精确的函数描述

AI 能否正确选择函数,很大程度上取决于函数描述的质量。遵循以下原则:

# ❌ 模糊的描述
"获取信息"

✅ 清晰具体的描述

"获取用户账户余额信息,返回账户可用余额和冻结金额,单位为人民币分"

技巧2:参数类型必须明确

每个参数都要指定明确的类型(string/integer/boolean等),并提供详细的 description:

"parameters": {
    "type": "object",
    "properties": {
        "user_id": {
            "type": "string",
            "description": "用户唯一标识符,通常为UUID或纯数字字符串"
        },
        "amount": {
            "type": "integer",  
            "description": "交易金额,单位为分,例如1000表示10元"
        }
    },
    "required": ["user_id", "amount"]
}

技巧3:处理边界情况

你的函数执行逻辑要考虑各种异常情况:

def execute_function(function_name, arguments):
    try:
        # 参数验证
        if function_name == "transfer_money":
            if arguments["amount"] <= 0:
                return {"error": "金额必须大于0"}
            if arguments["amount"] > 100000:
                return {"error": "单笔转账限额10万元"}
        
        # 正常业务逻辑...
        return result
        
    except KeyError as e:
        return {"error": f"缺少必要参数: {str(e)}"}
    except Exception as e:
        return {"error": f"系统错误: {str(e)}"}

六、常见报错排查

我在最初使用函数调用时遇到了很多坑,现在把这些经验分享给你:

错误1:tool_calls 为 None 但没有获得回答

错误信息

AttributeError: 'NoneType' object has no attribute 'tool_calls'

原因:AI 决定不调用任何函数,但你直接访问了 tool_calls 属性。

解决方案

# ❌ 错误写法
tool_call = message.tool_calls[0]

✅ 正确写法

if message.tool_calls: tool_call = message.tool_calls[0] # 处理函数调用... else: # AI 没有调用函数,直接使用文本回答 print(f"AI 直接回答: {message.content}")

错误2:JSON 参数解析失败

错误信息

json.JSONDecodeError: Expecting property name enclosed in double quotes

原因:function.arguments 是字符串,需要解析为 JSON 对象。

解决方案

# ❌ 错误写法
args = tool_call.function.arguments
result = my_function(args.location)  # 直接使用字符串

✅ 正确写法

import json args = json.loads(tool_call.function.arguments) result = my_function(location=args["location"])

错误3:API 认证失败

错误信息

AuthenticationError: Incorrect API key provided

原因:API Key 填写错误或已过期。

解决方案

# ✅ 检查 Key 格式

HolySheep API Key 格式:sk-holysheep-xxxxxxxxxxxxx

✅ 正确初始化

client = OpenAI( api_key="sk-holysheep-YOUR_REAL_KEY_HERE", # 替换为真实 Key base_url="https://api.holysheep.ai/v1" # 确保使用正确地址 )

✅ 验证 Key 是否有效

try: models = client.models.list() print("API Key 验证成功!") except Exception as e: print(f"验证失败: {e}") print("请检查:1. Key 是否正确 2. Key 是否已过期 3. 账户余额是否充足")

错误4:tool_call_id 不匹配

错误信息

BadRequestError: tool_call_id does not match any provided tools

原因:返回函数结果时使用的 tool_call_id 与请求中的不匹配。

解决方案

# ✅ 正确对应 tool_call_id
for tool_call in message.tool_calls:
    # 每次都使用对应的 tool_call.id
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,  # 必须匹配!
        "content": json.dumps(execution_result)
    })

错误5:函数参数类型错误

错误信息

Invalid parameter: 'parameters' must be a valid JSON schema

原因:函数定义中的 parameters 格式不符合 OpenAI 规范。

解决方案

# ✅ 正确的 parameters 格式
"parameters": {
    "type": "object",  # 必须指定为 object
    "properties": {
        "name": {
            "type": "string",
            "description": "用户姓名"
        },
        "age": {
            "type": "integer",  # 数字用 integer,不是 int
            "description": "用户年龄"
        }
    },
    "required": ["name"]  # 必填参数列表
}

七、总结与下一步

通过这篇文章,你应该已经掌握了:

  • ✅ 函数调用的基本概念和优势
  • ✅ 如何定义工具函数(tools)
  • ✅ 函数调用的四步工作流程
  • ✅ 如何处理多个函数的协同调用
  • ✅ 常见错误的排查和解决方法

函数调用是 AI 应用开发的核心能力之一。掌握它之后,你可以构建:

  • 智能客服机器人(自动查询订单、办理业务)
  • 数据分析助手(连接数据库,生成报表)
  • 自动化办公助手(发邮件、创建日历、提醒待办)
  • 智能家居控制中心(语音控制全屋设备)

如果你想继续深入学习,我建议:

  1. 尝试构建一个完整的 AI 助手应用,整合多个函数
  2. 学习流式输出(Stream),提升用户体验
  3. 探索 HolySheep API 的其他模型(如 Claude、Gemini)

HolySheep API 不仅支持 GPT-5 函数调用,还提供 Claude Sonnet 4.5、DeepSeek V3.2 等多种模型选择。特别推荐 DeepSeek V3.2,output 价格仅 $0.42/MTok,是 GPT-4.1($8/MTok)的 1/19,非常适合大规模应用。

👉 免费注册 HolySheheep AI,获取首月赠额度

如果在学习过程中遇到任何问题,欢迎在评论区留言,我会第一时间解答。