BotSharp/src/Infrastructure/BotSharp.Core/Conversations/Services/ConversationStateService.cs

363 lines
12 KiB
C#
Raw Normal View History

2024-04-02 16:38:18 +00:00
using BotSharp.Abstraction.Conversations.Enums;
2024-03-27 18:50:27 +00:00
using BotSharp.Abstraction.Users.Enums;
2024-03-26 21:57:13 +00:00
2023-08-09 21:49:55 +00:00
namespace BotSharp.Core.Conversations.Services;
/// <summary>
/// Maintain the conversation state
/// </summary>
public class ConversationStateService : IConversationStateService, IDisposable
{
2023-08-14 17:00:01 +00:00
private readonly ILogger _logger;
private readonly IServiceProvider _services;
2023-09-06 03:39:56 +00:00
private readonly IBotSharpRepository _db;
2024-04-03 17:12:31 +00:00
private string _conversationId;
/// <summary>
/// States in the current round of conversation
/// </summary>
private ConversationState _curStates;
/// <summary>
/// States in the previous rounds of conversation
/// </summary>
private ConversationState _historyStates;
2023-08-09 21:49:55 +00:00
2023-08-14 17:00:01 +00:00
public ConversationStateService(ILogger<ConversationStateService> logger,
2024-01-01 04:56:10 +00:00
IServiceProvider services,
2023-08-28 18:57:51 +00:00
IBotSharpRepository db)
2023-08-09 21:49:55 +00:00
{
2023-08-14 17:00:01 +00:00
_logger = logger;
_services = services;
2023-09-06 03:39:56 +00:00
_db = db;
2024-04-03 17:12:31 +00:00
_curStates = new ConversationState();
_historyStates = new ConversationState();
2023-08-09 21:49:55 +00:00
}
public string GetConversationId() => _conversationId;
2024-01-01 04:56:10 +00:00
/// <summary>
/// Set conversation state
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="isNeedVersion">whether the state is related to message or not</param>
2024-01-01 04:56:10 +00:00
/// <returns></returns>
2024-04-02 16:38:18 +00:00
public IConversationStateService SetState<T>(string name, T value, bool isNeedVersion = true,
2024-04-02 20:39:14 +00:00
int activeRounds = -1, string valueType = StateDataType.String, string source = StateSource.User, bool readOnly = false)
2023-08-09 21:49:55 +00:00
{
2023-09-18 08:35:02 +00:00
if (value == null)
{
return this;
}
2024-01-02 17:40:08 +00:00
var preValue = string.Empty;
2023-09-18 08:35:02 +00:00
var currentValue = value.ToString();
2023-08-14 17:00:01 +00:00
var hooks = _services.GetServices<IConversationHook>();
2024-03-31 03:43:45 +00:00
var curActiveRounds = activeRounds > 0 ? activeRounds : -1;
int? preActiveRounds = null;
2024-01-01 04:56:10 +00:00
2024-04-03 17:12:31 +00:00
if (ContainsState(name) && _curStates.TryGetValue(name, out var pair))
2024-01-02 17:40:08 +00:00
{
2024-04-08 14:58:25 +00:00
var leafNode = pair?.Values?.LastOrDefault();
preActiveRounds = leafNode?.ActiveRounds;
preValue = leafNode?.Data ?? string.Empty;
2024-01-02 17:40:08 +00:00
}
2024-03-29 21:37:35 +00:00
_logger.LogInformation($"[STATE] {name} = {value}");
var routingCtx = _services.GetRequiredService<IRoutingContext>();
2024-03-28 18:16:16 +00:00
2024-04-02 16:38:18 +00:00
if (!ContainsState(name) || preValue != currentValue || preActiveRounds != curActiveRounds)
2024-03-29 21:37:35 +00:00
{
2024-04-02 16:38:18 +00:00
foreach (var hook in hooks)
2023-08-14 17:00:01 +00:00
{
2024-04-02 16:38:18 +00:00
hook.OnStateChanged(new StateChangeModel
{
ConversationId = _conversationId,
MessageId = routingCtx.MessageId,
Name = name,
BeforeValue = preValue,
BeforeActiveRounds = preActiveRounds,
AfterValue = currentValue,
2024-04-02 19:09:42 +00:00
AfterActiveRounds = curActiveRounds,
DataType = valueType,
2024-04-02 20:39:14 +00:00
Source = source,
Readonly = readOnly
2024-04-02 16:38:18 +00:00
}).Wait();
}
2024-03-29 21:37:35 +00:00
}
2024-03-26 21:57:13 +00:00
2024-03-29 21:37:35 +00:00
var newPair = new StateKeyValue
{
Key = name,
2024-04-02 20:39:14 +00:00
Versioning = isNeedVersion,
Readonly = readOnly
2024-03-29 21:37:35 +00:00
};
var newValue = new StateValue
{
Data = currentValue,
MessageId = routingCtx.MessageId,
Active = true,
2024-03-31 03:43:45 +00:00
ActiveRounds = curActiveRounds,
2024-04-02 16:38:18 +00:00
DataType = valueType,
Source = source,
2024-03-29 21:37:35 +00:00
UpdateTime = DateTime.UtcNow,
};
2024-04-03 17:12:31 +00:00
if (!isNeedVersion || !_curStates.ContainsKey(name))
2024-03-29 21:37:35 +00:00
{
newPair.Values = new List<StateValue> { newValue };
2024-04-03 17:12:31 +00:00
_curStates[name] = newPair;
2024-03-29 21:37:35 +00:00
}
else
{
2024-04-03 17:12:31 +00:00
_curStates[name].Values.Add(newValue);
2023-08-14 17:00:01 +00:00
}
2023-09-14 16:42:48 +00:00
return this;
2023-08-09 21:49:55 +00:00
}
2024-04-10 17:45:35 +00:00
public Dictionary<string, string> Load(string conversationId, bool isReadOnly = false)
2023-08-09 21:49:55 +00:00
{
2024-04-10 17:45:35 +00:00
_conversationId = !isReadOnly ? conversationId : null;
2023-08-09 21:49:55 +00:00
2024-03-27 18:50:27 +00:00
var routingCtx = _services.GetRequiredService<IRoutingContext>();
var curMsgId = routingCtx.MessageId;
2024-04-03 17:12:31 +00:00
2024-04-10 17:49:12 +00:00
_historyStates = _db.GetConversationStates(conversationId);
var dialogs = _db.GetConversationDialogs(conversationId);
2024-03-27 18:50:27 +00:00
var userDialogs = dialogs.Where(x => x.MetaData?.Role == AgentRole.User || x.MetaData?.Role == UserRole.Client)
2024-04-16 19:31:51 +00:00
.GroupBy(x => x.MetaData?.MessageId)
.Select(g => g.First())
2024-03-27 18:50:27 +00:00
.OrderBy(x => x.MetaData?.CreateTime)
.ToList();
var curMsgIndex = userDialogs.FindIndex(x => !string.IsNullOrEmpty(curMsgId) && x.MetaData?.MessageId == curMsgId);
curMsgIndex = curMsgIndex < 0 ? userDialogs.Count() : curMsgIndex;
2023-08-09 21:49:55 +00:00
2024-04-03 17:12:31 +00:00
var endNodes = new Dictionary<string, string>();
if (_historyStates.IsNullOrEmpty()) return endNodes;
foreach (var state in _historyStates)
2023-08-09 21:49:55 +00:00
{
2024-04-03 17:12:31 +00:00
var key = state.Key;
var value = state.Value;
2024-04-08 14:58:25 +00:00
var leafNode = value?.Values?.LastOrDefault();
2024-04-03 17:12:31 +00:00
if (leafNode == null) continue;
_curStates[key] = new StateKeyValue
2023-08-09 21:49:55 +00:00
{
2024-04-03 17:12:31 +00:00
Key = key,
Versioning = value.Versioning,
Readonly = value.Readonly,
Values = new List<StateValue> { leafNode }
};
if (!leafNode.Active) continue;
2024-03-26 21:57:13 +00:00
2024-04-03 17:12:31 +00:00
// Handle state active rounds
if (leafNode.ActiveRounds > 0)
{
var stateMsgIndex = userDialogs.FindIndex(x => !string.IsNullOrEmpty(x.MetaData?.MessageId) && x.MetaData.MessageId == leafNode.MessageId);
if (stateMsgIndex >= 0 && curMsgIndex - stateMsgIndex >= leafNode.ActiveRounds)
2024-03-27 18:50:27 +00:00
{
2024-04-03 17:12:31 +00:00
_curStates[key].Values.Add(new StateValue
2024-03-27 18:50:27 +00:00
{
2024-04-03 17:12:31 +00:00
Data = leafNode.Data,
MessageId = curMsgId,
Active = false,
ActiveRounds = leafNode.ActiveRounds,
DataType = leafNode.DataType,
Source = leafNode.Source,
UpdateTime = DateTime.UtcNow
});
continue;
2024-03-27 18:50:27 +00:00
}
2023-08-09 21:49:55 +00:00
}
2024-04-03 17:12:31 +00:00
var data = leafNode.Data ?? string.Empty;
endNodes[state.Key] = data;
_logger.LogInformation($"[STATE] {key} : {data}");
2023-08-09 21:49:55 +00:00
}
2024-04-10 17:49:12 +00:00
_logger.LogInformation($"Loaded conversation states: {conversationId}");
2023-08-14 17:00:01 +00:00
var hooks = _services.GetServices<IConversationHook>();
foreach (var hook in hooks)
{
2024-04-03 17:12:31 +00:00
hook.OnStateLoaded(_curStates).Wait();
2023-08-14 17:00:01 +00:00
}
2024-04-03 17:12:31 +00:00
return endNodes;
2023-08-09 21:49:55 +00:00
}
public void Save()
{
2023-09-03 22:53:36 +00:00
if (_conversationId == null)
{
return;
}
2024-01-02 17:40:08 +00:00
var states = new List<StateKeyValue>();
2023-08-28 18:57:51 +00:00
2024-04-03 17:12:31 +00:00
foreach (var pair in _curStates)
2023-08-09 21:49:55 +00:00
{
2024-04-03 17:12:31 +00:00
var key = pair.Key;
var curValue = pair.Value;
2024-04-07 18:37:16 +00:00
if (!_historyStates.TryGetValue(key, out var historyValue)
|| historyValue == null
|| historyValue.Values.IsNullOrEmpty()
2024-04-03 17:12:31 +00:00
|| !curValue.Versioning)
{
states.Add(curValue);
}
else
{
var historyValues = historyValue.Values.Take(historyValue.Values.Count - 1).ToList();
var newValues = historyValues.Concat(curValue.Values).ToList();
var updatedNode = new StateKeyValue
{
Key = pair.Key,
Versioning = curValue.Versioning,
Readonly = curValue.Readonly,
Values = newValues
};
states.Add(updatedNode);
}
2023-08-09 21:49:55 +00:00
}
2023-08-28 18:57:51 +00:00
2024-01-02 17:40:08 +00:00
_db.UpdateConversationStates(_conversationId, states);
2024-01-01 04:56:10 +00:00
_logger.LogInformation($"Saved states of conversation {_conversationId}");
2023-08-09 21:49:55 +00:00
}
2024-04-03 17:12:31 +00:00
public bool RemoveState(string name)
{
if (!ContainsState(name)) return false;
var routingCtx = _services.GetRequiredService<IRoutingContext>();
2024-04-07 18:37:16 +00:00
var value = _curStates[name];
var leafNode = value?.Values?.LastOrDefault();
if (value == null || !value.Versioning || leafNode == null) return false;
2024-04-03 17:12:31 +00:00
_curStates[name].Values.Add(new StateValue
{
Data = leafNode.Data,
MessageId = routingCtx.MessageId,
Active = false,
ActiveRounds = leafNode.ActiveRounds,
DataType = leafNode.DataType,
Source = leafNode.Source,
UpdateTime = DateTime.UtcNow
});
2024-04-07 18:37:16 +00:00
var hooks = _services.GetServices<IConversationHook>();
foreach (var hook in hooks)
{
hook.OnStateChanged(new StateChangeModel
{
ConversationId = _conversationId,
MessageId = routingCtx.MessageId,
Name = name,
BeforeValue = leafNode.Data,
BeforeActiveRounds = leafNode.ActiveRounds,
AfterValue = null,
AfterActiveRounds = leafNode.ActiveRounds,
DataType = leafNode.DataType,
Source = leafNode.Source,
2024-04-08 14:58:25 +00:00
Readonly = value.Readonly
2024-04-07 18:37:16 +00:00
}).Wait();
}
2024-04-03 17:12:31 +00:00
return true;
}
2024-03-24 13:56:21 +00:00
public void CleanStates()
2023-08-15 15:41:34 +00:00
{
2024-03-28 03:21:34 +00:00
var routingCtx = _services.GetRequiredService<IRoutingContext>();
var curMsgId = routingCtx.MessageId;
2024-03-26 21:57:13 +00:00
var utcNow = DateTime.UtcNow;
2024-03-28 03:21:34 +00:00
2024-04-03 17:12:31 +00:00
foreach (var key in _curStates.Keys)
2024-03-26 21:57:13 +00:00
{
2024-04-03 17:12:31 +00:00
var value = _curStates[key];
2024-03-26 21:57:13 +00:00
if (value == null || !value.Versioning || value.Values.IsNullOrEmpty()) continue;
2024-04-03 17:12:31 +00:00
var leafNode = value.Values.LastOrDefault();
if (leafNode == null || !leafNode.Active) continue;
2024-03-26 21:57:13 +00:00
2024-03-26 22:09:49 +00:00
value.Values.Add(new StateValue
{
2024-04-03 17:12:31 +00:00
Data = leafNode.Data,
2024-03-28 15:32:09 +00:00
MessageId = curMsgId,
2024-03-26 22:09:49 +00:00
Active = false,
2024-04-03 17:12:31 +00:00
ActiveRounds = leafNode.ActiveRounds,
DataType = leafNode.DataType,
Source = leafNode.Source,
2024-03-26 22:09:49 +00:00
UpdateTime = utcNow
});
2024-03-26 21:57:13 +00:00
}
2023-08-15 15:41:34 +00:00
}
2024-01-02 17:40:08 +00:00
public Dictionary<string, string> GetStates()
{
2024-04-03 17:12:31 +00:00
var endNodes = new Dictionary<string, string>();
foreach (var state in _curStates)
2024-01-02 17:40:08 +00:00
{
2024-03-26 21:57:13 +00:00
var value = state.Value?.Values?.LastOrDefault();
if (value == null || !value.Active) continue;
2024-04-03 17:12:31 +00:00
endNodes[state.Key] = value.Data ?? string.Empty;
2024-01-02 17:40:08 +00:00
}
2024-04-03 17:12:31 +00:00
return endNodes;
2024-01-02 17:40:08 +00:00
}
2023-09-06 03:19:36 +00:00
2023-09-14 01:41:51 +00:00
public string GetState(string name, string defaultValue = "")
2023-08-09 21:49:55 +00:00
{
2024-04-03 17:12:31 +00:00
if (!_curStates.ContainsKey(name) || _curStates[name].Values.IsNullOrEmpty() || !_curStates[name].Values.Last().Active)
2023-09-14 16:42:48 +00:00
{
return defaultValue;
}
2024-04-03 17:12:31 +00:00
return _curStates[name].Values.Last().Data;
2023-08-09 21:49:55 +00:00
}
2023-08-14 17:00:01 +00:00
public void Dispose()
{
2024-04-10 17:47:51 +00:00
Save();
2023-08-14 17:00:01 +00:00
}
2023-09-25 22:46:00 +00:00
public bool ContainsState(string name)
{
2024-04-03 17:12:31 +00:00
return _curStates.ContainsKey(name)
&& !_curStates[name].Values.IsNullOrEmpty()
&& _curStates[name].Values.LastOrDefault()?.Active == true
&& !string.IsNullOrEmpty(_curStates[name].Values.Last().Data);
2023-09-25 22:46:00 +00:00
}
2023-11-01 01:48:12 +00:00
public void SaveStateByArgs(JsonDocument args)
{
if (args == null)
{
return;
}
if (args.RootElement is JsonElement root)
{
foreach (JsonProperty property in root.EnumerateObject())
{
2024-04-16 19:48:55 +00:00
var propertyValue = property.Value;
var stateValue = propertyValue.ToString();
2024-04-16 19:31:51 +00:00
if (!string.IsNullOrEmpty(stateValue))
2023-11-01 01:48:12 +00:00
{
2024-04-16 19:48:55 +00:00
if (propertyValue.ValueKind == JsonValueKind.True ||
propertyValue.ValueKind == JsonValueKind.False)
2024-04-16 19:31:51 +00:00
{
stateValue = stateValue?.ToLower();
}
SetState(property.Name, stateValue, source: StateSource.Application);
2023-11-01 01:48:12 +00:00
}
}
}
}
2023-08-09 21:49:55 +00:00
}