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('');
}					网友回复
- threejs如何做个三维搭积木的游戏?
- three如何实现标记多个起始路过地点位置后选择旅行工具(飞机汽车高铁等),最后三维模拟行驶动画导出mp4?
- ai实时驱动的3d数字人可视频聊天的开源技术有吗
- swoole+phpfpm如何实现不同域名指向不同目录的多租户模式?
- 如何用go替换nginx实现请求phpfpm解析运行php脚本?
- 有没有浏览器离线运行进行各种文档、图片、视频格式转换的开源工具?
- 如何使用go语言搭建一个web防火墙?
- linux如何检测特定网络协议比如http协议中报文是否包含特点关键词并阻止返回给客户?
- 如果在nginx外过滤包含某些关键词的网页并阻止打开?
- 程序员怎么做副业赚钱?



 
				 
			 
			 
				 
			