ChatGPT的大杀器!函数调用

OpenAI新推出了gpt-3.5-turbo-0613模型,模型引入了新的功能:函数调用。 函数调用的未来将是一个结合了AI、自然语言处理、外部服务和API等多个领域的综合体,这将大大提升AI助手的能力和实用性。 让我们来学习如何使用:

1.什么是函数调用?

函数调用是指当助手(这里的GPT模型)尝试调用在代码中定义的某个函数以获取特定的信息或执行特定的操作。

2.函数调用代码分析

这里以官方文档代码为例分析:

import openai
import json

# 这是一个示例的假函数,它固定返回相同的天气
# 在实际生产中,这可能是你的后端API或者一个外部API
def get_current_weather(location, unit="fahrenheit"):
    """获取指定地点的当前天气"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)


def run_conversation():
    # 步骤1:将对话和可用函数发送给GPT
    messages = [{"role": "user", "content": "What's the weather like in Boston?"}]
    functions = [
        {
            "name": "get_current_weather",
            "description": "获取指定地点的当前天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市和州,例如:San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        }
    ]
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=functions,
        function_call="auto",  # auto是默认值,但我们在这里明确指定
    )
    response_message = response["choices"][0]["message"]

    # 步骤2:检查GPT是否想要调用一个函数
    if response_message.get("function_call"):
        # 步骤3:调用函数
        # 注意:JSON响应可能并非总是有效的;要确保处理错误
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # 这个示例中只有一个函数,但你可以有多个
        function_name = response_message["function_call"]["name"]
        fuction_to_call = available_functions[function_name]
        function_args = json.loads(response_message["function_call"]["arguments"])
        function_response = fuction_to_call(
            location=function_args.get("location"),
            unit=function_args.get("unit"),
        )

        # 步骤4:将函数调用和函数响应的信息发送给GPT
        messages.append(response_message)  # 将助手的回复加入对话
        messages.append(
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            }
        )  # 将函数响应加入对话
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=messages,
        )  # 从GPT获取一个新的响应,这个响应可以看到函数的响应
        return second_response


print(run_conversation())

这里的流程是这样的:

1. 用户问一个问题,例如“波士顿现在的天气怎么样?”

2. 这个问题被发送给GPT模型,并告知其有一个可以调用的函数get_current_weather

3. GPT模型确定它需要调用这个函数来回答用户的问题,所以它返回一个“函数调用”的请求,指定要调用的函数名称和参数。

4. 代码中的运行会查找对应的函数(在这个例子中是get_current_weather),并用GPT模型指定的参数调用它。

5. 函数返回天气信息,这个信息被发送回GPT模型。

6. GPT模型使用这个天气信息来生成一个回答,例如“波士顿现在的天气是晴朗的,温度是72度”。

在这个流程中,"函数调用"是GPT模型尝试获取额外信息或执行操作以更好地回答问题的机制。

3.函数调用应用场景

相信大家在学习完上述代码后,已经能够想象到其在实际应用中的各种可能性和潜力。于提到的应用场景的具体例子:

        1.获取实时信息

用户问:"今天纳斯达克指数怎么样?" AI助手可以调用一个get_stock_price函数,如:

def get_stock_price(stock):
    # 这个函数将连接到股市API并返回给定股票的当前价格
    ...

        2.数据库查询

用户问:"我下个月有什么日程?" AI助手可以调用一个get_calendar_events函数,如:

codedef get_calendar_events(month):
    # 这个函数将查询数据库中的日历条目,并返回给定月份的所有事件
    ...

       3.执行操作

用户说:"请在明天下午3点设置一个提醒我买牛奶的闹钟。" AI助手可以调用一个set_reminder函数,如:

def set_reminder(reminder_text, time):
    # 这个函数将在给定的时间设置一个提醒
    ...

        4.与硬件设备交互

用户说:"把客厅的灯调暗一些。" AI助手可以调用一个adjust_lighting函数,如:

def adjust_lighting(room, level):
    # 这个函数将与智能家居设备通信,调整给定房间的灯光亮度
    ...

以上都是一些可能的应用场景,实际上你可以创建任何你需要的函数,然后让你的AI助手调用它们来执行复杂的任务。

猜你喜欢

转载自blog.csdn.net/qimablue/article/details/131289411