BotSharp/src/Plugins/BotSharp.Plugin.ChatHub/Hooks/StreamingLogHook.cs

72 lines
2.8 KiB
C#
Raw Normal View History

2024-01-10 14:18:59 +00:00
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Loggers;
2024-01-19 04:38:44 +00:00
using BotSharp.Abstraction.Loggers.Models;
2024-01-10 14:18:59 +00:00
using Microsoft.AspNetCore.SignalR;
namespace BotSharp.Plugin.ChatHub.Hooks;
public class StreamingLogHook : IContentGeneratingHook
{
private readonly ConversationSetting _convSettings;
private readonly IServiceProvider _services;
private readonly IHubContext<SignalRHub> _chatHub;
2024-01-19 04:38:44 +00:00
private readonly JsonSerializerOptions _serializerOptions;
2024-01-10 14:18:59 +00:00
public StreamingLogHook(
ConversationSetting convSettings,
IServiceProvider serivces,
IHubContext<SignalRHub> chatHub)
{
_convSettings = convSettings;
_services = serivces;
_chatHub = chatHub;
2024-01-19 04:38:44 +00:00
_serializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
AllowTrailingCommas = true
};
2024-01-10 14:18:59 +00:00
}
public async Task BeforeGenerating(Agent agent, List<RoleDialogModel> conversations)
{
if (!_convSettings.ShowVerboseLog) return;
var user = _services.GetRequiredService<IUserIdentity>();
2024-01-19 04:38:44 +00:00
var states = _services.GetRequiredService<IConversationStateService>();
var conversationId = states.GetConversationId();
2024-01-10 14:18:59 +00:00
var dialog = conversations.Last();
var log = $"{dialog.Role}: {dialog.Content} [msg_id: {dialog.MessageId}] ==>";
2024-01-19 04:38:44 +00:00
await _chatHub.Clients.User(user.Id).SendAsync("OnContentLogGenerated", BuildLog(conversationId, log));
2024-01-10 14:18:59 +00:00
}
public async Task AfterGenerated(RoleDialogModel message, TokenStatsModel tokenStats)
{
if (!_convSettings.ShowVerboseLog) return;
var agentService = _services.GetRequiredService<IAgentService>();
2024-01-19 04:38:44 +00:00
var states = _services.GetRequiredService<IConversationStateService>();
var conversationId = states.GetConversationId();
2024-01-10 14:18:59 +00:00
var agent = await agentService.LoadAgent(message.CurrentAgentId);
var log = message.Role == AgentRole.Function ?
$"[{agent?.Name}]: {message.FunctionName}({message.FunctionArgs})" :
$"[{agent?.Name}]: {message.Content}" + $" <== [msg_id: {message.MessageId}]";
var user = _services.GetRequiredService<IUserIdentity>();
2024-01-19 04:38:44 +00:00
await _chatHub.Clients.User(user.Id).SendAsync("OnContentLogGenerated", BuildLog(conversationId, tokenStats.Prompt));
await _chatHub.Clients.User(user.Id).SendAsync("OnContentLogGenerated", BuildLog(conversationId, log));
}
private string BuildLog(string conversationId, string content)
{
var log = new StreamingLogModel
{
ConversationId = conversationId,
Content = content,
CreateTime = DateTime.UtcNow
};
return JsonSerializer.Serialize(log, _serializerOptions);
2024-01-10 14:18:59 +00:00
}
}