Patterns and techniques for evaluating and improving AI agent outputs.
日本語の概要は準備中です。原文の説明を表示しています。
Integrates AI/LLM via Microsoft Agent Framework. Agents, workflows, tools, MCP servers, multi-agent orchestration.
インストールする前に、エージェントに与えられる指示の中身を確認できます。
Microsoft Agent Framework for building agentic AI applications in .NET. Covers agents, workflows, multi-agent orchestration, tool integration (MCP servers, function calling), provider configuration (Azure OpenAI, OpenAI, Microsoft Foundry, Anthropic, Ollama), chat history management, middleware, and enterprise features (observability, authentication, responsible AI).
Cross-references: [skill:dotnet-csharp-async-patterns] for async streaming patterns used with chat completions, [skill:dotnet-csharp-dependency-injection] for agent service registration in ASP.NET Core, [skill:dotnet-resilience] for retry policies on AI service calls, [skill:dotnet-csharp-configuration] for managing API keys and model configuration.
| Package | Purpose |
|---|---|
Microsoft.Agents.AI | Core abstractions, AIAgent base class |
Microsoft.Agents.AI.OpenAI | OpenAI provider support (Chat Completion, Responses, Assistants) |
Microsoft.Agents.AI.AzureAI | Azure OpenAI provider support |
Microsoft.Agents.AI.AzureAI.Persistent | Microsoft Foundry Agent Service integration |
Microsoft.Agents.AI.Anthropic | Anthropic provider support |
Microsoft.Agents.AI.Ollama | Ollama local model integration |
Microsoft.Agents.Hosting | Hosting abstractions for agent applications |
Microsoft.Agents.AI.Hosting.OpenAI | OpenAI-compatible endpoint hosting |
Microsoft.Agents.Middleware | Middleware pipeline for agent interception |
Azure.Identity | Azure authentication (DefaultAzureCredential, ManagedIdentity) |
The OpenAI provider supports three client types with different capabilities:
| Client Type | API | Best For |
|---|---|---|
| Chat Completion | Chat Completions API | Simple agents, broad model support |
| Responses | Responses API | Full-featured agents with hosted tools |
| Assistants | Assistants API | Server-managed agents with persistent threads |
using Microsoft.Agents.AI;
using OpenAI;
OpenAIClient client = new OpenAIClient("<your_api_key>");
var chatClient = client.GetChatClient("gpt-4o-mini");
AIAgent agent = chatClient.AsAIAgent(
instructions: "You are a helpful assistant specialized in data analysis.",
name: "DataAnalyst");
var response = await agent.RunAsync("Analyze Q3 sales trends.");
Console.WriteLine(response);
using Microsoft.Agents.AI.OpenAI;
using OpenAI;
OpenAIClient client = new OpenAIClient("<your_api_key>");
var responsesClient = client.GetResponsesClient("gpt-4o");
AIAgent agent = responsesClient.AsAIAgent(
instructions: "You are a research assistant with access to web search.",
name: "ResearchAssistant");
// Responses API supports hosted tools (web search, file search, code interpreter)
var response = await agent.RunAsync("Find recent articles about .NET 10 features.");
using Microsoft.Agents.AI.OpenAI;
using OpenAI;
OpenAIClient client = new OpenAIClient("<your_api_key>");
var assistantClient = client.GetAssistantClient();
// Create a persistent assistant with built-in tools
var assistant = await assistantClient.CreateAssistantAsync(
model: "gpt-4o",
name: "CodeReviewer",
instructions: "You review code for best practices and potential issues.",
tools: ["code_interpreter"]);
AIAgent agent = assistant.AsAIAgent();
Azure OpenAI provides enterprise-grade AI with managed endpoints, private networking, and Microsoft Entra authentication.
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
AzureOpenAIClient client = new AzureOpenAIClient(
new Uri("https://<resource>.openai.azure.com"),
new DefaultAzureCredential());
var chatClient = client.GetChatClient("gpt-4o");
AIAgent agent = chatClient.AsAIAgent(
instructions: "You are a customer support agent for Contoso.");
var response = await agent.RunAsync("I need help with my order.");
Azure OpenAI also supports Responses and Assistants APIs:
// Responses API
var responsesClient = client.GetResponsesClient("gpt-4o");
AIAgent agent = responsesClient.AsAIAgent(instructions: "...");
// Assistants API
var assistantClient = client.GetAssistantClient();
var assistant = await assistantClient.CreateAssistantAsync(model: "gpt-4o", ...);
AIAgent agent = assistant.AsAIAgent();
Foundry Agent Service provides managed, scalable agents with built-in content safety, persistent storage, and Microsoft 365 integration.
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Agents.AI;
var persistentAgentsClient = new PersistentAgentsClient(
"https://<resource>.services.ai.azure.com/api/projects/<project>",
new DefaultAzureCredential());
// Create a new agent in the service
AIAgent agent = await persistentAgentsClient.CreateAIAgentAsync(
model: "gpt-4o-mini",
name: "SupportBot",
instructions: "You handle customer support inquiries.");
// Use the agent
var response = await agent.RunAsync("My account is locked.");
// Or retrieve an existing agent
AIAgent existingAgent = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");
using Microsoft.Agents.AI.Anthropic;
using Anthropic;
var client = new AnthropicClient("<api_key>");
var agent = client.AsAIAgent(
model: "claude-3-opus-20240229",
instructions: "You are a helpful assistant.");
var response = await agent.RunAsync("Explain quantum computing.");
using Microsoft.Agents.AI.Ollama;
var client = new OllamaClient(new Uri("http://localhost:11434"));
var agent = client.AsAIAgent(
model: "llama3.2",
instructions: "You are a local AI assistant.");
var response = await agent.RunAsync("Summarize this document.");
Any service implementing Microsoft.Extensions.AI.IChatClient can be used with ChatClientAgent:
using Microsoft.Agents.AI;
// IChatClient from any provider
IChatClient chatClient = GetChatClientFromAnyProvider();
AIAgent agent = new ChatClientAgent(
chatClient,
instructions: "You are a helpful assistant.");
var response = await agent.RunAsync("Hello!");
Workflows provide graph-based orchestration for multi-step tasks with type-safe routing, checkpointing, and human-in-the-loop support.
using Microsoft.Agents.AI.Workflows;
var workflow = WorkflowBuilder.CreateSequential()
.AddStep<ResearchStep>("research")
.AddStep<WriteStep>("write")
.AddStep<ReviewStep>("review")
.Build();
var result = await workflow.ExecuteAsync(new ResearchInput { Topic = "AI in Healthcare" });
var workflow = WorkflowBuilder.Create()
.AddStep<AnalyzeIntentStep>("analyze")
.AddBranch(
condition: ctx => ctx.Get<Intent>("intent") == Intent.Support,
thenBranch: b => b.AddStep<HandleSupportStep>("support"),
elseBranch: b => b.AddStep<HandleSalesStep>("sales"))
.Build();
Multiple agents collaborating with termination conditions:
using Microsoft.Agents.AI.Workflows;
var analyst = new ChatClientAgent(chatClient,
instructions: "You analyze data and provide insights. Be concise.");
var writer = new ChatClientAgent(chatClient,
instructions: "You take analysis and write clear reports.");
var workflow = WorkflowBuilder.CreateGroupChat()
.AddAgent(analyst, "analyst")
.AddAgent(writer, "writer")
.WithTerminationCondition(ctx =>
ctx.Messages.Last().Content.Contains("[COMPLETE]"))
.WithMaxIterations(10)
.Build();
var result = await workflow.ExecuteAsync("Analyze Q4 sales and write a summary report.");
Transfer control between specialized agents:
var triage = new ChatClientAgent(chatClient,
instructions: "You triage requests and hand off to specialists.");
var billing = new ChatClientAgent(chatClient,
instructions: "You handle billing questions.");
var technical = new ChatClientAgent(chatClient,
instructions: "You handle technical support.");
var workflow = WorkflowBuilder.Create()
.AddStep<AgentStep>("triage", triage)
.AddHandoff(
from: "triage",
condition: ctx => ctx.Get<string>("department") == "billing",
to: billing)
.AddHandoff(
from: "triage",
condition: ctx => ctx.Get<string>("department") == "technical",
to: technical)
.Build();
A lead agent directs other agents:
var orchestrator = new ChatClientAgent(chatClient,
instructions: "You are an orchestrator. Delegate tasks to specialists and synthesize results.");
var workflow = WorkflowBuilder.CreateMagentic()
.WithLeadAgent(orchestrator)
.AddSpecialist("researcher", researchAgent, "Research specialist")
.AddSpecialist("coder", codeAgent, "Code specialist")
.Build();
var result = await workflow.ExecuteAsync("Build a web scraper that extracts product prices.");
public sealed class OrderTools
{
[Function("get_order_status")]
[Description("Retrieves the status of an order by ID")]
public async Task<OrderStatus> GetOrderStatusAsync(
[Description("The order ID to look up")] string orderId,
CancellationToken ct = default)
{
// Implementation
return await _orderService.GetStatusAsync(orderId, ct);
}
[Function("cancel_order")]
[Description("Cancels an order if eligible")]
public async Task<CancelResult> CancelOrderAsync(
[Description("The order ID to cancel")] string orderId,
CancellationToken ct = default)
{
// Implementation
return await _orderService.CancelAsync(orderId, ct);
}
}
// Register tools with agent
var agent = chatClient.AsAIAgent(
instructions: "You help customers with their orders.",
tools: new OrderTools());
Connect to MCP servers for external tools:
using Microsoft.Agents.AI.Tools.MCP;
// Connect to an MCP server
var mcpClient = new MCPClient("https://api.example.com/mcp");
// Get available tools from the server
var tools = await mcpClient.ListToolsAsync();
// Create agent with MCP tools
var agent = chatClient.AsAIAgent(
instructions: "You have access to external data sources via MCP.",
tools: tools);
// Or connect to hosted MCP servers (Azure OpenAI, OpenAI Responses API)
var responsesClient = client.GetResponsesClient("gpt-4o");
var agent = responsesClient.AsAIAgent(
instructions: "You have access to hosted tools.",
hostedTools: ["web_search", "file_search", "code_interpreter"]);
using Microsoft.Agents.AI.OpenAI;
var responsesClient = client.GetResponsesClient("gpt-4o");
var agent = responsesClient.AsAIAgent(
instructions: "You are a research assistant.",
hostedTools: new HostedTools
{
WebSearch = new WebSearchTool(),
FileSearch = new FileSearchTool { VectorStoreIds = ["vs_123"] },
CodeInterpreter = new CodeInterpreterTool()
});
var response = await agent.RunAsync("Search for recent papers on climate change and analyze the data.");
using Microsoft.Agents.AI.Sessions;
// Create a new session
var session = new AgentSession();
// Multi-turn conversation
await agent.RunAsync("What's the weather?", session);
await agent.RunAsync("Will it rain tomorrow?", session); // Has context from previous turn
// Persist session for later
var sessionData = session.Serialize();
// ... save to database ...
// Restore session later
var restoredSession = AgentSession.Deserialize(sessionData);
Use Redis or other providers for distributed session storage:
using Microsoft.Agents.AI.Sessions.Redis;
builder.Services.AddRedisChatHistoryProvider(
connectionString: "localhost:6379");
// Agent automatically uses Redis for session persistence
var agent = chatClient.AsAIAgent(
instructions: "You remember previous conversations.",
chatHistoryProvider: provider);
public class RAGContextProvider : IContextProvider
{
private readonly IVectorStore _vectorStore;
public async Task<IEnumerable<ChatMessage>> GetContextAsync(
string userMessage,
CancellationToken ct)
{
// Retrieve relevant documents
var embedding = await GenerateEmbeddingAsync(userMessage, ct);
var docs = await _vectorStore.SearchAsync(embedding, top: 5, ct);
return docs.Select(d => new ChatMessage(
Role.System,
$"Context: {d.Content}"));
}
}
var agent = chatClient.AsAIAgent(
instructions: "You answer based on the provided context.",
contextProviders: [new RAGContextProvider(vectorStore)]);
Middleware intercepts agent actions for logging, authorization, rate limiting, and modification.
public class AuthorizationMiddleware : IAgentMiddleware
{
public async Task<AgentResponse> InvokeAsync(
AgentContext context,
Func<AgentContext, Task<AgentResponse>> next)
{
// Check authorization before processing
if (context.FunctionName == "cancel_order")
{
var userId = context.User.Identity?.Name;
var orderId = context.Arguments["orderId"]?.ToString();
if (!await _authService.CanCancelOrderAsync(userId, orderId))
{
return new AgentResponse("You are not authorized to cancel this order.");
}
}
return await next(context);
}
}
// Register middleware
var agent = chatClient.AsAIAgent(instructions: "...")
.UseMiddleware<AuthorizationMiddleware>();
public class LoggingMiddleware : IAgentMiddleware
{
private readonly ILogger<LoggingMiddleware> _logger;
public async Task<AgentResponse> InvokeAsync(
AgentContext context,
Func<AgentContext, Task<AgentResponse>> next)
{
_logger.LogInformation(
"Agent {AgentName} processing: {Message}",
context.AgentName,
context.UserMessage);
var stopwatch = Stopwatch.StartNew();
var response = await next(context);
stopwatch.Stop();
_logger.LogInformation(
"Agent {AgentName} completed in {ElapsedMs}ms",
context.AgentName,
stopwatch.ElapsedMilliseconds);
return response;
}
}
public class RateLimitMiddleware : IAgentMiddleware
{
private readonly IRateLimiter _rateLimiter;
public async Task<AgentResponse> InvokeAsync(
AgentContext context,
Func<AgentContext, Task<AgentResponse>> next)
{
var userId = context.User.Identity?.Name;
if (!await _rateLimiter.TryAcquireAsync(userId))
{
return new AgentResponse("Rate limit exceeded. Please try again later.");
}
return await next(context);
}
}
using Microsoft.Agents.AI.Telemetry;
// Configure OpenTelemetry
builder.Services.AddOpenTelemetry()
.WithTracing(tracing =>
{
tracing.AddAgentFrameworkInstrumentation();
tracing.AddAzureMonitorTraceExporter();
})
.WithMetrics(metrics =>
{
metrics.AddAgentFrameworkMetrics();
metrics.AddAzureMonitorMetricExporter();
});
// All agent interactions automatically emit traces and metrics
using Azure.Identity;
using Microsoft.Agents.AI;
// Use managed identity in production
AzureOpenAIClient client = new AzureOpenAIClient(
new Uri("https://<resource>.openai.azure.com"),
new ManagedIdentityCredential());
// Or use Entra ID for user-delegated access
var credential = new InteractiveBrowserCredential();
using Microsoft.Agents.AI.Safety;
var agent = chatClient.AsAIAgent(instructions: "...")
.UseSafetyFilters(new SafetyOptions
{
// Prompt injection protection
PromptInjectionDetection = true,
// Content safety
ContentSafety = new ContentSafetyOptions
{
HateSpeech = FilterSeverity.Medium,
SelfHarm = FilterSeverity.High,
Violence = FilterSeverity.Medium
},
// Task adherence monitoring
TaskAdherenceMonitoring = true
});
var agent = chatClient.AsAIAgent(instructions: "...");
var session = new AgentSession();
await foreach (var chunk in agent.RunStreamingAsync("Tell me a story.", session))
{
Console.Write(chunk.Content);
}
[Description] attributes so the model
knows when and how to call them.CancellationToken through tool methods to support timeouts and
user cancellations.DefaultAzureCredential for development and ManagedIdentityCredential for
production. Hardcoded secrets leak into source control.CancellationToken to allow cancellation.Microsoft.Agents.AI NuGet package (prerelease)Microsoft.Agents.AI.OpenAI, Microsoft.Agents.AI.AzureAI)Primary approach: Use Serena symbol operations for efficient code navigation:
serena_find_symbol instead of text searchserena_get_symbols_overview for file organizationserena_find_referencing_symbols for impact analysisserena_replace_symbol_body for clean modificationsWhen to use Serena vs traditional tools:
Example workflow:
# Instead of:
Read: src/Services/OrderService.cs
Grep: "public void ProcessOrder"
# Use:
serena_find_symbol: "OrderService/ProcessOrder"
serena_get_symbols_overview: "src/Services/OrderService.cs"
まだレビューはありません。使ってみた感想をお寄せください。
概要と使いどころ
Patterns and techniques for evaluating and improving AI agent outputs.
日本語の概要は準備中です。原文の説明を表示しています。
Comprehensive AI prompt engineering safety review and improvement prompt. Analyzes prompts for safety, bias, security vulnerabilities, and effectiveness while providing detailed improvement recommendations.
日本語の概要は準備中です。原文の説明を表示しています。
Use when user requests research requiring multiple sources, comprehensive analysis, or synthesis across topics - technical research, domain knowledge gathering, market analysis, or learning about complex subjects
日本語の概要は準備中です。原文の説明を表示しています。
AI-powered wiki generation for code repositories with commands, agents, and skills
日本語の概要は準備中です。原文の説明を表示しています。
Use when building .NET 10 or C# 14 applications; when using minimal APIs, modular monolith patterns, or feature folders; when implementing HTTP resilience, Options pattern, Channels, or validation; when seeing outdated patterns like old extension method syntax
日本語の概要は準備中です。原文の説明を表示しています。
Implements accessible .NET UI. SemanticProperties, ARIA, AutomationPeer, testing per platform.
日本語の概要は準備中です。原文の説明を表示しています。