using System; using xAiApi.Models; using System.Threading; using xAiApi.Interfaces; using xCommons.Providers; using xAiModels.Constants; using xCommons.Extensions; using xExceptions.Constants; using System.Threading.Tasks; using xHttpService.Extensions; 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 { /// /// Knowledge (Persistent RAG over XAiVector Table) Controller ... /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete /// [Authorize] [Route("[controller]")] public class KnowledgeController : XBaseIdentityApiV1Controller { /// /// Persistent RAG Service ... /// private readonly IXAiRAGService ragService; public KnowledgeController( IXAiRAGService ragService, XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, ILogger logger, XValidationProvider validationProvider ) : base(logger, appConfiguration, identityProvider, validationProvider) { // this.ragService = ragService; } // #region Ingest ... /// /// Ingest Files into a Knowledge Scope: /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... /// /// /// Target Scope: User (default) / Project / Conversation / Global (Admin) /// ProjectId or ConversationId (Required for Project / Conversation) /// Optional Knowledge Type / Domain /// Replace Previously Stored Vectors of Same File (default true) /// /// [HttpPost("Ingest")] [Consumes("multipart/form-data")] public async Task> Ingest( [FromForm] IFormFileCollection files, [FromForm] XAiKnowledgeScope scope = XAiKnowledgeScope.Global, [FromForm] Guid? scopeId = null, [FromForm] string knowledgeType = null, [FromForm] bool replaceExisting = true, CancellationToken cancellationToken = default ) { // try { // // Validate ... if (!files.HasChild()) { XException.InvalidArgs.Throw(); } // var userInfo = await GetUserInfo(); var connectionId = GetConnectionId(); // var result = await ragService.IngestAsync( files: files, userInfo: userInfo, connectionId: connectionId, replaceExisting: replaceExisting, cancellationToken: cancellationToken, scope: BuildScope(scope, scopeId, knowledgeType) ); // return Ok(result); } catch (Exception ex) { // var result = GetExceptionActionResult(ex); return result; } } #endregion // #region Ask ... /// /// Ask a Question over Knowledge Base (RAG) ... /// /// /// /// [HttpPost("Ask")] public async Task> 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, userInfo: userInfo, cancellationToken: cancellationToken ); // return Ok(result); } catch (Exception ex) { // var result = GetExceptionActionResult(ex); return result; } } /// /// Ask a Question over Knowledge Base and Stream Response (SSE) ... /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has isFinal = true ... /// /// /// /// [HttpPost("AskStream")] public async Task AskStream( [FromBody] XAiKnowledgeAskRequest request, CancellationToken cancellationToken = default ) { // // Validate (before Stream Starts -> Proper Http Error) ... if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty()) { Response.StatusCode = StatusCodes.Status400BadRequest; Response.ContentType = "application/json; charset=utf-8"; await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); return; } // try { // var userInfo = await GetUserInfo(); // await using var enumerator = ragService .AskWithRAGAsEnumerable( request: request, userInfo: userInfo, cancellationToken: cancellationToken ) .GetAsyncEnumerator(cancellationToken); // // Pull First Item before Starting Stream, so Scope / Ownership / // Retrieval Errors are Returned as Regular Http Errors ... var hasItem = await enumerator.MoveNextAsync(); // // Configure SSE Response ... Response.PrepareSseResponse(); // while (hasItem) { // var chunk = enumerator.Current; if (!chunk.IsNullOrDefault()) { await WriteChunk(chunk, cancellationToken); } // hasItem = await enumerator.MoveNextAsync(); } // await Response.WriteSseDoneAsync(cancellationToken); } catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) { // Client Disconnected ... } catch (Exception ex) { // Logger.LogError(ex, "Knowledge: AskStream Failed"); if (!Response.HasStarted) { // var result = GetExceptionActionResult(ex); await result.ExecuteResultAsync(ControllerContext); return; } // await Response.WriteSseErrorAsync(ex.Message); } } #endregion // #region Documents ... /// /// List Ingested Documents of a Knowledge Scope ... /// /// User (default) / Project / Conversation / Global /// ProjectId or ConversationId (Required for Project / Conversation) /// Optional Knowledge Type Filter /// /// [HttpGet("Documents")] public async Task>> Documents( [FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User, [FromQuery] Guid? scopeId = null, [FromQuery] string knowledgeType = null, CancellationToken cancellationToken = default ) { // try { // var userInfo = await GetUserInfo(); // var result = await ragService.LoadDocumentsAsync( userInfo: userInfo, cancellationToken: cancellationToken, scope: BuildScope(scope, scopeId, knowledgeType) ); // return Ok(result); } catch (Exception ex) { // var result = GetExceptionActionResult(ex); return result; } } /// /// Remove All Vectors of a Document in a Knowledge Scope ... /// /// /// User (default) / Project / Conversation / Global (Admin) /// ProjectId or ConversationId (Required for Project / Conversation) /// /// Count of Removed Vectors [HttpDelete("Documents")] public async Task> DeleteDocument( [FromQuery] string fileName, [FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User, [FromQuery] Guid? scopeId = null, CancellationToken cancellationToken = default ) { // try { // // Validate ... ValidationProvider.NotEmpty(fileName); // var userInfo = await GetUserInfo(); // var result = await ragService.RemoveDocumentAsync( fileName: fileName, userInfo: userInfo, cancellationToken: cancellationToken, scope: BuildScope(scope, scopeId, null) ); // return Ok(result); } catch (Exception ex) { // var result = GetExceptionActionResult(ex); return result; } } #endregion // #region Private ... /// /// Build Scope Descriptor from Request Params ... /// private XAiKnowledgeScopeDescriptor BuildScope( XAiKnowledgeScope scope, Guid? scopeId, string knowledgeType ) { // var result = new XAiKnowledgeScopeDescriptor { Scope = scope, ScopeId = scopeId, Type = knowledgeType, }; // return result; } /// /// Write a SSE Event ... /// private Task WriteChunk( XAiDocumentAnswerChunk chunk, CancellationToken cancellationToken ) { // return Response.WriteSseEventAsync( data: chunk, cancellationToken: cancellationToken ); } #endregion } }