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;
- ...
This commit is contained in:
2026-10-25 22:24:39 +03:30
parent 47d8a19423
commit 47da04a594
11 changed files with 1349 additions and 171 deletions
+178 -5
View File
@@ -1,15 +1,11 @@
using System;
using OpenAI;
using OllamaSharp;
using System.Linq;
using xModels.Dtos;
using System.Net.Http;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using System.ClientModel;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
@@ -28,7 +24,6 @@ using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.ClientModel.Primitives;
using System.Runtime.CompilerServices;
namespace xAiApi.Providers
@@ -256,6 +251,181 @@ namespace xAiApi.Providers
}
#endregion
//
#region Context Actions ...
/// <summary>
/// Ask a Question using Provided Context Chunks (RAG) without Persisting ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> AskWithContextAsync(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
using var client = Descriptor.GetClient();
var history = GetContextHistory(prompt, context);
var response = await client.GetResponseAsync(
messages: history,
cancellationToken: cancellationToken
);
//
// Validate Response ...
if (!response.IsValid())
{
client.Dispose();
XException.ActionFailed.Throw();
}
//
var result = response.Text;
//
return result;
}
/// <summary>
/// Ask a Question using Provided Context Chunks (RAG) and Stream Response ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async IAsyncEnumerable<string> AskWithContextAsEnumerable(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
using var client = Descriptor.GetClient();
var history = GetContextHistory(prompt, context);
var enumerable = client.GetStreamingResponseAsync(
options: null,
messages: history,
cancellationToken: cancellationToken
);
//
await foreach (var res in enumerable)
{
//
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
//
yield return res.Text;
}
}
/// <summary>
/// Build Chat History for RAG:
/// [System: Introduction] + [System: ChatWithDocuments Prompt + Context Block] + [User: Prompt] ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <returns></returns>
protected virtual IList<ChatMessage> GetContextHistory(
string prompt,
IEnumerable<XAiVectorSearchResult> context
)
{
//
var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName);
if (ragPrompt.IsNullOrEmpty())
{
XException.InvalidConfiguration.Throw();
}
//
var contextBlock = BuildContextBlock(context);
var systemText = $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}Context:{Environment.NewLine}{contextBlock}";
//
List<ChatMessage> result =
[
new ChatMessage(ChatRole.System, configuration.GetPrompt()),
new ChatMessage(ChatRole.System, systemText),
new ChatMessage(ChatRole.User, prompt),
];
//
return result;
}
/// <summary>
/// Convert Context Chunks to a Numbered Text Block ...
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
protected virtual string BuildContextBlock(
IEnumerable<XAiVectorSearchResult> context
)
{
//
var result = "(no context)";
//
var items = context?
.Where(c =>
!c.IsNullOrDefault() &&
!c.Text.IsNullOrEmpty()
)
.ToList() ?? [];
if (!items.HasChild())
{
return result;
}
//
var index = 1;
var builder = new System.Text.StringBuilder();
foreach (var item in items)
{
//
var identifier = item.Identifier.IsNullOrEmpty()
? item.Id.ToString()
: item.Identifier;
//
builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})");
builder.AppendLine(item.Text.Trim());
builder.AppendLine("----");
//
index++;
}
//
result = builder.ToString();
//
return result;
}
#endregion
//
#region Loaders ...
/// <summary>
@@ -663,6 +833,9 @@ namespace xAiApi.Providers
{
continue;
}
//
// TODO: Implement File Save ...
}
//
+45 -17
View File
@@ -1,8 +1,8 @@
using System;
using System.Linq;
using xAiApi.Models;
using xAiService.Helpers;
using xAiApi.Interfaces;
using xAiService.Helpers;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using System.Collections.Concurrent;
@@ -99,10 +99,10 @@ namespace xAiApi.Providers
}
public IList<XAiVectorSearchResult> Search(
Guid sessionId,
ReadOnlyMemory<float> queryEmbedding,
int topK = 5,
float minScore = 0f,
Guid sessionId,
ReadOnlyMemory<float> queryEmbedding,
int topK = 5,
float minScore = 0f,
string ownerId = null
)
{
@@ -121,6 +121,7 @@ namespace xAiApi.Providers
}
//
var query = queryEmbedding.ToArray();
lock (session.SyncRoot)
{
//
@@ -135,7 +136,7 @@ namespace xAiApi.Providers
//
var score = VectorHelper.CosineSimilarity(
queryEmbedding.ToArray(),
query,
vector.Embedding.ToArray()
);
@@ -143,12 +144,13 @@ namespace xAiApi.Providers
if (score >= minScore)
{
//
result.Add(new XAiVectorSearchResult {
result.Add(new XAiVectorSearchResult
{
Score = score,
Id = vector.Id,
Text = vector.Text,
Metadata = vector.Metadata,
Identifier = vector.Identifier,
Id = vector.Id,
Text = vector.Text,
Metadata = vector.Metadata,
Identifier = vector.Identifier,
});
}
}
@@ -161,8 +163,8 @@ namespace xAiApi.Providers
}
public bool TryGet(
Guid sessionId,
out XAiDocumentSession session,
Guid sessionId,
out XAiDocumentSession session,
string ownerId = null
)
{
@@ -176,8 +178,12 @@ namespace xAiApi.Providers
return true;
}
public bool Remove(Guid sessionId, string ownerId = null)
public bool Remove(
Guid sessionId,
string ownerId = null
)
{
//
XAiDocumentSession session;
if (!TryGet(sessionId, out session, ownerId)) return false;
return sessions.TryRemove(sessionId, out session);
@@ -185,13 +191,35 @@ namespace xAiApi.Providers
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;
}
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(); }
//
#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
}
}
@@ -0,0 +1,77 @@
using System;
using System.Threading;
using xAiApi.Interfaces;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace xAiApi.Providers
{
/// <summary>
/// Periodically Removes Expired Document Sessions from In-Memory Vector Store ...
/// </summary>
public class XInMemoryVectorStoreCleanupService : BackgroundService
{
/// <summary>
/// Default Cleanup Interval ...
/// </summary>
public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5);
private readonly TimeSpan interval;
private readonly IXInMemoryVectorStore vectorStore;
private readonly ILogger<XInMemoryVectorStoreCleanupService> logger;
public XInMemoryVectorStoreCleanupService(
IXInMemoryVectorStore vectorStore,
ILogger<XInMemoryVectorStoreCleanupService> logger
)
{
this.logger = logger;
this.vectorStore = vectorStore;
this.interval = DefaultInterval;
}
/// <summary>
/// Cleanup Loop ...
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//
try
{
//
while (!stoppingToken.IsCancellationRequested)
{
//
await Task.Delay(interval, stoppingToken);
//
try
{
//
var removed = vectorStore.RemoveExpired();
if (removed > 0)
{
//
logger.LogInformation(
"InMemoryVectorStore Cleanup: {Removed} Expired Session(s) Removed, {Count} Remaining",
removed,
vectorStore.Count
);
}
}
catch (Exception ex)
{
logger.LogError(ex, "InMemoryVectorStore Cleanup Failed");
}
}
}
catch (OperationCanceledException)
{
// Shutdown ...
}
}
}
}