claude的前几行也单独处理,我的解决方案代码如下:
点击查看全文
try { const response = await fetch(this.apiUrl, { method: 'POST', signal: signal, headers: { 'Content-Type': 'application/json', 'x-api-key': this.apiKey, }, body: JSON.stringify({ model: "", messages: [], stream: true, system: }), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const reader = response.body.getReader(); const decoder = new TextDecoder(); var i = 0; while (true) { const { value, done } = await reader.read(); if (done) break; i++; const chunk = decoder.decode(value, { stream: true }); var lines = []; if (i == 1) { const getlinedata = flatfirstline(chunk); lines = ['data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'+getlinedata+'"} }']; } else { lines = chunk.split('\n').filter(line => line.trim() !== ''); } for (const line of lines) { console.log(line) if (line.startsWith('data: ')) { const message = line.replace(/^data: /, ''); console.log(message) try { const json = JSON.parse(message); console.log(json) if (json.type != 'content_block_stop') { if (json.type != 'content_block_delta') { break; } let content = json.delta.text; if (content != undefined && content != "error") { console.log(content) } else { break; } } else { break; } } catch (e) { console.error("Error parsing JSON: ", e.message); } } } } } catch (err) { if (err.name !== 'AbortError') { console.error('Fetch error:', err); } } finally { this.controller = null; } function flatfirstline(text) { const regex = /event: content_block_delta\s+data:.*?"text":"([^"]+)"/g; let match; const extractedTexts = []; while ((match = regex.exec(text)) !== null) { extractedTexts.push(match[1]); } return extractedTexts.join(''); }
网友回复
人形机器人的运动能否有端侧ai全面接管?
有没有抓取抖音头条等自媒体平台指定主题的评论的python开源程序?
css如何实现多个代码块向下滚动右上角复制按钮sticky粘性在顶部效果?
python+Quill如何实现多人实时文档编辑html?
什么是ai的6A工作流规则?
&、nohup、screen、tmux在linux中后台执行的区别?
python如何将调用ai大模型生成的文件修改行操作指令修改原文件后保存?
python如何将2d平面线图转换成数字2d线稿图?
acejs代码编辑器如何调用openai api实现选择代码修改与代码自动补全?
ace.js如何获取选择文本的开始和结束行数?