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

  • 小规模纳税人应纳增值税额的计算
  • 发票开具与小票的关系是怎样的
  • 个人所得税申报退税的条件
  • 印花税是根据什么征收的
  • 转让无形资产增值税
  • 股权转让时的资金是什么
  • 小企业取得存货计量的原则
  • 嵌入式软件产品增值税即征即退
  • 商品房买卖合同没有约定逾期交房违约金
  • 暂估入库产品行程影响所得税汇算清缴吗
  • 先收入后开票如何做账
  • 收入成本以前年度损益调整账务处理是怎样的?
  • 电子发票如何打印清单明细
  • 电子产品发票税是多少
  • 员工福利费是否计入赔偿
  • 人工服务费发票
  • 通讯费发票抬头为个人能否报销
  • 换账套期初数怎么填
  • 如何填制记账凭证总结
  • 所得税补缴自查需要缴纳什么
  • 外购软件可以加计扣除吗
  • 实收资本不变说明了什么
  • 长期股权投资溢价购入
  • 报关代理费是什么
  • php数组函数实现机选双色球
  • php写一个函数,算出两个文件的相对路径
  • php语言版本
  • 圣胡安岛战争
  • 请问酒厂销售酒怎么样?
  • 用php写的一个冒号的句子
  • 红冲上年度收入怎么做凭证
  • 长期借款的主要成本包括
  • 防伪税控开票系统安装
  • 二手车征税税率减按多少税
  • Python运算符的优先级别
  • 安全文明措施费比例
  • 开具农产品收购发票需要什么资料
  • 一般纳税人季报还是月报
  • 咨询公司小规模纳税人企业所得税核定征收
  • 投标报名费怎么做分录
  • 民办非注销原因如何写
  • 已计提的城建税有误,怎么办
  • 教育培训业能享受补贴吗
  • 应付账款的主要舞弊形式
  • 小微企业员工人数限制
  • 购买原材料没有发票能入库吗
  • 投资性房地产抵债怎么做账务处理
  • 股权转让对价款如何计算
  • 生产经营所得如何申请退税
  • 固定资产清理的累计折旧怎么算
  • 公益性捐赠会计利润总额计算方法
  • 发票免税怎么做账
  • 公司购入的房子卖了,如何交增值税
  • 盈余公积的会计分录
  • 高新企业研发费用占比
  • 会计基本前提包括会计主体货币计量资料完整和经济效益
  • 怎么调整原材料的数量和单价
  • 营业收入的核算内容包括
  • 笔记本带u
  • linux make命令怎么用
  • 常见内存大小
  • winxp系统怎么设置默认账户登入
  • win10如何关闭windows
  • centos 安装
  • redhat无法启动
  • linux 数据恢复
  • 详细说明什么是支撑
  • nodejs的理解
  • 数据库的列名是什么
  • node.js开发实战
  • 置顶高手
  • 安卓接口分类
  • python os.walk遍历目录
  • python socket模块
  • 天津税务局投诉举报咨询电话
  • 遵从与尊从
  • 小规模国税申报表填写方法
  • 营业执照网上申报入口官网
  • 服务费交哪个税目的印花税
  • 开票内容 大类
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设