From ae7f5920c18c91f1030d884b7635d604e39678d6 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 5 Nov 2026 18:17:30 +0330 Subject: [PATCH] - 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 ... --- Configurations/XAiApiConfiguration.cs | 6 ++ Controllers/McpServersController.cs | 13 ++- Interfaces/IXAiMcpServerProvider.cs | 7 +- Models/XDateTimeDescriptor.cs | 35 ++++++++ Providers/XAIServiceBase.cs | 119 ++++++++++++++++++++++++-- Providers/XAiMcpServerProvider.cs | 19 +++- appsettings.Development.json | 10 ++- 7 files changed, 197 insertions(+), 12 deletions(-) create mode 100644 Models/XDateTimeDescriptor.cs diff --git a/Configurations/XAiApiConfiguration.cs b/Configurations/XAiApiConfiguration.cs index 480c14a..16bd734 100644 --- a/Configurations/XAiApiConfiguration.cs +++ b/Configurations/XAiApiConfiguration.cs @@ -45,5 +45,11 @@ namespace xAiApi.Configurations /// RAG Configuration ... /// public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); + + /// + /// DateTime Configuration ... + /// + /// + public XDateTimeDescriptor DateTime { get; set; } = new(); } } \ No newline at end of file diff --git a/Controllers/McpServersController.cs b/Controllers/McpServersController.cs index dd53a9a..5b4c55f 100644 --- a/Controllers/McpServersController.cs +++ b/Controllers/McpServersController.cs @@ -468,16 +468,25 @@ namespace xAiApi.Controllers /// /// Refresh MCP Servers ... /// + /// /// [HttpPost("Refresh")] [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task RefreshMcpServers() + public async Task RefreshMcpServers( + CancellationToken cancellationToken = default + ) { // try { // - await mcpServerProvider.RefreshAsync(); + var userInfo = await GetUserInfo(); + + // + await mcpServerProvider.RefreshAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); // return Ok(); diff --git a/Interfaces/IXAiMcpServerProvider.cs b/Interfaces/IXAiMcpServerProvider.cs index fb25baa..6c0d75f 100644 --- a/Interfaces/IXAiMcpServerProvider.cs +++ b/Interfaces/IXAiMcpServerProvider.cs @@ -45,8 +45,13 @@ namespace xAiApi.Interfaces /// /// Force Refresh Mcp Servers ... /// + /// + /// /// - Task RefreshAsync(); + Task RefreshAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); #endregion // diff --git a/Models/XDateTimeDescriptor.cs b/Models/XDateTimeDescriptor.cs new file mode 100644 index 0000000..de4be60 --- /dev/null +++ b/Models/XDateTimeDescriptor.cs @@ -0,0 +1,35 @@ +namespace xAiApi.Models +{ + public class XDateTimeDescriptor + { + /// + /// Adding Current DateTime to Prompt ... + /// + public bool InjectIntoSystemPrompt { get; set; } = true; + + /// + /// Time Zone ... + /// + public string DefaultTimezone { get; set; } = "Asia/Tehran"; + + /// + /// Georgian Date Format ... + /// + public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss"; + + /// + /// Include Persian Calendar ... + /// + public bool IncludePersianCalendar { get; set; } = true; + + /// + /// Include Day of Week ... + /// + public bool IncludeDayOfWeek { get; set; } = true; + + /// + /// Include Unix Timestamp ... + /// + public bool IncludeUnixTimestamp { get; set; } = false; + } +} \ No newline at end of file diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index c3958d2..27893bd 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -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()]; + Options.Tools = [.. availableTools.Cast()]; } // @@ -191,7 +194,7 @@ namespace xAiApi.Providers ); // - Options.Tools = [.. availableTools .Cast()]; + Options.Tools = [.. availableTools.Cast()]; } // @@ -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 } } \ No newline at end of file diff --git a/Providers/XAiMcpServerProvider.cs b/Providers/XAiMcpServerProvider.cs index 14f51ad..cb66efd 100644 --- a/Providers/XAiMcpServerProvider.cs +++ b/Providers/XAiMcpServerProvider.cs @@ -207,13 +207,23 @@ namespace xAiApi.Providers return $"✗ Error: {ex.Message} ..."; } } - + /// /// Force Refresh Mcp Servers ... /// + /// + /// /// - 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 diff --git a/appsettings.Development.json b/appsettings.Development.json index abf4493..c4b7352 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -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": {