OpenAI 函数调用教程

了解 OpenAI 的新函数调用功能如何使 GPT 模型生成结构化 JSON 输出,从而解决由不规则输出引起的常见开发问题。

OpenAI 函数调用教程
在线工具推荐:三维数字孪生场景工具 - GLTF/GLB在线编辑器 - Three.js AI自动纹理化开发 - YOLO 虚幻合成数据生成器 - 3D模型在线转换 -  3D模型预览图生成服务

什么是OpenAI函数调用?

OpenAI API 非常擅长以系统的方式生成响应。只需几行代码即可管理提示、优化模型输出以及执行、生成和语言应用程序。

即使有这么多好东西,OpenAI API对开发人员和工程师来说也是一场噩梦。为什么?他们习惯于使用结构化数据类型,并且很难处理字符串等非结构化数据。

为了获得一致的结果,开发人员必须使用正则表达式 (RegEx) 或提示工程从文本字符串中提取信息。

这就是OpenAI的函数调用功能的用武之地。它允许 GPT-3.5 和 GPT-4 模型将用户定义的函数作为输入并生成结构输出。这样,您无需编写正则表达式或执行提示工程。

在本教程中,我们将探讨 OpenAI 函数调用如何帮助解决由不规则模型输出引起的常见开发人员问题。

如果您刚刚开始使用 ChatGPT 和 OpenAI API,请考虑查看 OpenAI API 和 ChatGPT 入门网络研讨会。此资源可以指导您完成语言和编码生成,并帮助您使用 Python API 执行基本任务。

使用OpenAI而无需调用函数

在本节中,我们将使用 GPT-3.5-Turbo 模型生成响应,而无需调用函数,以查看我们是否获得一致的输出。

在安装 OpenAI Python API 之前,您必须获取 API 密钥并在本地系统上进行设置。通过 Python 中的 OpenAI API 教程关注 GPT-3.5 和 GPT-4,了解如何获取 API 密钥并进行设置。本教程还包括在数据营工作区中设置环境变量的示例。

如需进一步帮助,请查看 OpenAI 函数调用工作区中的带有输出的笔记本。

我们将随机编写学生描述。您可以想出自己的文本,也可以使用 ChatGPT 为您生成一个。

student_1_description = "David Nguyen is a sophomore majoring in computer science at Stanford University. He is Asian American and has a 3.8 GPA. David is known for his programming skills and is an active member of the university's Robotics Club. He hopes to pursue a career in artificial intelligence after graduating."

在下一部分中,我们将编写一个提示,以从文本中提取学生信息,并将输出作为 JSON 对象返回。我们将在学生描述中提取姓名、专业、学校、年级和俱乐部。

# A simple prompt to extract information from "student_description" in a JSON format.prompt1 = f''' Please extract the following information from the given text and return it as a JSON object: name major school grades club This is the body of text to extract the information from: {student_1_description}'''

将提示添加到 OpenAI API 聊天完成模块以生成响应。

import openai # Generating response back from gpt-3.5-turboopenai_response = openai.ChatCompletion.create(    model = 'gpt-3.5-turbo',    messages = [{'role': 'user', 'content': prompt1}])openai_response['choices'][0]['message']['content']

反响相当不错。让我们将其转换为 JSON 以更好地理解它。

'{\n  "name": "David Nguyen",\n  "major": "computer science",\n  "school": "Stanford University",\n  "grades": "3.8 GPA",\n  "club": "Robotics Club"\n}'

我们将使用该库将文本转换为 JSON 对象。json

import json # Loading the response as a JSON objectjson_response = json.loads(openai_response['choices'][0]['message']['content'])json_response

最终的结果几乎是完美的。那么,为什么我们需要函数调用?

{'name': 'David Nguyen', 'major': 'computer science', 'school': 'Stanford University', 'grades': '3.8 GPA', 'club': 'Robotics Club'}

让我们尝试相同的提示,但使用不同的学生描述。

student_2_description="Ravi Patel is a sophomore majoring in computer science at the University of Michigan. He is South Asian Indian American and has a 3.7 GPA. Ravi is an active member of the university's Chess Club and the South Asian Student Association. He hopes to pursue a career in software engineering after graduating."

我们只会在提示中更改学生描述文本。

prompt2 = f''' Please extract the following information from the given text and return it as a JSON object: name major school grades club This is the body of text to extract the information from: {student_2_description}'''

并使用第二个提示符运行聊天完成功能。

openai_response = openai.ChatCompletion.create(    model = 'gpt-3.5-turbo',    messages = [{'role': 'user', 'content': prompt2 }]) # Loading the response as a JSON objectjson_response = json.loads(openai_response['choices'][0]['message']['content'])json_response

如您所见,它并不一致。

  • 第一个学生的成绩是“3.8 GPA”,而在第二个学生提示中,我们只得到数字“3.7”。当您构建稳定的系统时,这是一件大事。
  • 它没有返回一个俱乐部,而是返回了拉维加入的俱乐部名单。它也与第一个学生不同。

{'name': 'Ravi Patel', 'major': 'computer science', 'school': 'University of Michigan', 'grades': '3.7', 'club': ['Chess Club', 'South Asian Student Association']}

开放人工智能函数调用示例

为了解决此问题,我们现在将使用最近引入的称为函数调用的功能。必须创建自定义函数以将必要的信息添加到字典列表中,以便 OpenAI API 可以理解其功能。

  • name:写下您最近创建的 Python 函数名称。
  • 说明:函数的功能。
  • 参数:在“属性”中,我们将写入参数的名称、类型和描述。它将帮助OpenAI API识别我们正在寻找的世界。

注意:请确保您遵循正确的模式。通过阅读官方文档了解有关函数调用的更多信息。

student_custom_functions = [
{
'name': 'extract_student_info',
'description': 'Get the student information from the body of the input text',
'parameters': {
'type': 'object',
'properties': {
'name': {
'type': 'string',
'description': 'Name of the person'
},
'major': {
'type': 'string',
'description': 'Major subject.'
},
'school': {
'type': 'string',
'description': 'The university name.'
},
'grades': {
'type': 'integer',
'description': 'GPA of the student.'
},
'club': {
'type': 'string',
'description': 'School club for extracurricular activities. '
}

        }
    }
}

]

接下来,我们将使用添加到“functions”参数中的自定义函数为两个学生描述生成响应。之后,我们将文本响应转换为 JSON 对象并打印出来。

student_description = [student_1_description,student_2_description]
for sample in student_description:
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': sample}],
functions = student_custom_functions,
function_call = 'auto'
)

# Loading the response as a JSON object
json_response = json.loads(response['choices'][0]['message']['function_call']['arguments'])
print(json_response)

如我们所见,我们得到了统一的输出。我们甚至得到了数字而不是字符串的成绩。一致的输出对于创建无错误的 AI 应用程序至关重要。

{'name': 'David Nguyen', 'major': 'computer science', 'school': 'Stanford University', 'grades': 3.8, 'club': 'Robotics Club'}

{'name': 'Ravi Patel', 'major': 'computer science', 'school': 'University of Michigan', 'grades': 3.7, 'club': 'Chess Club'}

多个自定义函数

您可以在聊天完成功能中添加多个自定义函数。在本节中,我们将看到OpenAI API的神奇功能,以及它如何自动选择正确的函数并返回正确的参数。

在字典的 Python 列表中,我们将添加另一个名为“extract_school_info”的函数,它将帮助我们从文本中提取大学信息。

为此,您必须添加另一个带有名称、描述和参数的函数字典。

custom_functions = [
{
'name': 'extract_student_info',
'description': 'Get the student information from the body of the input text',
'parameters': {
'type': 'object',
'properties': {
'name': {
'type': 'string',
'description': 'Name of the person'
},
'major': {
'type': 'string',
'description': 'Major subject.'
},
'school': {
'type': 'string',
'description': 'The university name.'
},
'grades': {
'type': 'integer',
'description': 'GPA of the student.'
},
'club': {
'type': 'string',
'description': 'School club for extracurricular activities. '
}

        }
    }
},
{
    'name': 'extract_school_info',
    'description': 'Get the school information from the body of the input text',
    'parameters': {
        'type': 'object',
        'properties': {
            'name': {
                'type': 'string',
                'description': 'Name of the school.'
            },
            'ranking': {
                'type': 'integer',
                'description': 'QS world ranking of the school.'
            },
            'country': {
                'type': 'string',
                'description': 'Country of the school.'
            },
            'no_of_students': {
                'type': 'integer',
                'description': 'Number of students enrolled in the school.'
            }
        }
    }
}

]

我们将使用 ChatGPT 生成“斯坦福大学”描述来测试我们的函数。

school_1_description = "Stanford University is a private research university located in Stanford, California, United States. It was founded in 1885 by Leland Stanford and his wife, Jane Stanford, in memory of their only child, Leland Stanford Jr. The university is ranked #5 in the world by QS World University Rankings. It has over 17,000 students, including about 7,600 undergraduates and 9,500 graduates23. "

创建学生和学校描述列表,并通过 OpenAI 聊天完成功能传递它以生成响应。确保您已提供更新的自定义函数。

description = [student_1_description, school_1_description]
for i in description:
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': i}],
functions = custom_functions,
function_call = 'auto'
)

# Loading the response as a JSON object
json_response = json.loads(response['choices'][0]['message']['function_call']['arguments'])
print(json_response)

GPT-3.5-Turbo 型号已自动为不同的描述类型选择了正确的功能。我们为学生和学校提供完美的JSON输出。

{'name': 'David Nguyen', 'major': 'computer science', 'school': 'Stanford University', 'grades': 3.8, 'club': 'Robotics Club'}

{'name': 'Stanford University', 'ranking': 5, 'country': 'United States', 'no_of_students': 17000}

我们甚至可以查看使用“extract_school_info”函数生成休息的名称。

图像3.png

使用函数调用的应用程序

在本节中,我们将构建一个稳定的文本摘要器,该摘要器将以某种方式汇总学校和学生信息。

首先,我们将创建两个 Python 函数,它们从函数调用中获取参数并返回一个汇总的字符串。extract_student_infoextract_school_info,

def extract_student_info(name, major, school, grades, club):

"""Get the student information"""

return f"{name} is majoring in {major} at {school}. He has {grades} GPA and he is an active member of the university's {club}."

def extract_school_info(name, ranking, country, no_of_students):

"""Get the school information"""

return f"{name} is located in the {country}. The university is ranked #{ranking} in the world with {no_of_students} students."
  1. 创建 Python 列表,该列表由学生一描述、随机提示和学校一描述组成。添加随机提示以验证自动函数调用机制。
  2. 我们将使用“描述”列表中的每个文本生成响应。
  3. 如果使用函数调用,我们将获取函数的名称,并基于它,使用响应将相关参数应用于函数。否则,返回正常响应。
  4. 打印所有三个样本的输出。

descriptions = [
student_1_description,
"Who was a Abraham Lincoln?",
school_1_description
]
for i, sample in enumerate(descriptions):
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': sample}],
functions = custom_functions,
function_call = 'auto'
)

response_message = response["choices"][0]["message"]

if response_message.get('function_call'):
    
    # Which function call was invoked
    function_called = response_message['function_call']['name']
    
    # Extracting the arguments
    function_args  = json.loads(response_message['function_call']['arguments'])
    
    # Function names
    available_functions = {
        "extract_school_info": extract_school_info,
        "extract_student_info": extract_student_info
    }
    
    fuction_to_call = available_functions[function_called]
    response_message = fuction_to_call(*list(function_args .values()))
    
else:
    response_message = response_message['content']

print(f"\nSample#{i+1}\n")
print(response_message)
  • 示例 #1:GPT 模型选择了“extract_student_info”,我们得到了有关该学生的简短摘要。
  • 示例#2:GPT 模型没有选择任何函数并将提示视为常规问题,结果,我们得到了亚伯拉罕·林肯的传记。
  • 示例#3:GPT 模型选择了“extract_school_info”,我们得到了有关斯坦福大学的简短摘要。

Sample#1

David Nguyen is majoring in computer science at Stanford University. He has 3.8 GPA and he is an active member of the university's Robotics Club.

Sample#2

Abraham Lincoln was the 16th President of the United States. He served as president from March 1861 until his assassination in April 1865. Lincoln led the country through its greatest internal crisis, the American Civil War, and his Emancipation Proclamation declared slaves in Confederate territory to be free. He is known for his leadership, his commitment to preserving the Union, and his efforts to abolish slavery. Lincoln's presidency is widely regarded as one of the most transformative in American history.

Sample#3

Stanford University is located in the United States. The university is ranked #5 in the world with 17000 students.

结论

OpenAI 的函数调用为构建 AI 应用程序的开发人员开辟了令人兴奋的新可能性。通过允许 GPT-3.5 和 GPT-4 等模型通过自定义函数生成结构化 JSON 数据,它解决了围绕不一致和不可预测的文本输出的主要痛点。

函数调用可用于访问外部 Web API、执行自定义 SQL 查询以及开发稳定的 AI 应用程序。它可以从文本中提取相关信息,并为 API 和 SQL 命令提供一致的响应。

在本教程中,我们了解了 OpenAI 的新功能,函数调用。我们还学习了如何使用它来生成一致的输出、创建多个函数以及构建可靠的文本摘要器。

如果您想了解有关 OpenAI API 的更多信息,请考虑参加使用 OpenAI API 课程并使用 Python 中的 OpenAI API 备忘单来创建您的第一个 AI 驱动的项目。

3D建模学习工作室 整理翻译,转载请注明出处!

NSDT场景编辑器 | NSDT 数字孪生 | GLTF在线编辑器 | 3D模型在线转换 | UnrealSynth虚幻合成数据生成器 | 3D模型自动纹理化工具
2023 power by nsdt©鄂ICP备2023000829号