mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
aee1acbf8b
* Foundry Evals integration for .NET - Core evaluation framework: EvalItem, LocalEvaluator, FunctionEvaluator, EvalChecks - IAgentEvaluator interface with MeaiEvaluatorAdapter bridge - AgentEvaluationExtensions for agent.EvaluateAsync() overloads - FoundryEvals wrapping MEAI quality/safety evaluators - ConversationSplitters (LastTurn, Full) and IConversationSplitter - EvalItem.PerTurnItems() for multi-turn decomposition - HasImageContent for multimodal content detection - WorkflowEvaluationExtensions for per-agent workflow evaluation - 7 eval samples mirroring Python parity: 02-agents/Evaluation: SimpleEval, ExpectedOutputs, Multimodal 03-workflows/Evaluation: WorkflowEval 05-end-to-end/Evaluation: FoundryQuality, MixedProviders, ConversationSplits - Comprehensive unit tests (1958 passing) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Rewrite FoundryEvals to use real Foundry Evals API Replace MEAI evaluator shim with actual OpenAI EvaluationClient protocol methods. FoundryEvals now creates eval definitions, submits runs, polls for completion, and fetches per-item results server-side. - New constructor: FoundryEvals(AIProjectClient, model, evaluators) - Add FoundryEvalConverter for MEAI ChatMessage -> Foundry JSON format - Add EvalId, RunId, ReportUrl to AgentEvaluationResults - All 20 built-in evaluator constants now work (agent, tool, quality, safety) - Remove Microsoft.Extensions.AI.Evaluation.Quality/Safety dependencies - Update all samples for new constructor (no more ChatConfiguration) - Replace BuildEvaluators tests with ResolveEvaluator tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Add response output to CustomEvals and ExpectedOutputs samples Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address review: pagination, validation, error handling, tests FoundryEvals fixes: - Add pagination for output items (has_more/after cursor) - Add guard clauses for pollIntervalSeconds/timeoutSeconds <= 0 - Fix double TryGetProperty for passed field parsing - Throw on all-tool-evaluators with no tool definitions - Fix XML doc (default 300s, not 180s) New tests (30 added, 1989 total): - EvalChecks: NonEmpty, ContainsExpected (pass/fail/skip/case), HasImageContent, ToolCallsPresent - FoundryEvalConverter: ConvertMessage (text, image, function call, function results fan-out, empty fallback, mixed content), ConvertEvalItem, BuildTestingCriteria (quality/agent/tool/groundedness data mappings), BuildItemSchema Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix review: null-refs, Data.ToString() bug, ContainsExpected, add tests - Fix NullReferenceException in sample Response display (pattern matching) - Fix WorkflowEvaluationExtensions Data?.ToString() producing type names instead of message text (pattern-match ChatMessage/AgentResponse/list) - Change EvalChecks.ContainsExpected to return Passed=false when no ExpectedOutput (was silently passing, masking misconfiguration) - Add EvalItem constructor tests with LastTurn/Full/null splitters - Add FoundryEvalConverter.ConvertMessage DataContent (base64 image) test - Add ExtractAgentData tests with ChatMessage, list, and AgentResponse data Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix review: conversation fidelity, eval caching, fallback tests - WorkflowEvaluationExtensions: preserve full response messages (tool calls, intermediate) instead of synthetic 2-message conversation. Cast completed Data to AgentResponse and use Messages when available, fallback to text. - FoundryEvals: cache evalId per schema shape (hasContext, hasTools) so subsequent EvaluateAsync calls create runs under the same eval definition. - MeaiEvaluatorAdapter: code already correctly passes queryMessages (not full conversation) to IEvaluator — no change needed, verified by inspection. - Add tests: AgentResponse full messages preservation, unknown object ToString() fallback for ExtractAgentData. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Rename AzureAI→Foundry: move eval files, update references - Move FoundryEvals.cs and FoundryEvalConverter.cs from Microsoft.Agents.AI.AzureAI to Microsoft.Agents.AI.Foundry - Update namespace from AzureAI to Foundry in both files - Add explicit usings required by Foundry project (no implicit usings) - Move FoundryEvalConverter tests to Foundry.UnitTests project (avoids ReplacingRedactor type conflict from dual project refs) - Update all sample csproj references and using statements - Remove Foundry project reference from AI UnitTests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * PR review round 4: wire up tool extraction, remove eval cache, fix null safety - BuildEvalItem: extract tools from agent via GetService<ChatOptions>() into EvalItem.Tools (Python parity) - FoundryEvals: remove eval ID cache - each call creates fresh definition (matches Python behavior) - FoundryEvals: replace null-forgiving operators with descriptive InvalidOperationException - MixedProviders sample: remove unnecessary explicit PackageReferences (transitively provided) - FoundryEvalConverter: document that tool results take precedence over text content - Add LocalEvaluator zero-checks test documenting 0 metrics = failed behavior Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Python-dotnet parity: 9 feature gaps filled New checks: - ToolCallArgsMatch() — verify tool call names + argument subset match - ToolCalledCheck(ToolCalledMode.Any, ...) — match any of the specified tools - ToolCalledMode enum (All/Any) FoundryEvals enhancements: - Default evaluators now [Relevance, Coherence, TaskAdherence] (was Relevance, Coherence) - Auto-add ToolCallAccuracy when items have tool definitions - EvaluateTracesAsync — evaluate by response_ids, trace_ids, or agent_id - EvaluateFoundryTargetAsync — evaluate deployed Foundry targets Result type enrichment: - AgentEvaluationResults: added Status, Error, PerEvaluator, DetailedItems - New EvalItemResult/EvalScoreResult/PerEvaluatorResult types - FoundryEvals populates all new fields from API responses Workflow fix: - Skip internal executors (_*, input-conversation, end-conversation, end) Tests: 8 new tests covering ToolCallArgsMatch, ToolCalledMode.Any, internal executor filtering Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Add MeaiEvaluatorAdapter and PerTurnItems edge case tests - 3 tests for MeaiEvaluatorAdapter: query message forwarding, synthetic response fallback, multiple items aggregation - 3 tests for EvalItem.PerTurnItems: empty conversation, no user messages, system+assistant only - StubEvaluator and StubChatClient test helpers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Blocking link check for outdated package in DevUI. * Replace Dictionary<string, object> payloads with typed wire models Introduce internal FoundryEvalWireModels.cs with compile-time-safe types for the OpenAI Evals API wire format. The OpenAI .NET SDK (2.9.1) only provides protocol-level methods with BinaryContent/ClientResult — no typed request models. These internal models replace scattered dictionary literals with [JsonPropertyName]-annotated classes, giving: - Compile-time safety (typos become build errors) - Single point of change when the API evolves - IntelliSense discoverability - Cleaner serialization via JsonPolymorphic for content items Models: WireContentItem hierarchy (text, image, tool_call, tool_result), WireMessage, WireEvalItemPayload, WireTestingCriterion, WireItemSchema, WireCreateEvalRequest, WireCreateRunRequest, and data source variants. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Skip metric when Foundry returns neither score nor passed When an evaluator returns no score and no passed value, the previous code created BooleanMetric(name, false), which falsely failed items via ItemPassed. Now we skip the MEAI metric entirely for indeterminate results — the raw data remains available in DetailedItems for diagnostics. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address PR #4914 review comments: fix tool evaluator bug and add tests - Fix duplicate ToolCallAccuracy: resolve evaluator names before checking against ToolEvaluators set (Comment 2) - Make FilterToolEvaluators internal for testability; add tests for the ArgumentException edge case when all evaluators are tool-type (Comment 3) - Add CancellationToken test for LocalEvaluator (Comment 4) - Add EvaluateAsync integration test on Run with sequential workflow and per-agent SubResults verification (Comment 5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address Peter's review comments on PR #4914 - Add trailing newline to Evaluation_FoundryQuality.csproj (Comment 6) - Make evaluator name lookups case-insensitive: switch BuiltinEvaluators, ToolEvaluators, AgentEvaluators, and ResolveEvaluator's StartsWith check from Ordinal to OrdinalIgnoreCase (Comment 7) - Add Trace.TraceWarning when Foundry returns fewer results than submitted items, indicating expected vs actual count before padding (Comment 8) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Add Microsoft.Extensions.AI.Evaluation packages to Directory.Packages.props These were removed in #5269 as unused, but are needed by the Foundry and core evaluation integration added in this PR. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: alliscode <bentho@microsoft.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
329 lines
12 KiB
C#
329 lines
12 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text.Json;
|
|
using Microsoft.Extensions.AI;
|
|
|
|
namespace Microsoft.Agents.AI;
|
|
|
|
/// <summary>
|
|
/// Specifies how <see cref="EvalChecks.ToolCalledCheck(ToolCalledMode, string[])"/> matches tool names.
|
|
/// </summary>
|
|
public enum ToolCalledMode
|
|
{
|
|
/// <summary>All specified tools must have been called.</summary>
|
|
All,
|
|
|
|
/// <summary>At least one of the specified tools must have been called.</summary>
|
|
Any,
|
|
}
|
|
|
|
/// <summary>
|
|
/// Built-in check functions for common evaluation patterns.
|
|
/// </summary>
|
|
public static class EvalChecks
|
|
{
|
|
/// <summary>
|
|
/// Creates a check that verifies the response contains all specified keywords.
|
|
/// </summary>
|
|
/// <param name="keywords">Keywords that must appear in the response.</param>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck KeywordCheck(params string[] keywords)
|
|
{
|
|
return KeywordCheck(caseSensitive: false, keywords);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a check that verifies the response contains all specified keywords.
|
|
/// </summary>
|
|
/// <param name="caseSensitive">Whether the comparison is case-sensitive.</param>
|
|
/// <param name="keywords">Keywords that must appear in the response.</param>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck KeywordCheck(bool caseSensitive, params string[] keywords)
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
var comparison = caseSensitive
|
|
? StringComparison.Ordinal
|
|
: StringComparison.OrdinalIgnoreCase;
|
|
|
|
var missing = keywords
|
|
.Where(kw => !item.Response.Contains(kw, comparison))
|
|
.ToList();
|
|
|
|
var passed = missing.Count == 0;
|
|
var reason = passed
|
|
? $"All keywords found: {string.Join(", ", keywords)}"
|
|
: $"Missing keywords: {string.Join(", ", missing)}";
|
|
|
|
return new EvalCheckResult(passed, reason, "keyword_check");
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a check that verifies specific tools were called in the conversation.
|
|
/// All specified tools must have been called.
|
|
/// </summary>
|
|
/// <param name="toolNames">Tool names that must appear in the conversation.</param>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck ToolCalledCheck(params string[] toolNames)
|
|
{
|
|
return ToolCalledCheck(ToolCalledMode.All, toolNames);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a check that verifies specific tools were called in the conversation.
|
|
/// </summary>
|
|
/// <param name="mode">Whether <see cref="ToolCalledMode.All"/> or <see cref="ToolCalledMode.Any"/> of the specified tools must be called.</param>
|
|
/// <param name="toolNames">Tool names to check for.</param>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck ToolCalledCheck(ToolCalledMode mode, params string[] toolNames)
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
var calledTools = GetCalledTools(item);
|
|
|
|
if (mode == ToolCalledMode.Any)
|
|
{
|
|
var found = toolNames.Where(t => calledTools.Contains(t)).ToList();
|
|
var passed = found.Count > 0;
|
|
var reason = passed
|
|
? $"Called: {string.Join(", ", found)}"
|
|
: $"None of expected tools called: {string.Join(", ", toolNames)}";
|
|
return new EvalCheckResult(passed, reason, "tool_called_check");
|
|
}
|
|
|
|
var missing = toolNames.Where(t => !calledTools.Contains(t)).ToList();
|
|
var allPassed = missing.Count == 0;
|
|
var allReason = allPassed
|
|
? $"All tools called: {string.Join(", ", toolNames)}"
|
|
: $"Missing tool calls: {string.Join(", ", missing)}";
|
|
|
|
return new EvalCheckResult(allPassed, allReason, "tool_called_check");
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// A check that verifies at least one tool was called in the conversation.
|
|
/// </summary>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck ToolCallsPresent()
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
var calledTools = GetCalledTools(item);
|
|
var passed = calledTools.Count > 0;
|
|
var reason = passed
|
|
? $"Tools called: {string.Join(", ", calledTools)}"
|
|
: "No tool calls found in conversation";
|
|
|
|
return new EvalCheckResult(passed, reason, "tool_calls_present");
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// A check that verifies expected tool calls match on name and optionally arguments.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// For each expected tool call, finds matching calls in the conversation by name.
|
|
/// If <see cref="ExpectedToolCall.Arguments"/> is provided, checks that the actual
|
|
/// arguments contain all expected key-value pairs (subset match — extra actual arguments are OK).
|
|
/// </para>
|
|
/// <para>If no expected tool calls are set on the item, the check passes.</para>
|
|
/// </remarks>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck ToolCallArgsMatch()
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
var expected = item.ExpectedToolCalls;
|
|
if (expected is null || expected.Count == 0)
|
|
{
|
|
return new EvalCheckResult(true, "No expected tool calls specified.", "tool_call_args_match");
|
|
}
|
|
|
|
var actualCalls = GetCalledToolsWithArgs(item);
|
|
int matched = 0;
|
|
var details = new List<string>();
|
|
|
|
foreach (var exp in expected)
|
|
{
|
|
var matching = actualCalls.Where(c => string.Equals(c.Name, exp.Name, StringComparison.OrdinalIgnoreCase)).ToList();
|
|
|
|
if (matching.Count == 0)
|
|
{
|
|
details.Add($" {exp.Name}: not called");
|
|
continue;
|
|
}
|
|
|
|
if (exp.Arguments is null)
|
|
{
|
|
matched++;
|
|
details.Add($" {exp.Name}: called (args not checked)");
|
|
continue;
|
|
}
|
|
|
|
// Subset match — all expected keys present with expected values
|
|
bool found = false;
|
|
foreach (var call in matching)
|
|
{
|
|
if (call.Arguments is not null
|
|
&& exp.Arguments.All(kvp =>
|
|
call.Arguments.TryGetValue(kvp.Key, out var actual)
|
|
&& Equals(actual, kvp.Value)))
|
|
{
|
|
found = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (found)
|
|
{
|
|
matched++;
|
|
details.Add($" {exp.Name}: args match");
|
|
}
|
|
else
|
|
{
|
|
details.Add($" {exp.Name}: args mismatch");
|
|
}
|
|
}
|
|
|
|
var passed = matched == expected.Count;
|
|
var reason = $"Tool call args match: {matched}/{expected.Count}\n{string.Join("\n", details)}";
|
|
return new EvalCheckResult(passed, reason, "tool_call_args_match");
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a check that verifies the response is non-empty and meets a minimum length.
|
|
/// </summary>
|
|
/// <param name="minLength">Minimum response length (default 1).</param>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck NonEmpty(int minLength = 1)
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
var trimmed = item.Response.Trim();
|
|
var passed = trimmed.Length >= minLength;
|
|
var reason = passed
|
|
? $"Response length {trimmed.Length} meets minimum {minLength}"
|
|
: $"Response length {trimmed.Length} is below minimum {minLength}";
|
|
|
|
return new EvalCheckResult(passed, reason, "non_empty");
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a check that verifies the response contains the expected output text.
|
|
/// </summary>
|
|
/// <param name="caseSensitive">Whether the comparison is case-sensitive (default false).</param>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck ContainsExpected(bool caseSensitive = false)
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
if (string.IsNullOrEmpty(item.ExpectedOutput))
|
|
{
|
|
return new EvalCheckResult(false, "ExpectedOutput is not set; check cannot be applied.", "contains_expected");
|
|
}
|
|
|
|
var comparison = caseSensitive
|
|
? StringComparison.Ordinal
|
|
: StringComparison.OrdinalIgnoreCase;
|
|
|
|
var passed = item.Response.Contains(item.ExpectedOutput, comparison);
|
|
var reason = passed
|
|
? $"Response contains expected output: \"{item.ExpectedOutput}\""
|
|
: $"Response does not contain expected output: \"{item.ExpectedOutput}\"";
|
|
|
|
return new EvalCheckResult(passed, reason, "contains_expected");
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// A check that verifies the conversation contains at least one image
|
|
/// (<see cref="DataContent"/> or <see cref="UriContent"/> with an image media type).
|
|
/// </summary>
|
|
/// <returns>An <see cref="EvalCheck"/> delegate.</returns>
|
|
public static EvalCheck HasImageContent()
|
|
{
|
|
return (EvalItem item) =>
|
|
{
|
|
var passed = item.HasImageContent;
|
|
var reason = passed
|
|
? "Conversation contains image content"
|
|
: "No image content found in conversation";
|
|
|
|
return new EvalCheckResult(passed, reason, "has_image_content");
|
|
};
|
|
}
|
|
|
|
private static HashSet<string> GetCalledTools(EvalItem item)
|
|
{
|
|
var calledTools = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
foreach (var message in item.Conversation)
|
|
{
|
|
foreach (var content in message.Contents)
|
|
{
|
|
if (content is FunctionCallContent functionCall)
|
|
{
|
|
calledTools.Add(functionCall.Name);
|
|
}
|
|
}
|
|
}
|
|
|
|
return calledTools;
|
|
}
|
|
|
|
private static List<(string Name, IReadOnlyDictionary<string, object>? Arguments)> GetCalledToolsWithArgs(EvalItem item)
|
|
{
|
|
var calls = new List<(string Name, IReadOnlyDictionary<string, object>? Arguments)>();
|
|
|
|
foreach (var message in item.Conversation)
|
|
{
|
|
foreach (var content in message.Contents)
|
|
{
|
|
if (content is FunctionCallContent functionCall)
|
|
{
|
|
IDictionary<string, object?>? rawArgs = functionCall.Arguments;
|
|
IReadOnlyDictionary<string, object>? args = null;
|
|
if (rawArgs is not null)
|
|
{
|
|
var dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
|
|
foreach (var kvp in rawArgs)
|
|
{
|
|
if (kvp.Value is not null)
|
|
{
|
|
// Normalize JsonElement values to their .NET equivalents for comparison
|
|
dict[kvp.Key] = kvp.Value is JsonElement je ? UnwrapJsonElement(je) : kvp.Value;
|
|
}
|
|
}
|
|
|
|
args = dict;
|
|
}
|
|
|
|
calls.Add((functionCall.Name, args));
|
|
}
|
|
}
|
|
}
|
|
|
|
return calls;
|
|
}
|
|
|
|
private static object UnwrapJsonElement(JsonElement element)
|
|
{
|
|
return element.ValueKind switch
|
|
{
|
|
JsonValueKind.String => element.GetString()!,
|
|
JsonValueKind.Number => element.TryGetInt64(out var l) ? l : element.GetDouble(),
|
|
JsonValueKind.True => true,
|
|
JsonValueKind.False => false,
|
|
_ => element.ToString(),
|
|
};
|
|
}
|
|
}
|