Refactor Chat Pipeline into PrepareChatRequirementsAsync and Harden RAG Services

- 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.
This commit is contained in:
2026-11-02 16:37:57 +03:30
parent 726d6ce827
commit a870d61e61
10 changed files with 619 additions and 742 deletions
+166 -133
View File
@@ -18,6 +18,7 @@ using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using xFileService.Models.Dtos;
namespace xAiApi.Providers
{
@@ -127,149 +128,181 @@ namespace xAiApi.Providers
var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);
//
// Loop through Files ...
foreach (var file in files)
{
//
cancellationToken.ThrowIfCancellationRequested();
XFileDto uploadedFile = null;
//
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 ...
var uploadedFile = await fileProvider.Upload(
file: file,
userInfo: userInfo,
connectionId: connectionId,
cancellationToken: cancellationToken
);
//
// Add Reference File to Prompt Message ...
if (scope.ScopeId.HasValue)
try
{
//
await fileProvider.AddReference(
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,
id: uploadedFile.Id,
connectionId: connectionId,
cancellationToken: cancellationToken,
providedFor: scope.Scope.GetStringValue(),
forProvidedId: scope.ScopeId.Value.ToString()
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
);
}
//
// 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)
catch (Exception ex)
{
//
result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
cancellationToken: cancellationToken,
identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName)
);
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
);
}
}
//
// 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
);
}
//
@@ -483,11 +516,11 @@ namespace xAiApi.Providers
var file = await fileProvider.FindOne(
x => x.FileName
.Equals(
fileName,
fileName,
StringComparison.InvariantCultureIgnoreCase) &&
x.OwnerId
.Equals(
userInfo.UserId,
userInfo.UserId,
StringComparison.InvariantCultureIgnoreCase),
cancellationToken: cancellationToken
);
@@ -736,7 +769,7 @@ namespace xAiApi.Providers
//
return result;
}
//
#region Scope ...
/// <summary>
@@ -953,7 +986,7 @@ namespace xAiApi.Providers
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
/// </summary>
private string GetDocumentChunkPrefix(
string scopePrefix,
string scopePrefix,
string fileName
)
{