收藏
回答

真机调试 onChunkReceived 调用流式接口无返回?但是开发者工具可以

async sendMessageStream({ messages, onMessage }) {
        const token = uni.getStorageSync('token')
        if (!token) {
            throw new Error('请先登录')
        }


        const balance = await this.checkBalance()
        if (balance <= 0) {
            throw new Error('余额不足,请充值')
        }


        try {
            let hasStopSignal = false;
            let hasError = false;
            
            const requestTask = uni.request({
                url: 'https://api.xxx.com/v1/chat/completions',
                method: 'POST',
                timeout: 100000,
                header: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer xxx`,
                    'Accept': 'text/event-stream'
                },
                data: {
                    model: this.config.model || 'gpt-3.5-turbo',
                    messages: messages,
                    stream: true
                },
                enableChunked: true,
                success: (res) => {
                    console.log('请求成功:', res)
                    if (res.statusCode !== 200) {
                        hasError = true;
                        onMessage({ content: '', done: true, error: `请求失败: ${res.statusCode}` });
                    }
                },
                fail: (err) => {
                    console.error('请求失败:', err);
                    hasError = true;
                    onMessage({ content: '', done: true, error: err.errMsg || '请求失败' });
                },
                complete: () => {
                    console.log('请求完成');
                    // 如果没有收到停止信号且没有错误,则发送完成信号
                    if (!hasStopSignal && !hasError) {
                        onMessage({ content: '', done: true });
                    }
                }
            });


            // 添加分块接收监听
            requestTask.onChunkReceived((res) => {
                if (hasError) return; // 如果有错误,不处理数据块
                
                console.log('收到数据块:', res.data)
                const result = this.parseSSEChunk(res.data);
                
                // 检查是否是停止信号
                if (result.done) {
                    hasStopSignal = true;
                }
                
                onMessage(result);
            });


            return requestTask;
        } catch (error) {
            console.error('请求错误:', error)
            throw error
        }
    }


    // 添加SSE解析方法
    parseSSEChunk(chunk) {
        // 处理二进制数据
        if (typeof chunk !== 'string') {
            try {
                chunk = new TextDecoder().decode(chunk);
            } catch(e) {
                console.error('数据解码失败:', e);
                return { content: '', done: false };
            }
        }
        
        const lines = chunk.split('\n').filter(line => line.trim());
        console.log('解析后的数据:', lines)
        
        for (const line of lines) {
            const [key, ...values] = line.split(': ');
            const value = values.join(': '); // 重新组合可能包含 : 的值
            
            if (key === 'data') {
                try {
                    
                    const data = JSON.parse(value);
                    console.log('解析后的数据:', data)
                    
                    // 返回内容
                    if (data.choices?.[0]?.delta?.content) {
                        return { 
                            content: data.choices[0].delta.content,
                            done: false
                        };
                    }
                    
                    // 检查是否是结束标记
                    if (data.choices?.[0]?.finish_reason === 'stop') {
                        return { content: data.choices?.[0]?.delta?.content || '', done: true };
                    }
                } catch(e) {
                    console.error('JSON解析失败:', e, '数据:', value);
                }
            }
        }
        
        return { content: '', done: false };
    }
回答关注问题邀请回答
收藏

1 个回答

  • 社区技术运营专员--Demons
    社区技术运营专员--Demons
    02-10

    请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。

    02-10
    有用
    回复 1
    • 味蕾
      味蕾
      2天前
      你们自己跑个demo不就知道了,3.7.4的基础库就说修复了,修复了什么?真的抽象
      2天前
      回复
登录 后发表内容