利用NodeJS中GPT-4功能调用的能力

ChatGPT中文站
Photo by ilgmyzin on Unsplash

人工智能领域不断发展,如GPT-4中的函数调用等令人兴奋的进展持续涌现。该功能实现了人工智能能力与外部工具之间的直接链接,为开发者带来了新的可能性。然而,尽管Python资源丰富,但NodeJS的资源仍然稀缺。

在本文中,我们旨在弥合这一差距。我们将提供一份简明指南,介绍如何在NodeJS环境中利用GPT-4的函数调用。无论你是经验丰富的NodeJS开发人员进军AI,还是AI爱好者探索NodeJS,本指南都将为你提供帮助。

我们将从简要介绍GPT-4函数调用开始,然后深入研究如何使用NodeJS实现它的详细教程。在我们开始之前,作为参考,您可能需要阅读OpenAI的有关函数调用和其他API更新的博客文章。让我们开始吧。

什么是函数调用?

函数调用是GPT-4中可用的强大功能,它允许开发人员描述函数给AI模型,使其能够智能地响应JSON对象,包含这些函数的参数。此功能增强了AI的能力和外部工具或API之间的连接,允许可靠地提取结构化数据,将自然语言转换为API调用或数据库查询,并创建能够与外部工具交互的聊天机器人。这是AI技术方面的重大突破,弥合了会话式AI和实际API应用之间的差距,使AI集成更加动态和多样化。

JSON 和制作食品。

在我们的使用案例中,我们将专注于使用函数调用来生成使用OpenAI的GPT模型的食谱。所提供的代码是一个例子,展示了我们如何通过JSON模式来定义一个函数,描述食谱的结构,包括配料和它们的数量,烹饪说明和总烹饪时间。该函数set_recipe然后在OpenAI API调用中调用。当我们要求GPT模型提供食谱(例如,一道烤牛排配土豆),它使用该定义的函数返回一个结构化的JSON对象。该对象包含食谱的所有必要组成部分,整齐地组织并准备好使用。这个函数调用功能使我们能够利用GPT模型的强大功能以一致和可靠的方式生成结构化数据。

const schema = {
"type": "object",
"properties": {
"ingredients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"unit": {
"type": "string",
"enum": ["grams", "ml", "cups", "pieces", "teaspoons"]
},
"amount": { "type": "number" }
},
"required": ["name", "unit", "amount"]
}
},
"instructions": {
"type": "array",
"description": "Steps to prepare the recipe (no numbering)",
"items": { "type": "string" }
},
"time_to_cook": {
"type": "number",
"description": "Total time to prepare the recipe in minutes"
}
},
"required": ["ingredients", "instructions", "time_to_cook"]
};

为了访问此功能调用功能,您需要使用OpenAI API,可以通过多种编程语言完成。在本示例中,我们将使用NodeJS。首先,您需要设置一个NodeJS项目,然后安装 openai 软件包,然后您可以使用API密钥设置OpenAI配置。通过此设置,您可以对OpenAI的模型(如gpt-3.5-turbo-0613或gpt-4-0613)进行API调用。

新手学习NodeJS?让我们来建立一个项目!

让我们分解一下使用函数调用OpenAI API设置项目的过程。如果你熟悉Node.js和npm,这是一个简单的过程,但让我们一步一步地进行,以便那些可能对这个环境还不熟悉的人也能够理解。

  1. 首先,为您的项目创建一个新目录。可以使用命令 mkdir -p function-calling-meat-and-potatoes 完成。-p 标志确保创建必要的父目录。
  2. 接下来,使用cd命令进入您新创建的目录,目录名为function-calling-meat-and-potatoes。
  3. 现在,是时候初始化你的 Node.js 项目了。这可以通过 npm init 命令完成。该命令将引导您创建项目的 package.json 文件。package.json 文件是管理项目依赖关系的重要组成部分。
  4. 最后,安装OpenAI软件包。该软件包包含与OpenAI API交互所需的必要工具和功能。可以使用命令npm install openai安装。

让我们开始编码吧

现在我们环境已经设置好了,是时候开始写代码了。

  1. 设置OpenAI配置:首先,让我们从openai包中导入Configuration和OpenAIApi,配置我们的OpenAI API密钥。
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
apiKey: 'YOUR_API_KEY',
});
const openai = new OpenAIApi(configuration);

用你实际的OpenAI API密钥替换“YOUR_API_KEY”。

  1. 定义JSON模式:然后我们定义描述我们想要接收的输出结构的JSON模式。
const schema = {
/* your schema here */
};
  • 参考上面创建的JSON模式
  1. 创建 API 请求:接下来,我们将使用 createChatCompletion 函数创建 API 请求。我们需要传入模型名称、初始信息、函数详细信息以及我们想要调用的函数。
(async () => {
try {
const completion = await openai.createChatCompletion({
model: "gpt-4-0613", // or another model that supports function calls
messages: [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Provide a recipe for medium rare steak with potatoes" }
],
functions: [{ "name": "set_recipe", "parameters": schema }],
function_call: { "name": "set_recipe" },
temperature: 0
});

console.log(completion.data.choices[0].message.function_call.arguments);
} catch (error) {
console.error('An error occurred:', error);
}
})();

在这种情况下,我们使用模型gpt-3.5-turbo-0613,并要求它提供一个煮至五分熟的牛肉和土豆的食谱。在底部,我们从API响应中提取数据并显示它。

console.log(completion.data.choices[0].message.function_call.arguments);

当您运行脚本时,将按我们模式定义的结构格式打印出食谱。

> node index.js
{
"ingredients": [
{
"name": "steak",
"unit": "grams",
"amount": 200
},
{
"name": "potatoes",
"unit": "grams",
"amount": 500
},
{
"name": "olive oil",
"unit": "ml",
"amount": 30
},
{
"name": "salt",
"unit": "teaspoons",
"amount": 1
},
{
"name": "black pepper",
"unit": "teaspoons",
"amount": 1
},
{
"name": "garlic powder",
"unit": "teaspoons",
"amount": 1
},
{
"name": "rosemary",
"unit": "teaspoons",
"amount": 1
}
],
"instructions": [
"Preheat the oven to 200°C (400°F).",
"Season the steak with salt, black pepper, and garlic powder on both sides.",
"Heat a skillet over high heat and add olive oil.",
"Sear the steak for 2-3 minutes on each side to get a nice crust.",
"Transfer the steak to a baking sheet and sprinkle rosemary on top.",
"Place the steak in the preheated oven and cook for about 10 minutes for medium rare.",
"While the steak is cooking, peel and cut the potatoes into small cubes.",
"Boil the potatoes in salted water until tender, then drain.",
"Heat a separate skillet over medium heat and add olive oil.",
"Add the cooked potatoes to the skillet and season with salt, black pepper, and garlic powder.",
"Cook the potatoes for about 5 minutes, stirring occasionally, until they are crispy and golden brown.",
"Serve the medium rare steak with the crispy potatoes."
],
"time_to_cook": 30
}

牛排、土豆与知识

而现在你成功地调用了OpenAI API,并获得了一个结构化的响应。这种方法打开了一整个新的可能性范围。例如:

  • 聊天机器人: 您可以开发聊天机器人,通过调用外部工具或API来回答问题。例如,聊天机器人可以将用户的问题“波士顿的天气如何?”转换为一个函数调用,例如 get_current_weather(location: string, unit: 'celsius' | 'fahrenheit')。
  • 自然语言处理(NLP):将自然语言转换为API调用或数据库查询。 想象一下问:“这个月我的前十个客户是谁?” 系统将把这个问题转换为内部API调用,例如按收入获取客户(start_date:string,end_date:string,limit:int)。
  • 数据提取:从文本中提取结构化数据。您可以定义一个名为 extract_people_data(people:[{name:string,birthday:string,location:string}])的函数,以提取在维基百科文章中提到的所有人员信息。

这只是冰山一角。GPT模型中的函数调用的多功能性可以根据您的具体需求以许多创新的方式利用。开发OpenAI是一个兴奋的时刻。开心编程!

2023-10-20 16:54:38 AI中文站翻译自原文