mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
08541ee5a9
* .NET: Refactor AgentSkill API to async resource and script lookup Replace property-based AgentSkill.Content, Resources, and Scripts with async-by-name lookup methods plus boolean availability flags: - Content (string getter) -> GetContentAsync(CancellationToken) - Resources (full list) -> HasResources + GetResourceAsync(name, ct) - Scripts (full list) -> HasScripts + GetScriptAsync(name, ct) This makes the API friendlier for sources like MCP where enumerating all resources up front is expensive or impossible, and allows skill implementations to fetch content lazily. Subclass changes: - AgentFileSkill and AgentInlineSkill implement the new async API while preserving content caching. - AgentClassSkill<TSelf> keeps virtual Resources/Scripts properties for reflection-based discovery and seals the new HasResources/HasScripts/ GetResourceAsync/GetScriptAsync overrides. Its previously non-thread-safe lazy initialization is replaced with Lazy<T> (default thread-safety) wired up in a new protected constructor, so concurrent first-access from multiple threads is safe. - AgentSkillsProvider calls the new async API and exposes ead_skill_resource / load_skill / un_skill_script tools that await the per-name lookups. Includes baseline CompatibilitySuppressions.xml entries for the removed property getters. Tests: - Direct coverage for HasResources, HasScripts, GetResourceAsync, and GetScriptAsync on all three skill implementations (positive, missing-name, and no-resources/no-scripts cases). - Thread-safety regression test for AgentClassSkill<TSelf> that exercises concurrent first-access to Resources, Scripts, and GetContentAsync from many tasks and asserts all observers see the same cached instance. - Provider-level coverage for the ead_skill_resource tool (invocation + error paths) and for the previously untested error paths of load_skill and un_skill_script (empty names, skill/resource/script not found). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address PR review comments - Move GetScriptAsync inside try/catch in RunSkillScriptAsync for error-handling parity - Remove dead _reflectedResources branch from AgentSkillTestExtensions - Fix XML docs to reference virtual Resources/Scripts properties (not sealed methods) - Add Async suffix to async test methods per naming convention - Make no-await tests synchronous to eliminate CS1998 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix formatting: add UTF-8 BOM and remove unused using Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix XML cref: Resources/Scripts are on AgentClassSkill<TSelf> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Remove HasResources and HasScripts properties from AgentSkill Drop the virtual HasResources and HasScripts properties from AgentSkill and all concrete subclasses (AgentFileSkill, AgentInlineSkill, AgentClassSkill). AgentSkillsProvider now always includes all three tools (load_skill, read_skill_resource, run_skill_script) and both instruction blocks, since the tools already handle missing resources/scripts gracefully. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Add blank line for readability in file-based skills sample Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix HostedAgentSkillsPatternTests for always-included tools Update assertions to expect read_skill_resource and run_skill_script tools are always present, matching the new behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
112 lines
4.3 KiB
C#
112 lines
4.3 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
||
|
||
// This sample demonstrates how to define Agent Skills as C# classes using AgentClassSkill
|
||
// with attributes for automatic script and resource discovery.
|
||
|
||
using System.ComponentModel;
|
||
using System.Text.Json;
|
||
using Azure.AI.OpenAI;
|
||
using Azure.Identity;
|
||
using Microsoft.Agents.AI;
|
||
using OpenAI.Responses;
|
||
|
||
// --- Configuration ---
|
||
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
|
||
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-5.4-mini";
|
||
|
||
// --- Class-Based Skill ---
|
||
// Instantiate the skill class.
|
||
var unitConverter = new UnitConverterSkill();
|
||
|
||
// --- Skills Provider ---
|
||
var skillsProvider = new AgentSkillsProvider(unitConverter);
|
||
|
||
// --- Agent Setup ---
|
||
AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
|
||
.GetResponsesClient()
|
||
.AsAIAgent(new ChatClientAgentOptions
|
||
{
|
||
Name = "UnitConverterAgent",
|
||
ChatOptions = new()
|
||
{
|
||
Instructions = "You are a helpful assistant that can convert units.",
|
||
},
|
||
AIContextProviders = [skillsProvider],
|
||
},
|
||
model: deploymentName);
|
||
|
||
// --- Example: Unit conversion ---
|
||
Console.WriteLine("Converting units with class-based skills");
|
||
Console.WriteLine(new string('-', 60));
|
||
|
||
AgentResponse response = await agent.RunAsync(
|
||
"How many kilometers is a marathon (26.2 miles)? And how many pounds is 75 kilograms?");
|
||
|
||
Console.WriteLine($"Agent: {response.Text}");
|
||
|
||
/// <summary>
|
||
/// A unit-converter skill defined as a C# class using attributes for discovery.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// Properties annotated with <see cref="AgentSkillResourceAttribute"/> are automatically
|
||
/// discovered as skill resources, and methods annotated with <see cref="AgentSkillScriptAttribute"/>
|
||
/// are automatically discovered as skill scripts. Alternatively,
|
||
/// <see cref="AgentClassSkill{TSelf}.Resources"/> and <see cref="AgentClassSkill{TSelf}.Scripts"/> can be overridden.
|
||
/// </remarks>
|
||
internal sealed class UnitConverterSkill : AgentClassSkill<UnitConverterSkill>
|
||
{
|
||
/// <inheritdoc/>
|
||
public override AgentSkillFrontmatter Frontmatter { get; } = new(
|
||
"unit-converter",
|
||
"Convert between common units using a multiplication factor. Use when asked to convert miles, kilometers, pounds, or kilograms.");
|
||
|
||
/// <inheritdoc/>
|
||
protected override string Instructions => """
|
||
Use this skill when the user asks to convert between units.
|
||
|
||
1. Review the conversion-table resource to find the factor for the requested conversion.
|
||
2. Use the convert script, passing the value and factor from the table.
|
||
3. Present the result clearly with both units.
|
||
""";
|
||
|
||
/// <summary>
|
||
/// Gets the <see cref="JsonSerializerOptions"/> used to marshal parameters and return values
|
||
/// for scripts and resources.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// This override is not necessary for this sample, but can be used to provide custom
|
||
/// serialization options, for example a source-generated <c>JsonTypeInfoResolver</c>
|
||
/// for Native AOT compatibility.
|
||
/// </remarks>
|
||
protected override JsonSerializerOptions? SerializerOptions => null;
|
||
|
||
/// <summary>
|
||
/// A conversion table resource providing multiplication factors.
|
||
/// </summary>
|
||
[AgentSkillResource("conversion-table")]
|
||
[Description("Lookup table of multiplication factors for common unit conversions.")]
|
||
public string ConversionTable => """
|
||
# Conversion Tables
|
||
|
||
Formula: **result = value × factor**
|
||
|
||
| From | To | Factor |
|
||
|-------------|-------------|----------|
|
||
| miles | kilometers | 1.60934 |
|
||
| kilometers | miles | 0.621371 |
|
||
| pounds | kilograms | 0.453592 |
|
||
| kilograms | pounds | 2.20462 |
|
||
""";
|
||
|
||
/// <summary>
|
||
/// Converts a value by the given factor.
|
||
/// </summary>
|
||
[AgentSkillScript("convert")]
|
||
[Description("Multiplies a value by a conversion factor and returns the result as JSON.")]
|
||
private static string ConvertUnits(double value, double factor)
|
||
{
|
||
double result = Math.Round(value * factor, 4);
|
||
return JsonSerializer.Serialize(new { value, factor, result });
|
||
}
|
||
}
|