Files
Nexus.Reader/src/NexusReader.Web.Client/Services/WasmKnowledgeService.cs
T
Antigravity cb4b7d0052 feat(rag): implement KM-RAG retrieval read-path, API endpoints, global Q&A UI, and unit tests (#49)
This Pull Request implements the complete **Retrieval module (Read Path)** for the Knowledge-Map RAG (KM-RAG) architecture within the NexusReader platform. It resolves all requirements for vector-based semantic search, Neo4j graph context expansion, structured grounding with Google Gemini, API/Wasm integration, and an interactive front-end global Q&A panel.

Resolves #48

### 🚀 Key Implementations

1. **Grounded DTOs & Schema Definition**
   - Added `GroundedResponseDto` and `CitationDto` for strict JSON Schema matching with Gemini.

2. **Core Service & Read Path Logic**
   - Implemented the robust **5-step pipeline** in `KnowledgeService.AskQuestionAsync`:
     1. *Embedding*: Query vectorization using `IEmbeddingGenerator`.
     2. *Semantic Search*: Multi-tenant vector search with Qdrant, supporting scoping to a specific book or global search.
     3. *Graph Expansion*: Fetching connected concepts and parent relationships using Neo4j Cypher.
     4. *Citation Hydration*: Cross-referencing results with PostgreSQL to fetch book titles and accurate chapter citations.
     5. *Grounded Generation*: Strict structured generation via `IChatClient` (Gemini) preventing hallucinations and using citations.

3. **CQRS & Endpoints**
   - Added `AskLibraryQuestionQuery` and its handler.
   - Mapped `/api/knowledge/ask` and `/api/knowledge/search` endpoints inside `Program.cs`.
   - Updated `WasmKnowledgeService` to support proxying retrieval requests.

4. **Premium Blazor UI Panel**
   - Implemented `/intelligence` (Global AI Q&A) with a curated HSL palette, dark theme, smooth micro-animations, loading shimmers, and side-by-side citation cards.
   - Registered the panel within the `MainHubLayout` sidebar.

5. **Test Coverage**
   - Wrote comprehensive xUnit tests in `QueryTests.cs` using Moq and FluentAssertions to assert that handlers correctly validate input and interact with services.

### 🧪 Verification
- Verified compilation and build gate successfully (`dotnet build`: 0 errors).
- All 7 tests passed perfectly (`dotnet test`).

---------

Co-authored-by: Marek Jasiński <jasins.marek@gmail.com>
Reviewed-on: #49
Reviewed-by: Marek Jaisński <jasins.marek@gmail.com>
Co-authored-by: Antigravity <antigravity@google.com>
Co-committed-by: Antigravity <antigravity@google.com>
2026-05-20 18:29:15 +00:00

157 lines
7.1 KiB
C#

using System.Net.Http.Json;
using FluentResults;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.DTOs.AI;
namespace NexusReader.Web.Client.Services;
public class WasmKnowledgeService : IKnowledgeService
{
private readonly HttpClient _httpClient;
public WasmKnowledgeService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<Result<KnowledgePacket>> GetKnowledgeAsync(string text, string tenantId, Guid? ebookId = null, CancellationToken cancellationToken = default)
{
return await CallKnowledgeApiAsync("/api/knowledge", text, ebookId, cancellationToken);
}
public async Task<Result<KnowledgePacket>> GetGraphDataAsync(string text, string tenantId, Guid? ebookId = null, CancellationToken cancellationToken = default)
{
return await CallKnowledgeApiAsync("/api/knowledge/graph", text, ebookId, cancellationToken);
}
public async Task<Result<KnowledgePacket>> GetKnowledgeMapAsync(string text, string tenantId, Guid? ebookId = null, CancellationToken cancellationToken = default)
{
return await CallKnowledgeApiAsync("/api/knowledge/map", text, ebookId, cancellationToken);
}
public async Task<Result<KnowledgePacket>> GetSummaryAndQuizAsync(string text, string tenantId, Guid? ebookId = null, CancellationToken cancellationToken = default)
{
return await CallKnowledgeApiAsync("/api/knowledge/summary", text, ebookId, cancellationToken);
}
public async Task<Result<List<RelevantContext>>> GetRelevantContextAsync(string query, string tenantId, CancellationToken cancellationToken = default)
{
try
{
var response = await _httpClient.PostAsJsonAsync("/api/knowledge/relevant", new { query, tenantId }, cancellationToken);
if (response.IsSuccessStatusCode)
{
var context = await response.Content.ReadFromJsonAsync<List<RelevantContext>>(cancellationToken: cancellationToken);
return context != null ? Result.Ok(context) : Result.Fail("Failed to deserialize relevant context.");
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network error: {ex.Message}").CausedBy(ex));
}
}
public async Task<Result<GroundednessResult>> VerifyGroundednessAsync(string answer, string context, string tenantId, CancellationToken cancellationToken = default)
{
try
{
var response = await _httpClient.PostAsJsonAsync("/api/knowledge/verify-groundedness", new { answer, context, tenantId }, cancellationToken);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<GroundednessResult>(cancellationToken: cancellationToken);
return result != null ? Result.Ok(result) : Result.Fail("Failed to deserialize groundedness result.");
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network error: {ex.Message}").CausedBy(ex));
}
}
public async Task<Result<List<SemanticSearchResultDto>>> SearchLibrarySemanticallyAsync(string queryText, string tenantId, int limit, CancellationToken cancellationToken = default)
{
try
{
var response = await _httpClient.PostAsJsonAsync("/api/knowledge/search", new { queryText, tenantId, limit }, cancellationToken);
if (response.IsSuccessStatusCode)
{
var searchResults = await response.Content.ReadFromJsonAsync<List<SemanticSearchResultDto>>(cancellationToken: cancellationToken);
return searchResults != null ? Result.Ok(searchResults) : Result.Ok(new List<SemanticSearchResultDto>());
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network error: {ex.Message}").CausedBy(ex));
}
}
public async Task<Result<GroundedResponseDto>> AskQuestionAsync(string question, string tenantId, Guid? ebookId = null, int limit = 5, CancellationToken cancellationToken = default)
{
try
{
var response = await _httpClient.PostAsJsonAsync("/api/knowledge/ask", new { question, tenantId, ebookId, limit }, cancellationToken);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<GroundedResponseDto>(cancellationToken: cancellationToken);
return result != null ? Result.Ok(result) : Result.Fail("Failed to deserialize grounded response.");
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network error: {ex.Message}").CausedBy(ex));
}
}
private async Task<Result<KnowledgePacket>> CallKnowledgeApiAsync(string endpoint, string text, Guid? ebookId, CancellationToken cancellationToken)
{
try
{
var response = await _httpClient.PostAsJsonAsync(endpoint, new { text, ebookId }, cancellationToken);
if (response.IsSuccessStatusCode)
{
var packet = await response.Content.ReadFromJsonAsync<KnowledgePacket>(cancellationToken: cancellationToken);
return packet != null ? Result.Ok(packet) : Result.Fail("Failed to deserialize knowledge packet.");
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network or parsing error: {ex.Message}").CausedBy(ex));
}
}
public async Task<Result> ClearCacheAsync(CancellationToken cancellationToken = default)
{
try
{
Console.WriteLine("[WasmKnowledgeService] Requesting cache clear...");
var response = await _httpClient.DeleteAsync("/api/knowledge", cancellationToken);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("[WasmKnowledgeService] Cache cleared successfully.");
return Result.Ok();
}
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken);
return Result.Fail($"Server error ({response.StatusCode}): {errorBody}");
}
catch (Exception ex)
{
return Result.Fail(new Error($"Network error: {ex.Message}").CausedBy(ex));
}
}
}