Compare commits
46
Commits
20f1c7fb2f
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a228439a5 | ||
|
|
13cd0745c6 | ||
|
|
5bccce3475 | ||
|
|
cddf2650f5 | ||
|
|
fba69b274c | ||
|
|
0077008105 | ||
|
|
3dc54332c2 | ||
|
|
dab384ea37 | ||
|
|
f6a916fa83 | ||
|
|
5656ec07d5 | ||
|
|
c24c14eb74 | ||
|
|
b58f1dd736 | ||
|
|
31add513bc | ||
|
|
16fb715926 | ||
|
|
5307fe4d2f | ||
|
|
ae7f5920c1 | ||
|
|
97acf0a123 | ||
|
|
c7efdd5525 | ||
|
|
937e30dd9d | ||
|
|
c61f8aec98 | ||
|
|
a870d61e61 | ||
|
|
726d6ce827 | ||
|
|
fa1014bf20 | ||
|
|
ce4e5927dd | ||
|
|
51dddb4b68 | ||
|
|
ce5db9e349 | ||
|
|
c1173042d4 | ||
|
|
ad8ea9c1dd | ||
|
|
37d4e622e9 | ||
|
|
d3ecc8feea | ||
|
|
07a3caa98f | ||
|
|
d68c1367b6 | ||
|
|
058d8da780 | ||
|
|
9e82e05bfe | ||
|
|
fef38cad1b | ||
|
|
fa92763baa | ||
|
|
47da04a594 | ||
|
|
47d8a19423 | ||
|
|
429b97cded | ||
|
|
4b857de518 | ||
|
|
0e3d6249a2 | ||
|
|
0f92c54fb5 | ||
|
|
f39cde0d09 | ||
|
|
877627714c | ||
|
|
907926b0f7 | ||
|
|
ddfa7979a5 |
@@ -1,6 +1,7 @@
|
|||||||
#
|
#
|
||||||
bin/*
|
bin/*
|
||||||
obj/*
|
obj/*
|
||||||
|
Logs
|
||||||
|
|
||||||
#
|
#
|
||||||
Db/*
|
Db/*
|
||||||
|
|||||||
@@ -18,11 +18,38 @@ namespace xAiApi.Configurations
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// OCR Configuration ...
|
/// OCR Configuration ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public XAiOCRDescriptor OCR { get; set; }
|
public XAiOCRDescriptor OCR { get; set; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Transcript Configuration ...
|
/// Transcript Configuration ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public XAiTransciptDescriptor Transcript { get; set; }
|
public XAiTransciptDescriptor Transcript { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// PDF To Image Configuration ...
|
||||||
|
/// </summary>
|
||||||
|
public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Proxy Configuration ...
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Text Chunker Configuration ...
|
||||||
|
/// </summary>
|
||||||
|
public XTextChunkerDescriptor TextChunker { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// RAG Configuration ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DateTime Configuration ...
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public XDateTimeDescriptor DateTime { get; set; } = new();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,17 +11,15 @@ namespace xAiApi.Constants
|
|||||||
public const string XDILogTag = "XAiApi";
|
public const string XDILogTag = "XAiApi";
|
||||||
|
|
||||||
//
|
//
|
||||||
|
public const string XAiApiRagPromptName = "ChatWithDocuments";
|
||||||
public const string XAiApiIntroductionPromptName = "Introduction";
|
public const string XAiApiIntroductionPromptName = "Introduction";
|
||||||
public const string XAiApiContentExtractionPromptName = "ContentExtraction";
|
public const string XAiApiContentExtractionPromptName = "ContentExtraction";
|
||||||
|
|
||||||
//
|
//
|
||||||
public const string XAiDefaultModelName = "Gemma";
|
public const string XAiDefaultModelName = "Arion";
|
||||||
public const string XAiEmbeddingModelName = "Embed";
|
public const string XAiEmbeddingModelName = "Embed";
|
||||||
public const string XAiDefaultVisionModelName = "Qwen";
|
public const string XAiDefaultVisionModelName = "Qwen";
|
||||||
public const string XAiDefaultThinkingModelName = "Qwen";
|
public const string XAiDefaultThinkingModelName = "Qwen";
|
||||||
public const string XAiEmbeddingPromptName = "Embedding";
|
public const string XAiEmbeddingPromptName = "Embedding";
|
||||||
|
|
||||||
//
|
|
||||||
public const string XOpenAINoKey = "no-key-required";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,27 @@
|
|||||||
using xAiApi.Interfaces;
|
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using xIdentityHelper.Controllers;
|
||||||
using xIdentityService.Interfaces;
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
|
|
||||||
namespace xAiApi.Controllers
|
namespace xAiApi.Controllers
|
||||||
{
|
{
|
||||||
[Authorize]
|
public partial class AccountController : XAccountControllerBase
|
||||||
[Route("[controller]")]
|
|
||||||
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXDefaultEmbeddingService>
|
|
||||||
{
|
{
|
||||||
public DefaultEmbeddingController(
|
//
|
||||||
ILogger<DefaultEmbeddingController> logger,
|
#region Constructor ...
|
||||||
IXDefaultEmbeddingService aiService,
|
public AccountController(
|
||||||
|
ILogger<AccountController> logger,
|
||||||
XAppConfiguration appConfiguration,
|
XAppConfiguration appConfiguration,
|
||||||
IXIdentityProvider identityProvider,
|
IXIdentityProvider identityProvider,
|
||||||
XValidationProvider validationProvider
|
XValidationProvider validationProvider
|
||||||
) : base(
|
) : base(
|
||||||
logger,
|
logger,
|
||||||
aiService,
|
|
||||||
appConfiguration,
|
appConfiguration,
|
||||||
identityProvider,
|
identityProvider,
|
||||||
validationProvider
|
validationProvider
|
||||||
)
|
)
|
||||||
{ }
|
{ }
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,693 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using xAiApi.Models;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiApi.Interfaces;
|
||||||
|
using xAiApi.Extensions;
|
||||||
|
using xCommons.Providers;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xAiApi.Configurations;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
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 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]
|
||||||
|
public class ChatWithDocumentsController : XBaseIdentityApiV1Controller
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Default AI Service ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly IXAiService aiService;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Text Chunker Service ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly IXTextChunker textChunker;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// In Memory Vector Store ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly IXInMemoryVectorStore vectorStore;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// XAiApi Configuration ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly XAiApiConfiguration apiConfiguration;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Embedding Service ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly IXAiEmbeddingService embeddingService;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// File Context Extractor Service ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly IXFileContentExtractor fileContentExtractor;
|
||||||
|
|
||||||
|
public ChatWithDocumentsController(
|
||||||
|
IXAiService aiService,
|
||||||
|
IXTextChunker textChunker,
|
||||||
|
IXInMemoryVectorStore vectorStore,
|
||||||
|
XAppConfiguration appConfiguration,
|
||||||
|
IXIdentityProvider identityProvider,
|
||||||
|
XAiApiConfiguration apiConfiguration,
|
||||||
|
IXAiEmbeddingService embeddingService,
|
||||||
|
XValidationProvider validationProvider,
|
||||||
|
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>
|
||||||
|
/// Ingest Files into a (new or existing) In-Memory Session:
|
||||||
|
/// Extract -> Chunk -> Embed -> Store ...
|
||||||
|
/// </summary>
|
||||||
|
/// <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
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
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,
|
||||||
|
fileName: file.FileName,
|
||||||
|
mimeType: mimeType,
|
||||||
|
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.AskTextByContextAsync(
|
||||||
|
context: context,
|
||||||
|
userInfo: userInfo,
|
||||||
|
prompt: request.Prompt,
|
||||||
|
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
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||||
|
if (!request.IsValid())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||||
|
Response.ContentType = "application/json; charset=utf-8";
|
||||||
|
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
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 ...
|
||||||
|
Response.PrepareSseResponse();
|
||||||
|
|
||||||
|
//
|
||||||
|
// First Event: Sources ...
|
||||||
|
var hasContext = context.HasChild();
|
||||||
|
await WriteChunk(new XAiDocumentAnswerChunk
|
||||||
|
{
|
||||||
|
Text = string.Empty,
|
||||||
|
IsFinal = !hasContext,
|
||||||
|
NoContextFound = !hasContext,
|
||||||
|
Sources = ToSources(context)
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
//
|
||||||
|
if (!hasContext)
|
||||||
|
{
|
||||||
|
await Response.WriteSseDoneAsync(cancellationToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Stream Deltas ...
|
||||||
|
var enumerable = aiService.AskTextByContextAsEnumerable(
|
||||||
|
context: context,
|
||||||
|
userInfo: userInfo,
|
||||||
|
prompt: request.Prompt,
|
||||||
|
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);
|
||||||
|
await Response.WriteSseDoneAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||||
|
{
|
||||||
|
// Client Disconnected ...
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
|
||||||
|
if (!Response.HasStarted)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
await result.ExecuteResultAsync(ControllerContext);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
await Response.WriteSseErrorAsync(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#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 => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName))
|
||||||
|
.Where(f => !f.IsNullOrEmpty())
|
||||||
|
.Distinct()]
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
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 = c.Metadata.GetMetadata(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 = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write a SSE Event ...
|
||||||
|
/// </summary>
|
||||||
|
private Task WriteChunk(
|
||||||
|
XAiDocumentAnswerChunk chunk,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return Response.WriteSseEventAsync(
|
||||||
|
data: chunk,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
using xAiApi.Interfaces;
|
|
||||||
using xCommons.Providers;
|
|
||||||
using xCommons.Configurations;
|
|
||||||
using xIdentityService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace xAiApi.Controllers
|
|
||||||
{
|
|
||||||
public class DefaultThinkingAiController : XAiServiceControllerBase<IXDefaultThinkingAiService>
|
|
||||||
{
|
|
||||||
public DefaultThinkingAiController(
|
|
||||||
ILogger<DefaultThinkingAiController> logger,
|
|
||||||
IXDefaultThinkingAiService aiService,
|
|
||||||
XAppConfiguration appConfiguration,
|
|
||||||
IXIdentityProvider identityProvider,
|
|
||||||
XValidationProvider validationProvider
|
|
||||||
) : base(
|
|
||||||
logger,
|
|
||||||
aiService,
|
|
||||||
appConfiguration,
|
|
||||||
identityProvider,
|
|
||||||
validationProvider
|
|
||||||
)
|
|
||||||
{ }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
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;
|
||||||
|
using xIdentityHelper;
|
||||||
|
|
||||||
|
namespace xAiApi.Controllers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Knowledge (Persistent RAG over XAiVector Table) Controller ...
|
||||||
|
/// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
|
||||||
|
/// </summary>
|
||||||
|
[Authorize]
|
||||||
|
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 a Knowledge Scope:
|
||||||
|
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="files"></param>
|
||||||
|
/// <param name="scope">Target Scope: User (default) / Project / Conversation / Global (Admin)</param>
|
||||||
|
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
|
||||||
|
/// <param name="knowledgeType">Optional Knowledge Type / Domain</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")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||||||
|
public async Task<ActionResult<XAiKnowledgeIngestResult>> 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 Documents ...
|
||||||
|
/// <summary>
|
||||||
|
/// List Ingested Documents of a Knowledge Scope ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="scope">User (default) / Project / Conversation / Global</param>
|
||||||
|
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
|
||||||
|
/// <param name="knowledgeType">Optional Knowledge Type Filter</param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet("Documents")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||||||
|
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
|
||||||
|
[FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
|
||||||
|
[FromQuery] Guid? scopeId = null,
|
||||||
|
[FromQuery] string knowledgeType = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var scopeIdentifier = BuildScope(scope, scopeId, knowledgeType);
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await ragService.LoadDocumentsAsync(
|
||||||
|
userInfo: userInfo,
|
||||||
|
scope: scopeIdentifier,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Remove All Vectors of a Document in a Knowledge Scope ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="scope">User (default) / Project / Conversation / Global (Admin)</param>
|
||||||
|
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns>Count of Removed Vectors</returns>
|
||||||
|
[HttpDelete("Documents")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||||||
|
public async Task<ActionResult<int>> DeleteDocument(
|
||||||
|
[FromQuery] string fileName,
|
||||||
|
[FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
|
||||||
|
[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 ...
|
||||||
|
/// <summary>
|
||||||
|
/// Build Scope Descriptor from Request Params ...
|
||||||
|
/// </summary>
|
||||||
|
private XAiKnowledgeScopeDescriptor BuildScope(
|
||||||
|
XAiKnowledgeScope? scope,
|
||||||
|
Guid? scopeId,
|
||||||
|
string knowledgeType
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (!scope.HasValue)
|
||||||
|
{
|
||||||
|
scope = XAiKnowledgeScope.Global;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = new XAiKnowledgeScopeDescriptor
|
||||||
|
{
|
||||||
|
Scope = scope.Value,
|
||||||
|
ScopeId = scopeId,
|
||||||
|
Type = knowledgeType,
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write a SSE Event ...
|
||||||
|
/// </summary>
|
||||||
|
private Task WriteChunk(
|
||||||
|
XAiDocumentAnswerChunk chunk,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return Response.WriteSseEventAsync(
|
||||||
|
data: chunk,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,501 @@
|
|||||||
|
using System;
|
||||||
|
using xModels.Dtos;
|
||||||
|
using xIdentityHelper;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiApi.Interfaces;
|
||||||
|
using xCommons.Providers;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xAiModels.Extensions;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using xCommons.Configurations;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using xIdentityService.Controllers;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
namespace xAiApi.Controllers
|
||||||
|
{
|
||||||
|
[Authorize]
|
||||||
|
public class McpServersController : XBaseIdentityApiV1Controller
|
||||||
|
{
|
||||||
|
private readonly IXAiMcpServerProvider mcpServerProvider;
|
||||||
|
|
||||||
|
public McpServersController(
|
||||||
|
XAppConfiguration appConfiguration,
|
||||||
|
IXIdentityProvider identityProvider,
|
||||||
|
ILogger<McpServersController> logger,
|
||||||
|
XValidationProvider validationProvider,
|
||||||
|
IXAiMcpServerProvider mcpServerProvider
|
||||||
|
) : base(
|
||||||
|
logger,
|
||||||
|
appConfiguration,
|
||||||
|
identityProvider,
|
||||||
|
validationProvider
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.mcpServerProvider = mcpServerProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Provider ...
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieve Specified MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<XAiMcpServerDto>> GetMcpServer(
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid || id.IsDefaultGuid())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.GetMcpServer(
|
||||||
|
id: id,
|
||||||
|
userInfo: userInfo,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result.ToDynamicObject());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Add MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="item"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<XAiMcpServerDto>> AddMcpServer(
|
||||||
|
[FromBody] XAiMcpServerDto item,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid || item.IsNullOrDefault())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.AddMcpServer(
|
||||||
|
item: item,
|
||||||
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result.ToDynamicObject());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Update Specified MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="item"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPut("{id}")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<XAiMcpServerDto>> UpdateMcpServer(
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
[FromBody] XAiMcpServerDto item,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (id.IsDefaultGuid() ||
|
||||||
|
!ModelState.IsValid ||
|
||||||
|
!item.IsValidForAddOrUpdate())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.UpdateMcpServer(
|
||||||
|
id: id,
|
||||||
|
item: item,
|
||||||
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result.ToDynamicObject());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Remove Specified MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpDelete("{id}")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<XAiMcpServerDto>> RemoveMcpServer(
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid || id.IsDefaultGuid())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.RemoveMcpServer(
|
||||||
|
id: id,
|
||||||
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result.ToDynamicObject());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enable Specified MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("{id}/Enable")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<bool>> EnableMcpServer(
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid || id.IsDefaultGuid())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.EnableMcpServer(
|
||||||
|
id: id,
|
||||||
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Disable Specified MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("{id}/Disable")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<bool>> DisableMcpServer(
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid || id.IsDefaultGuid())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.DisableMcpServer(
|
||||||
|
id: id,
|
||||||
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Toggle Specified MCP Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("{id}/Toggle")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<bool>> ToggleMcpServer(
|
||||||
|
[FromRoute] Guid id,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid || id.IsDefaultGuid())
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.ToggleMcpServer(
|
||||||
|
id: id,
|
||||||
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get all Registered MCP Servers by handling Ownership ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> GetMcpServers(
|
||||||
|
[FromQuery] bool forceOwner = true,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.GetAll(
|
||||||
|
userInfo: userInfo,
|
||||||
|
forceOwner: forceOwner,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result.ToDynamicObject());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Query Registered MCP Servers by handling Ownership ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="query"></param>
|
||||||
|
/// <param name="forceOwner"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet("Query")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public virtual async Task<ActionResult<XQueryResult<XAiMcpServerDto>>> QueryMcpServers(
|
||||||
|
[FromQuery] XQuery query,
|
||||||
|
[FromQuery] bool forceOwner = true,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
{
|
||||||
|
XException.InvalidArgs.Throw();
|
||||||
|
}
|
||||||
|
await ValidationProvider
|
||||||
|
.GroupValidationBuilder()
|
||||||
|
.AddNotNull(query)
|
||||||
|
.ValidateGroupAsync();
|
||||||
|
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = await mcpServerProvider.Query(
|
||||||
|
query: query,
|
||||||
|
userInfo: userInfo,
|
||||||
|
forceOwner: forceOwner,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok(result.ToDynamicObject());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Refresh MCP Servers ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("Refresh")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledAdmin)]
|
||||||
|
public async Task<ActionResult> RefreshMcpServers(
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
|
||||||
|
//
|
||||||
|
await mcpServerProvider.RefreshAsync(
|
||||||
|
userInfo: userInfo,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return Ok();
|
||||||
|
} catch(Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using xCommons.Configurations;
|
|
||||||
using xCommons.Controllers;
|
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xCommons.Controllers;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using xCommons.Configurations;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
namespace xAiApi.Controllers
|
namespace xAiApi.Controllers
|
||||||
{
|
{
|
||||||
@@ -41,5 +44,20 @@ namespace xAiApi.Controllers
|
|||||||
//
|
//
|
||||||
return Ok(message);
|
return Ok(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Global Exception Handler Endpoint (Production) ...
|
||||||
|
/// Returns a Generic Error without Leaking Exception Details ...
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[AllowAnonymous]
|
||||||
|
[Route("error")]
|
||||||
|
[ApiExplorerSettings(IgnoreApi = true)]
|
||||||
|
public virtual ActionResult Error()
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var error = XException.ActionFailed.ToXError();
|
||||||
|
return StatusCode(StatusCodes.Status500InternalServerError, error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using xCommons.Providers;
|
||||||
|
using xCommons.Configurations;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
|
using xIdentityHelper.Controllers;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace xAiApi.Controllers {
|
||||||
|
/// <summary>
|
||||||
|
/// Test all Authentication Policies ...
|
||||||
|
/// </summary>
|
||||||
|
public class TestIdentity : XTestIdentityControllerBase {
|
||||||
|
public TestIdentity (
|
||||||
|
ILogger<TestIdentity> logger,
|
||||||
|
XAppConfiguration appConfiguration,
|
||||||
|
IXIdentityProvider identityProvider,
|
||||||
|
XValidationProvider validationProvider
|
||||||
|
) : base (
|
||||||
|
logger,
|
||||||
|
appConfiguration,
|
||||||
|
identityProvider,
|
||||||
|
validationProvider
|
||||||
|
) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using xIdentityService.Interfaces;
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
@@ -9,12 +8,11 @@ using Microsoft.AspNetCore.Authorization;
|
|||||||
namespace xAiApi.Controllers
|
namespace xAiApi.Controllers
|
||||||
{
|
{
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("[controller]")]
|
public class XAiController : XAiServiceControllerBase<IXAiService>
|
||||||
public class DefaultAiController : XAiServiceControllerBase<IXDefaultAiService>
|
|
||||||
{
|
{
|
||||||
public DefaultAiController(
|
public XAiController(
|
||||||
ILogger<DefaultAiController> logger,
|
ILogger<XAiController> logger,
|
||||||
IXDefaultAiService aiService,
|
IXAiService aiService,
|
||||||
XAppConfiguration appConfiguration,
|
XAppConfiguration appConfiguration,
|
||||||
IXIdentityProvider identityProvider,
|
IXIdentityProvider identityProvider,
|
||||||
XValidationProvider validationProvider
|
XValidationProvider validationProvider
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading;
|
|
||||||
using xAiApi.Interfaces;
|
|
||||||
using xCommons.Providers;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using xCommons.Configurations;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using xIdentityService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
|
|
||||||
namespace xAiApi.Controllers
|
|
||||||
{
|
|
||||||
[Authorize]
|
|
||||||
[Route("[controller]")]
|
|
||||||
public abstract class XAiEmbeddingServiceControllerBase<TAiService> : XAiServiceControllerBase<TAiService>, IXAiEmbeddingServiceControllerBase
|
|
||||||
where TAiService : IXAiEmbeddingServiceBase
|
|
||||||
{
|
|
||||||
private readonly TAiService aiService;
|
|
||||||
|
|
||||||
protected XAiEmbeddingServiceControllerBase(
|
|
||||||
ILogger logger,
|
|
||||||
TAiService aiService,
|
|
||||||
XAppConfiguration appConfiguration,
|
|
||||||
IXIdentityProvider identityProvider,
|
|
||||||
XValidationProvider validationProvider
|
|
||||||
) : base(
|
|
||||||
logger,
|
|
||||||
aiService,
|
|
||||||
appConfiguration,
|
|
||||||
identityProvider,
|
|
||||||
validationProvider
|
|
||||||
)
|
|
||||||
{
|
|
||||||
this.aiService = aiService;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Request For Embedding Specified String ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="content"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[AllowAnonymous]
|
|
||||||
[HttpGet("Embedding")]
|
|
||||||
public async Task<ActionResult<float[]>> Embedding(
|
|
||||||
[FromQuery] string content,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
try
|
|
||||||
{
|
|
||||||
//
|
|
||||||
// Validate ...
|
|
||||||
ValidationProvider.NotEmpty(content);
|
|
||||||
|
|
||||||
//
|
|
||||||
var result = await aiService.Embedding(
|
|
||||||
content: content,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var result = GetExceptionActionResult(ex);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Request For Embedding Specified Batch ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="batch"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[AllowAnonymous]
|
|
||||||
[HttpGet("Embeddings")]
|
|
||||||
public async Task<ActionResult<IReadOnlyList<float[]>>> Embeddings(
|
|
||||||
[FromQuery] string[] batch,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
try
|
|
||||||
{
|
|
||||||
//
|
|
||||||
// Validate ...
|
|
||||||
ValidationProvider.NotZeroChilds(batch);
|
|
||||||
|
|
||||||
//
|
|
||||||
var result = await aiService.Embeddings(
|
|
||||||
batch: batch,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var result = GetExceptionActionResult(ex);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,15 @@
|
|||||||
using System;
|
using System;
|
||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
|
using xAiApi.Providers;
|
||||||
using xAiApi.Extensions;
|
using xAiApi.Extensions;
|
||||||
|
using xAiApi.Interfaces;
|
||||||
|
using xAiApi.Middlewares;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
|
using xAiApi.Providers.Extractors;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
@@ -67,6 +73,105 @@ namespace xAiApi.DI
|
|||||||
source.AddSingleton(configuration);
|
source.AddSingleton(configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register Rag Service ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXRagService(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Persistent RAG (Knowledge over XAiVector Table) ...
|
||||||
|
source.AddScoped<IXAiEmbeddingService, XAiEmbeddingService>();
|
||||||
|
source.AddScoped<IXAiRAGService, XAiRAGService>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register Ai Services ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXAiServices(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
source.AddScoped<IXAiService, XAiService>();
|
||||||
|
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register AiApi File Content Extractor Services ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXAiFileContentExtractors(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Register File Content Extractors ...
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XPdfFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XRtfFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XEpubFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XDocxFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XHtmlFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XCodeFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XImageFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XAudioFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XExcelFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XVisionFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XPlainTextFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XPowerPointFileContentExtractor>();
|
||||||
|
source.AddSingleton<IXFileContentExtractorBase, XOpenDocumentFileContentExtractor>();
|
||||||
|
|
||||||
|
//
|
||||||
|
source.AddSingleton<IXFileContentExtractor, XFileContentExtractor>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register AiApi Text Chunker Service ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXAiTextChunker(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Stateless -> Singleton ...
|
||||||
|
source.AddSingleton<IXTextChunker, XTextChunker>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register In-Memory Vector Store Service ...
|
||||||
|
/// </summary>
|
||||||
|
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>
|
||||||
|
/// Use Model Proxy Provider ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IApplicationBuilder UseXAiModelProxy(
|
||||||
|
this IApplicationBuilder source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return source.UseMiddleware<XAiModelProxyMiddleware>();
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
#region Private ...
|
#region Private ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using xDataService.Db;
|
||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
using xAiModels.Providers;
|
using xAiModels.Providers;
|
||||||
using xDataService.Configuration;
|
using xTagService.Providers;
|
||||||
using xDataService.Db;
|
|
||||||
using xDataService.Providers;
|
using xDataService.Providers;
|
||||||
using xFileService.Providers;
|
using xFileService.Providers;
|
||||||
using xStringService.Providers;
|
using xStringService.Providers;
|
||||||
using xTagService.Providers;
|
using xDataService.Configuration;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace xAiApi.Database
|
namespace xAiApi.Database
|
||||||
{
|
{
|
||||||
@@ -38,8 +38,10 @@ namespace xAiApi.Database
|
|||||||
nameof(XTagEntityRegisterar),
|
nameof(XTagEntityRegisterar),
|
||||||
nameof(XFileEntityRegisterar),
|
nameof(XFileEntityRegisterar),
|
||||||
nameof(XStringEntityRegisterar),
|
nameof(XStringEntityRegisterar),
|
||||||
|
nameof(XAiVectorEntityRegisterar),
|
||||||
nameof(XAiMessageEntityRegisterar),
|
nameof(XAiMessageEntityRegisterar),
|
||||||
nameof(XAiProjectEntityRegisterar),
|
nameof(XAiProjectEntityRegisterar),
|
||||||
|
nameof(XAiMcpServerEntityRegisterar),
|
||||||
nameof(XAiConversationEntityRegisterar),
|
nameof(XAiConversationEntityRegisterar),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System;
|
|||||||
using OpenAI;
|
using OpenAI;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using OllamaSharp;
|
using OllamaSharp;
|
||||||
|
using xAiApi.Models;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
@@ -36,7 +37,43 @@ namespace xAiApi.Extensions
|
|||||||
source.Prompts.Any(p => p.Name
|
source.Prompts.Any(p => p.Name
|
||||||
.Equals(
|
.Equals(
|
||||||
XAiApiConstants.XAiApiIntroductionPromptName,
|
XAiApiConstants.XAiApiIntroductionPromptName,
|
||||||
System.StringComparison.InvariantCultureIgnoreCase));
|
StringComparison.InvariantCultureIgnoreCase));
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check TextChunker Descriptor is Valid or not ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static bool IsValid(this XTextChunkerDescriptor source)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result =
|
||||||
|
source.ChunkSize > 0 &&
|
||||||
|
source.ChunkOverlap >= 0 &&
|
||||||
|
source.ChunkOverlap < source.ChunkSize &&
|
||||||
|
source.MinChunkSize >= 0 &&
|
||||||
|
source.MinChunkSize <= source.ChunkSize;
|
||||||
|
|
||||||
|
//
|
||||||
|
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();
|
||||||
|
|
||||||
//
|
//
|
||||||
return result;
|
return result;
|
||||||
@@ -249,7 +286,7 @@ namespace xAiApi.Extensions
|
|||||||
//
|
//
|
||||||
// Instance Ollama Client using Custom HttpCLient ...
|
// Instance Ollama Client using Custom HttpCLient ...
|
||||||
var openAiClient = new OpenAIClient(
|
var openAiClient = new OpenAIClient(
|
||||||
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : apiKey),
|
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey),
|
||||||
new OpenAIClientOptions
|
new OpenAIClientOptions
|
||||||
{
|
{
|
||||||
Endpoint = url,
|
Endpoint = url,
|
||||||
@@ -288,5 +325,27 @@ namespace xAiApi.Extensions
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// public static IList<AITool> ToAITools(this IList<XAiMcpToolDefinition> source)
|
||||||
|
// {
|
||||||
|
// //
|
||||||
|
// var result = new List<AITool>();
|
||||||
|
|
||||||
|
// //
|
||||||
|
// foreach (var tool in source)
|
||||||
|
// {
|
||||||
|
// //
|
||||||
|
// var declaration = AIFunctionFactory.CreateDeclaration(
|
||||||
|
// name: tool.Name,
|
||||||
|
// jsonSchema: tool.InputSchema,
|
||||||
|
// description: tool.Description
|
||||||
|
// );
|
||||||
|
|
||||||
|
// //
|
||||||
|
// result.Add(declaration);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// //
|
||||||
|
// return result;
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,31 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using xIdentityHelper;
|
||||||
|
using xAiApi.Providers;
|
||||||
|
using xAiApi.Interfaces;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xCommons.Authorization;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using xCommons.Authorization;
|
|
||||||
using xCommons.Extensions;
|
|
||||||
using xIdentityHelper;
|
|
||||||
|
|
||||||
namespace xAiApi.Extensions
|
namespace xAiApi.Extensions
|
||||||
{
|
{
|
||||||
public static class XProgramExtensions
|
public static class XProgramExtensions
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Register MCP Server Provider ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXAiMcpServerProvider(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
source.AddScoped<IXAiMcpServerProvider, XAiMcpServerProvider>();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Register Authorization Policies
|
/// Register Authorization Policies
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -22,6 +37,7 @@ namespace xAiApi.Extensions
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
|
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
|
||||||
services.AddAuthorization(options =>
|
services.AddAuthorization(options =>
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -35,6 +51,26 @@ namespace xAiApi.Extensions
|
|||||||
{
|
{
|
||||||
var policyDescriptor = policiesEnumerator.Current;
|
var policyDescriptor = policiesEnumerator.Current;
|
||||||
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Add Policy to Policy Handler ...
|
||||||
|
if (!policyHandler.IsNull())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Check Policy is RequiredRole Policy ...
|
||||||
|
var roleRequirements = policyDescriptor.Value.Requirements
|
||||||
|
.OfType<RequiredRolesRequirement>()
|
||||||
|
.FirstOrDefault();
|
||||||
|
if (!roleRequirements.IsNull() &&
|
||||||
|
roleRequirements.Roles.HasChild())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
policyHandler.AddPolicy(
|
||||||
|
policy: policyDescriptor.Key.ToNormalString(),
|
||||||
|
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,8 +85,32 @@ namespace xAiApi.Extensions
|
|||||||
{
|
{
|
||||||
while (policiesEnumerator.MoveNext())
|
while (policiesEnumerator.MoveNext())
|
||||||
{
|
{
|
||||||
|
//
|
||||||
var policyDescriptor = policiesEnumerator.Current;
|
var policyDescriptor = policiesEnumerator.Current;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Add Policy to Authorization ...
|
||||||
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Add Policy to Policy Handler ...
|
||||||
|
if (!policyHandler.IsNull())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Check Policy is RequiredRole Policy ...
|
||||||
|
var roleRequirements = policyDescriptor.Value.Requirements
|
||||||
|
.OfType<RequiredRolesRequirement>()
|
||||||
|
.FirstOrDefault();
|
||||||
|
if (!roleRequirements.IsNull() &&
|
||||||
|
roleRequirements.Roles.HasChild())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
policyHandler.AddPolicy(
|
||||||
|
policy: policyDescriptor.Key.ToNormalString(),
|
||||||
|
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace xAiApi.Interfaces.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for source code files ...
|
||||||
|
/// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...)
|
||||||
|
/// </summary>
|
||||||
|
public interface IXCodeFileContentExtractor : IXFileContentExtractorBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace xAiApi.Interfaces.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for EPUB electronic publication format
|
||||||
|
/// (application/epub+zip)
|
||||||
|
/// </summary>
|
||||||
|
public interface IXEpubFileContentExtractor : IXFileContentExtractorBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace xAiApi.Interfaces.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for HTML documents (text/html, application/xhtml+xml)
|
||||||
|
/// </summary>
|
||||||
|
public interface IXHtmlFileContentExtractor : IXFileContentExtractorBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace xAiApi.Interfaces.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for OpenDocument Format (ODF) documents
|
||||||
|
/// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
|
||||||
|
/// </summary>
|
||||||
|
public interface IXOpenDocumentFileContentExtractor : IXFileContentExtractorBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace xAiApi.Interfaces.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for all PowerPoint Presentation formats
|
||||||
|
/// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot)
|
||||||
|
/// </summary>
|
||||||
|
public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace xAiApi.Interfaces.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for Rich Text Format (RTF) documents
|
||||||
|
/// (application/rtf, text/rtf)
|
||||||
|
/// </summary>
|
||||||
|
public interface IXRtfFileContentExtractor : IXFileContentExtractorBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -1,15 +1,14 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using OllamaSharp;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace xAiApi.Interfaces
|
namespace xAiApi.Interfaces
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Base Embedding Provider Service ...
|
/// Base Embedding Provider Service ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IXAiEmbeddingServiceBase : IXAiServiceBase
|
public interface IXAiEmbeddingServiceBase // : IXAiServiceBase
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Embedding Specified String ...
|
/// Embedding Specified String ...
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace xAiApi.Interfaces
|
|
||||||
{
|
|
||||||
public interface IXAiEmbeddingServiceControllerBase : IXAiServiceControllerBase
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Request For Embedding Specified String ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="content"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Embedding")]
|
|
||||||
Task<ActionResult<float[]>> Embedding(
|
|
||||||
[FromQuery] string content,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Request For Embedding Specified Batch ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="batch"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Embeddings")]
|
|
||||||
Task<ActionResult<IReadOnlyList<float[]>>> Embeddings(
|
|
||||||
[FromQuery] string[] batch,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
using System;
|
||||||
|
using xModels.Dtos;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using xAiModels.Models.Entities;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using ModelContextProtocol.Client;
|
||||||
|
using Microsoft.Extensions.AI;
|
||||||
|
|
||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// MCP Manager / Provider ...
|
||||||
|
/// </summary>
|
||||||
|
public interface IXAiMcpServerProvider
|
||||||
|
{
|
||||||
|
//
|
||||||
|
#region Manager ...
|
||||||
|
/// <summary>
|
||||||
|
/// Get a List Of Available Tools which Provided using registered Mcp Servers ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="forceOwner"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<IList<AITool>> GetAvailableToolsAsync(
|
||||||
|
bool forceOwner = false,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Test Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="server"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<string> TestServerAsync(
|
||||||
|
XAiMcpServerDto server,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Force Refresh Mcp Servers ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task RefreshAsync(
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Actions ...
|
||||||
|
/// <summary>
|
||||||
|
/// Add an Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="item"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiMcpServerDto> AddMcpServer(
|
||||||
|
XAiMcpServerDto item,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get an Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiMcpServerDto> GetMcpServer(
|
||||||
|
Guid id,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Update Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="item"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiMcpServerDto> UpdateMcpServer(
|
||||||
|
Guid id,
|
||||||
|
XAiMcpServerDto item,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Remove Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiMcpServerDto> RemoveMcpServer(
|
||||||
|
Guid id,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Disable Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<bool> DisableMcpServer(
|
||||||
|
Guid id,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enable Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<bool> EnableMcpServer(
|
||||||
|
Guid id,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Toggle Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<bool> ToggleMcpServer(
|
||||||
|
Guid id,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieve all Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="forceOwner"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<IEnumerable<XAiMcpServerDto>> GetAll(
|
||||||
|
bool forceOwner = false,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Find Specified Mcp Server ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="predicate"></param>
|
||||||
|
/// <param name="forceOwner"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiMcpServerDto> FindOne(
|
||||||
|
Expression<Func<XAiMcpServer, bool>> predicate,
|
||||||
|
bool forceOwner = false,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Find a Collection of Specified Mcp Servers ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="predicate"></param>
|
||||||
|
/// <param name="forceOwner"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<IEnumerable<XAiMcpServerDto>> FindMany(
|
||||||
|
Expression<Func<XAiMcpServer, bool>> predicate,
|
||||||
|
bool forceOwner = false,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Query Registered Mcp Servers ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="query"></param>
|
||||||
|
/// <param name="forceOwner"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XQueryResult<XAiMcpServerDto>> Query(
|
||||||
|
XQuery query,
|
||||||
|
bool forceOwner = false,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using xAiApi.Models;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Persistent RAG Service over XAiVector Table:
|
||||||
|
/// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
|
||||||
|
/// Isolation is Scope Based (Conversation / Project / User / Global) ...
|
||||||
|
/// </summary>
|
||||||
|
public interface IXAiRAGService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Ingest Files into Specified Knowledge Scope:
|
||||||
|
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="files"></param>
|
||||||
|
/// <param name="scope">Target Scope (Null = User Scope)</param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="replaceExisting"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiKnowledgeIngestResult> IngestAsync(
|
||||||
|
IFormFileCollection files,
|
||||||
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
string connectionId = null,
|
||||||
|
bool replaceExisting = true,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
||||||
|
XAiKnowledgeAskRequest request,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// List Ingested Documents of Specified Scope ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="scope">Target Scope (Null = User Scope)</param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
||||||
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Remove All Vectors of a Document in Specified Scope ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="scope">Target Scope (Null = User Scope)</param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns>Count of Removed Vectors</returns>
|
||||||
|
Task<int> RemoveDocumentAsync(
|
||||||
|
string fileName,
|
||||||
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
string connectionId = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
|
||||||
|
/// Idempotent: Returns 0 when Nothing Left to Migrate ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns>Count of Migrated Vectors</returns>
|
||||||
|
Task<int> MigrateLegacyVectorsAsync(
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Map Search Results to Public Sources ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
IList<XAiDocumentSource> ToSources(
|
||||||
|
IEnumerable<XAiVectorSearchResult> context
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
public interface IXAiService : IXAiServiceBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
+133
-63
@@ -1,6 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using xModels.Dtos;
|
using xModels.Dtos;
|
||||||
using System.Net.Http;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
using xAiModels.Models.Dtos;
|
using xAiModels.Models.Dtos;
|
||||||
@@ -33,10 +32,12 @@ namespace xAiApi.Interfaces
|
|||||||
/// Base Method for Communicate with LLM ...
|
/// Base Method for Communicate with LLM ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="prompt"></param>
|
/// <param name="prompt"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<string> AskTextAsync(
|
Task<string> AskTextAsync(
|
||||||
string prompt,
|
string prompt,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -44,33 +45,143 @@ namespace xAiApi.Interfaces
|
|||||||
/// Base Method for Communicate with LLM ...
|
/// Base Method for Communicate with LLM ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="prompt"></param>
|
/// <param name="prompt"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
IAsyncEnumerable<string> AskTextAsEnumerable(
|
IAsyncEnumerable<string> AskTextAsEnumerable(
|
||||||
string prompt,
|
string prompt,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Prepare a Message History List for LLM Communication based on Prompt ...
|
/// Ask a Question By Providing Vector Search Result ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="prompt"></param>
|
/// <param name="prompt"></param>
|
||||||
/// <param name="forcePrompt"></param>
|
/// <param name="context"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
IList<ChatMessage> GetHistory(
|
Task<string> AskTextByContextAsync(
|
||||||
string prompt = null,
|
string prompt,
|
||||||
bool forcePrompt = true
|
IList<XAiVectorSearchResult> context = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Prepare a Message History List for LLM Communication based on Prompt ...
|
/// Ask a Question By By Providing Vector Search Result and Stream Response ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="message"></param>
|
/// <param name="prompt"></param>
|
||||||
/// <param name="forceMessage"></param>
|
/// <param name="context"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
IList<ChatMessage> GetHistory(
|
IAsyncEnumerable<string> AskTextByContextAsEnumerable(
|
||||||
ChatMessage message = null,
|
string prompt,
|
||||||
bool forceMessage = true
|
IList<XAiVectorSearchResult> context = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ask a Question By Rag Retrive From Knowledge ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="prompt"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="topK"></param>
|
||||||
|
/// <param name="minScore"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<string> AskTextFromKnowledgeAsync(
|
||||||
|
string prompt,
|
||||||
|
string type = null,
|
||||||
|
int? topK = null,
|
||||||
|
float? minScore = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="prompt"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="topK"></param>
|
||||||
|
/// <param name="minScore"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
IAsyncEnumerable<string> AskTextFromKnowledgeAsEnumerable(
|
||||||
|
string prompt,
|
||||||
|
string type = null,
|
||||||
|
int? topK = null,
|
||||||
|
float? minScore = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ask a Question as Prompt and Retrieve Response ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="prompt"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="topK"></param>
|
||||||
|
/// <param name="minScore"></param>
|
||||||
|
/// <param name="projectId"></param>
|
||||||
|
/// <param name="conversationId"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="extractFileContents"></param>
|
||||||
|
/// <param name="addFilesToKnowledge"></param>
|
||||||
|
/// <param name="files"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<XAiMessageDto> AskAsync(
|
||||||
|
string prompt,
|
||||||
|
string type = null,
|
||||||
|
int? topK = null,
|
||||||
|
float? minScore = null,
|
||||||
|
Guid? projectId = null,
|
||||||
|
Guid? conversationId = null,
|
||||||
|
string connectionId = null,
|
||||||
|
bool extractFileContents = false,
|
||||||
|
bool addFilesToKnowledge = true,
|
||||||
|
IFormFileCollection files = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="prompt"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="topK"></param>
|
||||||
|
/// <param name="minScore"></param>
|
||||||
|
/// <param name="projectId"></param>
|
||||||
|
/// <param name="conversationId"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
/// <param name="extractFileContents"></param>
|
||||||
|
/// <param name="addFilesToKnowledge"></param>
|
||||||
|
/// <param name="files"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
|
||||||
|
string prompt,
|
||||||
|
string type = null,
|
||||||
|
int? topK = null,
|
||||||
|
float? minScore = null,
|
||||||
|
Guid? projectId = null,
|
||||||
|
Guid? conversationId = null,
|
||||||
|
string connectionId = null,
|
||||||
|
bool extractFileContents = false,
|
||||||
|
bool addFilesToKnowledge = true,
|
||||||
|
IFormFileCollection files = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -95,11 +206,13 @@ namespace xAiApi.Interfaces
|
|||||||
/// Load Conversations of Specified AI Project ...
|
/// Load Conversations of Specified AI Project ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="projectId"></param>
|
/// <param name="projectId"></param>
|
||||||
|
/// <param name="ownerId"></param>
|
||||||
/// <param name="connectionId"></param>
|
/// <param name="connectionId"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IEnumerable<XAiConversationDto>> LoadConversations(
|
Task<IEnumerable<XAiConversationDto>> LoadConversations(
|
||||||
Guid projectId,
|
Guid? projectId,
|
||||||
|
string ownerId = null,
|
||||||
string connectionId = null,
|
string connectionId = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
@@ -108,10 +221,14 @@ namespace xAiApi.Interfaces
|
|||||||
/// Load Messages of Specified Conversation ...
|
/// Load Messages of Specified Conversation ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="conversationId"></param>
|
/// <param name="conversationId"></param>
|
||||||
|
/// <param name="ownerId"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IEnumerable<XAiMessageDto>> LoadMessages(
|
Task<IEnumerable<XAiMessageDto>> LoadMessages(
|
||||||
Guid conversationId,
|
Guid? conversationId,
|
||||||
|
string ownerId = null,
|
||||||
|
string connectionId = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
#endregion
|
#endregion
|
||||||
@@ -190,13 +307,13 @@ namespace xAiApi.Interfaces
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<XAiConversationDto> CreateConversation(
|
Task<XAiConversationDto> CreateConversation(
|
||||||
string ownerId,
|
string ownerId,
|
||||||
Guid projectId,
|
Guid? projectId,
|
||||||
XAiConversationDto item,
|
XAiConversationDto item,
|
||||||
string connectionId = null,
|
string connectionId = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//
|
//
|
||||||
#region Content Extraction ...
|
#region Content Extraction ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -209,53 +326,6 @@ namespace xAiApi.Interfaces
|
|||||||
Task<string> ExtractContent(
|
Task<string> ExtractContent(
|
||||||
IFormFileCollection files,
|
IFormFileCollection files,
|
||||||
string[] extractors = null,
|
string[] extractors = null,
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
|
||||||
#region Data Actions ...
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question as Prompt and Retrieve Response ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="prompt"></param>
|
|
||||||
/// <param name="ownerId"></param>
|
|
||||||
/// <param name="projectId"></param>
|
|
||||||
/// <param name="conversationId"></param>
|
|
||||||
/// <param name="connectionId"></param>
|
|
||||||
/// <param name="files"></param>
|
|
||||||
/// <param name="userInfo"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<XAiMessageDto> AskAsync(
|
|
||||||
string prompt,
|
|
||||||
string ownerId,
|
|
||||||
Guid projectId,
|
|
||||||
Guid conversationId,
|
|
||||||
string connectionId = null,
|
|
||||||
IFormFileCollection files = null,
|
|
||||||
XUserClaimsInfoDto userInfo = null,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="prompt"></param>
|
|
||||||
/// <param name="ownerId"></param>
|
|
||||||
/// <param name="projectId"></param>
|
|
||||||
/// <param name="conversationId"></param>
|
|
||||||
/// <param name="connectionId"></param>
|
|
||||||
/// <param name="files"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
|
|
||||||
string prompt,
|
|
||||||
string ownerId,
|
|
||||||
Guid projectId,
|
|
||||||
Guid conversationId,
|
|
||||||
string connectionId = null,
|
|
||||||
IFormFileCollection files = null,
|
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -1,214 +0,0 @@
|
|||||||
using System;
|
|
||||||
using xModels.Dtos;
|
|
||||||
using System.Threading;
|
|
||||||
using xAiModels.Models;
|
|
||||||
using xAiModels.Models.Dtos;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
|
|
||||||
namespace xAiApi.Interfaces
|
|
||||||
{
|
|
||||||
public interface IXAiServiceControllerBase
|
|
||||||
{
|
|
||||||
//
|
|
||||||
#region Actions ...
|
|
||||||
/// <summary>
|
|
||||||
/// Ask Question and Get Response ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="question"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("AskText")]
|
|
||||||
Task<ActionResult<string>> AskText(
|
|
||||||
[FromQuery] string question,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask Question and Get Response Stream ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="question"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("AskTextStream")]
|
|
||||||
Task AskTextStream(
|
|
||||||
[FromQuery] string question,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
|
||||||
#region Loaders ...
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieve AI Projects ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="includeDefaults"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Projects")]
|
|
||||||
Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
|
|
||||||
[FromQuery] bool includeDefaults = false,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieve Specified AI Project's Conversations ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="projectId"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Projects/{projectId}/Conversations")]
|
|
||||||
Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
|
|
||||||
[FromRoute] Guid projectId,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieve Specified AI Conversation's Messages ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="conversationId"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Conversations/{conversationId}/Messages")]
|
|
||||||
Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
|
|
||||||
[FromRoute] Guid conversationId,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
|
||||||
#region Queries ...
|
|
||||||
/// <summary>
|
|
||||||
/// Query Projects ...
|
|
||||||
/// </summary>
|
|
||||||
/// <remarks>
|
|
||||||
/// </remarks>
|
|
||||||
/// <param name="query"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Projects/Query")]
|
|
||||||
Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
|
|
||||||
[FromQuery] XQuery query,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Query Conversations ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="projectId"></param>
|
|
||||||
/// <param name="query"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Projects/{projectId}/Conversations/Query")]
|
|
||||||
Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
|
|
||||||
[FromRoute] Guid projectId,
|
|
||||||
[FromQuery] XQuery query,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Query Messages ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="conversationId"></param>
|
|
||||||
/// <param name="query"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("Conversations/{conversationId}/Messages/Query")]
|
|
||||||
Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
|
|
||||||
[FromRoute] Guid conversationId,
|
|
||||||
[FromQuery] XQuery query,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
|
||||||
#region Creators ...
|
|
||||||
/// <summary>
|
|
||||||
/// Create an AI Project ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="item"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("Projects")]
|
|
||||||
Task<ActionResult<XAiProjectDto>> CreateProject(
|
|
||||||
[FromBody] XAiProjectDto item,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Create an AI Conversation ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="projectId"></param>
|
|
||||||
/// <param name="item"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("Projects/{projectId}/Conversations")]
|
|
||||||
Task<ActionResult<XAiConversationDto>> CreateConversation(
|
|
||||||
[FromRoute] Guid projectId,
|
|
||||||
[FromBody] XAiConversationDto item,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
|
||||||
#region Content Extraction ...
|
|
||||||
/// <summary>
|
|
||||||
/// Extract Files Content ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="files"></param>
|
|
||||||
/// <param name="extractors"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("ExtractContent")]
|
|
||||||
[Consumes("multipart/form-data")]
|
|
||||||
Task<ActionResult<string>> ExtractContent(
|
|
||||||
[FromForm] IFormFileCollection files,
|
|
||||||
[FromForm] string extractors = null,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
|
||||||
#region Data Actions ...
|
|
||||||
/// <summary>
|
|
||||||
/// Ask Question and Get Response ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("Ask")]
|
|
||||||
Task<ActionResult<string>> Ask(
|
|
||||||
[FromBody] XAiResponseRequest request,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask Question and Get Response Stream ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("AskStream")]
|
|
||||||
Task AskStream(
|
|
||||||
[FromBody] XAiResponseRequest request,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask Question with Files and Get Response ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("AskWithFiles")]
|
|
||||||
[Consumes("multipart/form-data")]
|
|
||||||
Task<ActionResult<string>> AskWithFiles(
|
|
||||||
[FromForm] XAiResponseRequest request,
|
|
||||||
[FromForm] IFormFileCollection files,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
#endregion
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
namespace xAiApi.Interfaces
|
|
||||||
{
|
|
||||||
public interface IXDefaultAiService : IXAiServiceBase
|
|
||||||
{ }
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
namespace xAiApi.Interfaces
|
|
||||||
{
|
|
||||||
public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase
|
|
||||||
{ }
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System;
|
||||||
|
using xAiApi.Models;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
public interface IXInMemoryVectorStore
|
||||||
|
{
|
||||||
|
int Count { get; }
|
||||||
|
int RemoveExpired();
|
||||||
|
Guid CreateSession(
|
||||||
|
string ownerId = null,
|
||||||
|
TimeSpan? ttl = null
|
||||||
|
);
|
||||||
|
Guid CreateSession(
|
||||||
|
IEnumerable<XAiVectorDto> vectors,
|
||||||
|
string ownerId = null,
|
||||||
|
TimeSpan? ttl = null
|
||||||
|
);
|
||||||
|
bool Replace(
|
||||||
|
Guid sessionId,
|
||||||
|
IEnumerable<XAiVectorDto> vectors,
|
||||||
|
string ownerId = null
|
||||||
|
);
|
||||||
|
bool Add(
|
||||||
|
Guid sessionId,
|
||||||
|
IEnumerable<XAiVectorDto> vectors,
|
||||||
|
string ownerId = null
|
||||||
|
);
|
||||||
|
IList<XAiVectorSearchResult> Search(
|
||||||
|
Guid sessionId,
|
||||||
|
ReadOnlyMemory<float> queryEmbedding,
|
||||||
|
int topK = 5,
|
||||||
|
float minScore = 0f,
|
||||||
|
string ownerId = null
|
||||||
|
);
|
||||||
|
bool TryGet(
|
||||||
|
Guid sessionId,
|
||||||
|
out XAiDocumentSession session,
|
||||||
|
string ownerId = null
|
||||||
|
);
|
||||||
|
bool Remove(
|
||||||
|
Guid sessionId,
|
||||||
|
string ownerId = null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using xAiApi.Models;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// a Service for Splitting Long Texts into Overlapping Chunks
|
||||||
|
/// which Suitable for Embedding ...
|
||||||
|
/// </summary>
|
||||||
|
public interface IXTextChunker
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Split Text into Chunks ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">Source Text</param>
|
||||||
|
/// <param name="source">Source Name (e.g. File Name) used for Identifier</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
IList<XTextChunk> Chunk(
|
||||||
|
string text,
|
||||||
|
string source = null
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Split Text into Chunks and Return only Texts ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
IList<string> ChunkTexts(
|
||||||
|
string text
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiApi.Extensions;
|
||||||
|
using xCommons.Constants;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xAiModels.Extensions;
|
||||||
|
using xAiApi.Configurations;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Net.Http.Headers;
|
||||||
|
using xIdentityService.Constants;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
|
using xIdentityService.Extensions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
using xIdentityModels.Constants;
|
||||||
|
|
||||||
|
namespace xAiApi.Middlewares
|
||||||
|
{
|
||||||
|
public class XAiModelProxyMiddleware
|
||||||
|
{
|
||||||
|
private readonly RequestDelegate next;
|
||||||
|
private readonly XAiApiConfiguration configuration;
|
||||||
|
private readonly IHttpClientFactory httpClientFactory;
|
||||||
|
private readonly ILogger<XAiModelProxyMiddleware> logger;
|
||||||
|
|
||||||
|
public XAiModelProxyMiddleware(
|
||||||
|
RequestDelegate next,
|
||||||
|
XAiApiConfiguration configuration,
|
||||||
|
IHttpClientFactory httpClientFactory,
|
||||||
|
ILogger<XAiModelProxyMiddleware> logger
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
this.next = next;
|
||||||
|
this.logger = logger;
|
||||||
|
this.configuration = configuration;
|
||||||
|
this.httpClientFactory = httpClientFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handle Routing ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task InvokeAsync(
|
||||||
|
HttpContext context,
|
||||||
|
IXIdentityProvider identityProvider
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate ...
|
||||||
|
var isValid =
|
||||||
|
!configuration.IsNull() &&
|
||||||
|
!configuration.ProxyConfiguration.IsNull() &&
|
||||||
|
configuration.ProxyConfiguration.Enabled &&
|
||||||
|
!configuration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty() &&
|
||||||
|
context.Request.Path.StartsWithSegments(configuration.ProxyConfiguration.RoutePrefix, out var remaining);
|
||||||
|
if (!isValid)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Validating Segment ...
|
||||||
|
var rawSegments = remaining.Value?
|
||||||
|
.Trim('/')
|
||||||
|
.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
if (!rawSegments.HasChild())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Extract Model Name and Retrieve Model Descriptor and do Validation ...
|
||||||
|
var modelName = Uri.UnescapeDataString(rawSegments[0]);
|
||||||
|
var descriptor = configuration.GetModel(modelName);
|
||||||
|
if (!descriptor.IsValid())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Handle Error ...
|
||||||
|
await context.Response.WriteJsonAsync(
|
||||||
|
status: HttpStatusCode.NotFound,
|
||||||
|
data: new
|
||||||
|
{
|
||||||
|
error = $"Model '{modelName}' is not configured."
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var errorMessages = new string[] { };
|
||||||
|
var apiKey = context.ExtractApiKey();
|
||||||
|
var clientIP = context.Request.ExtractClientIP();
|
||||||
|
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
|
||||||
|
var isAuthenticated =
|
||||||
|
//
|
||||||
|
(!apiKey.IsNullOrEmpty()) ||
|
||||||
|
//
|
||||||
|
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
|
||||||
|
;
|
||||||
|
if (isAuthenticated)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Handle Authentication ...
|
||||||
|
if (!apiKey.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Try to Validate Api Key ...
|
||||||
|
var validationResult = await identityProvider.ValidateApiKey(
|
||||||
|
request: new XApiKeyValidationRequest
|
||||||
|
{
|
||||||
|
ApiKey = apiKey,
|
||||||
|
ClientIP = clientIP,
|
||||||
|
RequiredScope = XApiKeyScope.Read.GetStringValue()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
isAuthenticated = !validationResult.Errors.HasChild();
|
||||||
|
if (!isAuthenticated)
|
||||||
|
{
|
||||||
|
errorMessages = [.. errorMessages, .. validationResult.Errors];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!tokenModel.IsNullOrDefault())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Try To Validate Token ...
|
||||||
|
var validationResult = await identityProvider.Validate(tokenModel);
|
||||||
|
isAuthenticated = !validationResult.IsError;
|
||||||
|
if (!isAuthenticated)
|
||||||
|
{
|
||||||
|
errorMessages = [..errorMessages, validationResult.Error];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
isAuthenticated = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isAuthenticated)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var error = XException.NotAuthorized.ToXError();
|
||||||
|
error.Message = $"{error.Message}: {errorMessages.ToListString(',')}";
|
||||||
|
await context.Response.WriteJsonAsync(
|
||||||
|
status: HttpStatusCode.Unauthorized,
|
||||||
|
data: error
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var suffixPath = Uri.UnescapeDataString(string.Join('/', rawSegments.Skip(1)));
|
||||||
|
var targetUri = BuildTargetUri(
|
||||||
|
descriptor.Url,
|
||||||
|
suffixPath,
|
||||||
|
context.Request.QueryString
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Collect Headers which need to Except ...
|
||||||
|
var exceptionHeaders = new string[]
|
||||||
|
{
|
||||||
|
XAuthorization.Header,
|
||||||
|
XAuthorization.ExpiresAt,
|
||||||
|
XAuthorization.XPoweredBy,
|
||||||
|
XAuthorization.AccessToken,
|
||||||
|
XAuthorization.RefreshToken,
|
||||||
|
XHeader.ApiKey.GetStringValue(),
|
||||||
|
XAuthorization.AccessTokenExpired,
|
||||||
|
XHeader.ConnectionId.GetStringValue(),
|
||||||
|
XHeader.ChecksumDigest.GetStringValue(),
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
using var upstreamRequest = new HttpRequestMessage(
|
||||||
|
new HttpMethod(context.Request.Method),
|
||||||
|
targetUri
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
context.CopyRequestHeaders(
|
||||||
|
dest: upstreamRequest,
|
||||||
|
exceptions: exceptionHeaders
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
if (
|
||||||
|
context.Request.ContentLength > 0 ||
|
||||||
|
context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
context.Request.EnableBuffering();
|
||||||
|
using var reader = new StreamReader(
|
||||||
|
context.Request.Body,
|
||||||
|
Encoding.UTF8,
|
||||||
|
detectEncodingFromByteOrderMarks: true,
|
||||||
|
bufferSize: 1024,
|
||||||
|
leaveOpen: true
|
||||||
|
);
|
||||||
|
var bodyText = await reader.ReadToEndAsync();
|
||||||
|
var actualLength = Encoding.UTF8.GetByteCount(bodyText);
|
||||||
|
var declaredLength = context.Request.ContentLength;
|
||||||
|
var contentType = context.Request.ContentType ?? "application/octet-stream";
|
||||||
|
var mediaType = contentType.Split(';')[0].Trim();
|
||||||
|
upstreamRequest.Content = new StringContent(
|
||||||
|
bodyText,
|
||||||
|
Encoding.UTF8,
|
||||||
|
mediaType
|
||||||
|
);
|
||||||
|
context.Request.Body.Position = 0;
|
||||||
|
context.CopyRequestHeaders(
|
||||||
|
dest: upstreamRequest.Content,
|
||||||
|
exceptions: exceptionHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Handle Api Key of LLM ...
|
||||||
|
descriptor.AddModelDescriptorApiKey(
|
||||||
|
request: upstreamRequest
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var client = httpClientFactory.CreateClient("XAiModelProxy");
|
||||||
|
client.Timeout = Timeout.InfiniteTimeSpan;
|
||||||
|
|
||||||
|
//
|
||||||
|
using var upstreamResponse = await client.SendAsync(
|
||||||
|
upstreamRequest,
|
||||||
|
HttpCompletionOption.ResponseHeadersRead,
|
||||||
|
context.RequestAborted
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
context.Response.StatusCode = (int)upstreamResponse.StatusCode;
|
||||||
|
|
||||||
|
//
|
||||||
|
upstreamResponse.CopyHeaders(
|
||||||
|
response: context.Response,
|
||||||
|
exceptions: exceptionHeaders
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
await using var responseStream = await upstreamResponse.Content
|
||||||
|
.ReadAsStreamAsync();
|
||||||
|
await responseStream.CopyToAsync(
|
||||||
|
context.Response.Body,
|
||||||
|
context.RequestAborted
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
||||||
|
{ }
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
logger.LogError(ex, "Proxy failed for model {ModelName}", modelName);
|
||||||
|
if (!context.Response.HasStarted)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Handle Error ...
|
||||||
|
var error = XException.ActionFailed.ToXError();
|
||||||
|
error.Message = $"{error.Message}: {ex.Message}";
|
||||||
|
await context.Response.WriteJsonAsync(
|
||||||
|
status: HttpStatusCode.BadGateway,
|
||||||
|
data: error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Private ...
|
||||||
|
private static Uri BuildTargetUri(
|
||||||
|
string baseUrl,
|
||||||
|
string suffixPath,
|
||||||
|
QueryString query
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var baseUri = new Uri(baseUrl, UriKind.Absolute);
|
||||||
|
var builder = new UriBuilder(baseUri);
|
||||||
|
var basePath = builder.Path.TrimEnd('/');
|
||||||
|
|
||||||
|
//
|
||||||
|
builder.Path = suffixPath.IsNullOrEmpty()
|
||||||
|
? basePath
|
||||||
|
: $"{basePath}/{suffixPath.TrimStart('/')}";
|
||||||
|
|
||||||
|
//
|
||||||
|
builder.Query = query.HasValue
|
||||||
|
? query.Value.TrimStart('?')
|
||||||
|
: string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
return builder.Uri;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
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>
|
||||||
|
/// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ...
|
||||||
|
/// </summary>
|
||||||
|
public string Scope { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Knowledge Type of the Chunk ...
|
||||||
|
/// </summary>
|
||||||
|
public string Type { 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";
|
||||||
|
|
||||||
|
//
|
||||||
|
// Knowledge (Persistent RAG) Limits ...
|
||||||
|
/// <summary>
|
||||||
|
/// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ...
|
||||||
|
/// </summary>
|
||||||
|
public int MaxFilesPerIngest { get; set; } = 20;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Max Size of a Single File in Bytes (0 = Unlimited) ...
|
||||||
|
/// </summary>
|
||||||
|
public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ...
|
||||||
|
/// </summary>
|
||||||
|
public int MaxDocumentsPerScope { get; set; } = 50;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
public class XAiDocumentSession
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public TimeSpan Ttl { get; set; }
|
||||||
|
public string OwnerId { get; set; }
|
||||||
|
public DateTime CreatedAtUtc { get; set; }
|
||||||
|
public DateTime LastAccessAtUtc { get; set; }
|
||||||
|
internal object SyncRoot { get; } = new object();
|
||||||
|
public IList<XAiVectorDto> Vectors { get; set; } = new List<XAiVectorDto>();
|
||||||
|
public bool IsExpired(DateTime utcNow) { return utcNow - LastAccessAtUtc >= Ttl; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
using System;
|
||||||
|
using xAiModels.Constants;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Describes Target Knowledge Base Scope of an Operation ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiKnowledgeScopeDescriptor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Scope Kind ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ...
|
||||||
|
/// </summary>
|
||||||
|
public Guid? ScopeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional Knowledge Type / Domain Filter ...
|
||||||
|
/// </summary>
|
||||||
|
public string Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Create User Scope Knowledge Descriptor ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static XAiKnowledgeScopeDescriptor User(
|
||||||
|
string type = null
|
||||||
|
) => new()
|
||||||
|
{
|
||||||
|
//
|
||||||
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
|
ScopeId = null,
|
||||||
|
Scope = XAiKnowledgeScope.User,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Create Global Scope Knowledge Descriptor ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static XAiKnowledgeScopeDescriptor Global(
|
||||||
|
string type = null
|
||||||
|
) => new()
|
||||||
|
{
|
||||||
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
|
ScopeId = null,
|
||||||
|
Scope = XAiKnowledgeScope.Global,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Create Project Scope Knowledge Descriptor ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="projectId"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static XAiKnowledgeScopeDescriptor Project(
|
||||||
|
Guid projectId,
|
||||||
|
string type = null
|
||||||
|
) => new()
|
||||||
|
{
|
||||||
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
|
ScopeId = projectId,
|
||||||
|
Scope = XAiKnowledgeScope.Project,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Create Conversational Scope Knowledge Descriptor ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="conversationId"></param>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static XAiKnowledgeScopeDescriptor Conversation(
|
||||||
|
Guid conversationId,
|
||||||
|
string type = null
|
||||||
|
) => new()
|
||||||
|
{
|
||||||
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
|
ScopeId = conversationId,
|
||||||
|
Scope = XAiKnowledgeScope.Conversation,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiKnowledgeIngestResult
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Target Scope ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiKnowledgeScope Scope { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Target Scope Identifier (Null for Global) ...
|
||||||
|
/// </summary>
|
||||||
|
public Guid? ScopeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Knowledge Type of Ingested Vectors ...
|
||||||
|
/// </summary>
|
||||||
|
public string Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Count of Successfully Ingested Files ...
|
||||||
|
/// </summary>
|
||||||
|
public int FilesCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Count of Stored Chunks (Vectors) in this Request ...
|
||||||
|
/// </summary>
|
||||||
|
public int ChunksCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Count of Removed Stale Vectors (Re-Ingest) ...
|
||||||
|
/// </summary>
|
||||||
|
public int ReplacedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Skipped Files (Empty, Unsupported or Extraction Failed) ...
|
||||||
|
/// </summary>
|
||||||
|
public IList<string> SkippedFiles { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ingested Documents Info ...
|
||||||
|
/// </summary>
|
||||||
|
public IList<XAiKnowledgeDocumentInfo> Documents { get; set; } = new List<XAiKnowledgeDocumentInfo>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ask Request over Persistent Knowledge Base ...
|
||||||
|
/// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiKnowledgeAskRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Question ...
|
||||||
|
/// </summary>
|
||||||
|
public string Prompt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional: Conversation Scope (Caller must be Conversation Owner) ...
|
||||||
|
/// When Provided, Conversation's Project is used for Second Tier Automatically ...
|
||||||
|
/// </summary>
|
||||||
|
public Guid? ConversationId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional: Project Scope (Caller must be Project Owner) ...
|
||||||
|
/// </summary>
|
||||||
|
public Guid? ProjectId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Include Personal (User) Knowledge Tier (default true) ...
|
||||||
|
/// </summary>
|
||||||
|
public bool IncludeUser { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Include Global Knowledge Tier (default true) ...
|
||||||
|
/// </summary>
|
||||||
|
public bool IncludeGlobal { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
|
||||||
|
/// </summary>
|
||||||
|
public string Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional: Restrict Retrieval to a Specific File Name ...
|
||||||
|
/// </summary>
|
||||||
|
public string FileName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional: Max Retrieved Chunks ...
|
||||||
|
/// </summary>
|
||||||
|
public int? TopK { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional: Minimum Cosine Similarity Score ...
|
||||||
|
/// </summary>
|
||||||
|
public float? MinScore { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ingested Document Info ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiKnowledgeDocumentInfo
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Scope ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiKnowledgeScope Scope { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scope Identifier (Null for Global) ...
|
||||||
|
/// </summary>
|
||||||
|
public Guid? ScopeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Knowledge Type ...
|
||||||
|
/// </summary>
|
||||||
|
public string Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// File Name ...
|
||||||
|
/// </summary>
|
||||||
|
public string FileName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Mime Type ...
|
||||||
|
/// </summary>
|
||||||
|
public string MimeType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ingesting User Identifier ...
|
||||||
|
/// </summary>
|
||||||
|
public string OwnerId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Count of Stored Chunks ...
|
||||||
|
/// </summary>
|
||||||
|
public int ChunksCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ingestion Time (UTC) ...
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? IngestedAtUtc { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Public Vector Info (Export) ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiKnowledgeVectorInfo
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public string Text { get; set; }
|
||||||
|
public string Type { get; set; }
|
||||||
|
public Guid? ScopeId { get; set; }
|
||||||
|
public string FileName { get; set; }
|
||||||
|
public int? ChunkIndex { get; set; }
|
||||||
|
public string Identifier { get; set; }
|
||||||
|
public XAiKnowledgeScope Scope { get; set; }
|
||||||
|
public Dictionary<string, string> Metadata { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Embedding (Only Filled when Requested) ...
|
||||||
|
/// </summary>
|
||||||
|
public float[] Embedding { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Describe an Mcp Server for Seeding ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiMcpServerDescriptor
|
||||||
|
{
|
||||||
|
public string Name { get; set; }
|
||||||
|
public string OwnerId { get; set; }
|
||||||
|
public string Headers { get; set; }
|
||||||
|
public string Endpoint { get; set; }
|
||||||
|
public string Description { get; set; }
|
||||||
|
public bool Enabled { get; set; } = true;
|
||||||
|
public int TimeoutSeconds { get; set; } = 30;
|
||||||
|
public string EnvironmentVariables { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
public class XAiModelProxyConfiguration
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Enable Proxy or not ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
public bool Enabled { get; set; } = false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Proxy Prefix ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
public string RoutePrefix { get; set; } = "ai-model";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
public class XDateTimeDescriptor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Adding Current DateTime to Prompt ...
|
||||||
|
/// </summary>
|
||||||
|
public bool InjectIntoSystemPrompt { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Time Zone ...
|
||||||
|
/// </summary>
|
||||||
|
public string DefaultTimezone { get; set; } = "Asia/Tehran";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Georgian Date Format ...
|
||||||
|
/// </summary>
|
||||||
|
public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Include Persian Calendar ...
|
||||||
|
/// </summary>
|
||||||
|
public bool IncludePersianCalendar { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Include Day of Week ...
|
||||||
|
/// </summary>
|
||||||
|
public bool IncludeDayOfWeek { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Include Unix Timestamp ...
|
||||||
|
/// </summary>
|
||||||
|
public bool IncludeUnixTimestamp { get; set; } = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
public class XPDFToImageDescriptor
|
||||||
|
{
|
||||||
|
public int Dpi { get; set; } = 300;
|
||||||
|
public int Width { get; set; } = 0;
|
||||||
|
public int Height { get; set; } = 0;
|
||||||
|
public bool UseTiling { get; set; } = false;
|
||||||
|
public bool WithFormFill { get; set; } = false;
|
||||||
|
public bool WithAspectRatio { get; set; } = false;
|
||||||
|
public bool WithAnnotations { get; set; } = false;
|
||||||
|
public bool DpiRelativeToBounds { get; set; } = false;
|
||||||
|
|
||||||
|
public int MaxImageWidth { get; set; } = 2000;
|
||||||
|
public int MinTextLengthThreshold { get; set; } = 50;
|
||||||
|
public int MaxPagesForImageFallback { get; set; } = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using Microsoft.Extensions.AI;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// a Shared Context Between Actions for Generation ...
|
||||||
|
/// </summary>
|
||||||
|
public class XPreparedChatContext
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Specified Related Project, if Exists ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiProjectDto Project { get; set; } = null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Specified Related Conversation, if Exists ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiConversationDto Conversation { get; set; } = null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Specified Message History, if Exists ...
|
||||||
|
/// </summary>
|
||||||
|
public IList<ChatMessage> History { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Specified Vector Search Conext, if Exists ...
|
||||||
|
/// </summary>
|
||||||
|
public IList<XAiVectorSearchResult> Context { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Specified Persisted Prompt, if Exists ...
|
||||||
|
/// </summary>
|
||||||
|
public XAiMessageDto PersistedPromptMessage { get; set; } = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Represents a Chunk of a Text which Produced by Text Chunker ...
|
||||||
|
/// </summary>
|
||||||
|
public class XTextChunk
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Zero Based Index of Chunk in Source Text ...
|
||||||
|
/// </summary>
|
||||||
|
public int Index { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Chunk Text Content ...
|
||||||
|
/// </summary>
|
||||||
|
public string Text { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Source Name (e.g. File Name) which Chunk Extracted From ...
|
||||||
|
/// </summary>
|
||||||
|
public string Source { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
|
||||||
|
/// </summary>
|
||||||
|
public string Identifier { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Start Offset of Chunk in Normalized Source Text ...
|
||||||
|
/// </summary>
|
||||||
|
public int StartOffset { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Length of Chunk Text ...
|
||||||
|
/// </summary>
|
||||||
|
public int Length => Text?.Length ?? 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
namespace xAiApi.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Text Chunker Descriptor ...
|
||||||
|
/// </summary>
|
||||||
|
public class XTextChunkerDescriptor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Maximum Characters Count of each Chunk ...
|
||||||
|
/// </summary>
|
||||||
|
public int ChunkSize { get; set; } = 800;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Characters Count which Shared between two Consecutive Chunks ...
|
||||||
|
/// </summary>
|
||||||
|
public int ChunkOverlap { get; set; } = 150;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Chunks Smaller than this Size will be Merged into Previous Chunk ...
|
||||||
|
/// </summary>
|
||||||
|
public int MinChunkSize { get; set; } = 50;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Chunck Identifier Separator ...
|
||||||
|
/// </summary>
|
||||||
|
public string ChunkIdentifierSeparator { get; set; } = "#";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Normalize Line Endings and Repeated Whitespaces before Chunking ...
|
||||||
|
/// </summary>
|
||||||
|
public bool NormalizeWhitespace { get; set; } = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-3
@@ -1,3 +1,5 @@
|
|||||||
|
using System.Text;
|
||||||
|
using xLoggingService.DI;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
@@ -7,14 +9,27 @@ namespace xAiApi
|
|||||||
{
|
{
|
||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
|
//
|
||||||
|
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||||
|
|
||||||
|
//
|
||||||
CreateHostBuilder(args).Build().Run();
|
CreateHostBuilder(args).Build().Run();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
public static IHostBuilder CreateHostBuilder(string[] args)
|
||||||
Host.CreateDefaultBuilder(args)
|
{
|
||||||
|
//
|
||||||
|
var result = Host.CreateDefaultBuilder(args)
|
||||||
|
.ConfigureLogging(logging =>
|
||||||
|
logging.AddXTelemetryLogger())
|
||||||
.ConfigureWebHostDefaults(webBuilder =>
|
.ConfigureWebHostDefaults(webBuilder =>
|
||||||
{
|
{
|
||||||
webBuilder.UseStartup<Startup>();
|
webBuilder.UseStartup<Startup>();
|
||||||
});
|
})
|
||||||
|
.AddXTelemetry();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
"commandName": "Project",
|
"commandName": "Project",
|
||||||
"launchBrowser": true,
|
"launchBrowser": true,
|
||||||
"launchUrl": "weatherforecast",
|
"launchUrl": "weatherforecast",
|
||||||
"applicationUrl": "https://localhost:6001;http://localhost:6000",
|
"applicationUrl": "https://localhost:6001;http://localhost:6000;https://0.0.0.0:6001;",
|
||||||
"environmentVariables": {
|
"environmentVariables": {
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using FFMpegCore;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Whisper.net;
|
using Whisper.net;
|
||||||
using NAudio.Wave;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using NAudio.MediaFoundation;
|
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
namespace xAiApi.Providers.Extractors
|
namespace xAiApi.Providers.Extractors
|
||||||
@@ -161,173 +160,76 @@ namespace xAiApi.Providers.Extractors
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var result = await Task.Run(() =>
|
var tempInput = Path.Combine(
|
||||||
|
Path.GetTempPath(),
|
||||||
|
$"audio_in_{Guid.NewGuid()}{GetExtensionFromMime(mimeType)}"
|
||||||
|
);
|
||||||
|
var tempOutput = Path.Combine(
|
||||||
|
Path.GetTempPath(),
|
||||||
|
$"audio_out_{Guid.NewGuid()}.wav"
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
MemoryStream result = null;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var memoryStream = new MemoryStream();
|
using var fs = File.Create(tempInput);
|
||||||
inputStream.CopyTo(memoryStream);
|
await inputStream.CopyToAsync(fs, cancellationToken);
|
||||||
memoryStream.Position = 0;
|
await FFMpegArguments
|
||||||
|
.FromFileInput(tempInput)
|
||||||
|
.OutputToFile(tempOutput, overwrite: true, options => options
|
||||||
|
.WithAudioCodec("pcm_s16le")
|
||||||
|
.WithCustomArgument("-ar 16000")
|
||||||
|
.WithCustomArgument("-ac 1")
|
||||||
|
.ForceFormat("wav"))
|
||||||
|
.ProcessAsynchronously();
|
||||||
|
|
||||||
//
|
//
|
||||||
var targetFormat = new WaveFormat(16000, 16, 1);
|
result = new();
|
||||||
string tempFilePath = null;
|
using var fsTmp = File.OpenRead(tempOutput);
|
||||||
|
await fsTmp.CopyToAsync(result, cancellationToken);
|
||||||
|
result.Position = 0;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
result = null;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
//
|
//
|
||||||
try
|
// Remove Temparory Files ...
|
||||||
{
|
if (File.Exists(tempInput)) File.Delete(tempInput);
|
||||||
//
|
if (File.Exists(tempOutput)) File.Delete(tempOutput);
|
||||||
WaveStream reader = GetAudioReader(memoryStream, mimeType, ref tempFilePath);
|
}
|
||||||
if (reader == null)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
XException.NotAllowed.Throw(
|
|
||||||
$"Unsupported audio format: {mimeType}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
//
|
||||||
var needsConversion =
|
if (result.IsNull())
|
||||||
reader.WaveFormat.SampleRate != 16000 ||
|
{
|
||||||
reader.WaveFormat.Channels != 1 ||
|
XException.ActionFailed.Throw();
|
||||||
reader.WaveFormat.BitsPerSample != 16 ||
|
}
|
||||||
reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm;
|
|
||||||
var outputStream = new MemoryStream();
|
|
||||||
if (!needsConversion)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
reader.CopyTo(outputStream);
|
|
||||||
reader.Dispose();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
//
|
|
||||||
MediaFoundationApi.Startup();
|
|
||||||
using var resampler = new MediaFoundationResampler(
|
|
||||||
reader,
|
|
||||||
targetFormat
|
|
||||||
);
|
|
||||||
resampler.ResamplerQuality = 60;
|
|
||||||
|
|
||||||
//
|
|
||||||
WaveFileWriter.WriteWavFileToStream(outputStream, resampler);
|
|
||||||
reader.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
outputStream.Position = 0;
|
|
||||||
return outputStream;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
//
|
|
||||||
if (!string.IsNullOrEmpty(tempFilePath) &&
|
|
||||||
File.Exists(tempFilePath))
|
|
||||||
{
|
|
||||||
//
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.Delete(tempFilePath);
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
memoryStream.Dispose();
|
|
||||||
}
|
|
||||||
}, cancellationToken);
|
|
||||||
|
|
||||||
//
|
//
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get appropriate WaveStream reader based on MIME type ...
|
/// Retrieve File Extension based on mime type ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="stream">Input stream (MemoryStream)</param>
|
/// <param name="mimeType"></param>
|
||||||
/// <param name="mimeType">MIME type of audio file</param>
|
/// <returns></returns>
|
||||||
/// <param name="tempFilePath">Path to temp file (if created)</param>
|
private string GetExtensionFromMime(string mimeType)
|
||||||
/// <returns>WaveStream reader or null if unsupported</returns>
|
|
||||||
private WaveStream GetAudioReader(
|
|
||||||
MemoryStream stream,
|
|
||||||
string mimeType,
|
|
||||||
ref string tempFilePath
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
try
|
return mimeType?.ToLowerInvariant() switch
|
||||||
{
|
{
|
||||||
//
|
"audio/mpeg" or "audio/mp3" => ".mp3",
|
||||||
var normalizedMime = mimeType?.ToLowerInvariant() ?? string.Empty;
|
"audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
|
||||||
switch (normalizedMime)
|
"audio/ogg" => ".ogg",
|
||||||
{
|
"audio/webm" => ".webm",
|
||||||
//
|
"audio/wav" or "audio/wave" or "audio/x-wav" => ".wav",
|
||||||
case "audio/wav":
|
_ => ".tmp"
|
||||||
case "audio/wave":
|
};
|
||||||
case "audio/x-wav":
|
|
||||||
return new WaveFileReader(stream);
|
|
||||||
|
|
||||||
//
|
|
||||||
case "audio/mpeg":
|
|
||||||
case "audio/mp3":
|
|
||||||
return new Mp3FileReader(stream);
|
|
||||||
|
|
||||||
//
|
|
||||||
case "audio/m4a":
|
|
||||||
case "audio/mp4":
|
|
||||||
case "audio/aac":
|
|
||||||
case "audio/ogg":
|
|
||||||
case "audio/webm":
|
|
||||||
case "audio/x-m4a":
|
|
||||||
//
|
|
||||||
var extension = normalizedMime switch
|
|
||||||
{
|
|
||||||
"audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
|
|
||||||
"audio/ogg" => ".ogg",
|
|
||||||
"audio/webm" => ".webm",
|
|
||||||
_ => ".tmp"
|
|
||||||
};
|
|
||||||
tempFilePath = Path.Combine(
|
|
||||||
Path.GetTempPath(),
|
|
||||||
$"audio_{Guid.NewGuid()}{extension}"
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
stream.Position = 0;
|
|
||||||
using (var fileStream = File.Create(tempFilePath))
|
|
||||||
{
|
|
||||||
stream.CopyTo(fileStream);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
MediaFoundationApi.Startup();
|
|
||||||
return new MediaFoundationReader(tempFilePath);
|
|
||||||
|
|
||||||
default:
|
|
||||||
//
|
|
||||||
tempFilePath = Path.Combine(
|
|
||||||
Path.GetTempPath(),
|
|
||||||
$"audio_{Guid.NewGuid()}.tmp"
|
|
||||||
);
|
|
||||||
stream.Position = 0;
|
|
||||||
using (var fileStream = File.Create(tempFilePath))
|
|
||||||
{
|
|
||||||
stream.CopyTo(fileStream);
|
|
||||||
}
|
|
||||||
try
|
|
||||||
{
|
|
||||||
MediaFoundationApi.Startup();
|
|
||||||
return new MediaFoundationReader(tempFilePath);
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for source code files ...
|
||||||
|
/// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...)
|
||||||
|
/// </summary>
|
||||||
|
public class XCodeFileContentExtractor : IXCodeFileContentExtractor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported MIME Types ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] SupportedMimeTypes =
|
||||||
|
[
|
||||||
|
"text/x-c",
|
||||||
|
"text/x-go",
|
||||||
|
"text/yaml",
|
||||||
|
"text/x-php",
|
||||||
|
"text/x-c++",
|
||||||
|
"text/x-sql",
|
||||||
|
"text/x-java",
|
||||||
|
"text/x-rust",
|
||||||
|
"text/x-ruby",
|
||||||
|
"text/x-csharp",
|
||||||
|
"text/x-python",
|
||||||
|
"text/javascript",
|
||||||
|
"text/typescript",
|
||||||
|
"text/x-java-source",
|
||||||
|
"application/x-yaml",
|
||||||
|
"application/x-csharp",
|
||||||
|
"application/x-python",
|
||||||
|
"application/javascript",
|
||||||
|
"application/typescript",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool CanExtract(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return SupportedMimeTypes.Contains(
|
||||||
|
mimeType?.ToLowerInvariant() ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract text content from file stream ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<string> ExtractAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await ExtractRichAsync(
|
||||||
|
fileStream,
|
||||||
|
string.Empty,
|
||||||
|
mimeType,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract content from stream as Rich Result ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XFileExtractionResult> ExtractRichAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new XFileExtractionResult
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
MimeType = mimeType
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
// Read entire source code as UTF-8 (with BOM detection) ...
|
||||||
|
using var reader = new StreamReader(
|
||||||
|
fileStream,
|
||||||
|
Encoding.UTF8,
|
||||||
|
leaveOpen: false,
|
||||||
|
detectEncodingFromByteOrderMarks: true
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
var content = await reader.ReadToEndAsync();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Normalize line endings for consistent downstream processing ...
|
||||||
|
content = content?
|
||||||
|
.Replace("\r\n", "\n")
|
||||||
|
.Replace("\r", "\n");
|
||||||
|
|
||||||
|
//
|
||||||
|
result.Text = content;
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using VersOne.Epub;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for EPUB electronic publication format
|
||||||
|
/// (application/epub+zip)
|
||||||
|
/// </summary>
|
||||||
|
public class XEpubFileContentExtractor : IXEpubFileContentExtractor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported MIME Types ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] SupportedMimeTypes =
|
||||||
|
[
|
||||||
|
"application/epub+zip"
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool CanExtract(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return SupportedMimeTypes.Contains(
|
||||||
|
mimeType?.ToLowerInvariant() ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract text content from file stream ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<string> ExtractAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await ExtractRichAsync(
|
||||||
|
fileStream,
|
||||||
|
"book.epub",
|
||||||
|
mimeType,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract content from stream as Rich Result ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XFileExtractionResult> ExtractRichAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new XFileExtractionResult
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
MimeType = mimeType
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Text = await ExtractEpubAsync(
|
||||||
|
fileStream,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"EPUB extraction failed: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Epub Content ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractEpubAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Copy to MemoryStream (VersOne.Epub requires seekable stream) ...
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await fileStream.CopyToAsync(ms, cancellationToken);
|
||||||
|
ms.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Load EPUB book ...
|
||||||
|
EpubBook book = await EpubReader.ReadBookAsync(ms);
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Extract metadata ...
|
||||||
|
|
||||||
|
//
|
||||||
|
if (!book.Title.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
sb.AppendLine($"Title: {book.Title}");
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (!book.Author.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
sb.AppendLine($"Author: {book.Author}");
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Extract chapters in reading order ...
|
||||||
|
var chapterIndex = 0;
|
||||||
|
foreach (var textContentFile in book.ReadingOrder)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
chapterIndex++;
|
||||||
|
sb.AppendLine($"[Chapter {chapterIndex}]");
|
||||||
|
var plainText = ExtractTextFromHtml(
|
||||||
|
textContentFile.Content
|
||||||
|
);
|
||||||
|
if (!plainText.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
sb.AppendLine(plainText);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Text Content from HTML ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="html"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string ExtractTextFromHtml(string html)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (html.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var htmlDocument = new HtmlDocument();
|
||||||
|
htmlDocument.LoadHtml(html);
|
||||||
|
|
||||||
|
//
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
var textNodes = htmlDocument.DocumentNode
|
||||||
|
.SelectNodes("//text()");
|
||||||
|
|
||||||
|
//
|
||||||
|
if (textNodes == null)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
foreach (var node in textNodes)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var text = node.InnerText?.Trim();
|
||||||
|
if (!text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
sb.AppendLine(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for HTML documents (text/html, application/xhtml+xml)
|
||||||
|
/// </summary>
|
||||||
|
public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported MIME Types ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] SupportedMimeTypes =
|
||||||
|
[
|
||||||
|
"text/html",
|
||||||
|
"application/xhtml+xml"
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool CanExtract(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return SupportedMimeTypes.Contains(
|
||||||
|
mimeType?.ToLowerInvariant() ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract text content from file stream ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<string> ExtractAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await ExtractRichAsync(
|
||||||
|
fileStream,
|
||||||
|
"document.html",
|
||||||
|
mimeType,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract content from stream as Rich Result ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XFileExtractionResult> ExtractRichAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new XFileExtractionResult
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
MimeType = mimeType
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Text = await ExtractHtmlAsync(
|
||||||
|
fileStream,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"HTML extraction failed: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Html Content as Text ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractHtmlAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
// Load HTML into HtmlDocument
|
||||||
|
var html = new HtmlDocument();
|
||||||
|
html.Load(fileStream);
|
||||||
|
|
||||||
|
// Remove noise nodes (script, style, etc.)
|
||||||
|
RemoveNoiseNodes(html);
|
||||||
|
|
||||||
|
// Extract title
|
||||||
|
var title = ExtractTitle(html);
|
||||||
|
|
||||||
|
// Extract body text
|
||||||
|
var body = html.DocumentNode
|
||||||
|
.SelectSingleNode("//body");
|
||||||
|
var bodyText = body?.InnerText ?? string.Empty;
|
||||||
|
|
||||||
|
// Clean and normalize text
|
||||||
|
var cleanedText = CleanText(bodyText);
|
||||||
|
|
||||||
|
// Build structured output
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
if (!string.IsNullOrWhiteSpace(title))
|
||||||
|
{
|
||||||
|
sb.AppendLine($"Title: {title}");
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
sb.AppendLine(cleanedText);
|
||||||
|
|
||||||
|
return sb.ToString().TrimEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Remove Noisy Nodes ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="html"></param>
|
||||||
|
private void RemoveNoiseNodes(HtmlDocument html)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Remove script and style tags ...
|
||||||
|
var noiseTags = new[] { "script", "style", "noscript", "iframe" };
|
||||||
|
foreach (var tag in noiseTags)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var nodes = html.DocumentNode
|
||||||
|
.Descendants(tag)
|
||||||
|
.ToList();
|
||||||
|
foreach (var node in nodes)
|
||||||
|
{
|
||||||
|
node.Remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Title ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="html"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string ExtractTitle(HtmlDocument html)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var titleNode = html.DocumentNode
|
||||||
|
.SelectSingleNode("//title");
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = titleNode?.InnerText?.Trim() ?? string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Clean Text ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string CleanText(string text)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
result = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Decode HTML entities ...
|
||||||
|
text = System.Net.WebUtility.HtmlDecode(text);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Normalize whitespace ...
|
||||||
|
text = System.Text.RegularExpressions.Regex
|
||||||
|
.Replace(text, @"\s+", " ")
|
||||||
|
.Trim();
|
||||||
|
|
||||||
|
//
|
||||||
|
result = text;
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using OfficeIMO.OpenDocument;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for OpenDocument Format (ODF) documents
|
||||||
|
/// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
|
||||||
|
/// </summary>
|
||||||
|
public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported MIME Types ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] SupportedMimeTypes =
|
||||||
|
[
|
||||||
|
"application/vnd.oasis.opendocument.text", // .odt
|
||||||
|
"application/vnd.oasis.opendocument.spreadsheet", // .ods
|
||||||
|
"application/vnd.oasis.opendocument.presentation" // .odp
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool CanExtract(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return SupportedMimeTypes.Contains(
|
||||||
|
mimeType?.ToLowerInvariant() ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract text content from file stream ...
|
||||||
|
/// </summary>
|
||||||
|
public async Task<string> ExtractAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await ExtractRichAsync(
|
||||||
|
fileStream,
|
||||||
|
"document.rtf",
|
||||||
|
mimeType,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract content from stream as Rich Result ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XFileExtractionResult> ExtractRichAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new XFileExtractionResult
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
MimeType = mimeType
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (IsOdt(mimeType))
|
||||||
|
{
|
||||||
|
result.Text = await ExtractOdtAsync(fileStream, cancellationToken);
|
||||||
|
}
|
||||||
|
else if (IsOds(mimeType))
|
||||||
|
{
|
||||||
|
result.Text = await ExtractOdsAsync(fileStream, cancellationToken);
|
||||||
|
}
|
||||||
|
else if (IsOdp(mimeType))
|
||||||
|
{
|
||||||
|
result.Text = await ExtractOdpAsync(fileStream, cancellationToken);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"Unsupported OpenDocument MIME type: {mimeType}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"RTF extraction failed: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check Mime Type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private bool IsOdt(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = mimeType?
|
||||||
|
.ToLowerInvariant() == "application/vnd.oasis.opendocument.text";
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check Mime Type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private bool IsOds(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = mimeType?
|
||||||
|
.ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet";
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check Mime Type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private bool IsOdp(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = mimeType?
|
||||||
|
.ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation";
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract ODT File Content ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractOdtAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await fileStream.CopyToAsync(ms, cancellationToken);
|
||||||
|
ms.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
var document = OdtDocument.Load(ms);
|
||||||
|
|
||||||
|
//
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
foreach (var paragraph in document.Paragraphs)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (!paragraph.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
sb.AppendLine(paragraph.Text.Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// 4. استخراج جداول
|
||||||
|
var tableIndex = 0;
|
||||||
|
foreach (var table in document.Tables)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
tableIndex++;
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine($"[Table {tableIndex}]");
|
||||||
|
|
||||||
|
//
|
||||||
|
foreach (var row in table.Rows)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var cellTexts = new List<string>();
|
||||||
|
foreach (var cell in row.Cells)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var cellText = string.Join(
|
||||||
|
" ",
|
||||||
|
cell.Paragraphs
|
||||||
|
.Select(p => p.Text?.Trim())
|
||||||
|
.Where(t => !string.IsNullOrWhiteSpace(t))
|
||||||
|
);
|
||||||
|
cellTexts.Add(cellText);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine($" | {string.Join(" | ", cellTexts)} |");
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract ODS File Content ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractOdsAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await fileStream.CopyToAsync(ms, cancellationToken);
|
||||||
|
ms.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
var document = OdsDocument.Load(ms);
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
var sheetIndex = 0;
|
||||||
|
foreach (var sheet in document.Sheets)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sheetIndex++;
|
||||||
|
sb.AppendLine($"--- Sheet: {sheet.Name} ---");
|
||||||
|
|
||||||
|
//
|
||||||
|
for (long row = 0; row < sheet.RowCount; row++)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var cellValues = new List<string>();
|
||||||
|
var columnCount = sheet.ColumnRuns.Sum(r => r.RepeatCount);
|
||||||
|
for (long col = 0; col < columnCount; col++)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var value = sheet.GetValue(row, col);
|
||||||
|
if (!value.IsNull())
|
||||||
|
{
|
||||||
|
var text = value.LexicalValue?.Trim() ?? string.Empty;
|
||||||
|
cellValues.Add(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (cellValues.Any(v => !string.IsNullOrWhiteSpace(v)))
|
||||||
|
{
|
||||||
|
sb.AppendLine(string.Join(" | ", cellValues));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract ODS File Content ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractOdpAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await fileStream.CopyToAsync(ms, cancellationToken);
|
||||||
|
ms.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
var presentation = OdpPresentation.Load(ms);
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
var slideIndex = 0;
|
||||||
|
foreach (var slide in presentation.Slides)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
slideIndex++;
|
||||||
|
sb.AppendLine($"[Slide {slideIndex}]");
|
||||||
|
var textParts = new List<string>();
|
||||||
|
|
||||||
|
//
|
||||||
|
foreach (var shape in slide.Shapes)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (shape is OdpTextBox textBox)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
foreach (var paragraph in textBox.Paragraphs)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (!paragraph.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
textParts.Add(paragraph.Text.Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (shape is OdpShape odpShape)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
foreach (var paragraph in odpShape.TextParagraphs)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (!paragraph.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
textParts.Add(paragraph.Text.Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (textParts.Count > 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
sb.AppendLine("Content:");
|
||||||
|
foreach (var text in textParts)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" - {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using SkiaSharp;
|
||||||
|
using PDFtoImage;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using PdfiumViewer;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
|
using xAiApi.Configurations;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
@@ -24,28 +26,20 @@ namespace xAiApi.Providers.Extractors
|
|||||||
];
|
];
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Minimum Length for Fallback Using Images ...
|
/// Api Configuration ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private const int MinTextLengthThreshold = 50;
|
private readonly XAiApiConfiguration configuration;
|
||||||
|
|
||||||
/// <summary>
|
public XPdfFileContentExtractor(XAiApiConfiguration configuration)
|
||||||
/// Max Pages for Falling Back Using Images ...
|
{
|
||||||
/// </summary>
|
this.configuration = configuration;
|
||||||
private const int MaxPagesForImageFallback = 10;
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Default DPI for Rendering Images ...
|
|
||||||
/// </summary>
|
|
||||||
private const int RenderDpi = 150;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Max Rendered Image Width ...
|
|
||||||
/// </summary>
|
|
||||||
private const int MaxImageWidth = 2000;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Check if this extractor supports the specified MIME type ...
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
public bool CanExtract(string mimeType)
|
public bool CanExtract(string mimeType)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -57,6 +51,10 @@ namespace xAiApi.Providers.Extractors
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Extract text content from file stream ...
|
/// Extract text content from file stream ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
public async Task<string> ExtractAsync(
|
public async Task<string> ExtractAsync(
|
||||||
Stream fileStream,
|
Stream fileStream,
|
||||||
string mimeType,
|
string mimeType,
|
||||||
@@ -170,6 +168,8 @@ namespace xAiApi.Providers.Extractors
|
|||||||
/// Check Extracted Content is Sufficient or not ...
|
/// Check Extracted Content is Sufficient or not ...
|
||||||
/// if not try to Falling Back using Images ...
|
/// if not try to Falling Back using Images ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <returns></returns>
|
||||||
private bool IsTextSufficient(string text)
|
private bool IsTextSufficient(string text)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -183,12 +183,20 @@ namespace xAiApi.Providers.Extractors
|
|||||||
var cleanText = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());
|
var cleanText = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());
|
||||||
|
|
||||||
//
|
//
|
||||||
return cleanText.Length >= MinTextLengthThreshold;
|
var result = cleanText.Length >= configuration.PDFToImageDescriptor.MinTextLengthThreshold;
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Fallback Converts PDF Pages to Images ...
|
/// Fallback Converts PDF Pages to Images ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="pdfStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
private async Task<XFileExtractionResult> FallbackToImageExtractionAsync(
|
private async Task<XFileExtractionResult> FallbackToImageExtractionAsync(
|
||||||
Stream pdfStream,
|
Stream pdfStream,
|
||||||
string fileName,
|
string fileName,
|
||||||
@@ -211,18 +219,51 @@ namespace xAiApi.Providers.Extractors
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
using var document = PdfDocument.Load(pdfStream);
|
// Calculating With ...
|
||||||
|
var width = configuration.PDFToImageDescriptor.Width;
|
||||||
//
|
if (width >= 0 && configuration.PDFToImageDescriptor.MaxImageWidth > 0)
|
||||||
var pageCount = Math.Min(
|
|
||||||
document.PageCount,
|
|
||||||
MaxPagesForImageFallback
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
|
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
|
width = Math.Min(
|
||||||
|
width,
|
||||||
|
configuration.PDFToImageDescriptor.MaxImageWidth
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Preparing Render Options ...
|
||||||
|
var renderOptions = new RenderOptions
|
||||||
|
{
|
||||||
|
Width = width,
|
||||||
|
Dpi = configuration.PDFToImageDescriptor.Dpi,
|
||||||
|
Height = configuration.PDFToImageDescriptor.Height,
|
||||||
|
UseTiling = configuration.PDFToImageDescriptor.UseTiling,
|
||||||
|
WithFormFill = configuration.PDFToImageDescriptor.WithFormFill,
|
||||||
|
WithAspectRatio = configuration.PDFToImageDescriptor.WithAspectRatio,
|
||||||
|
WithAnnotations = configuration.PDFToImageDescriptor.WithAnnotations,
|
||||||
|
DpiRelativeToBounds = configuration.PDFToImageDescriptor.DpiRelativeToBounds,
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
// Preparing Images to Fallback ...
|
||||||
|
var pagesCount = Conversion.GetPageCount(pdfStream);
|
||||||
|
pdfStream.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (configuration.PDFToImageDescriptor.MaxPagesForImageFallback > 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
pagesCount = Math.Min(
|
||||||
|
pagesCount,
|
||||||
|
configuration.PDFToImageDescriptor.MaxPagesForImageFallback
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
for (int pageIndex = 0; pageIndex < pagesCount; pageIndex++)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Check Cancellation Token ...
|
||||||
if (cancellationToken.IsCancellationRequested)
|
if (cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -232,52 +273,30 @@ namespace xAiApi.Providers.Extractors
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var pageSize = document.PageSizes[pageIndex];
|
var skBitmap = Conversion.ToImage(
|
||||||
|
|
||||||
//
|
|
||||||
var scaleFactor = RenderDpi / 72.0;
|
|
||||||
var renderWidth = (int)Math.Ceiling(pageSize.Width * scaleFactor);
|
|
||||||
var renderHeight = (int)Math.Ceiling(pageSize.Height * scaleFactor);
|
|
||||||
|
|
||||||
//
|
|
||||||
if (renderWidth > MaxImageWidth)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var ratio = (double)MaxImageWidth / renderWidth;
|
|
||||||
renderWidth = MaxImageWidth;
|
|
||||||
renderHeight = (int)(renderHeight * ratio);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
using var bitmap = document.Render(
|
|
||||||
dpiX: RenderDpi,
|
|
||||||
dpiY: RenderDpi,
|
|
||||||
page: pageIndex,
|
page: pageIndex,
|
||||||
width: renderWidth,
|
pdfStream: pdfStream,
|
||||||
forPrinting: false,
|
options: renderOptions
|
||||||
height: renderHeight
|
|
||||||
);
|
);
|
||||||
|
pdfStream.Position = 0;
|
||||||
|
|
||||||
//
|
//
|
||||||
byte[] imageBytes;
|
using (skBitmap)
|
||||||
using (var memoryStream = new MemoryStream())
|
using (var image = SKImage.FromBitmap(skBitmap))
|
||||||
|
using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
|
||||||
|
using (var ms = new MemoryStream())
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
|
data.SaveTo(ms);
|
||||||
imageBytes = memoryStream.ToArray();
|
result.Images.Add(new XExtractedImage
|
||||||
|
{
|
||||||
|
Bytes = ms.ToArray(),
|
||||||
|
MimeType = "image/png",
|
||||||
|
Description = $"Page {pageIndex + 1}, rendered from {fileName}"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
|
||||||
result.Images.Add(new XExtractedImage
|
|
||||||
{
|
|
||||||
Bytes = imageBytes,
|
|
||||||
MimeType = "image/png",
|
|
||||||
PageNumber = pageIndex + 1,
|
|
||||||
Description = $"Page {pageIndex + 1} of {fileName} ({renderWidth}x{renderHeight})"
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch { }
|
||||||
{ }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ namespace xAiApi.Providers.Extractors
|
|||||||
"text/plain",
|
"text/plain",
|
||||||
"text/markdown",
|
"text/markdown",
|
||||||
"text/csv",
|
"text/csv",
|
||||||
"text/html",
|
|
||||||
"text/xml",
|
"text/xml",
|
||||||
"application/json",
|
"application/json",
|
||||||
"application/xml"
|
"application/xml"
|
||||||
@@ -30,6 +29,8 @@ namespace xAiApi.Providers.Extractors
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Check if this extractor supports the specified MIME type ...
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
public bool CanExtract(string mimeType)
|
public bool CanExtract(string mimeType)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -0,0 +1,477 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using OfficeIMO.PowerPoint;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
using DocumentFormat.OpenXml.Packaging;
|
||||||
|
using DrawingText = DocumentFormat.OpenXml.Drawing.Text;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extracts content from all PowerPoint formats
|
||||||
|
/// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
|
||||||
|
/// </summary>
|
||||||
|
public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported MIME Types ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] SupportedMimeTypes =
|
||||||
|
[
|
||||||
|
// OpenXML Formats
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.slideshow", // .ppsx
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.template", // .potx
|
||||||
|
"application/vnd.ms-powerpoint.presentation.macroEnabled.12", // .pptm
|
||||||
|
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12", // .ppsm
|
||||||
|
"application/vnd.ms-powerpoint.template.macroEnabled.12", // .potm
|
||||||
|
// Legacy Binary Formats (.ppt / .pps / .pot share same MIME)
|
||||||
|
"application/vnd.ms-powerpoint"
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
|
/// </summary>
|
||||||
|
public bool CanExtract(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return SupportedMimeTypes.Contains(
|
||||||
|
mimeType?.ToLowerInvariant() ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract text content from file stream ...
|
||||||
|
/// </summary>
|
||||||
|
public async Task<string> ExtractAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await ExtractRichAsync(
|
||||||
|
fileStream: fileStream,
|
||||||
|
fileName: "presentation",
|
||||||
|
mimeType: mimeType,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
return result.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract content from stream as Rich Result ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XFileExtractionResult> ExtractRichAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new XFileExtractionResult
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
MimeType = mimeType
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (IsOpenXmlFormat(mimeType))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Text = await ExtractOpenXmlAsync(
|
||||||
|
fileStream,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
else if (IsLegacyFormat(mimeType))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Text = await ExtractLegacyAsync(
|
||||||
|
fileStream,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"Unsupported PowerPoint MIME type: {mimeType}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"PowerPoint extraction failed: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check Open XML Format ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private bool IsOpenXmlFormat(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = mimeType?.ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => true,
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true,
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.template" => true,
|
||||||
|
"application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true,
|
||||||
|
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true,
|
||||||
|
"application/vnd.ms-powerpoint.template.macroEnabled.12" => true,
|
||||||
|
_ => false
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check Legacy Format ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private bool IsLegacyFormat(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract an Slide Title ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="slidePart"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string GetSlideTitle(SlidePart slidePart)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Title placeholder has specific type
|
||||||
|
var titleShape = slidePart.Slide
|
||||||
|
.Descendants<DocumentFormat.OpenXml.Presentation.Shape>()
|
||||||
|
.FirstOrDefault(s => s.NonVisualShapeProperties?
|
||||||
|
.NonVisualDrawingProperties?
|
||||||
|
.Name?.Value?
|
||||||
|
.StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true
|
||||||
|
);
|
||||||
|
if (titleShape != null)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var titleText = titleShape
|
||||||
|
.Descendants<DrawingText>()
|
||||||
|
.Select(t => t.Text?.Trim())
|
||||||
|
.Where(t => !string.IsNullOrWhiteSpace(t));
|
||||||
|
result = string.Join(" ", titleText);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Speaker Notes ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="slidePart"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string GetSpeakerNotes(SlidePart slidePart)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
var notesSlidePart = slidePart.NotesSlidePart;
|
||||||
|
if (notesSlidePart?.NotesSlide == null)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var notesTexts = notesSlidePart.NotesSlide
|
||||||
|
.Descendants<DrawingText>()
|
||||||
|
.Select(t => t.Text?.Trim())
|
||||||
|
.Where(t => !string.IsNullOrWhiteSpace(t))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
//
|
||||||
|
result = notesTexts.Count > 0
|
||||||
|
? string.Join(Environment.NewLine, notesTexts)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract OpenXML Tables ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="slidePart"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private static string ExtractOpenXmlTables(SlidePart slidePart)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
|
||||||
|
//
|
||||||
|
var tableElements = slidePart.Slide
|
||||||
|
.Descendants<DocumentFormat.OpenXml.Drawing.Table>();
|
||||||
|
|
||||||
|
//
|
||||||
|
var tableIndex = 0;
|
||||||
|
foreach (var table in tableElements)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
tableIndex++;
|
||||||
|
sb.AppendLine($" Table {tableIndex}:");
|
||||||
|
|
||||||
|
//
|
||||||
|
foreach (var row in table
|
||||||
|
.Descendants<DocumentFormat.OpenXml.Drawing.TableRow>())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var cells = row
|
||||||
|
.Descendants<DocumentFormat.OpenXml.Drawing.TableCell>()
|
||||||
|
.Select(c => string.Join(" ", c
|
||||||
|
.Descendants<DrawingText>()
|
||||||
|
.Select(t => t.Text?.Trim())
|
||||||
|
.Where(t => !string.IsNullOrWhiteSpace(t))))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
//
|
||||||
|
if (cells.Count > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" | {string.Join(" | ", cells)} |");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Open XML Format ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractOpenXmlAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Copy to MemoryStream (OpenXml requires seekable stream)
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await fileStream.CopyToAsync(ms, cancellationToken);
|
||||||
|
ms.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
using var presentationDocument = PresentationDocument.Open(ms, false);
|
||||||
|
var presentationPart = presentationDocument.PresentationPart;
|
||||||
|
if (presentationPart == null)
|
||||||
|
{
|
||||||
|
XException.InvalidData.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var slideParts = presentationPart.SlideParts.ToList();
|
||||||
|
var slideIndex = 0;
|
||||||
|
foreach (var slidePart in slideParts)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested) break;
|
||||||
|
slideIndex++;
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine($"[Slide {slideIndex}]");
|
||||||
|
|
||||||
|
//
|
||||||
|
// 1. Extract slide title
|
||||||
|
var slideTitle = GetSlideTitle(slidePart);
|
||||||
|
if (!string.IsNullOrWhiteSpace(slideTitle))
|
||||||
|
{
|
||||||
|
sb.AppendLine($"Title: {slideTitle}");
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// 2. Extract body texts
|
||||||
|
var bodyTexts = slidePart.Slide
|
||||||
|
.Descendants<DrawingText>()
|
||||||
|
.Select(t => t.Text?.Trim())
|
||||||
|
.Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle)
|
||||||
|
.ToList();
|
||||||
|
if (bodyTexts.Count > 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
sb.AppendLine("Content:");
|
||||||
|
foreach (var text in bodyTexts)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" - {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// 3. Extract tables
|
||||||
|
var tables = ExtractOpenXmlTables(slidePart);
|
||||||
|
if (!string.IsNullOrWhiteSpace(tables))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
sb.AppendLine("[Tables]");
|
||||||
|
sb.AppendLine(tables);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// 4. Extract speaker notes
|
||||||
|
var notes = GetSpeakerNotes(slidePart);
|
||||||
|
if (!string.IsNullOrWhiteSpace(notes))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
sb.AppendLine("[Speaker Notes]");
|
||||||
|
sb.AppendLine(notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// 5. Image count metadata
|
||||||
|
var imageCount = slidePart.ImageParts?.Count() ?? 0;
|
||||||
|
if (imageCount > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine($"[Images: {imageCount}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Legacy Format ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractLegacyAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
|
||||||
|
//
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await fileStream.CopyToAsync(ms, cancellationToken);
|
||||||
|
ms.Position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
using var presentation = PowerPointPresentation.Load(ms);
|
||||||
|
var slideIndex = 0;
|
||||||
|
foreach (var slide in presentation.Slides)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
slideIndex++;
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine($"[Slide {slideIndex}]");
|
||||||
|
|
||||||
|
//
|
||||||
|
var textParts = new List<string>();
|
||||||
|
var imageCount = 0;
|
||||||
|
foreach (var shape in slide.Shapes)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (shape is PowerPointTextBox textBox)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (!textBox.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
textParts.Add(textBox.Text.Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (shape is PowerPointAutoShape autoShape)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (!autoShape.AltText.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
textParts.Add(autoShape.AltText.Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (shape is PowerPointPicture picture)
|
||||||
|
{
|
||||||
|
imageCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (textParts.Count > 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
sb.AppendLine("Content:");
|
||||||
|
foreach (var text in textParts)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" - {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (imageCount > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine($"[Images: {imageCount}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = sb.ToString().TrimEnd();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
using System;
|
||||||
|
using RtfPipe;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using xAiModels.Models;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers.Extractors
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extractor for Rich Text Format (RTF) documents
|
||||||
|
/// (application/rtf, text/rtf)
|
||||||
|
/// </summary>
|
||||||
|
public class XRtfFileContentExtractor : IXRtfFileContentExtractor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported MIME Types ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] SupportedMimeTypes =
|
||||||
|
[
|
||||||
|
"text/rtf",
|
||||||
|
"application/rtf",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if this extractor supports the specified MIME type ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool CanExtract(string mimeType)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
return SupportedMimeTypes.Contains(
|
||||||
|
mimeType?.ToLowerInvariant() ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract text content from file stream ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<string> ExtractAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = await ExtractRichAsync(
|
||||||
|
fileStream,
|
||||||
|
"document.rtf",
|
||||||
|
mimeType,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result.Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract content from stream as Rich Result ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="mimeType"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<XFileExtractionResult> ExtractRichAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new XFileExtractionResult
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
MimeType = mimeType
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Text = await ExtractRtfAsync(
|
||||||
|
fileStream,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.ErrorMessage =
|
||||||
|
$"RTF extraction failed: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract RTF Content ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileStream"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> ExtractRtfAsync(
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Read RTF content as string ...
|
||||||
|
using var reader = new StreamReader(
|
||||||
|
fileStream,
|
||||||
|
Encoding.UTF8,
|
||||||
|
detectEncodingFromByteOrderMarks: true,
|
||||||
|
leaveOpen: true
|
||||||
|
);
|
||||||
|
var rtfContent = await reader.ReadToEndAsync();
|
||||||
|
if (rtfContent.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
result = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Convert RTF to HTML using RtfPipe ...
|
||||||
|
var html = Rtf.ToHtml(rtfContent);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Convert HTML to plain text ...
|
||||||
|
result = HtmlToPlainText(html);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts Html to Text ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="html"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string HtmlToPlainText(string html)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (html.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
result = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Remove HTML tags ...
|
||||||
|
result = Regex.Replace(
|
||||||
|
html,
|
||||||
|
"<.*?>",
|
||||||
|
string.Empty,
|
||||||
|
RegexOptions.Singleline
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Decode HTML entities ...
|
||||||
|
result = System.Net.WebUtility.HtmlDecode(result);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Normalize whitespace ...
|
||||||
|
result = Regex.Replace(result, @"\s+", " ").Trim();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1180
-578
File diff suppressed because it is too large
Load Diff
@@ -1,25 +1,22 @@
|
|||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
|
using xCommons.Providers;
|
||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
using xCommons.Providers;
|
|
||||||
|
|
||||||
namespace xAiApi.Providers
|
namespace xAiApi.Providers
|
||||||
{
|
{
|
||||||
public class XDefaultEmbeddingService : XAiEmbeddingServiceBase, IXDefaultEmbeddingService
|
public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService
|
||||||
{
|
{
|
||||||
public XDefaultEmbeddingService(
|
public XAiEmbeddingService(
|
||||||
IXFileProvider fileProvider,
|
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
|
ILogger<XAiEmbeddingService> logger,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
ILogger<XDefaultEmbeddingService> logger,
|
|
||||||
IXFileContentExtractor fileContentExtractor
|
IXFileContentExtractor fileContentExtractor
|
||||||
) : base(
|
) : base(
|
||||||
fileProvider,
|
|
||||||
dataProvider,
|
dataProvider,
|
||||||
configuration,
|
configuration,
|
||||||
validationProvider,
|
validationProvider,
|
||||||
@@ -7,7 +7,7 @@ using xAiApi.Constants;
|
|||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
using xAiApi.Extensions;
|
using xAiApi.Extensions;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xAiService.Helpers;
|
using xAiModels.Helpers;
|
||||||
using System.ClientModel;
|
using System.ClientModel;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
@@ -17,7 +17,6 @@ using xAiModels.Interfaces;
|
|||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -29,28 +28,23 @@ namespace xAiApi.Providers
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Base Embedding Provider Service ...
|
/// Base Embedding Provider Service ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class XAiEmbeddingServiceBase : XAIServiceBase, IXAiEmbeddingServiceBase
|
public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase
|
||||||
{
|
{
|
||||||
private readonly IXFileProvider fileProvider;
|
private readonly string embeddingModelName;
|
||||||
private readonly XAiModelDescriptor descriptor;
|
private readonly XAiModelDescriptor descriptor;
|
||||||
|
private readonly IXAiDataProvider dataProvider;
|
||||||
|
private readonly XAiApiConfiguration configuration;
|
||||||
|
private readonly XValidationProvider validationProvider;
|
||||||
private readonly ILogger<XAiEmbeddingServiceBase> logger;
|
private readonly ILogger<XAiEmbeddingServiceBase> logger;
|
||||||
|
private readonly IXFileContentExtractor fileContentExtractor;
|
||||||
|
|
||||||
protected XAiEmbeddingServiceBase(
|
protected XAiEmbeddingServiceBase(
|
||||||
IXFileProvider fileProvider,
|
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
ILogger<XAiEmbeddingServiceBase> logger,
|
ILogger<XAiEmbeddingServiceBase> logger,
|
||||||
IXFileContentExtractor fileContentExtractor,
|
IXFileContentExtractor fileContentExtractor,
|
||||||
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
|
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
|
||||||
) : base(
|
|
||||||
fileProvider,
|
|
||||||
dataProvider,
|
|
||||||
logger,
|
|
||||||
configuration,
|
|
||||||
validationProvider,
|
|
||||||
fileContentExtractor,
|
|
||||||
null
|
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -61,10 +55,14 @@ namespace xAiApi.Providers
|
|||||||
XException.InvalidConfiguration.Throw();
|
XException.InvalidConfiguration.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.fileProvider = fileProvider;
|
this.dataProvider = dataProvider;
|
||||||
|
this.configuration = configuration;
|
||||||
|
this.validationProvider = validationProvider;
|
||||||
|
|
||||||
//
|
//
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
|
this.fileContentExtractor = fileContentExtractor;
|
||||||
|
this.embeddingModelName = embeddingModelName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -86,7 +84,7 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
using var generator = GetEmbeddingGenerator();
|
var generator = GetEmbeddingGenerator();
|
||||||
|
|
||||||
//
|
//
|
||||||
GeneratedEmbeddings<Embedding<float>> response = null;
|
GeneratedEmbeddings<Embedding<float>> response = null;
|
||||||
@@ -195,7 +193,7 @@ namespace xAiApi.Providers
|
|||||||
case XAiModelProviderType.OpenAI:
|
case XAiModelProviderType.OpenAI:
|
||||||
//
|
//
|
||||||
var openAiClient = new OpenAIClient(
|
var openAiClient = new OpenAIClient(
|
||||||
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : descriptor.ApiKey),
|
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
|
||||||
new OpenAIClientOptions
|
new OpenAIClientOptions
|
||||||
{
|
{
|
||||||
Endpoint = new Uri(descriptor.Url),
|
Endpoint = new Uri(descriptor.Url),
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -3,27 +3,28 @@ using xAiApi.Interfaces;
|
|||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
namespace xAiApi.Providers
|
namespace xAiApi.Providers
|
||||||
{
|
{
|
||||||
public class XDefaultAiService : XAIServiceBase, IXDefaultAiService
|
public class XAiService : XAIServiceBase, IXAiService
|
||||||
{
|
{
|
||||||
public XDefaultAiService(
|
public XAiService(
|
||||||
IXFileProvider fileProvider,
|
IXAiRAGService ragProvider,
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
ILogger<XDefaultAiService> logger,
|
ILogger<XAiService> logger,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
|
IXAiMcpServerProvider mcpServerProvider,
|
||||||
IXFileContentExtractor fileContentExtractor
|
IXFileContentExtractor fileContentExtractor
|
||||||
) : base(
|
) : base(
|
||||||
fileProvider,
|
ragProvider,
|
||||||
dataProvider,
|
dataProvider,
|
||||||
logger,
|
logger,
|
||||||
configuration,
|
configuration,
|
||||||
validationProvider,
|
validationProvider,
|
||||||
|
mcpServerProvider,
|
||||||
fileContentExtractor,
|
fileContentExtractor,
|
||||||
XAiApiConstants.XAiDefaultModelName
|
XAiApiConstants.XAiDefaultModelName
|
||||||
)
|
)
|
||||||
@@ -4,7 +4,6 @@ using xCommons.Providers;
|
|||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
@@ -13,20 +12,22 @@ namespace xAiApi.Providers
|
|||||||
public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
|
public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
|
||||||
{
|
{
|
||||||
public XDefaultThinkingAiService(
|
public XDefaultThinkingAiService(
|
||||||
IXFileProvider fileProvider,
|
IXAiRAGService ragProvider,
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
ILogger<XAIServiceBase> logger,
|
ILogger<XAIServiceBase> logger,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
|
IXAiMcpServerProvider mcpServerProvider,
|
||||||
IXFileContentExtractor fileContentExtractor,
|
IXFileContentExtractor fileContentExtractor,
|
||||||
ReasoningEffort effort = ReasoningEffort.Medium,
|
ReasoningEffort effort = ReasoningEffort.Medium,
|
||||||
ReasoningOutput output = ReasoningOutput.Full
|
ReasoningOutput output = ReasoningOutput.Full
|
||||||
) : base(
|
) : base(
|
||||||
fileProvider,
|
ragProvider,
|
||||||
dataProvider,
|
dataProvider,
|
||||||
logger,
|
logger,
|
||||||
configuration,
|
configuration,
|
||||||
validationProvider,
|
validationProvider,
|
||||||
|
mcpServerProvider,
|
||||||
fileContentExtractor,
|
fileContentExtractor,
|
||||||
XAiApiConstants.XAiDefaultThinkingModelName
|
XAiApiConstants.XAiDefaultThinkingModelName
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,254 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using xAiApi.Models;
|
||||||
|
using xAiApi.Interfaces;
|
||||||
|
using xAiModels.Helpers;
|
||||||
|
using xAiModels.Models.Dtos;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers
|
||||||
|
{
|
||||||
|
public class XInMemoryVectorStore : IXInMemoryVectorStore
|
||||||
|
{
|
||||||
|
private const int DefaultTtlMinutes = 30;
|
||||||
|
private readonly ConcurrentDictionary<Guid, XAiDocumentSession> sessions = new ConcurrentDictionary<Guid, XAiDocumentSession>();
|
||||||
|
public int Count { get { RemoveExpired(); return sessions.Count; } }
|
||||||
|
|
||||||
|
public Guid CreateSession(
|
||||||
|
string ownerId = null,
|
||||||
|
TimeSpan? ttl = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = CreateSession(null, ownerId, ttl);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Guid CreateSession(
|
||||||
|
IEnumerable<XAiVectorDto> vectors,
|
||||||
|
string ownerId = null,
|
||||||
|
TimeSpan? ttl = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var now = DateTime.UtcNow;
|
||||||
|
var session = new XAiDocumentSession
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
OwnerId = ownerId,
|
||||||
|
CreatedAtUtc = now,
|
||||||
|
LastAccessAtUtc = now,
|
||||||
|
Ttl = NormalizeTtl(ttl),
|
||||||
|
Vectors = Copy(vectors)
|
||||||
|
};
|
||||||
|
sessions[session.Id] = session;
|
||||||
|
var result = session.Id;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Replace(
|
||||||
|
Guid sessionId,
|
||||||
|
IEnumerable<XAiVectorDto> vectors,
|
||||||
|
string ownerId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
XAiDocumentSession session;
|
||||||
|
if (!TryGet(sessionId, out session, ownerId))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
lock (session.SyncRoot)
|
||||||
|
{
|
||||||
|
session.Vectors = Copy(vectors);
|
||||||
|
session.LastAccessAtUtc = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Add(
|
||||||
|
Guid sessionId,
|
||||||
|
IEnumerable<XAiVectorDto> vectors,
|
||||||
|
string ownerId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
XAiDocumentSession session;
|
||||||
|
if (!TryGet(sessionId, out session, ownerId))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
var additions = Copy(vectors);
|
||||||
|
lock (session.SyncRoot)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
foreach (var vector in additions)
|
||||||
|
{
|
||||||
|
session.Vectors.Add(vector);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
session.LastAccessAtUtc = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IList<XAiVectorSearchResult> Search(
|
||||||
|
Guid sessionId,
|
||||||
|
ReadOnlyMemory<float> queryEmbedding,
|
||||||
|
int topK = 5,
|
||||||
|
float minScore = 0f,
|
||||||
|
string ownerId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new List<XAiVectorSearchResult>();
|
||||||
|
if (topK <= 0 || queryEmbedding.Length == 0)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
XAiDocumentSession session;
|
||||||
|
if (!TryGet(sessionId, out session, ownerId))
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var query = queryEmbedding.ToArray();
|
||||||
|
lock (session.SyncRoot)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
session.LastAccessAtUtc = DateTime.UtcNow;
|
||||||
|
foreach (var vector in session.Vectors)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (vector == null || vector.Embedding.Length == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var score = VectorHelper.CosineSimilarity(
|
||||||
|
query,
|
||||||
|
vector.Embedding.ToArray()
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
if (score >= minScore)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Add(new XAiVectorSearchResult
|
||||||
|
{
|
||||||
|
Score = score,
|
||||||
|
Id = vector.Id,
|
||||||
|
Text = vector.Text,
|
||||||
|
Metadata = vector.Metadata,
|
||||||
|
Identifier = vector.Identifier,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
result = [.. result
|
||||||
|
.OrderByDescending(x => x.Score)
|
||||||
|
.Take(topK)];
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGet(
|
||||||
|
Guid sessionId,
|
||||||
|
out XAiDocumentSession session,
|
||||||
|
string ownerId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
session = null;
|
||||||
|
XAiDocumentSession found;
|
||||||
|
if (!sessions.TryGetValue(sessionId, out found))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
lock (found.SyncRoot)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
XAiDocumentSession current;
|
||||||
|
if (!sessions.TryGetValue(sessionId, out current) ||
|
||||||
|
!ReferenceEquals(current, found))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (!OwnerMatches(found, ownerId))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (found.IsExpired(DateTime.UtcNow))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
sessions.TryRemove(sessionId, out found);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
found.LastAccessAtUtc = DateTime.UtcNow;
|
||||||
|
session = found;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Remove(
|
||||||
|
Guid sessionId,
|
||||||
|
string ownerId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
XAiDocumentSession session;
|
||||||
|
if (!TryGet(sessionId, out session, ownerId)) return false;
|
||||||
|
return sessions.TryRemove(sessionId, out session);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
#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 ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,588 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using xAiApi.Models;
|
||||||
|
using xAiApi.Interfaces;
|
||||||
|
using xAiApi.Extensions;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using xAiApi.Configurations;
|
||||||
|
using xExceptions.Constants;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace xAiApi.Providers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy:
|
||||||
|
/// Paragraphs -> Sentences -> Words -> Hard Cut ...
|
||||||
|
/// </summary>
|
||||||
|
public class XTextChunker : IXTextChunker
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Default Options which used when no Options Provided ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly XAiApiConfiguration configuration;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Matches Paragraph Boundaries (two or more Line Breaks) ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Regex ParagraphSplitter = new(
|
||||||
|
@"\n\s*\n+",
|
||||||
|
RegexOptions.Compiled
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Regex SentenceSplitter = new(
|
||||||
|
@"(?<=[\.\!\?؟。!?])\s+|(?<=\n)",
|
||||||
|
RegexOptions.Compiled
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Matches Repeated Horizontal Whitespaces ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Regex HorizontalWhitespace = new(
|
||||||
|
@"[ \t\f\v\u00A0]{2,}",
|
||||||
|
RegexOptions.Compiled
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Matches Three or more Line Breaks ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Regex ExcessiveLineBreaks = new(
|
||||||
|
@"\n{3,}",
|
||||||
|
RegexOptions.Compiled
|
||||||
|
);
|
||||||
|
|
||||||
|
public XTextChunker(
|
||||||
|
XAiApiConfiguration configuration
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Validate Configuration ...
|
||||||
|
if (
|
||||||
|
!configuration.IsValid() ||
|
||||||
|
!configuration.TextChunker.IsValid()
|
||||||
|
)
|
||||||
|
{
|
||||||
|
XException.InvalidConfiguration.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
this.configuration = configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Split Text into Chunks ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public IList<XTextChunk> Chunk(
|
||||||
|
string text,
|
||||||
|
string source = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new List<XTextChunk>();
|
||||||
|
if (text.IsNullOrEmpty() || string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Normalize ...
|
||||||
|
var normalized = configuration.TextChunker.NormalizeWhitespace
|
||||||
|
? Normalize(text)
|
||||||
|
: text;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Short Circuit for Small Texts ...
|
||||||
|
if (normalized.Length <= configuration.TextChunker.ChunkSize)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Add(CreateChunk(normalized, 0, 0, source));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Build Atomic Units (never larger than ChunkSize) ...
|
||||||
|
var units = BuildUnits(normalized);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Accumulate Units into Chunks with Overlap ...
|
||||||
|
var chunks = Accumulate(units);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Merge too Small Tail Chunks ...
|
||||||
|
chunks = MergeSmallChunks(chunks);
|
||||||
|
|
||||||
|
//
|
||||||
|
for (var i = 0; i < chunks.Count; i++)
|
||||||
|
{
|
||||||
|
result.Add(CreateChunk(chunks[i].Text, chunks[i].Offset, i, source));
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Split Text into Chunks and Return only Texts ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public IList<string> ChunkTexts(string text)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = Chunk(text, null)
|
||||||
|
.Select(c => c.Text)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Private ...
|
||||||
|
/// <summary>
|
||||||
|
/// Internal Text Unit with its Offset in Normalized Source ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly struct Unit
|
||||||
|
{
|
||||||
|
public Unit(string text, int offset)
|
||||||
|
{
|
||||||
|
Text = text;
|
||||||
|
Offset = offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Text { get; }
|
||||||
|
public int Offset { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Normalize Line Endings and Whitespaces ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string Normalize(string text)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = text
|
||||||
|
.Replace("\r\n", "\n")
|
||||||
|
.Replace('\r', '\n');
|
||||||
|
|
||||||
|
//
|
||||||
|
result = HorizontalWhitespace.Replace(result, " ");
|
||||||
|
result = ExcessiveLineBreaks.Replace(result, "\n\n");
|
||||||
|
|
||||||
|
//
|
||||||
|
result = result.Trim();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Create Chunk Model ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <param name="offset"></param>
|
||||||
|
/// <param name="index"></param>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private XTextChunk CreateChunk(
|
||||||
|
string text,
|
||||||
|
int offset,
|
||||||
|
int index,
|
||||||
|
string source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var identifier = source.IsNullOrEmpty()
|
||||||
|
? index.ToString()
|
||||||
|
: $"{source}{configuration.TextChunker.ChunkIdentifierSeparator}{index}";
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = new XTextChunk
|
||||||
|
{
|
||||||
|
Text = text,
|
||||||
|
Index = index,
|
||||||
|
Source = source,
|
||||||
|
StartOffset = offset,
|
||||||
|
Identifier = identifier
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private List<Unit> BuildUnits(string text)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new List<Unit>();
|
||||||
|
|
||||||
|
//
|
||||||
|
foreach (var paragraph in SplitWithOffsets(text, ParagraphSplitter, 0))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (paragraph.Text.Length <= configuration.TextChunker.ChunkSize)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Add(paragraph);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Paragraph too Long -> Sentences ...
|
||||||
|
foreach (var sentence in SplitWithOffsets(paragraph.Text, SentenceSplitter, paragraph.Offset))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (sentence.Text.Length <= configuration.TextChunker.ChunkSize)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result.Add(sentence);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Sentence too Long -> Word Boundary Hard Cut ...
|
||||||
|
result.AddRange(HardSplit(sentence, configuration.TextChunker.ChunkSize));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <param name="splitter"></param>
|
||||||
|
/// <param name="baseOffset"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private IEnumerable<Unit> SplitWithOffsets(
|
||||||
|
string text,
|
||||||
|
Regex splitter,
|
||||||
|
int baseOffset
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var position = 0;
|
||||||
|
foreach (Match match in splitter.Matches(text))
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var part = text.Substring(position, match.Index - position);
|
||||||
|
var unit = TrimUnit(part, baseOffset + position);
|
||||||
|
if (!unit.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
yield return unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
position = match.Index + match.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (position < text.Length)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var tail = TrimUnit(text.Substring(position), baseOffset + position);
|
||||||
|
if (!tail.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
yield return tail;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Trim Unit Text while Adjusting its Offset ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <param name="offset"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private Unit TrimUnit(
|
||||||
|
string text,
|
||||||
|
int offset
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var start = 0;
|
||||||
|
while (start < text.Length && char.IsWhiteSpace(text[start]))
|
||||||
|
{
|
||||||
|
start++;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var end = text.Length;
|
||||||
|
while (end > start && char.IsWhiteSpace(text[end - 1]))
|
||||||
|
{
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = new Unit(text.Substring(start, end - start), offset + start);
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="unit"></param>
|
||||||
|
/// <param name="maxSize"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private IEnumerable<Unit> HardSplit(
|
||||||
|
Unit unit,
|
||||||
|
int maxSize
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var text = unit.Text;
|
||||||
|
var position = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
while (position < text.Length)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var remaining = text.Length - position;
|
||||||
|
if (remaining <= maxSize)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
yield return TrimUnit(text.Substring(position), unit.Offset + position);
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Find Last Whitespace within Window ...
|
||||||
|
var cut = text.LastIndexOfAny(WordBoundaries, position + maxSize - 1, maxSize);
|
||||||
|
if (cut <= position)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// No Whitespace -> Hard Cut ...
|
||||||
|
cut = position + maxSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var piece = TrimUnit(text.Substring(position, cut - position), unit.Offset + position);
|
||||||
|
if (!piece.Text.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
yield return piece;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
position = cut;
|
||||||
|
while (position < text.Length && char.IsWhiteSpace(text[position]))
|
||||||
|
{
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="units"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private List<Unit> Accumulate(List<Unit> units)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = new List<Unit>();
|
||||||
|
if (!units.HasChild())
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var buffer = new StringBuilder();
|
||||||
|
var buffered = new List<Unit>();
|
||||||
|
var bufferOffset = -1;
|
||||||
|
|
||||||
|
//
|
||||||
|
foreach (var unit in units)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var separator = buffer.Length > 0 ? " " : string.Empty;
|
||||||
|
var projected = buffer.Length + separator.Length + unit.Text.Length;
|
||||||
|
|
||||||
|
//
|
||||||
|
if (projected > configuration.TextChunker.ChunkSize && buffer.Length > 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Close Current Chunk ...
|
||||||
|
var closed = buffer.ToString();
|
||||||
|
result.Add(new Unit(closed, bufferOffset));
|
||||||
|
|
||||||
|
//
|
||||||
|
// Seed Next Chunk with Overlap Tail (only if Unit still Fits) ...
|
||||||
|
var overlap = TakeOverlap(closed, configuration.TextChunker.ChunkOverlap);
|
||||||
|
var fits = overlap.Length + 1 + unit.Text.Length <= configuration.TextChunker.ChunkSize;
|
||||||
|
|
||||||
|
//
|
||||||
|
buffer.Clear();
|
||||||
|
if (!overlap.IsNullOrEmpty() && fits)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
bufferOffset = ComputeOverlapOffset(buffered, overlap.Length);
|
||||||
|
buffer.Append(overlap);
|
||||||
|
separator = " ";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
//
|
||||||
|
bufferOffset = -1;
|
||||||
|
separator = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
buffered.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (bufferOffset < 0)
|
||||||
|
{
|
||||||
|
bufferOffset = unit.Offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
buffer.Append(separator).Append(unit.Text);
|
||||||
|
buffered.Add(unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
if (buffer.Length > 0)
|
||||||
|
{
|
||||||
|
result.Add(new Unit(buffer.ToString(), bufferOffset));
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Map Trailing Overlap Length of Buffered Units back to Source Offset ...
|
||||||
|
/// Units Joined by Single Space Separator in Buffer ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="buffered"></param>
|
||||||
|
/// <param name="overlapLength"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private int ComputeOverlapOffset(
|
||||||
|
List<Unit> buffered,
|
||||||
|
int overlapLength
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = 0;
|
||||||
|
var remaining = overlapLength;
|
||||||
|
for (var i = buffered.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var unit = buffered[i];
|
||||||
|
if (remaining <= unit.Text.Length)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result = unit.Offset + unit.Text.Length - remaining;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Consume Unit and its Leading Separator ...
|
||||||
|
remaining -= unit.Text.Length + 1;
|
||||||
|
if (remaining <= 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
result = unit.Offset;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
result = buffered.Count > 0 ? buffered[0].Offset : 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Take Trailing Overlap from Text, Aligned to Word Boundary ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <param name="overlap"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string TakeOverlap(
|
||||||
|
string text,
|
||||||
|
int overlap
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (overlap <= 0 || text.Length <= overlap)
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var start = text.Length - overlap;
|
||||||
|
var boundary = text.IndexOfAny(WordBoundaries, start);
|
||||||
|
if (boundary < 0 || boundary >= text.Length - 1)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// No Boundary inside Window -> Skip Overlap ...
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return text.Substring(boundary + 1).Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Merge Chunks Smaller than MinChunkSize into their Predecessor ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="chunks"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private List<Unit> MergeSmallChunks(List<Unit> chunks)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2)
|
||||||
|
{
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = new List<Unit>();
|
||||||
|
foreach (var chunk in chunks)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (chunk.Text.Length < configuration.TextChunker.MinChunkSize && result.Count > 0)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var previous = result[result.Count - 1];
|
||||||
|
var merged = $"{previous.Text} {chunk.Text}";
|
||||||
|
if (merged.Length <= configuration.TextChunker.ChunkSize)
|
||||||
|
{
|
||||||
|
result[result.Count - 1] = new Unit(merged, previous.Offset);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
result.Add(chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Characters Considered as Word Boundaries ...
|
||||||
|
/// </summary>
|
||||||
|
private readonly char[] WordBoundaries = [' ', '\n', '\t'];
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
+74
-31
@@ -3,6 +3,7 @@ using System.IO;
|
|||||||
using xAiApi.DI;
|
using xAiApi.DI;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using xAiModels.DI;
|
using xAiModels.DI;
|
||||||
|
using xAiService.DI;
|
||||||
using xTagService.DI;
|
using xTagService.DI;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using xAiApi.Database;
|
using xAiApi.Database;
|
||||||
@@ -11,23 +12,21 @@ using xPushService.DI;
|
|||||||
using xFileService.DI;
|
using xFileService.DI;
|
||||||
using xDataService.DI;
|
using xDataService.DI;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using xAiApi.Providers;
|
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using xAiApi.Extensions;
|
using xAiApi.Extensions;
|
||||||
using xStringService.DI;
|
using xStringService.DI;
|
||||||
using xAiApi.Interfaces;
|
using xLoggingService.DI;
|
||||||
using xStorageService.DI;
|
using xStorageService.DI;
|
||||||
using xIdentityService.DI;
|
using xIdentityService.DI;
|
||||||
using xDataService.Models;
|
using xDataService.Models;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
|
using xAiModels.Constants;
|
||||||
using xPushService.Helpers;
|
using xPushService.Helpers;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using xAiApi.Providers.Extractors;
|
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using xAiApi.Interfaces.Extractors;
|
|
||||||
using Newtonsoft.Json.Serialization;
|
using Newtonsoft.Json.Serialization;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -65,13 +64,17 @@ namespace xAiApi
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Register Validation Provider and all XCommons Module Services ...
|
// Register Validation Provider and all XCommons Module Services ...
|
||||||
services.AddXCommons();
|
services.AddXCommons(Configuration);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Register App Configuration ...
|
// Register App Configuration ...
|
||||||
services.AddXAppConfiguration(Configuration);
|
services.AddXAppConfiguration(Configuration);
|
||||||
var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
|
var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Register Logging Service ...
|
||||||
|
services.AddXLoggingService(Configuration);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Register Allowed Origins ...
|
// Register Allowed Origins ...
|
||||||
services.AddXCors(appConfiguration.AllowedOrigins);
|
services.AddXCors(appConfiguration.AllowedOrigins);
|
||||||
@@ -188,54 +191,95 @@ namespace xAiApi
|
|||||||
services.AddXAiApiConfiguration(Configuration);
|
services.AddXAiApiConfiguration(Configuration);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Register File Content Extractors ...
|
// Register MCP Server Provider ...
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XPdfFileContentExtractor>();
|
services.AddXAiMcpServerProvider();
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XDocxFileContentExtractor>();
|
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XImageFileContentExtractor>();
|
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XAudioFileContentExtractor>();
|
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XExcelFileContentExtractor>();
|
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XVisionFileContentExtractor>();
|
|
||||||
services.AddSingleton<IXFileContentExtractorBase, XPlainTextFileContentExtractor>();
|
|
||||||
|
|
||||||
//
|
//
|
||||||
services.AddSingleton<IXFileContentExtractor, XFileContentExtractor>();
|
// Register File Content Extractor Services ...
|
||||||
|
services.AddXAiFileContentExtractors();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Register Default Ai Service ...
|
// Register Text Chunker Service ...
|
||||||
services.AddScoped<IXDefaultAiService, XDefaultAiService>();
|
services.AddXAiTextChunker();
|
||||||
services.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
|
|
||||||
services.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
|
//
|
||||||
|
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
|
||||||
|
services.AddXAiChatWithDocuments();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Register XAiMcpClient ...
|
||||||
|
services.AddXAiMcpClient();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Persistent RAG (Knowledge over XAiVector Table) ...
|
||||||
|
services.AddXRagService();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Register Default AI Services ...
|
||||||
|
services.AddXAiServices();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
public void Configure(
|
||||||
|
IApplicationBuilder app,
|
||||||
|
IWebHostEnvironment env
|
||||||
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
var isDevelopmentEnvironment = false;
|
// Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors
|
||||||
if (env.IsDevelopment())
|
// -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ...
|
||||||
|
var isDevelopmentEnvironment = env.IsDevelopment();
|
||||||
|
if (isDevelopmentEnvironment)
|
||||||
{
|
{
|
||||||
isDevelopmentEnvironment = true;
|
|
||||||
app.UseDeveloperExceptionPage();
|
app.UseDeveloperExceptionPage();
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute);
|
||||||
|
app.UseHsts();
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Use Swagger Middleware ...
|
// Setting Environment in App Confiuration ...
|
||||||
app.UseXSwagger();
|
app.AddEnvironmentToXAppConfiguration(env.EnvironmentName);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Force Https Redirection ...
|
// Force Https Redirection ...
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Using Cors ...
|
// Use Storage Service (Prepare Folders + Static Files) ...
|
||||||
|
// Must be before Routing so Static Files Short Circuit Pipeline ...
|
||||||
|
app.UseXStorageService();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Use Swagger Middleware (Only in Development) ...
|
||||||
|
if (isDevelopmentEnvironment)
|
||||||
|
{
|
||||||
|
app.UseXSwagger();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Using Cors (before Proxy so Browser Requests get CORS Headers) ...
|
||||||
app.UseXCors();
|
app.UseXCors();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Enable Model Proxy (Handles its own Authentication) ...
|
||||||
|
app.UseXAiModelProxy();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Using Routing ...
|
// Using Routing ...
|
||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Use xIdentityService ...
|
// Using Request Logging ...
|
||||||
|
if (!isDevelopmentEnvironment)
|
||||||
|
{
|
||||||
|
app.UseXRequestLogger();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Use xIdentityService (Authentication) ...
|
||||||
app.UseXIdentityService();
|
app.UseXIdentityService();
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -249,11 +293,7 @@ namespace xAiApi
|
|||||||
});
|
});
|
||||||
|
|
||||||
//
|
//
|
||||||
// Use Storage Service ...
|
// Use PushService (Legacy UseSignalR -> Registers its own Router) ...
|
||||||
app.UseXStorageService();
|
|
||||||
|
|
||||||
//
|
|
||||||
// Use PushService ...
|
|
||||||
var pushHelper = new XPushServiceHelper();
|
var pushHelper = new XPushServiceHelper();
|
||||||
app.UseXPushService(pushHelper);
|
app.UseXPushService(pushHelper);
|
||||||
|
|
||||||
@@ -294,3 +334,6 @@ namespace xAiApi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
{
|
{
|
||||||
"AllowedOrigins": [
|
"AllowedOrigins": [
|
||||||
|
"http://127.0.0.1:5500",
|
||||||
"http://localhost:5000",
|
"http://localhost:5000",
|
||||||
"https://localhost:5001",
|
"https://localhost:5001",
|
||||||
"http://api.saherelm.ir",
|
"http://api.saherelm.ir",
|
||||||
"https://api.saherelm.ir",
|
"https://api.saherelm.ir",
|
||||||
"http://api.saherelmhub.ir",
|
"http://api.saherelmhub.ir",
|
||||||
|
"http://192.168.11.29:5173",
|
||||||
|
"http://192.168.11.29:5174",
|
||||||
"https://api.saherelmhub.ir"
|
"https://api.saherelmhub.ir"
|
||||||
],
|
],
|
||||||
"IdentityServiceConfiguration": {
|
"IdentityServiceConfiguration": {
|
||||||
@@ -37,9 +40,16 @@
|
|||||||
},
|
},
|
||||||
"AiApiConfiguration": {
|
"AiApiConfiguration": {
|
||||||
"Models": [
|
"Models": [
|
||||||
|
{
|
||||||
|
"Name": "Arion",
|
||||||
|
"Provider": "OpenAI",
|
||||||
|
"LLM": "claude-fable-5-1",
|
||||||
|
"Url": "https://arionhub.pro/v1",
|
||||||
|
"ApiKey": "sk-AKJGD8J9gOCrQgc5oWPGtRGUo25PnnQGnMoipzdliYHa3otZ"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ApiKey": "",
|
"ApiKey": "",
|
||||||
"Name": "Gemma",
|
"Name": "Gemma_BKP",
|
||||||
"LLM": "gemma3:1b",
|
"LLM": "gemma3:1b",
|
||||||
"Provider": "OpenAI",
|
"Provider": "OpenAI",
|
||||||
"Url": "http://178.131.88.93:1112/v1"
|
"Url": "http://178.131.88.93:1112/v1"
|
||||||
@@ -77,6 +87,12 @@
|
|||||||
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
|
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
|
||||||
"Description": "",
|
"Description": "",
|
||||||
"Params": []
|
"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": {
|
"OCR": {
|
||||||
@@ -88,7 +104,51 @@
|
|||||||
"Transcript": {
|
"Transcript": {
|
||||||
"Language": "fa",
|
"Language": "fa",
|
||||||
"ModelsPath": "Models/ggml-base.bin"
|
"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,
|
||||||
|
"DefaultMinScore": 0.35,
|
||||||
|
"EmbeddingBatchSize": 32,
|
||||||
|
"SourceSnippetLength": 200,
|
||||||
|
"MetadataFileName": "fileName",
|
||||||
|
"MetadataMimeType": "mimeType",
|
||||||
|
"PromptName": "ChatWithDocuments",
|
||||||
|
"MetadataChunkIndex": "chunkIndex"
|
||||||
|
},
|
||||||
|
"DateTime": {
|
||||||
|
"IncludeDayOfWeek": true,
|
||||||
|
"IncludeUnixTimestamp": false,
|
||||||
|
"InjectIntoSystemPrompt": true,
|
||||||
|
"IncludePersianCalendar": true,
|
||||||
|
"DefaultTimezone": "Asia/Tehran",
|
||||||
|
"GregorianFormat": "yyyy-MM-dd HH:mm:ss"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
@@ -98,4 +158,4 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
|
|||||||
+37
-1
@@ -4,6 +4,7 @@
|
|||||||
"DefaultLanguage": "fa-IR",
|
"DefaultLanguage": "fa-IR",
|
||||||
"XPoweredValue": "SaherElmITCenter",
|
"XPoweredValue": "SaherElmITCenter",
|
||||||
"WelcomeMessage": "Welcome to xSaherElm Project's AI API",
|
"WelcomeMessage": "Welcome to xSaherElm Project's AI API",
|
||||||
|
"DefaultCacheTtlMinutes": 10,
|
||||||
"AllowedOrigins": [
|
"AllowedOrigins": [
|
||||||
"http://api.saherelm.ir",
|
"http://api.saherelm.ir",
|
||||||
"https://api.saherelm.ir",
|
"https://api.saherelm.ir",
|
||||||
@@ -18,6 +19,9 @@
|
|||||||
"Name": "Hadi Khazaee Asl",
|
"Name": "Hadi Khazaee Asl",
|
||||||
"Email": "hadi_khazaee_asl@yahoo.com",
|
"Email": "hadi_khazaee_asl@yahoo.com",
|
||||||
"Url": "https://www.saherelm.ir"
|
"Url": "https://www.saherelm.ir"
|
||||||
|
},
|
||||||
|
"DefaultValues": {
|
||||||
|
"version": "1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"HttpServiceConfiguration": {
|
"HttpServiceConfiguration": {
|
||||||
@@ -48,6 +52,38 @@
|
|||||||
"BaseRoute": "hubs",
|
"BaseRoute": "hubs",
|
||||||
"AddSupportMessageProtocol": true
|
"AddSupportMessageProtocol": true
|
||||||
},
|
},
|
||||||
|
"LoggingServiceConfiguration": {
|
||||||
|
"Enabled": true,
|
||||||
|
"MinimumLevel": "Information",
|
||||||
|
"Queue": {
|
||||||
|
"Enabled": true,
|
||||||
|
"Capacity": 10000,
|
||||||
|
"ShutdownTimeoutSeconds": 10
|
||||||
|
},
|
||||||
|
"File": {
|
||||||
|
"Enabled": true,
|
||||||
|
"Directory": "./Logs",
|
||||||
|
"FileName": "xAiApi-.log",
|
||||||
|
"Format": "Json",
|
||||||
|
"MinimumLevel": "Information",
|
||||||
|
"RetainedFileCountLimit": 30
|
||||||
|
},
|
||||||
|
"Database": {
|
||||||
|
"Enabled": false,
|
||||||
|
"TableName": "XLogs",
|
||||||
|
"AutoCreateTable": true,
|
||||||
|
"MinimumLevel": "Warning",
|
||||||
|
"Provider": "Microsoft.Data.Sqlite",
|
||||||
|
"ConnectionString": "Filename=./Db/XLogs.db"
|
||||||
|
},
|
||||||
|
"Event": {
|
||||||
|
"Enabled": false,
|
||||||
|
"Sender": "xAiApi",
|
||||||
|
"MinimumLevel": "Error",
|
||||||
|
"Topic": "application-logs",
|
||||||
|
"Action": "ApplicationLogCreated"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
@@ -55,4 +91,4 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-9
@@ -7,7 +7,6 @@
|
|||||||
<Authors>Hadi Khazaee Asl</Authors>
|
<Authors>Hadi Khazaee Asl</Authors>
|
||||||
<Company>SaherElm IT Center</Company>
|
<Company>SaherElm IT Center</Company>
|
||||||
<PackageId>xSaherElm.xAiApi</PackageId>
|
<PackageId>xSaherElm.xAiApi</PackageId>
|
||||||
<!-- <TargetFramework>net8.0</TargetFramework> -->
|
|
||||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||||
|
|
||||||
<Description>
|
<Description>
|
||||||
@@ -18,8 +17,8 @@
|
|||||||
<PackageIcon>icon.png</PackageIcon>
|
<PackageIcon>icon.png</PackageIcon>
|
||||||
|
|
||||||
<!-- Fix Duplicate TargetFramework Issue -->
|
<!-- Fix Duplicate TargetFramework Issue -->
|
||||||
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
|
|
||||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||||
|
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<!-- Icon Handling -->
|
<!-- Icon Handling -->
|
||||||
@@ -41,27 +40,32 @@
|
|||||||
<ProjectReference Include="../Modules/xHttpService/xHttpService.csproj" />
|
<ProjectReference Include="../Modules/xHttpService/xHttpService.csproj" />
|
||||||
<ProjectReference Include="../Modules/xFileService/xFileService.csproj" />
|
<ProjectReference Include="../Modules/xFileService/xFileService.csproj" />
|
||||||
<ProjectReference Include="../Modules/xStorageService/xStorageService.csproj" />
|
<ProjectReference Include="../Modules/xStorageService/xStorageService.csproj" />
|
||||||
|
<ProjectReference Include="..\Modules\xLoggingService\xLoggingService.csproj" />
|
||||||
<ProjectReference Include="../Modules/xIdentityHelper/xIdentityHelper.csproj" />
|
<ProjectReference Include="../Modules/xIdentityHelper/xIdentityHelper.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<!-- Dependencies -->
|
<!-- Dependencies -->
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NAudio" Version="2.4.0" />
|
|
||||||
<PackageReference Include="Tesseract" Version="5.2.0" />
|
<PackageReference Include="Tesseract" Version="5.2.0" />
|
||||||
|
<PackageReference Include="PDFtoImage" Version="4.1.1" />
|
||||||
|
<PackageReference Include="FFMpegCore" Version="4.8.0" />
|
||||||
|
<PackageReference Include="AngleSharp" Version="1.1.2" />
|
||||||
<PackageReference Include="Whisper.net" Version="1.9.1" />
|
<PackageReference Include="Whisper.net" Version="1.9.1" />
|
||||||
|
<PackageReference Include="VersOne.Epub" Version="3.3.6" />
|
||||||
<PackageReference Include="OllamaSharp" Version="5.4.25" />
|
<PackageReference Include="OllamaSharp" Version="5.4.25" />
|
||||||
<PackageReference Include="PdfiumViewer" Version="2.13.0" />
|
|
||||||
<PackageReference Include="ExcelDataReader" Version="3.9.0" />
|
<PackageReference Include="ExcelDataReader" Version="3.9.0" />
|
||||||
|
<PackageReference Include="RtfPipe" Version="2.0.7677.4303" />
|
||||||
|
<PackageReference Include="HtmlAgilityPack" Version="1.13.0" />
|
||||||
<PackageReference Include="Whisper.net.Runtime" Version="1.9.1" />
|
<PackageReference Include="Whisper.net.Runtime" Version="1.9.1" />
|
||||||
|
<PackageReference Include="ModelContextProtocol" Version="2.3.1" />
|
||||||
|
<PackageReference Include="OfficeIMO.PowerPoint" Version="3.5.1" />
|
||||||
|
<PackageReference Include="OfficeIMO.OpenDocument" Version="3.5.1" />
|
||||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
|
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
|
||||||
<PackageReference Include="ExcelDataReader.DataSet" Version="3.9.0" />
|
<PackageReference Include="ExcelDataReader.DataSet" Version="3.9.0" />
|
||||||
<PackageReference Include="UglyToad.PdfPig" Version="1.7.0-custom-5" />
|
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0" />
|
||||||
<PackageReference Include="PdfiumViewer.Native.x86.v8-xfa" Version="2018.4.8.256" />
|
|
||||||
<PackageReference Include="PdfiumViewer.Native.x86_64.v8-xfa" Version="2018.4.8.256" />
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.11" />
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.11" />
|
||||||
<PackageReference Include="PdfiumViewer.Native.x86.no_v8-no_xfa" Version="2018.4.8.256" />
|
|
||||||
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="5.0.0" />
|
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="5.0.0" />
|
||||||
<PackageReference Include="PdfiumViewer.Native.x86_64.no_v8-no_xfa" Version="2018.4.8.256" />
|
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.116.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<!-- For XML Documentation Support -->
|
<!-- For XML Documentation Support -->
|
||||||
|
|||||||
Reference in New Issue
Block a user