OpenAI的GPT函数调用。欢迎来到2023年1月!

弥补失去的时间

2023年6月13日,OpenAI宣布另一个“突破性”的特性,这次是关于“函数调用和其他API更新”,它带来了一些新功能、调整后的GPT模型、更低的使用价格以及更长的聊天GPT上下文。

正如你所注意到的,标题上写着欢迎来到2023年1月,如果你猜不到为什么,让我简单解释一下:

ChatGPT于2022年11月发布,自那时起社会上对AI的热烈讨论不断- LangChain是专为与语言模型配合使用而开发的框架,发布时间比ChatGPT稍早- LangChain具备许多功能、链、API可能性等- LangChain允许您使用GPT进行API调用和可用性- OpenAI在6月才发布了这个可能性,在此之前社区已经建立了更多更深入的功能- 这个版本实际上很好,只是对party的开始有点晚了。

在我看来,OpenAI真的在努力跟上社区和行业的步伐并弥补失去的时间,但这并不意味着什么不好。这家拥有500人的公司发布了一款软件,在仅仅两个月内就吸引了1亿用户,这是前所未有的里程碑,TikTok用了9个月才达到同样的数字。没有人能预见这一点,甚至连公司自己也无法预料。

以下是简体中文翻译: 正如预料的那样,由于这个令人难以置信的新工具引起了如此多的炒作和关注,显然会有很多人尝试成为这场新的“淘金热”的第一批人。正如我们所看到的,OpenAI在自己的竞赛中远远落后。他们需要近6个月的时间才发布一个应用程序,而且他们只发布了iPhone版本,缺少一些网络应用程序的功能...

不仅如此,他们创建了一个工具,在全球范围内被用于驱动许多其他工具,并且效果超出了预期,但从商业角度来看,发布此工具并具有目前发布的某些或更多功能将无限次更加有利可图。这是我认为我们永远不会看到像苹果或特斯拉这样的大公司所做的动作,他们的作业方式是发布一些东西并锁定用户,防止其在未经许可的情况下使用。

但这并不是什么坏事,它增加了OpenAI的知名度并且让他们获得了一定的资金。对于一个拥有500名员工的公司来说,他们真的感觉在追赶时间,甚至在周末也在努力超越行业(再一次...)。

要点摘要(简版):

  • gpt-3.5-turbo 和 gpt-4 更加快速和“可操控” - gpt-3.5-turbo 现在具有 16k (记号)的上下文对话,比以前的版本大四倍。
  • SOTA嵌入模型(如ada和davinci)成本降低了75%,文本嵌入ada-002现在每1k个标记仅需0.0001美元(基本免费)。
  • GPT-3.5高速使用,INPUT代币成本降低25%。
  • 新款的两个版本,在型号名称结尾加上“-0613”时,将允许这些模型与函数调用配合使用。
  • 以保持HTML结构,将以下英文文本翻译成简体中文: 之前的模型(gpt3.5-turbo-0301和gpt-4-0314)现已计划停用。

功能调用:

好的,函数调用。这可能是一个方便的更新,适用于那些对LLMs的当前发展状态不是非常了解的人。现在已经有一段时间了,我们可以使用应用了代理或框架提供的任何工具的GPT-4来执行基于自然语言输入(语音或文本)的操作。

这是个很大的进步。例如,使用LangChain提供的SQL工具和GPT-4模型,你只需编写(或说)“根据Y显示X的百分比”,模型就会自动分析表格,理解你所要求的,并以非常快的速度呈现给你,而且与执行同样任务的Python函数相比,速度更快。

但是好了,先忘记框架吧。现在GPT可以一步到位,你只需要在使用之前做些准备工作,但这很简单,我会向你展示如何做。也许这会帮助你构建你想要的东西呢?!

例子1—最简单的函数调用实现:

基本上,我们将实现一个函数,该函数返回特定位置的时间。没有网络!!!

首先,让我们准备好python笔记本以使其正常工作。我们将安装openai软件包并导入其他一些软件包。

!pip install openai

我们将设置“OPENAI_API_KEY”作为环境键在整个笔记本中使用,并导入JSON来处理响应。

import os
import json

os.environ["OPENAI_API_KEY"] = "YOUR KEY HERE"

现在,我将创建一个计算时间的函数。这个函数的酷炫之处在于我们不需要调用API或进行任何请求来获得正确的答案并返回数据。这向我们展示了我们可以使用GPT的力量实现许多不同的函数,甚至可以做更多!

我们导入Python的时区包来处理时区计算。

代码已经注释,这有助于理解其功能,但我在这里简要解释一下:

  1. 我们提供两个参数,一个是本地时间,你可能已经知道它是什么,另一个是位置,这是我们想要计算本地时间的位置。
  2. 然后,我们将本地时间(作为字符串来自GPT)解析为日期时间。
  3. 获取位置时区
  4. 进行一些令人难以置信的计算。
  5. 返回一个短语,告诉用户所在位置的时间是比用户时间快还是慢。
from datetime import datetime
import pytz

def calculate_time_difference(local_time, location):
local_time = datetime.strptime(local_time, '%Y-%m-%dT%H:%M:%S')

# Get current time in the provided location
location_time = datetime.now(pytz.timezone(location))

# Extract just the time part
local_time_only = local_time.time()
location_time_only = location_time.time()

# Calculate the difference in hours and minutes
time_difference_in_minutes = ((location_time_only.hour * 60 + location_time_only.minute) -
(local_time_only.hour * 60 + local_time_only.minute))

hours, minutes = divmod(abs(time_difference_in_minutes), 60)

# Determine if the location time is ahead or behind local time
if time_difference_in_minutes < 0:
time_difference_str = f'{hours} hours, {minutes} minutes behind local time'
else:
time_difference_str = f'{hours} hours, {minutes} minutes ahead of local time'

# Format the current time in the provided location
location_time_str = location_time.strftime('%H:%M:%S')

time_response={
"local_time": location_time_str,
"location_time": time_difference_str
}

return json.dumps(time_response)

并进行测试:

# Usage
local_time_str = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') # Get current local time
time_response_json = calculate_time_difference(local_time_str, 'US/Pacific') # Replace 'US/Pacific' with your desired location
time_response = json.loads(time_response_json)

print(f"Time at location: {time_response['local_time']}")
print(f"Time difference: {time_response['location_time']}")

回应是:

Time at location: 15:26:32 
Time difference: 7 hours, 0 minutes behind local time

在这里,我们将看到GPT与函数一起使用的巨大可用性!如果你注意到了这个函数的使用,你可能会注意到它需要以特定格式如“US/Pacific”的形式存在,否则,Python时区包将无法理解我们想要获取信息的时区。

现在看看与GPT的对话和用户发送的消息。此功能由OpenAI的文档提供,并进行了一些更改,以使其在我们的代码中正常运行:

import openai

local_time = datetime.now()

def conversation_with_time():
# Step 1: send the conversation and available functions to GPT
messages = [{"role": "user", "content": "What's the time right now in Boston?"}]
functions = [
{
"name": "calculate_time_difference", # updated the name of the function to be called
"description": "Calculates the time difference for a given location", # updated the description of the function to be called

"parameters": {
"type": "object",
"properties": { # updated the properties that need to be provided
"local_time": {
"type": "string",
"description": "Current local time of the user request"
},
"location": {
"type": "string",
"description": "The city, state or country, needs to be the timezone like US/Pacific",
},
},
"required": ["local_time","location"], # updated the required parameters
},
}
]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=messages,
functions=functions,
function_call="auto", # auto is default, but we'll be explicit
)
response_message = response["choices"][0]["message"]

# Step 2: check if GPT wanted to call a function
if response_message.get("function_call"):
# Step 3: call the function
# Note: the JSON response may not always be valid; be sure to handle errors
available_functions = {
"calculate_time_difference": calculate_time_difference,
} # only one function in this example, but you can have multiple
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( # updated this method
local_time=function_args.get("local_time"),
location=function_args.get("location")
)

# Step 4: send the info on the function call and function response to GPT
messages.append(response_message) # extend conversation with assistant's reply
messages.append(
{
"role": "function",
"name": function_name,
"content": function_response,
}
) # extend conversation with function response
second_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=messages,
) # get a new response from GPT where it can see the function response
return second_response


print(conversation_with_time())

这次对话的回应是:

"message": { 
"role": "assistant",
"content": "The current time in Boston is 6:09 PM."
},

你看到了吗?你看到了吗? “位置”参数内部的功能描述说:“城市,州或国家需要是类似于美国/太平洋的时区”,而用户刚刚说了“波士顿”。GPT 知道波士顿的时区,并自动推断出函数正常运行所需的信息,根据用户请求的时区返回我们正确的时间。所有这些都不需要互联网连接、API 或相关的东西,只需要一个简单的函数和 GPT 对自然语言的解释。

现在想象一下,你可以使用简单的函数构建多少种不同的实现,以及你可以为像GPT-4这样强大的模型提供多少进一步的可用性。

例子n2-高级函数调用:

在这个例子中,我会做几乎相同的事情,但是这一次,我们将使用真正的API调用来返回数据!

首先,让我们安装pyowm软件包,它允许我们使用OpenWeatherMap API。

注:您需要获取一个OpenWeatherMap API密钥。这很简单,只需前往他们的网站这里并创建一个帐户。一旦您收到他们的电子邮件,请确认您的帐户,并等待几分钟,直到您的API密钥被激活。(我不明白为什么这不是瞬间的,但好吧......)

再次强调,代码中全部添加了注释,以便逐步更好地理解,简单概括地说:

  1. 导入pyowm并提供API密钥,获取您自己的密钥。
  2. 创建了一个观测点,接收我们的city_name参数并获取实时信息。
  3. 定义所需返回的信息以JSON格式返回
from pyowm import OWM

def get_live_weather(city_name):
# Initialize the OWM with your API key
owm = OWM('your-api-key') # replace 'your-api-key' with your actual API key

# Create a weather manager
manager = owm.weather_manager()

# Get the weather in the specified city
observation = manager.weather_at_place(city_name)
weather = observation.weather

# Extract the temperature, humidity, and status
temperature = weather.temperature('celsius')["temp"]
humidity = weather.humidity
status = weather.status

weather_data={
"temperature": temperature,
"humidity": humidity,
"status": status
}

return json.dumps(weather_data)

以 HTML 结构为基础,将以下英文翻译成简体中文: "And the response:" "而且回复: "

In London,GB, the temperature is 18.4°C, the humidity is 82%, and the weather status is Clouds.

以下代码片段是OpenAI文档提供的对话功能;我们只需要更新一些值即可按我们想要的方式运行它:

def conversation_with_weather():
# Step 1: send the conversation and available functions to GPT
messages = [{"role": "user", "content": "What's the weather like in Porto Alegre tomorrow?"}] # updated the message the get data about this marvelous city
functions = [
{
"name": "get_live_weather", # updated the name of the function to be called
"description": "Calls the OpenWeather API to get live data about the weather from a given location", # updated the description of the function
"parameters": {
"type": "object",
"properties": { # updated the properties that need to be provided
"city_name": {
"type": "string",
"description": "The city provided, needs to be updated to work like Boston,MA",
},
},
"required": ["city_name"], # updated the required information to work with the function
},
}
]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=messages,
functions=functions,
function_call="auto", # auto is default, but we'll be explicit
)
response_message = response["choices"][0]["message"]

# Step 2: check if GPT wanted to call a function
if response_message.get("function_call"):
# Step 3: call the function
# Note: the JSON response may not always be valid; be sure to handle errors
available_functions = {
"get_live_weather": get_live_weather,
} # only one function in this example, but you can have multiple
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(
city_name=function_args.get("city_name")
)

# Step 4: send the info on the function call and function response to GPT
messages.append(response_message) # extend conversation with assistant's reply
messages.append(
{
"role": "function",
"name": function_name,
"content": function_response,
}
) # extend conversation with function response
second_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=messages,
) # get a new response from GPT where it can see the function response
return second_response


print(conversation_with_weather())

再次进行一些快速简单的调整,结合 GPT 的推理能力,用户只需询问“明天...波尔图阿莱格里的天气”,它就可以轻松处理,并提供正确的 API 格式,等待响应,并为用户提供自然语言的回答。

"message": { 
"role": "assistant",
"content": "The weather in Porto Alegre today is clear with a temperature of 16.17 C and a humidity of 82%." }

如此简单,我们现在已经拥有了解锁这种高质量LLM的真正力量所需的缺失部分。这并不是什么新鲜事,而是能够轻松地执行动作并自然地表达某些东西,而模型能够理解并在需要时进行转化处理,这非常棒。不需要理解框架来创建某些东西让我心安。

这使得公司可以在自身内部或外部工具中更深入地使用GPT,提供了一个快速实现的好选择,只需几分钟而不是几小时或几天!

我希望这对你有用,现在,去创造一些很棒的东西吧!

请查看在Google Colab上运行的Python笔记本。

ChatGPT中文站
Image: Unsplash
ChatGPT中文站
Guilherme Zago

2023-10-20 17:04:25 AI中文站翻译自原文