- 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 ...
This commit is contained in:
2026-11-05 18:17:30 +03:30
parent 97acf0a123
commit ae7f5920c1
7 changed files with 197 additions and 12 deletions
+6
View File
@@ -45,5 +45,11 @@ namespace xAiApi.Configurations
/// RAG Configuration ...
/// </summary>
public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
/// <summary>
/// DateTime Configuration ...
/// </summary>
/// <returns></returns>
public XDateTimeDescriptor DateTime { get; set; } = new();
}
}
+11 -2
View File
@@ -468,16 +468,25 @@ namespace xAiApi.Controllers
/// <summary>
/// Refresh MCP Servers ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Refresh")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public async Task<ActionResult> RefreshMcpServers()
public async Task<ActionResult> RefreshMcpServers(
CancellationToken cancellationToken = default
)
{
//
try
{
//
await mcpServerProvider.RefreshAsync();
var userInfo = await GetUserInfo();
//
await mcpServerProvider.RefreshAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
return Ok();
+6 -1
View File
@@ -45,8 +45,13 @@ namespace xAiApi.Interfaces
/// <summary>
/// Force Refresh Mcp Servers ...
/// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task RefreshAsync();
Task RefreshAsync(
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
#endregion
//
+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;
}
}
+114 -5
View File
@@ -1,10 +1,12 @@
using System;
using System.Linq;
using System.Text;
using xModels.Dtos;
using xAiApi.Models;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using TimeZoneConverter;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Providers;
@@ -12,6 +14,7 @@ using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Interfaces;
using xAiModels.Extensions;
using System.Globalization;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
@@ -126,7 +129,7 @@ namespace xAiApi.Providers
);
//
Options.Tools = [.. availableTools .Cast<AITool>()];
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
@@ -191,7 +194,7 @@ namespace xAiApi.Providers
);
//
Options.Tools = [.. availableTools .Cast<AITool>()];
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
@@ -1204,9 +1207,23 @@ namespace xAiApi.Providers
[
introductionPrompt,
];
//
// Prepare Datetime ...
var datetimeContext = BuildDateTimeContext();
if (!datetimeContext.IsNullOrEmpty())
{
//
result.Add(new ChatMessage(
ChatRole.Assistant,
datetimeContext
));
}
//
if (forcePrompt &&
prompt is not null &&
!string.IsNullOrWhiteSpace(prompt))
!prompt.IsNullOrEmpty())
{
result.Add(promptMessage);
}
@@ -1236,6 +1253,7 @@ namespace xAiApi.Providers
}
//
var datetimeContext = BuildDateTimeContext();
var contextBlock = BuildContextBlock(context);
var systemText = introductionPrompt;
if (context.HasChild() &&
@@ -1244,7 +1262,17 @@ namespace xAiApi.Providers
{
//
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}" +
$"Context:{Environment.NewLine}{contextBlock}";
}
@@ -1305,12 +1333,22 @@ namespace xAiApi.Providers
$"Context:{Environment.NewLine}{contextBlock}";
}
//
// Prepare Datetime ...
var datetimeContext = BuildDateTimeContext();
if (!datetimeContext.IsNullOrEmpty())
{
//
systemText +=
$"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
}
//
// Apply Project Prompt as System Text ...
if (!project.IsNullOrDefault() &&
!project.Prompt.IsNullOrEmpty())
{
systemText += $"{project.Prompt}{Environment.NewLine}";
systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}";
}
//
@@ -1670,6 +1708,77 @@ namespace xAiApi.Providers
//
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
}
}
+16 -3
View File
@@ -207,13 +207,23 @@ namespace xAiApi.Providers
return $"✗ Error: {ex.Message} ...";
}
}
/// <summary>
/// Force Refresh Mcp Servers ...
/// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <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 ...");
foreach (var client in clients.Values)
@@ -230,7 +240,10 @@ namespace xAiApi.Providers
//
isInitialized = false;
await GetAvailableToolsAsync(cancellationToken: CancellationToken.None);
await GetAvailableToolsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
);
}
#endregion
+9 -1
View File
@@ -130,7 +130,15 @@
"MetadataMimeType": "mimeType",
"PromptName": "ChatWithDocuments",
"MetadataChunkIndex": "chunkIndex"
}
},
"DateTime": {
"IncludeDayOfWeek": true,
"IncludeUnixTimestamp": false,
"InjectIntoSystemPrompt": true,
"IncludePersianCalendar": true,
"DefaultTimezone": "Asia/Tehran",
"GregorianFormat": "yyyy-MM-dd HH:mm:ss"
}
},
"Logging": {
"LogLevel": {