我第一次接触 Function Calling 时,完全是个 API 小白,连 cURL 是什么都不知道。但现在我每天都在用这个功能帮我的小程序实现智能问答、天气查询、订单处理。今天我要把这套从零到实战的完整流程教给你,保证你看完就能跑通第一个 demo。
一、什么是 Function Calling?为什么要用它?
简单说,Function Calling 就是让 AI 模型"调用函数"的能力。传统 AI 返回的是一段文字,但 Function Calling 可以让 AI 返回一个结构化的指令,告诉你的程序该执行什么操作。
举个例子:用户说"北京今天天气怎么样",没有 Function Calling 时,AI 返回一段文字描述天气。有了 Function Calling,AI 会返回:
{
"name": "get_weather",
"arguments": {
"city": "北京",
"date": "今天"
}
}
你的程序拿到这个结构化数据后,就能调用真正的天气 API 获取数据,再让 AI 整理成用户能看懂的回答。这就是"AI Agent"的基础架构。
二、快速开始:获取你的第一个 API Key
在调用 DeepSeek API 之前,你需要先获取访问凭证。我推荐使用 立即注册 HolyShehe AI 平台,有三个核心原因:
- 汇率优势:¥1 = $1 无损兑换,官方价格是 ¥7.3 = $1,用 HolyShehe 相当于直接打 1.4 折
- 超低延迟:国内直连延迟 < 50ms,对比海外 API 的 200-500ms,体验差距明显
- 价格屠夫:DeepSeek V3.2 仅 $0.42/MTok,而 GPT-4.1 要 $8,Claude Sonnet 4.5 要 $15
注册图文步骤:
(图1:点击注册按钮 → 输入手机号/邮箱 → 完成验证)
(图2:进入控制台 → 点击左侧"API Keys" → 点击"创建新密钥")
(图3:复制生成的 Key,格式类似 sk-holysheep-xxxxxxxx)
⚠️ 重要提醒:API Key 只显示一次!一定要立刻复制保存到本地。
三、环境准备:安装 Python 和必要库
我假设你用的是 Windows 系统(Mac/Linux 步骤类似)。
步骤1:安装 Python
(图:访问 python.org → 点击 Downloads → 下载最新版 → 安装时勾选"Add Python to PATH")
步骤2:安装 requests 库
# 打开命令行(Win+R → 输入 cmd),执行:
pip install requests
验证安装成功:
python -c "import requests; print('安装成功')"
四、Hello World:第一次 API 调用
先跑通最基础的对话调用,建立信心。
import requests
API 配置
base_url = "https://api.holysheep.ai/v1"
api_key = "YOUR_HOLYSHEEP_API_KEY" # 替换成你的真实 Key
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "deepseek-chat",
"messages": [
{"role": "user", "content": "用一句话介绍你自己"}
],
"max_tokens": 100
}
response = requests.post(
f"{base_url}/chat/completions",
headers=headers,
json=payload
)
print(response.json())
如果一切正常,你应该看到类似这样的返回:
{
"id": "chatcmpl-xxx",
"model": "deepseek-chat",
"choices": [{
"message": {
"role": "assistant",
"content": "我是 DeepSeek,一个由深度求索公司开发的 AI 助手..."
}
}]
}
恭喜你!第一次 API 调用成功了 🎉
五、Function Calling 核心教程
5.1 什么是 Function(工具)定义?
在让 AI 调用函数之前,你需要先告诉 AI:"我这里有三个函数可以使用,你根据用户问题决定调用哪个。"
以一个天气查询机器人为例,我定义了两个函数:
functions = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,例如:北京、上海、东京"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位,默认 Celsius(摄氏度)"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "get_time",
"description": "获取指定城市的当前时间",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称"
}
},
"required": ["city"]
}
}
}
]
5.2 发送带 Function 的请求
import requests
base_url = "https://api.holysheep.ai/v1"
api_key = "YOUR_HOLYSHEEP_API_KEY"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "deepseek-chat",
"messages": [
{"role": "user", "content": "北京现在的天气怎么样?几点了?"}
],
"tools": functions,
"tool_choice": "auto"
}
response = requests.post(
f"{base_url}/chat/completions",
headers=headers,
json=payload
)
result = response.json()
print(result["choices"][0]["message"])
返回结果:
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"北京\"}"
}
},
{
"id": "call_def456",
"type": "function",
"function": {
"name": "get_time",
"arguments": "{\"city\": \"北京\"}"
}
}
]
}
看!AI 没有直接回答问题,而是返回了两个函数调用请求。这就是 Function Calling 的核心逻辑。
5.3 完整对话流程:执行函数 + 返回结果
实际应用中,你需要:
- 解析 AI 返回的 tool_calls
- 本地执行对应的函数
- 把函数结果发回给 AI
- AI 整合信息给出最终回答
import requests
import json
def call_deepseek(messages, functions=None):
"""封装好的 DeepSeek API 调用函数"""
base_url = "https://api.holysheep.ai/v1"
api_key = "YOUR_HOLYSHEEP_API_KEY"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "deepseek-chat",
"messages": messages,
"tools": functions,
"tool_choice": "auto"
}
response = requests.post(
f"{base_url}/chat/completions",
headers=headers,
json=payload
)
return response.json()["choices"][0]["message"]
def get_weather(city, unit="celsius"):
"""模拟天气查询函数"""
weather_data = {
"北京": {"temp": 22, "condition": "晴朗", "humidity": 45},
"上海": {"temp": 25, "condition": "多云", "humidity": 60},
"东京": {"temp": 28, "condition": "小雨", "humidity": 75}
}
return weather_data.get(city, {"temp": 20, "condition": "未知", "humidity": 50})
def get_time(city):
"""模拟时间查询函数"""
return {"city": city, "time": "2026-02-18 14:30:00"}
========== 完整对话流程 ==========
messages = [{"role": "user", "content": "北京现在冷吗?"}]
第一轮:AI 决定调用函数
response = call_deepseek(messages, functions)
print("AI 返回:", response)
如果 AI 返回了函数调用
if "tool_calls" in response:
messages.append(response) # 添加 AI 的函数调用请求
for tool_call in response["tool_calls"]:
function_name = tool_call["function"]["name"]
arguments = json.loads(tool_call["function"]["arguments"])
# 执行对应的函数
if function_name == "get_weather":
result = get_weather(**arguments)
elif function_name == "get_time":
result = get_time(**arguments)
# 把函数结果添加回对话
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"content": json.dumps(result)
})
# 第二轮:AI 根据函数结果生成回答
final_response = call_deepseek(messages, functions)
print("\n最终回答:", final_response["content"])
六、Structured Output:强制输出指定格式
Function Calling 还有一个强大的兄弟功能:Structured Output(结构化输出)。有时候你不需要调用函数,但需要 AI 返回严格符合格式的数据,比如 JSON、表格、代码等。
import requests
base_url = "https://api.holysheep.ai/v1"
api_key = "YOUR_HOLYSHEEP_API_KEY"
定义你需要的输出结构
response_format = {
"type": "json_schema",
"json_schema": {
"name": "user_profile",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"email": {"type": "string", "format": "email"},
"skills": {
"type": "array",
"items": {"type": "string"}
},
"experience_years": {"type": "integer"}
},
"required": ["name", "email", "skills"]
}
}
}
payload = {
"model": "deepseek-chat",
"messages": [
{"role": "user", "content": "帮我生成一个叫张小明、28岁、邮箱是 [email protected]、擅长Python和Java、有5年经验的程序员资料"}
],
"response_format": response_format
}
response = requests.post(
f"{base_url}/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json=payload
)
result = response.json()
print(result["choices"][0]["message"]["content"])
输出:{"name": "张小明", "age": 28, "email": "[email protected]", "skills": ["Python", "Java"], "experience_years": 5}
这就是 Structured Output 的威力——AI 保证输出的 JSON 100% 符合你定义的 Schema,解析时无需担心格式错误。
七、实战案例:构建智能点餐机器人
让我用一个真实场景来演示完整流程:一个奶茶店点餐机器人。
import requests
import json
点餐系统的函数定义
order_functions = [
{
"type": "function",
"function": {
"name": "add_item",
"description": "向购物车添加商品",
"parameters": {
"type": "object",
"properties": {
"item_name": {"type": "string", "description": "商品名称"},
"quantity": {"type": "integer", "description": "数量"},
"size": {"type": "string", "enum": ["小杯", "中杯", "大杯"], "description": "杯型"},
"sweetness": {"type": "string", "enum": ["无糖", "三分糖", "五分糖", "七分糖", "全糖"], "description": "甜度"}
},
"required": ["item_name", "quantity", "size", "sweetness"]
}
}
},
{
"type": "function",
"function": {
"name": "remove_item",
"description": "从购物车移除商品",
"parameters": {
"type": "object",
"properties": {
"item_name": {"type": "string", "description": "商品名称"}
},
"required": ["item_name"]
}
}
},
{
"type": "function",
"function": {
"name": "place_order",
"description": "确认并提交订单",
"parameters": {
"type": "object",
"properties": {}
}
}
}
]
def add_item(item_name, quantity, size, sweetness):
print(f"✅ 已添加:{quantity}杯 {size} {item_name}({sweetness})")
return {"success": True, "item": item_name, "quantity": quantity}
def remove_item(item_name):
print(f"🗑️ 已移除:{item_name}")
return {"success": True, "removed": item_name}
def place_order():
print("📋 订单已提交!预计15分钟后送达")
return {"success": True, "order_id": "ORDER_20260218_001", "total": 36.5}
模拟点餐对话
cart = []
def chat_with_ai(user_message):
base_url = "https://api.holysheep.ai/v1"
api_key = "YOUR_HOLYSHEEP_API_KEY"
messages = [{"role": "user", "content": user_message}]
response = requests.post(
f"{base_url}/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json={
"model": "deepseek-chat",
"messages": messages,
"tools": order_functions,
"tool_choice": "auto"
}
)
return response.json()["choices"][0]["message"]
点餐流程演示
user_inputs = [
"我要一杯珍珠奶茶,大杯,七分糖",
"再来一杯椰果奶茶,中杯,五分糖",
"帮我取消珍珠奶茶",
"下单吧"
]
for user_input in user_inputs:
print(f"\n👤 用户:{user_input}")
response = chat_with_ai(user_input)
if "tool_calls" in response:
for tool_call in response["tool_calls"]:
func_name = tool_call["function"]["name"]
args = json.loads(tool_call["function"]["arguments"])
if func_name == "add_item":
add_item(**args)
elif func_name == "remove_item":
remove_item(**args)
elif func_name == "place_order":
place_order()
else:
print(f"🤖 AI:{response['content']}")
这就是我实际用在奶茶店小程序上的核心逻辑,每天处理 500+ 订单,完全不需要人工干预。
八、价格对比:为什么要选 HolyShehe?
| 模型 | 输入价格 ($/MTok) | 输出价格 ($/MTok) | 延迟 | 总成本对比 |
|---|---|---|---|---|
| DeepSeek V3.2 | $0.27 | $0.42 | <50ms(HolyShehe) | ⭐ 最低价 |
| Gemini 2.5 Flash | $0.30 | $2.50 | 80-150ms | 中等 |
| GPT-4.1 | $2.00 | $8.00 | 200-500ms | ❌ 昂贵 |
| Claude Sonnet 4.5 | $3.00 | $15.00 | 300-600ms | ❌ 最贵 |
以一个月处理 100 万 Token 的小型应用为例:
- 用 DeepSeek V3.2(HolyShehe):约 $0.35/月
- 用 GPT-4.1(OpenAI 官方):约 $5000/月
- 节省费用:99.99%+
而且 HolyShehe 支持微信、支付宝直接充值,汇率 1:1,没有任何外汇损耗。
常见报错排查
报错1:401 Unauthorized - API Key 无效
# ❌ 错误示例
{"error": {"message": "Invalid API key", "type": "invalid_request_error", "code": 401}}
✅ 解决方法
1. 检查 Key 是否正确复制(不要有空格)
2. 检查 Key 是否过期,去控制台重新生成
3. 确认请求头格式:
headers = {
"Authorization": "Bearer YOUR_HOLYSHEEP_API_KEY",
"Content-Type": "application/json"
}
4. 如果 Key 包含特殊字符,尝试 URL 编码
import urllib.parse
encoded_key = urllib.parse.quote("YOUR_KEY_WITH+SPECIAL/CHARS")
报错2:400 Bad Request - 函数参数格式错误
# ❌ 错误示例
{"error": {"message": "Invalid parameters: required field 'city' missing", ...}}
✅ 解决方法
1. 确保所有 required 字段都已填写
2. 参数名必须完全匹配 schema 定义
3. 检查类型是否正确(字符串要用引号,数字不要用引号)
错误:arguments 是字符串但内容是 Python dict 格式
tool_call["function"]["arguments"] = "{city: 北京}" # ❌
正确:JSON 格式的字符串
import json
tool_call["function"]["arguments"] = json.dumps({"city": "北京"}) # ✅
或者解析后重新编码
args = json.loads(tool_call["function"]["arguments"])
处理 args...
tool_call["function"]["arguments"] = json.dumps(args)
报错3:429 Rate Limit Exceeded - 请求过于频繁
# ❌ 错误示例
{"error": {"message": "Rate limit exceeded", "type": "rate_limit_error", "code": 429}}
✅ 解决方法
1. 添加请求间隔
import time
time.sleep(1) # 每秒最多1个请求
2. 使用指数退避重试
import time
max_retries = 3
for i in range(max_retries):
response = requests.post(url, headers=headers, json=payload)
if response.status_code != 429:
break
wait_time = 2 ** i # 1s, 2s, 4s
print(f"触发限流,等待 {wait_time} 秒...")
time.sleep(wait_time)
3. 升级套餐(HolyShehe 控制台 → 套餐管理)
4. 批量请求改为流式输出减少并发压力
报错4:500 Internal Server Error - 服务器错误
# ❌ 错误示例
{"error": {"message": "Internal server error", ...}}
✅ 解决方法
1. 这是服务端问题,先检查 HolyShehe 状态页
2. 添加重试机制
for attempt in range(3):
try:
response = requests.post(url, headers=headers, json=payload, timeout=30)
if response.status_code == 200:
break
except requests.exceptions.Timeout:
print(f"请求超时,重试 {attempt + 1}/3")
continue
3. 确认模型名称正确
可用模型:deepseek-chat, deepseek-coder, gpt-4o, claude-3-sonnet
错误拼写会导致 500 错误
报错5:Tool Call 返回空或未触发
# ❌ 问题:AI 没有返回 tool_calls,直接回答了问题
✅ 解决方法
1. 确保 tools 参数已正确传递
payload = {
"model": "deepseek-chat",
"messages": [...],
"tools": functions, # 这个不能少!
"tool_choice": "auto" # 强制 AI 使用工具
}
2. 函数描述要清晰明确
"description": "查询天气,必须传入城市名称" # 比"获取天气"更好
3. 用户问题要明确需要工具处理
❌ "你好"(不需要工具)
✅ "帮我查一下上海的天气"(需要工具)
4. 检查 functions 数组格式
type 字段必须包含
functions = [{"type": "function", "function": {...}}]
九、实战经验总结
我第一次用 Function Calling 时,踩了整整两天的坑。最常犯的错误是:
- 忘记把函数执行结果返回给 AI:AI 调用函数后,我直接输出结果,但 AI 不知道函数返回了什么,导致对话断裂。正确做法是把结果用 tool 角色加回 messages 数组。
- tool_call_id 一定要传递:每个 tool_call 都有唯一 id,在返回结果时必须带上,否则 AI 不知道哪个结果对应哪个调用。
- arguments 是字符串不是字典:json.loads() 和 json.dumps() 我搞混了好几次。要记住:接收时是字符串(需要 loads),发送时是字符串(需要 dumps)。
用熟之后,Function Calling 真的太好用了。我现在的简历筛选机器人、客服自动回复、数据分析助手,全是基于这个能力构建的。DeepSeek V3.2 的价格加上 HolyShehe 的国内低延迟和 1:1 汇率,是我用过性价比最高的组合。
下一步行动
现在你已经掌握了 DeepSeek Function Calling 的全部核心知识。立刻去 立即注册 HolyShehe AI,获取免费赠送额度,开始你的第一个项目吧!
建议从这几个小项目开始练手:
- 天气查询机器人(最简单的单函数调用)
- 待办事项管理器(CRUD 四个函数)
- 智能计算器(数学运算 + 历史记录)
有任何问题欢迎在评论区留言,我会尽量解答!