[update] Non empty code style constraint (default value constraint), unified optimization of the CreatedTime field and MongoDBContext methods;

This commit is contained in:
chait 2025-02-13 11:25:32 +08:00
parent 3624ec84a1
commit 513007b7ce
47 changed files with 231 additions and 254 deletions

View file

@ -16,10 +16,10 @@ public class Conversation
public string TitleAlias { get; set; } = string.Empty;
[JsonIgnore]
public List<DialogElement> Dialogs { get; set; } = new();
public List<DialogElement> Dialogs { get; set; } = [];
[JsonIgnore]
public Dictionary<string, string> States { get; set; } = new();
public Dictionary<string, string> States { get; set; } = [];
public string Status { get; set; } = ConversationStatus.Open;
@ -28,11 +28,11 @@ public class Conversation
/// <summary>
/// Channel id, like phone number, email address, etc.
/// </summary>
public string ChannelId { get; set; }
public string ChannelId { get; set; } = default!;
public int DialogCount { get; set; }
public List<string> Tags { get; set; } = new();
public List<string> Tags { get; set; } = [];
public DateTime UpdatedTime { get; set; } = DateTime.UtcNow;
public DateTime CreatedTime { get; set; } = DateTime.UtcNow;
@ -41,10 +41,10 @@ public class Conversation
public class DialogElement
{
[JsonPropertyName("meta_data")]
public DialogMetaData MetaData { get; set; }
public DialogMetaData MetaData { get; set; } = new();
[JsonPropertyName("content")]
public string Content { get; set; }
public string Content { get; set; } = default!;
[JsonPropertyName("secondary_content")]
public string? SecondaryContent { get; set; }
@ -76,23 +76,23 @@ public class DialogElement
public override string ToString()
{
return $"{MetaData.Role}: {Content} [{MetaData?.CreateTime}]";
return $"{MetaData.Role}: {Content} [{MetaData?.CreatedTime}]";
}
}
public class DialogMetaData
{
[JsonPropertyName("role")]
public string Role { get; set; }
public string Role { get; set; } = default!;
[JsonPropertyName("agent_id")]
public string AgentId { get; set; }
public string AgentId { get; set; } = default!;
[JsonPropertyName("message_id")]
public string MessageId { get; set; }
public string MessageId { get; set; } = default!;
[JsonPropertyName("message_type")]
public string MessageType { get; set; }
public string MessageType { get; set; } = default!;
[JsonPropertyName("function_name")]
public string? FunctionName { get; set; }
@ -101,5 +101,5 @@ public class DialogMetaData
public string? SenderId { get; set; }
[JsonPropertyName("create_at")]
public DateTime CreateTime { get; set; }
public DateTime CreatedTime { get; set; }
}

View file

@ -15,6 +15,6 @@ public class DashboardComponent
public class DashboardConversation : DashboardComponent
{
public string? ConversationId { get; set; }
public string? Instruction { get; set; } = "";
public string? Instruction { get; set; }
}

View file

@ -151,7 +151,7 @@ public class ConversationStateService : IConversationStateService, IDisposable
var userDialogs = dialogs.Where(x => x.MetaData?.Role == AgentRole.User)
.GroupBy(x => x.MetaData?.MessageId)
.Select(g => g.First())
.OrderBy(x => x.MetaData?.CreateTime)
.OrderBy(x => x.MetaData?.CreatedTime)
.ToList();
var curMsgIndex = userDialogs.FindIndex(x => !string.IsNullOrEmpty(curMsgId) && x.MetaData?.MessageId == curMsgId);
curMsgIndex = curMsgIndex < 0 ? userDialogs.Count() : curMsgIndex;

View file

@ -39,7 +39,7 @@ public class ConversationStorage : IConversationStorage
MessageId = dialog.MessageId,
MessageType = dialog.MessageType,
FunctionName = dialog.FunctionName,
CreateTime = dialog.CreatedAt
CreatedTime = dialog.CreatedAt
};
var content = dialog.Content.RemoveNewLine();
@ -65,7 +65,7 @@ public class ConversationStorage : IConversationStorage
MessageType = dialog.MessageType,
SenderId = dialog.SenderId,
FunctionName = dialog.FunctionName,
CreateTime = dialog.CreatedAt
CreatedTime = dialog.CreatedAt
};
var content = dialog.Content.RemoveNewLine();
@ -108,7 +108,7 @@ public class ConversationStorage : IConversationStorage
MessageId = dialog.MessageId,
MessageType = dialog.MessageType,
FunctionName = dialog.FunctionName,
CreateTime = dialog.CreatedAt
CreatedTime = dialog.CreatedAt
};
var content = dialog.Content.RemoveNewLine();
@ -134,7 +134,7 @@ public class ConversationStorage : IConversationStorage
MessageType = dialog.MessageType,
SenderId = dialog.SenderId,
FunctionName = dialog.FunctionName,
CreateTime = dialog.CreatedAt
CreatedTime = dialog.CreatedAt
};
var content = dialog.Content.RemoveNewLine();
@ -179,7 +179,7 @@ public class ConversationStorage : IConversationStorage
var messageType = meta.MessageType;
var function = meta.FunctionName;
var senderId = role == AgentRole.Function ? currentAgentId : meta.SenderId;
var createdAt = meta.CreateTime;
var createdAt = meta.CreatedTime;
var richContent = !string.IsNullOrEmpty(dialog.RichContent) ?
JsonSerializer.Deserialize<RichContent<IRichMessage>>(dialog.RichContent, _options.JsonSerializerOptions) : null;
var secondaryRichContent = !string.IsNullOrEmpty(dialog.SecondaryRichContent) ?

View file

@ -583,7 +583,7 @@ public partial class FileRepository
var isSaved = HandleTruncatedDialogs(convDir, dialogDir, dialogs, foundIdx);
// Handle truncated states
var refTime = dialogs.ElementAt(foundIdx).MetaData.CreateTime;
var refTime = dialogs.ElementAt(foundIdx).MetaData.CreatedTime;
var stateDir = Path.Combine(convDir, STATE_FILE);
var states = CollectConversationStates(stateDir);
isSaved = HandleTruncatedStates(stateDir, states, messageId, refTime);

View file

@ -50,7 +50,7 @@ public partial class FileRepository
return Users.FirstOrDefault(x => x.Phone == phone && x.Type == UserType.Affiliate);
}
public User? GetUserById(string id = null)
public User? GetUserById(string? id = null)
{
return Users.FirstOrDefault(x => x.Id == id || (x.ExternalId != null && x.ExternalId == id));
}
@ -65,12 +65,12 @@ public partial class FileRepository
return Users.Where(x => x.AffiliateId == affiliateId).ToList();
}
public User? GetUserByUserName(string userName = null)
public User? GetUserByUserName(string? userName = null)
{
return Users.FirstOrDefault(x => x.UserName == userName.ToLower());
}
public Dashboard? GetDashboard(string userId = null)
public Dashboard? GetDashboard(string? userId = null)
{
return Dashboards.FirstOrDefault();
}
@ -97,6 +97,8 @@ public partial class FileRepository
public void UpdateUserVerified(string userId)
{
var user = GetUserById(userId);
if (user == null) return;
user.Verified = true;
var dir = Path.Combine(_dbSettings.FileRepository, USERS_FOLDER, user.Id);
var path = Path.Combine(dir, USER_FILE);
@ -147,7 +149,7 @@ public partial class FileRepository
public List<User> SearchLoginUsers(User filter, string source = UserSource.Internal)
{
List<User> searchResult = new List<User>();
List<User> searchResult = [];
// search by filters
if (!string.IsNullOrWhiteSpace(filter.Id))
@ -183,7 +185,7 @@ public partial class FileRepository
else if (!string.IsNullOrWhiteSpace(filter.Email))
{
var curUser = Users.AsQueryable().FirstOrDefault(x => x.Source == source && x.Email == filter.Email.ToString());
User user = curUser != null ? curUser : null;
User? user = curUser != null ? curUser : null;
if (user != null)
{
searchResult.Add(user);
@ -194,7 +196,7 @@ public partial class FileRepository
if (searchResult.Count == 0 && !string.IsNullOrWhiteSpace(filter.UserName))
{
var curUser = Users.AsQueryable().FirstOrDefault(x => x.Source == source && x.UserName == filter.UserName);
User user = curUser != null ? curUser : null;
User? user = curUser != null ? curUser : null;
if (user != null)
{
searchResult.Add(user);

View file

@ -2,27 +2,27 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class AgentDocument : MongoBase
{
public string Name { get; set; }
public string Description { get; set; }
public string Type { get; set; }
public string Name { get; set; } = default!;
public string Description { get; set; } = default!;
public string Type { get; set; } = default!;
public string? InheritAgentId { get; set; }
public string? IconUrl { get; set; }
public string Instruction { get; set; }
public string Instruction { get; set; } = default!;
public bool IsPublic { get; set; }
public bool Disabled { get; set; }
public bool MergeUtility { get; set; }
public int? MaxMessageCount { get; set; }
public List<ChannelInstructionMongoElement> ChannelInstructions { get; set; }
public List<AgentTemplateMongoElement> Templates { get; set; }
public List<FunctionDefMongoElement> Functions { get; set; }
public List<AgentResponseMongoElement> Responses { get; set; }
public List<string> Samples { get; set; }
public List<AgentUtilityMongoElement> Utilities { get; set; }
public List<AgentKnowledgeBaseMongoElement> KnowledgeBases { get; set; }
public List<string> Profiles { get; set; }
public List<string> Labels { get; set; }
public List<RoutingRuleMongoElement> RoutingRules { get; set; }
public List<AgentRuleMongoElement> Rules { get; set; }
public List<ChannelInstructionMongoElement> ChannelInstructions { get; set; } = [];
public List<AgentTemplateMongoElement> Templates { get; set; } = [];
public List<FunctionDefMongoElement> Functions { get; set; } = [];
public List<AgentResponseMongoElement> Responses { get; set; } = [];
public List<string> Samples { get; set; } = [];
public List<AgentUtilityMongoElement> Utilities { get; set; } = [];
public List<AgentKnowledgeBaseMongoElement> KnowledgeBases { get; set; } = [];
public List<string> Profiles { get; set; } = [];
public List<string> Labels { get; set; } = [];
public List<RoutingRuleMongoElement> RoutingRules { get; set; } = [];
public List<AgentRuleMongoElement> Rules { get; set; } = [];
public AgentLlmConfigMongoElement? LlmConfig { get; set; }
public DateTime CreatedTime { get; set; }

View file

@ -4,12 +4,12 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class AgentTaskDocument : MongoBase
{
public string Name { get; set; }
public string Name { get; set; } = default!;
public string? Description { get; set; }
public string Content { get; set; }
public string Content { get; set; } = default!;
public bool Enabled { get; set; }
public string AgentId { get; set; }
public string Status { get; set; }
public string AgentId { get; set; } = default!;
public string Status { get; set; } = default!;
public DateTime CreatedTime { get; set; }
public DateTime UpdatedTime { get; set; }

View file

@ -2,12 +2,12 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class ConversationContentLogDocument : MongoBase
{
public string ConversationId { get; set; }
public string MessageId { get; set; }
public string ConversationId { get; set; } = default!;
public string MessageId { get; set; } = default!;
public string? Name { get; set; }
public string? AgentId { get; set; }
public string Role { get; set; }
public string Source { get; set; }
public string Content { get; set; }
public DateTime CreateTime { get; set; }
public string Role { get; set; } = default!;
public string Source { get; set; } = default!;
public string Content { get; set; } = default!;
public DateTime CreatedTime { get; set; }
}

View file

@ -2,8 +2,8 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class ConversationDialogDocument : MongoBase
{
public string ConversationId { get; set; }
public string AgentId { get; set; }
public string ConversationId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public DateTime UpdatedTime { get; set; }
public List<DialogMongoElement> Dialogs { get; set; }
public List<DialogMongoElement> Dialogs { get; set; } = [];
}

View file

@ -2,16 +2,16 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class ConversationDocument : MongoBase
{
public string AgentId { get; set; }
public string UserId { get; set; }
public string AgentId { get; set; } = default!;
public string UserId { get; set; } = default!;
public string? TaskId { get; set; }
public string Title { get; set; }
public string TitleAlias { get; set; }
public string Channel { get; set; }
public string ChannelId { get; set; }
public string Status { get; set; }
public string Title { get; set; } = default!;
public string TitleAlias { get; set; } = default!;
public string Channel { get; set; } = default!;
public string ChannelId { get; set; } = default!;
public string Status { get; set; } = default!;
public int DialogCount { get; set; }
public List<string> Tags { get; set; }
public List<string> Tags { get; set; } = [];
public DateTime CreatedTime { get; set; }
public DateTime UpdatedTime { get; set; }
}

View file

@ -2,9 +2,9 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class ConversationStateDocument : MongoBase
{
public string ConversationId { get; set; }
public string AgentId { get; set; }
public string ConversationId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public DateTime UpdatedTime { get; set; }
public List<StateMongoElement> States { get; set; } = new List<StateMongoElement>();
public List<BreakpointMongoElement> Breakpoints { get; set; } = new List<BreakpointMongoElement>();
public List<StateMongoElement> States { get; set; } = [];
public List<BreakpointMongoElement> Breakpoints { get; set; } = [];
}

View file

@ -2,9 +2,9 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class ConversationStateLogDocument : MongoBase
{
public string ConversationId { get; set; }
public string AgentId { get; set; }
public string MessageId { get; set; }
public Dictionary<string, string> States { get; set; }
public DateTime CreateTime { get; set; }
public string ConversationId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public string MessageId { get; set; } = default!;
public Dictionary<string, string> States { get; set; } = [];
public DateTime CreatedTime { get; set; }
}

View file

@ -4,13 +4,13 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class CrontabItemDocument : MongoBase
{
public string UserId { get; set; }
public string AgentId { get; set; }
public string ConversationId { get; set; }
public string ExecutionResult { get; set; }
public string Cron { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string UserId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public string ConversationId { get; set; } = default!;
public string ExecutionResult { get; set; } = default!;
public string Cron { get; set; } = default!;
public string Title { get; set; } = default!;
public string Description { get; set; } = default!;
public int ExecutionCount { get; set; }
public int MaxExecutionCount { get; set; }
public int ExpireSeconds { get; set; }

View file

@ -2,6 +2,6 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class ExecutionLogDocument : MongoBase
{
public string ConversationId { get; set; }
public List<string> Logs { get; set; }
public string ConversationId { get; set; } = default!;
public List<string> Logs { get; set; } = [];
}

View file

@ -2,12 +2,12 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class GlobalStatisticsDocument : MongoBase
{
public string Metric { get; set; }
public string Dimension { get; set; }
public string DimRefVal { get; set; }
public string Metric { get; set; } = default!;
public string Dimension { get; set; } = default!;
public string DimRefVal { get; set; } = default!;
public IDictionary<string, double> Data { get; set; } = new Dictionary<string, double>();
public DateTime RecordTime { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Interval { get; set; }
public string Interval { get; set; } = default!;
}

View file

@ -2,8 +2,8 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class KnowledgeCollectionConfigDocument : MongoBase
{
public string Name { get; set; }
public string Type { get; set; }
public KnowledgeVectorStoreConfigMongoModel VectorStore { get; set; }
public KnowledgeEmbeddingConfigMongoModel TextEmbedding { get; set; }
public string Name { get; set; } = default!;
public string Type { get; set; } = default!;
public KnowledgeVectorStoreConfigMongoModel VectorStore { get; set; } = new();
public KnowledgeEmbeddingConfigMongoModel TextEmbedding { get; set; } = new();
}

View file

@ -2,14 +2,14 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class KnowledgeCollectionFileMetaDocument : MongoBase
{
public string Collection { get; set; }
public string Collection { get; set; } = default!;
public Guid FileId { get; set; }
public string FileName { get; set; }
public string FileSource { get; set; }
public string ContentType { get; set; }
public string VectorStoreProvider { get; set; }
public IEnumerable<string> VectorDataIds { get; set; } = new List<string>();
public string FileName { get; set; } = default!;
public string FileSource { get; set; } = default!;
public string ContentType { get; set; } = default!;
public string VectorStoreProvider { get; set; } = default!;
public IEnumerable<string> VectorDataIds { get; set; } = [];
public KnowledgeFileMetaRefMongoModel? RefData { get; set; }
public DateTime CreateDate { get; set; }
public string CreateUserId { get; set; }
public DateTime CreatedDate { get; set; }
public string CreateUserId { get; set; } = default!;
}

View file

@ -2,6 +2,6 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class LlmCompletionLogDocument : MongoBase
{
public string ConversationId { get; set; }
public List<PromptLogMongoElement> Logs { get; set; }
public string ConversationId { get; set; } = default!;
public List<PromptLogMongoElement> Logs { get; set; } = [];
}

View file

@ -2,5 +2,5 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class PluginDocument : MongoBase
{
public List<string> EnabledPlugins { get; set; }
public List<string> EnabledPlugins { get; set; } = [];
}

View file

@ -4,8 +4,8 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class RoleAgentDocument : MongoBase
{
public string RoleId { get; set; }
public string AgentId { get; set; }
public string RoleId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public IEnumerable<string> Actions { get; set; } = [];
public DateTime CreatedTime { get; set; }
public DateTime UpdatedTime { get; set; }

View file

@ -4,7 +4,7 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class RoleDocument : MongoBase
{
public string Name { get; set; }
public string Name { get; set; } = default!;
public IEnumerable<string> Permissions { get; set; } = [];
public DateTime CreatedTime { get; set; }
public DateTime UpdatedTime { get; set; }

View file

@ -2,7 +2,7 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class TranslationMemoryDocument : MongoBase
{
public string OriginalText { get; set; }
public string HashText { get; set; }
public List<TranslationMemoryMongoElement> Translations { get; set; } = new List<TranslationMemoryMongoElement>();
public string OriginalText { get; set; } = default!;
public string HashText { get; set; } = default!;
public List<TranslationMemoryMongoElement> Translations { get; set; } = [];
}

View file

@ -2,8 +2,8 @@ namespace BotSharp.Plugin.MongoStorage.Collections;
public class UserAgentDocument : MongoBase
{
public string UserId { get; set; }
public string AgentId { get; set; }
public string UserId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public IEnumerable<string> Actions { get; set; } = [];
public DateTime CreatedTime { get; set; }
public DateTime UpdatedTime { get; set; }

View file

@ -5,8 +5,8 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class AgentKnowledgeBaseMongoElement
{
public string Name { get; set; }
public string Type { get; set; }
public string Name { get; set; } = default!;
public string Type { get; set; } = default!;
public bool Disabled { get; set; }
public static AgentKnowledgeBaseMongoElement ToMongoElement(AgentKnowledgeBase knowledgeBase)

View file

@ -5,9 +5,9 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class AgentResponseMongoElement
{
public string Prefix { get; set; }
public string Intent { get; set; }
public string Content { get; set; }
public string Prefix { get; set; } = default!;
public string Intent { get; set; } = default!;
public string Content { get; set; } = default!;
public static AgentResponseMongoElement ToMongoElement(AgentResponse response)
{

View file

@ -5,9 +5,9 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class AgentRuleMongoElement
{
public string TriggerName { get; set; }
public string TriggerName { get; set; } = default!;
public bool Disabled { get; set; }
public string Criteria { get; set; }
public string Criteria { get; set; } = default!;
public static AgentRuleMongoElement ToMongoElement(AgentRule rule)
{

View file

@ -5,8 +5,8 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class AgentTemplateMongoElement
{
public string Name { get; set; }
public string Content { get; set; }
public string Name { get; set; } = default!;
public string Content { get; set; } = default!;
public static AgentTemplateMongoElement ToMongoElement(AgentTemplate template)
{

View file

@ -5,7 +5,7 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class AgentUtilityMongoElement
{
public string Name { get; set; }
public string Name { get; set; } = default!;
public bool Disabled { get; set; }
public List<UtilityFunctionMongoElement> Functions { get; set; } = [];
public List<UtilityTemplateMongoElement> Templates { get; set; } = [];
@ -33,32 +33,12 @@ public class AgentUtilityMongoElement
}
}
public class UtilityFunctionMongoElement
public class UtilityFunctionMongoElement(string name)
{
public string Name { get; set; }
public UtilityFunctionMongoElement()
{
}
public UtilityFunctionMongoElement(string name)
{
Name = name;
}
public string Name { get; set; } = name;
}
public class UtilityTemplateMongoElement
public class UtilityTemplateMongoElement(string name)
{
public string Name { get; set; }
public UtilityTemplateMongoElement()
{
}
public UtilityTemplateMongoElement(string name)
{
Name = name;
}
public string Name { get; set; } = name;
}

View file

@ -5,8 +5,8 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class ChannelInstructionMongoElement
{
public string Channel { get; set; }
public string Instruction { get; set; }
public string Channel { get; set; } = default!;
public string Instruction { get; set; } = default!;
public static ChannelInstructionMongoElement ToMongoElement(ChannelInstruction instruction)
{

View file

@ -5,9 +5,9 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class CronTaskMongoElement
{
public string Topic { get; set; }
public string Script { get; set; }
public string Language { get; set; }
public string Topic { get; set; } = default!;
public string Script { get; set; } = default!;
public string Language { get; set; } = default!;
public static CronTaskMongoElement ToMongoElement(ScheduleTaskItemArgs model)
{

View file

@ -5,18 +5,13 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class DialogMongoElement
{
public DialogMetaDataMongoElement MetaData { get; set; }
public string Content { get; set; }
public DialogMetaDataMongoElement MetaData { get; set; } = new();
public string Content { get; set; } = default!;
public string? SecondaryContent { get; set; }
public string? RichContent { get; set; }
public string? SecondaryRichContent { get; set; }
public string? Payload { get; set; }
public DialogMongoElement()
{
}
public static DialogMongoElement ToMongoElement(DialogElement dialog)
{
return new DialogMongoElement
@ -46,18 +41,13 @@ public class DialogMongoElement
public class DialogMetaDataMongoElement
{
public string Role { get; set; }
public string AgentId { get; set; }
public string MessageId { get; set; }
public string MessageType { get; set; }
public string Role { get; set; } = default!;
public string AgentId { get; set; } = default!;
public string MessageId { get; set; } = default!;
public string MessageType { get; set; } = default!;
public string? FunctionName { get; set; }
public string? SenderId { get; set; }
public DateTime CreateTime { get; set; }
public DialogMetaDataMongoElement()
{
}
public DateTime CreatedTime { get; set; }
public static DialogMetaData ToDomainElement(DialogMetaDataMongoElement meta)
{
@ -69,7 +59,7 @@ public class DialogMetaDataMongoElement
MessageType = meta.MessageType,
FunctionName = meta.FunctionName,
SenderId = meta.SenderId,
CreateTime = meta.CreateTime,
CreatedTime = meta.CreatedTime,
};
}
@ -83,7 +73,7 @@ public class DialogMetaDataMongoElement
MessageType = meta.MessageType,
FunctionName = meta.FunctionName,
SenderId = meta.SenderId,
CreateTime = meta.CreateTime,
CreatedTime = meta.CreatedTime,
};
}
}

View file

@ -6,17 +6,12 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class FunctionDefMongoElement
{
public string Name { get; set; }
public string Description { get; set; }
public string Name { get; set; } = default!;
public string Description { get; set; } = default!;
public List<string>? Channels { get; set; }
public string? VisibilityExpression { get; set; }
public string? Impact { get; set; }
public FunctionParametersDefMongoElement Parameters { get; set; } = new FunctionParametersDefMongoElement();
public FunctionDefMongoElement()
{
}
public FunctionParametersDefMongoElement Parameters { get; set; } = new();
public static FunctionDefMongoElement ToMongoElement(FunctionDef function)
{
@ -57,12 +52,7 @@ public class FunctionDefMongoElement
public class FunctionParametersDefMongoElement
{
public string Type { get; set; }
public string Properties { get; set; }
public List<string> Required { get; set; } = new List<string>();
public FunctionParametersDefMongoElement()
{
}
public string Type { get; set; } = default!;
public string Properties { get; set; } = default!;
public List<string> Required { get; set; } = [];
}

View file

@ -5,8 +5,8 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class KnowledgeEmbeddingConfigMongoModel
{
public string Provider { get; set; }
public string Model { get; set; }
public string Provider { get; set; } = default!;
public string Model { get; set; } = default!;
public int Dimension { get; set; }
public static KnowledgeEmbeddingConfigMongoModel ToMongoModel(KnowledgeEmbeddingConfig model)

View file

@ -5,10 +5,10 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class KnowledgeFileMetaRefMongoModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Url { get; set; }
public string Id { get; set; } = default!;
public string Name { get; set; } = default!;
public string Type { get; set; } = default!;
public string Url { get; set; } = default!;
public IDictionary<string, string>? Data { get; set; }
public static KnowledgeFileMetaRefMongoModel? ToMongoModel(DocMetaRefData? model)

View file

@ -5,7 +5,7 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class KnowledgeVectorStoreConfigMongoModel
{
public string Provider { get; set; }
public string Provider { get; set; } = default!;
public static KnowledgeVectorStoreConfigMongoModel ToMongoModel(VectorStoreConfig model)
{

View file

@ -3,9 +3,9 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class PromptLogMongoElement
{
public string MessageId { get; set; }
public string AgentId { get; set; }
public string Prompt { get; set; }
public string MessageId { get; set; } = default!;
public string AgentId { get; set; } = default!;
public string Prompt { get; set; } = default!;
public string? Response { get; set; }
public DateTime CreateDateTime { get; set; }
}

View file

@ -5,17 +5,12 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class RoutingRuleMongoElement
{
public string Field { get; set; }
public string Description { get; set; }
public string Field { get; set; } = default!;
public string Description { get; set; } = default!;
public bool Required { get; set; }
public string? RedirectTo { get; set; }
public string Type { get; set; }
public string FieldType { get; set; }
public RoutingRuleMongoElement()
{
}
public string Type { get; set; } = default!;
public string FieldType { get; set; } = default!;
public static RoutingRuleMongoElement ToMongoElement(RoutingRule routingRule)
{

View file

@ -5,10 +5,10 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class StateMongoElement
{
public string Key { get; set; }
public string Key { get; set; } = default!;
public bool Versioning { get; set; }
public bool Readonly { get; set; }
public List<StateValueMongoElement> Values { get; set; }
public List<StateValueMongoElement> Values { get; set; } = [];
public static StateMongoElement ToMongoElement(StateKeyValue state)
{
@ -17,7 +17,7 @@ public class StateMongoElement
Key = state.Key,
Versioning = state.Versioning,
Readonly = state.Readonly,
Values = state.Values?.Select(x => StateValueMongoElement.ToMongoElement(x))?.ToList() ?? new List<StateValueMongoElement>()
Values = state.Values?.Select(x => StateValueMongoElement.ToMongoElement(x))?.ToList() ?? []
};
}
@ -28,19 +28,19 @@ public class StateMongoElement
Key = state.Key,
Versioning = state.Versioning,
Readonly = state.Readonly,
Values = state.Values?.Select(x => StateValueMongoElement.ToDomainElement(x))?.ToList() ?? new List<StateValue>()
Values = state.Values?.Select(x => StateValueMongoElement.ToDomainElement(x))?.ToList() ?? []
};
}
}
public class StateValueMongoElement
{
public string Data { get; set; }
public string Data { get; set; } = default!;
public string? MessageId { get; set; }
public bool Active { get; set; }
public int ActiveRounds { get; set; }
public string DataType { get; set; }
public string Source { get; set; }
public string DataType { get; set; } = default!;
public string Source { get; set; } = default!;
public DateTime UpdateTime { get; set; }

View file

@ -3,8 +3,8 @@ namespace BotSharp.Plugin.MongoStorage.Models;
[BsonIgnoreExtraElements(Inherited = true)]
public class TranslationMemoryMongoElement
{
public string TranslatedText { get; set; }
public string Language { get; set; }
public string TranslatedText { get; set; } = default!;
public string Language { get; set; } = default!;
public static TranslationMemoryMongoElement ToMongoElement(TranslationMemoryItem item)
{

View file

@ -4,5 +4,5 @@ namespace BotSharp.Plugin.MongoStorage;
public abstract class MongoBase
{
[BsonId(IdGenerator = typeof(StringGuidIdGenerator))]
public string Id { get; set; }
public string Id { get; set; } = default!;
}

View file

@ -46,12 +46,32 @@ public class MongoDbContext
return databaseName;
}
private IMongoDatabase Database { get { return _mongoClient.GetDatabase(_mongoDbDatabaseName); } }
private IMongoDatabase Database => _mongoClient.GetDatabase(_mongoDbDatabaseName);
private bool CollectionExists(IMongoDatabase database, string collectionName)
{
var filter = Builders<BsonDocument>.Filter.Eq("name", collectionName);
var collections = database.ListCollections(new ListCollectionsOptions { Filter = filter });
return collections.Any();
}
private IMongoCollection<TDocument> GetCollectionOrCreate<TDocument>(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException($"The collection {name} cannot be empty.");
string collectionName = $"{_collectionPrefix}_{name}";
if (!CollectionExists(Database, collectionName))
Database.CreateCollection(collectionName);
var collection = Database.GetCollection<TDocument>(collectionName);
return collection;
}
#region Indexes
private IMongoCollection<ConversationDocument> CreateConversationIndex()
{
var collection = Database.GetCollection<ConversationDocument>($"{_collectionPrefix}_Conversations");
var collection = GetCollectionOrCreate<ConversationDocument>("Conversations");
var indexes = collection.Indexes.List().ToList();
var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreatedTime"));
if (createTimeIndex == null)
@ -64,7 +84,7 @@ public class MongoDbContext
private IMongoCollection<ConversationStateDocument> CreateConversationStateIndex()
{
var collection = Database.GetCollection<ConversationStateDocument>($"{_collectionPrefix}_ConversationStates");
var collection = GetCollectionOrCreate<ConversationStateDocument>("ConversationStates");
var indexes = collection.Indexes.List().ToList();
var stateIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("States.Key"));
if (stateIndex == null)
@ -77,7 +97,7 @@ public class MongoDbContext
private IMongoCollection<AgentTaskDocument> CreateAgentTaskIndex()
{
var collection = Database.GetCollection<AgentTaskDocument>($"{_collectionPrefix}_AgentTasks");
var collection = GetCollectionOrCreate<AgentTaskDocument>("AgentTasks");
var indexes = collection.Indexes.List().ToList();
var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreatedTime"));
if (createTimeIndex == null)
@ -90,12 +110,12 @@ public class MongoDbContext
private IMongoCollection<ConversationContentLogDocument> CreateContentLogIndex()
{
var collection = Database.GetCollection<ConversationContentLogDocument>($"{_collectionPrefix}_ConversationContentLogs");
var collection = GetCollectionOrCreate<ConversationContentLogDocument>("ConversationContentLogs");
var indexes = collection.Indexes.List().ToList();
var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreateTime"));
if (createTimeIndex == null)
{
var indexDef = Builders<ConversationContentLogDocument>.IndexKeys.Ascending(x => x.CreateTime);
var indexDef = Builders<ConversationContentLogDocument>.IndexKeys.Ascending(x => x.CreatedTime);
collection.Indexes.CreateOne(new CreateIndexModel<ConversationContentLogDocument>(indexDef));
}
return collection;
@ -103,12 +123,12 @@ public class MongoDbContext
private IMongoCollection<ConversationStateLogDocument> CreateStateLogIndex()
{
var collection = Database.GetCollection<ConversationStateLogDocument>($"{_collectionPrefix}_ConversationStateLogs");
var collection = GetCollectionOrCreate<ConversationStateLogDocument>("ConversationStateLogs");
var indexes = collection.Indexes.List().ToList();
var createTimeIndex = indexes.FirstOrDefault(x => x.GetElement("name").ToString().StartsWith("CreateTime"));
if (createTimeIndex == null)
{
var indexDef = Builders<ConversationStateLogDocument>.IndexKeys.Ascending(x => x.CreateTime);
var indexDef = Builders<ConversationStateLogDocument>.IndexKeys.Ascending(x => x.CreatedTime);
collection.Indexes.CreateOne(new CreateIndexModel<ConversationStateLogDocument>(indexDef));
}
return collection;
@ -116,7 +136,7 @@ public class MongoDbContext
#endregion
public IMongoCollection<AgentDocument> Agents
=> Database.GetCollection<AgentDocument>($"{_collectionPrefix}_Agents");
=> GetCollectionOrCreate<AgentDocument>("Agents");
public IMongoCollection<AgentTaskDocument> AgentTasks
=> CreateAgentTaskIndex();
@ -125,16 +145,16 @@ public class MongoDbContext
=> CreateConversationIndex();
public IMongoCollection<ConversationDialogDocument> ConversationDialogs
=> Database.GetCollection<ConversationDialogDocument>($"{_collectionPrefix}_ConversationDialogs");
=> GetCollectionOrCreate<ConversationDialogDocument>("ConversationDialogs");
public IMongoCollection<ConversationStateDocument> ConversationStates
=> CreateConversationStateIndex();
public IMongoCollection<ExecutionLogDocument> ExectionLogs
=> Database.GetCollection<ExecutionLogDocument>($"{_collectionPrefix}_ExecutionLogs");
=> GetCollectionOrCreate<ExecutionLogDocument>("ExecutionLogs");
public IMongoCollection<LlmCompletionLogDocument> LlmCompletionLogs
=> Database.GetCollection<LlmCompletionLogDocument>($"{_collectionPrefix}_LlmCompletionLogs");
=> GetCollectionOrCreate<LlmCompletionLogDocument>("LlmCompletionLogs");
public IMongoCollection<ConversationContentLogDocument> ContentLogs
=> CreateContentLogIndex();
@ -143,33 +163,33 @@ public class MongoDbContext
=> CreateStateLogIndex();
public IMongoCollection<UserDocument> Users
=> Database.GetCollection<UserDocument>($"{_collectionPrefix}_Users");
=> GetCollectionOrCreate<UserDocument>("Users");
public IMongoCollection<UserAgentDocument> UserAgents
=> Database.GetCollection<UserAgentDocument>($"{_collectionPrefix}_UserAgents");
=> GetCollectionOrCreate<UserAgentDocument>("UserAgents");
public IMongoCollection<PluginDocument> Plugins
=> Database.GetCollection<PluginDocument>($"{_collectionPrefix}_Plugins");
=> GetCollectionOrCreate<PluginDocument>("Plugins");
public IMongoCollection<TranslationMemoryDocument> TranslationMemories
=> Database.GetCollection<TranslationMemoryDocument>($"{_collectionPrefix}_TranslationMemories");
=> GetCollectionOrCreate<TranslationMemoryDocument>("TranslationMemories");
public IMongoCollection<KnowledgeCollectionConfigDocument> KnowledgeCollectionConfigs
=> Database.GetCollection<KnowledgeCollectionConfigDocument>($"{_collectionPrefix}_KnowledgeCollectionConfigs");
=> GetCollectionOrCreate<KnowledgeCollectionConfigDocument>("KnowledgeCollectionConfigs");
public IMongoCollection<KnowledgeCollectionFileMetaDocument> KnowledgeCollectionFileMeta
=> Database.GetCollection<KnowledgeCollectionFileMetaDocument>($"{_collectionPrefix}_KnowledgeCollectionFileMeta");
=> GetCollectionOrCreate<KnowledgeCollectionFileMetaDocument>("KnowledgeCollectionFileMeta");
public IMongoCollection<RoleDocument> Roles
=> Database.GetCollection<RoleDocument>($"{_collectionPrefix}_Roles");
=> GetCollectionOrCreate<RoleDocument>("Roles");
public IMongoCollection<RoleAgentDocument> RoleAgents
=> Database.GetCollection<RoleAgentDocument>($"{_collectionPrefix}_RoleAgents");
=> GetCollectionOrCreate<RoleAgentDocument>("RoleAgents");
public IMongoCollection<CrontabItemDocument> CrontabItems
=> Database.GetCollection<CrontabItemDocument>($"{_collectionPrefix}_CronTabItems");
=> GetCollectionOrCreate<CrontabItemDocument>("CronTabItems");
public IMongoCollection<GlobalStatisticsDocument> GlobalStatistics
=> Database.GetCollection<GlobalStatisticsDocument>($"{_collectionPrefix}_GlobalStatistics");
=> GetCollectionOrCreate<GlobalStatisticsDocument>("GlobalStatistics");
}
}

View file

@ -534,7 +534,7 @@ public partial class MongoRepository
var truncatedDialogs = foundDialog.Dialogs.Where((x, idx) => idx < foundIdx).ToList();
// Handle truncated states
var refTime = foundDialog.Dialogs.ElementAt(foundIdx).MetaData.CreateTime;
var refTime = foundDialog.Dialogs.ElementAt(foundIdx).MetaData.CreatedTime;
var stateFilter = Builders<ConversationStateDocument>.Filter.Eq(x => x.ConversationId, conversationId);
var foundStates = _dc.ConversationStates.Find(stateFilter).FirstOrDefault();
@ -596,12 +596,12 @@ public partial class MongoRepository
var contentLogFilters = new List<FilterDefinition<ConversationContentLogDocument>>()
{
contentLogBuilder.Eq(x => x.ConversationId, conversationId),
contentLogBuilder.Gte(x => x.CreateTime, refTime)
contentLogBuilder.Gte(x => x.CreatedTime, refTime)
};
var stateLogFilters = new List<FilterDefinition<ConversationStateLogDocument>>()
{
stateLogBuilder.Eq(x => x.ConversationId, conversationId),
stateLogBuilder.Gte(x => x.CreateTime, refTime)
stateLogBuilder.Gte(x => x.CreatedTime, refTime)
};
_dc.ContentLogs.DeleteMany(contentLogBuilder.And(contentLogFilters));

View file

@ -17,7 +17,7 @@ public partial class MongoRepository
Type = x.Type,
VectorStore = KnowledgeVectorStoreConfigMongoModel.ToMongoModel(x.VectorStore),
TextEmbedding = KnowledgeEmbeddingConfigMongoModel.ToMongoModel(x.TextEmbedding)
})?.ToList() ?? new List<KnowledgeCollectionConfigDocument>();
})?.ToList() ?? [];
if (reset)
{
@ -136,7 +136,7 @@ public partial class MongoRepository
VectorStoreProvider = metaData.VectorStoreProvider,
VectorDataIds = metaData.VectorDataIds,
RefData = KnowledgeFileMetaRefMongoModel.ToMongoModel(metaData.RefData),
CreateDate = metaData.CreateDate,
CreatedDate = metaData.CreateDate,
CreateUserId = metaData.CreateUserId
};
@ -208,7 +208,7 @@ public partial class MongoRepository
}
var filterDef = builder.And(docFilters);
var sortDef = Builders<KnowledgeCollectionFileMetaDocument>.Sort.Descending(x => x.CreateDate);
var sortDef = Builders<KnowledgeCollectionFileMetaDocument>.Sort.Descending(x => x.CreatedDate);
var docs = _dc.KnowledgeCollectionFileMeta.Find(filterDef).Sort(sortDef).Skip(filter.Offset).Limit(filter.Size).ToList();
var count = _dc.KnowledgeCollectionFileMeta.CountDocuments(filterDef);
@ -222,9 +222,9 @@ public partial class MongoRepository
VectorStoreProvider = x.VectorStoreProvider,
VectorDataIds = x.VectorDataIds,
RefData = KnowledgeFileMetaRefMongoModel.ToDomainModel(x.RefData),
CreateDate = x.CreateDate,
CreateDate = x.CreatedDate,
CreateUserId = x.CreateUserId
})?.ToList() ?? new();
})?.ToList() ?? [];
return new PagedItems<KnowledgeDocMetaData>
{

View file

@ -74,7 +74,7 @@ public partial class MongoRepository
Role = log.Role,
Source = log.Source,
Content = log.Content,
CreateTime = log.CreateTime
CreatedTime = log.CreateTime
};
_dc.ContentLogs.InsertOne(logDoc);
@ -94,7 +94,7 @@ public partial class MongoRepository
Role = x.Role,
Source = x.Source,
Content = x.Content,
CreateTime = x.CreateTime
CreateTime = x.CreatedTime
})
.OrderBy(x => x.CreateTime)
.ToList();
@ -116,7 +116,7 @@ public partial class MongoRepository
AgentId= log.AgentId,
MessageId = log.MessageId,
States = log.States,
CreateTime = log.CreateTime
CreatedTime = log.CreateTime
};
_dc.StateLogs.InsertOne(logDoc);
@ -133,7 +133,7 @@ public partial class MongoRepository
AgentId = x.AgentId,
MessageId = x.MessageId,
States = x.States,
CreateTime = x.CreateTime
CreateTime = x.CreatedTime
})
.OrderBy(x => x.CreateTime)
.ToList();

View file

@ -49,7 +49,7 @@ public partial class MongoRepository
var hashTexts = inputs.Where(x => !string.IsNullOrEmpty(x.HashText)).Select(x => x.HashText).ToList();
var filter = Builders<TranslationMemoryDocument>.Filter.In(x => x.HashText, hashTexts);
var memories = _dc.TranslationMemories.Find(filter)?.ToList() ?? new List<TranslationMemoryDocument>();
var memories = _dc.TranslationMemories.Find(filter)?.ToList() ?? [];
var newMemories = new List<TranslationMemoryDocument>();
var updateMemories = new List<TranslationMemoryDocument>();
@ -90,7 +90,7 @@ public partial class MongoRepository
if (foundMemory.Translations == null)
{
foundMemory.Translations = new List<TranslationMemoryMongoElement> { newItem };
foundMemory.Translations = [newItem];
}
else
{

View file

@ -76,13 +76,13 @@ public partial class MongoRepository
public List<User> GetUserByIds(List<string> ids)
{
var users = _dc.Users.AsQueryable().Where(x => ids.Contains(x.Id) || (x.ExternalId != null && ids.Contains(x.ExternalId))).ToList();
return users?.Any() == true ? users.Select(x => x.ToUser()).ToList() : new List<User>();
return users?.Any() == true ? users.Select(x => x.ToUser()).ToList() : [];
}
public List<User> GetUsersByAffiliateId(string affiliateId)
{
var users = _dc.Users.AsQueryable().Where(x => x.AffiliateId == affiliateId).ToList();
return users?.Any() == true ? users.Select(x => x.ToUser()).ToList() : new List<User>();
return users?.Any() == true ? users.Select(x => x.ToUser()).ToList() : [];
}
public User? GetUserByUserName(string userName)
@ -259,13 +259,13 @@ public partial class MongoRepository
public List<User> SearchLoginUsers(User filter, string source = UserSource.Internal)
{
List<User> searchResult = new List<User>();
List<User> searchResult = [];
// search by filters
if (!string.IsNullOrWhiteSpace(filter.Id))
{
var curUser = _dc.Users.AsQueryable().FirstOrDefault(x => x.Source == source && x.Id == filter.Id.ToLower());
User user = curUser != null ? curUser.ToUser() : null;
User? user = curUser != null ? curUser.ToUser() : null;
if (user != null)
{
searchResult.Add(user);
@ -307,7 +307,7 @@ public partial class MongoRepository
else if (!string.IsNullOrWhiteSpace(filter.Email))
{
var curUser = _dc.Users.AsQueryable().FirstOrDefault(x => x.Source == source && x.Email == filter.Email.ToLower());
User user = curUser != null ? curUser.ToUser() : null;
User? user = curUser != null ? curUser.ToUser() : null;
if (user != null)
{
searchResult.Add(user);
@ -318,7 +318,7 @@ public partial class MongoRepository
if (searchResult.Count == 0 && !string.IsNullOrWhiteSpace(filter.UserName))
{
var curUser = _dc.Users.AsQueryable().FirstOrDefault(x => x.Source == source && x.UserName == filter.UserName);
User user = curUser != null ? curUser.ToUser() : null;
User? user = curUser != null ? curUser.ToUser() : null;
if (user != null)
{
searchResult.Add(user);
@ -429,7 +429,7 @@ public partial class MongoRepository
return true;
}
public Dashboard? GetDashboard(string userId = null)
public Dashboard? GetDashboard(string? userId = null)
{
return null;
}