Add Persistent Knowledge RAG Service and API
- Add IXAiRAGService and XAiRAGService for Extract -> Chunk -> Embed -> Store;
- Add synchronous and streaming RAG answers with sources;
- Add Knowledge models and KnowledgeController endpoints;
- Register IXAiRAGService as scoped;
- Keep current identifier: {ownerId}/{fileName}#{chunkIndex}.
This commit is contained in:
@@ -0,0 +1,319 @@
|
||||
using System;
|
||||
using xAiApi.Models;
|
||||
using System.Threading;
|
||||
using xAiApi.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Controllers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xAiApi.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Knowledge (Persistent RAG over XAiVector Table) Controller ...
|
||||
/// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[Route("[controller]")]
|
||||
public class KnowledgeController : XBaseIdentityApiV1Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Persistent RAG Service ...
|
||||
/// </summary>
|
||||
private readonly IXAiRAGService ragService;
|
||||
|
||||
public KnowledgeController(
|
||||
IXAiRAGService ragService,
|
||||
XAppConfiguration appConfiguration,
|
||||
IXIdentityProvider identityProvider,
|
||||
ILogger<KnowledgeController> logger,
|
||||
XValidationProvider validationProvider
|
||||
) : base(logger, appConfiguration, identityProvider, validationProvider)
|
||||
{
|
||||
//
|
||||
this.ragService = ragService;
|
||||
}
|
||||
|
||||
//
|
||||
#region Ingest ...
|
||||
/// <summary>
|
||||
/// Ingest Files into Current User's Knowledge Base:
|
||||
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
|
||||
/// </summary>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("Ingest")]
|
||||
[Consumes("multipart/form-data")]
|
||||
public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
|
||||
[FromForm] IFormFileCollection files,
|
||||
[FromForm] bool replaceExisting = true,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!files.HasChild())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await ragService.IngestAsync(
|
||||
files: files,
|
||||
ownerId: userInfo.UserId,
|
||||
replaceExisting: replaceExisting,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Ask ...
|
||||
/// <summary>
|
||||
/// Ask a Question over Knowledge Base (RAG) ...
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("Ask")]
|
||||
public async Task<ActionResult<XAiDocumentAnswer>> Ask(
|
||||
[FromBody] XAiKnowledgeAskRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await ragService.AskWithRAGAsync(
|
||||
request: request,
|
||||
ownerId: userInfo.UserId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ask a Question over Knowledge Base 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] XAiKnowledgeAskRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
// 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();
|
||||
|
||||
//
|
||||
var enumerable = ragService.AskWithRAGAsEnumerable(
|
||||
request: request,
|
||||
ownerId: userInfo.UserId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
await foreach (var chunk in enumerable)
|
||||
{
|
||||
//
|
||||
if (chunk.IsNullOrDefault())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
await WriteChunk(chunk, cancellationToken);
|
||||
}
|
||||
|
||||
//
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
Logger.LogError(ex, "Knowledge: AskStream Failed");
|
||||
try
|
||||
{
|
||||
//
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
}
|
||||
await Response.Body.FlushAsync(CancellationToken.None);
|
||||
}
|
||||
catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Documents ...
|
||||
/// <summary>
|
||||
/// List Ingested Documents of Current User ...
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Documents")]
|
||||
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await ragService.LoadDocumentsAsync(
|
||||
ownerId: userInfo.UserId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove All Vectors of a Document ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns>Count of Removed Vectors</returns>
|
||||
[HttpDelete("Documents")]
|
||||
public async Task<ActionResult<int>> DeleteDocument(
|
||||
[FromQuery] string fileName,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
ValidationProvider.NotEmpty(fileName);
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await ragService.RemoveDocumentAsync(
|
||||
fileName: fileName,
|
||||
ownerId: userInfo.UserId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <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