位置: IT常识 - 正文

js调用gpt3.5(支持流回显、高频功能)(js调用函数的几种方法)

编辑:rootadmin
js调用gpt3.5(支持流回显、高频功能)

推荐整理分享js调用gpt3.5(支持流回显、高频功能)(js调用函数的几种方法),希望有所帮助,仅作参考,欢迎阅读内容。

js调用gpt3.5(支持流回显、高频功能)(js调用函数的几种方法)

文章相关热门搜索词:js调用js,js调用go,调用js函数,grpc js 调用,js调用go,js调用get请求,js调用js,js调用go,内容如对您有帮助,希望把文章链接给更多的朋友!

参考链接:直接在前端调用 GPT-3 API

效果图: 查看在线demo(要梯子)

注意: 1. 需要apiKey,自用安全,不要给别人 2. 需要梯子 3. 选择稳定、人少的代理ip 4. 不要频繁切换ip,防止封号 5. api调用上限高,请遵守openAI审核政策 [doge]

<!DOCTYPE html><html><head> <meta charset="UTF-8" /> <title>ChatGPT Web Example</title></head><body> <div id="chatgpt_demo_container"></div></body><!-- Load React. --><!-- Note: when deploying, replace "development.js" with "production.min.js". --><script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script><script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script><script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script><!-- Load our React component. --><script type="text/babel"> // openAI接口文档 https://platform.openai.com/docs/guides/chat const e = React.createElement; class RootComponent extends React.Component { state = { endpoint: "https://api.openai.com/v1/chat/completions", apiKey: localStorage.getItem("localApiKey") || "", model: "gpt-3.5-turbo", temperature: 0.7, max_tokens: 1000, overTime: 30000, historyMessageNum: undefined, historyMessage: [], prompts: [{ role: "system", content: "" }], nextPrompts: [], question: "", loading: false, controller: null, conversationId: localStorage.getItem("localConversionId") || "conversion1", conversationIds: ["conversion1", "conversion2", "conversion3"], }; constructor(props) { super(props); } addMessage(text, sender) { let historyMessage = this.state.historyMessage; if ( sender !== "assistant" || historyMessage[historyMessage.length - 1].role !== "assistant" ) { historyMessage = [ ...this.state.historyMessage.filter( (v) => ["system", "user", "assistant"].includes(v.role) && v.content !== "" ), { role: sender, content: text, time: Date.now() }, ]; } else { historyMessage[historyMessage.length - 1].content += text; } this.setState({ historyMessage }); setTimeout(() => { this.scrollToBottom(sender !== "assistant"); }, 0); } editMessage(idx) { this.stopStreamFetch(); this.state.question = this.state.historyMessage[idx].content; const historyMessage = this.state.historyMessage.slice(0, idx); this.setState({ historyMessage }); } stopStreamFetch = () => { if (this.state.controller) { this.state.controller.abort("__ignore"); } }; regenerateStreamFetch = () => { this.stopStreamFetch(); if ( this.state.historyMessage.length && this.state.historyMessage[this.state.historyMessage.length - 1].role !== "user" ) this.setState({ historyMessage: this.state.historyMessage.slice(0, -1), }); setTimeout(() => { this.handleSearch(true); }, 0); }; async getResponseFromAPI(text) { const controller = new AbortController(); this.setState({ controller }); const signal = controller.signal; const timeout = setTimeout(() => { controller.abort(); }, this.state.overTime); const messages = [ ...this.state.historyMessage, { role: "user", content: text }, ] .filter( (v) => ["system", "user", "assistant"].includes(v.role) && v.content ) .map((v) => ({ role: v.role, content: v.content })) .slice(-this.state.historyMessageNum - 1); // 上文消息 const response = await fetch(this.state.endpoint, { signal, method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.state.apiKey}`, }, body: JSON.stringify({ model: this.state.model, messages: this.state.prompts .concat( messages, this.state.nextPrompts.length ? this.state.nextPrompts : [] ) .filter((v) => v), max_tokens: this.state.max_tokens, n: 1, stop: null, temperature: this.state.temperature, stream: true, }), }); clearTimeout(timeout); if (!response.ok) { const { error } = await response.json(); throw new Error(error.message || error.code); } const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); const stream = new ReadableStream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // When no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // Enqueue the next data chunk into our target stream // 'data: {"id":"chatcmpl-705I7nqSPYDvCTBv3OdNMatVEI85o","object":"chat.completion.chunk","created":1680254695,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"role":"assistant"},"index":0,"finish_reason":null}]}\n\ndata: {"id":"chatcmpl-705I7nqSPYDvCTBv3OdNMatVEI85o","object":"chat.completion.chunk","created":1680254695,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"ä½ "},"index":0,"finish_reason":null}]}\n\n' // 'data: {"id":"chatcmpl-705I7nqSPYDvCTBv3OdNMatVEI85o","object":"chat.completion.chunk","created":1680254695,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"好"},"index":0,"finish_reason":null}]}\n\n' // 'data: {"id":"chatcmpl-705I7nqSPYDvCTBv3OdNMatVEI85o","object":"chat.completion.chunk","created":1680254695,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"ï¼\x81"},"index":0,"finish_reason":null}]}\n\n' // '[DONE]\n\n' let text = ""; const str = decoder.decode(value); const strs = str.split("data: ").filter((v) => v); for (let i = 0; i < strs.length; i++) { const val = strs[i]; if (val.includes("[DONE]")) { controller.close(); return; } const data = JSON.parse(val); data.choices[0].delta.content && (text += data.choices[0].delta.content); } controller.enqueue(text); return pump(); }); } }, }); return new Response(stream); } handleSearch(regenerateFlag) { const input = this.state.question; if (!regenerateFlag) { if (!input) { alert("请输入问题"); return; } this.addMessage(input, "user"); this.setState({ question: "" }); } this.state.loading = true; // 使用 OpenAI API 获取 ChatGPT 的回答 this.getResponseFromAPI(input) .then(async (response) => { if (!response.ok) { const error = await response.json(); throw new Error(error.error); } const data = response.body; if (!data) throw new Error("No data"); const reader = data.getReader(); let done = false; while (!done) { const { value, done: readerDone } = await reader.read(); if (value) { this.addMessage(value, "assistant"); this.scrollToBottom(); } done = readerDone; } }) .catch((error) => { if (this.state.controller.signal.reason === "__ignore") { return; } console.log('-------------error', this.state.controller.signal, this.state.controller.signal.reason, error, error.name, error.message); this.addMessage( error.name === "AbortError" ? "Network Error" : error.message, "warning" ); }) .finally(() => { this.setState({ loading: false }); }); } handleChangePromots = () => { const input = prompt( `请输入你的前置引导词`, this.state.prompts[0].content || `e.g. CR: Capacity and Role(能力与角色)。你希望 ChatGPT 扮演怎样的角色。I: Insight(洞察力),背景信息和上下文。S: Statement(指令),你希望 ChatGPT 做什么。P: Personality(个性),你希望 ChatGPT 以什么风格或方式回答你。` ); if (input != null) { const prompts = this.state.prompts; prompts[0].content = input; this.setState({ prompts }); } }; handleChangeMessageNum = () => { const input = prompt( `请设置携带的上文消息条数。条数越多,回答的关联性越强。条数越少,生成的内容越随机。如果携带信息超过上限,请减少条数。`, this.state.historyMessageNum ); if (input != null) { const num = Number(input); if (isNaN(num) || num < 0) return alert("请输入合法数字"); this.setState({ historyMessageNum: num }); } }; handleChangeApiKey = () => { const input = prompt(`请输入你的apiKey`, this.state.apiKey); if (input != null) { this.setState({ apiKey: input }); } }; handleChangeNextPrompts = () => { const input = prompt( `请输入你的后置诱导的问答,中间用"///"分开`, this.state.nextPrompts.map((v) => v.content).join("///") || "e.g. 好的,但我需要先向你申请权限并且得到免责
本文链接地址:https://www.jiuchutong.com/zhishi/300300.html 转载请保留说明!

上一篇:端午假期整理了仿天猫H5 APP项目vue.js+express+mongo(端午假期干什么)

下一篇:vue3 响应式对象的 api 详解(vue3响应式对象数组)

  • 注册谷歌账号需收费多少元(注册谷歌账号)(注册谷歌账号需要按标准费率支付费用)

    注册谷歌账号需收费多少元(注册谷歌账号)(注册谷歌账号需要按标准费率支付费用)

  • 小米10s可以用电信移动卡(小米1s电信版能用移动卡吗)(小米10s可以用电信卡吗)

    小米10s可以用电信移动卡(小米1s电信版能用移动卡吗)(小米10s可以用电信卡吗)

  • qq号注销后还可以恢复吗(qq号注销后还可以申请新号码吗)

    qq号注销后还可以恢复吗(qq号注销后还可以申请新号码吗)

  • 微信直播红包抢了之后在哪里(微信直播抢到的红包怎么提现)

    微信直播红包抢了之后在哪里(微信直播抢到的红包怎么提现)

  • 看不了朋友圈是拉黑还是删除(看不了朋友圈是什么情况)

    看不了朋友圈是拉黑还是删除(看不了朋友圈是什么情况)

  • 怎么注销苹果id账号是永久注销哪种(怎么注销苹果id账号重新注册)

    怎么注销苹果id账号是永久注销哪种(怎么注销苹果id账号重新注册)

  • 小米手机无线充电充不进电(小米手机无线充电有哪几款?)

    小米手机无线充电充不进电(小米手机无线充电有哪几款?)

  • 显卡代码43(amd显卡代码43)

    显卡代码43(amd显卡代码43)

  • 微信账号保护选项消失(微信账号保护模式怎么造成的)

    微信账号保护选项消失(微信账号保护模式怎么造成的)

  • 快手同城置顶是什么意思(快手同城置顶怎么收费)

    快手同城置顶是什么意思(快手同城置顶怎么收费)

  • 星标朋友有什么特殊含义(星标朋友有什么特殊提示音)

    星标朋友有什么特殊含义(星标朋友有什么特殊提示音)

  • 组成完整计算机系统包括(组成一个完整的计算机应该包括)

    组成完整计算机系统包括(组成一个完整的计算机应该包括)

  • iphonex和11pro屏幕一样吗(iphonex和11pro屏幕哪个好)

    iphonex和11pro屏幕一样吗(iphonex和11pro屏幕哪个好)

  • 手机上怎么显示拼音(手机上怎么显示海拔多少米)

    手机上怎么显示拼音(手机上怎么显示海拔多少米)

  • 华为云服务可以卸载吗(华为云服务可以保存微信聊天记录吗)

    华为云服务可以卸载吗(华为云服务可以保存微信聊天记录吗)

  • 网络正常抖音为什么接不到网络(网络正常抖音打不开是什么原因)

    网络正常抖音为什么接不到网络(网络正常抖音打不开是什么原因)

  • vnr怎么用(vnr怎么用腾讯翻译)

    vnr怎么用(vnr怎么用腾讯翻译)

  • 华为nova4和nova5i的区别(华为nova4和nova5i屏幕一样吗)

    华为nova4和nova5i的区别(华为nova4和nova5i屏幕一样吗)

  • 充电宝充一会就发烫(充电宝充一会就不充了是怎么回事)

    充电宝充一会就发烫(充电宝充一会就不充了是怎么回事)

  • 微信用久了卡怎么办(微信用久了卡怎么解绑)

    微信用久了卡怎么办(微信用久了卡怎么解绑)

  • 天猫手机如何换货(天猫怎么换)

    天猫手机如何换货(天猫怎么换)

  • gcasServ.exe是什么进程 作用是什么 gcasServ进程查询(g++.exe error)

    gcasServ.exe是什么进程 作用是什么 gcasServ进程查询(g++.exe error)

  • 餐饮税务每个月几号报税
  • 小规模纳税人城市维护建设税税率
  • 员工垫资报销记账
  • 车船税是费用吗
  • 保安服务业务
  • 装修辅材行业辅材现状
  • 企业的哪些活动对企业有长期影响呢
  • 小规模纳税人怎么查询
  • 支付各种办公费用
  • 分公司单独做账吗
  • 怎样冲减虚开发票的会计分录
  • 没有计提12月底的工资
  • 作废的发票怎么复制开新票
  • 如何理解纳税人资格
  • 管理费用的纳税调整
  • 印花税按次申报怎么报
  • 12月的工资啥时候发
  • 半年付一次房租,房东一般提前多长时间催租
  • 收到分包公司工程发票收入怎么做账
  • 合伙项目如何进行分红
  • 无法支付的其他应付款可以用现金核销吗
  • 财报申报逾期可不可以补报
  • 幼儿园收的保教费是什么费
  • 以产品分成方式销售商品
  • 升级打装备的手游
  • 腾讯电脑管家中如何安装 文件夹上锁专家
  • 质押已至票据到期日
  • 无法收回的应收款项计入什么科目
  • 企业注销需要多久
  • php session_start
  • PHP:base64_encode()的用法_url函数
  • 税务登记 申报
  • php 实例
  • thinkphp钩子场景
  • 房屋产权置换协议书范本
  • 转让土地使用权的条件是什么
  • 奥林匹克国家公园
  • arc架构
  • 银行历年账单怎么查
  • yolov5训练命令
  • laravel日志管理系统
  • 外购商品用于赠送增值税可以抵扣么
  • c语言中有哪些循环结构
  • 主营业务成本如何记账
  • 给员工分红是否交税
  • 递延收益与预收收益区别
  • 员工门诊收费票据可以入账吗
  • 预收账款可以用什么科目核算
  • 收到赠送的货物会计分录
  • ibm db2认证
  • 母公司兼并子公司怎么办
  • 应收预收应付预付科目怎么合并
  • 取得收入未开具发票
  • 收到客户账款会计分录
  • 固定资产增值税发票如何入账
  • 分支机构可不可以不建账合并到总机构?
  • 汇率调节主要手段
  • 成本费用利润率一般在什么范围
  • 工会经费按实际发放交还是以计提的
  • friend怎么用
  • mysql 5.6 从陌生到熟练之_数据库备份恢复的实现方法
  • 苹果mac录制屏幕
  • linux版flash
  • freebsd怎么样
  • 无线网络找不到证书
  • centos配置kdump
  • win7系统安装的配置要求有什么
  • win10电脑无法上网
  • win7禁用开机启动服务
  • 升级win10系统后电脑变卡处理方法
  • 下载的mt4安装成了mt5
  • 哪些游戏是c#开发的
  • 阴影效果有什么用
  • opengl 生成图片
  • 用正则表达式替换掉两汉字间的括号
  • nodemoudles可以复制粘贴别的电脑运行程序吗
  • 如何进行arp病毒防范
  • 电子税务局申报密码怎么设置?
  • 企业所得税要在几号之前申报
  • 个人股权转让是否增值了怎么判断
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设