Compare commits

...
1 Commits
Author SHA1 Message Date
saherelm a870d61e61 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.
2026-11-02 16:37:57 +03:30
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;
+35 -2
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,7 +128,14 @@ namespace xAiApi.Providers
var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);
//
// Loop through Files ...
foreach (var file in files)
{
//
XFileDto uploadedFile = null;
//
try
{
//
cancellationToken.ThrowIfCancellationRequested();
@@ -196,7 +204,7 @@ namespace xAiApi.Providers
//
// Handle File Save ...
var uploadedFile = await fileProvider.Upload(
uploadedFile = await fileProvider.Upload(
file: file,
userInfo: userInfo,
connectionId: connectionId,
@@ -205,7 +213,11 @@ namespace xAiApi.Providers
//
// Add Reference File to Prompt Message ...
if (scope.ScopeId.HasValue)
if (
!uploadedFile.IsNullOrDefault() &&
scope.ScopeId.HasValue &&
!uploadedFile.Id.IsDefaultGuid()
)
{
//
await fileProvider.AddReference(
@@ -271,6 +283,27 @@ namespace xAiApi.Providers
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;
+28 -2
View File
@@ -174,12 +174,38 @@ 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; }
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(
Guid sessionId,