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

180 lines
7.3 KiB
C#
Raw Normal View History

2024-01-10 14:18:59 +00:00
using BotSharp.Abstraction.Agents.Models;
2024-02-20 23:13:44 +00:00
using BotSharp.Abstraction.Functions.Models;
2024-01-10 14:18:59 +00:00
using BotSharp.Abstraction.Loggers;
2024-02-22 17:25:13 +00:00
using BotSharp.Abstraction.Loggers.Enums;
2024-01-19 04:38:44 +00:00
using BotSharp.Abstraction.Loggers.Models;
2024-02-15 20:43:36 +00:00
using BotSharp.Abstraction.Repositories;
2024-01-10 14:18:59 +00:00
using Microsoft.AspNetCore.SignalR;
namespace BotSharp.Plugin.ChatHub.Hooks;
2024-01-24 23:47:57 +00:00
public class StreamingLogHook : ConversationHookBase, IContentGeneratingHook
2024-01-10 14:18:59 +00:00
{
private readonly ConversationSetting _convSettings;
2024-01-24 23:47:57 +00:00
private readonly JsonSerializerOptions _serializerOptions;
2024-01-10 14:18:59 +00:00
private readonly IServiceProvider _services;
private readonly IHubContext<SignalRHub> _chatHub;
2024-01-24 23:47:57 +00:00
private readonly IConversationStateService _state;
private readonly IUserIdentity _user;
2024-02-23 01:53:00 +00:00
private readonly IAgentService _agentService;
2024-01-10 14:18:59 +00:00
public StreamingLogHook(
ConversationSetting convSettings,
IServiceProvider serivces,
2024-01-24 23:47:57 +00:00
IHubContext<SignalRHub> chatHub,
IConversationStateService state,
2024-02-23 01:53:00 +00:00
IUserIdentity user,
IAgentService agentService)
2024-01-10 14:18:59 +00:00
{
_convSettings = convSettings;
_services = serivces;
_chatHub = chatHub;
2024-01-24 23:47:57 +00:00
_state = state;
_user = user;
2024-02-23 01:53:00 +00:00
_agentService = agentService;
2024-01-19 04:38:44 +00:00
_serializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
2024-02-23 01:53:00 +00:00
AllowTrailingCommas = true,
WriteIndented = true
2024-01-19 04:38:44 +00:00
};
2024-01-10 14:18:59 +00:00
}
2024-02-22 17:25:13 +00:00
2024-01-24 23:47:57 +00:00
public override async Task OnMessageReceived(RoleDialogModel message)
{
var conversationId = _state.GetConversationId();
2024-02-27 13:19:05 +00:00
var log = $"{message.Role}: {message.Content}";
2024-02-22 17:25:13 +00:00
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, _user.UserName, log, ContentLogSource.UserInput, message));
2024-01-24 23:47:57 +00:00
}
2024-01-10 14:18:59 +00:00
2024-02-23 01:53:00 +00:00
public override async Task OnConversationRouting(FunctionCallFromLlm instruct, RoleDialogModel message)
{
var conversationId = _state.GetConversationId();
var agent = await _agentService.LoadAgent(message.CurrentAgentId);
var log = JsonSerializer.Serialize(instruct, _serializerOptions);
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, agent?.Name, log, ContentLogSource.AgentResponse, message));
}
2024-02-22 21:14:13 +00:00
public override async Task OnConversationRedirected(string toAgentId, RoleDialogModel message)
{
var conversationId = _state.GetConversationId();
2024-02-23 01:53:00 +00:00
var fromAgent = await _agentService.LoadAgent(message.CurrentAgentId);
var toAgent = await _agentService.LoadAgent(toAgentId);
2024-02-22 21:14:13 +00:00
var log = $"{message.Content}\r\n=====\r\nREDIRECTED TO {toAgent.Name}";
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, fromAgent.Name, log, ContentLogSource.HardRule, message));
}
2024-01-10 14:18:59 +00:00
public async Task BeforeGenerating(Agent agent, List<RoleDialogModel> conversations)
{
if (!_convSettings.ShowVerboseLog) return;
2024-01-24 23:47:57 +00:00
/*var _state = _services.GetRequiredService<IConversationStateService>();
var conversationId = _state.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-24 23:47:57 +00:00
await _chatHub.Clients.User(_user.Id).SendAsync("OnContentLogGenerated", BuildLog(conversationId, log));*/
}
public override async Task OnFunctionExecuted(RoleDialogModel message)
{
2024-02-20 20:37:32 +00:00
var conversationId = _state.GetConversationId();
2024-02-23 01:53:00 +00:00
var agent = await _agentService.LoadAgent(message.CurrentAgentId);
var log = $"{message.FunctionName}({message.FunctionArgs})\r\n => {message.Content}";
2024-02-22 17:25:13 +00:00
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, agent?.Name, log, ContentLogSource.FunctionCall, message));
2024-01-10 14:18:59 +00:00
}
2024-02-20 20:37:32 +00:00
/// <summary>
/// Used to log prompt
/// </summary>
/// <param name="message"></param>
/// <param name="tokenStats"></param>
/// <returns></returns>
2024-01-10 14:18:59 +00:00
public async Task AfterGenerated(RoleDialogModel message, TokenStatsModel tokenStats)
{
if (!_convSettings.ShowVerboseLog) return;
2024-01-24 23:47:57 +00:00
var conversationId = _state.GetConversationId();
2024-02-23 01:53:00 +00:00
var agent = await _agentService.LoadAgent(message.CurrentAgentId);
2024-02-22 17:25:13 +00:00
var logSource = string.Empty;
2024-01-10 14:18:59 +00:00
2024-02-22 21:14:13 +00:00
var log = tokenStats.Prompt;
logSource = ContentLogSource.Prompt;
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, agent?.Name, log, logSource, message));
2024-01-19 04:38:44 +00:00
}
2024-02-20 20:37:32 +00:00
/// <summary>
/// Used to log final response
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
2024-02-16 21:58:39 +00:00
public override async Task OnResponseGenerated(RoleDialogModel message)
{
var conv = _services.GetRequiredService<IConversationService>();
2024-02-23 01:53:00 +00:00
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversateStateLogGenerated", BuildStateLog(conv.ConversationId, _state.GetStates(), message));
2024-02-20 20:37:32 +00:00
if (message.Role == AgentRole.Assistant)
{
2024-02-23 01:53:00 +00:00
var agent = await _agentService.LoadAgent(message.CurrentAgentId);
2024-02-22 21:14:13 +00:00
var log = $"{message.Content}";
2024-02-20 20:38:49 +00:00
if (message.RichContent != null && message.RichContent.Message.RichType != "text")
2024-02-20 20:37:32 +00:00
{
2024-02-20 20:38:49 +00:00
var richContent = JsonSerializer.Serialize(message.RichContent, _serializerOptions);
log += $"\r\n{richContent}";
2024-02-20 20:37:32 +00:00
}
2024-02-22 17:25:13 +00:00
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conv.ConversationId, agent?.Name, log, ContentLogSource.AgentResponse, message));
2024-02-20 20:37:32 +00:00
}
2024-02-16 21:58:39 +00:00
}
2024-02-22 17:25:13 +00:00
private string BuildContentLog(string conversationId, string? name, string logContent, string logSource, RoleDialogModel message)
2024-01-19 04:38:44 +00:00
{
2024-02-15 20:43:36 +00:00
var log = new ConversationContentLogModel
2024-01-19 04:38:44 +00:00
{
ConversationId = conversationId,
2024-02-15 20:43:36 +00:00
MessageId = message.MessageId,
2024-01-26 21:47:06 +00:00
Name = name,
2024-02-15 20:43:36 +00:00
Role = message.Role,
2024-02-22 17:25:13 +00:00
Content = logContent,
Source = logSource,
2024-01-19 04:38:44 +00:00
CreateTime = DateTime.UtcNow
};
2024-02-15 20:43:36 +00:00
var convSettings = _services.GetRequiredService<ConversationSetting>();
if (convSettings.EnableContentLog)
{
var db = _services.GetRequiredService<IBotSharpRepository>();
db.SaveConversationContentLog(log);
}
2024-01-19 04:38:44 +00:00
return JsonSerializer.Serialize(log, _serializerOptions);
2024-01-10 14:18:59 +00:00
}
2024-02-16 21:58:39 +00:00
private string BuildStateLog(string conversationId, Dictionary<string, string> states, RoleDialogModel message)
{
var log = new ConversationStateLogModel
{
ConversationId = conversationId,
MessageId = message.MessageId,
States = states,
CreateTime = DateTime.UtcNow
};
var convSettings = _services.GetRequiredService<ConversationSetting>();
if (convSettings.EnableStateLog)
{
var db = _services.GetRequiredService<IBotSharpRepository>();
db.SaveConversationStateLog(log);
}
return JsonSerializer.Serialize(log, _serializerOptions);
}
2024-01-10 14:18:59 +00:00
}