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

78 lines
2.4 KiB
C#

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 ...
}
}
}
}