Function Calling 介绍与实战

633 阅读4分钟

function calling功能在gpt3.5以上使用

functions 是 Chat Completion API 中的可选参数,用于提供函数定义。其目的是使 GPT 模型能够生成符合所提供定义的函数参数。请注意,API不会实际执行任何函数调用。开发人员需要使用GPT 模型输出来执行函数调用。

如果提供了functions参数,默认情况下,GPT 模型将决定在何时适当地使用其中一个函数。

可以通过将function_call参数设置为{"name": "<insert-function-name>"}来强制 API 使用指定函数。

同时,也支持通过将function_call参数设置为"none"来强制API不使用任何函数。

如果使用了某个函数,则响应中的输出将包含"finish_reason": "function_call",以及一个具有该函数名称和生成的函数参数的function_call对象。

functions 参数使用方法

安装依赖

pip install scipy tenacity tiktoken termcolor openai requests
import json
import requests
import os
from tenacity import retry, wait_random_exponential, stop_after_attempt
from termcolor import colored

GPT_MODEL = "gpt-3.5-turbo"

定义工具函数

# 第一个字典定义了一个名为"get_current_weather"的功能
functions = [
    {
        "name": "get_current_weather",  # 功能的名称
        "description": "Get the current weather",  # 功能的描述
        "parameters": {  # 定义该功能需要的参数
            "type": "object",
            "properties": {  # 参数的属性
                "location": {  # 地点参数
                    "type": "string",  # 参数类型为字符串
                    "description": "The city and state, e.g. San Francisco, CA",  # 参数的描述
                },
                "format": {  # 温度单位参数
                    "type": "string",  # 参数类型为字符串
                    "enum": ["celsius", "fahrenheit"],  # 参数的取值范围
                    "description": "The temperature unit to use. Infer this from the users location.",  # 参数的描述
                },
            },
            "required": ["location", "format"],  # 该功能需要的必要参数
        },
    },
    # 第二个字典定义了一个名为"get_n_day_weather_forecast"的功能
    {
        "name": "get_n_day_weather_forecast",  # 功能的名称
        "description": "Get an N-day weather forecast",  # 功能的描述
        "parameters": {  # 定义该功能需要的参数
            "type": "object",
            "properties": {  # 参数的属性
                "location": {  # 地点参数
                    "type": "string",  # 参数类型为字符串
                    "description": "The city and state, e.g. San Francisco, CA",  # 参数的描述
                },
                "format": {  # 温度单位参数
                    "type": "string",  # 参数类型为字符串
                    "enum": ["celsius", "fahrenheit"],  # 参数的取值范围
                    "description": "The temperature unit to use. Infer this from the users location.",  # 参数的描述
                },
                "num_days": {  # 预测天数参数
                    "type": "integer",  # 参数类型为整数
                    "description": "The number of days to forecast",  # 参数的描述
                }
            },
            "required": ["location", "format", "num_days"]  # 该功能需要的必要参数
        },
    },
]

定义函数chat_completion_request

# 定义一个函数chat_completion_request,主要用于发送 聊天补全 请求到OpenAI服务器

def chat_completion_request(messages, functions=None, function_call=None, model=GPT_MODEL):

    # 设定请求的header信息,包括 API_KEY
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + os.getenv("OPENAI_API_KEY"),
    }

    # 设定请求的JSON数据,包括GPT 模型名和要进行补全的消息
    json_data = {"model": model, "messages": messages}

    # 如果传入了functions,将其加入到json_data中
    if functions is not None:
        json_data.update({"functions": functions})

    # 如果传入了function_call,将其加入到json_data中
    if function_call is not None:
        json_data.update({"function_call": function_call})

    # 尝试发送POST请求到OpenAI服务器的chat/completions接口
    try:
        response = requests.post(
            "https://api.openai.com/v1/chat/completions",
            headers=headers,
            json=json_data,
        )
        # 返回服务器的响应
        return response

    # 如果发送请求或处理响应时出现异常,打印异常信息并返回
    except Exception as e:
        print("Unable to generate ChatCompletion response")
        print(f"Exception: {e}")
        return e

执行调用

# 定义一个空列表messages,用于存储聊天的内容
messages = []

# 使用append方法向messages列表添加一条系统角色的消息
messages.append({
    "role": "system",  # 消息的角色是"system"
    "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."  # 消息的内容
})

# 向messages列表添加一条用户角色的消息
messages.append({
    "role": "user",  # 消息的角色是"user"
    "content": "What's the weather like today"  # 用户询问今天的天气情况
})

# 使用定义的chat_completion_request函数发起一个请求,传入messages和functions作为参数
chat_response = chat_completion_request(
    messages, functions=functions
)

# 解析返回的JSON数据,获取助手的回复消息
assistant_message = chat_response.json()["choices"][0]["message"]

# 将助手的回复消息添加到messages列表中
messages.append(assistant_message)

pretty_print_conversation(messages)

这段代码首先定义了一个messages列表用来存储聊天的消息,然后向列表中添加了系统和用户的消息。

然后,它使用了之前定义的chat_completion_request函数发送一个请求,传入的参数包括消息列表和函数列表。

在接收到响应后,它从JSON响应中解析出助手的消息,并将其添加到消息列表中

如何使用 functions 参数

这段代码定义了两个可以在程序中调用的函数,分别是获取当前天气和获取未来N天的天气预报。

每个函数(function)都有其名称、描述和需要的参数(包括参数的类型、描述等信息)。

image.png

总结

调用 api.openai.com/v1/chat/com… 时 传递functions参数时

completion 模型返回的结果中会通过function_call参数 提示你调用哪个函数

流程

  • 定义好function函数
  • 调用大模型 大模型返回结果 告诉你调用哪个函数 包括具体的参数值
  • 调用函数 获取结果
  • 将结果查询的结果放到message队列中 重新传给大模型