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(''); }
网友回复