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
+1 -1
View File
@@ -189,8 +189,8 @@ namespace xAiApi.Controllers
// Embed in Batches ...
var fileVectors = await EmbedChunks(
chunks: chunks,
mimeType: mimeType,
fileName: file.FileName,
mimeType: mimeType,
cancellationToken: cancellationToken
);
+1 -1
View File
@@ -464,7 +464,7 @@ namespace xAiApi.Controllers
//
var result = await aiService.AskAsync(
files: null,
files: files,
topK: request.TopK,
userInfo: userInfo,
type: request.Type,
+1 -3
View File
@@ -73,9 +73,7 @@ namespace xAiApi.Extensions
var result =
!source.IsNullOrDefault() &&
!source.Prompt.IsNullOrEmpty() &&
!source.SessionId.IsDefaultGuid() &&
source.TopK.HasValue && source.TopK.Value > 0 &&
source.MinScore.HasValue && source.MinScore.Value >= -1f && source.MinScore.Value <= 1f;
!source.SessionId.IsDefaultGuid();
//
return result;
@@ -1,34 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace xAiApi.Interfaces
{
public interface IXAiEmbeddingServiceControllerBase
{
/// <summary>
/// Request For Embedding Specified String ...
/// </summary>
/// <param name="content"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Embedding")]
Task<ActionResult<float[]>> Embedding(
[FromQuery] string content,
CancellationToken cancellationToken = default
);
/// <summary>
/// Request For Embedding Specified Batch ...
/// </summary>
/// <param name="batch"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Embeddings")]
Task<ActionResult<IReadOnlyList<float[]>>> Embeddings(
[FromQuery] string[] batch,
CancellationToken cancellationToken = default
);
}
}
+1 -1
View File
@@ -106,7 +106,7 @@ namespace xAiApi.Middlewares
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
var isAuthenticated =
//
(!apiKey.IsNullOrEmpty()) |
(!apiKey.IsNullOrEmpty()) ||
//
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
;
+37
View File
@@ -0,0 +1,37 @@
using xAiModels.Models.Dtos;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
namespace xAiApi.Models
{
/// <summary>
/// a Shared Context Between Actions for Generation ...
/// </summary>
public class XPreparedChatContext
{
/// <summary>
/// Specified Related Project, if Exists ...
/// </summary>
public XAiProjectDto Project { get; set; } = null;
/// <summary>
/// Specified Related Conversation, if Exists ...
/// </summary>
public XAiConversationDto Conversation { get; set; } = null;
/// <summary>
/// Specified Message History, if Exists ...
/// </summary>
public IList<ChatMessage> History { get; set; } = [];
/// <summary>
/// Specified Vector Search Conext, if Exists ...
/// </summary>
public IList<XAiVectorSearchResult> Context { get; set; } = [];
/// <summary>
/// Specified Persisted Prompt, if Exists ...
/// </summary>
public XAiMessageDto PersistedPromptMessage { get; set; } = null;
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -84,7 +84,7 @@ namespace xAiApi.Providers
}
//
using var generator = GetEmbeddingGenerator();
var generator = GetEmbeddingGenerator();
//
GeneratedEmbeddings<Embedding<float>> response = null;
+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
)
{
+31 -5
View File
@@ -174,11 +174,37 @@ namespace xAiApi.Providers
//
session = null;
XAiDocumentSession found;
if (!sessions.TryGetValue(sessionId, out found) || !OwnerMatches(found, ownerId)) return false;
if (found.IsExpired(DateTime.UtcNow)) { sessions.TryRemove(sessionId, out found); return false; }
found.LastAccessAtUtc = DateTime.UtcNow;
session = found;
return true;
if (!sessions.TryGetValue(sessionId, out found))
{
return false;
}
//
lock (found.SyncRoot)
{
//
XAiDocumentSession current;
if (!sessions.TryGetValue(sessionId, out current) ||
!ReferenceEquals(current, found))
return false;
//
if (!OwnerMatches(found, ownerId))
return false;
//
if (found.IsExpired(DateTime.UtcNow))
{
//
sessions.TryRemove(sessionId, out found);
return false;
}
//
found.LastAccessAtUtc = DateTime.UtcNow;
session = found;
return true;
}
}
public bool Remove(