refactor: 重构AI聊天服务为流式返回,优化OOS路径与仓库初始化逻辑

1. 重构AI聊天接口与实现为流式返回,支持SSE协议
2. 修正BaseRepository的数据库上下文初始化逻辑
3. 更新AutoDotCodeConsumer的OOS存储路径
4. 新增阿里云OSS配置项到appsettings
5. 优化AiChatService的日志与代码注释
This commit is contained in:
glz
2026-06-24 18:25:25 +08:00
parent bf333cd718
commit 3c3453668f
6 changed files with 94 additions and 49 deletions

View File

@ -1,8 +1,8 @@
using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Enum;
using System.Text.Json;
namespace QYZH.InteractiveMagazine.WebApi.Controllers;
@ -24,27 +24,39 @@ public class AiChatController : BaseController
}
/// <summary>
/// AI聊天根据需求生成提示词
/// AI聊天(流式返回),根据需求生成提示词
/// </summary>
/// <param name="input">用户需求消息</param>
/// <returns>AI生成的提示词Markdown格式</returns>
/// <returns>SSE流逐块返回AI生成的提示词内容</returns>
[HttpPost]
public async Task<BaseResponse<AiChatOutput>> ChatAsync([FromBody] AiChatInput input)
public async Task ChatAsync([FromBody] AiChatInput input)
{
Response.ContentType = "text/event-stream";
Response.Headers.Append("Cache-Control", "no-cache");
Response.Headers.Append("Connection", "keep-alive");
try
{
var result = await _aiChatService.ChatAsync(input);
return Success(result, "AI聊天成功");
await foreach (var chunk in _aiChatService.ChatAsync(input, HttpContext.RequestAborted))
{
var data = JsonSerializer.Serialize(new { content = chunk });
await Response.WriteAsync($"data: {data}\n\n");
await Response.Body.FlushAsync();
}
await Response.WriteAsync("data: [DONE]\n\n");
await Response.Body.FlushAsync();
}
catch (BusinessException ex)
catch (OperationCanceledException)
{
_logger.LogWarning(ex, "AI聊天业务异常: {Message}", ex.Message);
return BaseResponse<AiChatOutput>.Fail(ex.Message);
_logger.LogInformation("客户端断开连接AI聊天流式返回终止");
}
catch (Exception ex)
{
_logger.LogError(ex, "AI聊天系统异常,参数:{Input}", input);
return BaseResponse<AiChatOutput>.Fail("AI聊天失败请稍后重试");
_logger.LogError(ex, "AI聊天流式返回异常,参数:{Input}", input);
var errorData = JsonSerializer.Serialize(new { error = "AI聊天失败请稍后重试" });
await Response.WriteAsync($"data: {errorData}\n\n");
await Response.Body.FlushAsync();
}
}
}