Files
xSaherElmAiApi/Providers/XInMemoryVectorStore.cs
T
saherelm fef38cad1b Fix Jinja Conversation Role Alternation in RAG Context History
- Merge Introduction prompt, RAG prompt and context block into one System message;
- Keep the user question as the following User message;
- Prevent consecutive System roles in AskWithContextAsync and AskWithContextAsEnumerable;
- Update the GetContextHistory XML documentation to describe the new message layout;
- Preserve the existing context retrieval and response flow.
- ...
2026-10-26 10:43:17 +03:30

229 lines
6.5 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,
});
}
}
}
//
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) || !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
}
}