Files
xSaherElmAiApi/Providers/XInMemoryVectorStore.cs
T
saherelm 47da04a594 Implement Chat With Documents (In-Memory RAG) ...
- Add XAiDocumentModels (IngestResult, AskRequest, Answer, AnswerChunk, Source, SessionInfo, RAGDescriptor DTOs);
- Add AskWithContextAsync and AskWithContextAsEnumerable (Context Actions) to IXAiServiceBase and XAIServiceBase;
- Add GetContextHistory and BuildContextBlock Helpers for Building RAG Chat History without Persisting;
- Rewrite ChatWithDocumentsController with Ingest, Ask, AskStream (SSE), Get Session and Delete Session Endpoints;
- Add XInMemoryVectorStoreCleanupService (BackgroundService) for Removing Expired Sessions Periodically;
- Add AddXAiChatWithDocuments DI Extension, Register Cleanup HostedService and use it in Startup;
- Add RAGDescriptor Property to XAiApiConfiguration and its Section to appsettings.Development.json;
- Add ChatWithDocuments System Prompt to Prompts in appsettings.Development.json;
- Add IsValid Extension Method for XAiDocumentAskRequest;
- Optimize XInMemoryVectorStore.Search (Query Embedding Converted once) and Refactor Formatting;
- Remove Unused Usings in XAIServiceBase and IXAiServiceBase;
- ...
2026-10-25 22:24:39 +03:30

226 lines
6.4 KiB
C#

using System;
using System.Linq;
using xAiApi.Models;
using xAiApi.Interfaces;
using xAiService.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,
});
}
}
}
//
return [.. result
.OrderByDescending(x => x.Score)
.Take(topK)];
}
public bool TryGet(
Guid sessionId,
out XAiDocumentSession session,
string ownerId = null
)
{
//
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;
}
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
}
}