Skip to content

DeepSeek API 函数调用指南

函数调用(Function Calling)是 DeepSeek API 的一项强大功能,允许模型调用外部工具和服务,扩展AI的能力边界。

概述

函数调用功能使得 AI 模型能够:

  • 调用外部 API 和服务
  • 执行计算和数据处理
  • 与数据库交互
  • 控制外部设备和系统
  • 获取实时信息

基本概念

函数定义

函数需要使用 JSON Schema 格式定义,包含:

  • name: 函数名称
  • description: 函数描述
  • parameters: 参数定义(JSON Schema 格式)

函数调用流程

  1. 用户发送包含函数定义的请求
  2. 模型分析用户意图,决定是否调用函数
  3. 模型返回函数调用请求
  4. 应用程序执行函数并获取结果
  5. 将函数结果发送回模型
  6. 模型基于函数结果生成最终回复

快速开始

基础示例

python
import requests
import json

# API 配置
url = "https://api.deepseek.com/v1/chat/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"
}

# 定义函数
functions = [
    {
        "name": "get_weather",
        "description": "获取指定城市的天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位"
                }
            },
            "required": ["city"]
        }
    }
]

# 发送请求
data = {
    "model": "deepseek-chat",
    "messages": [
        {
            "role": "user",
            "content": "北京今天天气怎么样?"
        }
    ],
    "functions": functions,
    "function_call": "auto"
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

# 检查是否有函数调用
if "function_call" in result["choices"][0]["message"]:
    function_call = result["choices"][0]["message"]["function_call"]
    function_name = function_call["name"]
    function_args = json.loads(function_call["arguments"])
    
    # 执行函数(这里是模拟)
    if function_name == "get_weather":
        weather_result = {
            "city": function_args["city"],
            "temperature": "22°C",
            "condition": "晴朗",
            "humidity": "45%"
        }
        
        # 将函数结果发送回模型
        data["messages"].append({
            "role": "assistant",
            "content": None,
            "function_call": function_call
        })
        data["messages"].append({
            "role": "function",
            "name": function_name,
            "content": json.dumps(weather_result, ensure_ascii=False)
        })
        
        # 获取最终回复
        final_response = requests.post(url, headers=headers, json=data)
        print(final_response.json()["choices"][0]["message"]["content"])

高级用法

多函数定义

python
functions = [
    {
        "name": "calculate",
        "description": "执行数学计算",
        "parameters": {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "数学表达式,如 '2 + 3 * 4'"
                }
            },
            "required": ["expression"]
        }
    },
    {
        "name": "search_database",
        "description": "在数据库中搜索信息",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "搜索查询"
                },
                "table": {
                    "type": "string",
                    "description": "数据表名称"
                },
                "limit": {
                    "type": "integer",
                    "description": "返回结果数量限制",
                    "default": 10
                }
            },
            "required": ["query", "table"]
        }
    }
]

强制函数调用

python
# 强制调用特定函数
data = {
    "model": "deepseek-chat",
    "messages": [...],
    "functions": functions,
    "function_call": {"name": "get_weather"}  # 强制调用 get_weather 函数
}

禁用函数调用

python
# 禁用函数调用
data = {
    "model": "deepseek-chat",
    "messages": [...],
    "functions": functions,
    "function_call": "none"  # 禁用所有函数调用
}

实际应用场景

1. 天气查询助手

python
def get_weather(city, unit="celsius"):
    # 调用天气 API
    # 返回天气信息
    pass

weather_function = {
    "name": "get_weather",
    "description": "获取指定城市的实时天气信息",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "城市名称"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
        },
        "required": ["city"]
    }
}

2. 数据库查询助手

python
def query_database(sql_query, table_name):
    # 执行数据库查询
    # 返回查询结果
    pass

database_function = {
    "name": "query_database",
    "description": "执行数据库查询",
    "parameters": {
        "type": "object",
        "properties": {
            "sql_query": {"type": "string", "description": "SQL 查询语句"},
            "table_name": {"type": "string", "description": "目标数据表"}
        },
        "required": ["sql_query", "table_name"]
    }
}

3. 文件操作助手

python
def read_file(file_path):
    # 读取文件内容
    pass

def write_file(file_path, content):
    # 写入文件内容
    pass

file_functions = [
    {
        "name": "read_file",
        "description": "读取文件内容",
        "parameters": {
            "type": "object",
            "properties": {
                "file_path": {"type": "string", "description": "文件路径"}
            },
            "required": ["file_path"]
        }
    },
    {
        "name": "write_file",
        "description": "写入文件内容",
        "parameters": {
            "type": "object",
            "properties": {
                "file_path": {"type": "string", "description": "文件路径"},
                "content": {"type": "string", "description": "文件内容"}
            },
            "required": ["file_path", "content"]
        }
    }
]

最佳实践

1. 函数设计原则

  • 单一职责: 每个函数只做一件事
  • 清晰命名: 使用描述性的函数名
  • 详细描述: 提供清晰的函数和参数描述
  • 参数验证: 定义必需参数和可选参数

2. 错误处理

python
def safe_function_call(function_name, function_args):
    try:
        if function_name == "get_weather":
            return get_weather(**function_args)
        elif function_name == "calculate":
            return calculate(**function_args)
        else:
            return {"error": f"未知函数: {function_name}"}
    except Exception as e:
        return {"error": f"函数执行错误: {str(e)}"}

3. 性能优化

  • 缓存结果: 对于重复调用的函数,使用缓存
  • 异步执行: 对于耗时操作,考虑异步处理
  • 超时控制: 设置函数执行超时时间

4. 安全考虑

  • 输入验证: 验证函数参数的安全性
  • 权限控制: 限制函数的访问权限
  • 敏感信息: 避免在函数中暴露敏感信息

调试和测试

1. 函数调用日志

python
import logging

def log_function_call(function_name, args, result):
    logging.info(f"函数调用: {function_name}")
    logging.info(f"参数: {args}")
    logging.info(f"结果: {result}")

2. 单元测试

python
import unittest

class TestFunctions(unittest.TestCase):
    def test_get_weather(self):
        result = get_weather("北京")
        self.assertIn("temperature", result)
        self.assertIn("condition", result)
    
    def test_calculate(self):
        result = calculate("2 + 3")
        self.assertEqual(result, 5)

常见问题

Q: 函数调用失败怎么办?

A: 检查函数定义是否正确,参数类型是否匹配,函数实现是否有错误。

Q: 如何处理函数执行超时?

A: 在函数实现中添加超时控制,或者在应用层面设置超时机制。

Q: 可以调用多个函数吗?

A: 模型一次只能调用一个函数,但可以在后续对话中继续调用其他函数。

Q: 函数调用的性能如何?

A: 函数调用会增加一些延迟,建议优化函数执行效率和使用缓存。

相关资源


最后更新: 2025年1月27日

基于 DeepSeek AI 大模型技术