Files
xSaherElmAiApi/Providers/XInMemoryVectorStore.cs
T
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

255 lines
7.0 KiB
C#

using System;
using System.Linq;
using xAiApi.Models;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace xAiApi.Providers
{
public class XInMemoryVectorStore : IXInMemoryVectorStore
{
private const int DefaultTtlMinutes = 30;
private readonly ConcurrentDictionary<Guid, XAiDocumentSession> sessions = new ConcurrentDictionary<Guid, XAiDocumentSession>();
public int Count { get { RemoveExpired(); return sessions.Count; } }
public Guid CreateSession(
string ownerId = null,
TimeSpan? ttl = null
)
{
//
var result = CreateSession(null, ownerId, ttl);
return result;
}
public Guid CreateSession(
IEnumerable<XAiVectorDto> vectors,
string ownerId = null,
TimeSpan? ttl = null
)
{
//
var now = DateTime.UtcNow;
var session = new XAiDocumentSession
{
Id = Guid.NewGuid(),
OwnerId = ownerId,
CreatedAtUtc = now,
LastAccessAtUtc = now,
Ttl = NormalizeTtl(ttl),
Vectors = Copy(vectors)
};
sessions[session.Id] = session;
var result = session.Id;
return result;
}
public bool Replace(
Guid sessionId,
IEnumerable<XAiVectorDto> vectors,
string ownerId = null
)
{
//
XAiDocumentSession session;
if (!TryGet(sessionId, out session, ownerId))
{
return false;
}
//
lock (session.SyncRoot)
{
session.Vectors = Copy(vectors);
session.LastAccessAtUtc = DateTime.UtcNow;
}
//
return true;
}
public bool Add(
Guid sessionId,
IEnumerable<XAiVectorDto> vectors,
string ownerId = null
)
{
//
XAiDocumentSession session;
if (!TryGet(sessionId, out session, ownerId))
{
return false;
}
var additions = Copy(vectors);
lock (session.SyncRoot)
{
//
foreach (var vector in additions)
{
session.Vectors.Add(vector);
}
//
session.LastAccessAtUtc = DateTime.UtcNow;
}
return true;
}
public IList<XAiVectorSearchResult> Search(
Guid sessionId,
ReadOnlyMemory<float> queryEmbedding,
int topK = 5,
float minScore = 0f,
string ownerId = null
)
{
//
var result = new List<XAiVectorSearchResult>();
if (topK <= 0 || queryEmbedding.Length == 0)
{
return result;
}
//
XAiDocumentSession session;
if (!TryGet(sessionId, out session, ownerId))
{
return result;
}
//
var query = queryEmbedding.ToArray();
lock (session.SyncRoot)
{
//
session.LastAccessAtUtc = DateTime.UtcNow;
foreach (var vector in session.Vectors)
{
//
if (vector == null || vector.Embedding.Length == 0)
{
continue;
}
//
var score = VectorHelper.CosineSimilarity(
query,
vector.Embedding.ToArray()
);
//
if (score >= minScore)
{
//
result.Add(new XAiVectorSearchResult
{
Score = score,
Id = vector.Id,
Text = vector.Text,
Metadata = vector.Metadata,
Identifier = vector.Identifier,
});
}
}
}
//
result = [.. result
.OrderByDescending(x => x.Score)
.Take(topK)];
//
return result;
}
public bool TryGet(
Guid sessionId,
out XAiDocumentSession session,
string ownerId = null
)
{
//
session = null;
XAiDocumentSession found;
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,
string ownerId = null
)
{
//
XAiDocumentSession session;
if (!TryGet(sessionId, out session, ownerId)) return false;
return sessions.TryRemove(sessionId, out session);
}
public int RemoveExpired()
{
//
var now = DateTime.UtcNow; var removed = 0;
foreach (var pair in sessions) { if (pair.Value.IsExpired(now) && sessions.TryRemove(pair.Key, out _)) removed++; }
return removed;
}
//
#region Private ...
private static bool OwnerMatches(
XAiDocumentSession session,
string ownerId
)
{
return string.IsNullOrEmpty(session.OwnerId) || string.Equals(session.OwnerId, ownerId, StringComparison.Ordinal);
}
private static TimeSpan NormalizeTtl(
TimeSpan? ttl
)
{
return !ttl.HasValue || ttl.Value <= TimeSpan.Zero ? TimeSpan.FromMinutes(DefaultTtlMinutes) : ttl.Value;
}
private static IList<XAiVectorDto> Copy(
IEnumerable<XAiVectorDto> vectors
)
{
return vectors == null ? new List<XAiVectorDto>() : vectors.Where(x => x != null).ToList();
}
#endregion
}
}