上一篇文章写的不够详细这篇文章我们来说一说,对于GPT API不言而喻能够做很多方面AI的事情,可以用于:
- 文本生成:GPT API可以根据给定的输入文本生成连贯、有逻辑的自然语言文本,如文章、故事、对话等。
- 语言翻译:使用GPT API,你可以将输入文本从一种语言翻译成另一种语言。
- 文本摘要:通过提供一段文本,GPT API可以生成该文本的摘要,提取出关键信息和主要观点。
- 问题回答:GPT API可以根据提供的问题生成相应的答案,帮助解决特定领域或常见问题。
- 对话系统:利用GPT API,你可以构建智能对话系统,使用户能够与模型进行自然语言交互。
下面介绍一下GPT API Web正确的接入方式。
我们先来看一个效果
- 页面构建
<template> <div style="width: 60%;margin: 100px auto 0 auto;"> <div style="height: 300px;background-color: #F8F8F8;overflow-y: scroll;"> <v-md-preview :text="text"/> </div> <input type="text" v-model="title" style="width: 100%;height:28px;margin: 6px 0px 10px 0px;"> <div><input type="button" @click="sendText" value="发送消息"/></div> </div> </template> <style> .v-md-editor-preview { color: #525252; } </style>
- 页面数据结构定义
data() { return { apiKey: 'OpenAI api-key', text: '', //gpt识别结果文本 title: '发送到gpt的消息内容如:写一篇民间故事,话题是妖怪', messageId: '',//发送内容后返回的消息id用于查询gpt识别结果的messageId textResult: { "finish_reason": '',//当finish_reason==stop时表示已结束 "message": "",//本次查询的消息 "fromIndex": 0 //从fromIndex索引处开始查询到本次查询已识别到的内容 }, tempText: '' //临时文本用于页面过滤渲染 } }
- 点击发送消息调用GPT文本消息请求
sendText() { eyapi('post', '/ncgpt/ai/text/chat/3', { "apiKey": this.apiKey, "secret": "", //该密钥值在易由数据平台->模型/数据板块->国内GPT API代理服务中免费申请 "content": this.title, "temperature": 0.8 }).then((response) => { this.messageId = response; this.text = '思考中...'; this.tempText = ''; this.getText(); //这里开始查询识别结果 this.renderText(); //同时开始页面效果渲染 }).catch((message) => { console.log(message); }); }
- 查询文本识别结果
getText() { if (this.messageId.length === 0) { return; } eyapi('get', '/ncgpt/ai/text/conversation/query', { "secret": "1e7feb989dc9ee44239e5962df1e712d", "messageId": this.messageId, "fromIndex": this.textResult.fromIndex }).then((response) => { this.textResult = response; this.tempText += this.textResult.message; //识别到的内容先赋值给临时文本 if (this.textResult.finish_reason !== "stop") { setTimeout(() => { // 延迟1秒后开始查询识别结果 // 这里是个函数递归直到finish_reason===stop为止 this.getText(); }, 1000); } else { // stop: 结束本次操作,初始化对象值 this.messageId = ''; this.textResult = {}; } }).catch((message) => { console.log(message); }); }
- 页面效果渲染处理
renderText() { setInterval(() => { if (this.tempText.length > 0) { if (this.text === "思考中...") { this.text = ''; } this.text += this.tempText.substr(0, 1); this.tempText = this.tempText.substr(1); this.scrollToBottom(); } }, 50); }
好了,看到这里即可在web集成GPT文本智能AI功能。如果对文档中eyapi网络组件或想了解更多GPT API使用方式,请查看基于GPT 3.5/4.0国内AI中文文档
https://openaidoc.eyapis.com/#/start/README.md