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

242 lines
9.8 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-02-28 16:21:14 +00:00
using BotSharp.Abstraction.Routing;
2024-01-10 14:18:59 +00:00
using Microsoft.AspNetCore.SignalR;
namespace BotSharp.Plugin.ChatHub.Hooks;
2024-02-28 16:21:14 +00:00
public class StreamingLogHook : ConversationHookBase, IContentGeneratingHook, IRoutingHook
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-02-28 16:21:14 +00:00
private string _messageId;
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)
{
2024-02-28 16:21:14 +00:00
_messageId = message.MessageId;
2024-01-24 23:47:57 +00:00
var conversationId = _state.GetConversationId();
2024-02-28 16:21:14 +00:00
var log = $"{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
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
2024-02-28 16:21:14 +00:00
var json = JsonSerializer.Serialize(log, _serializerOptions);
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-02-28 16:21:14 +00:00
return json;
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-02-28 16:21:14 +00:00
#region IRoutingHook
public async Task OnAgentEnqueued(string agentId, string preAgentId)
{
var conversationId = _state.GetConversationId();
var agent = await _agentService.LoadAgent(agentId);
var preAgent = await _agentService.LoadAgent(preAgentId);
var log = $"{agent.Name} is enqueued";
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, preAgent.Name, log, ContentLogSource.HardRule, new RoleDialogModel(AgentRole.System, log)
{
MessageId = _messageId
}));
}
public async Task OnAgentDequeued(string agentId, string currentAgentId)
{
var conversationId = _state.GetConversationId();
var agent = await _agentService.LoadAgent(agentId);
var currentAgent = await _agentService.LoadAgent(currentAgentId);
var log = $"{agent.Name} is dequeued";
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
2024-02-28 16:34:08 +00:00
BuildContentLog(conversationId, agent.Name, log, ContentLogSource.HardRule, new RoleDialogModel(AgentRole.System, log)
2024-02-28 16:21:14 +00:00
{
MessageId = _messageId
}));
}
public async Task OnAgentReplaced(string fromAgentId, string toAgentId)
{
var conversationId = _state.GetConversationId();
var fromAgent = await _agentService.LoadAgent(fromAgentId);
var toAgent = await _agentService.LoadAgent(toAgentId);
var log = $"{fromAgent.Name} is replaced to {toAgent.Name}";
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, toAgent.Name, log, ContentLogSource.HardRule, new RoleDialogModel(AgentRole.System, log)
{
MessageId = _messageId
}));
}
public async Task OnAgentQueueEmptied(string agentId)
{
var conversationId = _state.GetConversationId();
var agent = await _agentService.LoadAgent(agentId);
var log = $"Agent queue is cleared.";
await _chatHub.Clients.User(_user.Id).SendAsync("OnConversationContentLogGenerated",
BuildContentLog(conversationId, agent.Name, log, ContentLogSource.HardRule, new RoleDialogModel(AgentRole.System, log)
{
MessageId = _messageId
}));
}
public 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));
}
public async Task OnConversationRedirected(string toAgentId, RoleDialogModel message)
{
var conversationId = _state.GetConversationId();
var fromAgent = await _agentService.LoadAgent(message.CurrentAgentId);
var toAgent = await _agentService.LoadAgent(toAgentId);
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));
}
#endregion
2024-01-10 14:18:59 +00:00
}