位置: 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响应式对象数组)

  • 微信推广方式都有哪些(微信推广方式都包括什么)

    微信推广方式都有哪些(微信推广方式都包括什么)

  • 网易云音乐歌曲速度怎么调(网易云音乐歌曲怎么下载到u盘)

    网易云音乐歌曲速度怎么调(网易云音乐歌曲怎么下载到u盘)

  • 章鱼输入法怎么打花体字(章鱼输入法怎么取消自动续费)

    章鱼输入法怎么打花体字(章鱼输入法怎么取消自动续费)

  • 小爱同学怎么连手机蓝牙(小爱同学怎么连接小米空调)

    小爱同学怎么连手机蓝牙(小爱同学怎么连接小米空调)

  • 幻灯片切换方案设置(幻灯片切换方案设置为时钟)

    幻灯片切换方案设置(幻灯片切换方案设置为时钟)

  • excel中true代表1还是0

    excel中true代表1还是0

  • 华为一直显示耳机状态(华为一直显示耳机连接)

    华为一直显示耳机状态(华为一直显示耳机连接)

  • 快手怎么隐藏共同好友(快手里怎么隐藏我的互相关注)

    快手怎么隐藏共同好友(快手里怎么隐藏我的互相关注)

  • 手机可以下载word文档吗(手机可以下载word2016吗)

    手机可以下载word文档吗(手机可以下载word2016吗)

  • 苹果手表3和5的区别(苹果手表3和5的区别图片)

    苹果手表3和5的区别(苹果手表3和5的区别图片)

  • 爱奇艺有tv版吗(爱奇艺有TV版吗)

    爱奇艺有tv版吗(爱奇艺有TV版吗)

  • 什么是m站(m站是什么意思啊)

    什么是m站(m站是什么意思啊)

  • 发射卫星属于计算机在什么领域的应用(发射卫星属于计算机什么领域)

    发射卫星属于计算机在什么领域的应用(发射卫星属于计算机什么领域)

  • 微博永久封号怎么解除(微博永久封号怎样解绑手机号)

    微博永久封号怎么解除(微博永久封号怎样解绑手机号)

  • ios微信怎么改通知铃声(苹果手机怎么改微信电话)

    ios微信怎么改通知铃声(苹果手机怎么改微信电话)

  • 卡贴iphone怎么开热点(卡贴怎么打开)

    卡贴iphone怎么开热点(卡贴怎么打开)

  • 手机网站劫持怎么处理(手机网页劫持)

    手机网站劫持怎么处理(手机网页劫持)

  • 百度地图如何测海拔(百度地图如何测量两个地点的距离)

    百度地图如何测海拔(百度地图如何测量两个地点的距离)

  • 如何连接网络共享打印机(如何连接网络共享打印机具体步骤)

    如何连接网络共享打印机(如何连接网络共享打印机具体步骤)

  • qq大小船消失规则(qq小船不会消失吗)

    qq大小船消失规则(qq小船不会消失吗)

  • 小米蓝牙耳机如何恢复出厂设置(小米蓝牙耳机如何充电)

    小米蓝牙耳机如何恢复出厂设置(小米蓝牙耳机如何充电)

  • pr项目窗口怎么恢复(pr项目窗口怎么下拉)

    pr项目窗口怎么恢复(pr项目窗口怎么下拉)

  • 手机怎么开通银联支付(手机怎么开通银行卡余额变动提醒)

    手机怎么开通银联支付(手机怎么开通银行卡余额变动提醒)

  • MAC如何在Numbers单元格里面显示公式而不是最终答案(mac如何在桌面显示我的电脑)

    MAC如何在Numbers单元格里面显示公式而不是最终答案(mac如何在桌面显示我的电脑)

  • 已知税金及附加怎么算增值税
  • 企业所得税的计算公式
  • 所得税交多了怎么办
  • 微商怎么交易流程
  • 别人给开的普通发票能抵扣多少税
  • 公司为员工购买社保证明
  • 企业一直亏损但是汇算清缴调增
  • 账目不清什么意思
  • 三证合一后银行开户许可证还有吗
  • 退回剩余的工程物资
  • 公司往来款现金流量表
  • 小规模纳税人专票开1%还是3%
  • 福利费可以用什么科目
  • 应收未收的利息如何处理
  • 南方建筑主编
  • 普通发票红字冲销,需要退回原发票吗
  • 关税税率表包括哪些税种
  • 认缴制下实收资本可以一直为零吗
  • 公司的班车费用怎么入账
  • 研发支出采用什么明细账
  • 个人租车给单位合同怎么写
  • 三险一金专项扣除怎么查
  • 进口应税消费品的组成计税价格为
  • openlayers加载geojson
  • cpu风扇应该怎么调
  • Win11怎么设置自启动软件
  • 进程核心栈
  • PHP:pg_field_type_oid()的用法_PostgreSQL函数
  • 账务处理程序有什么
  • 金融机构贷款利息规定
  • 汽车维修收费标准及费用计算方法
  • 纳税申报包括哪些税种
  • 应纳税为什么是0
  • 会计申报需要哪些数据
  • python的Django框架
  • ChatGPT的火爆出圈,你对它有几分了解?
  • 电子商业汇票业务
  • 固定资产提足折旧后,不论能否继续使用
  • 凭样品销售
  • 应纳税所得额中国债利息收入
  • echarts怎么引入
  • 将房产以股权形式出售
  • 企业所得税成本核定
  • 其他应付款不用付了会计分录
  • win2008安装sql2008教程
  • 一般纳税人销售旧货税率
  • mysql中删除语句怎么写
  • 债权投资相关科目
  • 电子商业汇票背书人记载不得转让
  • 办理契税所需要的证件
  • 结转增值税的账务处理
  • 销售返现如何做账务处理
  • 银行日记账上月的余额要结转吗
  • 营业外收入的账户核算有哪些
  • 计提以前年度应付股利的分录
  • 旅游业差额开票的票据可以累计一季度吗
  • 今年成立的公司需要申报残疾人保障金吗
  • sql语句错误提示
  • mysql加密解密
  • mysql 5.1.6
  • Windows 7 RTM、Vista、XP 性能测试
  • win7系统的摄像功能在哪
  • ctrl+的作用
  • 虚拟机centos7无法启动
  • window10的小娜不支持中文版
  • linux系统中限定系统口令的长度
  • javascript中的函数
  • 捉虫趣事作文200字
  • qt绘制3d
  • texture packer工具
  • 网卡流量怎么计算
  • 有关于js构造函数的题
  • typeof的缺点
  • jquery跨域请求有哪些方式
  • jquery $each
  • 重大税务违法案件一案双查标准
  • 信用社股金分红时间
  • 河南个人社保查询登录入口官网
  • 浙江摩托车上牌条件
  • 中国古代的税收制度的演变
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设