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:
@@ -189,8 +189,8 @@ namespace xAiApi.Controllers
|
|||||||
// Embed in Batches ...
|
// Embed in Batches ...
|
||||||
var fileVectors = await EmbedChunks(
|
var fileVectors = await EmbedChunks(
|
||||||
chunks: chunks,
|
chunks: chunks,
|
||||||
mimeType: mimeType,
|
|
||||||
fileName: file.FileName,
|
fileName: file.FileName,
|
||||||
|
mimeType: mimeType,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -464,7 +464,7 @@ namespace xAiApi.Controllers
|
|||||||
|
|
||||||
//
|
//
|
||||||
var result = await aiService.AskAsync(
|
var result = await aiService.AskAsync(
|
||||||
files: null,
|
files: files,
|
||||||
topK: request.TopK,
|
topK: request.TopK,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
type: request.Type,
|
type: request.Type,
|
||||||
|
|||||||
@@ -73,9 +73,7 @@ namespace xAiApi.Extensions
|
|||||||
var result =
|
var result =
|
||||||
!source.IsNullOrDefault() &&
|
!source.IsNullOrDefault() &&
|
||||||
!source.Prompt.IsNullOrEmpty() &&
|
!source.Prompt.IsNullOrEmpty() &&
|
||||||
!source.SessionId.IsDefaultGuid() &&
|
!source.SessionId.IsDefaultGuid();
|
||||||
source.TopK.HasValue && source.TopK.Value > 0 &&
|
|
||||||
source.MinScore.HasValue && source.MinScore.Value >= -1f && source.MinScore.Value <= 1f;
|
|
||||||
|
|
||||||
//
|
//
|
||||||
return result;
|
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
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -106,7 +106,7 @@ namespace xAiApi.Middlewares
|
|||||||
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
|
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
|
||||||
var isAuthenticated =
|
var isAuthenticated =
|
||||||
//
|
//
|
||||||
(!apiKey.IsNullOrEmpty()) |
|
(!apiKey.IsNullOrEmpty()) ||
|
||||||
//
|
//
|
||||||
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
|
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
|
||||||
;
|
;
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+357
-540
File diff suppressed because it is too large
Load Diff
@@ -84,7 +84,7 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
using var generator = GetEmbeddingGenerator();
|
var generator = GetEmbeddingGenerator();
|
||||||
|
|
||||||
//
|
//
|
||||||
GeneratedEmbeddings<Embedding<float>> response = null;
|
GeneratedEmbeddings<Embedding<float>> response = null;
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ using Microsoft.AspNetCore.Http;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
using xFileService.Models.Dtos;
|
||||||
|
|
||||||
namespace xAiApi.Providers
|
namespace xAiApi.Providers
|
||||||
{
|
{
|
||||||
@@ -127,7 +128,14 @@ namespace xAiApi.Providers
|
|||||||
var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);
|
var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);
|
||||||
|
|
||||||
//
|
//
|
||||||
|
// Loop through Files ...
|
||||||
foreach (var file in files)
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
XFileDto uploadedFile = null;
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -196,7 +204,7 @@ namespace xAiApi.Providers
|
|||||||
|
|
||||||
//
|
//
|
||||||
// Handle File Save ...
|
// Handle File Save ...
|
||||||
var uploadedFile = await fileProvider.Upload(
|
uploadedFile = await fileProvider.Upload(
|
||||||
file: file,
|
file: file,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
@@ -205,7 +213,11 @@ namespace xAiApi.Providers
|
|||||||
|
|
||||||
//
|
//
|
||||||
// Add Reference File to Prompt Message ...
|
// Add Reference File to Prompt Message ...
|
||||||
if (scope.ScopeId.HasValue)
|
if (
|
||||||
|
!uploadedFile.IsNullOrDefault() &&
|
||||||
|
scope.ScopeId.HasValue &&
|
||||||
|
!uploadedFile.Id.IsDefaultGuid()
|
||||||
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
await fileProvider.AddReference(
|
await fileProvider.AddReference(
|
||||||
@@ -271,6 +283,27 @@ namespace xAiApi.Providers
|
|||||||
fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount
|
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;
|
return result;
|
||||||
|
|||||||
@@ -174,12 +174,38 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
session = null;
|
session = null;
|
||||||
XAiDocumentSession found;
|
XAiDocumentSession found;
|
||||||
if (!sessions.TryGetValue(sessionId, out found) || !OwnerMatches(found, ownerId)) return false;
|
if (!sessions.TryGetValue(sessionId, out found))
|
||||||
if (found.IsExpired(DateTime.UtcNow)) { sessions.TryRemove(sessionId, out found); return false; }
|
{
|
||||||
|
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;
|
found.LastAccessAtUtc = DateTime.UtcNow;
|
||||||
session = found;
|
session = found;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public bool Remove(
|
public bool Remove(
|
||||||
Guid sessionId,
|
Guid sessionId,
|
||||||
|
|||||||
Reference in New Issue
Block a user