Compare commits

..
37 Commits
Author SHA1 Message Date
saherelm 3a228439a5 add config for cache ttl ... 2026-11-15 21:26:41 +03:30
saherelm 13cd0745c6 last ... 2026-11-14 08:34:10 +03:30
saherelm 5bccce3475 apply fix on Create Conversation Validations ... 2026-11-11 11:56:11 +03:30
saherelm cddf2650f5 fix Create Conversation to Handle Default Project Id ... 2026-11-11 11:42:55 +03:30
saherelm fba69b274c adding allowed origin for Live Server ... 2026-11-10 18:35:11 +03:30
saherelm 0077008105 last ... 2026-11-10 17:29:59 +03:30
saherelm 3dc54332c2 fix ask with files ... 2026-11-10 11:56:55 +03:30
saherelm dab384ea37 adding cors origins ... 2026-11-10 10:40:00 +03:30
saherelm f6a916fa83 make it use global ip ... 2026-11-09 15:41:23 +03:30
saherelm 5656ec07d5 - .gitignore: +Logs
- Program.cs: +xLoggingService، +AddXTelemetryLogger، +AddXTelemetry
- Startup.cs: +UseXRequestLogger (non-development)
- xAiApi.csproj: +xLoggingService reference
2026-11-09 12:50:22 +03:30
saherelm c24c14eb74 add using XLoggingService ... 2026-11-08 22:55:56 +03:30
saherelm b58f1dd736 last ... 2026-11-08 17:59:31 +03:30
saherelm 31add513bc add support for File Content Extraction, use Data Bytes for Multi Modal or add them to Knowledge ... 2026-11-06 20:53:26 +03:30
saherelm 16fb715926 last ... 2026-11-06 19:14:02 +03:30
saherelm 5307fe4d2f add support filling policy handler ... 2026-11-05 23:19:14 +03:30
saherelm ae7f5920c1 - Apply Using XUserInfoClaims to RefreshAsync on McpServers ...
- Adding DateTime Prompt Handling in XAiServiceBase ...
- Adding Support for Function Tools Attachment into ChatOptions when Asking Ai ...
- Adding XDateTimeDescriptor class for Configuring DateTime attaching in Prompt Context, attached it on XAiApiConfiguration and also Configure it in appSettings File ...
2026-11-05 18:17:30 +03:30
saherelm 97acf0a123 Add Support for Default Swagger Parameters Values in appSetting and Add Support for MCPServers Connecting and Handling Function Tooling ... 2026-11-05 14:54:05 +03:30
saherelm c7efdd5525 last ... 2026-11-03 22:53:48 +03:30
saherelm 937e30dd9d last ... 2026-11-03 18:56:42 +03:30
saherelm c61f8aec98 add MCP Serer Descriptor ... 2026-11-02 23:16:20 +03:30
saherelm a870d61e61 Refactor Chat Pipeline into PrepareChatRequirementsAsync and Harden RAG Services
- XAIServiceBase: add PrepareChatRequirementsAsync as the single entry point
  for chat prerequisites (normalize RAG params, resolve default
  project/conversation, ingest attachments, retrieve RAG context, build history,
  persist prompt message) and return the new XPreparedChatContext;
- XAIServiceBase: add NormalizeRagParams (topK / minScore / type) and use it in
  all Ask* methods instead of duplicated inline normalization;
- XAIServiceBase: rework GetHistory - the single
  GetHistory(ChatMessage, bool) signature is replaced by two overloads
  GetHistory(prompt, forcePrompt) and GetHistory(prompt, context); the latter is
  used by the non-persisted chat path;
- XAIServiceBase: remove AskLLMAsync; LLM invocation is now inlined in each
  Ask* method over prep.History;
- XAIServiceBase: rewrite AskAsync and AskAsEnumerable on top of
  PrepareChatRequirementsAsync; streamed responses now use Role = Assistant,
  RespondTo = prep.PersistedPromptMessage.Id and Sequence++;
- XAIServiceBase: use XAiApiConstants.XAiApiRagPromptName instead of
  configuration.RAGDescriptor.PromptName;
- XAIServiceBase.LoadConversations: call the renamed GetDafaultProject;
- Add Models/XPreparedChatContext.cs (Project, Conversation, History, Context,
  PersistedPromptMessage) as the shared context between actions;
- XAiRAGService: wrap each file ingest in its own try/catch with
  logger.LogError so one bad file no longer aborts the whole ingest;
- XAiRAGService: upload the file and add a scope reference
  (providedFor / forProvidedId) for the ingested scope;
- XAiRAGService: remove stale vectors of the same document via
  RemoveVectorsAsync(identifierPrefix) when replaceExisting is set;
- XInMemoryVectorStore: make session retrieval thread-safe via
  lock (found.SyncRoot) and ReferenceEquals check against concurrent removal;
- XAiServiceControllerBase.Ask: pass the attached files to the AI service
  (was files: null) so RAG works on attachments;
- XModelsExtensions: relax ChatWithDocuments ask validation - TopK and
  MinScore are optional again (defaults come from RAGDescriptor);
- XAiModelProxyMiddleware: use logical OR instead of bitwise OR in the
  authentication check;
- XAiEmbeddingServiceBase: do not dispose the embedding generator
  (removed `using` to avoid premature disposal);
- ChatWithDocumentsController: reorder EmbedChunks parameters;
- Remove Interfaces/IXAiEmbeddingServiceControllerBase.cs.
2026-11-02 16:37:57 +03:30
saherelm 726d6ce827 Try to Fix Embeding RAG Persisted Issues ... 2026-11-01 23:12:12 +03:30
saherelm fa1014bf20 Refactoring Services ... 2026-11-01 22:36:20 +03:30
saherelm ce4e5927dd last ... 2026-11-01 18:13:49 +03:30
saherelm 51dddb4b68 last ... 2026-11-01 18:11:26 +03:30
saherelm ce5db9e349 last ... 2026-10-31 17:19:17 +03:30
saherelm c1173042d4 last ... 2026-10-31 05:49:17 +03:30
saherelm ad8ea9c1dd Integrate RAG into Chat Pipeline and Decouple Embedding Service
- AskAsync: accept Guid? projectId / conversationId; resolve defaults;
- AskAsync: ingest attached files into Conversation scope (replaceExisting)
  via IXAiRAGService instead of Upload + Extract + raw content attachment;
- AskAsync: retrieve context (Conversation -> Project -> User -> Global)
  and build a single System message: Introduction + ChatWithDocuments prompt
  + Context block (+ Project prompt);
- XAIServiceBase / XDefaultAiService / XDefaultThinkingAiService:
  inject IXAiRAGService instead of IXFileProvider;
- Add IXAiEmbeddingService + XAiEmbeddingService; remove
  IXDefaultEmbeddingService + XDefaultEmbeddingService;
- XAiEmbeddingServiceBase no longer inherits XAIServiceBase;
  IXAiEmbeddingServiceBase / IXAiEmbeddingServiceControllerBase no longer
  extend chat interfaces; XAiEmbeddingServiceControllerBase derives from
  XBaseIdentityApiV1Controller;
- XAiRAGService: drop IXDefaultAiService dependency (removes circular
  dependency); remove AskWithRAGAsync / AskWithRAGAsEnumerable; add file
  reference (AddReference) for scoped ingests;
- KnowledgeController: remove POST Ask and POST AskStream;
- DI: add AddXRagService() and call it from Startup before AddXAiServices();
- Add XAiApiRagPromptName = "ChatWithDocuments";
- Knowledge scope factories default Type to XAiDefaultKnowledgeType;
- ChatWithDocuments ask request: TopK and MinScore are now required.
BREAKING: /Knowledge/Ask and /Knowledge/AskStream removed;
          IXDefaultEmbeddingService replaced by IXAiEmbeddingService.
2026-10-30 19:46:20 +03:30
saherelm 37d4e622e9 Implement RAG Scopes, Remove ProxyController, Fix Pipeline Order and SSE Format
- RAG: real scopes with identifiers conversation/{id}/, project/{id}/, user/{ownerId}/, global/;
- RAG: ownership checks via GetProject/GetConversation; Global write requires admin role;
- RAG: tiered retrieval Conversation -> Project -> User -> Global (single embedding, dedup, TopK fill);
- RAG: apply Type filter, sanitize file names, enforce MaxFilesPerIngest/MaxFileSizeBytes/MaxDocumentsPerScope;
- RAG: store scope/scopeId/type/ownerId metadata; return it in documents and sources;
- RAG: add MigrateLegacyVectorsAsync + POST /Knowledge/MigrateLegacy ({ownerId}/... -> user/{ownerId}/...);
- Knowledge API: scope/scopeId on Ingest, Documents, DELETE Documents;
- Remove ProxyController (root route "{modelName}/{path}" + AllowAnonymous hijacked all 2-segment paths);
- Startup: ExceptionHandler("/error") + HSTS outside Development; Swagger only in Development;
  static files before routing; CORS before model proxy; add /error endpoint;
- SSE: all stream endpoints use xHttpService XSseExtensions; validate before streaming;
  pre-stream errors return proper HTTP status; remove "Connection: keep-alive";
- Use xAiModels.Constants for XAiKnowledgeScope / Knowledge constants / XOpenAINoKey;
- Register XAiVectorEntityRegisterar in XAiApiDbContext;
- XCodeFileContentExtractor: actually read stream content; drop hard-coded "book.epub".
BREAKING: AskTextStream emits data: {"text":"..."}; AskStream emits data: {json}; both end with event: done.
2026-10-29 19:59:18 +03:30
saherelm d3ecc8feea Last Refactor Works for Improvement ... 2026-10-29 14:17:11 +03:30
saherelm 07a3caa98f last ... 2026-10-28 14:27:06 +03:30
saherelm d68c1367b6 review and fix changelogs overview, uncomplete ... 2026-10-28 00:07:56 +03:30
saherelm 058d8da780 last ... 2026-10-27 05:56:08 +03:30
saherelm 9e82e05bfe Add Persistent Knowledge RAG Service and API
- Add IXAiRAGService and XAiRAGService for Extract -> Chunk -> Embed -> Store;
- Add synchronous and streaming RAG answers with sources;
- Add Knowledge models and KnowledgeController endpoints;
- Register IXAiRAGService as scoped;
- Keep current identifier: {ownerId}/{fileName}#{chunkIndex}.
2026-10-26 17:51:39 +03:30
saherelm fef38cad1b Fix Jinja Conversation Role Alternation in RAG Context History
- Merge Introduction prompt, RAG prompt and context block into one System message;
- Keep the user question as the following User message;
- Prevent consecutive System roles in AskWithContextAsync and AskWithContextAsEnumerable;
- Update the GetContextHistory XML documentation to describe the new message layout;
- Preserve the existing context retrieval and response flow.
- ...
2026-10-26 10:43:17 +03:30
saherelm fa92763baa fix issue in appsettings ... 2026-10-25 22:27:55 +03:30
saherelm 47da04a594 Implement Chat With Documents (In-Memory RAG) ...
- Add XAiDocumentModels (IngestResult, AskRequest, Answer, AnswerChunk, Source, SessionInfo, RAGDescriptor DTOs);
- Add AskWithContextAsync and AskWithContextAsEnumerable (Context Actions) to IXAiServiceBase and XAIServiceBase;
- Add GetContextHistory and BuildContextBlock Helpers for Building RAG Chat History without Persisting;
- Rewrite ChatWithDocumentsController with Ingest, Ask, AskStream (SSE), Get Session and Delete Session Endpoints;
- Add XInMemoryVectorStoreCleanupService (BackgroundService) for Removing Expired Sessions Periodically;
- Add AddXAiChatWithDocuments DI Extension, Register Cleanup HostedService and use it in Startup;
- Add RAGDescriptor Property to XAiApiConfiguration and its Section to appsettings.Development.json;
- Add ChatWithDocuments System Prompt to Prompts in appsettings.Development.json;
- Add IsValid Extension Method for XAiDocumentAskRequest;
- Optimize XInMemoryVectorStore.Search (Query Embedding Converted once) and Refactor Formatting;
- Remove Unused Usings in XAIServiceBase and IXAiServiceBase;
- ...
2026-10-25 22:24:39 +03:30
50 changed files with 7471 additions and 1781 deletions
+1
View File
@@ -1,6 +1,7 @@
#
bin/*
obj/*
Logs
#
Db/*
+11
View File
@@ -40,5 +40,16 @@ namespace xAiApi.Configurations
/// 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();
}
}
+2 -4
View File
@@ -11,17 +11,15 @@ namespace xAiApi.Constants
public const string XDILogTag = "XAiApi";
//
public const string XAiApiRagPromptName = "ChatWithDocuments";
public const string XAiApiIntroductionPromptName = "Introduction";
public const string XAiApiContentExtractionPromptName = "ContentExtraction";
//
public const string XAiDefaultModelName = "Gemma";
public const string XAiDefaultModelName = "Arion";
public const string XAiEmbeddingModelName = "Embed";
public const string XAiDefaultVisionModelName = "Qwen";
public const string XAiDefaultThinkingModelName = "Qwen";
public const string XAiEmbeddingPromptName = "Embedding";
//
public const string XOpenAINoKey = "no-key-required";
}
}
@@ -1,30 +1,27 @@
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityHelper.Controllers;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXDefaultEmbeddingService>
public partial class AccountController : XAccountControllerBase
{
public DefaultEmbeddingController(
ILogger<DefaultEmbeddingController> logger,
IXDefaultEmbeddingService aiService,
//
#region Constructor ...
public AccountController(
ILogger<AccountController> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
aiService,
appConfiguration,
identityProvider,
validationProvider
)
{ }
#endregion
}
}
+649 -21
View File
@@ -1,38 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xAiApi.Interfaces.Extractors;
using xAiModels.Models.Dtos;
using xCommons.Configurations;
using xAiApi.Extensions;
using xCommons.Providers;
using xIdentityService.Controllers;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using 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]
[Route("[controller]")]
public class ChatWithDocumentsController : XBaseIdentityApiV1Controller, IDisposable
public class ChatWithDocumentsController : XBaseIdentityApiV1Controller
{
/// <summary>
/// Default AI Service ...
/// </summary>
private IXDefaultAiService aiService;
private readonly IXAiService aiService;
/// <summary>
/// Text Chunker Service ...
/// </summary>
private readonly IXTextChunker textChunker;
/// <summary>
/// In Memory Vector Store ...
/// </summary>
private IList<XAiVectorDto> vectorStore = [];
private readonly IXInMemoryVectorStore vectorStore;
/// <summary>
/// XAiApi Configuration ...
/// </summary>
private readonly XAiApiConfiguration apiConfiguration;
/// <summary>
/// Embedding Service ...
/// </summary>
private readonly IXDefaultEmbeddingService embeddingService;
private readonly IXAiEmbeddingService embeddingService;
/// <summary>
/// File Context Extractor Service ...
@@ -40,26 +61,633 @@ namespace xAiApi.Controllers
private readonly IXFileContentExtractor fileContentExtractor;
public ChatWithDocumentsController(
IXDefaultAiService aiService,
ILogger<ChatWithDocumentsController> logger,
IXAiService aiService,
IXTextChunker textChunker,
IXInMemoryVectorStore vectorStore,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
IXDefaultEmbeddingService embeddingService,
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>
/// Dispose ...
/// Ingest Files into a (new or existing) In-Memory Session:
/// Extract -> Chunk -> Embed -> Store ...
/// </summary>
public void Dispose()
/// <param name="files"></param>
/// <param name="sessionId">Optional: Add to an Existing Session</param>
/// <param name="ttlMinutes">Optional: Session TTL in Minutes (only for new Session)</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ingest")]
[Consumes("multipart/form-data")]
public async Task<ActionResult<XAiDocumentIngestResult>> Ingest(
[FromForm] IFormFileCollection files,
[FromForm] Guid? sessionId = null,
[FromForm] int? ttlMinutes = null,
CancellationToken cancellationToken = default
)
{
vectorStore.Clear();
//
try
{
//
// Validate ...
if (!files.HasChild())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var ownerId = userInfo.UserId;
//
// Resolve Target Session ...
Guid targetSessionId;
if (sessionId.HasValue && sessionId.Value != Guid.Empty)
{
//
if (!vectorStore.TryGet(sessionId.Value, out _, ownerId))
{
XException.NotFound.Throw();
}
targetSessionId = sessionId.Value;
}
else
{
//
var ttl = TimeSpan.FromMinutes(
ttlMinutes.HasValue && ttlMinutes.Value > 0
? ttlMinutes.Value
: apiConfiguration.RAGDescriptor.DefaultTtlMinutes
);
targetSessionId = vectorStore.CreateSession(ownerId, ttl);
}
//
var result = new XAiDocumentIngestResult
{
SessionId = targetSessionId
};
//
// Extract -> Chunk -> Embed ...
var vectors = new List<XAiVectorDto>();
foreach (var file in files)
{
//
cancellationToken.ThrowIfCancellationRequested();
//
if (file.IsNull() || file.Length == 0)
{
result.SkippedFiles.Add(file?.FileName ?? "(null)");
continue;
}
//
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
if (!fileContentExtractor.CanExtract(mimeType))
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
var text = await ExtractText(file, mimeType, cancellationToken);
if (string.IsNullOrWhiteSpace(text))
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
var chunks = textChunker.Chunk(text, file.FileName);
if (!chunks.HasChild())
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
// Embed in Batches ...
var fileVectors = await EmbedChunks(
chunks: chunks,
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
)
{ }
}
}
+244
View File
@@ -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
}
}
+501
View File
@@ -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;
}
}
}
}
-248
View File
@@ -1,248 +0,0 @@
using System;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading;
using xAiApi.Extensions;
using xCommons.Providers;
using xExceptions.Models;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[AllowAnonymous]
public class ProxyController : XBaseIdentityApiController
{
private readonly IServiceProvider serviceProvider;
private readonly XAiApiConfiguration apiConfiguration;
private readonly IHttpClientFactory httpClientFactory;
public ProxyController(
ILogger<ProxyController> logger,
IServiceProvider serviceProvider,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XAiApiConfiguration apiConfiguration,
IHttpClientFactory httpClientFactory,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
this.serviceProvider = serviceProvider;
this.apiConfiguration = apiConfiguration;
this.httpClientFactory = httpClientFactory;
}
[AcceptVerbs("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD")]
[Route("{modelName}/{path}")]
public async Task Proxy(
[FromRoute] string modelName,
[FromRoute] string path = null,
object body = null,
CancellationToken cancellationToken = default
)
{
//
var descriptor = apiConfiguration.GetModel(modelName);
if (!descriptor.IsValid())
{
//
var error = XException.NotFound.ToXError();
error.Message = $"{error.Message}: {modelName}' is not configured.";
await WriteJsonError(
StatusCodes.Status502BadGateway,
error.ToJSON()
);
//
return;
}
//
var targetUrl = BuildTargetUrl(
remainingPath: path,
modelName: modelName,
query: Request.QueryString
);
var method = new HttpMethod(Request.Method);
using var upstreamRequest = new HttpRequestMessage(method, targetUrl);
//
// Attach Body ...
if (!body.IsNull())
{
//
var json = body.ToJSON();
upstreamRequest.Content = new StringContent(
json,
Encoding.UTF8,
"application/json"
);
}
//
Request.CopyHeaders(
exceptions: null,
dest: upstreamRequest
);
//
var client = httpClientFactory.CreateClient("XAiModelProxy");
client.Timeout = Timeout.InfiniteTimeSpan;
HttpResponseMessage upstreamResponse;
try
{
//
upstreamResponse = await client.SendAsync(
upstreamRequest,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
//
Logger.LogError(ex, "Proxy failed for model {Model}", modelName);
var error = XException.ActionFailed.ToXError();
error.Message = $"{error.Message}: Upstream model is unavailable.";
await WriteJsonError(
StatusCodes.Status502BadGateway,
error.ToJSON()
);
return;
}
//
using (upstreamResponse)
{
//
if (!upstreamResponse.IsSuccessStatusCode)
{
//
var statusCode = (int)upstreamResponse.StatusCode;
//
XError error;
string errorBody;
try
{
//
errorBody = await upstreamResponse.Content
.ReadAsStringAsync();
//
error = errorBody.IsXError()
? errorBody.ToXError()
: XException.BadRequest.ToXError();
}
catch
{
error = XException.BadRequest.ToXError();
}
//
await WriteJsonError(
statusCode: statusCode,
message: error.ToJSON()
);
//
return;
}
//
upstreamResponse.CopyHeaders(
exceptions: null,
response: Response
);
Response.StatusCode = (int)upstreamResponse.StatusCode;
//
using var responseStream = await upstreamResponse.Content.ReadAsStreamAsync();
await responseStream.CopyToAsync(Response.Body, cancellationToken);
}
}
// ============================================================
// Helpers
// ============================================================
private async Task WriteJsonError(
int statusCode,
string message
)
{
//
Response.StatusCode = statusCode;
Response.ContentType = "application/json; charset=utf-8";
//
await Response.WriteAsync(message);
}
private Uri BuildTargetUrl(
string modelName,
string remainingPath = null,
QueryString query = default
)
{
//
// Validate ...
var isValid =
!modelName.IsNullOrEmpty() &&
!apiConfiguration.IsNull() &&
!apiConfiguration.ProxyConfiguration.IsNull() &&
!apiConfiguration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty();
if (!isValid)
{
XException.InvalidArgs.Throw();
}
//
var baseUrls = serviceProvider.GetApplicationUrls().ToArray();
if (!baseUrls.HasChild())
{
XException.InvalidData.Throw();
}
//
var baseUrl = baseUrls[0];
//
var path = $"{baseUrl}/{apiConfiguration.ProxyConfiguration.RoutePrefix.TrimStart('/')}/{modelName}";
if (!remainingPath.IsNullOrEmpty())
{
path += "/" + remainingPath.TrimStart('/');
}
//
var builder = new UriBuilder(path)
{
Query = query.HasValue
? query.Value.TrimStart('?')
: string.Empty
};
//
var result = builder.Uri;
//
return result;
}
}
}
+23 -5
View File
@@ -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.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
{
@@ -41,5 +44,20 @@ namespace xAiApi.Controllers
//
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);
}
}
}
+24
View File
@@ -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 xCommons.Providers;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
@@ -9,12 +8,11 @@ using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
public class DefaultAiController : XAiServiceControllerBase<IXDefaultAiService>
public class XAiController : XAiServiceControllerBase<IXAiService>
{
public DefaultAiController(
ILogger<DefaultAiController> logger,
IXDefaultAiService aiService,
public XAiController(
ILogger<XAiController> logger,
IXAiService aiService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
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
+27 -3
View File
@@ -73,6 +73,20 @@ namespace xAiApi.DI
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>
@@ -82,9 +96,8 @@ namespace xAiApi.DI
)
{
//
source.AddScoped<IXDefaultAiService, XDefaultAiService>();
source.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
source.AddScoped<IXAiService, XAiService>();
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
}
/// <summary>
@@ -134,6 +147,17 @@ namespace xAiApi.DI
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>
+6 -4
View File
@@ -1,12 +1,12 @@
using Microsoft.EntityFrameworkCore;
using xDataService.Db;
using xAiApi.Constants;
using xAiModels.Providers;
using xDataService.Configuration;
using xDataService.Db;
using xTagService.Providers;
using xDataService.Providers;
using xFileService.Providers;
using xStringService.Providers;
using xTagService.Providers;
using xDataService.Configuration;
using Microsoft.EntityFrameworkCore;
namespace xAiApi.Database
{
@@ -38,8 +38,10 @@ namespace xAiApi.Database
nameof(XTagEntityRegisterar),
nameof(XFileEntityRegisterar),
nameof(XStringEntityRegisterar),
nameof(XAiVectorEntityRegisterar),
nameof(XAiMessageEntityRegisterar),
nameof(XAiProjectEntityRegisterar),
nameof(XAiMcpServerEntityRegisterar),
nameof(XAiConversationEntityRegisterar),
]
)
+41 -2
View File
@@ -2,6 +2,7 @@ using System;
using OpenAI;
using System.Linq;
using OllamaSharp;
using xAiApi.Models;
using System.Net.Http;
using xAiApi.Constants;
using xAiModels.Models;
@@ -15,7 +16,6 @@ using xExceptions.Constants;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System.ClientModel.Primitives;
using xAiApi.Models;
namespace xAiApi.Extensions
{
@@ -62,6 +62,23 @@ namespace xAiApi.Extensions
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;
}
/// <summary>
/// Extract Default Model Descriptor ...
/// </summary>
@@ -269,7 +286,7 @@ namespace xAiApi.Extensions
//
// Instance Ollama Client using Custom HttpCLient ...
var openAiClient = new OpenAIClient(
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : apiKey),
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey),
new OpenAIClientOptions
{
Endpoint = url,
@@ -308,5 +325,27 @@ namespace xAiApi.Extensions
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;
// }
}
}
+60
View File
@@ -1,7 +1,11 @@
using System.Linq;
using xIdentityHelper;
using xAiApi.Providers;
using xAiApi.Interfaces;
using xCommons.Extensions;
using xCommons.Authorization;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
@@ -11,6 +15,17 @@ namespace xAiApi.Extensions
{
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>
/// Register Authorization Policies
/// </summary>
@@ -22,6 +37,7 @@ namespace xAiApi.Extensions
)
{
//
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
services.AddAuthorization(options =>
{
//
@@ -35,6 +51,26 @@ namespace xAiApi.Extensions
{
var policyDescriptor = policiesEnumerator.Current;
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())
{
//
var policyDescriptor = policiesEnumerator.Current;
//
// Add Policy to Authorization ...
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())
);
}
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
namespace xAiApi.Interfaces
{
public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase
{ }
}
+2 -3
View File
@@ -1,15 +1,14 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OllamaSharp;
using System.Collections.Generic;
namespace xAiApi.Interfaces
{
/// <summary>
/// Base Embedding Provider Service ...
/// </summary>
public interface IXAiEmbeddingServiceBase : IXAiServiceBase
public interface IXAiEmbeddingServiceBase // : IXAiServiceBase
{
/// <summary>
/// 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
);
}
}
+228
View File
@@ -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
}
}
+102
View File
@@ -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
);
}
}
+5
View File
@@ -0,0 +1,5 @@
namespace xAiApi.Interfaces
{
public interface IXAiService : IXAiServiceBase
{ }
}
+133 -63
View File
@@ -1,6 +1,5 @@
using System;
using xModels.Dtos;
using System.Net.Http;
using System.Threading;
using xAiModels.Models;
using xAiModels.Models.Dtos;
@@ -33,10 +32,12 @@ namespace xAiApi.Interfaces
/// Base Method for Communicate with LLM ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> AskTextAsync(
string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
@@ -44,33 +45,143 @@ namespace xAiApi.Interfaces
/// Base Method for Communicate with LLM ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IAsyncEnumerable<string> AskTextAsEnumerable(
string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Prepare a Message History List for LLM Communication based on Prompt ...
/// Ask a Question By Providing Vector Search Result ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="forcePrompt"></param>
/// <param name="context"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IList<ChatMessage> GetHistory(
string prompt = null,
bool forcePrompt = true
Task<string> AskTextByContextAsync(
string prompt,
IList<XAiVectorSearchResult> context = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <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>
/// <param name="message"></param>
/// <param name="forceMessage"></param>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IList<ChatMessage> GetHistory(
ChatMessage message = null,
bool forceMessage = true
IAsyncEnumerable<string> AskTextByContextAsEnumerable(
string prompt,
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
@@ -95,11 +206,13 @@ namespace xAiApi.Interfaces
/// Load Conversations of Specified AI Project ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XAiConversationDto>> LoadConversations(
Guid projectId,
Guid? projectId,
string ownerId = null,
string connectionId = null,
CancellationToken cancellationToken = default
);
@@ -108,10 +221,14 @@ namespace xAiApi.Interfaces
/// Load Messages of Specified Conversation ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XAiMessageDto>> LoadMessages(
Guid conversationId,
Guid? conversationId,
string ownerId = null,
string connectionId = null,
CancellationToken cancellationToken = default
);
#endregion
@@ -190,13 +307,13 @@ namespace xAiApi.Interfaces
/// <returns></returns>
Task<XAiConversationDto> CreateConversation(
string ownerId,
Guid projectId,
Guid? projectId,
XAiConversationDto item,
string connectionId = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Content Extraction ...
/// <summary>
@@ -209,53 +326,6 @@ namespace xAiApi.Interfaces
Task<string> ExtractContent(
IFormFileCollection files,
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
);
#endregion
-214
View File
@@ -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
}
}
-5
View File
@@ -1,5 +0,0 @@
namespace xAiApi.Interfaces
{
public interface IXDefaultAiService : IXAiServiceBase
{ }
}
-5
View File
@@ -1,5 +0,0 @@
namespace xAiApi.Interfaces
{
public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase
{ }
}
+1 -1
View File
@@ -106,7 +106,7 @@ namespace xAiApi.Middlewares
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
var isAuthenticated =
//
(!apiKey.IsNullOrEmpty()) |
(!apiKey.IsNullOrEmpty()) ||
//
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
;
+208
View File
@@ -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;
}
}
+255
View File
@@ -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; }
}
}
+17
View File
@@ -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; }
}
}
+35
View File
@@ -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;
}
}
+37
View File
@@ -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;
}
}
+5 -1
View File
@@ -1,4 +1,5 @@
using System.Text;
using xLoggingService.DI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
@@ -19,10 +20,13 @@ namespace xAiApi
{
//
var result = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
logging.AddXTelemetryLogger())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
})
.AddXTelemetry();
//
return result;
+1 -1
View File
@@ -21,7 +21,7 @@
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:6001;http://localhost:6000",
"applicationUrl": "https://localhost:6001;http://localhost:6000;https://0.0.0.0:6001;",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -72,7 +72,7 @@ namespace xAiApi.Providers.Extractors
//
var result = await ExtractRichAsync(
fileStream,
"book.epub",
string.Empty,
mimeType,
cancellationToken
);
@@ -112,12 +112,18 @@ namespace xAiApi.Providers.Extractors
detectEncodingFromByteOrderMarks: true
);
//
var content = await reader.ReadToEndAsync();
//
// Normalize line endings for consistent downstream processing ...
result.Text = result.Text?
content = content?
.Replace("\r\n", "\n")
.Replace("\r", "\n");
//
result.Text = content;
//
return result;
}
+1180 -578
View File
File diff suppressed because it is too large Load Diff
@@ -1,25 +1,22 @@
using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xFileService.Interfaces;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using xCommons.Providers;
namespace xAiApi.Providers
{
public class XDefaultEmbeddingService : XAiEmbeddingServiceBase, IXDefaultEmbeddingService
public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService
{
public XDefaultEmbeddingService(
IXFileProvider fileProvider,
public XAiEmbeddingService(
IXAiDataProvider dataProvider,
XAiApiConfiguration configuration,
ILogger<XAiEmbeddingService> logger,
XValidationProvider validationProvider,
ILogger<XDefaultEmbeddingService> logger,
IXFileContentExtractor fileContentExtractor
) : base(
fileProvider,
dataProvider,
configuration,
validationProvider,
+14 -16
View File
@@ -7,7 +7,7 @@ using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xAiService.Helpers;
using xAiModels.Helpers;
using System.ClientModel;
using xCommons.Providers;
using xCommons.Extensions;
@@ -17,7 +17,6 @@ using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using xFileService.Interfaces;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
@@ -29,28 +28,23 @@ namespace xAiApi.Providers
/// <summary>
/// Base Embedding Provider Service ...
/// </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 IXAiDataProvider dataProvider;
private readonly XAiApiConfiguration configuration;
private readonly XValidationProvider validationProvider;
private readonly ILogger<XAiEmbeddingServiceBase> logger;
private readonly IXFileContentExtractor fileContentExtractor;
protected XAiEmbeddingServiceBase(
IXFileProvider fileProvider,
IXAiDataProvider dataProvider,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
ILogger<XAiEmbeddingServiceBase> logger,
IXFileContentExtractor fileContentExtractor,
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
) : base(
fileProvider,
dataProvider,
logger,
configuration,
validationProvider,
fileContentExtractor,
null
)
{
//
@@ -61,10 +55,14 @@ namespace xAiApi.Providers
XException.InvalidConfiguration.Throw();
}
this.fileProvider = fileProvider;
this.dataProvider = dataProvider;
this.configuration = configuration;
this.validationProvider = validationProvider;
//
this.logger = logger;
this.fileContentExtractor = fileContentExtractor;
this.embeddingModelName = embeddingModelName;
}
/// <summary>
@@ -86,7 +84,7 @@ namespace xAiApi.Providers
}
//
using var generator = GetEmbeddingGenerator();
var generator = GetEmbeddingGenerator();
//
GeneratedEmbeddings<Embedding<float>> response = null;
@@ -195,7 +193,7 @@ namespace xAiApi.Providers
case XAiModelProviderType.OpenAI:
//
var openAiClient = new OpenAIClient(
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : descriptor.ApiKey),
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
new OpenAIClientOptions
{
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 xAiModels.Interfaces;
using xAiApi.Configurations;
using xFileService.Interfaces;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers
{
public class XDefaultAiService : XAIServiceBase, IXDefaultAiService
public class XAiService : XAIServiceBase, IXAiService
{
public XDefaultAiService(
IXFileProvider fileProvider,
public XAiService(
IXAiRAGService ragProvider,
IXAiDataProvider dataProvider,
ILogger<XDefaultAiService> logger,
ILogger<XAiService> logger,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
IXAiMcpServerProvider mcpServerProvider,
IXFileContentExtractor fileContentExtractor
) : base(
fileProvider,
ragProvider,
dataProvider,
logger,
configuration,
validationProvider,
mcpServerProvider,
fileContentExtractor,
XAiApiConstants.XAiDefaultModelName
)
+4 -3
View File
@@ -4,7 +4,6 @@ using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using Microsoft.Extensions.AI;
using xFileService.Interfaces;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
@@ -13,20 +12,22 @@ namespace xAiApi.Providers
public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
{
public XDefaultThinkingAiService(
IXFileProvider fileProvider,
IXAiRAGService ragProvider,
IXAiDataProvider dataProvider,
ILogger<XAIServiceBase> logger,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
IXAiMcpServerProvider mcpServerProvider,
IXFileContentExtractor fileContentExtractor,
ReasoningEffort effort = ReasoningEffort.Medium,
ReasoningOutput output = ReasoningOutput.Full
) : base(
fileProvider,
ragProvider,
dataProvider,
logger,
configuration,
validationProvider,
mcpServerProvider,
fileContentExtractor,
XAiApiConstants.XAiDefaultThinkingModelName
)
+80 -23
View File
@@ -1,8 +1,8 @@
using System;
using System.Linq;
using xAiApi.Models;
using xAiService.Helpers;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using System.Collections.Concurrent;
@@ -99,10 +99,10 @@ namespace xAiApi.Providers
}
public IList<XAiVectorSearchResult> Search(
Guid sessionId,
ReadOnlyMemory<float> queryEmbedding,
int topK = 5,
float minScore = 0f,
Guid sessionId,
ReadOnlyMemory<float> queryEmbedding,
int topK = 5,
float minScore = 0f,
string ownerId = null
)
{
@@ -121,6 +121,7 @@ namespace xAiApi.Providers
}
//
var query = queryEmbedding.ToArray();
lock (session.SyncRoot)
{
//
@@ -135,7 +136,7 @@ namespace xAiApi.Providers
//
var score = VectorHelper.CosineSimilarity(
queryEmbedding.ToArray(),
query,
vector.Embedding.ToArray()
);
@@ -143,41 +144,75 @@ namespace xAiApi.Providers
if (score >= minScore)
{
//
result.Add(new XAiVectorSearchResult {
result.Add(new XAiVectorSearchResult
{
Score = score,
Id = vector.Id,
Text = vector.Text,
Metadata = vector.Metadata,
Identifier = vector.Identifier,
Id = vector.Id,
Text = vector.Text,
Metadata = vector.Metadata,
Identifier = vector.Identifier,
});
}
}
}
//
return [.. result
result = [.. result
.OrderByDescending(x => x.Score)
.Take(topK)];
//
return result;
}
public bool TryGet(
Guid sessionId,
out XAiDocumentSession session,
Guid sessionId,
out XAiDocumentSession session,
string ownerId = null
)
{
//
session = null;
XAiDocumentSession found;
if (!sessions.TryGetValue(sessionId, out found) || !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;
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)
public bool Remove(
Guid sessionId,
string ownerId = null
)
{
//
XAiDocumentSession session;
if (!TryGet(sessionId, out session, ownerId)) return false;
return sessions.TryRemove(sessionId, out session);
@@ -185,13 +220,35 @@ namespace xAiApi.Providers
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;
}
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(); }
//
#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 ...
}
}
}
}
+62 -16
View File
@@ -3,6 +3,7 @@ using System.IO;
using xAiApi.DI;
using System.Linq;
using xAiModels.DI;
using xAiService.DI;
using xTagService.DI;
using System.Net.Http;
using xAiApi.Database;
@@ -14,10 +15,12 @@ using Newtonsoft.Json;
using System.Reflection;
using xAiApi.Extensions;
using xStringService.DI;
using xLoggingService.DI;
using xStorageService.DI;
using xIdentityService.DI;
using xDataService.Models;
using xCommons.Extensions;
using xAiModels.Constants;
using xPushService.Helpers;
using xCommons.Configurations;
using System.Collections.Generic;
@@ -68,6 +71,10 @@ namespace xAiApi
services.AddXAppConfiguration(Configuration);
var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
//
// Register Logging Service ...
services.AddXLoggingService(Configuration);
//
// Register Allowed Origins ...
services.AddXCors(appConfiguration.AllowedOrigins);
@@ -183,6 +190,10 @@ namespace xAiApi
// Register XAiApi Configuration ...
services.AddXAiApiConfiguration(Configuration);
//
// Register MCP Server Provider ...
services.AddXAiMcpServerProvider();
//
// Register File Content Extractor Services ...
services.AddXAiFileContentExtractors();
@@ -192,39 +203,68 @@ namespace xAiApi
services.AddXAiTextChunker();
//
// Register In-Memory Vector Store Service ...
services.AddXAiInMemoryVectorStore();
// 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.
var isDevelopmentEnvironment = false;
if (env.IsDevelopment())
// Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors
// -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ...
var isDevelopmentEnvironment = env.IsDevelopment();
if (isDevelopmentEnvironment)
{
isDevelopmentEnvironment = true;
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute);
app.UseHsts();
}
//
// Use Swagger Middleware ...
app.UseXSwagger();
// Setting Environment in App Confiuration ...
app.AddEnvironmentToXAppConfiguration(env.EnvironmentName);
//
// Force Https Redirection ...
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();
//
// Enable Model Proxy ...
// Enable Model Proxy (Handles its own Authentication) ...
app.UseXAiModelProxy();
//
@@ -232,7 +272,14 @@ namespace xAiApi
app.UseRouting();
//
// Use xIdentityService ...
// Using Request Logging ...
if (!isDevelopmentEnvironment)
{
app.UseXRequestLogger();
}
//
// Use xIdentityService (Authentication) ...
app.UseXIdentityService();
//
@@ -246,11 +293,7 @@ namespace xAiApi
});
//
// Use Storage Service ...
app.UseXStorageService();
//
// Use PushService ...
// Use PushService (Legacy UseSignalR -> Registers its own Router) ...
var pushHelper = new XPushServiceHelper();
app.UseXPushService(pushHelper);
@@ -291,3 +334,6 @@ namespace xAiApi
}
}
}
+160 -124
View File
@@ -1,125 +1,161 @@
{
"AllowedOrigins": [
"http://localhost:5000",
"https://localhost:5001",
"http://api.saherelm.ir",
"https://api.saherelm.ir",
"http://api.saherelmhub.ir",
"https://api.saherelmhub.ir"
],
"IdentityServiceConfiguration": {
"Authority": "https://localhost:4001",
"ApiName": "xSaherElmAPI",
"ApiSecret": "s@H@1694056",
"ClientId": "xSaherElmAPIClient",
"ClientSecret": "s@H@1694056",
"XPoweredValue": "SaherElmITCenter",
"XRevisionSecretKey": "SaherElmITCenter@1694056",
"DefaultClientTimeout": -1
},
"StorageConfiguration": {
"Authority": "https://localhost:5001",
"IdentityAuthority": "https://localhost:5001",
"Storage": "Storage",
"Temp": "Temp",
"Thumb": "Thumb",
"Uploads": "Uploads",
"Widgets": "Widgets",
"Image": "Image",
"Audio": "Audio",
"Video": "Video",
"Document": "Document",
"FilePrefix": "xSaherElm_",
"ThumbPrefix": "Thumb_",
"ThumbSize": 512,
"ThumbQuality": 72,
"MaxFileSize": 41943040
},
"AiApiConfiguration": {
"Models": [
{
"ApiKey": "",
"Name": "Gemma",
"LLM": "gemma3:1b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1112/v1"
},
{
"ApiKey": "",
"Name": "Qwen",
"LLM": "qwen-9b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1114/v1"
},
{
"ApiKey": "",
"Name": "Embed",
"LLM": "bge-m3",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1113/v1"
}
],
"Prompts": [
{
"Name": "Introduction",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.",
"Description": "",
"Params": []
},
{
"Name": "ContentExtraction",
"Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.",
"Description": "",
"Params": []
},
{
"Name": "Embedding",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
"Description": "",
"Params": []
}
],
"OCR": {
"DataPath": "Models",
"EngineMode": "LstmOnly",
"EnableOcrFallback": true,
"DefaultLanguage": "fas+eng"
},
"Transcript": {
"Language": "fa",
"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": "#"
}
},
"Logging": {
"LogLevel": {
"Microsoft": "Warning",
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
"AllowedOrigins": [
"http://127.0.0.1:5500",
"http://localhost:5000",
"https://localhost:5001",
"http://api.saherelm.ir",
"https://api.saherelm.ir",
"http://api.saherelmhub.ir",
"http://192.168.11.29:5173",
"http://192.168.11.29:5174",
"https://api.saherelmhub.ir"
],
"IdentityServiceConfiguration": {
"Authority": "https://localhost:4001",
"ApiName": "xSaherElmAPI",
"ApiSecret": "s@H@1694056",
"ClientId": "xSaherElmAPIClient",
"ClientSecret": "s@H@1694056",
"XPoweredValue": "SaherElmITCenter",
"XRevisionSecretKey": "SaherElmITCenter@1694056",
"DefaultClientTimeout": -1
},
"StorageConfiguration": {
"Authority": "https://localhost:5001",
"IdentityAuthority": "https://localhost:5001",
"Storage": "Storage",
"Temp": "Temp",
"Thumb": "Thumb",
"Uploads": "Uploads",
"Widgets": "Widgets",
"Image": "Image",
"Audio": "Audio",
"Video": "Video",
"Document": "Document",
"FilePrefix": "xSaherElm_",
"ThumbPrefix": "Thumb_",
"ThumbSize": 512,
"ThumbQuality": 72,
"MaxFileSize": 41943040
},
"AiApiConfiguration": {
"Models": [
{
"Name": "Arion",
"Provider": "OpenAI",
"LLM": "claude-fable-5-1",
"Url": "https://arionhub.pro/v1",
"ApiKey": "sk-AKJGD8J9gOCrQgc5oWPGtRGUo25PnnQGnMoipzdliYHa3otZ"
},
{
"ApiKey": "",
"Name": "Gemma_BKP",
"LLM": "gemma3:1b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1112/v1"
},
{
"ApiKey": "",
"Name": "Qwen",
"LLM": "qwen-9b",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1114/v1"
},
{
"ApiKey": "",
"Name": "Embed",
"LLM": "bge-m3",
"Provider": "OpenAI",
"Url": "http://178.131.88.93:1113/v1"
}
],
"Prompts": [
{
"Name": "Introduction",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.",
"Description": "",
"Params": []
},
{
"Name": "ContentExtraction",
"Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.",
"Description": "",
"Params": []
},
{
"Name": "Embedding",
"Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
"Description": "",
"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": {
"DataPath": "Models",
"EngineMode": "LstmOnly",
"EnableOcrFallback": true,
"DefaultLanguage": "fas+eng"
},
"Transcript": {
"Language": "fa",
"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": {
"LogLevel": {
"Microsoft": "Warning",
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
+37 -1
View File
@@ -4,6 +4,7 @@
"DefaultLanguage": "fa-IR",
"XPoweredValue": "SaherElmITCenter",
"WelcomeMessage": "Welcome to xSaherElm Project's AI API",
"DefaultCacheTtlMinutes": 10,
"AllowedOrigins": [
"http://api.saherelm.ir",
"https://api.saherelm.ir",
@@ -18,6 +19,9 @@
"Name": "Hadi Khazaee Asl",
"Email": "hadi_khazaee_asl@yahoo.com",
"Url": "https://www.saherelm.ir"
},
"DefaultValues": {
"version": "1.0"
}
},
"HttpServiceConfiguration": {
@@ -48,6 +52,38 @@
"BaseRoute": "hubs",
"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": {
"LogLevel": {
"Default": "Information",
@@ -55,4 +91,4 @@
}
},
"AllowedHosts": "*"
}
}
+3 -2
View File
@@ -7,7 +7,6 @@
<Authors>Hadi Khazaee Asl</Authors>
<Company>SaherElm IT Center</Company>
<PackageId>xSaherElm.xAiApi</PackageId>
<!-- <TargetFramework>net8.0</TargetFramework> -->
<TargetFramework>netcoreapp3.1</TargetFramework>
<Description>
@@ -18,8 +17,8 @@
<PackageIcon>icon.png</PackageIcon>
<!-- Fix Duplicate TargetFramework Issue -->
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
</PropertyGroup>
<!-- Icon Handling -->
@@ -41,6 +40,7 @@
<ProjectReference Include="../Modules/xHttpService/xHttpService.csproj" />
<ProjectReference Include="../Modules/xFileService/xFileService.csproj" />
<ProjectReference Include="../Modules/xStorageService/xStorageService.csproj" />
<ProjectReference Include="..\Modules\xLoggingService\xLoggingService.csproj" />
<ProjectReference Include="../Modules/xIdentityHelper/xIdentityHelper.csproj" />
</ItemGroup>
@@ -57,6 +57,7 @@
<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="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" />