Compare commits

...
17 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
21 changed files with 1791 additions and 619 deletions
+1
View File
@@ -1,6 +1,7 @@
# #
bin/* bin/*
obj/* obj/*
Logs
# #
Db/* Db/*
+6
View File
@@ -45,5 +45,11 @@ namespace xAiApi.Configurations
/// RAG Configuration ... /// RAG Configuration ...
/// </summary> /// </summary>
public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
/// <summary>
/// DateTime Configuration ...
/// </summary>
/// <returns></returns>
public XDateTimeDescriptor DateTime { get; set; } = new();
} }
} }
+1 -1
View File
@@ -16,7 +16,7 @@ namespace xAiApi.Constants
public const string XAiApiContentExtractionPromptName = "ContentExtraction"; public const string XAiApiContentExtractionPromptName = "ContentExtraction";
// //
public const string XAiDefaultModelName = "Gemma"; public const string XAiDefaultModelName = "Arion";
public const string XAiEmbeddingModelName = "Embed"; public const string XAiEmbeddingModelName = "Embed";
public const string XAiDefaultVisionModelName = "Qwen"; public const string XAiDefaultVisionModelName = "Qwen";
public const string XAiDefaultThinkingModelName = "Qwen"; public const string XAiDefaultThinkingModelName = "Qwen";
-433
View File
@@ -1,433 +0,0 @@
using System;
using System.Linq;
using xModels.Dtos;
using xModels.Base;
using xIdentityHelper;
using System.Threading;
using xCommons.Providers;
using xAiModels.Models.Dtos;
using xAiModels.Controllers;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xAiModels.Interfaces.Dtos;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore.Query;
namespace xAiApi.Controllers
{
[Authorize]
public class McpServerController : XAiMcpServerControllerBase
{
public McpServerController(
ILogger<McpServerController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider,
IXAiMcpServerRepositoryService repositoryService,
Func<IQueryable<XAiMcpServer>, IOrderedQueryable<XAiMcpServer>> defaultOrderBuilder = null,
Func<IQueryable<XAiMcpServer>, IIncludableQueryable<XAiMcpServer, object>> defaultIncludeBuilder = null
) : base(
logger,
appConfiguration,
validationProvider,
repositoryService,
defaultOrderBuilder,
defaultIncludeBuilder
)
{ }
//
#region Actions ...
//
#region Add ...
/// <summary>
/// Add Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Add(
[FromBody] XAiMcpServerDto item,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Add(
item: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Add or Update Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AddOrUpdate")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> AddOrUpdate(
[FromBody] XAiMcpServerDto item,
CancellationToken cancellationToken = default
)
{
//
var result = await base.AddOrUpdate(
item: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Add a Collection of Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AddMany")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult> AddMany(
[FromBody] XBaseRangeRequest<XAiMcpServerDto> request,
CancellationToken cancellationToken = default
)
{
//
var result = await base.AddMany(
request: request,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
//
#region Retrieve ...
/// <summary>
/// Get Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Get(
[FromRoute] Guid id,
[FromQuery] bool ignoreSoftDeleteds = true,
[FromQuery] bool useDefaultIncludes = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Get(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds,
useDefaultIncludes: useDefaultIncludes
);
//
return result;
}
/// <summary>
/// Get All Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultOrders"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> GetAll(
[FromQuery] bool ignoreSoftDeleteds = true,
[FromQuery] bool useDefaultOrders = false,
[FromQuery] bool useDefaultIncludes = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.GetAll(
useDefaultOrders: useDefaultOrders,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds,
useDefaultIncludes: useDefaultIncludes
);
//
return result;
}
/// <summary>
/// Find Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("FindOne/{query}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> FindOne(
[FromRoute] string query,
[FromQuery] bool ignoreSoftDeleteds = true,
[FromQuery] bool useDefaultIncludes = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.FindOne(
query: query,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds,
useDefaultIncludes: useDefaultIncludes
);
//
return result;
}
/// <summary>
/// Find Many Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultOrders"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("FindMany/{query}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> FindMany(
[FromRoute] string query,
[FromQuery] bool ignoreSoftDeleteds = true,
[FromQuery] bool useDefaultOrders = false,
[FromQuery] bool useDefaultIncludes = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.FindMany(
query: query,
useDefaultOrders: useDefaultOrders,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds,
useDefaultIncludes: useDefaultIncludes
);
//
return result;
}
/// <summary>
/// Retrieve Items Based on Query Mechanism ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultOrders"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Query")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XQueryResult<XAiMcpServerDto>>> Query(
[FromQuery] XQuery query,
[FromQuery] bool ignoreSoftDeleteds = true,
[FromQuery] bool useDefaultOrders = false,
[FromQuery] bool useDefaultIncludes = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Query(
query: query,
useDefaultOrders: useDefaultOrders,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds,
useDefaultIncludes: useDefaultIncludes
);
//
return result;
}
#endregion
//
#region Update ...
/// <summary>
/// Update Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPut("{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Update(
[FromRoute] Guid id,
[FromBody] XAiMcpServerDto item,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Update(
id: id,
item: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Update a Collection of items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("UpdateMany")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<bool>> UpdateMany(
[FromBody] XBaseRangeRequest<XAiMcpServerDto> request,
CancellationToken cancellationToken = default
)
{
//
var result = await base.UpdateMany(
request: request,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
//
#region Exists ...
/// <summary>
///Check an Item Exists or not ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("{id}/IsExists")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<bool>> IsExists(
[FromRoute] Guid id,
[FromQuery] bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = await base.IsExists(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
return result;
}
#endregion
//
#region Remove ...
/// <summary>
/// Remove an Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpDelete("{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Remove(
[FromRoute] Guid id,
[FromQuery] bool softDelete = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Remove(
id: id,
softDelete: softDelete,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Remove Many Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="request"></param>
/// <param name="softDelete"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("RemoveMany")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult> RemoveMany(
[FromBody] XBaseRangeRequest<XAiMcpServerDto> request,
[FromQuery] bool softDelete = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.RemoveMany(
request: request,
softDelete: softDelete,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
#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;
}
}
}
}
+155 -17
View File
@@ -67,9 +67,13 @@ namespace xAiApi.Controllers
// Validate ... // Validate ...
ValidationProvider.NotEmpty(question); ValidationProvider.NotEmpty(question);
//
var userInfo = await GetUserInfo();
// //
var result = await aiService.AskTextAsync( var result = await aiService.AskTextAsync(
prompt: question, prompt: question,
userInfo: userInfo,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -112,9 +116,13 @@ namespace xAiApi.Controllers
// Configure SSE Response ... // Configure SSE Response ...
Response.PrepareSseResponse(); Response.PrepareSseResponse();
//
var userInfo = await GetUserInfo();
// //
var enumerable = aiService.AskTextAsEnumerable( var enumerable = aiService.AskTextAsEnumerable(
prompt: question, prompt: question,
userInfo: userInfo,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -324,7 +332,7 @@ namespace xAiApi.Controllers
files: null, files: null,
topK: request.TopK, topK: request.TopK,
userInfo: userInfo, userInfo: userInfo,
type: request.Type, type: request.Type,
prompt: request.Prompt, prompt: request.Prompt,
minScore: request.MinScore, minScore: request.MinScore,
connectionId: connectionId, connectionId: connectionId,
@@ -381,7 +389,7 @@ namespace xAiApi.Controllers
files: null, files: null,
topK: request.TopK, topK: request.TopK,
userInfo: userInfo, userInfo: userInfo,
type: request.Type, type: request.Type,
prompt: request.Prompt, prompt: request.Prompt,
minScore: request.MinScore, minScore: request.MinScore,
connectionId: connectionId, connectionId: connectionId,
@@ -466,7 +474,7 @@ namespace xAiApi.Controllers
files: files, files: files,
topK: request.TopK, topK: request.TopK,
userInfo: userInfo, userInfo: userInfo,
type: request.Type, type: request.Type,
prompt: request.Prompt, prompt: request.Prompt,
minScore: request.MinScore, minScore: request.MinScore,
connectionId: connectionId, connectionId: connectionId,
@@ -524,10 +532,12 @@ namespace xAiApi.Controllers
files: files, files: files,
topK: request.TopK, topK: request.TopK,
userInfo: userInfo, userInfo: userInfo,
type: request.Type, type: request.Type,
prompt: request.Prompt, prompt: request.Prompt,
minScore: request.MinScore, minScore: request.MinScore,
connectionId: connectionId, connectionId: connectionId,
extractFileContents: false,
addFilesToKnowledge: false,
projectId: request.ProjectId, projectId: request.ProjectId,
cancellationToken: cancellationToken, cancellationToken: cancellationToken,
conversationId: request.ConversationId conversationId: request.ConversationId
@@ -626,7 +636,7 @@ namespace xAiApi.Controllers
[Authorize(Policy = XPolicies.EnabledUser)] [Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Projects/{projectId}/Conversations")] [HttpGet("Projects/{projectId}/Conversations")]
public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations( public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
[FromRoute] Guid projectId, [FromRoute] Guid? projectId,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
@@ -634,12 +644,44 @@ namespace xAiApi.Controllers
try try
{ {
// //
// Validate ... var userInfo = await GetUserInfo();
if (projectId.IsDefaultGuid()) var connectionId = GetConnectionId();
{
XException.InvalidArgs.Throw();
}
//
var result = await aiService.LoadConversations(
projectId: projectId,
ownerId: userInfo.UserId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Retrieve Specified AI Project's Conversations ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Projects/Conversations")]
public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadProjectConversations(
[FromQuery] Guid? projectId,
CancellationToken cancellationToken = default
)
{
//
try
{
// //
var userInfo = await GetUserInfo(); var userInfo = await GetUserInfo();
var connectionId = GetConnectionId(); var connectionId = GetConnectionId();
@@ -647,6 +689,7 @@ namespace xAiApi.Controllers
// //
var result = await aiService.LoadConversations( var result = await aiService.LoadConversations(
projectId: projectId, projectId: projectId,
ownerId: userInfo.UserId,
connectionId: connectionId, connectionId: connectionId,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -671,7 +714,7 @@ namespace xAiApi.Controllers
[Authorize(Policy = XPolicies.EnabledUser)] [Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Conversations/{conversationId}/Messages")] [HttpGet("Conversations/{conversationId}/Messages")]
public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages( public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
[FromRoute] Guid conversationId, [FromRoute] Guid? conversationId,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
@@ -679,14 +722,52 @@ namespace xAiApi.Controllers
try try
{ {
// //
// Validate ... var userInfo = await GetUserInfo();
if (conversationId.IsDefaultGuid()) var connectionId = GetConnectionId();
{
XException.InvalidArgs.Throw();
}
// //
var result = await aiService.LoadMessages( var result = await aiService.LoadMessages(
ownerId: userInfo.UserId,
connectionId: connectionId,
conversationId: conversationId,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Retrieve Specified AI Conversation's Messages ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Conversations/Messages")]
public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadConversationMessages(
[FromQuery] Guid? conversationId,
CancellationToken cancellationToken = default
)
{
//
try
{
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
var result = await aiService.LoadMessages(
ownerId: userInfo.UserId,
connectionId: connectionId,
conversationId: conversationId, conversationId: conversationId,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -941,6 +1022,63 @@ namespace xAiApi.Controllers
return result; return result;
} }
} }
/// <summary>
/// Create an AI Conversation ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpPost("Projects/Conversations")]
public async Task<ActionResult<XAiConversationDto>> CreateProjectConversation(
[FromQuery] Guid? projectId,
[FromBody] XAiConversationDto item,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (item.IsNullOrDefault())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
// Update Required Params ...
item.OwnerId = userInfo.UserId;
if (!item.IsValidForAddOrUpdate())
{
XException.InvalidData.Throw();
}
//
var result = await aiService.CreateConversation(
item: item,
projectId: projectId,
ownerId: userInfo.UserId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion #endregion
// //
+22
View File
@@ -325,5 +325,27 @@ namespace xAiApi.Extensions
return result; return result;
} }
// public static IList<AITool> ToAITools(this IList<XAiMcpToolDefinition> source)
// {
// //
// var result = new List<AITool>();
// //
// foreach (var tool in source)
// {
// //
// var declaration = AIFunctionFactory.CreateDeclaration(
// name: tool.Name,
// jsonSchema: tool.InputSchema,
// description: tool.Description
// );
// //
// result.Add(declaration);
// }
// //
// return result;
// }
} }
} }
+60
View File
@@ -1,7 +1,11 @@
using System.Linq;
using xIdentityHelper; using xIdentityHelper;
using xAiApi.Providers;
using xAiApi.Interfaces;
using xCommons.Extensions; using xCommons.Extensions;
using xCommons.Authorization; using xCommons.Authorization;
using System.Collections.Generic; using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
@@ -11,6 +15,17 @@ namespace xAiApi.Extensions
{ {
public static class XProgramExtensions public static class XProgramExtensions
{ {
/// <summary>
/// Register MCP Server Provider ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiMcpServerProvider(
this IServiceCollection source
)
{
source.AddScoped<IXAiMcpServerProvider, XAiMcpServerProvider>();
}
/// <summary> /// <summary>
/// Register Authorization Policies /// Register Authorization Policies
/// </summary> /// </summary>
@@ -22,6 +37,7 @@ namespace xAiApi.Extensions
) )
{ {
// //
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
services.AddAuthorization(options => services.AddAuthorization(options =>
{ {
// //
@@ -35,6 +51,26 @@ namespace xAiApi.Extensions
{ {
var policyDescriptor = policiesEnumerator.Current; var policyDescriptor = policiesEnumerator.Current;
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
//
// Add Policy to Policy Handler ...
if (!policyHandler.IsNull())
{
//
// Check Policy is RequiredRole Policy ...
var roleRequirements = policyDescriptor.Value.Requirements
.OfType<RequiredRolesRequirement>()
.FirstOrDefault();
if (!roleRequirements.IsNull() &&
roleRequirements.Roles.HasChild())
{
//
policyHandler.AddPolicy(
policy: policyDescriptor.Key.ToNormalString(),
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
);
}
}
} }
} }
} }
@@ -49,8 +85,32 @@ namespace xAiApi.Extensions
{ {
while (policiesEnumerator.MoveNext()) while (policiesEnumerator.MoveNext())
{ {
//
var policyDescriptor = policiesEnumerator.Current; var policyDescriptor = policiesEnumerator.Current;
//
// Add Policy to Authorization ...
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
//
// Add Policy to Policy Handler ...
if (!policyHandler.IsNull())
{
//
// Check Policy is RequiredRole Policy ...
var roleRequirements = policyDescriptor.Value.Requirements
.OfType<RequiredRolesRequirement>()
.FirstOrDefault();
if (!roleRequirements.IsNull() &&
roleRequirements.Roles.HasChild())
{
//
policyHandler.AddPolicy(
policy: policyDescriptor.Key.ToNormalString(),
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
);
}
}
} }
} }
} }
+36 -11
View File
@@ -1,17 +1,20 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using ModelContextProtocol.Client;
using xAiModels.Models.Dtos;
using xAiModels.Models.Entities;
using xIdentityModels.Models;
using xModels.Dtos; 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 namespace xAiApi.Interfaces
{ {
/// <summary>
/// MCP Manager / Provider ...
/// </summary>
public interface IXAiMcpServerProvider public interface IXAiMcpServerProvider
{ {
// //
@@ -23,7 +26,7 @@ namespace xAiApi.Interfaces
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<IList<McpClientTool>> GetAvailableToolsAsync( Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false, bool forceOwner = false,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -33,18 +36,27 @@ namespace xAiApi.Interfaces
/// Test Specified Mcp Server ... /// Test Specified Mcp Server ...
/// </summary> /// </summary>
/// <param name="server"></param> /// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<string> TestServerAsync( Task<string> TestServerAsync(
XAiMcpServerDto server, XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
/// <summary> /// <summary>
/// Force Refresh Mcp Servers ... /// Force Refresh Mcp Servers ...
/// </summary> /// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task RefreshAsync(); Task RefreshAsync(
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
#endregion #endregion
// //
@@ -64,6 +76,19 @@ namespace xAiApi.Interfaces
CancellationToken cancellationToken = default 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> /// <summary>
/// Update Specified Mcp Server ... /// Update Specified Mcp Server ...
/// </summary> /// </summary>
+21 -3
View File
@@ -32,10 +32,12 @@ namespace xAiApi.Interfaces
/// Base Method for Communicate with LLM ... /// Base Method for Communicate with LLM ...
/// </summary> /// </summary>
/// <param name="prompt"></param> /// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<string> AskTextAsync( Task<string> AskTextAsync(
string prompt, string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
@@ -43,10 +45,12 @@ namespace xAiApi.Interfaces
/// Base Method for Communicate with LLM ... /// Base Method for Communicate with LLM ...
/// </summary> /// </summary>
/// <param name="prompt"></param> /// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
IAsyncEnumerable<string> AskTextAsEnumerable( IAsyncEnumerable<string> AskTextAsEnumerable(
string prompt, string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
@@ -128,6 +132,8 @@ namespace xAiApi.Interfaces
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="conversationId"></param> /// <param name="conversationId"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param> /// <param name="files"></param>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
@@ -140,6 +146,8 @@ namespace xAiApi.Interfaces
Guid? projectId = null, Guid? projectId = null,
Guid? conversationId = null, Guid? conversationId = null,
string connectionId = null, string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null, IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -155,6 +163,8 @@ namespace xAiApi.Interfaces
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="conversationId"></param> /// <param name="conversationId"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param> /// <param name="files"></param>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
@@ -167,6 +177,8 @@ namespace xAiApi.Interfaces
Guid? projectId = null, Guid? projectId = null,
Guid? conversationId = null, Guid? conversationId = null,
string connectionId = null, string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null, IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -194,11 +206,13 @@ namespace xAiApi.Interfaces
/// Load Conversations of Specified AI Project ... /// Load Conversations of Specified AI Project ...
/// </summary> /// </summary>
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<XAiConversationDto>> LoadConversations( Task<IEnumerable<XAiConversationDto>> LoadConversations(
Guid projectId, Guid? projectId,
string ownerId = null,
string connectionId = null, string connectionId = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
@@ -207,10 +221,14 @@ namespace xAiApi.Interfaces
/// Load Messages of Specified Conversation ... /// Load Messages of Specified Conversation ...
/// </summary> /// </summary>
/// <param name="conversationId"></param> /// <param name="conversationId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<XAiMessageDto>> LoadMessages( Task<IEnumerable<XAiMessageDto>> LoadMessages(
Guid conversationId, Guid? conversationId,
string ownerId = null,
string connectionId = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
#endregion #endregion
@@ -289,7 +307,7 @@ namespace xAiApi.Interfaces
/// <returns></returns> /// <returns></returns>
Task<XAiConversationDto> CreateConversation( Task<XAiConversationDto> CreateConversation(
string ownerId, string ownerId,
Guid projectId, Guid? projectId,
XAiConversationDto item, XAiConversationDto item,
string connectionId = null, string connectionId = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
+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;
}
}
+5 -1
View File
@@ -1,4 +1,5 @@
using System.Text; using System.Text;
using xLoggingService.DI;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
@@ -19,10 +20,13 @@ namespace xAiApi
{ {
// //
var result = Host.CreateDefaultBuilder(args) var result = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
logging.AddXTelemetryLogger())
.ConfigureWebHostDefaults(webBuilder => .ConfigureWebHostDefaults(webBuilder =>
{ {
webBuilder.UseStartup<Startup>(); webBuilder.UseStartup<Startup>();
}); })
.AddXTelemetry();
// //
return result; return result;
+1 -1
View File
@@ -21,7 +21,7 @@
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "weatherforecast", "launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:6001;http://localhost:6000", "applicationUrl": "https://localhost:6001;http://localhost:6000;https://0.0.0.0:6001;",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
+366 -32
View File
@@ -1,10 +1,12 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Text;
using xModels.Dtos; using xModels.Dtos;
using xAiApi.Models; using xAiApi.Models;
using System.Threading; using System.Threading;
using xAiApi.Constants; using xAiApi.Constants;
using xAiModels.Models; using xAiModels.Models;
using TimeZoneConverter;
using xAiApi.Interfaces; using xAiApi.Interfaces;
using xAiApi.Extensions; using xAiApi.Extensions;
using xCommons.Providers; using xCommons.Providers;
@@ -12,6 +14,7 @@ using xCommons.Extensions;
using xAiModels.Constants; using xAiModels.Constants;
using xAiModels.Interfaces; using xAiModels.Interfaces;
using xAiModels.Extensions; using xAiModels.Extensions;
using System.Globalization;
using xAiApi.Configurations; using xAiApi.Configurations;
using xExceptions.Constants; using xExceptions.Constants;
using xAiModels.Models.Dtos; using xAiModels.Models.Dtos;
@@ -24,6 +27,7 @@ using System.Collections.Generic;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors; using xAiApi.Interfaces.Extractors;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using MongoDB.Driver.Core.Connections;
namespace xAiApi.Providers namespace xAiApi.Providers
{ {
@@ -47,16 +51,22 @@ namespace xAiApi.Providers
private readonly ILogger<XAIServiceBase> logger; private readonly ILogger<XAIServiceBase> logger;
private readonly XAiApiConfiguration configuration; private readonly XAiApiConfiguration configuration;
private readonly XValidationProvider validationProvider; private readonly XValidationProvider validationProvider;
private readonly IXAiMcpServerProvider mcpServerProvider;
private readonly IXFileContentExtractor fileContentExtractor; private readonly IXFileContentExtractor fileContentExtractor;
//
private readonly bool useProvidedMcpServers;
protected XAIServiceBase( protected XAIServiceBase(
IXAiRAGService ragProvider, IXAiRAGService ragProvider,
IXAiDataProvider dataProvider, IXAiDataProvider dataProvider,
ILogger<XAIServiceBase> logger, ILogger<XAIServiceBase> logger,
XAiApiConfiguration configuration, XAiApiConfiguration configuration,
XValidationProvider validationProvider, XValidationProvider validationProvider,
IXAiMcpServerProvider mcpServerProvider,
IXFileContentExtractor fileContentExtractor, IXFileContentExtractor fileContentExtractor,
string model = null string model = null,
bool useProvidedMcpServers = true
) )
{ {
// //
@@ -64,8 +74,10 @@ namespace xAiApi.Providers
this.ragProvider = ragProvider; this.ragProvider = ragProvider;
this.dataProvider = dataProvider; this.dataProvider = dataProvider;
this.configuration = configuration; this.configuration = configuration;
this.mcpServerProvider = mcpServerProvider;
this.validationProvider = validationProvider; this.validationProvider = validationProvider;
this.fileContentExtractor = fileContentExtractor; this.fileContentExtractor = fileContentExtractor;
this.useProvidedMcpServers = useProvidedMcpServers;
// //
// Prepare Embedding Model Descriptor ... // Prepare Embedding Model Descriptor ...
@@ -86,10 +98,12 @@ namespace xAiApi.Providers
/// Base Method for Communicate with LLM ... /// Base Method for Communicate with LLM ...
/// </summary> /// </summary>
/// <param name="prompt"></param> /// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<string> AskTextAsync( public virtual async Task<string> AskTextAsync(
string prompt, string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
@@ -103,6 +117,23 @@ namespace xAiApi.Providers
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
var history = GetHistory(prompt); var history = GetHistory(prompt);
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools];
}
//
var response = await client.GetResponseAsync( var response = await client.GetResponseAsync(
options: Options, options: Options,
messages: history, messages: history,
@@ -131,10 +162,12 @@ namespace xAiApi.Providers
/// Base Method for Communicate with LLM ... /// Base Method for Communicate with LLM ...
/// </summary> /// </summary>
/// <param name="prompt"></param> /// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public virtual async IAsyncEnumerable<string> AskTextAsEnumerable( public virtual async IAsyncEnumerable<string> AskTextAsEnumerable(
string prompt, string prompt,
XUserClaimsInfoDto userInfo = null,
[EnumeratorCancellation] [EnumeratorCancellation]
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -149,6 +182,23 @@ namespace xAiApi.Providers
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
var history = GetHistory(prompt); var history = GetHistory(prompt);
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var enumerable = client.GetStreamingResponseAsync( var enumerable = client.GetStreamingResponseAsync(
options: Options, options: Options,
messages: history messages: history
@@ -196,6 +246,23 @@ namespace xAiApi.Providers
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
var history = GetHistory(prompt, context); var history = GetHistory(prompt, context);
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var response = await client.GetResponseAsync( var response = await client.GetResponseAsync(
options: Options, options: Options,
messages: history, messages: history,
@@ -245,6 +312,23 @@ namespace xAiApi.Providers
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
var history = GetHistory(prompt, context); var history = GetHistory(prompt, context);
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var enumerable = client.GetStreamingResponseAsync( var enumerable = client.GetStreamingResponseAsync(
options: Options, options: Options,
messages: history, messages: history,
@@ -306,12 +390,32 @@ namespace xAiApi.Providers
connectionId: null, connectionId: null,
conversationId: null, conversationId: null,
persistPrompt: false, persistPrompt: false,
additionalContents: null,
addFilesToKnowledge: false,
resolveConversation: false, resolveConversation: false,
extractFileContents: false,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var response = await client var response = await client
.GetResponseAsync( .GetResponseAsync(
options: Options, options: Options,
@@ -370,12 +474,32 @@ namespace xAiApi.Providers
connectionId: null, connectionId: null,
conversationId: null, conversationId: null,
persistPrompt: false, persistPrompt: false,
additionalContents: null,
resolveConversation: false, resolveConversation: false,
addFilesToKnowledge: false,
extractFileContents: false,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var stream = client var stream = client
.GetStreamingResponseAsync( .GetStreamingResponseAsync(
options: Options, options: Options,
@@ -405,6 +529,8 @@ namespace xAiApi.Providers
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="conversationId"></param> /// <param name="conversationId"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param> /// <param name="files"></param>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
@@ -417,6 +543,8 @@ namespace xAiApi.Providers
Guid? projectId = null, Guid? projectId = null,
Guid? conversationId = null, Guid? conversationId = null,
string connectionId = null, string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null, IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -441,14 +569,34 @@ namespace xAiApi.Providers
userInfo: userInfo, userInfo: userInfo,
persistPrompt: true, persistPrompt: true,
projectId: projectId, projectId: projectId,
additionalContents: null,
resolveConversation: true, resolveConversation: true,
connectionId: connectionId, connectionId: connectionId,
conversationId: conversationId, conversationId: conversationId,
cancellationToken: cancellationToken cancellationToken: cancellationToken,
extractFileContents: extractFileContents,
addFilesToKnowledge: addFilesToKnowledge
); );
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var response = await client.GetResponseAsync( var response = await client.GetResponseAsync(
options: Options, options: Options,
messages: prep.History, messages: prep.History,
@@ -491,6 +639,8 @@ namespace xAiApi.Providers
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="conversationId"></param> /// <param name="conversationId"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param> /// <param name="files"></param>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
@@ -503,6 +653,8 @@ namespace xAiApi.Providers
Guid? projectId = null, Guid? projectId = null,
Guid? conversationId = null, Guid? conversationId = null,
string connectionId = null, string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null, IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
[EnumeratorCancellation] [EnumeratorCancellation]
@@ -528,14 +680,34 @@ namespace xAiApi.Providers
userInfo: userInfo, userInfo: userInfo,
persistPrompt: true, persistPrompt: true,
projectId: projectId, projectId: projectId,
additionalContents: null,
resolveConversation: true, resolveConversation: true,
connectionId: connectionId, connectionId: connectionId,
conversationId: conversationId, conversationId: conversationId,
cancellationToken: cancellationToken cancellationToken: cancellationToken,
extractFileContents: extractFileContents,
addFilesToKnowledge: addFilesToKnowledge
); );
// //
using var client = Descriptor.GetClient(); using var client = Descriptor.GetClient();
//
// Handle Provided MCP Servers ...
if (useProvidedMcpServers)
{
//
var availableTools = await mcpServerProvider
.GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
var stream = client var stream = client
.GetStreamingResponseAsync( .GetStreamingResponseAsync(
options: Options, options: Options,
@@ -665,24 +837,20 @@ namespace xAiApi.Providers
/// Load Conversations of Specified AI Project ... /// Load Conversations of Specified AI Project ...
/// </summary> /// </summary>
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<IEnumerable<XAiConversationDto>> LoadConversations( public virtual async Task<IEnumerable<XAiConversationDto>> LoadConversations(
Guid projectId, Guid? projectId,
string ownerId = null,
string connectionId = null, string connectionId = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
//
// Validate Args ...
if (projectId.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
// //
var result = await dataProvider.LoadConversations( var result = await dataProvider.LoadConversations(
ownerId: ownerId,
fillMessages: false, fillMessages: false,
projectId: projectId, projectId: projectId,
connectionId: connectionId, connectionId: connectionId,
@@ -697,22 +865,21 @@ namespace xAiApi.Providers
/// Load Messages of Specified Conversation ... /// Load Messages of Specified Conversation ...
/// </summary> /// </summary>
/// <param name="conversationId"></param> /// <param name="conversationId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<IEnumerable<XAiMessageDto>> LoadMessages( public virtual async Task<IEnumerable<XAiMessageDto>> LoadMessages(
Guid conversationId, Guid? conversationId,
string ownerId = null,
string connectionId = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
//
// Validate Args ...
if (conversationId.IsDefaultGuid())
{
XException.InvalidArgs.Throw();
}
// //
var result = await dataProvider.LoadMessages( var result = await dataProvider.LoadMessages(
ownerId: ownerId,
connectionId: connectionId,
conversationId: conversationId, conversationId: conversationId,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -905,7 +1072,7 @@ namespace xAiApi.Providers
/// <returns></returns> /// <returns></returns>
public virtual async Task<XAiConversationDto> CreateConversation( public virtual async Task<XAiConversationDto> CreateConversation(
string ownerId, string ownerId,
Guid projectId, Guid? projectId,
XAiConversationDto item, XAiConversationDto item,
string connectionId = null, string connectionId = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -992,9 +1159,6 @@ namespace xAiApi.Providers
{ {
continue; continue;
} }
//
// TODO: Implement File Save ...
} }
// //
@@ -1059,9 +1223,23 @@ namespace xAiApi.Providers
[ [
introductionPrompt, introductionPrompt,
]; ];
//
// Prepare Datetime ...
var datetimeContext = BuildDateTimeContext();
if (!datetimeContext.IsNullOrEmpty())
{
//
result.Add(new ChatMessage(
ChatRole.Assistant,
datetimeContext
));
}
//
if (forcePrompt && if (forcePrompt &&
prompt is not null && prompt is not null &&
!string.IsNullOrWhiteSpace(prompt)) !prompt.IsNullOrEmpty())
{ {
result.Add(promptMessage); result.Add(promptMessage);
} }
@@ -1091,6 +1269,7 @@ namespace xAiApi.Providers
} }
// //
var datetimeContext = BuildDateTimeContext();
var contextBlock = BuildContextBlock(context); var contextBlock = BuildContextBlock(context);
var systemText = introductionPrompt; var systemText = introductionPrompt;
if (context.HasChild() && if (context.HasChild() &&
@@ -1099,7 +1278,17 @@ namespace xAiApi.Providers
{ {
// //
systemText = systemText =
$"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}";
//
if (!datetimeContext.IsNullOrEmpty())
{
//
systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
}
//
systemText +=
$"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
$"Context:{Environment.NewLine}{contextBlock}"; $"Context:{Environment.NewLine}{contextBlock}";
} }
@@ -1133,6 +1322,9 @@ namespace xAiApi.Providers
// //
var result = new List<ChatMessage>(); var result = new List<ChatMessage>();
//
await Task.FromResult(true);
// //
// Retrieve Introduction Prompt ... // Retrieve Introduction Prompt ...
var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
@@ -1157,12 +1349,22 @@ namespace xAiApi.Providers
$"Context:{Environment.NewLine}{contextBlock}"; $"Context:{Environment.NewLine}{contextBlock}";
} }
//
// Prepare Datetime ...
var datetimeContext = BuildDateTimeContext();
if (!datetimeContext.IsNullOrEmpty())
{
//
systemText +=
$"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
}
// //
// Apply Project Prompt as System Text ... // Apply Project Prompt as System Text ...
if (!project.IsNullOrDefault() && if (!project.IsNullOrDefault() &&
!project.Prompt.IsNullOrEmpty()) !project.Prompt.IsNullOrEmpty())
{ {
systemText += $"{project.Prompt}{Environment.NewLine}"; systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}";
} }
// //
@@ -1279,17 +1481,20 @@ namespace xAiApi.Providers
/// <summary> /// <summary>
/// Retrieve Prepared Chat Context ... /// Retrieve Prepared Chat Context ...
/// </summary> /// </summary>
/// <param name="prompt"></param>
/// <param name="type"></param>
/// <param name="topK"></param> /// <param name="topK"></param>
/// <param name="type"></param>
/// <param name="prompt"></param>
/// <param name="minScore"></param> /// <param name="minScore"></param>
/// <param name="projectId"></param> /// <param name="projectId"></param>
/// <param name="conversationId"></param> /// <param name="persistPrompt"></param>
/// <param name="connectionId"></param> /// <param name="connectionId"></param>
/// <param name="conversationId"></param>
/// <param name="resolveConversation"></param>
/// <param name="files"></param> /// <param name="files"></param>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="resolveConversation"></param> /// <param name="extractFileContents"></param>
/// <param name="persistPrompt"></param> /// <param name="addFilesToKnowledge"></param>
/// <param name="additionalContents"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
private async Task<XPreparedChatContext> PrepareChatRequirementsAsync( private async Task<XPreparedChatContext> PrepareChatRequirementsAsync(
@@ -1304,6 +1509,8 @@ namespace xAiApi.Providers
bool resolveConversation, bool resolveConversation,
IFormFileCollection files, IFormFileCollection files,
XUserClaimsInfoDto userInfo, XUserClaimsInfoDto userInfo,
bool extractFileContents = true,
bool addFilesToKnowledge = false,
IList<AIContent> additionalContents = null, IList<AIContent> additionalContents = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -1394,7 +1601,8 @@ namespace xAiApi.Providers
// Ingest Files if Provided and also Resolve Conversation Flagged ... // Ingest Files if Provided and also Resolve Conversation Flagged ...
if ( if (
files.HasChild() && files.HasChild() &&
resolveConversation resolveConversation &&
addFilesToKnowledge
) )
{ {
// //
@@ -1437,6 +1645,59 @@ namespace xAiApi.Providers
} }
} }
//
// If there isn't Files need to add Files to Knowledge ...
if (files.HasChild() &&
!addFilesToKnowledge
)
{
//
// Extract File Content and add them to Additional Contents ...
foreach (var file in files)
{
//
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
if (mimeType.IsNullOrEmpty() ||
!fileContentExtractor.CanExtract(mimeType))
{
continue;
}
//
using var stream = file.OpenReadStream();
//
// Extract File Content if necessary ...
if (extractFileContents)
{
//
var content = await fileContentExtractor.ExtractAsync(
fileStream: stream,
mimeType: mimeType,
cancellationToken: cancellationToken
);
if (!content.IsNullOrEmpty())
{
//
var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}");
additionalContents = [.. additionalContents, fileContent];
}
}
else
{
//
var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken);
if (additionalContents.IsNull())
{
additionalContents = [];
}
//
additionalContents = [.. additionalContents, fileContent];
}
}
}
// //
// Request Knowledge ... // Request Knowledge ...
var knowledgeRequest = new XAiKnowledgeAskRequest var knowledgeRequest = new XAiKnowledgeAskRequest
@@ -1467,6 +1728,8 @@ namespace xAiApi.Providers
// Retrieve Conversation Message ... // Retrieve Conversation Message ...
var messages = await dataProvider var messages = await dataProvider
.LoadMessages( .LoadMessages(
ownerId: userInfo.UserId,
connectionId: connectionId,
conversationId: conversationId.Value, conversationId: conversationId.Value,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -1522,6 +1785,77 @@ namespace xAiApi.Providers
// //
return result; return result;
} }
private string BuildDateTimeContext()
{
//
var cfg = configuration.DateTime;
if (cfg == null || !cfg.InjectIntoSystemPrompt)
{
return string.Empty;
}
//
try
{
//
var tz = ResolveTimezone(cfg.DefaultTimezone);
var nowUtc = DateTime.UtcNow;
var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz);
//
var sb = new StringBuilder();
sb.AppendLine("[CURRENT DATETIME — for your reference]");
sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}");
//
if (cfg.IncludeDayOfWeek)
{
sb.AppendLine($"Day of week: {nowLocal:dddd}");
}
//
if (cfg.IncludePersianCalendar)
{
//
var pc = new PersianCalendar();
sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}");
}
//
if (cfg.IncludeUnixTimestamp)
{
sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}");
}
//
sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations.");
return sb.ToString().TrimEnd();
}
catch
{
return string.Empty;
}
}
private static TimeZoneInfo ResolveTimezone(string id)
{
//
if (id.IsNullOrEmpty())
{
return TimeZoneInfo.Utc;
}
//
try
{
return TZConvert.GetTimeZoneInfo(id);
}
catch
{
return TimeZoneInfo.Utc;
}
}
#endregion #endregion
} }
} }
+485 -113
View File
@@ -7,20 +7,26 @@ using xAiApi.Interfaces;
using xCommons.Providers; using xCommons.Providers;
using xCommons.Extensions; using xCommons.Extensions;
using xAiModels.Constants; using xAiModels.Constants;
using xAiService.Services;
using xAiModels.Extensions; using xAiModels.Extensions;
using xAiService.Extensions;
using xExceptions.Constants; using xExceptions.Constants;
using xAiModels.Models.Dtos; using xAiModels.Models.Dtos;
using xIdentityModels.Models; using xIdentityModels.Models;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Linq.Expressions; using System.Linq.Expressions;
using xCommons.Configurations;
using Microsoft.Extensions.AI;
using xAiModels.Providers.Hubs;
using xAiModels.Models.Entities; using xAiModels.Models.Entities;
using xAiModels.Interfaces.Dtos; using xAiModels.Interfaces.Dtos;
using xIdentityHelper.Extensions; using xIdentityHelper.Extensions;
using System.Collections.Generic; using System.Collections.Generic;
using xIdentityService.Interfaces; using xIdentityService.Interfaces;
using ModelContextProtocol.Client;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities; using xAiModels.Interfaces.Entities;
using System.Collections.Concurrent;
using xAiModels.Interfaces.Enrichers; using xAiModels.Interfaces.Enrichers;
namespace xAiApi.Providers namespace xAiApi.Providers
@@ -30,6 +36,13 @@ namespace xAiApi.Providers
/// </summary> /// </summary>
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
{ {
//
private readonly XAiMcpSessionStore sessionStore;
private readonly XAiMcpHttpTransport mcpTransport;
//
private readonly XAppConfiguration configuration;
private readonly IHubContext<XAiDataProviderHub> hub;
private readonly IXIdentityProvider identityProvider; private readonly IXIdentityProvider identityProvider;
private readonly ILogger<XAiMcpServerProvider> logger; private readonly ILogger<XAiMcpServerProvider> logger;
private readonly XValidationProvider validationProvider; private readonly XValidationProvider validationProvider;
@@ -37,13 +50,21 @@ namespace xAiApi.Providers
private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider;
private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider;
private readonly Dictionary<Guid, McpClient> clients = []; //
private readonly Dictionary<Guid, XAiMcpServerDto> mcpServers = []; private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> mcpServers = [];
private readonly Dictionary<Guid, IList<McpClientTool>> tools = []; private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new();
private readonly SemaphoreSlim initLock = new(1, 1); private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new();
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<AITool>> tools = new();
//
private bool isInitialized = false; private bool isInitialized = false;
private readonly SemaphoreSlim initLock = new(1, 1);
public XAiMcpServerProvider( public XAiMcpServerProvider(
XAiMcpSessionStore sessionStore,
XAppConfiguration configuration,
XAiMcpHttpTransport mcpTransport,
IHubContext<XAiDataProviderHub> hub,
IXIdentityProvider identityProvider, IXIdentityProvider identityProvider,
ILogger<XAiMcpServerProvider> logger, ILogger<XAiMcpServerProvider> logger,
XValidationProvider validationProvider, XValidationProvider validationProvider,
@@ -52,8 +73,12 @@ namespace xAiApi.Providers
IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider
) )
{ {
this.configuration = configuration;
// //
this.hub = hub;
this.logger = logger; this.logger = logger;
this.sessionStore = sessionStore;
this.mcpTransport = mcpTransport;
this.identityProvider = identityProvider; this.identityProvider = identityProvider;
this.mcpServerEnricher = mcpServerEnricher; this.mcpServerEnricher = mcpServerEnricher;
this.validationProvider = validationProvider; this.validationProvider = validationProvider;
@@ -84,7 +109,7 @@ namespace xAiApi.Providers
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<IList<McpClientTool>> GetAvailableToolsAsync( public async Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false, bool forceOwner = false,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -105,78 +130,97 @@ namespace xAiApi.Providers
} }
// //
// Check Initialization ... // Load Servers Metadata ...
if (isInitialized) await EnsureServersLoadedAsync(cancellationToken);
//
// Extract Accessible Mcp Servers ...
var accessibleServers = mcpServers.Values
.Where(s => s.OwnerId == userInfo.UserId ||
s.Scope == XAiMcpServerUsageScope.All)
.ToList();
//
// Create User Speciic Client Connection ...
foreach (var server in accessibleServers)
{ {
// //
var selectedServers = mcpServers // Create User Specific Client Key ...
.Where(s => var key = (server.Id, userInfo.UserId);
s.Value.OwnerId == userInfo.UserId ||
s.Value.Scope == XAiMcpServerUsageScope.All //
) // Check Expiration ...
.Select(s => s.Key); if (clients.ContainsKey(key) &&
var result = tools clientExpirations.TryGetValue(key, out var exp) &&
.Where(c => selectedServers.Contains(c.Key)) exp < DateTime.UtcNow)
.SelectMany(c => c.Value); {
return [.. result]; //
// Remove Expired Client and Tools ...
if (clients.TryRemove(key, out var old))
{
//
try
{
await old.DisposeAsync();
}
catch { }
}
//
tools.TryRemove(key, out _);
clientExpirations.TryRemove(key, out _);
}
//
if (clients.ContainsKey(key))
{
continue;
}
//
await initLock.WaitAsync(cancellationToken);
try
{
//
if (!clients.ContainsKey(key))
{
//
await ConnectAndValidateAsync(
descriptor: server,
userInfo: userInfo,
cancellationToken: cancellationToken
);
}
}
finally
{
initLock.Release();
}
} }
// //
await initLock.WaitAsync(cancellationToken); // Extract User Specified Mcp Client Tools ...
try var result = tools
{ .Where(kv => kv.Key.UserId == userInfo.UserId)
// .SelectMany(kv => kv.Value)
if (isInitialized) .ToList();
{
//
var selectedServers = mcpServers
.Where(s =>
s.Value.OwnerId == userInfo.UserId ||
s.Value.Scope == XAiMcpServerUsageScope.All
)
.Select(s => s.Key);
var result = tools
.Where(c => selectedServers.Contains(c.Key))
.SelectMany(c => c.Value);
return [.. result];
}
// //
var servers = await mcpServerServiceProvider return result;
.FindManyAsync(
orderBuilder: null,
includeBuilder: null,
ignoreSoftDeleteds: true,
predicate: x => x.Enabled,
cancellationToken: cancellationToken
);
if (servers.HasChild())
{
//
var tasks = servers
.Select(s =>
ConnectAndValidateAsync(s, cancellationToken));
await Task.WhenAll(tasks);
}
//
isInitialized = true;
return [.. tools.Values.SelectMany(t => t)];
}
finally
{
initLock.Release();
}
} }
/// <summary> /// <summary>
/// Test Specified Mcp Server ... /// Test Specified Mcp Server ...
/// </summary> /// </summary>
/// <param name="server"></param> /// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<string> TestServerAsync( public async Task<string> TestServerAsync(
XAiMcpServerDto server, XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
@@ -188,8 +232,8 @@ namespace xAiApi.Providers
cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
// //
var client = await CreateClientAsync(server, cts.Token); var client = CreateClientAsync(server, connectionId, userInfo);
await client.PingAsync(cancellationToken: cts.Token); // await client.PingAsync(cancellationToken: cts.Token);
var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);
// //
@@ -206,9 +250,20 @@ namespace xAiApi.Providers
/// <summary> /// <summary>
/// Force Refresh Mcp Servers ... /// Force Refresh Mcp Servers ...
/// </summary> /// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task RefreshAsync() public async Task RefreshAsync(
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{ {
//
if (!userInfo.IsAdmin())
{
XException.NotAllowed.Throw();
}
// //
logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); logger.LogInformation("MCP: Reinitialize Mcp Servers ...");
foreach (var client in clients.Values) foreach (var client in clients.Values)
@@ -225,7 +280,10 @@ namespace xAiApi.Providers
// //
isInitialized = false; isInitialized = false;
await GetAvailableToolsAsync(cancellationToken: CancellationToken.None); await GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
} }
#endregion #endregion
@@ -299,11 +357,22 @@ namespace xAiApi.Providers
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
//
// Sending Push ...
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: result.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.McpServerCreated.GetStringValue()
);
// //
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
await ConnectAndValidateAsync(result, cancellationToken); //
mcpServers[result.Id] = result;
await ConnectAndValidateAsync(result, connectionId, userInfo);
} }
finally finally
{ {
@@ -315,6 +384,59 @@ namespace xAiApi.Providers
return result; return result;
} }
/// <summary>
/// Get an Mcp Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiMcpServerDto> GetMcpServer(
Guid id,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validation ...
validationProvider
.GroupValidationBuilder()
.AddIsGuid(id)
.AddNotNull(userInfo)
.AddNotEmpty(userInfo.UserId)
.ValidateGroup();
//
var result = await mcpServerServiceProvider
.GetAsync(
id: id,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
//
// Validate Ownership ...
if (!userInfo.IsAdmin() && result.OwnerId != userInfo.UserId)
{
XException.NotAllowed.Throw();
}
//
if (!result.IsNullOrDefault())
{
//
// Handle Enrichment ...
result = await mcpServerEnricher.Enrich(
source: result,
cancellationToken: cancellationToken
);
}
//
return result;
}
/// <summary> /// <summary>
/// Update Specified Mcp Server ... /// Update Specified Mcp Server ...
/// </summary> /// </summary>
@@ -396,19 +518,44 @@ namespace xAiApi.Providers
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
//
// Sending Push ...
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: result.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
);
// //
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
// //
// Remove Exists ... mcpServers[result.Id] = result;
tools.Remove(result.Id);
clients.Remove(result.Id);
mcpServers.Remove(result.Id);
// //
// Update ... // Remove Exists ...
await ConnectAndValidateAsync(result, cancellationToken); var keysToRemove = clients.Keys
.Where(k => k.ServerId == result.Id)
.ToList();
foreach (var key in keysToRemove)
{
//
if (clients.TryRemove(key, out var old))
{
try
{
await old.DisposeAsync();
}
catch { }
}
tools.TryRemove(key, out _);
}
//
// Reconnect ...
await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken);
} }
finally finally
{ {
@@ -484,15 +631,44 @@ namespace xAiApi.Providers
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
//
// Sending Push ...
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: result.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.McpServerRemoved.GetStringValue()
);
// //
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
// //
// Remove Exists ... // Remove Server Descriptor ...
tools.Remove(result.Id); mcpServers.TryRemove(result.Id, out _);
clients.Remove(result.Id);
mcpServers.Remove(result.Id); //
// Disconnect all Connections ...
var keysToRemove = clients.Keys
.Where(k => k.ServerId == result.Id)
.ToList();
foreach (var key in keysToRemove)
{
//
if (clients.TryRemove(key, out var c))
{
//
try
{
await c.DisposeAsync();
}
catch { }
}
//
tools.TryRemove(key, out _);
}
} }
finally finally
{ {
@@ -569,15 +745,44 @@ namespace xAiApi.Providers
// //
if (result) if (result)
{ {
//
// Sending Push ...
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: exists.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
);
// //
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
// //
// Remove Exists ... // Remove Server Descriptor ...
tools.Remove(exists.Id); mcpServers.TryRemove(exists.Id, out _);
clients.Remove(exists.Id);
mcpServers.Remove(exists.Id); //
// Disconnect all Connections ...
var keysToRemove = clients.Keys
.Where(k => k.ServerId == exists.Id)
.ToList();
foreach (var key in keysToRemove)
{
//
if (clients.TryRemove(key, out var c))
{
//
try
{
await c.DisposeAsync();
}
catch { }
}
//
tools.TryRemove(key, out _);
}
} }
finally finally
{ {
@@ -654,11 +859,22 @@ namespace xAiApi.Providers
// //
if (result) if (result)
{ {
//
// Sending Push ...
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: exists.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
);
// //
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
await ConnectAndValidateAsync(exists, cancellationToken); //
mcpServers[exists.Id] = exists;
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
} }
finally finally
{ {
@@ -731,21 +947,53 @@ namespace xAiApi.Providers
// //
if (result) if (result)
{ {
//
// Sending Push ...
await SendPush(
connectionId: connectionId,
cancellationToken: cancellationToken,
payLoad: exists.ToJSON(camelCase: true),
action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
);
// //
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
//
if (exists.Enabled) if (exists.Enabled)
{ {
await ConnectAndValidateAsync(exists, cancellationToken); //
mcpServers[exists.Id] = exists;
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
} }
else else
{ {
// //
// Remove Exists ... // Remove Server Descriptor ...
tools.Remove(exists.Id); mcpServers.TryRemove(exists.Id, out _);
clients.Remove(exists.Id);
mcpServers.Remove(exists.Id); //
// Disconnect all Connections ...
var keysToRemove = clients.Keys
.Where(k => k.ServerId == exists.Id)
.ToList();
foreach (var key in keysToRemove)
{
//
if (clients.TryRemove(key, out var c))
{
//
try
{
await c.DisposeAsync();
}
catch { }
}
//
tools.TryRemove(key, out _);
}
} }
} }
finally finally
@@ -1053,66 +1301,190 @@ namespace xAiApi.Providers
=> json.IsNullOrEmpty() ? null => json.IsNullOrEmpty() ? null
: JsonSerializer.Deserialize<List<string>>(json); : JsonSerializer.Deserialize<List<string>>(json);
private static async Task<McpClient> CreateClientAsync( private XAiMcpClient CreateClientAsync(
XAiMcpServerDto s, XAiMcpServerDto descriptor,
CancellationToken cancellationToken string connectionId = null,
XUserClaimsInfoDto userInfo = null
) )
{ {
// //
IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions var result = new XAiMcpClient(
{ logger: logger,
Endpoint = new Uri(s.Endpoint!), userInfo: userInfo,
AdditionalHeaders = ParseJsonDict(s.Headers), transport: mcpTransport,
TransportMode = HttpTransportMode.AutoDetect serverId: descriptor.Id,
}); sessionStore: sessionStore,
connectionId: connectionId,
appConfiguration: configuration,
endpoint: new Uri(descriptor.Endpoint)
);
// //
return await McpClient return result;
.CreateAsync(
transport,
cancellationToken: cancellationToken
);
} }
private async Task ConnectAndValidateAsync( private async Task ConnectAndValidateAsync(
XAiMcpServerDto descriptor, XAiMcpServerDto descriptor,
CancellationToken cancellationToken string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
) )
{ {
// //
try try
{ {
// //
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); // Create Specified Cancellation Token ...
using var cts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
// //
var client = await CreateClientAsync(descriptor, cts.Token); var client = CreateClientAsync(
await client.PingAsync(cancellationToken: cts.Token); userInfo: userInfo,
var serverTools = await client descriptor: descriptor,
.ListToolsAsync(cancellationToken: cts.Token); connectionId: connectionId
);
// //
clients[descriptor.Id] = client; await client.InitializeAsync(cts.Token);
tools[descriptor.Id] = serverTools;
//
var clientTools = await client.ListToolsAsync(cts.Token);
var aiTools = clientTools.ToAITools(client);
//
// Key for Cache ...
var key = (descriptor.Id, userInfo.UserId);
//
tools[key] = aiTools;
clients[key] = client;
mcpServers[descriptor.Id] = descriptor; mcpServers[descriptor.Id] = descriptor;
clientExpirations[key] = DateTime.UtcNow.AddMinutes(15);
// //
logger.LogInformation( logger.LogInformation(
"MCP '{Name}': {Count} Tools Detected ...", "MCP '{Name}': {Count} Tools Detected for {UserId} ...",
descriptor.Name, descriptor.Name,
serverTools.Count aiTools.Count,
userInfo.UserId
); );
} } catch(Exception ex)
catch (Exception ex)
{ {
// //
logger.LogWarning(ex, logger.LogWarning(ex,
"MCP '{Name}': Connection Established Failed, Ignored ...", "MCP '{Name}': Connection Established Failed, Ignored ...",
descriptor.Name descriptor.Name
);
}
}
private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken)
{
//
if (isInitialized)
{
return;
}
//
await initLock.WaitAsync(cancellationToken);
try
{
//
if (isInitialized)
{
return;
}
//
var servers = await mcpServerServiceProvider.FindManyAsync(
orderBuilder: null,
includeBuilder: null,
ignoreSoftDeleteds: true,
predicate: x => x.Enabled,
cancellationToken: cancellationToken
); );
//
if (servers.HasChild())
{
//
foreach (var s in servers)
{
//
mcpServers[s.Id] = s;
}
}
//
isInitialized = true;
}
finally
{
initLock.Release();
} }
} }
#endregion #endregion
//
#region Hub Actions ...
/// <summary>
/// Send Custom Push Message ...
/// </summary>
/// <param name="action"></param>
/// <param name="payLoad"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task SendPush(
string action,
string payLoad,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Collect Allowed Actions ...
var actions = new List<string>
{
XAiDataProviderHubActions.McpServerCreated.GetStringValue(),
XAiDataProviderHubActions.McpServerUpdated.GetStringValue(),
XAiDataProviderHubActions.McpServerRemoved.GetStringValue(),
};
//
// Validate Args ...
var isValid =
!action.IsNullOrEmpty() &&
actions.Contains(action);
if (!isValid)
{
return;
}
//
// Retrieve Connection Id ...
var clients = hub.Clients.All;
if (!connectionId.IsNullOrEmpty())
{
clients = hub.Clients.AllExcept(connectionId);
}
//
await clients.SendAsync(
action,
payLoad,
connectionId,
cancellationToken
);
}
catch { }
}
#endregion
} }
} }
+2
View File
@@ -16,6 +16,7 @@ namespace xAiApi.Providers
ILogger<XAiService> logger, ILogger<XAiService> logger,
XAiApiConfiguration configuration, XAiApiConfiguration configuration,
XValidationProvider validationProvider, XValidationProvider validationProvider,
IXAiMcpServerProvider mcpServerProvider,
IXFileContentExtractor fileContentExtractor IXFileContentExtractor fileContentExtractor
) : base( ) : base(
ragProvider, ragProvider,
@@ -23,6 +24,7 @@ namespace xAiApi.Providers
logger, logger,
configuration, configuration,
validationProvider, validationProvider,
mcpServerProvider,
fileContentExtractor, fileContentExtractor,
XAiApiConstants.XAiDefaultModelName XAiApiConstants.XAiDefaultModelName
) )
+2
View File
@@ -17,6 +17,7 @@ namespace xAiApi.Providers
ILogger<XAIServiceBase> logger, ILogger<XAIServiceBase> logger,
XAiApiConfiguration configuration, XAiApiConfiguration configuration,
XValidationProvider validationProvider, XValidationProvider validationProvider,
IXAiMcpServerProvider mcpServerProvider,
IXFileContentExtractor fileContentExtractor, IXFileContentExtractor fileContentExtractor,
ReasoningEffort effort = ReasoningEffort.Medium, ReasoningEffort effort = ReasoningEffort.Medium,
ReasoningOutput output = ReasoningOutput.Full ReasoningOutput output = ReasoningOutput.Full
@@ -26,6 +27,7 @@ namespace xAiApi.Providers
logger, logger,
configuration, configuration,
validationProvider, validationProvider,
mcpServerProvider,
fileContentExtractor, fileContentExtractor,
XAiApiConstants.XAiDefaultThinkingModelName XAiApiConstants.XAiDefaultThinkingModelName
) )
+33 -2
View File
@@ -3,6 +3,7 @@ using System.IO;
using xAiApi.DI; using xAiApi.DI;
using System.Linq; using System.Linq;
using xAiModels.DI; using xAiModels.DI;
using xAiService.DI;
using xTagService.DI; using xTagService.DI;
using System.Net.Http; using System.Net.Http;
using xAiApi.Database; using xAiApi.Database;
@@ -14,6 +15,7 @@ using Newtonsoft.Json;
using System.Reflection; using System.Reflection;
using xAiApi.Extensions; using xAiApi.Extensions;
using xStringService.DI; using xStringService.DI;
using xLoggingService.DI;
using xStorageService.DI; using xStorageService.DI;
using xIdentityService.DI; using xIdentityService.DI;
using xDataService.Models; using xDataService.Models;
@@ -69,6 +71,10 @@ namespace xAiApi
services.AddXAppConfiguration(Configuration); services.AddXAppConfiguration(Configuration);
var appConfiguration = services.GetRegisteredService<XAppConfiguration>(); var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
//
// Register Logging Service ...
services.AddXLoggingService(Configuration);
// //
// Register Allowed Origins ... // Register Allowed Origins ...
services.AddXCors(appConfiguration.AllowedOrigins); services.AddXCors(appConfiguration.AllowedOrigins);
@@ -184,10 +190,14 @@ namespace xAiApi
// Register XAiApi Configuration ... // Register XAiApi Configuration ...
services.AddXAiApiConfiguration(Configuration); services.AddXAiApiConfiguration(Configuration);
//
// Register MCP Server Provider ...
services.AddXAiMcpServerProvider();
// //
// Register File Content Extractor Services ... // Register File Content Extractor Services ...
services.AddXAiFileContentExtractors(); services.AddXAiFileContentExtractors();
// //
// Register Text Chunker Service ... // Register Text Chunker Service ...
services.AddXAiTextChunker(); services.AddXAiTextChunker();
@@ -196,6 +206,10 @@ namespace xAiApi
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ... // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
services.AddXAiChatWithDocuments(); services.AddXAiChatWithDocuments();
//
// Register XAiMcpClient ...
services.AddXAiMcpClient();
// //
// Persistent RAG (Knowledge over XAiVector Table) ... // Persistent RAG (Knowledge over XAiVector Table) ...
services.AddXRagService(); services.AddXRagService();
@@ -205,7 +219,10 @@ namespace xAiApi
services.AddXAiServices(); services.AddXAiServices();
} }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env
)
{ {
// //
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
@@ -222,6 +239,10 @@ namespace xAiApi
app.UseHsts(); app.UseHsts();
} }
//
// Setting Environment in App Confiuration ...
app.AddEnvironmentToXAppConfiguration(env.EnvironmentName);
// //
// Force Https Redirection ... // Force Https Redirection ...
app.UseHttpsRedirection(); app.UseHttpsRedirection();
@@ -250,6 +271,13 @@ namespace xAiApi
// Using Routing ... // Using Routing ...
app.UseRouting(); app.UseRouting();
//
// Using Request Logging ...
if (!isDevelopmentEnvironment)
{
app.UseXRequestLogger();
}
// //
// Use xIdentityService (Authentication) ... // Use xIdentityService (Authentication) ...
app.UseXIdentityService(); app.UseXIdentityService();
@@ -306,3 +334,6 @@ namespace xAiApi
} }
} }
} }
+20 -2
View File
@@ -1,10 +1,13 @@
{ {
"AllowedOrigins": [ "AllowedOrigins": [
"http://127.0.0.1:5500",
"http://localhost:5000", "http://localhost:5000",
"https://localhost:5001", "https://localhost:5001",
"http://api.saherelm.ir", "http://api.saherelm.ir",
"https://api.saherelm.ir", "https://api.saherelm.ir",
"http://api.saherelmhub.ir", "http://api.saherelmhub.ir",
"http://192.168.11.29:5173",
"http://192.168.11.29:5174",
"https://api.saherelmhub.ir" "https://api.saherelmhub.ir"
], ],
"IdentityServiceConfiguration": { "IdentityServiceConfiguration": {
@@ -37,9 +40,16 @@
}, },
"AiApiConfiguration": { "AiApiConfiguration": {
"Models": [ "Models": [
{
"Name": "Arion",
"Provider": "OpenAI",
"LLM": "claude-fable-5-1",
"Url": "https://arionhub.pro/v1",
"ApiKey": "sk-AKJGD8J9gOCrQgc5oWPGtRGUo25PnnQGnMoipzdliYHa3otZ"
},
{ {
"ApiKey": "", "ApiKey": "",
"Name": "Gemma", "Name": "Gemma_BKP",
"LLM": "gemma3:1b", "LLM": "gemma3:1b",
"Provider": "OpenAI", "Provider": "OpenAI",
"Url": "http://178.131.88.93:1112/v1" "Url": "http://178.131.88.93:1112/v1"
@@ -130,7 +140,15 @@
"MetadataMimeType": "mimeType", "MetadataMimeType": "mimeType",
"PromptName": "ChatWithDocuments", "PromptName": "ChatWithDocuments",
"MetadataChunkIndex": "chunkIndex" "MetadataChunkIndex": "chunkIndex"
} },
"DateTime": {
"IncludeDayOfWeek": true,
"IncludeUnixTimestamp": false,
"InjectIntoSystemPrompt": true,
"IncludePersianCalendar": true,
"DefaultTimezone": "Asia/Tehran",
"GregorianFormat": "yyyy-MM-dd HH:mm:ss"
}
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
+37 -1
View File
@@ -4,6 +4,7 @@
"DefaultLanguage": "fa-IR", "DefaultLanguage": "fa-IR",
"XPoweredValue": "SaherElmITCenter", "XPoweredValue": "SaherElmITCenter",
"WelcomeMessage": "Welcome to xSaherElm Project's AI API", "WelcomeMessage": "Welcome to xSaherElm Project's AI API",
"DefaultCacheTtlMinutes": 10,
"AllowedOrigins": [ "AllowedOrigins": [
"http://api.saherelm.ir", "http://api.saherelm.ir",
"https://api.saherelm.ir", "https://api.saherelm.ir",
@@ -18,6 +19,9 @@
"Name": "Hadi Khazaee Asl", "Name": "Hadi Khazaee Asl",
"Email": "hadi_khazaee_asl@yahoo.com", "Email": "hadi_khazaee_asl@yahoo.com",
"Url": "https://www.saherelm.ir" "Url": "https://www.saherelm.ir"
},
"DefaultValues": {
"version": "1.0"
} }
}, },
"HttpServiceConfiguration": { "HttpServiceConfiguration": {
@@ -48,6 +52,38 @@
"BaseRoute": "hubs", "BaseRoute": "hubs",
"AddSupportMessageProtocol": true "AddSupportMessageProtocol": true
}, },
"LoggingServiceConfiguration": {
"Enabled": true,
"MinimumLevel": "Information",
"Queue": {
"Enabled": true,
"Capacity": 10000,
"ShutdownTimeoutSeconds": 10
},
"File": {
"Enabled": true,
"Directory": "./Logs",
"FileName": "xAiApi-.log",
"Format": "Json",
"MinimumLevel": "Information",
"RetainedFileCountLimit": 30
},
"Database": {
"Enabled": false,
"TableName": "XLogs",
"AutoCreateTable": true,
"MinimumLevel": "Warning",
"Provider": "Microsoft.Data.Sqlite",
"ConnectionString": "Filename=./Db/XLogs.db"
},
"Event": {
"Enabled": false,
"Sender": "xAiApi",
"MinimumLevel": "Error",
"Topic": "application-logs",
"Action": "ApplicationLogCreated"
}
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
@@ -55,4 +91,4 @@
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*"
} }
+2 -2
View File
@@ -7,7 +7,6 @@
<Authors>Hadi Khazaee Asl</Authors> <Authors>Hadi Khazaee Asl</Authors>
<Company>SaherElm IT Center</Company> <Company>SaherElm IT Center</Company>
<PackageId>xSaherElm.xAiApi</PackageId> <PackageId>xSaherElm.xAiApi</PackageId>
<!-- <TargetFramework>net8.0</TargetFramework> -->
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
<Description> <Description>
@@ -18,8 +17,8 @@
<PackageIcon>icon.png</PackageIcon> <PackageIcon>icon.png</PackageIcon>
<!-- Fix Duplicate TargetFramework Issue --> <!-- Fix Duplicate TargetFramework Issue -->
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
</PropertyGroup> </PropertyGroup>
<!-- Icon Handling --> <!-- Icon Handling -->
@@ -41,6 +40,7 @@
<ProjectReference Include="../Modules/xHttpService/xHttpService.csproj" /> <ProjectReference Include="../Modules/xHttpService/xHttpService.csproj" />
<ProjectReference Include="../Modules/xFileService/xFileService.csproj" /> <ProjectReference Include="../Modules/xFileService/xFileService.csproj" />
<ProjectReference Include="../Modules/xStorageService/xStorageService.csproj" /> <ProjectReference Include="../Modules/xStorageService/xStorageService.csproj" />
<ProjectReference Include="..\Modules\xLoggingService\xLoggingService.csproj" />
<ProjectReference Include="../Modules/xIdentityHelper/xIdentityHelper.csproj" /> <ProjectReference Include="../Modules/xIdentityHelper/xIdentityHelper.csproj" />
</ItemGroup> </ItemGroup>