Update analyzers for .NET 10 SDK (#2611)

This commit is contained in:
Stephen Toub
2025-12-10 05:34:56 -05:00
committed by GitHub
Unverified
parent 2f0b2db12a
commit b01fd23cd2
41 changed files with 382 additions and 259 deletions
@@ -281,7 +281,7 @@ internal sealed class A2AAgent : AIAgent
private static A2AContinuationToken? CreateContinuationToken(string taskId, TaskState state)
{
if (state == TaskState.Submitted || state == TaskState.Working)
if (state is TaskState.Submitted or TaskState.Working)
{
return new A2AContinuationToken(taskId);
}
@@ -220,7 +220,11 @@ public sealed class AGUIChatClient : DelegatingChatClient
if (options?.Tools is { Count: > 0 })
{
input.Tools = options.Tools.AsAGUITools();
this._logger.LogDebug("[AGUIChatClient] Tool count: {ToolCount}", options.Tools.Count);
if (this._logger.IsEnabled(LogLevel.Debug))
{
this._logger.LogDebug("[AGUIChatClient] Tool count: {ToolCount}", options.Tools.Count);
}
}
var clientToolSet = new HashSet<string>();
@@ -27,7 +27,7 @@ internal static class ActivityProcessor
{
yield return CreateChatMessageFromActivity(activity, [new TextContent(activity.Text)]);
}
else
else if (logger.IsEnabled(LogLevel.Warning))
{
logger.LogWarning("Unknown activity type '{ActivityType}' received.", activity.Type);
}
@@ -274,7 +274,7 @@ public sealed class CosmosChatMessageStore : ChatMessageStore, IDisposable
throw new ArgumentException("Invalid serialized state", nameof(serializedStoreState));
}
var state = JsonSerializer.Deserialize<StoreState>(serializedStoreState, jsonSerializerOptions);
var state = serializedStoreState.Deserialize<StoreState>(jsonSerializerOptions);
if (state?.ConversationIdentifier is not { } conversationId)
{
throw new ArgumentException("Invalid serialized state", nameof(serializedStoreState));
@@ -83,7 +83,11 @@ internal sealed partial class DevUIMiddleware
context.Response.StatusCode = StatusCodes.Status301MovedPermanently;
context.Response.Headers.Location = redirectUrl;
this._logger.LogDebug("Redirecting {OriginalPath} to {RedirectUrl}", NewlineRegex().Replace(path, ""), NewlineRegex().Replace(redirectUrl, ""));
if (this._logger.IsEnabled(LogLevel.Debug))
{
this._logger.LogDebug("Redirecting {OriginalPath} to {RedirectUrl}", NewlineRegex().Replace(path, ""), NewlineRegex().Replace(redirectUrl, ""));
}
return;
}
@@ -123,7 +127,11 @@ internal sealed partial class DevUIMiddleware
{
if (!this._resourceCache.TryGetValue(resourcePath.Replace('.', '/'), out var cacheEntry))
{
this._logger.LogDebug("Embedded resource not found: {ResourcePath}", resourcePath);
if (this._logger.IsEnabled(LogLevel.Debug))
{
this._logger.LogDebug("Embedded resource not found: {ResourcePath}", resourcePath);
}
return false;
}
@@ -133,7 +141,12 @@ internal sealed partial class DevUIMiddleware
if (context.Request.Headers.IfNoneMatch == cacheEntry.ETag)
{
response.StatusCode = StatusCodes.Status304NotModified;
this._logger.LogDebug("Resource not modified (304): {ResourcePath}", resourcePath);
if (this._logger.IsEnabled(LogLevel.Debug))
{
this._logger.LogDebug("Resource not modified (304): {ResourcePath}", resourcePath);
}
return true;
}
@@ -161,12 +174,20 @@ internal sealed partial class DevUIMiddleware
await response.Body.WriteAsync(content, context.RequestAborted).ConfigureAwait(false);
this._logger.LogDebug("Served embedded resource: {ResourcePath} (compressed: {Compressed})", resourcePath, serveCompressed);
if (this._logger.IsEnabled(LogLevel.Debug))
{
this._logger.LogDebug("Served embedded resource: {ResourcePath} (compressed: {Compressed})", resourcePath, serveCompressed);
}
return true;
}
catch (Exception ex)
{
this._logger.LogError(ex, "Error serving embedded resource: {ResourcePath}", resourcePath);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(ex, "Error serving embedded resource: {ResourcePath}", resourcePath);
}
return false;
}
}
@@ -98,8 +98,10 @@ public sealed class DurableAIAgent : AIAgent
responseFormat = chatClientOptions.ChatOptions?.ResponseFormat;
}
RunRequest request = new([.. messages], responseFormat, enableToolCalls, enableToolNames);
request.OrchestrationId = this._context.InstanceId;
RunRequest request = new([.. messages], responseFormat, enableToolCalls, enableToolNames)
{
OrchestrationId = this._context.InstanceId
};
try
{
@@ -46,7 +46,7 @@ internal sealed class DurableAgentStateFunctionCallContent : DurableAgentStateCo
{
return new DurableAgentStateFunctionCallContent()
{
Arguments = content.Arguments?.ToImmutableDictionary() ?? ImmutableDictionary<string, object?>.Empty,
Arguments = content.Arguments?.ToDictionary() ?? [],
CallId = content.CallId,
Name = content.Name
};
@@ -20,8 +20,6 @@ internal sealed partial class AGUIServerSentEventsResult : IResult, IDisposable
private readonly ILogger<AGUIServerSentEventsResult> _logger;
private Utf8JsonWriter? _jsonWriter;
public int? StatusCode => StatusCodes.Status200OK;
internal AGUIServerSentEventsResult(IAsyncEnumerable<BaseEvent> events, ILogger<AGUIServerSentEventsResult> logger)
{
this._events = events;
@@ -59,7 +59,11 @@ internal sealed class HostedAgentResponseExecutor : IResponseExecutor
AIAgent? agent = this._serviceProvider.GetKeyedService<AIAgent>(agentName);
if (agent is null)
{
this._logger.LogWarning("Failed to resolve agent with name '{AgentName}'", agentName);
if (this._logger.IsEnabled(LogLevel.Warning))
{
this._logger.LogWarning("Failed to resolve agent with name '{AgentName}'", agentName);
}
return ValueTask.FromResult<ResponseError?>(new ResponseError
{
Code = "agent_not_found",
@@ -133,7 +133,7 @@ internal sealed class Mem0Client
[JsonPropertyName("agent_id")] public string? AgentId { get; set; }
[JsonPropertyName("run_id")] public string? RunId { get; set; }
[JsonPropertyName("user_id")] public string? UserId { get; set; }
[JsonPropertyName("messages")] public CreateMemoryMessage[] Messages { get; set; } = Array.Empty<CreateMemoryMessage>();
[JsonPropertyName("messages")] public CreateMemoryMessage[] Messages { get; set; } = [];
}
internal sealed class CreateMemoryMessage
@@ -153,7 +153,7 @@ public sealed class Mem0Provider : AIContextProvider
? null
: $"{this._contextPrompt}\n{string.Join(Environment.NewLine, memories)}";
if (this._logger is not null)
if (this._logger?.IsEnabled(LogLevel.Information) is true)
{
this._logger.LogInformation(
"Mem0AIContextProvider: Retrieved {Count} memories. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
@@ -162,7 +162,8 @@ public sealed class Mem0Provider : AIContextProvider
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
if (outputMessageText is not null)
if (outputMessageText is not null && this._logger.IsEnabled(LogLevel.Trace))
{
this._logger.LogTrace(
"Mem0AIContextProvider: Search Results\nInput:{Input}\nOutput:{MessageText}\nApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
@@ -186,13 +187,16 @@ public sealed class Mem0Provider : AIContextProvider
}
catch (Exception ex)
{
this._logger?.LogError(
ex,
"Mem0AIContextProvider: Failed to search Mem0 for memories due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
if (this._logger?.IsEnabled(LogLevel.Error) is true)
{
this._logger.LogError(
ex,
"Mem0AIContextProvider: Failed to search Mem0 for memories due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
}
return new AIContext();
}
}
@@ -212,13 +216,16 @@ public sealed class Mem0Provider : AIContextProvider
}
catch (Exception ex)
{
this._logger?.LogError(
ex,
"Mem0AIContextProvider: Failed to send messages to Mem0 due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._storageScope.ApplicationId,
this._storageScope.AgentId,
this._storageScope.ThreadId,
this.SanitizeLogData(this._storageScope.UserId));
if (this._logger?.IsEnabled(LogLevel.Error) is true)
{
this._logger.LogError(
ex,
"Mem0AIContextProvider: Failed to send messages to Mem0 due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._storageScope.ApplicationId,
this._storageScope.AgentId,
this._storageScope.ThreadId,
this.SanitizeLogData(this._storageScope.UserId));
}
}
}
@@ -43,7 +43,10 @@ internal sealed class BackgroundJobRunner
}
catch (Exception e) when (e is not OperationCanceledException and not SystemException)
{
this._logger.LogError(e, "Error running background job {BackgroundJobError}.", e.Message);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(e, "Error running background job {BackgroundJobError}.", e.Message);
}
}
}
});
@@ -73,7 +73,10 @@ internal class ChannelHandler : IChannelHandler
}
catch (Exception e) when (this._purviewSettings.IgnoreExceptions)
{
this._logger.LogError(e, "Error queuing job: {ExceptionMessage}", e.Message);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(e, "Error queuing job: {ExceptionMessage}", e.Message);
}
}
}
@@ -38,16 +38,12 @@ public class PurviewAppLocation
/// <exception cref="InvalidOperationException">Thrown when an invalid location type is provided.</exception>
internal PolicyLocation GetPolicyLocation()
{
switch (this.LocationType)
return this.LocationType switch
{
case PurviewLocationType.Application:
return new PolicyLocation($"{Constants.ODataGraphNamespace}.policyLocationApplication", this.LocationValue);
case PurviewLocationType.Uri:
return new PolicyLocation($"{Constants.ODataGraphNamespace}.policyLocationUrl", this.LocationValue);
case PurviewLocationType.Domain:
return new PolicyLocation($"{Constants.ODataGraphNamespace}.policyLocationDomain", this.LocationValue);
default:
throw new InvalidOperationException("Invalid location type.");
}
PurviewLocationType.Application => new($"{Constants.ODataGraphNamespace}.policyLocationApplication", this.LocationValue),
PurviewLocationType.Uri => new($"{Constants.ODataGraphNamespace}.policyLocationUrl", this.LocationValue),
PurviewLocationType.Domain => new($"{Constants.ODataGraphNamespace}.policyLocationDomain", this.LocationValue),
_ => throw new InvalidOperationException("Invalid location type."),
};
}
}
@@ -58,7 +58,7 @@ internal sealed class PurviewClient : IPurviewClient
this._tokenCredential = tokenCredential;
this._httpClient = httpClient;
this._scopes = new string[] { $"https://{purviewSettings.GraphBaseUri.Host}/.default" };
this._scopes = [$"https://{purviewSettings.GraphBaseUri.Host}/.default"];
this._graphUri = purviewSettings.GraphBaseUri.ToString().TrimEnd('/');
this._logger = logger ?? NullLogger.Instance;
}
@@ -176,7 +176,11 @@ internal sealed class PurviewClient : IPurviewClient
throw new PurviewRequestException(DeserializeError);
}
this._logger.LogError("Failed to process content. Status code: {StatusCode}", response.StatusCode);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError("Failed to process content. Status code: {StatusCode}", response.StatusCode);
}
throw CreateExceptionForStatusCode(response.StatusCode, "processContent");
}
}
@@ -241,7 +245,11 @@ internal sealed class PurviewClient : IPurviewClient
throw new PurviewRequestException(DeserializeError);
}
this._logger.LogError("Failed to retrieve protection scopes. Status code: {StatusCode}", response.StatusCode);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError("Failed to retrieve protection scopes. Status code: {StatusCode}", response.StatusCode);
}
throw CreateExceptionForStatusCode(response.StatusCode, "protectionScopes/compute");
}
}
@@ -304,7 +312,11 @@ internal sealed class PurviewClient : IPurviewClient
throw new PurviewRequestException(DeserializeError);
}
this._logger.LogError("Failed to create content activities. Status code: {StatusCode}", response.StatusCode);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError("Failed to create content activities. Status code: {StatusCode}", response.StatusCode);
}
throw CreateExceptionForStatusCode(response.StatusCode, "contentActivities");
}
}
@@ -73,13 +73,20 @@ internal sealed class PurviewWrapper : IDisposable
(bool shouldBlockPrompt, resolvedUserId) = await this._scopedProcessor.ProcessMessagesAsync(messages, options?.ConversationId, Activity.UploadText, this._purviewSettings, null, cancellationToken).ConfigureAwait(false);
if (shouldBlockPrompt)
{
this._logger.LogInformation("Prompt blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedPromptMessage);
if (this._logger.IsEnabled(LogLevel.Information))
{
this._logger.LogInformation("Prompt blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedPromptMessage);
}
return new ChatResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedPromptMessage));
}
}
catch (Exception ex)
{
this._logger.LogError(ex, "Error processing prompt: {ExceptionMessage}", ex.Message);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(ex, "Error processing prompt: {ExceptionMessage}", ex.Message);
}
if (!this._purviewSettings.IgnoreExceptions)
{
@@ -94,13 +101,20 @@ internal sealed class PurviewWrapper : IDisposable
(bool shouldBlockResponse, _) = await this._scopedProcessor.ProcessMessagesAsync(response.Messages, options?.ConversationId, Activity.UploadText, this._purviewSettings, resolvedUserId, cancellationToken).ConfigureAwait(false);
if (shouldBlockResponse)
{
this._logger.LogInformation("Response blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedResponseMessage);
if (this._logger.IsEnabled(LogLevel.Information))
{
this._logger.LogInformation("Response blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedResponseMessage);
}
return new ChatResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedResponseMessage));
}
}
catch (Exception ex)
{
this._logger.LogError(ex, "Error processing response: {ExceptionMessage}", ex.Message);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(ex, "Error processing response: {ExceptionMessage}", ex.Message);
}
if (!this._purviewSettings.IgnoreExceptions)
{
@@ -132,13 +146,20 @@ internal sealed class PurviewWrapper : IDisposable
if (shouldBlockPrompt)
{
this._logger.LogInformation("Prompt blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedPromptMessage);
if (this._logger.IsEnabled(LogLevel.Information))
{
this._logger.LogInformation("Prompt blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedPromptMessage);
}
return new AgentRunResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedPromptMessage));
}
}
catch (Exception ex)
{
this._logger.LogError(ex, "Error processing prompt: {ExceptionMessage}", ex.Message);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(ex, "Error processing prompt: {ExceptionMessage}", ex.Message);
}
if (!this._purviewSettings.IgnoreExceptions)
{
@@ -154,13 +175,20 @@ internal sealed class PurviewWrapper : IDisposable
if (shouldBlockResponse)
{
this._logger.LogInformation("Response blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedResponseMessage);
if (this._logger.IsEnabled(LogLevel.Information))
{
this._logger.LogInformation("Response blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedResponseMessage);
}
return new AgentRunResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedResponseMessage));
}
}
catch (Exception ex)
{
this._logger.LogError(ex, "Error processing response: {ExceptionMessage}", ex.Message);
if (this._logger.IsEnabled(LogLevel.Error))
{
this._logger.LogError(ex, "Error processing response: {ExceptionMessage}", ex.Message);
}
if (!this._purviewSettings.IgnoreExceptions)
{
@@ -242,23 +242,16 @@ internal sealed class ScopedContentProcessor : IScopedContentProcessor
/// </summary>
/// <param name="pcResponse">The process content response which may contain DLP actions.</param>
/// <param name="actionInfos">DLP actions returned from protection scopes.</param>
/// <returns>The process content response with the protection scopes DLP actions added. Actions are deduplicated.</returns>
/// <returns>The process content response with the protection scopes DLP actions added.</returns>
private static ProcessContentResponse CombinePolicyActions(ProcessContentResponse pcResponse, List<DlpActionInfo>? actionInfos)
{
if (actionInfos == null || actionInfos.Count == 0)
if (actionInfos?.Count > 0)
{
return pcResponse;
pcResponse.PolicyActions = pcResponse.PolicyActions is null ?
actionInfos :
[.. pcResponse.PolicyActions, .. actionInfos];
}
if (pcResponse.PolicyActions == null)
{
pcResponse.PolicyActions = actionInfos;
return pcResponse;
}
List<DlpActionInfo> pcActionInfos = new(pcResponse.PolicyActions);
pcActionInfos.AddRange(actionInfos);
pcResponse.PolicyActions = pcActionInfos;
return pcResponse;
}
@@ -339,20 +332,14 @@ internal sealed class ScopedContentProcessor : IScopedContentProcessor
/// <returns>The protection scopes activity.</returns>
private static ProtectionScopeActivities TranslateActivity(Activity activity)
{
switch (activity)
return activity switch
{
case Activity.Unknown:
return ProtectionScopeActivities.None;
case Activity.UploadText:
return ProtectionScopeActivities.UploadText;
case Activity.UploadFile:
return ProtectionScopeActivities.UploadFile;
case Activity.DownloadText:
return ProtectionScopeActivities.DownloadText;
case Activity.DownloadFile:
return ProtectionScopeActivities.DownloadFile;
default:
return ProtectionScopeActivities.UnknownFutureValue;
}
Activity.Unknown => ProtectionScopeActivities.None,
Activity.UploadText => ProtectionScopeActivities.UploadText,
Activity.UploadFile => ProtectionScopeActivities.UploadFile,
Activity.DownloadText => ProtectionScopeActivities.DownloadText,
Activity.DownloadFile => ProtectionScopeActivities.DownloadFile,
_ => ProtectionScopeActivities.UnknownFutureValue,
};
}
}
@@ -46,7 +46,7 @@ internal static class RepresentationExtensions
keySelector: sourceId => sourceId,
elementSelector: sourceId => workflow.Edges[sourceId].Select(ToEdgeInfo).ToList());
HashSet<RequestPortInfo> inputPorts = new(workflow.Ports.Values.Select(ToPortInfo));
HashSet<RequestPortInfo> inputPorts = [.. workflow.Ports.Values.Select(ToPortInfo)];
return new WorkflowInfo(executors, edges, inputPorts, workflow.StartExecutorId, workflow.OutputExecutors);
}
@@ -41,8 +41,8 @@ public sealed class EdgeConnection : IEquatable<EdgeConnection>
/// contains duplicate values.</exception>
public static EdgeConnection CreateChecked(List<string> sourceIds, List<string> sinkIds)
{
HashSet<string> sourceSet = new(Throw.IfNull(sourceIds));
HashSet<string> sinkSet = new(Throw.IfNull(sinkIds));
HashSet<string> sourceSet = [.. Throw.IfNull(sourceIds)];
HashSet<string> sinkSet = [.. Throw.IfNull(sinkIds)];
if (sourceSet.Count != sourceIds.Count)
{
@@ -14,7 +14,7 @@ internal sealed class FanInEdgeState
public FanInEdgeState(FanInEdgeData fanInEdge)
{
this.SourceIds = fanInEdge.SourceIds.ToArray();
this.Unseen = new(this.SourceIds);
this.Unseen = [.. this.SourceIds];
this._pendingMessages = [];
}
@@ -40,7 +40,7 @@ internal sealed class FanInEdgeState
if (this.Unseen.Count == 0)
{
List<PortableMessageEnvelope> takenMessages = Interlocked.Exchange(ref this._pendingMessages, []);
this.Unseen = new(this.SourceIds);
this.Unseen = [.. this.SourceIds];
if (takenMessages.Count == 0)
{
@@ -380,7 +380,7 @@ public class WorkflowBuilder
}
// Make sure that all nodes are connected to the start executor (transitively)
HashSet<string> remainingExecutors = new(this._executorBindings.Keys);
HashSet<string> remainingExecutors = [.. this._executorBindings.Keys];
Queue<string> toVisit = new([this._startExecutorId]);
if (!validateOrphans)
@@ -212,13 +212,17 @@ public sealed class ChatHistoryMemoryProvider : AIContextProvider, IDisposable
}
catch (Exception ex)
{
this._logger?.LogError(
ex,
"ChatHistoryMemoryProvider: Failed to search for chat history due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
if (this._logger?.IsEnabled(LogLevel.Error) is true)
{
this._logger.LogError(
ex,
"ChatHistoryMemoryProvider: Failed to search for chat history due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
}
return new AIContext();
}
}
@@ -264,13 +268,16 @@ public sealed class ChatHistoryMemoryProvider : AIContextProvider, IDisposable
}
catch (Exception ex)
{
this._logger?.LogError(
ex,
"ChatHistoryMemoryProvider: Failed to add messages to chat history vector store due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
if (this._logger?.IsEnabled(LogLevel.Error) is true)
{
this._logger.LogError(
ex,
"ChatHistoryMemoryProvider: Failed to add messages to chat history vector store due to error. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
}
}
}
@@ -302,14 +309,18 @@ public sealed class ChatHistoryMemoryProvider : AIContextProvider, IDisposable
var formatted = $"{this._contextPrompt}\n{outputResultsText}";
this._logger?.LogTrace(
"ChatHistoryMemoryProvider: Search Results\nInput:{Input}\nOutput:{MessageText}\n ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this.SanitizeLogData(userQuestion),
this.SanitizeLogData(formatted),
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
if (this._logger?.IsEnabled(LogLevel.Trace) is true)
{
this._logger.LogTrace(
"ChatHistoryMemoryProvider: Search Results\nInput:{Input}\nOutput:{MessageText}\n ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
this.SanitizeLogData(userQuestion),
this.SanitizeLogData(formatted),
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
}
return formatted;
}
@@ -383,13 +394,16 @@ public sealed class ChatHistoryMemoryProvider : AIContextProvider, IDisposable
results.Add(result.Record);
}
this._logger?.LogInformation(
"ChatHistoryMemoryProvider: Retrieved {Count} search results. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
results.Count,
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
if (this._logger?.IsEnabled(LogLevel.Information) is true)
{
this._logger.LogInformation(
"ChatHistoryMemoryProvider: Retrieved {Count} search results. ApplicationId: '{ApplicationId}', AgentId: '{AgentId}', ThreadId: '{ThreadId}', UserId: '{UserId}'.",
results.Count,
this._searchScope.ApplicationId,
this._searchScope.AgentId,
this._searchScope.ThreadId,
this.SanitizeLogData(this._searchScope.UserId));
}
return results;
}
@@ -134,7 +134,11 @@ public sealed class TextSearchProvider : AIContextProvider
// Search
var results = await this._searchAsync(input, cancellationToken).ConfigureAwait(false);
IList<TextSearchResult> materialized = results as IList<TextSearchResult> ?? results.ToList();
this._logger?.LogInformation("TextSearchProvider: Retrieved {Count} search results.", materialized.Count);
if (this._logger?.IsEnabled(LogLevel.Information) is true)
{
this._logger?.LogInformation("TextSearchProvider: Retrieved {Count} search results.", materialized.Count);
}
if (materialized.Count == 0)
{
@@ -144,7 +148,10 @@ public sealed class TextSearchProvider : AIContextProvider
// Format search results
string formatted = this.FormatResults(materialized);
this._logger?.LogTrace("TextSearchProvider: Search Results\nInput:{Input}\nOutput:{MessageText}", input, formatted);
if (this._logger?.IsEnabled(LogLevel.Trace) is true)
{
this._logger.LogTrace("TextSearchProvider: Search Results\nInput:{Input}\nOutput:{MessageText}", input, formatted);
}
return new AIContext
{
@@ -230,8 +237,15 @@ public sealed class TextSearchProvider : AIContextProvider
IList<TextSearchResult> materialized = results as IList<TextSearchResult> ?? results.ToList();
string outputText = this.FormatResults(materialized);
this._logger?.LogInformation("TextSearchProvider: Retrieved {Count} search results.", materialized.Count);
this._logger?.LogTrace("TextSearchProvider Input:{UserQuestion}\nOutput:{MessageText}", userQuestion, outputText);
if (this._logger?.IsEnabled(LogLevel.Information) is true)
{
this._logger.LogInformation("TextSearchProvider: Retrieved {Count} search results.", materialized.Count);
if (this._logger.IsEnabled(LogLevel.Trace))
{
this._logger.LogTrace("TextSearchProvider Input:{UserQuestion}\nOutput:{MessageText}", userQuestion, outputText);
}
}
return outputText;
}