Files
xAiModels/Providers/XAiDataProvider.cs
T
saherelm 9e7710e345 Make projectId Nullable in Data Provider and Remove Api Configuration
- IXAiDataProvider.GetDefaultConversation: projectId changed from Guid to Guid?;
- XAiDataProvider.GetDefaultConversation / HasDefaultConversation /
  CreateDefaultConversation: adapt to Guid? (use !projectId.HasValue instead of
  projectId.IsNull(); resolve project via projectId.Value);
- XAiDataProvider: conversation lookup predicate fixed to
  x.ProjectId == project.Id (was x.ProjectId == projectId);
- XEmbeddingExtensions: add ToEmbedding(this ReadOnlyMemory<float>) to persist
  embeddings as JSON;
- XAiDataProvider: use item.Embedding.ToEmbedding() instead of ToJSON() when
  upserting vectors;
- XAiModelsExtensions: rename GetDafualtProject -> GetDafaultProject (typo fix);
- Remove Configurations/XAiApiConfiguration.cs and
  Extensions/XAiApiConfigurationExtensions.cs (Api configuration does not belong
  to the models module).
BREAKING: XAiApiConfiguration / XAiApiConfigurationExtensions removed from
          xAiModels; GetDafualtProject renamed to GetDafaultProject.
2026-11-02 16:37:27 +03:30

2363 lines
77 KiB
C#

using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xAiModels.Helpers;
using xAiModels.Constants;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiModels.Interfaces;
using xAiModels.Models.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using System.Linq.Expressions;
using xDataService.Extensions;
using xAiModels.Providers.Hubs;
using xAiModels.Interfaces.Dtos;
using xStringService.Interfaces;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities;
using xAiModels.Interfaces.Enrichers;
namespace xAiModels.Providers
{
/// <summary>
/// All Data Manipulation Requirements ...
/// </summary>
public class XAiDataProvider : IXAiDataProvider
{
//
#region Properties ...
private readonly IXStringProvider stringProvider;
private readonly IXAiVectorEnricher vectorEnricher;
private readonly XAppConfiguration appConfiguration;
private readonly IHubContext<XAiDataProviderHub> hub;
private readonly IXAiMessageEnricher messageEnricher;
private readonly IXAiProjectEnricher projectEnricher;
private readonly IXAiVectorRepository vectorRepository;
private readonly IXAiConversationEnricher conversationEnricher;
private readonly IXAiVectorRepositoryService vectorRepositoryService;
private readonly IXAiMessageRepositoryService messageRepositoryService;
private readonly IXAiProjectRepositoryService projectRepositoryService;
private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider;
private readonly IXAiConversationRepositoryService conversationRepositoryService;
private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider;
private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider;
#endregion
public XAiDataProvider(
IXStringProvider stringProvider,
IXAiVectorEnricher vectorEnricher,
XAppConfiguration appConfiguration,
IHubContext<XAiDataProviderHub> hub,
IXAiProjectEnricher projectEnricher,
IXAiMessageEnricher messageEnricher,
IXAiVectorRepository vectorRepository,
IXAiConversationEnricher conversationEnricher,
IXAiVectorRepositoryService vectorRepositoryService,
IXAiMessageRepositoryService messageRepositoryService,
IXAiProjectRepositoryService projectRepositoryService,
IXAiProjectTitleResourceProvider projectTitleResourceProvider,
IXAiConversationRepositoryService conversationRepositoryService,
IXAiConversationTitleResourceProvider conversationTitleResourceProvider,
IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider
)
{
this.hub = hub;
this.stringProvider = stringProvider;
this.vectorEnricher = vectorEnricher;
this.projectEnricher = projectEnricher;
this.messageEnricher = messageEnricher;
this.appConfiguration = appConfiguration;
this.vectorRepository = vectorRepository;
this.conversationEnricher = conversationEnricher;
this.vectorRepositoryService = vectorRepositoryService;
this.messageRepositoryService = messageRepositoryService;
this.projectRepositoryService = projectRepositoryService;
this.projectTitleResourceProvider = projectTitleResourceProvider;
this.conversationRepositoryService = conversationRepositoryService;
this.conversationTitleResourceProvider = conversationTitleResourceProvider;
this.projectDescriptionResourceProvider = projectDescriptionResourceProvider;
}
//
#region Loaders ...
/// <summary>
/// Load Projects List of Specified Owner ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="fillConversations"></param>
/// <param name="fillConversationMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiProjectDto>> LoadProjects(
string ownerId,
string connectionId = null,
bool fillConversations = false,
bool fillConversationMessages = false,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (ownerId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Handle Default Project and Conversation ...
//
// Default Project ...
bool hasDefault = await HasDefaultProject(
ownerId: ownerId,
cancellationToken: cancellationToken
);
if (!hasDefault)
{
//
await CreateDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
var defaultProject = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
//
// Default Project's Default Conversation ...
hasDefault = await HasDefaultConversation(
ownerId: ownerId,
projectId: defaultProject.Id,
cancellationToken: cancellationToken
);
if (!hasDefault)
{
//
await CreateDefaultConversation(
ownerId: ownerId,
connectionId: connectionId,
projectId: defaultProject.Id,
cancellationToken: cancellationToken
);
}
//
// Retrieve Project List ...
var result = await projectRepositoryService.FindManyAsync(
includeBuilder: null,
ignoreSoftDeleteds: true,
predicate: x => x.OwnerId == ownerId,
cancellationToken: cancellationToken,
orderBuilder: x => x.OrderBy(y => y.CreatedOn)
);
//
if (result.HasChild())
{
//
result = await projectEnricher.EnrichRange(
sources: result,
cancellationToken: cancellationToken,
fillConversations: fillConversations,
fillConversationMessages: fillConversationMessages
);
}
//
return result;
}
/// <summary>
/// Load List of Conversations for Specified Project ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="connectionId"></param>
/// <param name="fillMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiConversationDto>> LoadConversations(
Guid projectId,
bool fillMessages = false,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (projectId.IsNull() ||
projectId.IsDefaultGuid()
)
{
XException.InvalidArgs.Throw();
}
//
// Retrieve Project ...
var project = await projectRepositoryService.GetAsync(
id: projectId,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
if (project.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Default Conversation ...
var hasDefault = await HasDefaultConversation(
projectId: projectId,
ownerId: project.OwnerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!hasDefault)
{
//
await CreateDefaultConversation(
projectId: projectId,
ownerId: project.OwnerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
//
// Retrieve Conversation's List ...
var result = await conversationRepositoryService.FindManyAsync(
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: x => x.ProjectId == projectId,
orderBuilder: x => x.OrderBy(y => y.CreatedOn)
);
//
if (result.HasChild())
{
//
result = await conversationEnricher.EnrichRange(
sources: result,
fillMessages: fillMessages,
cancellationToken: cancellationToken
);
}
//
return result;
}
/// <summary>
/// Load Messages of Specified Conversation ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiMessageDto>> LoadMessages(
Guid conversationId,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (conversationId.IsNull() ||
conversationId.IsDefaultGuid()
)
{
XException.InvalidArgs.Throw();
}
//
var conversation = await conversationRepositoryService.GetAsync(
id: conversationId,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
if (conversation.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Retrieve Message Lists of Specified Conversation ...
var result = await messageRepositoryService.FindManyAsync(
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
orderBuilder: x => x.OrderBy(y => y.CreatedOn),
predicate: x => x.ConversationId == conversationId
);
//
if (result.HasChild())
{
//
result = await messageEnricher.EnrichRange(
sources: result,
cancellationToken: cancellationToken
);
}
//
return result;
}
#endregion
//
#region Getters ...
/// <summary>
/// Retrieve Specified Project ...
/// </summary>
/// <param name="id"></param>
/// <param name="fillConversations"></param>
/// <param name="fillConversationMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiProjectDto> GetProject(
Guid id,
bool fillConversations = false,
bool fillConversationMessages = false,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (id.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
//
var result = await projectRepositoryService.GetAsync(
id: id,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Handle Enrichment ...
result = await projectEnricher.Enrich(
source: result,
fillConversations: fillConversations,
cancellationToken: cancellationToken,
fillConversationMessages: fillConversationMessages
);
//
return result;
}
/// <summary>
/// Retrieve Specified Conversation ...
/// </summary>
/// <param name="id"></param>
/// <param name="fillMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiConversationDto> GetConversation(
Guid id,
bool fillMessages = false,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (id.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
//
var result = await conversationRepositoryService.GetAsync(
id: id,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Handle Enrichment ...
result = await conversationEnricher.Enrich(
source: result,
fillMessages: fillMessages,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
//
#region Creator/Adders ...
/// <summary>
/// Create Project ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="item"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiProjectDto> CreateProject(
string ownerId,
XAiProjectDto item = null,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (ownerId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Check Project Provided or not ...
var hasProject = !item.IsNullOrDefault();
//
// Normalize Provided Project ...
if (hasProject)
{
//
item.OwnerId = ownerId;
item.CreatedOn = DateTime.UtcNow;
//
// Validate Item ...
if (!item.IsValidForAddOrUpdate())
{
XException.InvalidData.Throw();
}
}
//
XAiProjectDto result = null;
var defaultLanguage = appConfiguration.DefaultLanguage;
//
// Create Provided Project ...
if (hasProject)
{
//
// Add Item for ID Gneneration ...
result = await projectRepositoryService.AddAsync(
item: item,
saveChanges: true,
cancellationToken: cancellationToken
);
//
// Checking Resources ...
//
// Titles ...
var titleResource = string.Empty;
if (!item.TitleResource.IsNullOrDefault() &&
item.TitleResource.Locales.HasChild())
{
//
// Adding Title Resource Locales ...
var isDefaultLanguageHandled = false;
foreach (var trl in item.TitleResource.Locales)
{
//
// Attaching Default Language ...
if (!isDefaultLanguageHandled &&
trl.Language.IsNullOrEmpty())
{
//
trl.Language = defaultLanguage;
isDefaultLanguageHandled = true;
}
//
// Check Value Exists ...
if (trl.Value.IsNullOrEmpty())
{
continue;
}
//
var resource = await projectTitleResourceProvider.AddOrUpdateLocale(
locale: trl,
owner: ownerId,
identifier: result.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!resource.IsNullOrDefault() &&
titleResource.IsNullOrEmpty())
{
titleResource = resource.Resource;
}
}
}
//
// Descriptions ...
var descriptionResource = string.Empty;
if (!item.DescriptionResource.IsNullOrDefault() &&
item.DescriptionResource.Locales.HasChild())
{
//
// Adding Description Resource Locales ....
var isDefaultLanguageHandled = false;
foreach (var trl in item.DescriptionResource.Locales)
{
//
// Attaching Default Language ...
if (!isDefaultLanguageHandled &&
trl.Language.IsNullOrEmpty())
{
//
trl.Language = defaultLanguage;
isDefaultLanguageHandled = true;
}
//
// Check Value Exists ...
if (trl.Value.IsNullOrEmpty())
{
continue;
}
//
var resource = await projectDescriptionResourceProvider.AddOrUpdateLocale(
locale: trl,
owner: ownerId,
identifier: result.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!resource.IsNullOrDefault() &&
descriptionResource.IsNullOrEmpty())
{
descriptionResource = resource.Resource;
}
}
}
//
// Update Data ...
result.Title = titleResource;
result.Description = descriptionResource;
result = await projectRepositoryService.UpdateAsync(
item: result,
id: result.Id,
saveChanges: true,
cancellationToken: cancellationToken
);
if (!result.IsNullOrDefault())
{
//
result = await projectEnricher.Enrich(
source: result,
fillConversations: false,
fillConversationMessages: false,
cancellationToken: cancellationToken
);
}
//
// Handling Send Push Notification ...
if (!result.IsNullOrDefault() &&
!connectionId.IsNullOrEmpty()
)
{
//
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: item.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.ProjectCreated.GetStringValue()
);
}
}
//
// Check Default Project ...
else
{
//
// Check Default Project Exists or not ...
var hasDefault = await HasDefaultProject(
ownerId: ownerId,
cancellationToken: cancellationToken
);
//
// If Default Project Exists, Throw Exception ...
if (hasDefault)
{
XException.InvalidArgs.Throw();
}
//
// Create and Retrive Default Project ...
result = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
//
// Validate ...
if (result.IsNullOrDefault())
{
XException.ActionFailed.Throw();
}
//
// Handle Enrichment ...
result = await Enrich(
source: result,
fillConversations: false,
fillConversationMessages: false,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Create an AI Conversation ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="projectId"></param>
/// <param name="item"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiConversationDto> CreateConversation(
string ownerId,
Guid projectId,
XAiConversationDto item = null,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (projectId.IsNull() ||
projectId.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
//
// Handle Proejct ...
XAiProjectDto project = await projectRepositoryService.GetAsync(
id: projectId,
includeBuilder: null,
ignoreSoftDeleteds: true,
// fillConversations: false,
// fillConversationMessages: false,
cancellationToken: cancellationToken
);
if (project.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Check Conversation Provided or not ...
var hasConversation = !item.IsNullOrDefault();
//
// Normalize Conversation if Provided ...
if (hasConversation)
{
//
item.OwnerId = ownerId;
item.ProjectId = project.Id;
item.CreatedOn = DateTime.UtcNow;
//
// Validate Item ...
if (!item.IsValidForAddOrUpdate())
{
XException.InvalidData.Throw();
}
}
//
XAiConversationDto result = null;
var defaultLanguage = appConfiguration.DefaultLanguage;
//
// Create Provided Conversation ...
if (hasConversation)
{
//
// Add Item for ID Gneneration ...
result = await conversationRepositoryService.AddAsync(
item: item,
saveChanges: true,
// fillMessages: false,
cancellationToken: cancellationToken
);
//
// Checking Resources ...
//
// Titles ...
var titleResource = string.Empty;
if (!item.TitleResource.IsNullOrDefault() &&
item.TitleResource.Locales.HasChild())
{
//
// Adding Title Resource Locales ...
var isDefaultLanguageHandled = false;
foreach (var trl in item.TitleResource.Locales)
{
//
// Attaching Default Language ...
if (!isDefaultLanguageHandled &&
trl.Language.IsNullOrEmpty())
{
//
trl.Language = defaultLanguage;
isDefaultLanguageHandled = true;
}
//
// Check Value Exists ...
if (trl.Value.IsNullOrEmpty())
{
continue;
}
//
var resource = await conversationTitleResourceProvider.AddOrUpdateLocale(
locale: trl,
owner: ownerId,
identifier: result.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!resource.IsNullOrDefault() &&
titleResource.IsNullOrEmpty())
{
titleResource = resource.Resource;
}
}
}
//
// Update Data ...
result.Title = titleResource;
result = await conversationRepositoryService.UpdateAsync(
item: result,
id: result.Id,
saveChanges: true,
cancellationToken: cancellationToken
);
if (!result.IsNullOrDefault())
{
//
result = await conversationEnricher.Enrich(
source: result,
fillMessages: false,
cancellationToken: cancellationToken
);
}
//
// Handling Send Push Notification ...
if (!result.IsNullOrDefault() &&
!connectionId.IsNullOrEmpty()
)
{
//
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: item.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.ConversationCreated.GetStringValue()
);
}
}
//
// Check Default Conversation ...
else
{
//
// Check Default Conversation Exists or not ...
var hasDefault = await HasDefaultConversation(
projectId: project.Id,
ownerId: project.OwnerId,
cancellationToken: cancellationToken
);
//
// If Default Project Exists, Throw Exception ...
if (hasDefault)
{
XException.InvalidArgs.Throw();
}
//
// Create and Retrive Default Conversation ...
result = await GetDefaultConversation(
projectId: project.Id,
ownerId: project.OwnerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
//
// Validate ...
if (result.IsNullOrDefault())
{
XException.ActionFailed.Throw();
}
//
// Handle Enrichment ...
result = await Enrich(
source: result,
fillMessages: false,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Add Message ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="item"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiMessageDto> AddMessage(
Guid conversationId,
XAiMessageDto item,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (item.IsNullOrDefault() ||
conversationId.IsNull() ||
conversationId.IsDefaultGuid()
)
{
XException.InvalidArgs.Throw();
}
//
// Normalize ...
item.CreatedOn = DateTime.UtcNow;
item.ConversationId = conversationId;
//
// Validate Item ...
if (!item.IsValidForAddOrUpdate())
{
XException.InvalidData.Throw();
}
//
var result = await messageRepositoryService.AddAsync(
item: item,
saveChanges: true,
cancellationToken: cancellationToken
);
//
// Handle Enrichment ...
if (!result.IsNullOrDefault())
{
//
result = await Enrich(
source: result,
cancellationToken: cancellationToken
);
}
//
// Handling Send Push Notification ...
if (!result.IsNullOrDefault() &&
!connectionId.IsNullOrEmpty()
)
{
//
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: item.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.MessageCreated.GetStringValue()
);
}
//
return result;
}
#endregion
//
#region Updaters ...
#endregion
//
#region Defaults ...
/// <summary>
/// Retrieve Default Project of Specified Owner ...
/// Create it if not Handled ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiProjectDto> GetDefaultProject(
string ownerId,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Check Default Project Exists or noit ...
var isExists = await HasDefaultProject(
ownerId: ownerId,
cancellationToken: cancellationToken
);
if (!isExists)
{
//
await CreateDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
//
var resource = await stringProvider.FindOne(
cancellationToken: cancellationToken,
predicate: x =>
x.ResourceTitle
.ToNormalString()
.Contains(ownerId.ToNormalString()) &&
x.ResourceTitle
.ToNormalString()
.Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) &&
x.TranslatedValue
.ToNormalString()
.Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix.ToNormalString())
);
if (resource.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
var result = await projectRepositoryService.FindOneAsync(
cancellationToken: cancellationToken,
predicate: x => x.Title
.Equals(
resource.ResourceTitle,
StringComparison.InvariantCultureIgnoreCase
)
);
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// Retrieve Default Conversation of Specified Owner ...
/// Create it if not Handled ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="projectId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiConversationDto> GetDefaultConversation(
string ownerId,
Guid? projectId,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (ownerId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Prepare Project ...
XAiProjectDto project = null;
if (!projectId.HasValue ||
projectId.Value.IsDefaultGuid()
)
{
//
project = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
else
{
//
project = await projectRepositoryService.GetAsync(
id: projectId.Value,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
}
if (project.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Check Default Conversation Exists or noit ...
var isExists = await HasDefaultConversation(
ownerId: ownerId,
projectId: project.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!isExists)
{
//
await CreateDefaultConversation(
ownerId: ownerId,
projectId: project.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
//
// Check Default Owner Exists or not ...
var resource = await stringProvider.FindOne(
cancellationToken: cancellationToken,
predicate: x =>
x.ResourceTitle
.ToNormalString()
.Contains(ownerId.ToString().ToNormalString()) &&
x.ResourceTitle
.ToNormalString()
.Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) &&
x.TranslatedValue
.ToNormalString()
.Contains(XAiDataProviderConstants.XDefaultAiConversationSuffix.ToNormalString())
);
if (resource.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
var result = await conversationRepositoryService.FindOneAsync(
cancellationToken: cancellationToken,
predicate: x =>
x.ProjectId == project.Id &&
x.Title == resource.ResourceTitle
);
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// Query Projects ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="query"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XQueryResult<XAiProjectDto>> QueryProjects(
string ownerId,
XQuery query,
CancellationToken cancellationToken = default
)
{
//
Expression<Func<XAiProject, bool>> predicate = null;
if (!ownerId.IsNullOrEmpty())
{
predicate = x => x.OwnerId == ownerId;
}
//
var result = await projectRepositoryService.QueryAsync(
query: query,
predicate: predicate,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
orderBuilder: x => x.OrderBy(y => y.CreatedOn)
);
if (!result.IsNullOrDefault() &&
result.Items.HasChild())
{
//
result.Items = [..await EnrichRange(
sources: result.Items,
fillConversations: false,
fillConversationMessages: false,
cancellationToken: cancellationToken
)];
}
//
return result;
}
/// <summary>
/// Query Conversations ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="projectId"></param>
/// <param name="query"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XQueryResult<XAiConversationDto>> QueryConversations(
string ownerId,
Guid projectId,
XQuery query,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (projectId.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
//
// Retrieve Project ...
var project = await projectRepositoryService.GetAsync(
id: projectId,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
if (project.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
Expression<Func<XAiConversation, bool>> predicate = x =>
x.ProjectId == projectId;
if (!ownerId.IsNullOrEmpty())
{
//
predicate = x =>
x.OwnerId == ownerId &&
x.ProjectId == projectId;
}
//
var result = await conversationRepositoryService.QueryAsync(
query: query,
predicate: predicate,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
orderBuilder: x => x.OrderBy(y => y.CreatedOn)
);
if (!result.IsNullOrDefault() &&
result.Items.HasChild())
{
//
result.Items = [..await EnrichRange(
fillMessages: false,
sources: result.Items,
cancellationToken: cancellationToken
)];
}
//
return result;
}
/// <summary>
/// Query Messages ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="conversationId"></param>
/// <param name="query"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XQueryResult<XAiMessageDto>> QueryMessages(
string ownerId,
Guid conversationId,
XQuery query,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (conversationId.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
//
// Retrieve Conversation ...
var conversation = await conversationRepositoryService.GetAsync(
id: conversationId,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
if (conversation.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
Expression<Func<XAiMessage, bool>> predicate = x =>
x.ConversationId == conversationId;
if (!ownerId.IsNullOrEmpty())
{
//
predicate = x =>
x.OwnerId == ownerId &&
x.ConversationId == conversationId;
}
//
var result = await messageRepositoryService.QueryAsync(
query: query,
predicate: predicate,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
orderBuilder: x => x.OrderBy(y => y.CreatedOn)
);
if (!result.IsNullOrDefault() &&
result.Items.HasChild())
{
//
result.Items = [..await EnrichRange(
sources: result.Items,
cancellationToken: cancellationToken
)];
}
//
return result;
}
#endregion
//
#region Vectors ...
/// <summary>
/// Insert or Update a Single Vector (Matched by Identifier) ...
/// </summary>
/// <param name="identifier"></param>
/// <param name="text"></param>
/// <param name="embedding"></param>
/// <param name="metadata"></param>
/// <param name="type"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task UpsertVectorAsync(
string identifier,
string text,
ReadOnlyMemory<float> embedding,
Dictionary<string, string> metadata = null,
string type = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (
embedding.IsEmpty ||
text.IsNullOrEmpty() ||
identifier.IsNullOrEmpty()
)
{
XException.InvalidArgs.Throw();
}
//
var exists = await vectorRepository.FindOneAsync(
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: x => x.Identifier == identifier
);
var isExists = !exists.IsNullOrDefault();
if (isExists)
{
//
exists.Text = text;
exists.Embedding = embedding.ToJSON();
exists.Type = type.IsNullOrEmpty() ? exists.Type : type;
exists.Metadata = metadata.IsNullOrDefault() ? exists.Metadata : metadata.ToJSON();
}
else
{
//
exists = new XAiVector
{
Text = text,
Type = type,
Identifier = identifier,
Metadata = metadata.ToJSON(),
Embedding = embedding.ToJSON(),
};
}
//
await vectorRepository.AddOrUpdateAsync(
item: exists,
saveChanges: true,
cancellationToken: cancellationToken
);
}
/// <summary>
/// Search Vectors by Cosine Similarity (Top K) ...
/// </summary>
/// <param name="queryEmbedding"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="identifierPrefix"></param>
/// <param name="type"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IReadOnlyList<XAiVectorSearchResult>> SearchVectorsAsync(
ReadOnlyMemory<float> queryEmbedding,
int topK = 5,
float minScore = 0f,
string identifierPrefix = null,
string type = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (
topK <= 0 ||
queryEmbedding.IsEmpty
)
{
XException.InvalidArgs.Throw();
}
//
// Normalize ...
if (type.IsNullOrEmpty())
{
type = XAiModelsConstants.XAiDefaultKnowledgeType;
}
//
// Converts Question Vector to Vector Array ...
var queryVector = queryEmbedding.ToArray();
var scoredResult = new List<(XAiVectorSearchResult Result, float Score)>();
//
// Load Candidates (Restricted by Prefix / Type when Provided) ...
var predicateExp = BuildVectorPredicateExpression(identifierPrefix, type);
IAsyncEnumerable<XAiVector> candidates;
if (predicateExp.IsNull())
{
//
candidates = vectorRepository
.GetAllAsAsyncEnumerable(
ignoreSoftDeleteds: true,
orderBuilder: null,
includeBuilder: null
);
}
else
{
//
candidates = (await vectorRepository
.FindManyAsync(
predicate: predicateExp,
ignoreSoftDeleteds: true,
orderBuilder: null,
includeBuilder: null,
cancellationToken: cancellationToken
))
.ToAsyncEnumerable();
}
//
await foreach (var vector in candidates.WithCancellation(cancellationToken))
{
//
// Validate Vector ...
if (vector.Embedding.IsNullOrEmpty())
{
continue;
}
//
// Ignore Unsame Vectors ...
var embd = vector.Embedding.AsEmbedding();
if (
embd.IsNull() ||
embd.Length != queryEmbedding.Length
)
{
continue;
}
//
// Calculate Cosine Similarity Score ...
var score = VectorHelper.CosineSimilarity(queryVector, embd);
if (score < minScore)
{
continue;
}
//
scoredResult.Add((new XAiVectorSearchResult
{
//
Score = score,
Id = vector.Id,
Text = vector.Text,
Type = vector.Type,
Identifier = vector.Identifier,
Metadata = vector.Metadata.AsMetadat(),
}, score));
}
//
var result = scoredResult
.OrderByDescending(x => x.Score)
.Take(topK)
.Select(x => x.Result)
.ToList();
//
return result;
}
/// <summary>
/// Insert or Update a Batch of Vectors (Matched by Identifier) ...
/// </summary>
/// <param name="items"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Stored Vectors</returns>
public async Task<int> UpsertVectorsAsync(
IEnumerable<XAiVectorDto> items,
CancellationToken cancellationToken = default
)
{
//
// Validate & Normalize (Last One Wins on Duplicate Identifiers) ...
var validItems = (items ?? [])
.Where(x =>
!x.IsNullOrDefault() &&
!x.Embedding.IsEmpty &&
!x.Text.IsNullOrEmpty() &&
!x.Identifier.IsNullOrEmpty()
)
.GroupBy(x => x.Identifier)
.Select(g => g.Last())
.ToList();
if (!validItems.HasChild())
{
return 0;
}
//
// Load Existing Vectors with Same Identifiers ...
var identifiers = validItems
.Select(x => x.Identifier)
.ToList();
var existings = await vectorRepository.FindManyAsync(
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: x => identifiers.Contains(x.Identifier)
);
var existingMap = (existings ?? [])
.GroupBy(x => x.Identifier)
.ToDictionary(g => g.Key, g => g.First());
//
// Split to Insert / Update ...
var toAdd = new List<XAiVector>();
var toUpdate = new List<XAiVector>();
foreach (var item in validItems)
{
//
if (existingMap.TryGetValue(item.Identifier, out var exists))
{
//
exists.Text = item.Text;
exists.Embedding = item.Embedding.ToEmbedding();
exists.Type = item.Type.IsNullOrEmpty() ? exists.Type : item.Type;
exists.Metadata = item.Metadata.IsNullOrDefault() ? exists.Metadata : item.Metadata.ToJSON();
toUpdate.Add(exists);
}
else
{
//
toAdd.Add(new XAiVector
{
Text = item.Text,
Type = item.Type,
Identifier = item.Identifier,
Metadata = item.Metadata.ToJSON(),
Embedding = item.Embedding.ToEmbedding(),
Id = item.Id.IsDefaultGuid() ? Guid.NewGuid() : item.Id,
});
}
}
//
if (toUpdate.HasChild())
{
await vectorRepository.UpdateRangeAsync(
items: toUpdate,
saveChanges: false,
cancellationToken: cancellationToken
);
}
if (toAdd.HasChild())
{
await vectorRepository.AddRangeAsync(
items: toAdd,
saveChanges: false,
cancellationToken: cancellationToken
);
}
//
await vectorRepository.SaveChangesAsync(cancellationToken);
//
var result = toAdd.Count + toUpdate.Count;
return result;
}
/// <summary>
/// Load Vectors whose Identifier Starts with Specified Prefix ...
/// </summary>
/// <param name="identifierPrefix"></param>
/// <param name="includeEmbedding"></param>
/// <param name="type"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IReadOnlyList<XAiVectorDto>> LoadVectorsAsync(
string identifierPrefix,
bool includeEmbedding = false,
string type = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (identifierPrefix.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var vectors = await vectorRepository.FindManyAsync(
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: BuildVectorPredicateExpression(identifierPrefix, type)
);
//
var result = (vectors ?? [])
.Select(v => new XAiVectorDto
{
Id = v.Id,
Text = v.Text,
Type = v.Type,
Identifier = v.Identifier,
Metadata = v.Metadata.AsMetadat(),
Embedding = includeEmbedding ? v.Embedding.AsEmbedding() : null,
})
.ToList();
//
return result;
}
/// <summary>
/// Remove Vectors whose Identifier Starts with Specified Prefix ...
/// </summary>
/// <param name="identifierPrefix"></param>
/// <param name="type"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Removed Vectors</returns>
public async Task<int> RemoveVectorsAsync(
string identifierPrefix,
string type = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (identifierPrefix.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var vectors = await vectorRepository.FindManyAsync(
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: BuildVectorPredicateExpression(identifierPrefix, type)
);
var toRemove = (vectors ?? []).ToList();
if (!toRemove.HasChild())
{
return 0;
}
//
// Hard Delete (Vectors are Disposable Data) ...
await vectorRepository.RemoveRangeAsync(
items: toRemove,
softDelete: false,
saveChanges: true,
cancellationToken: cancellationToken
);
//
var result = toRemove.Count;
return result;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Specified Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiVectorDto> Enrich(
XAiVector source,
CancellationToken cancellationToken = default
)
{
//
var result = await vectorEnricher.Enrich(
source: source,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Items ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiVectorDto>> EnrichRange(
IEnumerable<XAiVector> sources,
CancellationToken cancellationToken = default
)
{
//
var result = await vectorEnricher.EnrichRange(
sources: sources,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiVectorDto> Enrich(
XAiVectorDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await vectorEnricher.Enrich(
source: source,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Items ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiVectorDto>> EnrichRange(
IEnumerable<XAiVectorDto> sources,
CancellationToken cancellationToken = default
)
{
//
var result = await vectorEnricher.EnrichRange(
sources: sources,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="fillConversations"></param>
/// <param name="fillConversationMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiProjectDto> Enrich(
XAiProjectDto source,
bool fillConversations = false,
bool fillConversationMessages = false,
CancellationToken cancellationToken = default
)
{
//
var result = await projectEnricher.Enrich(
source: source,
fillConversations: fillConversations,
cancellationToken: cancellationToken,
fillConversationMessages: fillConversationMessages
);
//
return result;
}
/// <summary>
/// Enrich Specified Items ...
/// </summary>
/// <param name="sources"></param>
/// <param name="fillConversations"></param>
/// <param name="fillConversationMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiProjectDto>> EnrichRange(
IEnumerable<XAiProjectDto> sources,
bool fillConversations = false,
bool fillConversationMessages = false,
CancellationToken cancellationToken = default
)
{
//
var result = await projectEnricher.EnrichRange(
sources: sources,
fillConversations: fillConversations,
cancellationToken: cancellationToken,
fillConversationMessages: fillConversationMessages
);
//
return result;
}
/// <summary>
/// Enrich Specified Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="fillMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiConversationDto> Enrich(
XAiConversationDto source,
bool fillMessages = false,
CancellationToken cancellationToken = default
)
{
//
var result = await conversationEnricher.Enrich(
source: source,
fillMessages: fillMessages,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Items ...
/// </summary>
/// <param name="sources"></param>
/// <param name="fillMessages"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiConversationDto>> EnrichRange(
IEnumerable<XAiConversationDto> sources,
bool fillMessages = false,
CancellationToken cancellationToken = default
)
{
//
var result = await conversationEnricher.EnrichRange(
sources: sources,
fillMessages: fillMessages,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiMessageDto> Enrich(
XAiMessageDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await messageEnricher.Enrich(
source: source,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Specified Items ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiMessageDto>> EnrichRange(
IEnumerable<XAiMessageDto> sources,
CancellationToken cancellationToken = default
)
{
//
var result = await messageEnricher.EnrichRange(
sources: sources,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
//
#region Private ...
/// <summary>
/// Check Default Project Exists or not ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<bool> HasDefaultProject(
string ownerId,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
var result = !ownerId.IsNullOrEmpty();
if (!result)
{
return result;
}
//
// Check Default Owner Exists or not ...
var defaultProjectResource = await stringProvider.FindOne(
cancellationToken: cancellationToken,
predicate: x =>
x.ResourceTitle
.ToNormalString()
.Contains(ownerId.ToNormalString()) &&
x.ResourceTitle
.ToNormalString()
.Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) &&
x.TranslatedValue
.ToNormalString()
.Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix.ToNormalString())
);
result = !defaultProjectResource.IsNullOrDefault();
//
return result;
}
/// <summary>
/// Create Default Project for Specified Owner ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task CreateDefaultProject(
string ownerId,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
if (ownerId.IsNullOrEmpty())
{
return;
}
//
var defaultLang = appConfiguration.DefaultLanguage;
//
// Check Default Owner Exists or not ...
var isExists = await HasDefaultProject(
ownerId: ownerId,
cancellationToken: cancellationToken
);
if (isExists)
{
return;
}
//
// Create Default ...
var item = new XAiProjectDto()
{
OwnerId = ownerId,
CreatedOn = DateTime.UtcNow,
Title = Guid.NewGuid().ToString(),
Description = Guid.NewGuid().ToString(),
};
item = await projectRepositoryService.AddAsync(
item: item,
saveChanges: true,
cancellationToken: cancellationToken
);
//
// Prepare Tile and Description Resource Ids ...
var titleResource = await projectTitleResourceProvider.AddOrUpdateLocale(
owner: ownerId,
identifier: item.Id,
locale: new XLocaleResourceDto
{
Language = defaultLang,
Value = XAiDataProviderConstants.XDefaultAiProjectSuffix
},
cancellationToken: cancellationToken
);
var descriptionResource = await projectDescriptionResourceProvider.AddOrUpdateLocale(
owner: ownerId,
identifier: item.Id,
new XLocaleResourceDto
{
Language = defaultLang,
Value = XAiDataProviderConstants.XDefaultAiProjectSuffix
},
cancellationToken: cancellationToken
);
if (titleResource.IsNullOrDefault() ||
descriptionResource.IsNullOrDefault()
)
{
return;
}
//
// Update Project Resources ...
item.Title = titleResource.Resource;
item.Description = descriptionResource.Resource;
item = await projectRepositoryService.UpdateAsync(
id: item.Id,
item: item,
saveChanges: true,
cancellationToken: cancellationToken
);
//
// Sending Push ...
if (!connectionId.IsNullOrEmpty())
{
//
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: item.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.ProjectCreated.GetStringValue()
);
}
}
/// <summary>
/// Check Default Conversation Exists or not ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="projectId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<bool> HasDefaultConversation(
string ownerId,
Guid? projectId,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
var result = !ownerId.IsNullOrEmpty();
if (!result)
{
return result;
}
//
// Prepare Project ...
XAiProjectDto project = null;
if (!projectId.HasValue ||
projectId.Value.IsDefaultGuid()
)
{
//
project = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
else
{
//
project = await projectRepositoryService.GetAsync(
id: projectId.Value,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
}
if (project.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Check Default Owner Exists or not ...
var resource = await stringProvider.FindOne(
cancellationToken: cancellationToken,
predicate: x =>
x.ResourceTitle
.ToNormalString()
.Contains(ownerId.ToString().ToNormalString()) &&
x.ResourceTitle
.ToNormalString()
.Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) &&
x.TranslatedValue
.ToNormalString()
.Contains(XAiDataProviderConstants.XDefaultAiConversationSuffix.ToNormalString())
);
result = !resource.IsNullOrDefault();
if (!result)
{
return result;
}
//
var defaultConversation = await conversationRepositoryService.FindOneAsync(
cancellationToken: cancellationToken,
predicate: x =>
x.ProjectId == project.Id &&
x.Title == resource.ResourceTitle
);
result = !defaultConversation.IsNullOrDefault();
//
return result;
}
/// <summary>
/// Check Default Conversation Exists or not ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="projectId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task CreateDefaultConversation(
string ownerId,
Guid? projectId,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
var isValid = !ownerId.IsNullOrEmpty();
if (!isValid)
{
return;
}
//
var defaultLang = appConfiguration.DefaultLanguage;
//
// Prepare Project ...
XAiProjectDto project = null;
if (!projectId.HasValue ||
projectId.Value.IsDefaultGuid()
)
{
//
project = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
else
{
//
project = await projectRepositoryService.GetAsync(
id: projectId.Value,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
}
if (project.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Check Default Owner Exists or not ...
isValid = await HasDefaultConversation(
ownerId: ownerId,
projectId: project.Id,
cancellationToken: cancellationToken
);
if (isValid)
{
return;
}
//
// Create Default Conversation ...
var item = new XAiConversationDto
{
OwnerId = ownerId,
ProjectId = project.Id,
CreatedOn = DateTime.UtcNow,
Title = Guid.NewGuid().ToString()
};
item = await conversationRepositoryService.AddAsync(
item: item,
saveChanges: true,
cancellationToken: cancellationToken
);
//
// Prepare Title Resource Ids ...
var titleResource = await conversationTitleResourceProvider.AddOrUpdateLocale(
owner: ownerId,
identifier: item.Id,
locale: new XLocaleResourceDto
{
Language = defaultLang,
Value = XAiDataProviderConstants.XDefaultAiConversationSuffix
},
cancellationToken: cancellationToken
);
if (titleResource.IsNullOrDefault())
{
return;
}
//
// Update Conversation Resources ...
item.Title = titleResource.Resource;
item = await conversationRepositoryService.UpdateAsync(
item: item,
id: item.Id,
saveChanges: true,
cancellationToken: cancellationToken
);
//
// Sending Push ...
if (!connectionId.IsNullOrEmpty())
{
//
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: item.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.ConversationCreated.GetStringValue()
);
}
}
/// <summary>
/// Send Custom Push Message ...
/// </summary>
/// <param name="action"></param>
/// <param name="payLoad"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task SendPush(
string action,
string payLoad,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Collect Allowed Actions ...
var actions = new List<string>
{
XAiDataProviderHubActions.ProjectCreated.GetStringValue(),
XAiDataProviderHubActions.ProjectUpdated.GetStringValue(),
XAiDataProviderHubActions.ProjectRemoved.GetStringValue(),
XAiDataProviderHubActions.MessageCreated.GetStringValue(),
XAiDataProviderHubActions.MessageUpdated.GetStringValue(),
XAiDataProviderHubActions.MessageRemoved.GetStringValue(),
XAiDataProviderHubActions.ConversationCreated.GetStringValue(),
XAiDataProviderHubActions.ConversationUpdated.GetStringValue(),
XAiDataProviderHubActions.ConversationRemoved.GetStringValue(),
};
//
// Validate Args ...
var isValid =
!action.IsNullOrEmpty() &&
actions.Contains(action);
if (!isValid)
{
return;
}
//
// Retrieve Connection Id ...
var clients = hub.Clients.All;
if (!connectionId.IsNullOrEmpty())
{
clients = hub.Clients.AllExcept(connectionId);
}
//
await clients.SendAsync(
action,
payLoad,
connectionId,
cancellationToken
);
}
catch { }
}
/// <summary>
/// Build Database Predicate Expression for Vectors by Optional Identifier Prefix and Type ...
/// Returns null when no Filter Provided ...
/// </summary>
/// <param name="identifierPrefix"></param>
/// <param name="type"></param>
/// <returns></returns>
private Expression<Func<XAiVector, bool>> BuildVectorPredicateExpression(
string identifierPrefix,
string type
)
{
//
Expression<Func<XAiVector, bool>> result = null;
//
var hasType = !type.IsNullOrEmpty();
var hasPrefix = !identifierPrefix.IsNullOrEmpty();
//
if (hasPrefix && hasType)
{
//
result = x => x.Identifier
.StartsWith(identifierPrefix) && x.Type == type;
}
else if (hasPrefix)
{
//
result = x => x.Identifier
.StartsWith(identifierPrefix);
}
else if (hasType)
{
result = x => x.Type == type;
}
//
return result;
}
#endregion
}
}