流式生成会员周度总结API文档

本文档描述了如何使用流式生成会员周度总结API调用AI生成会员最近一周的数据变化总结和专业建议,并以流式方式实时返回生成的内容。

API概述

流式生成会员周度总结API提供了调用AI分析会员最近一周(或指定时间段)的数据变化,并生成专业教练建议的功能,同时以流式方式实时返回生成的内容,提供更好的用户体验。这些数据包括体重变化、训练记录、阶段进度等,AI会根据会员的健身目的提供针对性的分析和建议。

接口详情

流式生成会员周度总结

POST /gym/member/stream_weekly_summary

调用AI生成指定会员的周度数据变化总结和专业建议,并以流式方式实时返回生成的内容。

请求参数

参数名 类型 必填 描述
member_id Integer 会员ID,如果不提供则使用当前登录用户关联的会员
start_date String 开始日期,格式为'YYYY-MM-DD',默认为一周前
end_date String 结束日期,格式为'YYYY-MM-DD',默认为今天

响应格式

API返回Server-Sent Events (SSE)格式的流式数据,每个事件包含以下JSON数据:

{
    "text": "生成的文本块",  // 生成的文本块,如果为空字符串且done为true,表示生成完成
    "done": true/false     // 可选,如果为true,表示生成完成
}

错误码说明

错误码 描述
400 请求参数错误,如当前用户未关联会员
404 未找到指定会员
500 服务器内部错误

示例请求

POST /gym/member/stream_weekly_summary
Content-Type: application/json

{
    "member_id": 123,
    "start_date": "2025-03-23",
    "end_date": "2025-03-30"
}

使用说明

调用此API后,服务器会以流式方式实时返回AI生成的内容,客户端可以逐块显示这些内容,提供更好的用户体验。服务器会分析指定时间段内会员的各项数据变化,并使用AI生成专业的教练建议。这些数据包括:

AI会根据会员的健身目的(如减脂、增肌、塑形等)提供针对性的分析和建议,帮助会员更好地了解自己的训练效果和改进方向。

使用示例

JavaScript示例(使用EventSource)

// 使用EventSource接收流式数据
function streamWeeklySummary(memberId, startDate, endDate, accessToken) {
    // 创建结果容器
    const resultContainer = document.getElementById('result-container');
    resultContainer.innerHTML = '';
    
    // 完整的总结内容
    let fullSummary = '';
    
    // 创建EventSource
    const url = `/gym/member/stream_weekly_summary?member_id=${memberId}&start_date=${startDate}&end_date=${endDate}&access_token=${accessToken}`;
    const eventSource = new EventSource(url);
    
    // 处理消息
    eventSource.onmessage = function(event) {
        try {
            const data = JSON.parse(event.data);
            
            // 检查是否完成
            if (data.done === true) {
                console.log('生成完成');
                eventSource.close();
                return;
            }
            
            // 检查是否有错误
            if (data.error) {
                console.error('生成错误:', data.error);
                resultContainer.innerHTML += `

${data.error}

`; eventSource.close(); return; } // 显示文本块 if (data.text) { fullSummary += data.text; resultContainer.innerHTML = fullSummary.replace(/\n/g, '
'); // 滚动到底部 resultContainer.scrollTop = resultContainer.scrollHeight; } } catch (e) { console.error('解析事件数据出错:', e); } }; // 处理错误 eventSource.onerror = function(error) { console.error('EventSource错误:', error); resultContainer.innerHTML += '

连接错误,请重试

'; eventSource.close(); }; } // 调用示例 streamWeeklySummary( 123, // 会员ID '2025-03-23', // 开始日期 '2025-03-30', // 结束日期 'your-access-token' // 访问令牌 );

使用fetch API的替代方法

// 使用fetch API接收流式数据
async function streamWeeklySummaryWithFetch(memberId, startDate, endDate, accessToken) {
    // 创建结果容器
    const resultContainer = document.getElementById('result-container');
    resultContainer.innerHTML = '';
    
    // 完整的总结内容
    let fullSummary = '';
    
    try {
        // 发送请求
        const response = await fetch(`/gym/member/stream_weekly_summary`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + accessToken
            },
            body: JSON.stringify({
                member_id: memberId,
                start_date: startDate,
                end_date: endDate
            })
        });
        
        // 获取reader
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        // 读取数据
        while (true) {
            const { value, done } = await reader.read();
            
            if (done) {
                console.log('流读取完成');
                break;
            }
            
            // 解码数据
            const chunk = decoder.decode(value, { stream: true });
            
            // 处理SSE格式的数据
            const lines = chunk.split('\n\n');
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    try {
                        const data = JSON.parse(line.substring(6));
                        
                        // 检查是否有错误
                        if (data.error) {
                            console.error('生成错误:', data.error);
                            resultContainer.innerHTML += `

${data.error}

`; return; } // 检查是否完成 if (data.done === true) { console.log('生成完成'); return; } // 显示文本块 if (data.text) { fullSummary += data.text; resultContainer.innerHTML = fullSummary.replace(/\n/g, '
'); // 滚动到底部 resultContainer.scrollTop = resultContainer.scrollHeight; } } catch (e) { console.error('解析事件数据出错:', e); } } } } } catch (error) { console.error('请求出错:', error); resultContainer.innerHTML += '

连接错误,请重试

'; } }

Python示例

import requests
import json
import sseclient  # 需要安装 sseclient-py 包

def stream_weekly_summary(member_id=None, start_date=None, end_date=None, access_token=None):
    """
    流式生成会员周度总结
    
    Args:
        member_id: 会员ID,如果不提供则使用当前登录用户关联的会员
        start_date: 开始日期,格式为'YYYY-MM-DD',默认为一周前
        end_date: 结束日期,格式为'YYYY-MM-DD',默认为今天
        access_token: 访问令牌
    """
    url = 'http://your-domain.com/gym/member/stream_weekly_summary'
    
    headers = {
        'Accept': 'text/event-stream',
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }
    
    data = {}
    if member_id:
        data['member_id'] = member_id
    if start_date:
        data['start_date'] = start_date
    if end_date:
        data['end_date'] = end_date
    
    # 发送请求
    response = requests.post(url, json=data, headers=headers, stream=True)
    
    # 创建SSE客户端
    client = sseclient.SSEClient(response)
    
    # 完整的总结内容
    full_summary = ''
    
    # 处理事件
    try:
        for event in client.events():
            try:
                data = json.loads(event.data)
                
                # 检查是否有错误
                if 'error' in data:
                    print(f"生成错误: {data['error']}")
                    break
                
                # 检查是否完成
                if data.get('done', False):
                    print("生成完成")
                    break
                
                # 显示文本块
                if 'text' in data and data['text']:
                    full_summary += data['text']
                    print(data['text'], end='', flush=True)
                    
            except json.JSONDecodeError:
                print(f"解析事件数据出错: {event.data}")
                
    except Exception as e:
        print(f"流处理错误: {str(e)}")
    
    return full_summary

# 调用示例
try:
    summary = stream_weekly_summary(
        member_id=123,
        start_date='2025-03-23',
        end_date='2025-03-30',
        access_token='your-access-token'
    )
    
    print(f"\n完整总结:\n{summary}")
    
except Exception as e:
    print(f"流式生成会员周度总结失败: {str(e)}")