Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Use when building AI agents with Microsoft Agent Framework (Semantic Kernel + AutoGen unified); when implementing memory or context providers; when threads won't deserialize; when workflow checkpointing fails; when migrating from Semantic Kernel or AutoGen; when seeing ChatAgent or AgentThread errors
.claude/skills/majiayu000-working-with-ms-agent-framework/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 86% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 54% | 0% |
| case-03 | ✗→✓ | ▲ Improved | 69% | 0% |
| case-05 | ✗→✓ | ▲ Improved | 117% | 0% |
| case-06 | ✗→✓ | ▲ Improved | 149% | 0% |
Microsoft Agent Framework (October 2025) unifies Semantic Kernel and AutoGen into one SDK. Both legacy frameworks are in maintenance mode.
Core principle: Agents are stateless. All state lives in threads. Context providers enforce policy about what enters the prompt, how, and when it decays.
> Additional reference files in this skill: > - context-providers.md - Policy-based memory, capsule pattern, Mem0 integration > - orchestration-patterns.md - The 5 orchestration patterns with when-to-use guidance > - design-patterns.md - Production patterns, testing, migration
Official guidance (Jeremy Licknes, PM): Start with ME AI, escalate only when needed.
| Layer | Use For | When to Escalate | |-------|---------|------------------| | ME AI (Microsoft.Extensions.AI) | Chat clients, structured outputs, embeddings, middleware | Need agents, workflows, memory | | Agent Framework | Agents, threads, orchestration, context providers | Need specific SK adapters | | Semantic Kernel | Specific adapters, utilities not in ME AI | Never start here |
ME AI (foundation) → Agent Framework (agents/workflows) → SK (specific utilities only)Key insight: ME AI provides universal APIs that work across OpenAI, Ollama, Foundry Local, etc. Agent Framework builds on ME AI for agentic patterns. SK primitives migrated to ME AI; only use SK for specific adapters not yet in ME AI.
ME AI features you get automatically:
| Concept | C# Type | Purpose | |---------|---------|---------| | Agent | AIAgent | Stateless LLM wrapper | | Thread | AgentThread | Stateful conversation container | | Context Provider | AIContextBehavior | Policy-based memory/context injection | | Orchestration | SequentialOrchestration, etc. | Multi-agent coordination |
bashdotnet add package Microsoft.Agents.AI.OpenAI --prerelease dotnet add package Azure.AI.OpenAI --version 2.1.0
csharpusing Azure.AI.OpenAI; using Azure.Identity; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; // Azure OpenAI AIAgent agent = new AzureOpenAIClient( new Uri("https://<resource>.openai.azure.com"), new AzureCliCredential()) .GetChatClient("gpt-4o-mini") .CreateAIAgent( instructions: "You are a helpful assistant.", name: "Assistant"); // Direct OpenAI var agent = new OpenAIClient("api-key") .GetChatClient("gpt-4o-mini") .AsIChatClient() .CreateAIAgent(instructions: "...", name: "Assistant"); // With tools [Description("Gets weather for a location")] static string GetWeather(string location) => $"Sunny in {location}"; AIAgent agent = chatClient.CreateAIAgent( instructions: "You help with weather queries.", tools: [AIFunctionFactory.Create(GetWeather)] );
csharp// Simple Console.WriteLine(await agent.RunAsync("Hello!")); // With thread for multi-turn AgentThread thread = agent.GetNewThread(); await agent.RunAsync("My name is Alice.", thread); await agent.RunAsync("What's my name?", thread); // Remembers "Alice" // Streaming await foreach (var update in agent.RunStreamingAsync("Tell me a story.", thread)) { Console.Write(update.Text); }
For production streaming, add cancellation support and resilience:
csharp// Basic streaming with cancellation await foreach (var update in agent.RunStreamingAsync("Tell me a story.", thread) .WithCancellation(cancellationToken)) { Console.Write(update.Text); } // With Polly resilience pipeline var pipeline = new ResiliencePipelineBuilder() .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 }) .AddTimeout(TimeSpan.FromMinutes(2)) .Build(); await pipeline.ExecuteAsync(async token => { await foreach (var chunk in agent.RunStreamingAsync(userMessage, thread) .WithCancellation(token)) { Console.Write(chunk.Text); } }, cancellationToken);
Error differentiation:
OperationCanceledException: User cancelledTimeoutRejectedException: Polly timeoutHttpRequestException: Network issuesLightweight web interface for testing agents and workflows. Development only—not for production.
Install:
bashpip install agent-framework-devui --pre
Option 1: Programmatic Registration
pythonfrom agent_framework import ChatAgent from agent_framework.openai import OpenAIChatClient from agent_framework.devui import serve agent = ChatAgent( name="WeatherAgent", chat_client=OpenAIChatClient(), tools=[get_weather] ) # Launch DevUI with tracing serve(entities=[agent], auto_open=True, tracing_enabled=True) # Opens browser to http://localhost:8080
Option 2: Directory Discovery (CLI)
bashdevui ./entities --port 8080 --tracing
Directory structure for discovery:
entities/
weather_agent/
__init__.py # Must export: agent = ChatAgent(...)
.env # Optional: API keys
my_workflow/
__init__.py # Must export: workflow = WorkflowBuilder()...C# embeds DevUI as SDK component (docs in progress):
csharpvar app = builder.Build(); app.MapOpenAIResponses(); app.MapConversation(); if (app.Environment.IsDevelopment()) { app.MapAgentUI(); // Accessible at /ui }
| Feature | Description | |---------|-------------| | Web interface | Interactive testing of agents/workflows | | OpenAI-compatible API | Use OpenAI SDK against local agents | | Tracing | OpenTelemetry spans in debug panel | | File uploads | Multimodal inputs (images, documents) | | Auto-generated inputs | Workflow inputs based on first executor type |
Enable with --tracing flag or tracing_enabled=True. View in debug panel:
Agent Execution
├── LLM Call (prompt → response)
├── Tool Call
│ ├── Tool Execution
│ └── Tool Result
└── LLM Call (prompt → response)Export to external tools (Jaeger, Azure Monitor):
bashexport OTLP_ENDPOINT="http://localhost:4317" devui ./entities --tracing
Interact with DevUI agents via OpenAI Python SDK:
pythonfrom openai import OpenAI client = OpenAI(base_url="http://localhost:8080/v1", api_key="not-needed") response = client.responses.create( metadata={"entity_id": "weather_agent"}, input="What's the weather in Seattle?" )
devui [directory] [options]
--port, -p Port (default: 8080)
--tracing Enable OpenTelemetry tracing
--reload Auto-reload on file changes
--headless API only, no UI
--mode developer|user (default: developer)csharp// Serialize for persistence JsonElement serialized = await thread.SerializeAsync(); await File.WriteAllTextAsync("thread.json", serialized.GetRawText()); // Later: restore and resume string json = await File.ReadAllTextAsync("thread.json"); JsonElement element = JsonSerializer.Deserialize<JsonElement>(json); AgentThread restored = agent.DeserializeThread(element, JsonSerializerOptions.Web); await agent.RunAsync("Continue...", restored);
Key behaviors:
Context providers are not "memory injection" — they're policy enforcement:
| Policy | What It Decides | |--------|-----------------| | Selection | What becomes memory | | Gating | When it's retrieved | | Decay | When it expires | | Noise avoidance | When NOT to use |
csharpChatHistoryAgentThread thread = new(); // Long-term user memory thread.AIContextProviders.Add(new Mem0Provider(httpClient, new() { UserId = "user123" })); // Short-term conversation context thread.AIContextProviders.Add(new WhiteboardProvider(chatClient)); // RAG integration thread.AIContextProviders.Add(new TextSearchProvider(textSearch, new() { SearchTime = TextSearchProviderOptions.RagBehavior.OnDemandFunctionCalling }));
See context-providers.md for custom implementation patterns.
| Pattern | Use When | |---------|----------| | Sequential | Clear dependencies (draft → review → polish) | | Concurrent | Independent perspectives, ensemble reasoning | | Handoff | Unknown optimal agent upfront, dynamic expertise | | GroupChat | Collaborative ideation, human-in-the-loop | | Magentic | Complex open-ended problems |
csharp// Sequential SequentialOrchestration orchestration = new(analystAgent, writerAgent); // Handoff - CRITICAL: Always set termination conditions! var workflow = AgentWorkflowBuilder.StartHandoffWith(triageAgent) .WithHandoffs(triageAgent, [mathTutor, historyTutor]) .WithHandoff(mathTutor, triageAgent) // Allows routing back .WithHandoff(historyTutor, triageAgent) .WithMaxHandoffs(10) // REQUIRED: Prevent infinite loops .Build(); // Execute InProcessRuntime runtime = new(); await runtime.StartAsync(); var result = await orchestration.InvokeAsync(task, runtime);
CRITICAL for Handoffs: Missing .WithMaxHandoffs() causes infinite loops. Always set termination conditions.
See orchestration-patterns.md for detailed patterns and when-to-use guidance.
For workflows that must survive process restarts:
csharp// Basic checkpointing with CheckpointManager var checkpointManager = CheckpointManager.Default; await using Checkpointed<StreamingRun> checkpointedRun = await InProcessExecution.StreamAsync(workflow, input, checkpointManager); // Resume from checkpoint await InProcessExecution.ResumeStreamAsync(savedCheckpoint, checkpointManager);
For long-running workflows, checkpoint thread state after each step:
csharp// Save thread state after each workflow step var serialized = await thread.SerializeAsync(); await checkpointStore.SaveAsync(workflowId, currentStep, serialized.GetRawText()); // Resume after restart var json = await checkpointStore.GetAsync(workflowId); var element = JsonSerializer.Deserialize<JsonElement>(json); var restored = agent.DeserializeThread(element, JsonSerializerOptions.Web); await agent.RunAsync(nextStep, restored);
csharppublic class WorkflowRecoveryService : BackgroundService { private readonly ICheckpointStore _store; private readonly AIAgent _agent; protected override async Task ExecuteAsync(CancellationToken ct) { var pending = await _store.GetPendingWorkflowsAsync(); foreach (var workflow in pending) { var thread = _agent.DeserializeThread(workflow.State, JsonSerializerOptions.Web); await _agent.RunAsync(workflow.NextStep, thread, cancellationToken: ct); } } }
Key principle: Checkpoint after each step completes, not before. This ensures you can resume from the last successful step.
| SK | Agent Framework | |----|-----------------| | Kernel | AIAgent | | ChatHistory | AgentThread | | [KernelFunction] | [Description] on methods | | IPromptFilter | AIContextBehavior | | KernelFunctionFactory.CreateFromMethod | AIFunctionFactory.Create |
| AutoGen | Agent Framework | |---------|-----------------| | AssistantAgent | AIAgent via CreateAIAgent() | | FunctionTool | AIFunctionFactory.Create() | | GroupChat/Teams | WorkflowBuilder patterns | | TopicSubscription | AgentWorkflowBuilder.WithHandoffs() | | BaseAgent, IHandle<> | AIAgent with tools |
Topic-Based to Handoff Migration:
csharp// ❌ OLD AutoGen pattern (deprecated) [TopicSubscription("queries")] public class MyAgent : BaseAgent, IHandle<Query> { public async Task Handle(Query msg, CancellationToken ct) { // Process and publish to another topic await PublishMessageAsync(new Response(...), "responses"); } } // ✅ NEW Agent Framework pattern var triageAgent = chatClient.CreateAIAgent( instructions: "Route queries to appropriate specialist.", name: "Triage"); var mathAgent = chatClient.CreateAIAgent( instructions: "Handle math queries.", name: "Math"); var workflow = AgentWorkflowBuilder.StartHandoffWith(triageAgent) .WithHandoffs(triageAgent, [mathAgent, otherAgent]) .WithMaxHandoffs(10) // REQUIRED .Build(); await workflow.InvokeStreamingAsync(input, runtime);
| Don't | Do | |-------|-----| | Store state in agent instances | Use AgentThread for all state | | Serialize only messages | Serialize entire thread | | Share agent instances in workflows | Use factory pattern | | Mix thread types across services | Threads are service-specific | | Use Magentic when Sequential suffices | Use simplest pattern that works | | Skip UseImmutableKernel with ContextualFunctionProvider | Always set UseImmutableKernel = true | | Start with Semantic Kernel for new projects | Start with ME AI, escalate to Agent Framework |
Kernel instead of AIAgent (old SK)AssistantAgent instead of AIAgent (old AutoGen)github.com/microsoft/agent-frameworklearn.microsoft.com/en-us/agent-framework/learn.microsoft.com/en-us/agent-framework/migration-guide/| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 22,403 | 14,871 | -34% | 1 | 1 | 0% | 3,091 | 5,740 | +86% | 0 | 0 | — |
case-02 | fail→pass | 22,813 | 20,832 | -9% | 1 | 1 | 0% | 4,724 | 7,294 | +54% | 0 | 0 | — |
case-03 | fail→pass | 34,422 | 11,066 | -68% | 1 | 1 | 0% | 2,878 | 4,857 | +69% | 0 | 0 | — |
case-04 | pass→pass | 18,998 | 9,369 | -51% | 1 | 1 | 0% | 2,292 | 5,328 | +132% | 0 | 0 | — |
case-05 | fail→pass | 15,155 | 16,101 | +6% | 1 | 1 | 0% | 2,618 | 5,674 | +117% | 0 | 0 | — |
case-06 | fail→pass | 11,257 | 10,516 | -7% | 1 | 1 | 0% | 1,781 | 4,435 | +149% | 0 | 0 | — |
case-07 | fail→pass | 11,560 | 8,832 | -24% | 1 | 1 | 0% | 1,787 | 4,322 | +142% | 0 | 0 | — |
case-08 | fail→pass | 18,655 | 5,702 | -69% | 1 | 1 | 0% | 2,259 | 4,866 | +115% | 0 | 0 | — |
case-09 | fail→pass | 19,500 | 14,822 | -24% | 1 | 1 | 0% | 3,177 | 6,552 | +106% | 0 | 0 | — |
case-10 | fail→pass | 32,378 | 20,467 | -37% | 1 | 1 | 0% | 4,598 | 6,652 | +45% | 0 | 0 | — |
case-11 | fail→pass | 22,920 | 10,153 | -56% | 1 | 1 | 0% | 3,479 | 4,820 | +39% | 0 | 0 | — |
case-20 | pass→pass | 18,545 | 16,572 | -11% | 1 | 1 | 0% | 2,660 | 5,910 | +122% | 0 | 0 | — |
case-12 | fail→pass | 17,245 | 9,117 | -47% | 1 | 1 | 0% | 2,098 | 4,449 | +112% | 0 | 0 | — |
case-13 | fail→pass | 17,660 | 16,979 | -4% | 1 | 1 | 0% | 2,394 | 5,861 | +145% | 0 | 0 | — |
case-14 | pass→pass | 15,960 | 13,023 | -18% | 1 | 1 | 0% | 2,657 | 5,138 | +93% | 0 | 0 | — |
case-15 | pass→pass | 20,300 | 6,486 | -68% | 1 | 1 | 0% | 2,735 | 5,077 | +86% | 0 | 0 | — |
case-16 | fail→pass | 12,197 | 11,351 | -7% | 1 | 1 | 0% | 1,881 | 4,872 | +159% | 0 | 0 | — |
case-17 | pass→pass | 13,304 | 9,893 | -26% | 1 | 1 | 0% | 1,356 | 4,576 | +237% | 0 | 0 | — |
case-18 | fail→pass | 10,409 | 9,868 | -5% | 1 | 1 | 0% | 1,926 | 4,607 | +139% | 0 | 0 | — |
case-19 | pass→pass | 20,160 | 18,696 | -7% | 1 | 1 | 0% | 2,495 | 5,693 | +128% | 0 | 0 | — |
case-21 | pass→fail | 16,465 | 6,747 | -59% | 1 | 1 | 0% | 2,296 | 5,135 | +124% | 0 | 0 | — |
case-22 | pass→pass | 18,842 | 18,471 | -2% | 1 | 1 | 0% | 2,620 | 6,346 | +142% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +59 percentage points is the difference between those two pass rates over the 22 comparable cases. 1 case got worse with the skill loaded, and it is included in that figure.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.