(requestText: string)
| 164 | * @returns |
| 165 | */ |
| 166 | export async function getGPTResponseByOpenAI(requestText: string) { |
| 167 | const views = Zotero.ZoteroGPT.views as Views |
| 168 | const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`) |
| 169 | const temperature = Zotero.Prefs.get(`${config.addonRef}.temperature`) |
| 170 | let api = Zotero.Prefs.get(`${config.addonRef}.api`) as string |
| 171 | api = api.replace(/\/(?:v1)?\/?$/, "") |
| 172 | const model = Zotero.Prefs.get(`${config.addonRef}.model`) |
| 173 | views.messages.push({ |
| 174 | role: "user", |
| 175 | content: requestText |
| 176 | }) |
| 177 | // outputSpan.innerText = responseText; |
| 178 | const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number |
| 179 | // 储存上一次的结果 |
| 180 | let _textArr: string[] = [] |
| 181 | // 随着请求返回实时变化 |
| 182 | let textArr: string[] = [] |
| 183 | // 激活输出 |
| 184 | views.stopAlloutput() |
| 185 | views.setText("") |
| 186 | let responseText: string | undefined |
| 187 | const id: number = window.setInterval(async () => { |
| 188 | if (!responseText && _textArr.length == textArr.length) { return} |
| 189 | _textArr = textArr.slice(0, _textArr.length + 1) |
| 190 | let text = _textArr.join("") |
| 191 | text.length > 0 && views.setText(text) |
| 192 | if (responseText && responseText == text) { |
| 193 | views.setText(text, true) |
| 194 | window.clearInterval(id) |
| 195 | } |
| 196 | }, deltaTime) |
| 197 | views._ids.push({ |
| 198 | type: "output", |
| 199 | id: id |
| 200 | }) |
| 201 | const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number |
| 202 | const url = `${api}/v1/chat/completions` |
| 203 | try { |
| 204 | await Zotero.HTTP.request( |
| 205 | "POST", |
| 206 | url, |
| 207 | { |
| 208 | headers: { |
| 209 | "Content-Type": "application/json", |
| 210 | "Authorization": `Bearer ${secretKey}`, |
| 211 | }, |
| 212 | body: JSON.stringify({ |
| 213 | model: model, |
| 214 | messages: views.messages.slice(-chatNumber), |
| 215 | stream: true, |
| 216 | temperature: Number(temperature) |
| 217 | }), |
| 218 | responseType: "text", |
| 219 | requestObserver: (xmlhttp: XMLHttpRequest) => { |
| 220 | xmlhttp.onprogress = (e: any) => { |
| 221 | try { |
| 222 | textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf("content") >= 0).map((s: string) => { |
| 223 | try { |
no test coverage detected