using System.Text;
using Dpz.Core.Service.Network;
using Dpz.Core.Service.Network.Models;
using Dpz.Core.Service.RepositoryService;
using JetBrains.Annotations;
using Medallion.Threading;
using Microsoft.Extensions.Logging;
namespace Dpz.Core.Hangfire;
[UsedImplicitly]
public class AnalyzeChatActivator(
IAiChatService aiChatService,
ChatCompletionService chatCompletionService,
IDistributedLockProvider distributedLockProvider,
ILogger<AnalyzeChatActivator> logger
)
{
/// <summary>
/// analyze
/// </summary>
[ProlongExpirationTime]
public async Task<string?> AnalyzeAsync(
string userId,
string sessionId,
string questionContent,
string answerContent,
string modelType
)
{
string? sessionName = null;
var lockKey = $"AI_Analyze.Chat.Lock:{userId}_{sessionId}";
try
{
await using (await distributedLockProvider.AcquireLockAsync(lockKey))
{
var prompt = new StringBuilder("问:")
.AppendLine()
.AppendLine(questionContent)
.AppendLine()
.AppendLine("------")
.AppendLine()
.AppendLine("答:")
.AppendLine()
.AppendLine(answerContent)
.AppendLine()
.AppendLine("------")
.AppendLine()
.AppendLine("请给以上对话简单总结出一个标题")
.ToString();
var message = new ChatMessage { Role = "user", Message = prompt };
var result = await chatCompletionService.SendChatAsync(
[message],
x => x.Stream = false
);
if (result is { Success: true, Data: not null, Data.Choices.Count: > 0 })
{
sessionName = result.Data.Choices[0].Message.Content;
await aiChatService.CreateSessionAsync(
userId,
sessionId,
sessionName,
modelType
);
}
}
}
catch (Exception e)
{
logger.LogError(
e,
"Analyze chat failed. UserId: {UserId}, SessionId: {SessionId}",
userId,
sessionId
);
}
return sessionName;
}
}