Function Calling 使得 AI 模型能够与外部工具和 API 进行交互,执行特定操作并获取实时信息。这一功能扩展了 AI 模型的能力,不仅仅是简单的文本生成,支持更具动态性和实用性的应用场景。

支持的模型

以下模型支持 Function Calling:

  • deepseek/deepseek-v3
  • deepseek/deepseek-r1-turbo
  • deepseek/deepseek-v3-turbo
  • qwen/qwq-32b

快速开始

本指南演示了如何使用 Function Calling 调用指定位置的当前天气信息。我们将通过一个完整的 Python 代码示例进行演示。

对于 Function Calling 的具体 API 格式,请参考 API 文档 创建聊天对话请求

1. 初始化客户端

首先,您需要使用您的派欧算力云 API 密钥初始化客户端。

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.ppinfra.com/v3/openai",
    # 从 https://ppinfra.com/settings/key-management 获取您的派欧算力云 API 密钥。
    api_key="<您的派欧算力云 API 密钥>",
)

model = "deepseek/deepseek-v3"

2. 定义要调用的函数

接下来,定义模型可以调用的 Python 函数。在这个例子中,演示获取天气信息的功能。

# 示例函数,用于模拟获取天气数据。
def get_weather(location):
    """获取指定地点的当前天气"""
    print("调用 get_weather 函数,位置: ", location)
    # 在实际应用中,您需要在这里调用外部天气 API。
    # 这是一个简化示例,返回硬编码数据。
    return json.dumps({"位置": location, "温度": "20 摄氏度"})

3. 构造包含工具和用户消息的 API 请求

创建派欧算力云 API 的调用请求。此请求包括 tools 参数,定义模型可以使用的函数,以及用户的消息。

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取一个地点的天气,用户需要首先提供地点",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市信息, 例如:上海",
                    }
                },
                "required": ["location"]
            },
        }
    },
]

messages = [
    {
        "role": "user",
        "content": "上海的天气怎么样?"
    }
]

# 发送请求并打印响应
response = client.chat.completions.create(
    model=model,
    messages=messages,
    tools=tools,
)

# 请在生产环境中检查响应是否包含工具调用
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())

输出:

{'id': '0', 'function': {'arguments': '{"location": "上海"}', 'name': 'get_weather'}, 'type': 'function'}

4. 根据函数调用结果进行响应并获取最终答案

接下来处理函数调用,执行 get_weather 函数,并将结果发送回模型以生成最终响应给用户。

# 确保工具调用已从上一步定义
if tool_call:
    # 扩展对话历史记录,添加助手工具调用消息
    messages.append(response.choices[0].message)

    function_name = tool_call.function.name
    if function_name == "get_weather":
        function_args = json.loads(tool_call.function.arguments)
        # 执行函数并获取响应
        function_response = get_weather(
            location=function_args.get("location"))
        # 将函数响应添加到消息中
        messages.append(
            {
                "tool_call_id": tool_call.id,
                "role": "tool",
                "content": function_response,
            }
        )

    # 从模型获取最终响应,包含函数结果
    answer_response = client.chat.completions.create(
        model=model,
        messages=messages,
        # 注意:不要在此处包含 tools 参数
    )
    print(answer_response.choices[0].message)

输出:

ChatCompletionMessage(content="上海目前的温度是 20 摄氏度。请注意,天气情况可能会随时变化,建议您查看最新的天气预报以获取更准确的信息。", refusal=None, role='assistant', function_call=None, tool_calls=None)

完整代码

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.ppinfra.com/v3/openai",
    # 从 https://ppinfra.com/settings/key-management 获取您的派欧算力云 API 密钥。
    api_key="<您的派欧算力云 API 密钥>",
)

model = "deepseek/deepseek-v3"

# 示例函数,用于模拟获取天气数据。
def get_weather(location):
    """获取指定地点的当前天气"""
    print("调用 get_weather 函数,位置: ", location)
    # 在实际应用中,您需要在这里调用外部天气 API。
    # 这是一个简化示例,返回硬编码数据。
    return json.dumps({"位置": location, "温度": "20 摄氏度"})

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取一个地点的天气,用户需要首先提供地点",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市信息, 例如:上海",
                    }
                },
                "required": ["location"]
            },
        }
    },
]

messages = [
    {
        "role": "user",
        "content": "上海的天气怎么样?"
    }
]

# 发送请求并打印响应
response = client.chat.completions.create(
    model=model,
    messages=messages,
    tools=tools,
)

# 请在生产环境中检查响应是否包含工具调用
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())

# 确保工具调用已从上一步定义
if tool_call:
    # 扩展对话历史记录,添加助手工具调用消息
    messages.append(response.choices[0].message)

    function_name = tool_call.function.name
    if function_name == "get_weather":
        function_args = json.loads(tool_call.function.arguments)
        # 执行函数并获取响应
        function_response = get_weather(
            location=function_args.get("location"))
        # 将函数响应添加到消息中
        messages.append(
            {
                "tool_call_id": tool_call.id,
                "role": "tool",
                "content": function_response,
            }
        )

    # 从模型获取最终响应,包含函数结果
    answer_response = client.chat.completions.create(
        model=model,
        messages=messages,
        # 注意:不要在此处包含 tools 参数
    )
    print(answer_response.choices[0].message)