OpenAI 函数调用教程

news/2024/5/20 9:12:08 标签: chatgpt, openAI
推荐:使用 NSDT场景编辑器 快速搭建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”,我们得到了有关斯坦福大学的简短摘要。

示例#1

David Nguyen在斯坦福大学主修计算机科学。他的GPA为3.8,是该大学机器人俱乐部的活跃成员。

示例#2

亚伯拉罕·林肯是美国第16任总统。他从 1861 年 1865 月开始担任总统,直到 <> 年 <> 月被暗杀。林肯领导美国度过了最大的内部危机——美国内战,他的解放宣言宣布邦联领土上的奴隶是自由的。他以他的领导才能、他对维护联邦的承诺以及他废除奴隶制的努力而闻名。林肯的总统任期被广泛认为是美国历史上最具变革性的总统任期之一。

示例#3

斯坦福大学位于美国。该大学在世界排名#5,拥有17000名学生。

结论

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

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

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

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

原文链接:OpenAI 函数调用教程 (mvrlink.com)


http://www.niftyadmin.cn/n/5007444.html

相关文章

【Arduino26】88点阵显示液晶对比度实验

硬件准备 8*8点阵&#xff1a;1个 LCD1602显示屏&#xff1a;1 个 旋钮电位器&#xff1a;1个 220欧的电阻&#xff1a;1 个 面包板&#xff1a;1个 杜邦线&#xff1a;若干 硬件连线 按下图接好旋钮电位器 之后用杜邦线接好8*8点阵。 软件程序 #include <LiquidCry…

问道管理:底部渐渐抬高 今年反弹时刻或已来临

快速探底后&#xff0c;两市呈现分解走势。 沪指周三低开震动&#xff0c;指数在20日均线取得支撑后小幅上升&#xff0c;最终以红盘报收。深成指走势弱于沪指&#xff0c;尽管午后指数有所上升&#xff0c;但最终未能翻红。到收盘&#xff0c;沪指报收3158.08点&#xff0c;上…

07架构管理之架构评审方法

一句话导读 在软件开发领域&#xff0c;架构评审是确保项目成功的关键环节之一。它有助于团队在设计和实现阶段发现问题、降低风险&#xff0c;并确保系统能够达到预期的质量和性能标准。本文将深入探讨架构评审方法&#xff0c;介绍一些常用的评审技巧&#xff0c;以及如何在项…

SpringMVC常用注解介绍及参数传递说明

前言 上一篇文章介绍了SpringMVC是什么以及它的工作流程和核心组件&#xff0c;介绍入门示例时&#xff0c;提到了RequestMapping注解&#xff0c;那么这篇文章就来介绍SpringMVC中更多的常用的注解&#xff0c;以及它的参数传递。 一. SpringMVC常用注解 1.1 RequestParam …

js去除字符串空格的几种方式

方法1&#xff1a;(最常用)全部去除掉空格 var str abc d e f g ; function trim(str) { var reg /[\t\r\f\n\s]*/g; if (typeof str string) { var trimStr str.replace(reg,); } console.lo…

横版武侠手游推荐,有什么武侠游戏好玩的手游?

武侠游戏是游戏市场上不可或缺的游戏类型&#xff0c;许多武侠手游沿用了经典武侠小说中的各种设置&#xff0c;为玩家创造了一个身临其境的世界。有什么武侠游戏好玩的手游&#xff1f;今天小编就为大家带来了横版武侠手游推荐&#xff0c;这些游戏的游戏性和操作感是同类游戏…

HTTPS加密协议详解:TLS/SSL握手过程

1、握手与密钥协商过程 基于RSA握手和密钥交换的客户端验证服务器为示例详解TLS/SSL握手过程。 (1).client_hello 客户端发起请求&#xff0c;以明文传输请求信息&#xff0c;包含版本信息&#xff0c;加密套件候选列表&#xff0c;压缩算法候选列表&#xff0c;随机数&#…

如何在自动化测试中使用MitmProxy获取数据返回?

背景介绍 当我们在接口或UI自动化项目中&#xff0c;常常会出现这种现象——明明是正常请求&#xff0c;却无法获取到想要的数据返回。 比如&#xff1a; 场景A&#xff1a;页面是动态数据&#xff0c;第一次进入页面获取到的数据&#xff0c;和下次进入页面获取到的数据完全…