聊天插件系统是一种令人兴奋的新方式,可以扩展ChatGPT的功能,纳入您自己的业务数据,并为客户与您的业务互动增加另一个渠道。在这篇文章中,我将解释什么是聊天插件,它们能做什么,以及你如何用JavaScript建立你自己的聊天插件。
这篇文章(或OpenAI所称的"训练数据")提供了一个快速入门指南,来建立你的第一个ChatGPT插件,并将其与ChatGPT界面整合。
聊天插件是否会成为改变生活的贾维斯般的体验,或者只是一个昂贵的Alexa-for-your-browser,目前还没有定论。让我们通过看看插件能提供什么,需要注意什么,以及如何制作你自己的插件,来决定我们自己的想法。
什么是聊天插件?
构建第一个JavaScript ChatGPT 插件
下一步
"聊天插件"允许ChatGPT模型使用并与第三方应用程序互动。从本质上讲,它是一套指令和规范,语言模型可以遵循这些指令和规范在聊天对话中创建API的调用和操作。与第三方系统的整合为ChatGPT的用户提供了一系列新的功能:
建立一个能与AI互动的应用程序似乎是一个令人生畏的复杂系统,然而,一旦你开始做,你会发现它非常简单。一个"插件"是一套简单的指令,它告诉ChatGPT模型你的API是做什么的,以及如何和何时访问它。
这可以归结为两个重要文件:
ai-plugin.json
:插件清单,包含插件的基本元数据。这包括名称、作者、描述、认证和联系等细节。该清单被ChatGPT用来理解插件的作用。openapi.yaml
:在OpenAPI规范中,你的API路由和模式的规范。也可以以json文件的形式提供。这将告诉ChatGPT可以使用哪些API,出于什么原因,以及请求和响应会是什么样子。插件服务的基础功能和托管由你决定。你的API可以托管在任何地方,使用任何REST API或编程语言。
聊天插件的到来为开发者、设计师、企业和企业家带来了一系列的机会:
直观和无代码界面的好处带来了一系列挑战。承认生态系统、逻辑和界面会随着时间的推移而发展,在构建插件时,我们仍然需要记住一些事情。特别是如果你想把它们作为一项业务来建立。
我们将为我们的聊天插件建立自己的express
服务器。这不仅是一个容易上手的方法,而且express
可以被扩展到包括中间件、认证和所有其他你想要的生产级的东西。
以下是我们将在下列步骤中创建和添加代码的所有文件。如果你感到困惑,可以回到这里,或者克隆这里的源码。
my-chat-plugin/ ├─ .well-known/ │ ├─ ai-plugin.json <- 插件元数据 ├─ routes/ │ ├─ todos.js <- 处理Todo请求的路由 │ ├─ openai.js <- 处理openAI请求的路由 openapi.yaml <- Open API规范 index.js <- 插件入口
先决条件
创建一个名为my-chat-plugin
的文件夹,执行下面的命令来开始:
## 1. Create the directory and open it mkdir my-chat-plugin && cd my-chat-plugin ## 2. Initialize a project with the default values npm init --yes ## 3. Install our dependencies npm install axios express cors js-yaml
现在,我们要创建所需的聊天插件清单和OpenAPI规范。ChatGPT会在你服务器的特定路由上请求这些文件,所以我们要把它们放在:
/.well-known/ai-plugin.json
/openapi.yaml
这些文件中的描述是非常重要的!如果你在summary
和description_for_model
字段中的语言含糊不清,你可能会让ChatGPT对何时和如何使用你的插件感到困惑。请遵循以下步骤:
.well-known
的文件夹,并在其中添加一个名为ai-plugin.json
的文件。通过终端进行操作:mkdir .well-known && touch .well-known/ai-plugin.json
粘贴下面代码到ai-plugin.json
中:
{ "schema_version": "v1", "name_for_human": "My ChatGPT To Do Plugin", "name_for_model": "todo", "description_for_human": "Plugin for managing a To Do list. You can add, remove and view your To Dos.", "description_for_model": "Plugin for managing a To Do list. You can add, remove and view your ToDos.", "auth": { "type": "none" }, "api": { "type": "openapi", "url": "<http://localhost:3000/openapi.yaml>", "is_user_authenticated": false }, "logo_url": "<http://localhost:3000/logo.png>", "contact_email": "support@yourdomain.com", "legal_info_url": "<http://www.yourdomain.com/legal>" }
openapi.yaml
,并且添加下列代码到文件中。这是OpenAPI规范,ChatGPT会用它来理解您的API路由的作用(注意每个路由的summary
)以及请求和响应的格式。如果ChatGPT在使用您的API时遇到问题,十有八九是因为这个规范与您的API的响应不一致。
openapi: 3.0.1 info: title: TODO Plugin description: A plugin that allows the user to create and manage a To Do list using ChatGPT. version: 'v1' servers: - url: <http://localhost:3000> paths: /todos: get: operationId: getTodos summary: Get the list of todos responses: "200": description: OK content: application/json: schema: type: array items: $ref: '#/components/schemas/Todo' post: operationId: addTodo summary: Add a todo to the list requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/Todo' responses: "201": description: Created content: application/json: schema: $ref: '#/components/schemas/Todo' /todos/{id}: delete: operationId: removeTodo summary: Delete a todo from the list when it is complete, or no longer required. parameters: - name: id in: path required: true schema: type: integer responses: "204": description: No Content components: schemas: Todo: type: object properties: id: type: integer format: int64 task: type: string required: - id - task
我们的下一步是创建我们的主文件,也就是我们插件的入口。在项目根目录下,添加一个名为index.js
的文件,并添加以下代码。
注意:ChatGPT文档显示openapi.yaml
和openapi.json
都有一个路由。本地测试显示只有yaml文件被请求,但值得把它们都放在那里,因为以后可能会用到。
粘贴下面代码到index.js
中:
const express = require('express'); const cors = require('cors'); const todoRouter = require('./routes/todos'); const openaiRoutes = require('./routes/openai'); const app = express(); const PORT = 3000; // Setting CORS to allow chat.openapi.com is required for ChatGPT to access your plugin app.use(cors({ origin: [`http://localhost:${PORT}`, '<https://chat.openai.com>'] })); app.use(express.json()); // Simple request logging to see if your plugin is being called by ChatGPT app.use((req, res, next) => { console.log(`Request received: ${req.method}: ${req.path}`) next() }) // OpenAI Required Routes app.use(openaiRoutes); // The dummy todos API app.use('/todos', todoRouter); app.listen(PORT, () => { console.log(`Plugin server listening on port ${PORT}`); });
上述代码做了下列事情:
express
和cors
所需的库在这一步中,我们将为OpenAI / ChatGPT添加强制性的路由,来获取所需文件。我们将把所有具体的路由逻辑放在一个"routes"目录中。这就是我们将存储插件路由以及其他自定义路由的地方。
(你可能希望用额外的文件夹(控制器、中间件、服务等)扩展这个结构,或者创建你自己的结构)。
/routes
文件夹openai.js
的文件routes/openai.js
中:const express = require('express'); const router = express.Router(); const fs = require('fs'); const path = require('path'); const yaml = require('js-yaml'); router.get('/openapi.yaml', async function(req, res) { try { const yamlData = fs.readFileSync(path.join(process.cwd(), 'openapi.yaml'), 'utf8'); const jsonData = yaml.load(yamlData); res.json(jsonData); } catch(e) { console.log(e.message) res.status(500).send({ error: 'Unable to fetch manifest.' }); } }); router.get('/.well-known/ai-plugin.json', function(req, res) { res.sendFile(path.join(process.cwd(), '/.well-known/ai-plugin.json')); }); router.get('/logo.png', function(req, res) { res.sendFile(path.join(process.cwd(), 'logo.png')); }) module.exports = router;
上述代码做了下列事情:
index.js
中导入它们。现在我们将创建一些简单的路由来模拟一个简单的创建、更新、删除功能。我们通常避免使用todo教程,但考虑到文档中使用这个作为指南,我们希望尽可能保持它的可转移性。
todos.js
的新文件routes/todos.js
中:const express = require('express'); const router = express.Router(); let todos = [ { id: 1, task: 'Wake up' }, { id: 2, task: 'Grab a brush'}, { id: 3, task: 'Put a little makeup'}, { id: 4, task: 'Build a Chat Plugin'} ]; // placeholder todos let currentId = 5; // to assign unique ids to new todos getTodos = async function(req, res) { res.json(todos); } addTodo = async function(req, res) { const { task } = req.body; const newTodo = { id: currentId, task }; todos.push(newTodo); currentId++; res.json(newTodo); } removeTodo = async function(req, res) { const { id } = req.params; todos = todos.filter(todo => todo.id !== Number(id)); res.json({ "message" : "Todo successfully deleted" }); } router.get('/', getTodos); router.post('/', addTodo); router.delete('/:id', removeTodo); module.exports = router;
上述代码做了下列事情:
index.js
文件。现在,有趣的部分来了。我们已经有了所有必要的代码和设置,可以在ChatGPT上手动建立和运行一个本地插件了!我们开始吧:
在终端中输入node index.js
。这会在终端中开启服务并打印’Plugin server listening on port 3000’。
进入chat.openai.com,在你的账户中打开一个新的聊天窗口。点击GPT-4下拉菜单,Plugins > Plugin Store > 点击Develop Your Own Plugin
> 输入localhost:3000
> 点击Find manifest file。
你应该看到一条验证信息,即ChatGPT能够获得你的清单文件,这样你就可以开始了。如果没有,请检查你的终端,服务器正在运行,并且正在接收传入的请求。
试试下面的一些命令:
what are my todos?
"I have woken up
(你不需要说出确切的Todo任务,它就能理解你指的是什么)如果你已经有一个在本地或外部运行的API来发送请求,你可以把这个服务器作为一个代理,把请求转发给它。这是一个值得推荐的选项,因为它使你能够快速测试和迭代如何处理清单和规范文件,而不必重新部署或更新你现有的代码库。
在你创建的路由下的index.js
中添加以下代码:
// PASTE IN BEFORE app.listen(... // Proxy server to an existing API const api_url = '<http://localhost>'; app.all('/:path', async (req, res) => { const { path } = req.params; const url = `${api_url}/${path}`; console.log(`Forwarding call: ${req.method} ${path} -> ${url}`); const headers = { 'Content-Type': 'application/json', }; try { const response = await axios({ method: req.method, url, headers, params: req.query, data: req.body, }); res.send(response.data); } catch (error) { console.error(`Error in forwarding call: ${error}`); res.status(500).send('Error in forwarding call'); } });
这个基本教程应该是你开始建立自己的基于JavaScript的成熟聊天插件所需要的。将你的应用程序部署到生产环境中,需要一些额外的认证和部署步骤。教程中没有提到这些,但我推荐以下资源来完成这些工作:
以上就是本文的全部内容,感谢阅读。