- XAIServiceBase: add PrepareChatRequirementsAsync as the single entry point for chat prerequisites (normalize RAG params, resolve default project/conversation, ingest attachments, retrieve RAG context, build history, persist prompt message) and return the new XPreparedChatContext; - XAIServiceBase: add NormalizeRagParams (topK / minScore / type) and use it in all Ask* methods instead of duplicated inline normalization; - XAIServiceBase: rework GetHistory - the single GetHistory(ChatMessage, bool) signature is replaced by two overloads GetHistory(prompt, forcePrompt) and GetHistory(prompt, context); the latter is used by the non-persisted chat path; - XAIServiceBase: remove AskLLMAsync; LLM invocation is now inlined in each Ask* method over prep.History; - XAIServiceBase: rewrite AskAsync and AskAsEnumerable on top of PrepareChatRequirementsAsync; streamed responses now use Role = Assistant, RespondTo = prep.PersistedPromptMessage.Id and Sequence++; - XAIServiceBase: use XAiApiConstants.XAiApiRagPromptName instead of configuration.RAGDescriptor.PromptName; - XAIServiceBase.LoadConversations: call the renamed GetDafaultProject; - Add Models/XPreparedChatContext.cs (Project, Conversation, History, Context, PersistedPromptMessage) as the shared context between actions; - XAiRAGService: wrap each file ingest in its own try/catch with logger.LogError so one bad file no longer aborts the whole ingest; - XAiRAGService: upload the file and add a scope reference (providedFor / forProvidedId) for the ingested scope; - XAiRAGService: remove stale vectors of the same document via RemoveVectorsAsync(identifierPrefix) when replaceExisting is set; - XInMemoryVectorStore: make session retrieval thread-safe via lock (found.SyncRoot) and ReferenceEquals check against concurrent removal; - XAiServiceControllerBase.Ask: pass the attached files to the AI service (was files: null) so RAG works on attachments; - XModelsExtensions: relax ChatWithDocuments ask validation - TopK and MinScore are optional again (defaults come from RAGDescriptor); - XAiModelProxyMiddleware: use logical OR instead of bitwise OR in the authentication check; - XAiEmbeddingServiceBase: do not dispose the embedding generator (removed `using` to avoid premature disposal); - ChatWithDocumentsController: reorder EmbedChunks parameters; - Remove Interfaces/IXAiEmbeddingServiceControllerBase.cs.
1084 lines
38 KiB
C#
1084 lines
38 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using xAiApi.Models;
|
|
using xIdentityHelper;
|
|
using System.Threading;
|
|
using xAiApi.Interfaces;
|
|
using xAiModels.Constants;
|
|
using xCommons.Extensions;
|
|
using xAiModels.Interfaces;
|
|
using xAiApi.Configurations;
|
|
using xExceptions.Constants;
|
|
using xAiModels.Models.Dtos;
|
|
using System.Threading.Tasks;
|
|
using xIdentityModels.Models;
|
|
using xFileService.Interfaces;
|
|
using Microsoft.AspNetCore.Http;
|
|
using System.Collections.Generic;
|
|
using Microsoft.Extensions.Logging;
|
|
using xAiApi.Interfaces.Extractors;
|
|
using xFileService.Models.Dtos;
|
|
|
|
namespace xAiApi.Providers
|
|
{
|
|
/// <summary>
|
|
/// Persistent RAG Service over XAiVector Table ...
|
|
/// Isolation (Identifier Layout):
|
|
/// Conversation: "conversation/{conversationId}/{fileName}#{i}"
|
|
/// Project : "project/{projectId}/{fileName}#{i}"
|
|
/// User : "user/{ownerId}/{fileName}#{i}"
|
|
/// Global : "global/{fileName}#{i}"
|
|
/// Retrieval is Tiered: Conversation -> Project -> User -> Global ...
|
|
/// </summary>
|
|
public class XAiRAGService : IXAiRAGService
|
|
{
|
|
private readonly IXTextChunker textChunker;
|
|
private readonly IXFileProvider fileProvider;
|
|
private readonly IXAiDataProvider dataProvider;
|
|
private readonly ILogger<XAiRAGService> logger;
|
|
private readonly XAiApiConfiguration configuration;
|
|
private readonly IXAiEmbeddingService embeddingService;
|
|
private readonly IXFileContentExtractor fileContentExtractor;
|
|
|
|
/// <summary>
|
|
/// Characters which are not Allowed in File Name Part of Identifier ...
|
|
/// </summary>
|
|
private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#'];
|
|
|
|
public XAiRAGService(
|
|
IXTextChunker textChunker,
|
|
IXFileProvider fileProvider,
|
|
IXAiDataProvider dataProvider,
|
|
ILogger<XAiRAGService> logger,
|
|
XAiApiConfiguration configuration,
|
|
IXAiEmbeddingService embeddingService,
|
|
IXFileContentExtractor fileContentExtractor
|
|
)
|
|
{
|
|
//
|
|
this.logger = logger;
|
|
this.textChunker = textChunker;
|
|
this.fileProvider = fileProvider;
|
|
this.dataProvider = dataProvider;
|
|
this.configuration = configuration;
|
|
this.embeddingService = embeddingService;
|
|
this.fileContentExtractor = fileContentExtractor;
|
|
}
|
|
|
|
//
|
|
#region Ingest ...
|
|
/// <summary>
|
|
/// Ingest Files into Specified Knowledge Scope:
|
|
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
|
/// </summary>
|
|
/// <param name="files"></param>
|
|
/// <param name="scope"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="replaceExisting"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XAiKnowledgeIngestResult> IngestAsync(
|
|
IFormFileCollection files,
|
|
XAiKnowledgeScopeDescriptor scope = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
string connectionId = null,
|
|
bool replaceExisting = true,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (!files.HasChild() || !IsValidUser(userInfo))
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
if (rag.MaxFilesPerIngest > 0 && files.Count > rag.MaxFilesPerIngest)
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// Resolve & Authorize Scope (Write) ...
|
|
scope = NormalizeScope(scope);
|
|
await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);
|
|
|
|
//
|
|
var knowledgeType = scope.Type.IsNullOrEmpty()
|
|
? XAiModelsConstants.XAiDefaultKnowledgeType
|
|
: scope.Type;
|
|
var scopePrefix = GetScopePrefix(scope, userInfo);
|
|
|
|
//
|
|
var result = new XAiKnowledgeIngestResult
|
|
{
|
|
Type = knowledgeType,
|
|
Scope = scope.Scope,
|
|
ScopeId = scope.ScopeId,
|
|
};
|
|
var ingestedAt = DateTime.UtcNow;
|
|
var ingestedAtUtc = ingestedAt.ToString("O");
|
|
|
|
//
|
|
// Existing Documents (for MaxDocumentsPerScope Limit) ...
|
|
var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);
|
|
|
|
//
|
|
// Loop through Files ...
|
|
foreach (var file in files)
|
|
{
|
|
//
|
|
XFileDto uploadedFile = null;
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
//
|
|
if (file.IsNull() || file.Length == 0)
|
|
{
|
|
result.SkippedFiles.Add(file?.FileName ?? "(null)");
|
|
continue;
|
|
}
|
|
|
|
//
|
|
// Size Limit ...
|
|
if (rag.MaxFileSizeBytes > 0 && file.Length > rag.MaxFileSizeBytes)
|
|
{
|
|
result.SkippedFiles.Add(file.FileName);
|
|
continue;
|
|
}
|
|
|
|
//
|
|
var fileName = NormalizeFileName(file.FileName);
|
|
if (fileName.IsNullOrEmpty())
|
|
{
|
|
result.SkippedFiles.Add(file.FileName);
|
|
continue;
|
|
}
|
|
|
|
//
|
|
// Documents per Scope Limit (Global Unlimited; Re-Ingest of Existing Doc Allowed) ...
|
|
var isNewDocument = !existingDocuments.Contains(fileName);
|
|
if (
|
|
isNewDocument &&
|
|
scope.Scope != XAiKnowledgeScope.Global &&
|
|
rag.MaxDocumentsPerScope > 0 &&
|
|
existingDocuments.Count >= rag.MaxDocumentsPerScope
|
|
)
|
|
{
|
|
result.SkippedFiles.Add(file.FileName);
|
|
continue;
|
|
}
|
|
|
|
//
|
|
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
|
|
if (!fileContentExtractor.CanExtract(mimeType))
|
|
{
|
|
result.SkippedFiles.Add(file.FileName);
|
|
continue;
|
|
}
|
|
|
|
//
|
|
var text = await ExtractText(file, mimeType, cancellationToken);
|
|
if (text.IsNullOrEmpty())
|
|
{
|
|
result.SkippedFiles.Add(file.FileName);
|
|
continue;
|
|
}
|
|
|
|
//
|
|
// Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ...
|
|
var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}");
|
|
if (!chunks.HasChild())
|
|
{
|
|
result.SkippedFiles.Add(file.FileName);
|
|
continue;
|
|
}
|
|
|
|
//
|
|
// Handle File Save ...
|
|
uploadedFile = await fileProvider.Upload(
|
|
file: file,
|
|
userInfo: userInfo,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Add Reference File to Prompt Message ...
|
|
if (
|
|
!uploadedFile.IsNullOrDefault() &&
|
|
scope.ScopeId.HasValue &&
|
|
!uploadedFile.Id.IsDefaultGuid()
|
|
)
|
|
{
|
|
//
|
|
await fileProvider.AddReference(
|
|
userInfo: userInfo,
|
|
id: uploadedFile.Id,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken,
|
|
providedFor: scope.Scope.GetStringValue(),
|
|
forProvidedId: scope.ScopeId.Value.ToString()
|
|
);
|
|
}
|
|
|
|
//
|
|
// Embed in Batches ...
|
|
var vectors = await EmbedChunks(
|
|
scope: scope,
|
|
chunks: chunks,
|
|
fileName: fileName,
|
|
mimeType: mimeType,
|
|
type: knowledgeType,
|
|
ownerId: userInfo.UserId,
|
|
ingestedAtUtc: ingestedAtUtc,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Remove Stale Vectors of Same Document ...
|
|
if (replaceExisting)
|
|
{
|
|
//
|
|
result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
|
|
cancellationToken: cancellationToken,
|
|
identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName)
|
|
);
|
|
}
|
|
|
|
//
|
|
// Store ...
|
|
var storedCount = await dataProvider.UpsertVectorsAsync(
|
|
items: vectors,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
existingDocuments.Add(fileName);
|
|
result.FilesCount++;
|
|
result.ChunksCount += storedCount;
|
|
result.Documents.Add(new XAiKnowledgeDocumentInfo
|
|
{
|
|
FileName = fileName,
|
|
MimeType = mimeType,
|
|
Type = knowledgeType,
|
|
Scope = scope.Scope,
|
|
ScopeId = scope.ScopeId,
|
|
ChunksCount = storedCount,
|
|
OwnerId = userInfo.UserId,
|
|
IngestedAtUtc = ingestedAt,
|
|
});
|
|
|
|
//
|
|
logger.LogInformation(
|
|
"Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks",
|
|
fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount
|
|
);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
//
|
|
logger.LogError(ex, "Ingesting Failed ...");
|
|
|
|
//
|
|
// Removing Uploaded File if Chuncking Failed ...
|
|
if (!uploadedFile.IsNullOrDefault() &&
|
|
!uploadedFile.Id.IsDefaultGuid()
|
|
)
|
|
{
|
|
//
|
|
await fileProvider.Remove(
|
|
id: uploadedFile.Id,
|
|
userInfo: userInfo,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Ask ...
|
|
/// <summary>
|
|
/// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
|
|
/// Each Tier Fills Remaining TopK; Duplicates are Removed ...
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
|
XAiKnowledgeAskRequest request,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (
|
|
request.IsNullOrDefault() ||
|
|
request.Prompt.IsNullOrEmpty() ||
|
|
!IsValidUser(userInfo)
|
|
)
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
var effectiveTopK = Math.Clamp(request.TopK ?? rag.DefaultTopK, 1, rag.MaxTopK);
|
|
var effectiveMinScore = request.MinScore ?? rag.DefaultMinScore;
|
|
|
|
//
|
|
// Resolve Tiers (with Ownership Checks) before Embedding ...
|
|
var tiers = await ResolveTiers(request, userInfo, cancellationToken);
|
|
if (!tiers.HasChild())
|
|
{
|
|
return [];
|
|
}
|
|
|
|
//
|
|
// Embed Question (Once) ...
|
|
var queryEmbedding = await embeddingService.Embedding(
|
|
content: request.Prompt,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
|
|
{
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
var fileName = NormalizeFileName(request.FileName);
|
|
var result = new List<XAiVectorSearchResult>();
|
|
var seen = new HashSet<string>(StringComparer.Ordinal);
|
|
foreach (var tier in tiers)
|
|
{
|
|
//
|
|
var remaining = effectiveTopK - result.Count;
|
|
if (remaining <= 0)
|
|
{
|
|
break;
|
|
}
|
|
|
|
//
|
|
var scopePrefix = GetScopePrefix(tier, userInfo);
|
|
var prefix = fileName.IsNullOrEmpty()
|
|
? scopePrefix
|
|
: GetDocumentChunkPrefix(scopePrefix, fileName);
|
|
|
|
//
|
|
var searchResult = await dataProvider.SearchVectorsAsync(
|
|
topK: remaining,
|
|
type: request.Type,
|
|
identifierPrefix: prefix,
|
|
minScore: effectiveMinScore,
|
|
queryEmbedding: queryEmbedding,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
foreach (var item in searchResult ?? [])
|
|
{
|
|
if (seen.Add(item.Identifier ?? item.Id.ToString()))
|
|
{
|
|
result.Add(item);
|
|
}
|
|
}
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Documents ...
|
|
/// <summary>
|
|
/// List Ingested Documents of Specified Scope ...
|
|
/// </summary>
|
|
/// <param name="scope"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
|
XAiKnowledgeScopeDescriptor scope = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (!IsValidUser(userInfo))
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// Resolve & Authorize Scope (Read) ...
|
|
scope = NormalizeScope(scope);
|
|
await EnsureAccess(scope, userInfo, isWrite: false, cancellationToken);
|
|
|
|
//
|
|
var vectors = await dataProvider.LoadVectorsAsync(
|
|
type: scope.Type,
|
|
includeEmbedding: false,
|
|
cancellationToken: cancellationToken,
|
|
identifierPrefix: GetScopePrefix(scope, userInfo)
|
|
);
|
|
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
var result = (vectors ?? [])
|
|
.GroupBy(v => v.Metadata.GetMetadata(rag.MetadataFileName).IsNullOrEmpty()
|
|
? v.Identifier
|
|
: v.Metadata.GetMetadata(rag.MetadataFileName))
|
|
.Select(g =>
|
|
{
|
|
//
|
|
var first = g.First();
|
|
var ingestedText = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc);
|
|
|
|
//
|
|
return new XAiKnowledgeDocumentInfo
|
|
{
|
|
FileName = g.Key,
|
|
Type = first.Type,
|
|
Scope = scope.Scope,
|
|
ChunksCount = g.Count(),
|
|
ScopeId = scope.ScopeId,
|
|
MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType),
|
|
OwnerId = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataOwnerId),
|
|
IngestedAtUtc = DateTime.TryParse(
|
|
ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
|
|
) ? dt : null
|
|
};
|
|
})
|
|
.OrderBy(d => d.FileName)
|
|
.ToList();
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Remove All Vectors of a Document in Specified Scope ...
|
|
/// </summary>
|
|
/// <param name="fileName"></param>
|
|
/// <param name="scope"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns>Count of Removed Vectors</returns>
|
|
public async Task<int> RemoveDocumentAsync(
|
|
string fileName,
|
|
XAiKnowledgeScopeDescriptor scope = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
string connectionId = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
var normalizedFileName = NormalizeFileName(fileName);
|
|
if (normalizedFileName.IsNullOrEmpty() || !IsValidUser(userInfo))
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// Resolve & Authorize Scope (Write) ...
|
|
scope = NormalizeScope(scope);
|
|
await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);
|
|
|
|
//
|
|
var result = await dataProvider.RemoveVectorsAsync(
|
|
cancellationToken: cancellationToken,
|
|
identifierPrefix: GetDocumentChunkPrefix(GetScopePrefix(scope, userInfo), normalizedFileName)
|
|
);
|
|
if (result > 0)
|
|
{
|
|
//
|
|
// Remove Files using ...
|
|
var file = await fileProvider.FindOne(
|
|
x => x.FileName
|
|
.Equals(
|
|
fileName,
|
|
StringComparison.InvariantCultureIgnoreCase) &&
|
|
x.OwnerId
|
|
.Equals(
|
|
userInfo.UserId,
|
|
StringComparison.InvariantCultureIgnoreCase),
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
if (!file.IsNullOrDefault())
|
|
{
|
|
//
|
|
await fileProvider.Remove(
|
|
id: file.Id,
|
|
userInfo: userInfo,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
}
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
|
|
/// Store First then Remove Legacy (no Data Loss on Failure); Idempotent ...
|
|
/// </summary>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns>Count of Migrated Vectors</returns>
|
|
public async Task<int> MigrateLegacyVectorsAsync(
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (!IsValidUser(userInfo))
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var legacyPrefix = $"{userInfo.UserId}{XAiModelsConstants.XAiKnowledgeOwnerSeparator}";
|
|
var legacyVectors = await dataProvider.LoadVectorsAsync(
|
|
includeEmbedding: true,
|
|
identifierPrefix: legacyPrefix,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (!legacyVectors.HasChild())
|
|
{
|
|
return 0;
|
|
}
|
|
|
|
//
|
|
var scope = XAiKnowledgeScopeDescriptor.User();
|
|
var scopePrefix = GetScopePrefix(scope, userInfo);
|
|
var migrated = legacyVectors
|
|
.Select(v =>
|
|
{
|
|
//
|
|
var type = v.Type.IsNullOrEmpty() ? XAiModelsConstants.XAiDefaultKnowledgeType : v.Type;
|
|
var metadata = v.Metadata ?? new Dictionary<string, string>();
|
|
metadata[XAiModelsConstants.XAiKnowledgeMetadataType] = type;
|
|
metadata[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = string.Empty;
|
|
metadata[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString();
|
|
metadata[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = userInfo.UserId;
|
|
|
|
//
|
|
return new XAiVectorDto
|
|
{
|
|
Type = type,
|
|
Text = v.Text,
|
|
Metadata = metadata,
|
|
Embedding = v.Embedding,
|
|
Identifier = $"{scopePrefix}{v.Identifier.Substring(legacyPrefix.Length)}",
|
|
};
|
|
})
|
|
.ToList();
|
|
|
|
//
|
|
var result = await dataProvider.UpsertVectorsAsync(
|
|
items: migrated,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
await dataProvider.RemoveVectorsAsync(
|
|
identifierPrefix: legacyPrefix,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
logger.LogInformation(
|
|
"Knowledge: Migrated {Count} Legacy Vectors of {OwnerId} into User Scope",
|
|
result, userInfo.UserId
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Map Search Results to Public Sources ...
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
/// <returns></returns>
|
|
public IList<XAiDocumentSource> ToSources(
|
|
IEnumerable<XAiVectorSearchResult> context
|
|
)
|
|
{
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
var result = (context ?? [])
|
|
.Select(c =>
|
|
{
|
|
//
|
|
var text = c.Text ?? string.Empty;
|
|
var snippetLength = Math.Min(text.Length, rag.SourceSnippetLength);
|
|
var chunkIndexText = c.Metadata.GetMetadata(rag.MetadataChunkIndex);
|
|
|
|
//
|
|
return new XAiDocumentSource
|
|
{
|
|
Type = c.Type,
|
|
Score = c.Score,
|
|
Identifier = c.Identifier,
|
|
Snippet = text.Substring(0, snippetLength),
|
|
FileName = c.Metadata.GetMetadata(rag.MetadataFileName),
|
|
Scope = c.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataScope),
|
|
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
|
|
};
|
|
})
|
|
.ToList();
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Private ...
|
|
/// <summary>
|
|
/// Extract Plain Text of a File (Text or Audio Transcript) ...
|
|
/// </summary>
|
|
private async Task<string> ExtractText(
|
|
IFormFile file,
|
|
string mimeType,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
try
|
|
{
|
|
//
|
|
using var stream = file.OpenReadStream();
|
|
var extraction = await fileContentExtractor.ExtractRichAsync(
|
|
fileStream: stream,
|
|
mimeType: mimeType,
|
|
fileName: file.FileName,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
var result = extraction?.Text;
|
|
if (string.IsNullOrWhiteSpace(result))
|
|
{
|
|
result = extraction?.AudioTranscript;
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
|
|
/// </summary>
|
|
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
|
XAiKnowledgeScopeDescriptor scope,
|
|
IList<XTextChunk> chunks,
|
|
string type,
|
|
string ownerId,
|
|
string fileName,
|
|
string mimeType,
|
|
string ingestedAtUtc,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
var batchSize = Math.Max(1, rag.EmbeddingBatchSize);
|
|
var result = new List<XAiVectorDto>(chunks.Count);
|
|
|
|
//
|
|
for (var offset = 0; offset < chunks.Count; offset += batchSize)
|
|
{
|
|
//
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
//
|
|
var batch = chunks.Skip(offset).Take(batchSize).ToList();
|
|
var embeddings = await embeddingService.Embeddings(
|
|
batch: batch.Select(c => c.Text).ToArray(),
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
|
|
{
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
for (var i = 0; i < batch.Count; i++)
|
|
{
|
|
//
|
|
var chunk = batch[i];
|
|
result.Add(new XAiVectorDto
|
|
{
|
|
//
|
|
Type = type,
|
|
Text = chunk.Text,
|
|
Embedding = embeddings[i],
|
|
Identifier = chunk.Identifier,
|
|
Metadata = new Dictionary<string, string>
|
|
{
|
|
[rag.MetadataFileName] = fileName,
|
|
[rag.MetadataMimeType] = mimeType,
|
|
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
|
|
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
|
|
[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
|
[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
|
|
[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
|
|
[XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
//
|
|
#region Scope ...
|
|
/// <summary>
|
|
/// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
|
|
/// </summary>
|
|
private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
|
|
{
|
|
//
|
|
var result = scope ?? XAiKnowledgeScopeDescriptor.User();
|
|
switch (result.Scope)
|
|
{
|
|
case XAiKnowledgeScope.User:
|
|
case XAiKnowledgeScope.Global:
|
|
result.ScopeId = null;
|
|
break;
|
|
|
|
case XAiKnowledgeScope.Project:
|
|
case XAiKnowledgeScope.Conversation:
|
|
if (!result.ScopeId.HasValue || result.ScopeId.Value == Guid.Empty)
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
break;
|
|
|
|
default:
|
|
XException.InvalidArgs.Throw();
|
|
break;
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ensure Caller has Access to Scope:
|
|
/// User: Own Data | Global: Read = Everyone, Write = Admin
|
|
/// Project / Conversation: Caller must be Owner ...
|
|
/// </summary>
|
|
private async Task EnsureAccess(
|
|
XAiKnowledgeScopeDescriptor scope,
|
|
XUserClaimsInfoDto userInfo,
|
|
bool isWrite,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
switch (scope.Scope)
|
|
{
|
|
case XAiKnowledgeScope.Global:
|
|
if (isWrite && !IsAdmin(userInfo))
|
|
{
|
|
XException.NotAuthorized.Throw();
|
|
}
|
|
break;
|
|
|
|
case XAiKnowledgeScope.Project:
|
|
await EnsureProjectOwner(scope.ScopeId.Value, userInfo, cancellationToken);
|
|
break;
|
|
|
|
case XAiKnowledgeScope.Conversation:
|
|
await EnsureConversationOwner(scope.ScopeId.Value, userInfo, cancellationToken);
|
|
break;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ensure Caller Owns Project ...
|
|
/// </summary>
|
|
private async Task<XAiProjectDto> EnsureProjectOwner(
|
|
Guid projectId,
|
|
XUserClaimsInfoDto userInfo,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
var result = await dataProvider.GetProject(
|
|
id: projectId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (result.IsNullOrDefault())
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
|
|
{
|
|
XException.NotAuthorized.Throw();
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ensure Caller Owns Conversation ...
|
|
/// </summary>
|
|
private async Task<XAiConversationDto> EnsureConversationOwner(
|
|
Guid conversationId,
|
|
XUserClaimsInfoDto userInfo,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
var result = await dataProvider.GetConversation(
|
|
id: conversationId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (result.IsNullOrDefault())
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
|
|
{
|
|
XException.NotAuthorized.Throw();
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ...
|
|
/// </summary>
|
|
private async Task<IList<XAiKnowledgeScopeDescriptor>> ResolveTiers(
|
|
XAiKnowledgeAskRequest request,
|
|
XUserClaimsInfoDto userInfo,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
var result = new List<XAiKnowledgeScopeDescriptor>();
|
|
Guid? projectId = request.ProjectId.HasValue && request.ProjectId.Value != Guid.Empty
|
|
? request.ProjectId
|
|
: null;
|
|
|
|
//
|
|
// Conversation Tier (+ Implicit Project) ...
|
|
if (request.ConversationId.HasValue && request.ConversationId.Value != Guid.Empty)
|
|
{
|
|
//
|
|
var conversation = await EnsureConversationOwner(
|
|
request.ConversationId.Value, userInfo, cancellationToken
|
|
);
|
|
result.Add(XAiKnowledgeScopeDescriptor.Conversation(request.ConversationId.Value));
|
|
|
|
//
|
|
// Conversation must Belong to Requested Project ...
|
|
if (
|
|
projectId.HasValue &&
|
|
conversation.ProjectId != Guid.Empty &&
|
|
projectId.Value != conversation.ProjectId
|
|
)
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
if (conversation.ProjectId != Guid.Empty)
|
|
{
|
|
projectId = conversation.ProjectId;
|
|
}
|
|
}
|
|
|
|
//
|
|
// Project Tier ...
|
|
if (projectId.HasValue)
|
|
{
|
|
await EnsureProjectOwner(projectId.Value, userInfo, cancellationToken);
|
|
result.Add(XAiKnowledgeScopeDescriptor.Project(projectId.Value));
|
|
}
|
|
|
|
//
|
|
// User / Global Tiers ...
|
|
if (request.IncludeUser)
|
|
{
|
|
result.Add(XAiKnowledgeScopeDescriptor.User());
|
|
}
|
|
if (request.IncludeGlobal)
|
|
{
|
|
result.Add(XAiKnowledgeScopeDescriptor.Global());
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"):
|
|
/// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ...
|
|
/// </summary>
|
|
private static string GetScopePrefix(
|
|
XAiKnowledgeScopeDescriptor scope,
|
|
XUserClaimsInfoDto userInfo
|
|
)
|
|
{
|
|
//
|
|
var separator = XAiModelsConstants.XAiKnowledgeSeparator;
|
|
var result = scope.Scope switch
|
|
{
|
|
XAiKnowledgeScope.Global => $"{XAiModelsConstants.XAiKnowledgeGlobalPrefix}{separator}",
|
|
XAiKnowledgeScope.User => $"{XAiModelsConstants.XAiKnowledgeUserPrefix}{separator}{userInfo.UserId}{separator}",
|
|
XAiKnowledgeScope.Project => $"{XAiModelsConstants.XAiKnowledgeProjectPrefix}{separator}{scope.ScopeId:D}{separator}",
|
|
XAiKnowledgeScope.Conversation => $"{XAiModelsConstants.XAiKnowledgeConversationPrefix}{separator}{scope.ScopeId:D}{separator}",
|
|
_ => null
|
|
};
|
|
if (result.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
|
|
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
|
|
/// </summary>
|
|
private string GetDocumentChunkPrefix(
|
|
string scopePrefix,
|
|
string fileName
|
|
)
|
|
{
|
|
return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ...
|
|
/// </summary>
|
|
private string NormalizeFileName(string fileName)
|
|
{
|
|
//
|
|
if (string.IsNullOrWhiteSpace(fileName))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
//
|
|
// Strip Client Side Path (Both Separators) ...
|
|
var name = Path.GetFileName(fileName.Replace('\\', '/'))?.Trim();
|
|
if (name.IsNullOrEmpty())
|
|
{
|
|
return null;
|
|
}
|
|
|
|
//
|
|
foreach (var c in UnsafeFileNameChars)
|
|
{
|
|
name = name.Replace(c, '_');
|
|
}
|
|
var chunkSeparator = configuration.TextChunker.ChunkIdentifierSeparator;
|
|
if (!chunkSeparator.IsNullOrEmpty())
|
|
{
|
|
name = name.Replace(chunkSeparator, "_");
|
|
}
|
|
|
|
//
|
|
return name;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load Distinct Document Names of a Scope ...
|
|
/// </summary>
|
|
private async Task<HashSet<string>> LoadDocumentNames(
|
|
string scopePrefix,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
//
|
|
var vectors = await dataProvider.LoadVectorsAsync(
|
|
includeEmbedding: false,
|
|
identifierPrefix: scopePrefix,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
var result = new HashSet<string>(
|
|
(vectors ?? [])
|
|
.Select(v => v.Metadata.GetMetadata(rag.MetadataFileName))
|
|
.Where(n => !n.IsNullOrEmpty()),
|
|
StringComparer.Ordinal
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Is Valid User ...
|
|
/// </summary>
|
|
private static bool IsValidUser(XUserClaimsInfoDto userInfo)
|
|
{
|
|
return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Is Caller Admin ...
|
|
/// </summary>
|
|
private static bool IsAdmin(XUserClaimsInfoDto userInfo)
|
|
{
|
|
//
|
|
var result =
|
|
!userInfo.IsNullOrDefault() &&
|
|
!userInfo.Roles.IsNullOrDefault() &&
|
|
userInfo.Roles.Any(r => string.Equals(r, XUserRoles.ADMIN, StringComparison.OrdinalIgnoreCase));
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
#endregion
|
|
}
|
|
}
|