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
+5
View File
@@ -40,5 +40,10 @@ namespace xAiApi.Configurations
/// Text Chunker Configuration ...
/// </summary>
public XTextChunkerDescriptor TextChunker { get; set; } = new();
/// <summary>
/// RAG Configuration ...
/// </summary>
public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
}
}
+656 -18
View File
@@ -1,33 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xAiApi.Interfaces.Extractors;
using xAiModels.Models.Dtos;
using xCommons.Configurations;
using xAiApi.Extensions;
using xCommons.Providers;
using xIdentityService.Controllers;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using xAiApi.Interfaces.Extractors;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
/// <summary>
/// Chat With Documents (In-Memory RAG) Controller ...
/// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session
/// </summary>
[Authorize]
[Route("[controller]")]
public class ChatWithDocumentsController : XBaseIdentityApiV1Controller, IDisposable
public class ChatWithDocumentsController : XBaseIdentityApiV1Controller
{
/// <summary>
/// Default AI Service ...
/// </summary>
private IXDefaultAiService aiService;
private readonly IXDefaultAiService aiService;
/// <summary>
/// Text Chunker Service ...
/// </summary>
private readonly IXTextChunker textChunker;
/// <summary>
/// In Memory Vector Store ...
/// </summary>
private IList<XAiVectorDto> vectorStore = [];
private readonly IXInMemoryVectorStore vectorStore;
/// <summary>
/// XAiApi Configuration ...
/// </summary>
private readonly XAiApiConfiguration apiConfiguration;
/// <summary>
/// Embedding Service ...
@@ -40,26 +61,643 @@ namespace xAiApi.Controllers
private readonly IXFileContentExtractor fileContentExtractor;
public ChatWithDocumentsController(
IXTextChunker textChunker,
IXDefaultAiService aiService,
ILogger<ChatWithDocumentsController> logger,
IXInMemoryVectorStore vectorStore,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
IXDefaultEmbeddingService embeddingService,
XAiApiConfiguration apiConfiguration,
XValidationProvider validationProvider,
IXDefaultEmbeddingService embeddingService,
ILogger<ChatWithDocumentsController> logger,
IXFileContentExtractor fileContentExtractor
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
//
this.aiService = aiService;
this.textChunker = textChunker;
this.vectorStore = vectorStore;
this.apiConfiguration = apiConfiguration;
this.embeddingService = embeddingService;
this.fileContentExtractor = fileContentExtractor;
}
//
#region Ingest ...
/// <summary>
/// Dispose ...
/// Ingest Files into a (new or existing) In-Memory Session:
/// Extract -> Chunk -> Embed -> Store ...
/// </summary>
public void Dispose()
/// <param name="files"></param>
/// <param name="sessionId">Optional: Add to an Existing Session</param>
/// <param name="ttlMinutes">Optional: Session TTL in Minutes (only for new Session)</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ingest")]
[Consumes("multipart/form-data")]
public async Task<ActionResult<XAiDocumentIngestResult>> Ingest(
[FromForm] IFormFileCollection files,
[FromForm] Guid? sessionId = null,
[FromForm] int? ttlMinutes = null,
CancellationToken cancellationToken = default
)
{
vectorStore.Clear();
//
try
{
//
// Validate ...
if (!files.HasChild())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var ownerId = userInfo.UserId;
//
// Resolve Target Session ...
Guid targetSessionId;
if (sessionId.HasValue && sessionId.Value != Guid.Empty)
{
//
if (!vectorStore.TryGet(sessionId.Value, out _, ownerId))
{
XException.NotFound.Throw();
}
targetSessionId = sessionId.Value;
}
else
{
//
var ttl = TimeSpan.FromMinutes(
ttlMinutes.HasValue && ttlMinutes.Value > 0
? ttlMinutes.Value
: apiConfiguration.RAGDescriptor.DefaultTtlMinutes
);
targetSessionId = vectorStore.CreateSession(ownerId, ttl);
}
//
var result = new XAiDocumentIngestResult
{
SessionId = targetSessionId
};
//
// Extract -> Chunk -> Embed ...
var vectors = new List<XAiVectorDto>();
foreach (var file in files)
{
//
cancellationToken.ThrowIfCancellationRequested();
//
if (file.IsNull() || file.Length == 0)
{
result.SkippedFiles.Add(file?.FileName ?? "(null)");
continue;
}
//
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
if (!fileContentExtractor.CanExtract(mimeType))
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
var text = await ExtractText(file, mimeType, cancellationToken);
if (string.IsNullOrWhiteSpace(text))
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
var chunks = textChunker.Chunk(text, file.FileName);
if (!chunks.HasChild())
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
// Embed in Batches ...
var fileVectors = await EmbedChunks(
chunks: chunks,
mimeType: mimeType,
fileName: file.FileName,
cancellationToken: cancellationToken
);
//
vectors.AddRange(fileVectors);
result.FilesCount++;
}
//
// Store ...
if (vectors.HasChild() &&
!vectorStore.Add(targetSessionId, vectors, ownerId))
{
XException.ActionFailed.Throw();
}
//
// Fill Result ...
result.ChunksCount = vectors.Count;
if (vectorStore.TryGet(targetSessionId, out var session, ownerId))
{
lock (session.SyncRoot)
{
result.TotalVectorsCount = session.Vectors.Count;
}
result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl);
}
//
return Ok(result);
}
catch (Exception ex)
{
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Ask ...
/// <summary>
/// Ask a Question over Ingested Documents ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ask")]
public async Task<ActionResult<XAiDocumentAnswer>> Ask(
[FromBody] XAiDocumentAskRequest request,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!request.IsValid())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var ownerId = userInfo.UserId;
//
// Check Session ...
if (!vectorStore.TryGet(request.SessionId, out _, ownerId))
{
XException.NotFound.Throw();
}
//
// Retrieve ...
var context = await Retrieve(request, ownerId, cancellationToken);
//
var result = new XAiDocumentAnswer
{
SessionId = request.SessionId,
Sources = ToSources(context)
};
//
if (!context.HasChild())
{
result.NoContextFound = true;
return Ok(result);
}
//
// Generate ...
result.Answer = await aiService.AskWithContextAsync(
prompt: request.Prompt,
context: context,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Ask a Question over Ingested Documents and Stream Response (SSE) ...
/// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AskStream")]
public async Task AskStream(
[FromBody] XAiDocumentAskRequest request,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!request.IsValid())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var ownerId = userInfo.UserId;
//
// Check Session ...
if (!vectorStore.TryGet(request.SessionId, out _, ownerId))
{
XException.NotFound.Throw();
}
//
// Retrieve ...
var context = await Retrieve(request, ownerId, cancellationToken);
//
// Configure SSE Response Headers ...
Response.Headers["X-Accel-Buffering"] = "no";
Response.Headers["Connection"] = "keep-alive";
Response.Headers["Content-Type"] = "text/event-stream";
Response.Headers["Cache-Control"] = "no-cache, no-store";
//
// Disable response buffering ...
var responseBodyFeature = HttpContext.Features
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
responseBodyFeature?.DisableBuffering();
//
// First Event: Sources ...
var hasContext = context.HasChild();
await WriteChunk(new XAiDocumentAnswerChunk
{
Text = string.Empty,
IsFinal = !hasContext,
NoContextFound = !hasContext,
Sources = ToSources(context)
}, cancellationToken);
//
if (!hasContext)
{
return;
}
//
// Stream Deltas ...
var enumerable = aiService.AskWithContextAsEnumerable(
prompt: request.Prompt,
context: context,
cancellationToken: cancellationToken
);
await foreach (var delta in enumerable)
{
//
if (delta.IsNullOrEmpty())
{
continue;
}
//
await WriteChunk(new XAiDocumentAnswerChunk
{
Text = delta
}, cancellationToken);
}
//
// Final Event ...
await WriteChunk(new XAiDocumentAnswerChunk
{
Text = string.Empty,
IsFinal = true
}, cancellationToken);
}
catch (Exception ex)
{
//
Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
if (!Response.HasStarted)
{
Response.StatusCode = StatusCodes.Status400BadRequest;
}
await Response.Body.FlushAsync();
}
}
#endregion
//
#region Session ...
/// <summary>
/// Retrieve Session Info (without Embeddings) ...
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("Session/{id:guid}")]
public async Task<ActionResult<XAiDocumentSessionInfo>> GetSession(Guid id)
{
//
try
{
//
var userInfo = await GetUserInfo();
if (!vectorStore.TryGet(id, out var session, userInfo.UserId))
{
XException.NotFound.Throw();
}
//
IList<XAiVectorDto> vectors;
lock (session.SyncRoot)
{
vectors = session.Vectors.ToList();
}
//
var result = new XAiDocumentSessionInfo
{
Id = session.Id,
Ttl = session.Ttl,
VectorsCount = vectors.Count,
CreatedAtUtc = session.CreatedAtUtc,
LastAccessAtUtc = session.LastAccessAtUtc,
ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
Files = vectors
.Select(v => GetMetadata(v.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName))
.Where(f => !f.IsNullOrEmpty())
.Distinct()
.ToList()
};
//
return Ok(result);
}
catch (Exception ex)
{
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Remove a Session and Free Memory ...
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("Session/{id:guid}")]
public async Task<ActionResult<bool>> DeleteSession(Guid id)
{
//
try
{
//
var userInfo = await GetUserInfo();
if (!vectorStore.Remove(id, userInfo.UserId))
{
XException.NotFound.Throw();
}
//
return Ok(true);
}
catch (Exception ex)
{
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Private ...
/// <summary>
/// Extract Plain Text of a File (Text or Audio Transcript) ...
/// </summary>
private async Task<string> ExtractText(
IFormFile file,
string mimeType,
CancellationToken cancellationToken
)
{
//
try
{
//
using var stream = file.OpenReadStream();
var extraction = await fileContentExtractor.ExtractRichAsync(
fileStream: stream,
mimeType: mimeType,
fileName: file.FileName,
cancellationToken: cancellationToken
);
//
var result = extraction?.Text;
if (string.IsNullOrWhiteSpace(result))
{
result = extraction?.AudioTranscript;
}
//
return result;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName);
return null;
}
}
/// <summary>
/// Embed Chunks in Batches and Build Vectors ...
/// </summary>
private async Task<IList<XAiVectorDto>> EmbedChunks(
IList<XTextChunk> chunks,
string fileName,
string mimeType,
CancellationToken cancellationToken
)
{
//
var result = new List<XAiVectorDto>(chunks.Count);
var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize;
//
for (var offset = 0; offset < chunks.Count; offset += batchSize)
{
//
cancellationToken.ThrowIfCancellationRequested();
//
var batch = chunks.Skip(offset).Take(batchSize).ToList();
var embeddings = await embeddingService.Embeddings(
batch: batch.Select(c => c.Text).ToArray(),
cancellationToken: cancellationToken
);
//
if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
{
XException.ActionFailed.Throw();
}
//
for (var i = 0; i < batch.Count; i++)
{
//
var chunk = batch[i];
result.Add(new XAiVectorDto
{
Id = Guid.NewGuid(),
Text = chunk.Text,
Embedding = embeddings[i],
Identifier = chunk.Identifier,
Metadata = new Dictionary<string, string>
{
[apiConfiguration.RAGDescriptor.MetadataFileName] = fileName,
[apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType,
[apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString()
}
});
}
}
//
return result;
}
/// <summary>
/// Embed Prompt and Search Session ...
/// </summary>
private async Task<IList<XAiVectorSearchResult>> Retrieve(
XAiDocumentAskRequest request,
string ownerId,
CancellationToken cancellationToken
)
{
//
var topK = Math.Clamp(
request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK,
1,
apiConfiguration.RAGDescriptor.MaxTopK
);
var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore;
//
var queryEmbedding = await embeddingService.Embedding(
content: request.Prompt,
cancellationToken: cancellationToken
);
if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
{
XException.ActionFailed.Throw();
}
//
var result = vectorStore.Search(
topK: topK,
ownerId: ownerId,
minScore: minScore,
sessionId: request.SessionId,
queryEmbedding: queryEmbedding
);
//
return result ?? [];
}
/// <summary>
/// Map Search Results to Public Sources ...
/// </summary>
private IList<XAiDocumentSource> ToSources(
IEnumerable<XAiVectorSearchResult> context
)
{
//
var result = (context ?? [])
.Select(c =>
{
//
var chunkIndexText = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataChunkIndex);
var text = c.Text ?? string.Empty;
var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);
//
return new XAiDocumentSource
{
Score = c.Score,
Identifier = c.Identifier,
Snippet = text.Substring(0, snippetLength),
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
FileName = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName)
};
})
.ToList();
//
return result;
}
/// <summary>
/// Safe Metadata Reader ...
/// </summary>
private string GetMetadata(
IDictionary<string, string> metadata,
string key
)
{
//
if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value))
{
return null;
}
//
return value;
}
/// <summary>
/// Write a SSE Event ...
/// </summary>
private async Task WriteChunk(
XAiDocumentAnswerChunk chunk,
CancellationToken cancellationToken
)
{
//
var payload = chunk.ToJSON(camelCase: true);
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
#endregion
}
}
}
+11
View File
@@ -134,6 +134,17 @@ namespace xAiApi.DI
public static void AddXAiInMemoryVectorStore(this IServiceCollection source)
{
source.AddSingleton<IXInMemoryVectorStore, XInMemoryVectorStore>();
source.AddHostedService<XInMemoryVectorStoreCleanupService>();
}
/// <summary>
/// Register all Services Required for Chat With Documents (In-Memory RAG):
/// Text Chunker + In-Memory Vector Store (+ Cleanup) ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiChatWithDocuments(this IServiceCollection source)
{
source.AddXAiInMemoryVectorStore();
}
/// <summary>
+20 -1
View File
@@ -2,6 +2,7 @@ using System;
using OpenAI;
using System.Linq;
using OllamaSharp;
using xAiApi.Models;
using System.Net.Http;
using xAiApi.Constants;
using xAiModels.Models;
@@ -15,7 +16,6 @@ using xExceptions.Constants;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System.ClientModel.Primitives;
using xAiApi.Models;
namespace xAiApi.Extensions
{
@@ -62,6 +62,25 @@ namespace xAiApi.Extensions
return result;
}
/// <summary>
/// Check Document Ask Request is Valid or not ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsValid(this XAiDocumentAskRequest source)
{
//
var result =
!source.IsNullOrDefault() &&
!source.Prompt.IsNullOrEmpty() &&
!source.SessionId.IsDefaultGuid() &&
(!source.TopK.HasValue || source.TopK.Value > 0) &&
(!source.MinScore.HasValue || (source.MinScore.Value >= -1f && source.MinScore.Value <= 1f));
//
return result;
}
/// <summary>
/// Extract Default Model Descriptor ...
/// </summary>
+31 -3
View File
@@ -1,6 +1,5 @@
using System;
using xModels.Dtos;
using System.Net.Http;
using System.Threading;
using xAiModels.Models;
using xAiModels.Models.Dtos;
@@ -74,6 +73,35 @@ namespace xAiApi.Interfaces
);
#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>
Task<string> AskWithContextAsync(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
CancellationToken cancellationToken = default
);
/// <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>
IAsyncEnumerable<string> AskWithContextAsEnumerable(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
CancellationToken cancellationToken = default
);
#endregion
//
#region Loaders ...
/// <summary>
@@ -196,7 +224,7 @@ namespace xAiApi.Interfaces
CancellationToken cancellationToken = default
);
#endregion
//
#region Content Extraction ...
/// <summary>
@@ -209,7 +237,7 @@ namespace xAiApi.Interfaces
Task<string> ExtractContent(
IFormFileCollection files,
string[] extractors = null,
CancellationToken cancellationToken = default
CancellationToken cancellationToken = default
);
#endregion
+181
View File
@@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
namespace xAiApi.Models
{
/// <summary>
/// Result of Ingesting Documents into an In-Memory Session ...
/// </summary>
public class XAiDocumentIngestResult
{
/// <summary>
/// Session Identifier which must be used in Ask Requests ...
/// </summary>
public Guid SessionId { get; set; }
/// <summary>
/// Count of Successfully Processed Files ...
/// </summary>
public int FilesCount { get; set; }
/// <summary>
/// Count of Chunks (Vectors) Added to Session ...
/// </summary>
public int ChunksCount { get; set; }
/// <summary>
/// Total Vectors Count in Session after Ingest ...
/// </summary>
public int TotalVectorsCount { get; set; }
/// <summary>
/// Files which Skipped (Unsupported / Empty / Failed) ...
/// </summary>
public IList<string> SkippedFiles { get; set; } = new List<string>();
/// <summary>
/// Session Expiration Time (UTC) based on Last Access ...
/// </summary>
public DateTime ExpiresAtUtc { get; set; }
}
/// <summary>
/// Request for Asking a Question over Ingested Documents ...
/// </summary>
public class XAiDocumentAskRequest
{
/// <summary>
/// Session Identifier ...
/// </summary>
public Guid SessionId { get; set; }
/// <summary>
/// User Question ...
/// </summary>
public string Prompt { get; set; }
/// <summary>
/// Count of Top Chunks used as Context (Optional) ...
/// </summary>
public int? TopK { get; set; }
/// <summary>
/// Minimum Similarity Score of Chunks (Optional) ...
/// </summary>
public float? MinScore { get; set; }
}
/// <summary>
/// a Source Chunk which used for Generating Answer ...
/// </summary>
public class XAiDocumentSource
{
/// <summary>
/// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Source File Name ...
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Chunk Index in Source File ...
/// </summary>
public int? ChunkIndex { get; set; }
/// <summary>
/// Similarity Score ...
/// </summary>
public float Score { get; set; }
/// <summary>
/// Short Snippet of Chunk Text ...
/// </summary>
public string Snippet { get; set; }
}
/// <summary>
/// Answer of a Chat With Documents Request ...
/// </summary>
public class XAiDocumentAnswer
{
/// <summary>
/// Session Identifier ...
/// </summary>
public Guid SessionId { get; set; }
/// <summary>
/// Generated Answer ...
/// </summary>
public string Answer { get; set; }
/// <summary>
/// True when no Relevant Chunk Found in Session ...
/// </summary>
public bool NoContextFound { get; set; }
/// <summary>
/// Sources used for Generating Answer ...
/// </summary>
public IList<XAiDocumentSource> Sources { get; set; } = new List<XAiDocumentSource>();
}
/// <summary>
/// Streaming Chunk of a Chat With Documents Answer ...
/// </summary>
public class XAiDocumentAnswerChunk
{
/// <summary>
/// Text Delta ...
/// </summary>
public string Text { get; set; }
/// <summary>
/// True for Last Chunk ...
/// </summary>
public bool IsFinal { get; set; }
/// <summary>
/// True when no Relevant Chunk Found in Session ...
/// </summary>
public bool NoContextFound { get; set; }
/// <summary>
/// Sources (Only Filled in First Chunk) ...
/// </summary>
public IList<XAiDocumentSource> Sources { get; set; }
}
/// <summary>
/// Public Info of a Document Session (without Embeddings) ...
/// </summary>
public class XAiDocumentSessionInfo
{
public Guid Id { get; set; }
public TimeSpan Ttl { get; set; }
public int VectorsCount { get; set; }
public DateTime CreatedAtUtc { get; set; }
public DateTime LastAccessAtUtc { get; set; }
public DateTime ExpiresAtUtc { get; set; }
public IList<string> Files { get; set; } = new List<string>();
}
/// <summary>
/// Document RAG Configuration ...
/// </summary>
public class XAiDocumentRAGDescriptor
{
public int MaxTopK { get; set; } = 20;
public int DefaultTopK { get; set; } = 5;
public int DefaultTtlMinutes { get; set; } = 30;
public int EmbeddingBatchSize { get; set; } = 32;
public int SourceSnippetLength { get; set; } = 200;
public float DefaultMinScore { get; set; } = 0.35f;
public string MetadataFileName { get; set; } = "fileName";
public string MetadataMimeType { get; set; } = "mimeType";
public string PromptName { get; set; } = "ChatWithDocuments";
public string MetadataChunkIndex { get; set; } = "chunkIndex";
}
}
+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 ...
}
}
}
}
+3 -3
View File
@@ -186,14 +186,14 @@ namespace xAiApi
//
// Register File Content Extractor Services ...
services.AddXAiFileContentExtractors();
//
// Register Text Chunker Service ...
services.AddXAiTextChunker();
//
// Register In-Memory Vector Store Service ...
services.AddXAiInMemoryVectorStore();
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
services.AddXAiChatWithDocuments();
//
// Register Default AI Services ...
+142 -124
View File
@@ -1,125 +1,143 @@
{
"AllowedOrigins": [
"http://localhost:5000",
"https://localhost:5001",
"http://api.saherelm.ir",
"https://api.saherelm.ir",
"http://api.saherelmhub.ir",
"https://api.saherelmhub.ir"
],
"IdentityServiceConfiguration": {
"Authority": "https://localhost:4001",
"ApiName": "xSaherElmAPI",
"ApiSecret": "s@H@1694056",
"ClientId": "xSaherElmAPIClient",
"ClientSecret": "s@H@1694056",
"XPoweredValue": "SaherElmITCenter",
"XRevisionSecretKey": "SaherElmITCenter@1694056",
"DefaultClientTimeout": -1
},
"StorageConfiguration": {
"Authority": "https://localhost:5001",
"IdentityAuthority": "https://localhost:5001",
"Storage": "Storage",
"Temp": "Temp",
"Thumb": "Thumb",
"Uploads": "Uploads",
"Widgets": "Widgets",
"Image": "Image",
"Audio": "Audio",
"Video": "Video",
"Document": "Document",
"FilePrefix": "xSaherElm_",
"ThumbPrefix": "Thumb_",
"ThumbSize": 512,
"ThumbQuality": 72,
"MaxFileSize": 41943040
},
"AiApiConfiguration": {
"Models": [
{
"ApiKey": "",
"Name": "Gemma",
"LLM": "gemma3:1b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1112/v1"
},
{
"ApiKey": "",
"Name": "Qwen",
"LLM": "qwen-9b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1114/v1"
},
{
"ApiKey": "",
"Name": "Embed",
"LLM": "bge-m3",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1113/v1"
}
],
"Prompts": [
{
"Name": "Introduction",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.",
"Description": "",
"Params": []
},
{
"Name": "ContentExtraction",
"Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.",
"Description": "",
"Params": []
},
{
"Name": "Embedding",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
"Description": "",
"Params": []
}
],
"OCR": {
"DataPath": "Models",
"EngineMode": "LstmOnly",
"EnableOcrFallback": true,
"DefaultLanguage": "fas+eng"
},
"Transcript": {
"Language": "fa",
"ModelsPath": "Models/ggml-base.bin"
},
"PDFToImageDescriptor": {
"Dpi": 300,
"Width": 0,
"Height": 0,
"UseTiling": false,
"WithFormFill": false,
"WithAspectRatio": false,
"WithAnnotations": false,
"DpiRelativeToBounds": false,
"MaxImageWidth": 2000,
"MinTextLengthThreshold": 50,
"MaxPagesForImageFallback": 0
},
"ProxyConfiguration": {
"Enabled": true,
"RoutePrefix": "/ai-model"
},
"TextChunker": {
"ChunkSize": 800,
"ChunkOverlap": 150,
"MinChunkSize": 50,
"NormalizeWhitespace": true,
"ChunkIdentifierSeparator": "#"
}
},
"Logging": {
"LogLevel": {
"Microsoft": "Warning",
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
"AllowedOrigins": [
"http://localhost:5000",
"https://localhost:5001",
"http://api.saherelm.ir",
"https://api.saherelm.ir",
"http://api.saherelmhub.ir",
"https://api.saherelmhub.ir"
],
"IdentityServiceConfiguration": {
"Authority": "https://localhost:4001",
"ApiName": "xSaherElmAPI",
"ApiSecret": "s@H@1694056",
"ClientId": "xSaherElmAPIClient",
"ClientSecret": "s@H@1694056",
"XPoweredValue": "SaherElmITCenter",
"XRevisionSecretKey": "SaherElmITCenter@1694056",
"DefaultClientTimeout": -1
},
"StorageConfiguration": {
"Authority": "https://localhost:5001",
"IdentityAuthority": "https://localhost:5001",
"Storage": "Storage",
"Temp": "Temp",
"Thumb": "Thumb",
"Uploads": "Uploads",
"Widgets": "Widgets",
"Image": "Image",
"Audio": "Audio",
"Video": "Video",
"Document": "Document",
"FilePrefix": "xSaherElm_",
"ThumbPrefix": "Thumb_",
"ThumbSize": 512,
"ThumbQuality": 72,
"MaxFileSize": 41943040
},
"AiApiConfiguration": {
"Models": [
{
"ApiKey": "",
"Name": "Gemma",
"LLM": "gemma3:1b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1112/v1"
},
{
"ApiKey": "",
"Name": "Qwen",
"LLM": "qwen-9b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1114/v1"
},
{
"ApiKey": "",
"Name": "Embed",
"LLM": "bge-m3",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1113/v1"
}
],
"Prompts": [
{
"Name": "Introduction",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.",
"Description": "",
"Params": []
},
{
"Name": "ContentExtraction",
"Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.",
"Description": "",
"Params": []
},
{
"Name": "Embedding",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
"Description": "",
"Params": []
},
{
"Name": "ChatWithDocuments",
"Template": "You are a document question-answering assistant. Answer the user's question ONLY based on the provided Context chunks below. Follow these rules: 1. If the answer is not present in the Context, clearly state that the information was not found in the provided documents and do not make up an answer. 2. When using information from a chunk, cite its source identifier in square brackets (e.g. [file.pdf#3]). 3. Answer in the same language as the user's question. 4. Be concise and precise; do not add unrelated information.",
"Description": "System prompt for RAG based Chat With Documents",
"Params": []
}
],
"OCR": {
"DataPath": "Models",
"EngineMode": "LstmOnly",
"EnableOcrFallback": true,
"DefaultLanguage": "fas+eng"
},
"Transcript": {
"Language": "fa",
"ModelsPath": "Models/ggml-base.bin"
},
"PDFToImageDescriptor": {
"Dpi": 300,
"Width": 0,
"Height": 0,
"UseTiling": false,
"WithFormFill": false,
"WithAspectRatio": false,
"WithAnnotations": false,
"DpiRelativeToBounds": false,
"MaxImageWidth": 2000,
"MinTextLengthThreshold": 50,
"MaxPagesForImageFallback": 0
},
"ProxyConfiguration": {
"Enabled": true,
"RoutePrefix": "/ai-model"
},
"TextChunker": {
"ChunkSize": 800,
"ChunkOverlap": 150,
"MinChunkSize": 50,
"NormalizeWhitespace": true,
"ChunkIdentifierSeparator": "#"
},
"RAGDescriptor": {
"MaxTopK": 20,
"DefaultTopK": 5,
"DefaultTtlMinutes": 30,
"EmbeddingBatchSize": 32,
"SourceSnippetLength": 200,
"DefaultMinScore": "0.35f",
"MetadataFileName": "fileName",
"MetadataMimeType": "mimeType",
"PromptName": "ChatWithDocuments",
"MetadataChunkIndex": "chunkIndex"
}
},
"Logging": {
"LogLevel": {
"Microsoft": "Warning",
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}