update:使用标准化SSE统一进度推送逻辑
This commit is contained in:
@@ -7,7 +7,7 @@ import json
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from app.database import get_db
|
||||
from app.utils.sse_response import SSEResponse, create_sse_response
|
||||
from app.utils.sse_response import SSEResponse, create_sse_response, WizardProgressTracker
|
||||
from app.models.character import Character
|
||||
from app.models.project import Project
|
||||
from app.models.generation_history import GenerationHistory
|
||||
@@ -660,15 +660,16 @@ async def generate_character_stream(
|
||||
通过Server-Sent Events返回实时进度信息
|
||||
"""
|
||||
async def generate() -> AsyncGenerator[str, None]:
|
||||
tracker = WizardProgressTracker("角色")
|
||||
try:
|
||||
# 验证用户权限和项目是否存在
|
||||
user_id = getattr(http_request.state, 'user_id', None)
|
||||
project = await verify_project_access(request.project_id, user_id, db)
|
||||
|
||||
yield await SSEResponse.send_progress("开始生成角色...", 1)
|
||||
yield await tracker.start()
|
||||
|
||||
# 获取已存在的角色列表
|
||||
yield await SSEResponse.send_progress("获取项目上下文...", 2)
|
||||
yield await tracker.loading("获取项目上下文...", 0.3)
|
||||
|
||||
existing_chars_result = await db.execute(
|
||||
select(Character)
|
||||
@@ -760,7 +761,8 @@ async def generate_character_stream(
|
||||
- 其他要求:{request.requirements or '无'}
|
||||
"""
|
||||
|
||||
yield await SSEResponse.send_progress("构建AI提示词...", 3)
|
||||
yield await tracker.loading("项目上下文准备完成", 0.7)
|
||||
yield await tracker.preparing("构建AI提示词...")
|
||||
|
||||
# 获取自定义提示词模板
|
||||
template = await PromptService.get_template("SINGLE_CHARACTER_GENERATION", user_id, db)
|
||||
@@ -771,16 +773,17 @@ async def generate_character_stream(
|
||||
user_input=user_input
|
||||
)
|
||||
|
||||
yield await SSEResponse.send_progress("调用AI服务生成角色...", 10)
|
||||
yield await tracker.generating(0, max(3000, len(prompt) * 8), "调用AI服务生成角色...")
|
||||
logger.info(f"🎯 开始为项目 {request.project_id} 生成角色(SSE流式)")
|
||||
|
||||
try:
|
||||
# 直接使用 AIService 流式生成
|
||||
ai_response = ""
|
||||
chunk_count = 0
|
||||
estimated_total = max(3000, len(prompt) * 8)
|
||||
|
||||
logger.info(f"🎯 开始生成角色(流式模式)...")
|
||||
yield await SSEResponse.send_progress("🎯 开始生成角色...", 15)
|
||||
yield await tracker.generating(0, estimated_total, "开始生成角色...")
|
||||
|
||||
async for chunk in user_ai_service.generate_text_stream(
|
||||
prompt=prompt,
|
||||
@@ -802,29 +805,22 @@ async def generate_character_stream(
|
||||
current_len = len(ai_response)
|
||||
if current_len >= chunk_count * 500:
|
||||
chunk_count += 1
|
||||
# 使用实际字符数量计算进度,上限85%(留15%给后续解析和保存)
|
||||
# 估算最终字符数约为提示词的8倍,最少3000字符
|
||||
estimated_total = max(3000, len(prompt) * 8)
|
||||
progress = min(15 + int(current_len / estimated_total * 70), 85)
|
||||
yield await SSEResponse.send_progress(
|
||||
f"AI生成角色中... ({current_len}字符)",
|
||||
progress
|
||||
)
|
||||
yield await tracker.generating(current_len, estimated_total)
|
||||
|
||||
# 心跳
|
||||
if chunk_count % 20 == 0:
|
||||
yield await SSEResponse.send_heartbeat()
|
||||
yield await tracker.heartbeat()
|
||||
|
||||
except Exception as ai_error:
|
||||
logger.error(f"❌ AI服务调用异常:{str(ai_error)}")
|
||||
yield await SSEResponse.send_error(f"AI服务调用失败:{str(ai_error)}")
|
||||
yield await tracker.error(f"AI服务调用失败:{str(ai_error)}")
|
||||
return
|
||||
|
||||
if not ai_response or not ai_response.strip():
|
||||
yield await SSEResponse.send_error("AI服务返回空响应")
|
||||
yield await tracker.error("AI服务返回空响应")
|
||||
return
|
||||
|
||||
yield await SSEResponse.send_progress("解析AI响应...", 96)
|
||||
yield await tracker.parsing("解析AI响应...", 0.5)
|
||||
|
||||
# ✅ 使用统一的 JSON 清洗方法
|
||||
try:
|
||||
@@ -834,10 +830,10 @@ async def generate_character_stream(
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"❌ 角色JSON解析失败: {e}")
|
||||
logger.error(f" 原始响应预览: {ai_response[:200]}")
|
||||
yield await SSEResponse.send_error(f"AI返回的内容无法解析为JSON:{str(e)}")
|
||||
yield await tracker.error(f"AI返回的内容无法解析为JSON:{str(e)}")
|
||||
return
|
||||
|
||||
yield await SSEResponse.send_progress("创建角色记录...", 97)
|
||||
yield await tracker.saving("创建角色记录...", 0.3)
|
||||
|
||||
# 转换traits
|
||||
traits_json = json.dumps(character_data.get("traits", []), ensure_ascii=False) if character_data.get("traits") else None
|
||||
@@ -1002,7 +998,7 @@ async def generate_character_stream(
|
||||
|
||||
# 如果是组织,创建Organization详情
|
||||
if is_organization:
|
||||
yield await SSEResponse.send_progress("创建组织详情...", 98)
|
||||
yield await tracker.saving("创建组织详情...", 0.6)
|
||||
|
||||
org_check = await db.execute(
|
||||
select(Organization).where(Organization.character_id == character.id)
|
||||
@@ -1169,7 +1165,7 @@ async def generate_character_stream(
|
||||
|
||||
logger.info(f"✅ 成功创建 {created_members} 条组织成员记录")
|
||||
|
||||
yield await SSEResponse.send_progress("保存生成历史...", 99)
|
||||
yield await tracker.saving("保存生成历史...", 0.9)
|
||||
|
||||
# 记录生成历史
|
||||
history = GenerationHistory(
|
||||
@@ -1185,10 +1181,10 @@ async def generate_character_stream(
|
||||
|
||||
logger.info(f"🎉 成功生成角色: {character.name}")
|
||||
|
||||
yield await SSEResponse.send_progress("角色生成完成!", 100, "success")
|
||||
yield await tracker.complete("角色生成完成!")
|
||||
|
||||
# 发送结果数据
|
||||
yield await SSEResponse.send_result({
|
||||
yield await tracker.result({
|
||||
"character": {
|
||||
"id": character.id,
|
||||
"name": character.name,
|
||||
@@ -1197,14 +1193,14 @@ async def generate_character_stream(
|
||||
}
|
||||
})
|
||||
|
||||
yield await SSEResponse.send_done()
|
||||
yield await tracker.done()
|
||||
|
||||
except HTTPException as he:
|
||||
logger.error(f"HTTP异常: {he.detail}")
|
||||
yield await SSEResponse.send_error(he.detail, he.status_code)
|
||||
yield await tracker.error(he.detail, he.status_code)
|
||||
except Exception as e:
|
||||
logger.error(f"生成角色失败: {str(e)}")
|
||||
yield await SSEResponse.send_error(f"生成角色失败: {str(e)}")
|
||||
yield await tracker.error(f"生成角色失败: {str(e)}")
|
||||
|
||||
return create_sse_response(generate())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user