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