2023-08-17 04:04:23 +00:00
|
|
|
using BotSharp.Abstraction.Agents.Models;
|
2023-06-27 18:31:13 +00:00
|
|
|
using BotSharp.Abstraction.Conversations.Models;
|
2023-07-30 18:22:07 +00:00
|
|
|
using BotSharp.Abstraction.Functions;
|
2023-06-27 18:31:13 +00:00
|
|
|
using BotSharp.Abstraction.MLTasks;
|
2023-06-03 02:07:30 +00:00
|
|
|
|
2023-06-12 13:28:49 +00:00
|
|
|
namespace BotSharp.Core.Conversations.Services;
|
2023-06-03 02:07:30 +00:00
|
|
|
|
|
|
|
|
public class ConversationService : IConversationService
|
|
|
|
|
{
|
2023-08-09 21:49:55 +00:00
|
|
|
private readonly ILogger _logger;
|
2023-06-27 18:31:13 +00:00
|
|
|
private readonly IServiceProvider _services;
|
|
|
|
|
private readonly IUserIdentity _user;
|
|
|
|
|
private readonly ConversationSetting _settings;
|
|
|
|
|
private readonly IConversationStorage _storage;
|
2023-06-03 02:07:30 +00:00
|
|
|
|
2023-08-17 04:04:23 +00:00
|
|
|
public ConversationService(IServiceProvider services,
|
2023-06-27 18:31:13 +00:00
|
|
|
IUserIdentity user,
|
|
|
|
|
ConversationSetting settings,
|
2023-08-09 21:49:55 +00:00
|
|
|
IConversationStorage storage,
|
|
|
|
|
ILogger<ConversationService> logger)
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
2023-06-27 18:31:13 +00:00
|
|
|
_services = services;
|
|
|
|
|
_user = user;
|
|
|
|
|
_settings = settings;
|
|
|
|
|
_storage = storage;
|
2023-08-09 21:49:55 +00:00
|
|
|
_logger = logger;
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public Task DeleteConversation(string id)
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
2023-06-27 18:31:13 +00:00
|
|
|
throw new NotImplementedException();
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-07-19 22:30:23 +00:00
|
|
|
public async Task<Conversation> GetConversation(string id)
|
|
|
|
|
{
|
2023-08-10 04:53:22 +00:00
|
|
|
var db = _services.GetRequiredService<IBotSharpRepository>();
|
2023-07-19 22:30:23 +00:00
|
|
|
var query = from sess in db.Conversation
|
|
|
|
|
where sess.Id == id
|
|
|
|
|
orderby sess.CreatedTime descending
|
|
|
|
|
select sess.ToConversation();
|
|
|
|
|
return query.FirstOrDefault();
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public async Task<List<Conversation>> GetConversations()
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
2023-08-10 04:53:22 +00:00
|
|
|
var db = _services.GetRequiredService<IBotSharpRepository>();
|
2023-06-27 18:31:13 +00:00
|
|
|
var query = from sess in db.Conversation
|
|
|
|
|
where sess.UserId == _user.Id
|
|
|
|
|
orderby sess.CreatedTime descending
|
|
|
|
|
select sess.ToConversation();
|
|
|
|
|
return query.ToList();
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public async Task<Conversation> NewConversation(Conversation sess)
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
2023-08-10 04:53:22 +00:00
|
|
|
var db = _services.GetRequiredService<IBotSharpRepository>();
|
2023-06-27 18:31:13 +00:00
|
|
|
|
|
|
|
|
var record = ConversationRecord.FromConversation(sess);
|
2023-07-21 15:15:30 +00:00
|
|
|
record.Id = sess.Id.IfNullOrEmptyAs(Guid.NewGuid().ToString());
|
|
|
|
|
record.UserId = sess.UserId.IfNullOrEmptyAs(_user.Id);
|
2023-06-27 18:31:13 +00:00
|
|
|
record.Title = "New Conversation";
|
|
|
|
|
|
2023-07-21 21:56:14 +00:00
|
|
|
db.Transaction<IBotSharpTable>(delegate
|
2023-06-27 18:31:13 +00:00
|
|
|
{
|
2023-07-21 21:56:14 +00:00
|
|
|
db.Add<IBotSharpTable>(record);
|
2023-06-27 18:31:13 +00:00
|
|
|
});
|
|
|
|
|
|
2023-08-09 21:49:55 +00:00
|
|
|
_storage.InitStorage(record.Id);
|
2023-06-27 18:31:13 +00:00
|
|
|
|
|
|
|
|
return record.ToConversation();
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-08-17 04:04:23 +00:00
|
|
|
public async Task<bool> SendMessage(string agentId, string conversationId,
|
2023-08-18 04:27:07 +00:00
|
|
|
RoleDialogModel lastDialog,
|
2023-08-17 04:04:23 +00:00
|
|
|
Func<RoleDialogModel, Task> onMessageReceived,
|
2023-08-07 17:48:09 +00:00
|
|
|
Func<RoleDialogModel, Task> onFunctionExecuting)
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
2023-07-19 22:30:23 +00:00
|
|
|
var converation = await GetConversation(conversationId);
|
2023-06-29 23:14:57 +00:00
|
|
|
|
2023-08-10 22:17:55 +00:00
|
|
|
// Create conversation if this conversation not exists
|
|
|
|
|
if (converation == null)
|
|
|
|
|
{
|
|
|
|
|
var sess = new Conversation
|
|
|
|
|
{
|
|
|
|
|
Id = conversationId,
|
|
|
|
|
AgentId = agentId
|
|
|
|
|
};
|
|
|
|
|
converation = await NewConversation(sess);
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-14 17:00:01 +00:00
|
|
|
// conversation state
|
2023-08-09 21:49:55 +00:00
|
|
|
var stateService = _services.GetRequiredService<IConversationStateService>();
|
2023-08-14 17:00:01 +00:00
|
|
|
stateService.SetConversation(conversationId);
|
|
|
|
|
stateService.Load();
|
2023-08-15 15:41:34 +00:00
|
|
|
|
2023-08-17 04:04:23 +00:00
|
|
|
var router = _services.GetRequiredService<IAgentRouting>();
|
|
|
|
|
var agent = await router.LoadCurrentAgent();
|
2023-08-15 15:41:34 +00:00
|
|
|
|
2023-08-19 00:15:50 +00:00
|
|
|
_logger.LogInformation($"[{agent.Name}] {lastDialog.Role}: {lastDialog.Content}");
|
|
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
lastDialog.CurrentAgentId = agent.Id;
|
2023-08-19 00:15:50 +00:00
|
|
|
_storage.Append(conversationId, agent.Id, lastDialog);
|
2023-08-18 04:27:07 +00:00
|
|
|
|
|
|
|
|
var wholeDialogs = GetDialogHistory(conversationId);
|
|
|
|
|
|
2023-06-29 23:14:57 +00:00
|
|
|
// Get relevant domain knowledge
|
2023-08-14 17:00:01 +00:00
|
|
|
/*if (_settings.EnableKnowledgeBase)
|
2023-06-29 23:14:57 +00:00
|
|
|
{
|
|
|
|
|
var knowledge = _services.GetRequiredService<IKnowledgeService>();
|
|
|
|
|
agent.Knowledges = await knowledge.GetKnowledges(new KnowledgeRetrievalModel
|
|
|
|
|
{
|
|
|
|
|
AgentId = agentId,
|
2023-07-21 20:15:09 +00:00
|
|
|
Question = string.Join("\n", wholeDialogs.Select(x => x.Content))
|
2023-06-29 23:14:57 +00:00
|
|
|
});
|
2023-08-14 17:00:01 +00:00
|
|
|
}*/
|
2023-06-29 23:14:57 +00:00
|
|
|
|
2023-08-14 17:00:01 +00:00
|
|
|
var hooks = _services.GetServices<IConversationHook>().ToList();
|
2023-07-19 12:08:40 +00:00
|
|
|
|
2023-07-27 21:56:57 +00:00
|
|
|
// Before chat completion hook
|
|
|
|
|
foreach (var hook in hooks)
|
2023-07-19 22:30:23 +00:00
|
|
|
{
|
2023-08-09 21:49:55 +00:00
|
|
|
hook.SetAgent(agent)
|
2023-08-14 17:00:01 +00:00
|
|
|
.SetConversation(converation);
|
2023-08-09 21:49:55 +00:00
|
|
|
|
2023-08-14 17:00:01 +00:00
|
|
|
await hook.OnDialogsLoaded(wholeDialogs);
|
2023-08-09 21:49:55 +00:00
|
|
|
await hook.BeforeCompletion();
|
2023-07-27 21:56:57 +00:00
|
|
|
}
|
|
|
|
|
|
2023-08-14 22:14:05 +00:00
|
|
|
var chatCompletion = GetChatCompletion();
|
2023-08-18 04:27:07 +00:00
|
|
|
var result = await GetChatCompletionsAsyncRecursively(chatCompletion,
|
|
|
|
|
conversationId,
|
|
|
|
|
agent,
|
|
|
|
|
wholeDialogs,
|
|
|
|
|
onMessageReceived,
|
|
|
|
|
onFunctionExecuting);
|
2023-08-17 04:04:23 +00:00
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
private async Task<bool> GetChatCompletionsAsyncRecursively(IChatCompletion chatCompletion,
|
|
|
|
|
string conversationId,
|
|
|
|
|
Agent agent,
|
|
|
|
|
List<RoleDialogModel> wholeDialogs,
|
2023-08-17 04:04:23 +00:00
|
|
|
Func<RoleDialogModel, Task> onMessageReceived,
|
|
|
|
|
Func<RoleDialogModel, Task> onFunctionExecuting)
|
|
|
|
|
{
|
2023-08-18 04:27:07 +00:00
|
|
|
var result = await chatCompletion.GetChatCompletionsAsync(agent, wholeDialogs, async msg =>
|
2023-08-17 04:04:23 +00:00
|
|
|
{
|
2023-08-18 04:27:07 +00:00
|
|
|
await HandleAssistantMessage(msg, onMessageReceived);
|
2023-08-14 22:14:05 +00:00
|
|
|
|
2023-08-17 04:04:23 +00:00
|
|
|
// Add to dialog history
|
2023-08-19 00:15:50 +00:00
|
|
|
_storage.Append(conversationId, agent.Id, msg);
|
2023-08-18 04:27:07 +00:00
|
|
|
}, async fn =>
|
2023-08-17 04:04:23 +00:00
|
|
|
{
|
2023-08-18 04:27:07 +00:00
|
|
|
var preAgentId = agent.Id;
|
2023-08-15 15:41:34 +00:00
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
await HandleFunctionMessage(fn, onFunctionExecuting);
|
|
|
|
|
|
2023-08-19 00:15:50 +00:00
|
|
|
fn.Content = fn.ExecutionResult;
|
|
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
// Agent has been transferred
|
|
|
|
|
if (fn.CurrentAgentId != preAgentId)
|
2023-08-15 15:41:34 +00:00
|
|
|
{
|
2023-08-19 00:15:50 +00:00
|
|
|
var agentSettings = _services.GetRequiredService<AgentSettings>();
|
2023-08-18 04:27:07 +00:00
|
|
|
var agentService = _services.GetRequiredService<IAgentService>();
|
|
|
|
|
agent = await agentService.LoadAgent(fn.CurrentAgentId);
|
|
|
|
|
|
|
|
|
|
// Set state to make next conversation will go to this agent directly
|
2023-08-19 00:15:50 +00:00
|
|
|
// var state = _services.GetRequiredService<IConversationStateService>();
|
|
|
|
|
// state.SetState("agentId", fn.CurrentAgentId);
|
2023-08-15 15:41:34 +00:00
|
|
|
}
|
2023-07-19 12:08:40 +00:00
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
// Add to dialog history
|
2023-08-19 00:15:50 +00:00
|
|
|
_storage.Append(conversationId, preAgentId, fn);
|
2023-08-18 04:27:07 +00:00
|
|
|
|
|
|
|
|
// After function is executed, pass the result to LLM to get a natural response
|
|
|
|
|
wholeDialogs.Add(fn);
|
|
|
|
|
|
|
|
|
|
await GetChatCompletionsAsyncRecursively(chatCompletion, conversationId, agent, wholeDialogs, onMessageReceived, onFunctionExecuting);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return result;
|
2023-08-17 04:04:23 +00:00
|
|
|
}
|
|
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
private async Task HandleAssistantMessage(RoleDialogModel msg, Func<RoleDialogModel, Task> onMessageReceived)
|
2023-08-17 04:04:23 +00:00
|
|
|
{
|
2023-08-18 04:27:07 +00:00
|
|
|
var hooks = _services.GetServices<IConversationHook>().ToList();
|
|
|
|
|
|
|
|
|
|
// After chat completion hook
|
|
|
|
|
foreach (var hook in hooks)
|
2023-08-17 04:04:23 +00:00
|
|
|
{
|
2023-08-18 04:27:07 +00:00
|
|
|
await hook.AfterCompletion(msg);
|
|
|
|
|
}
|
2023-08-17 04:04:23 +00:00
|
|
|
|
2023-08-18 04:27:07 +00:00
|
|
|
await onMessageReceived(msg);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task HandleFunctionMessage(RoleDialogModel msg, Func<RoleDialogModel, Task> onFunctionExecuting)
|
|
|
|
|
{
|
|
|
|
|
// Save states
|
|
|
|
|
SaveStateByArgs(msg.FunctionArgs);
|
|
|
|
|
|
|
|
|
|
// Call functions
|
|
|
|
|
await onFunctionExecuting(msg);
|
|
|
|
|
await CallFunctions(msg);
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-08-14 22:14:05 +00:00
|
|
|
private void SaveStateByArgs(string args)
|
|
|
|
|
{
|
|
|
|
|
var stateService = _services.GetRequiredService<IConversationStateService>();
|
|
|
|
|
var jo = JsonSerializer.Deserialize<object>(args);
|
|
|
|
|
if (jo is JsonElement root)
|
|
|
|
|
{
|
|
|
|
|
foreach (JsonProperty property in root.EnumerateObject())
|
|
|
|
|
{
|
|
|
|
|
stateService.SetState(property.Name, property.Value.ToString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-17 04:04:23 +00:00
|
|
|
private async Task CallFunctions(RoleDialogModel msg)
|
2023-08-14 22:14:05 +00:00
|
|
|
{
|
|
|
|
|
var hooks = _services.GetServices<IConversationHook>().ToList();
|
|
|
|
|
|
|
|
|
|
// Invoke functions
|
|
|
|
|
var functions = _services.GetServices<IFunctionCallback>()
|
|
|
|
|
.Where(x => x.Name == msg.FunctionName)
|
|
|
|
|
.ToList();
|
|
|
|
|
|
2023-08-17 04:04:23 +00:00
|
|
|
if (functions.Count == 0)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError($"Can't find function implementation of {msg.FunctionName}.");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-14 22:14:05 +00:00
|
|
|
foreach (var fn in functions)
|
|
|
|
|
{
|
|
|
|
|
// Before executing functions
|
|
|
|
|
foreach (var hook in hooks)
|
|
|
|
|
{
|
|
|
|
|
await hook.OnFunctionExecuting(msg);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Execute function
|
|
|
|
|
await fn.Execute(msg);
|
|
|
|
|
|
|
|
|
|
// After functions have been executed
|
|
|
|
|
foreach (var hook in hooks)
|
|
|
|
|
{
|
|
|
|
|
await hook.OnFunctionExecuted(msg);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public IChatCompletion GetChatCompletion()
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
2023-06-27 18:31:13 +00:00
|
|
|
var completions = _services.GetServices<IChatCompletion>();
|
2023-06-27 19:17:53 +00:00
|
|
|
return completions.FirstOrDefault(x => x.GetType().FullName.EndsWith(_settings.ChatCompletion));
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public Task CleanHistory(string agentId)
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
|
|
|
|
throw new NotImplementedException();
|
|
|
|
|
}
|
2023-06-27 18:31:13 +00:00
|
|
|
|
2023-08-09 21:49:55 +00:00
|
|
|
public List<RoleDialogModel> GetDialogHistory(string conversationId, int lastCount = 20)
|
2023-06-27 18:31:13 +00:00
|
|
|
{
|
2023-08-09 21:49:55 +00:00
|
|
|
var dialogs = _storage.GetDialogs(conversationId);
|
2023-08-14 22:14:05 +00:00
|
|
|
return dialogs
|
|
|
|
|
.Where(x => x.CreatedAt > DateTime.UtcNow.AddHours(-8))
|
|
|
|
|
.TakeLast(lastCount).ToList();
|
2023-06-27 18:31:13 +00:00
|
|
|
}
|
2023-06-03 02:07:30 +00:00
|
|
|
}
|