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
+1 -2
View File
@@ -3,8 +3,7 @@
<!-- Default properties inherited by all projects. Projects can override. -->
<RunAnalyzersDuringBuild>true</RunAnalyzersDuringBuild>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisLevel>10.0-all</AnalysisLevel>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
+1
View File
@@ -1,6 +1,7 @@
# Suppressing errors for Sample projects under dotnet/samples folder
[*.cs]
dotnet_diagnostic.CA1716.severity = none # Add summary to documentation comment.
dotnet_diagnostic.CA1873.severity = none # Evaluation of logging arguments may be expensive
dotnet_diagnostic.CA2000.severity = none # Call System.IDisposable.Dispose on object before all references to it are out of scope
dotnet_diagnostic.CA2007.severity = none # Do not directly await a Task
@@ -49,7 +49,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
GenerateContentResponse generateResult = await this._models.GenerateContentAsync(modelId!, contents, config).ConfigureAwait(false);
// Create the response.
ChatResponse chatResponse = new(new ChatMessage(ChatRole.Assistant, new List<AIContent>()))
ChatResponse chatResponse = new(new ChatMessage(ChatRole.Assistant, []))
{
CreatedAt = generateResult.CreateTime is { } dt ? new DateTimeOffset(dt) : null,
ModelId = !string.IsNullOrWhiteSpace(generateResult.ModelVersion) ? generateResult.ModelVersion : modelId,
@@ -82,7 +82,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
await foreach (GenerateContentResponse generateResult in this._models.GenerateContentStreamAsync(modelId!, contents, config).WithCancellation(cancellationToken).ConfigureAwait(false))
{
// Create a response update for each result in the stream.
ChatResponseUpdate responseUpdate = new(ChatRole.Assistant, new List<AIContent>())
ChatResponseUpdate responseUpdate = new(ChatRole.Assistant, [])
{
CreatedAt = generateResult.CreateTime is { } dt ? new DateTimeOffset(dt) : null,
ModelId = !string.IsNullOrWhiteSpace(generateResult.ModelVersion) ? generateResult.ModelVersion : modelId,
@@ -148,7 +148,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
// create the request instance, allowing the caller to populate it with GenAI-specific options. Otherwise, create
// a new instance directly.
string? model = this._defaultModelId;
List<Content> contents = new();
List<Content> contents = [];
GenerateContentConfig config = options?.RawRepresentationFactory?.Invoke(this) as GenerateContentConfig ?? new();
if (options is not null)
@@ -160,7 +160,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
if (options.Instructions is { } instructions)
{
((config.SystemInstruction ??= new()).Parts ??= new()).Add(new() { Text = instructions });
((config.SystemInstruction ??= new()).Parts ??= []).Add(new() { Text = instructions });
}
if (options.MaxOutputTokens is { } maxOutputTokens)
@@ -185,7 +185,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
if (options.StopSequences is { } stopSequences)
{
(config.StopSequences ??= new()).AddRange(stopSequences);
(config.StopSequences ??= []).AddRange(stopSequences);
}
if (options.Temperature is { } temperature)
@@ -213,7 +213,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
switch (tool)
{
case AIFunctionDeclaration af:
functionDeclarations ??= new();
functionDeclarations ??= [];
functionDeclarations.Add(new()
{
Name = af.Name,
@@ -223,15 +223,15 @@ internal sealed class GoogleGenAIChatClient : IChatClient
break;
case HostedCodeInterpreterTool:
(config.Tools ??= new()).Add(new() { CodeExecution = new() });
(config.Tools ??= []).Add(new() { CodeExecution = new() });
break;
case HostedFileSearchTool:
(config.Tools ??= new()).Add(new() { Retrieval = new() });
(config.Tools ??= []).Add(new() { Retrieval = new() });
break;
case HostedWebSearchTool:
(config.Tools ??= new()).Add(new() { GoogleSearch = new() });
(config.Tools ??= []).Add(new() { GoogleSearch = new() });
break;
}
}
@@ -240,8 +240,8 @@ internal sealed class GoogleGenAIChatClient : IChatClient
if (functionDeclarations is { Count: > 0 })
{
Tool functionTools = new();
(functionTools.FunctionDeclarations ??= new()).AddRange(functionDeclarations);
(config.Tools ??= new()).Add(functionTools);
(functionTools.FunctionDeclarations ??= []).AddRange(functionDeclarations);
(config.Tools ??= []).Add(functionTools);
}
// Transfer over the tool mode if there are any tools.
@@ -261,7 +261,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
config.ToolConfig = new() { FunctionCallingConfig = new() { Mode = FunctionCallingConfigMode.ANY } };
if (required.RequiredFunctionName is not null)
{
((config.ToolConfig.FunctionCallingConfig ??= new()).AllowedFunctionNames ??= new()).Add(required.RequiredFunctionName);
((config.ToolConfig.FunctionCallingConfig ??= new()).AllowedFunctionNames ??= []).Add(required.RequiredFunctionName);
}
break;
}
@@ -287,14 +287,14 @@ internal sealed class GoogleGenAIChatClient : IChatClient
string instruction = message.Text;
if (!string.IsNullOrWhiteSpace(instruction))
{
((config.SystemInstruction ??= new()).Parts ??= new()).Add(new() { Text = instruction });
((config.SystemInstruction ??= new()).Parts ??= []).Add(new() { Text = instruction });
}
continue;
}
Content content = new() { Role = message.Role == ChatRole.Assistant ? "model" : "user" };
content.Parts ??= new();
content.Parts ??= [];
AddPartsForAIContents(ref callIdToFunctionNames, message.Contents, content.Parts);
contents.Add(content);
@@ -367,7 +367,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
break;
case FunctionCallContent functionCallContent:
(callIdToFunctionNames ??= new())[functionCallContent.CallId] = functionCallContent.Name;
(callIdToFunctionNames ??= [])[functionCallContent.CallId] = functionCallContent.Name;
callIdToFunctionNames[""] = functionCallContent.Name; // track last function name in case calls don't have IDs
part = new()
@@ -480,22 +480,22 @@ internal sealed class GoogleGenAIChatClient : IChatClient
{
foreach (var citation in citations)
{
textContent.Annotations = new List<AIAnnotation>()
{
new CitationAnnotation()
{
Title = citation.Title,
Url = Uri.TryCreate(citation.Uri, UriKind.Absolute, out Uri? uri) ? uri : null,
AnnotatedRegions = new List<AnnotatedRegion>()
{
new TextSpanAnnotatedRegion()
{
StartIndex = citation.StartIndex,
EndIndex = citation.EndIndex,
}
},
}
};
textContent.Annotations =
[
new CitationAnnotation()
{
Title = citation.Title,
Url = Uri.TryCreate(citation.Uri, UriKind.Absolute, out Uri? uri) ? uri : null,
AnnotatedRegions =
[
new TextSpanAnnotatedRegion()
{
StartIndex = citation.StartIndex,
EndIndex = citation.EndIndex,
}
],
}
];
}
}
}
@@ -551,7 +551,7 @@ internal sealed class GoogleGenAIChatClient : IChatClient
{
if (value is int i)
{
(details.AdditionalCounts ??= new())[key] = i;
(details.AdditionalCounts ??= [])[key] = i;
}
}
}
@@ -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;
}
+4
View File
@@ -1,6 +1,10 @@
# Suppressing errors for Test projects under dotnet/tests folder
[*.cs]
dotnet_diagnostic.CA1822.severity = none # Member does not access instance data and can be marked as static
dotnet_diagnostic.CA1873.severity = none # Evaluation of logging arguments may be expensive
dotnet_diagnostic.CA1875.severity = none # Regex.IsMatch/Count instead of Regex.Match(...).Success/Regex.Matches(...).Count
dotnet_diagnostic.CA2007.severity = none # Do not directly await a Task
dotnet_diagnostic.CA2249.severity = none # Use `string.Contains` instead of `string.IndexOf` to improve readability
dotnet_diagnostic.CS1591.severity = none # Missing XML comment for publicly visible type or member
@@ -547,7 +547,7 @@ public sealed class A2AAgentTests : IDisposable
var result = await this._agent.RunAsync("Test message");
// Assert
if (taskState == TaskState.Submitted || taskState == TaskState.Working)
if (taskState is TaskState.Submitted or TaskState.Working)
{
Assert.NotNull(result.ContinuationToken);
}
@@ -64,12 +64,12 @@ public sealed class A2AArtifactExtensionsTests
{
ArtifactId = "artifact-ai-multi",
Name = "test",
Parts = new List<Part>
{
Parts =
[
new TextPart { Text = "Part 1" },
new TextPart { Text = "Part 2" },
new TextPart { Text = "Part 3" }
},
],
Metadata = null
};
@@ -93,7 +93,7 @@ public sealed class A2AArtifactExtensionsTests
{
ArtifactId = "artifact-empty",
Name = "test",
Parts = new List<Part>(),
Parts = [],
Metadata = null
};
@@ -919,7 +919,7 @@ public sealed class AGUIAgentTests
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
// Act - First turn
List<ChatMessage> conversation = new(messages);
List<ChatMessage> conversation = [.. messages];
string? conversationId = null;
await foreach (var update in chatClient.GetStreamingResponseAsync(conversation, options))
{
@@ -2684,13 +2684,12 @@ public sealed class AzureAIProjectChatClientExtensionsTests
private sealed class MockPipelineResponse : PipelineResponse
{
private readonly int _status;
private readonly BinaryData _content;
private readonly MockPipelineResponseHeaders _headers;
public MockPipelineResponse(int status, BinaryData? content = null)
{
this._status = status;
this._content = content ?? BinaryData.Empty;
this.Content = content ?? BinaryData.Empty;
this._headers = new MockPipelineResponseHeaders();
}
@@ -2704,7 +2703,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
set { }
}
public override BinaryData Content => this._content;
public override BinaryData Content { get; }
protected override PipelineResponseHeaders HeadersCore => this._headers;
@@ -8,7 +8,6 @@ using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.AI;
using Xunit;
@@ -81,7 +80,7 @@ public sealed class CosmosChatMessageStoreTests : IAsyncLifetime, IDisposable
throughput: 400);
// Create container for hierarchical partitioning tests with hierarchical partition key
var hierarchicalContainerProperties = new ContainerProperties(HierarchicalTestContainerId, new List<string> { "/tenantId", "/userId", "/sessionId" });
var hierarchicalContainerProperties = new ContainerProperties(HierarchicalTestContainerId, ["/tenantId", "/userId", "/sessionId"]);
await databaseResponse.Database.CreateContainerIfNotExistsAsync(
hierarchicalContainerProperties,
throughput: 400);
@@ -247,7 +246,7 @@ public sealed class CosmosChatMessageStoreTests : IAsyncLifetime, IDisposable
PartitionKey = new PartitionKey(conversationId)
});
List<dynamic> rawResults = new();
List<dynamic> rawResults = [];
while (rawIterator.HasMoreResults)
{
var rawResponse = await rawIterator.ReadNextAsync();
@@ -77,7 +77,7 @@ public class CosmosCheckpointStoreTests : IAsyncLifetime, IDisposable
this._emulatorAvailable = true;
}
catch (Exception ex) when (!(ex is OutOfMemoryException || ex is StackOverflowException || ex is AccessViolationException))
catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException))
{
// Emulator not available, tests will be skipped
this._emulatorAvailable = false;
@@ -100,9 +100,6 @@ public sealed class AGUIServerSentEventsResultTests
// Act
await result.ExecuteAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status200OK, result.StatusCode);
}
[Fact]
@@ -49,14 +49,14 @@ public sealed class Mem0ProviderTests : IDisposable
var sut = new Mem0Provider(this._httpClient, storageScope);
await sut.ClearStoredMemoriesAsync();
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
Assert.DoesNotContain("Caoimhe", ctxBefore.Messages?[0].Text ?? string.Empty);
// Act
await sut.InvokedAsync(new AIContextProvider.InvokedContext(new[] { input }, aiContextProviderMessages: null));
await sut.InvokedAsync(new AIContextProvider.InvokedContext([input], aiContextProviderMessages: null));
var ctxAfterAdding = await GetContextWithRetryAsync(sut, question);
await sut.ClearStoredMemoriesAsync();
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
// Assert
Assert.Contains("Caoimhe", ctxAfterAdding.Messages?[0].Text ?? string.Empty);
@@ -73,14 +73,14 @@ public sealed class Mem0ProviderTests : IDisposable
var sut = new Mem0Provider(this._httpClient, storageScope);
await sut.ClearStoredMemoriesAsync();
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
Assert.DoesNotContain("Caoimhe", ctxBefore.Messages?[0].Text ?? string.Empty);
// Act
await sut.InvokedAsync(new AIContextProvider.InvokedContext(new[] { assistantIntro }, aiContextProviderMessages: null));
await sut.InvokedAsync(new AIContextProvider.InvokedContext([assistantIntro], aiContextProviderMessages: null));
var ctxAfterAdding = await GetContextWithRetryAsync(sut, question);
await sut.ClearStoredMemoriesAsync();
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxAfterClearing = await sut.InvokingAsync(new AIContextProvider.InvokingContext([question]));
// Assert
Assert.Contains("Caoimhe", ctxAfterAdding.Messages?[0].Text ?? string.Empty);
@@ -99,13 +99,13 @@ public sealed class Mem0ProviderTests : IDisposable
await sut1.ClearStoredMemoriesAsync();
await sut2.ClearStoredMemoriesAsync();
var ctxBefore1 = await sut1.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore2 = await sut2.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }));
var ctxBefore1 = await sut1.InvokingAsync(new AIContextProvider.InvokingContext([question]));
var ctxBefore2 = await sut2.InvokingAsync(new AIContextProvider.InvokingContext([question]));
Assert.DoesNotContain("Caoimhe", ctxBefore1.Messages?[0].Text ?? string.Empty);
Assert.DoesNotContain("Caoimhe", ctxBefore2.Messages?[0].Text ?? string.Empty);
// Act
await sut1.InvokedAsync(new AIContextProvider.InvokedContext(new[] { assistantIntro }, aiContextProviderMessages: null));
await sut1.InvokedAsync(new AIContextProvider.InvokedContext([assistantIntro], aiContextProviderMessages: null));
var ctxAfterAdding1 = await GetContextWithRetryAsync(sut1, question);
var ctxAfterAdding2 = await GetContextWithRetryAsync(sut2, question);
@@ -123,7 +123,7 @@ public sealed class Mem0ProviderTests : IDisposable
AIContext? ctx = null;
for (int i = 0; i < attempts; i++)
{
ctx = await provider.InvokingAsync(new AIContextProvider.InvokingContext(new[] { question }), CancellationToken.None);
ctx = await provider.InvokingAsync(new AIContextProvider.InvokingContext([question]), CancellationToken.None);
var text = ctx.Messages?[0].Text;
if (!string.IsNullOrEmpty(text) && text.IndexOf("Caoimhe", StringComparison.OrdinalIgnoreCase) >= 0)
{
@@ -35,6 +35,10 @@ public sealed class Mem0ProviderTests : IDisposable
.Setup(f => f.CreateLogger(typeof(Mem0Provider).FullName!))
.Returns(this._loggerMock.Object);
this._loggerMock
.Setup(f => f.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
this._httpClient = new HttpClient(this._handler)
{
BaseAddress = new Uri("https://localhost/")
@@ -131,10 +135,10 @@ public sealed class Mem0ProviderTests : IDisposable
}
[Theory]
[InlineData(false, false, 2)]
[InlineData(true, false, 2)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, false, 4)]
[InlineData(true, false, 4)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokingAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogInvocations)
{
// Arrange
@@ -157,7 +161,7 @@ public sealed class Mem0ProviderTests : IDisposable
var options = new Mem0ProviderOptions { EnableSensitiveTelemetryData = enableSensitiveTelemetryData };
var sut = new Mem0Provider(this._httpClient, storageScope, options: options, loggerFactory: this._loggerFactoryMock.Object);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Who am I?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Who am I?")]);
// Act
await sut.InvokingAsync(invokingContext, CancellationToken.None);
@@ -166,7 +170,12 @@ public sealed class Mem0ProviderTests : IDisposable
Assert.Equal(expectedLogInvocations, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
var state = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2]);
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user" : "<redacted>", userIdValue);
@@ -275,8 +284,8 @@ public sealed class Mem0ProviderTests : IDisposable
[Theory]
[InlineData(false, false, 0)]
[InlineData(true, false, 0)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokedAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogCount)
{
// Arrange
@@ -315,7 +324,12 @@ public sealed class Mem0ProviderTests : IDisposable
Assert.Equal(expectedLogCount, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
var state = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2]);
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user" : "<redacted>", userIdValue);
}
@@ -386,7 +400,7 @@ public sealed class Mem0ProviderTests : IDisposable
// Arrange
var storageScope = new Mem0ProviderScope { ApplicationId = "app" };
var provider = new Mem0Provider(this._httpClient, storageScope, loggerFactory: this._loggerFactoryMock.Object);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
@@ -50,10 +49,10 @@ public sealed class PurviewClientTests : IDisposable
{
Id = "test-id-123",
ProtectionScopeState = ProtectionScopeState.NotModified,
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { Action = DlpAction.NotifyUser }
}
]
};
this._handler.StatusCodeToReturn = HttpStatusCode.OK;
@@ -228,8 +227,8 @@ public sealed class PurviewClientTests : IDisposable
var expectedResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -238,7 +237,7 @@ public sealed class PurviewClientTests : IDisposable
new ("microsoft.graph.policyLocationApplication", "app-123")
]
}
}
]
};
this._handler.StatusCodeToReturn = HttpStatusCode.OK;
@@ -264,7 +263,7 @@ public sealed class PurviewClientTests : IDisposable
{
// Arrange
var request = new ProtectionScopesRequest("test-user-id", "test-tenant-id");
var expectedResponse = new ProtectionScopesResponse { Scopes = new List<PolicyScopeBase>() };
var expectedResponse = new ProtectionScopesResponse { Scopes = [] };
this._handler.StatusCodeToReturn = HttpStatusCode.OK;
this._handler.ResponseToReturn = JsonSerializer.Serialize(expectedResponse, PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(ProtectionScopesResponse)));
@@ -56,8 +56,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -67,7 +67,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -76,10 +76,10 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { Action = DlpAction.BlockAccess }
}
]
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -115,8 +115,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -126,7 +126,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -135,10 +135,10 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { RestrictionAction = RestrictionAction.Block }
}
]
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -174,8 +174,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -185,7 +185,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -194,10 +194,10 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>
{
PolicyActions =
[
new() { Action = DlpAction.NotifyUser }
}
]
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -229,8 +229,8 @@ public sealed class ScopedContentProcessorTests
var cachedPsResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -240,7 +240,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockCacheProvider.Setup(x => x.GetAsync<ProtectionScopesCacheKey, ProtectionScopesResponse>(
@@ -249,7 +249,7 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
PolicyActions = new List<DlpActionInfo>()
PolicyActions = []
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -285,8 +285,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -296,7 +296,7 @@ public sealed class ScopedContentProcessorTests
],
ExecutionMode = ExecutionMode.EvaluateInline
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -306,7 +306,7 @@ public sealed class ScopedContentProcessorTests
var pcResponse = new ProcessContentResponse
{
ProtectionScopeState = ProtectionScopeState.Modified,
PolicyActions = new List<DlpActionInfo>()
PolicyActions = []
};
this._mockPurviewClient.Setup(x => x.ProcessContentAsync(
@@ -342,8 +342,8 @@ public sealed class ScopedContentProcessorTests
var psResponse = new ProtectionScopesResponse
{
Scopes = new List<PolicyScopeBase>
{
Scopes =
[
new()
{
Activities = ProtectionScopeActivities.UploadText,
@@ -352,7 +352,7 @@ public sealed class ScopedContentProcessorTests
new ("microsoft.graph.policyLocationApplication", "app-456")
]
}
}
]
};
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
@@ -436,7 +436,7 @@ public sealed class ScopedContentProcessorTests
It.IsAny<ProtectionScopesCacheKey>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((ProtectionScopesResponse?)null);
var psResponse = new ProtectionScopesResponse { Scopes = new List<PolicyScopeBase>() };
var psResponse = new ProtectionScopesResponse { Scopes = [] };
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
It.IsAny<ProtectionScopesRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(psResponse);
@@ -471,7 +471,7 @@ public sealed class ScopedContentProcessorTests
It.IsAny<ProtectionScopesCacheKey>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((ProtectionScopesResponse?)null);
var psResponse = new ProtectionScopesResponse { Scopes = new List<PolicyScopeBase>() };
var psResponse = new ProtectionScopesResponse { Scopes = [] };
this._mockPurviewClient.Setup(x => x.GetProtectionScopesAsync(
It.IsAny<ProtectionScopesRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(psResponse);
@@ -30,6 +30,10 @@ public sealed class TextSearchProviderTests
this._loggerFactoryMock
.Setup(f => f.CreateLogger(typeof(TextSearchProvider).FullName!))
.Returns(this._loggerMock.Object);
this._loggerMock
.Setup(f => f.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
}
[Theory]
@@ -135,7 +139,7 @@ public sealed class TextSearchProviderTests
FunctionToolDescription = overrideDescription
};
var provider = new TextSearchProvider(this.NoResultSearchAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -154,7 +158,7 @@ public sealed class TextSearchProviderTests
{
// Arrange
var provider = new TextSearchProvider(this.FailingSearchAsync, default, null, loggerFactory: this._loggerFactoryMock.Object);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -247,7 +251,7 @@ public sealed class TextSearchProviderTests
ContextFormatter = r => $"Custom formatted context with {r.Count} results."
};
var provider = new TextSearchProvider(SearchDelegateAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -281,7 +285,7 @@ public sealed class TextSearchProviderTests
ContextFormatter = r => string.Join(",", r.Select(x => ((RawPayload)x.RawRepresentation!).Id))
};
var provider = new TextSearchProvider(SearchDelegateAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -298,7 +302,7 @@ public sealed class TextSearchProviderTests
// Arrange
var options = new TextSearchProviderOptions { SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke };
var provider = new TextSearchProvider(this.NoResultSearchAsync, default, null, options);
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "Q?") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "Q?")]);
// Act
var aiContext = await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -338,10 +342,10 @@ public sealed class TextSearchProviderTests
};
await provider.InvokedAsync(new(initialMessages, aiContextProviderMessages: null) { InvokeException = new InvalidOperationException("Request Failed") });
var invokingContext = new AIContextProvider.InvokingContext(new[]
{
var invokingContext = new AIContextProvider.InvokingContext(
[
new ChatMessage(ChatRole.User, "E")
});
]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -378,10 +382,10 @@ public sealed class TextSearchProviderTests
};
await provider.InvokedAsync(new(initialMessages, aiContextProviderMessages: null));
var invokingContext = new AIContextProvider.InvokingContext(new[]
{
var invokingContext = new AIContextProvider.InvokingContext(
[
new ChatMessage(ChatRole.User, "E")
});
]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -409,21 +413,21 @@ public sealed class TextSearchProviderTests
var provider = new TextSearchProvider(SearchDelegateAsync, default, null, options);
// First memory update (A,B)
await provider.InvokedAsync(new(new[]
{
await provider.InvokedAsync(new(
[
new ChatMessage(ChatRole.User, "A"),
new ChatMessage(ChatRole.Assistant, "B"),
}, aiContextProviderMessages: null));
], aiContextProviderMessages: null));
// Second memory update (C,D,E)
await provider.InvokedAsync(new(new[]
{
await provider.InvokedAsync(new(
[
new ChatMessage(ChatRole.User, "C"),
new ChatMessage(ChatRole.Assistant, "D"),
new ChatMessage(ChatRole.User, "E"),
}, aiContextProviderMessages: null));
], aiContextProviderMessages: null));
var invokingContext = new AIContextProvider.InvokingContext(new[] { new ChatMessage(ChatRole.User, "F") });
var invokingContext = new AIContextProvider.InvokingContext([new ChatMessage(ChatRole.User, "F")]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -460,10 +464,10 @@ public sealed class TextSearchProviderTests
};
await provider.InvokedAsync(new(initialMessages, null));
var invokingContext = new AIContextProvider.InvokingContext(new[]
{
var invokingContext = new AIContextProvider.InvokingContext(
[
new ChatMessage(ChatRole.User, "Question?") // Current request message always appended.
});
]);
// Act
await provider.InvokingAsync(invokingContext, CancellationToken.None);
@@ -36,6 +36,10 @@ public class ChatHistoryMemoryProviderTests
.Setup(f => f.CreateLogger(typeof(ChatHistoryMemoryProvider).FullName!))
.Returns(this._loggerMock.Object);
this._loggerMock
.Setup(f => f.IsEnabled(It.IsAny<LogLevel>()))
.Returns(true);
this._vectorStoreCollectionMock = new(MockBehavior.Strict);
this._vectorStoreMock = new(MockBehavior.Strict);
@@ -218,8 +222,8 @@ public class ChatHistoryMemoryProviderTests
[Theory]
[InlineData(false, false, 0)]
[InlineData(true, false, 0)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokedAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogInvocations)
{
// Arrange
@@ -259,6 +263,11 @@ public class ChatHistoryMemoryProviderTests
Assert.Equal(expectedLogInvocations, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user1" : "<redacted>", userIdValue);
@@ -385,10 +394,10 @@ public class ChatHistoryMemoryProviderTests
}
[Theory]
[InlineData(false, false, 1)]
[InlineData(true, false, 1)]
[InlineData(false, true, 1)]
[InlineData(true, true, 1)]
[InlineData(false, false, 2)]
[InlineData(true, false, 2)]
[InlineData(false, true, 2)]
[InlineData(true, true, 2)]
public async Task InvokingAsync_LogsUserIdBasedOnEnableSensitiveTelemetryDataAsync(bool enableSensitiveTelemetryData, bool requestThrows, int expectedLogInvocations)
{
// Arrange
@@ -442,7 +451,12 @@ public class ChatHistoryMemoryProviderTests
Assert.Equal(expectedLogInvocations, this._loggerMock.Invocations.Count);
foreach (var logInvocation in this._loggerMock.Invocations)
{
var state = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2]);
if (logInvocation.Method.Name == nameof(ILogger.IsEnabled))
{
continue;
}
var state = Assert.IsType<IReadOnlyList<KeyValuePair<string, object?>>>(logInvocation.Arguments[2], exactMatch: false);
var userIdValue = state.First(kvp => kvp.Key == "UserId").Value;
Assert.Equal(enableSensitiveTelemetryData ? "user1" : "<redacted>", userIdValue);
@@ -57,7 +57,7 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre
protected virtual IEnumerable<ChatMessage> GetEpilogueMessages(AgentRunOptions? options = null)
{
return Enumerable.Empty<ChatMessage>();
return [];
}
public override Task<AgentRunResponse> RunAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)