聊天插件系统是一种令人兴奋的新方式,可以扩展ChatGPT的构建功能,纳入您自己的构建业务数据,并为客户与您的构建业务互动增加另一个渠道。在这篇文章中,构建我将解释什么是构建聊天插件,它们能做什么,构建以及你如何用JavaScript建立你自己的构建聊天插件。
这篇文章(或OpenAI所称的"训练数据")提供了一个快速入门指南,来建立你的第一个ChatGPT插件,并将其与ChatGPT界面整合。
聊天插件是否会成为改变生活的贾维斯般的体验,或者只是一个昂贵的Alexa-for-your-browser,目前还没有定论。让我们通过看看插件能提供什么,需要注意什么,以及如何制作你自己的插件,来决定我们自己的想法。
插件组成部分
聊天插件生态系统的新机遇
插件开发的考量和局限
"聊天插件"允许ChatGPT模型使用并与第三方应用程序互动。从本质上讲,它是一套指令和规范,语言模型可以遵循这些指令和规范在聊天对话中创建API的调用和操作。与第三方系统的整合为ChatGPT的用户提供了一系列新的功能:
建立一个能与AI互动的应用程序似乎是一个令人生畏的复杂系统,然而,一旦你开始做,你会发现它非常简单。一个"插件"是一套简单的指令,它告诉ChatGPT模型你的API是做什么的,以及如何和何时访问它。
这可以归结为两个重要文件:
插件服务的基础功能和托管由你决定。你的API可以托管在任何地方,使用任何REST API或编程语言。
聊天插件的到来为开发者、设计师、企业和企业家带来了一系列的机会:
直观和无代码界面的好处带来了一系列挑战。承认生态系统、逻辑和界面会随着时间的推移而发展,在构建插件时,我们仍然需要记住一些事情。特别是如果你想把它们作为一项业务来建立。
我们将为我们的聊天插件建立自己的express服务器。这不仅是一个容易上手的方法,而且express可以被扩展到包括中间件、认证和所有其他你想要的生产级的东西。
以下是我们将在下列步骤中创建和添加代码的所有文件。如果你感到困惑,可以回到这里,或者克隆这里的源码[1]。
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 itmkdir my-chat-plugin && cd my-chat-plugin## 2. Initialize a project with the default valuesnpm init --yes## 3. Install our dependenciesnpm install axios express cors js-yaml
现在,我们要创建所需的聊天插件清单和OpenAPI规范。ChatGPT会在你服务器的特定路由上请求这些文件,所以我们要把它们放在:
这些文件中的描述是非常重要的!如果你在summary和description_for_model字段中的语言含糊不清,你可能会让ChatGPT对何时和如何使用你的插件感到困惑。请遵循以下步骤:
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规范,ChatGPT会用它来理解您的API路由的作用(注意每个路由的summary)以及请求和响应的格式。如果ChatGPT在使用您的API时遇到问题,十有八九是因为这个规范与您的API的响应不一致。
openapi: 3.0.1info: 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 Contentcomponents: 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 pluginapp.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 ChatGPTapp.use((req, res, next) => { console.log(`Request received: ${ req.method}: ${ req.path}`) next()})// OpenAI Required Routesapp.use(openaiRoutes);// The dummy todos APIapp.use('/todos', todoRouter);app.listen(PORT, () => { console.log(`Plugin server listening on port ${ PORT}`);});
上述代码做了下列事情:
在这一步中,我们将为OpenAI / ChatGPT添加强制性的路由,来获取所需文件。我们将把所有具体的路由逻辑放在一个"routes"目录中。这就是我们将存储插件路由以及其他自定义路由的地方。
(你可能希望用额外的文件夹(控制器、中间件、服务等)扩展这个结构,或者创建你自己的结构)。
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;
上述代码做了下列事情:
现在我们将创建一些简单的路由来模拟一个简单的创建、更新、删除功能。我们通常避免使用todo教程,但考虑到文档中使用这个作为指南,我们希望尽可能保持它的可转移性。
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 todoslet currentId = 5; // to assign unique ids to new todosgetTodos = 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;
上述代码做了下列事情:
现在,有趣的部分来了。我们已经有了所有必要的代码和设置,可以在ChatGPT上手动建立和运行一个本地插件了!我们开始吧:
在终端中输入node index.js。这会在终端中开启服务并打印’Plugin server listening on port 3000’。
进入chat.openai.com[4],在你的账户中打开一个新的聊天窗口。点击GPT-4下拉菜单,Plugins > Plugin Store > 点击Develop Your Own Plugin > 输入localhost:3000 > 点击「Find manifest file」。
你应该看到一条验证信息,即ChatGPT能够获得你的清单文件,这样你就可以开始了。如果没有,请检查你的终端,服务器正在运行,并且正在接收传入的请求。
试试下面的一些命令:
如果你已经有一个在本地或外部运行的API来发送请求,你可以把这个服务器作为一个代理,把请求转发给它。这是一个值得推荐的选项,因为它使你能够快速测试和迭代如何处理清单和规范文件,而不必重新部署或更新你现有的代码库。
在你创建的路由下的index.js中添加以下代码:
// PASTE IN BEFORE app.listen(... // Proxy server to an existing APIconst 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的成熟聊天插件所需要的。将你的应用程序部署到生产环境中,需要一些额外的认证和部署步骤。教程中没有提到这些,但我推荐以下资源来完成这些工作:
本文译自:https://www.sitepoint.com/javascript-chatgpt-plugin/[7]
以上就是本文的全部内容,感谢阅读。
[1]源码:https://github.com/sitepoint-editors/chatgpt-plugin-quickstart-js
[2]注册:https://platform.openai.com/signup?launch
[3]这里:https://openai.com/waitlist/plugins
[4]chat.openai.com:https://chat.openai.com/
[5]官方插件实例:https://platform.openai.com/docs/plugins/examples
[6]生产你的应用程序:https://platform.openai.com/docs/plugins/production/domain-verification-and-security
[7]https://www.sitepoint.com/javascript-chatgpt-plugin/:https://www.sitepoint.com/javascript-chatgpt-plugin/
责任编辑:武晓燕 来源: 前端F2E JavaScriptChatGPT插件(责任编辑:综合)
冀东装备(000856.SZ)公布消息:拟向冀东集团申请总额不超4亿元借款
四川省乐山全力推进主城区城市排水防涝准备工作 提高各部门应急决策水平
2021年合肥中欧班列累计开行668列 列数同比增长17.61%
深高速(00548.HK)年度净利润减少19.88% 末期现金股息每股0.43元