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:
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user