Microsoft Agent Framework 1.0 — SDK Thống Nhất Cho AI Agents Trên .NET 10
Posted on: 4/18/2026 9:16:10 AM
Table of contents
- 1. Tại sao cần hợp nhất?
- 2. Timeline hợp nhất
- 3. Kiến trúc 5 tầng
- 4. Năm Orchestration Patterns Built-in
- 5. Middleware Pipeline — Sức mạnh từ Semantic Kernel
- 6. Declarative Agents — Định nghĩa Agent bằng YAML
- 7. Tool Registration và MCP Integration
- 8. Observability với OpenTelemetry
- 9. Graph-based Workflows — Vượt xa Orchestration Patterns
- 10. So sánh với các Agent Framework khác
- 11. Real-world Architecture: Interview Coach
- 12. Migration từ Semantic Kernel / AutoGen
- 13. Quick Start — Từ 0 đến Agent đầu tiên
- 14. Best Practices cho Production
- Kết luận
Trong nhiều năm, hệ sinh thái .NET có hai framework AI agent đáng chú ý nhưng lại tách biệt hoàn toàn: Semantic Kernel — enterprise-grade, type-safe, middleware pipeline mạnh mẽ, và AutoGen — đột phá với conversation-centric multi-agent, dễ prototype. Nhà phát triển buộc phải chọn một trong hai, hoặc tự viết glue code kết nối cả hai. Ngày 3 tháng 4 năm 2026, Microsoft chính thức phát hành Agent Framework 1.0 — SDK thống nhất hợp nhất tinh hoa của cả Semantic Kernel lẫn AutoGen vào một framework duy nhất, production-ready, hỗ trợ đồng thời C#/.NET và Python.
Bài viết này sẽ đi sâu vào kiến trúc, các orchestration pattern, middleware pipeline, declarative agents, observability, và cách tích hợp MCP — tất cả với code example C# cụ thể trên .NET 10.
1. Tại sao cần hợp nhất?
Trước Agent Framework 1.0, bức tranh agent trên .NET khá phân mảnh:
| Tiêu chí | Semantic Kernel | AutoGen |
|---|---|---|
| Triết lý | Enterprise — type safety, middleware, telemetry | Research — conversation-centric, prototype nhanh |
| Multi-agent | Hạn chế, chủ yếu single-agent + plugins | Mạnh — group chat, Magentic-One |
| Orchestration | Sequential plugins | Conversation-based routing |
| Production readiness | Cao — session management, telemetry | Trung bình — thiếu middleware, observability |
| Ngôn ngữ | C# (chính), Python | Python (chính), C# |
Sự phân mảnh này tạo ra vấn đề thực tế: team enterprise muốn dùng multi-agent pattern của AutoGen nhưng cần middleware pipeline của Semantic Kernel. Kết quả là glue code tự viết, không chuẩn hóa, khó maintain. Agent Framework 1.0 giải quyết triệt để bằng cách lấy thế mạnh của cả hai:
Agent Framework 1.0 = ?
Từ AutoGen: Agent abstractions đơn giản (Agent, ChatAgent), multi-agent patterns (group chat, Magentic-One), conversation flows.
Từ Semantic Kernel: Enterprise middleware pipeline, session-based state, type safety, OpenTelemetry integration, model connector ecosystem.
Mới hoàn toàn: Graph-based workflows, declarative YAML agents, MCP/A2A protocol support, DevUI debugger.
2. Timeline hợp nhất
Microsoft.Agents.AI v1.1.0, PyPI package agent-framework.3. Kiến trúc 5 tầng
Agent Framework được thiết kế theo kiến trúc layered rõ ràng, mỗi tầng có trách nhiệm riêng biệt:
graph TB
subgraph L1["🖥️ Client / Application Layer"]
A1[Web Apps / APIs]
A2[Console Apps]
A3[Teams Bots]
A4[Background Services]
end
subgraph L2["🤖 Agent Layer"]
B1[ChatClientAgent]
B2[Declarative Agent YAML]
B3[Custom Agent]
end
subgraph L3["⚙️ Runtime Layer"]
C1[Session Management]
C2[Middleware Pipeline]
C3[Memory / Context]
C4[Execution Loop]
end
subgraph L4["🔧 Tool / Integration Layer"]
D1[Function Tools]
D2[MCP Clients]
D3[External APIs]
D4[Databases]
end
subgraph L5["🧠 Model Provider Layer"]
E1[Azure OpenAI]
E2[OpenAI]
E3[Anthropic Claude]
E4[Google Gemini]
E5[Ollama]
end
L1 --> L2
L2 --> L3
L3 --> L4
L3 --> L5
style L1 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style L2 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style L3 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style L4 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style L5 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Điểm đặc biệt: tất cả model connectors đều implement interface IChatClient từ Microsoft.Extensions.AI — cho phép viết code hoàn toàn provider-agnostic. Bạn có thể swap từ Azure OpenAI sang Anthropic Claude hay Ollama local mà không đổi một dòng business logic nào.
4. Năm Orchestration Patterns Built-in
Đây là nơi Agent Framework thực sự tỏa sáng so với việc tự build. Framework cung cấp 5 pattern sẵn, cover hầu hết các use case multi-agent trong production:
graph LR
subgraph Sequential
S1[Agent A] --> S2[Agent B] --> S3[Agent C]
end
subgraph Concurrent
C0[Input] --> C1[Agent A]
C0 --> C2[Agent B]
C0 --> C3[Agent C]
C1 --> C4[Aggregator]
C2 --> C4
C3 --> C4
end
style S1 fill:#e94560,stroke:#fff,color:#fff
style S2 fill:#e94560,stroke:#fff,color:#fff
style S3 fill:#e94560,stroke:#fff,color:#fff
style C0 fill:#2c3e50,stroke:#fff,color:#fff
style C1 fill:#e94560,stroke:#fff,color:#fff
style C2 fill:#e94560,stroke:#fff,color:#fff
style C3 fill:#e94560,stroke:#fff,color:#fff
style C4 fill:#2c3e50,stroke:#fff,color:#fff
| Pattern | Topology | Use Case Điển Hình |
|---|---|---|
| Sequential | Pipeline — A → B → C | Content pipeline: viết → review → dịch. Output agent trước là input agent sau. |
| Concurrent | Fan-out/Fan-in | Phân tích song song: sentiment + entity extraction + summarization → aggregate. |
| Handoff | Mesh — agents chuyển quyền điều khiển | Customer support: triage → refund/order/return agent. Agent tự quyết định handoff. |
| Group Chat | Shared conversation thread | Brainstorming: nhiều agent với expertise khác nhau thảo luận trong cùng thread. |
| Magentic-One | Manager điều phối dynamic | Complex task: manager agent phân tích task, gán cho agent phù hợp nhất. |
4.1 Sequential — Pipeline đơn giản
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Orchestrations;
// Tạo agents cho content pipeline
var writer = new ChatClientAgent(chatClient,
"Bạn là copywriter. Viết một đoạn marketing ngắn gọn, súc tích.",
name: "writer");
var reviewer = new ChatClientAgent(chatClient,
"Bạn là editor. Review và cải thiện bản draft, giữ nguyên tone.",
name: "reviewer");
var translator = new ChatClientAgent(chatClient,
"Bạn là translator. Dịch nội dung sang tiếng Việt tự nhiên.",
name: "translator");
// Build sequential workflow
var workflow = AgentWorkflowBuilder.BuildSequential([writer, reviewer, translator]);
// Execute
var messages = new List<ChatMessage>
{
new(ChatRole.User, "Write a tagline for a cloud-native .NET framework")
};
await using var run = await InProcessExecution.RunStreamingAsync(workflow, messages);
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
Khi nào dùng Sequential?
Khi output của agent trước là input bắt buộc của agent sau. Đừng dùng sequential nếu các agents có thể chạy độc lập — hãy dùng Concurrent để tiết kiệm thời gian.
4.2 Handoff — Mesh topology với chuyển quyền điều khiển
Handoff là pattern mạnh nhất cho các hệ thống customer-facing. Agents tự quyết định khi nào cần chuyển conversation sang agent khác:
// Định nghĩa agents
var triageAgent = new ChatClientAgent(chatClient,
"Bạn phân loại yêu cầu. LUÔN handoff sang agent phù hợp.",
name: "triage_agent", description: "Router chính");
var refundAgent = new ChatClientAgent(chatClient,
"Bạn xử lý yêu cầu hoàn tiền. Xác minh order ID trước khi xử lý.",
name: "refund_agent", description: "Xử lý hoàn tiền");
var orderAgent = new ChatClientAgent(chatClient,
"Bạn tra cứu và cập nhật trạng thái đơn hàng.",
name: "order_agent", description: "Quản lý đơn hàng");
var returnAgent = new ChatClientAgent(chatClient,
"Bạn hướng dẫn quy trình đổi trả hàng.",
name: "return_agent", description: "Xử lý đổi trả");
// Build handoff workflow với routing rules
var workflow = AgentWorkflowBuilder
.CreateHandoffBuilderWith(triageAgent)
.WithHandoffs(triageAgent, [refundAgent, orderAgent, returnAgent])
.WithHandoffs(returnAgent, [refundAgent])
.WithHandoffs(orderAgent, [triageAgent])
.WithHandoff(refundAgent, triageAgent)
.Build();
graph TD
T[Triage Agent] -->|"hoàn tiền"| R[Refund Agent]
T -->|"đơn hàng"| O[Order Agent]
T -->|"đổi trả"| RT[Return Agent]
RT -->|"cần hoàn tiền"| R
O -->|"quay lại"| T
R -->|"hoàn tất"| T
style T fill:#e94560,stroke:#fff,color:#fff
style R fill:#2c3e50,stroke:#fff,color:#fff
style O fill:#2c3e50,stroke:#fff,color:#fff
style RT fill:#2c3e50,stroke:#fff,color:#fff
5. Middleware Pipeline — Sức mạnh từ Semantic Kernel
Một trong những tính năng enterprise quan trọng nhất được kế thừa từ Semantic Kernel là middleware pipeline. Thiết kế theo đúng pattern của ASP.NET Core middleware: ordered components, context object, và call_next() delegate.
Ba tầng middleware
graph LR
REQ[Request] --> ARM[Agent Run Middleware]
ARM --> FM[Function Middleware]
FM --> CM[Chat Middleware]
CM --> LLM[LLM Provider]
LLM --> CM2[Chat Middleware]
CM2 --> FM2[Function Middleware]
FM2 --> ARM2[Agent Run Middleware]
ARM2 --> RES[Response]
style REQ fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style ARM fill:#e94560,stroke:#fff,color:#fff
style FM fill:#16213e,stroke:#fff,color:#fff
style CM fill:#2c3e50,stroke:#fff,color:#fff
style LLM fill:#4CAF50,stroke:#fff,color:#fff
style CM2 fill:#2c3e50,stroke:#fff,color:#fff
style FM2 fill:#16213e,stroke:#fff,color:#fff
style ARM2 fill:#e94560,stroke:#fff,color:#fff
style RES fill:#f8f9fa,stroke:#e94560,color:#2c3e50
| Middleware Type | Intercepts | Use Case |
|---|---|---|
| Agent Run Middleware | Toàn bộ agent execution (input/output) | Logging, security checks, response override, audit trail |
| Function Middleware | Tool/function calls | Input validation, rate limiting, result transformation, caching |
| Chat (IChatClient) Middleware | Raw LLM requests/responses | Prompt injection detection, token tracking, content filtering |
Ví dụ: Security Middleware chặn sensitive data
// Middleware chặn request chứa thông tin nhạy cảm
async Task<AgentResponse> SecurityMiddleware(
IEnumerable<ChatMessage> messages,
AgentSession? session,
AgentRunOptions? options,
AIAgent innerAgent,
CancellationToken ct)
{
var lastMessage = messages.LastOrDefault()?.Text ?? "";
// Kiểm tra PII patterns
if (Regex.IsMatch(lastMessage, @"\b\d{9,12}\b") ||
lastMessage.Contains("password", StringComparison.OrdinalIgnoreCase))
{
return new AgentResponse(new[]
{
new ChatMessage(ChatRole.Assistant,
"Yêu cầu bị chặn: phát hiện thông tin nhạy cảm.")
});
}
// Cho phép tiếp tục nếu an toàn
return await innerAgent.RunAsync(messages, session, options, ct);
}
// Middleware log mọi function call
async ValueTask<object?> AuditFunctionMiddleware(
AIAgent agent,
FunctionInvocationContext context,
Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next,
CancellationToken ct)
{
var start = Stopwatch.GetTimestamp();
logger.LogInformation("Tool call: {Name}, Args: {Args}",
context.Function.Name, context.Arguments);
var result = await next(context, ct);
var elapsed = Stopwatch.GetElapsedTime(start);
logger.LogInformation("Tool {Name} completed in {Ms}ms",
context.Function.Name, elapsed.TotalMilliseconds);
return result;
}
// Đăng ký middleware
var securedAgent = originalAgent
.AsBuilder()
.Use(runFunc: SecurityMiddleware)
.Use(AuditFunctionMiddleware)
.Build();
Thứ tự middleware quan trọng!
Middleware thực thi theo thứ tự đăng ký (outermost → innermost). Security middleware nên đăng ký đầu tiên để chặn sớm nhất có thể, trước khi request đi vào logging hay business logic.
6. Declarative Agents — Định nghĩa Agent bằng YAML
Thay vì hard-code agent trong C#, Agent Framework hỗ trợ định nghĩa agent bằng YAML — version-controlled, dễ review, và cho phép non-dev (PM, domain expert) tham gia thiết kế agent behavior:
# agents/diagnostic-agent.yaml
kind: Prompt
name: DiagnosticAgent
displayName: Trợ lý Chẩn đoán Hệ thống
description: Agent chuyên phân tích logs và đề xuất fix
instructions: |
Bạn là chuyên gia DevOps. Khi nhận log error:
1. Phân tích root cause
2. Đề xuất fix cụ thể với code
3. Đánh giá mức độ nghiêm trọng (P0-P3)
Luôn trả lời bằng tiếng Việt.
model:
id: gpt-4o
connection:
kind: azure_openai
endpoint: https://my-project.openai.azure.com/
options:
temperature: 0.3
topP: 0.9
outputSchema:
properties:
severity:
type: string
enum: [P0, P1, P2, P3]
root_cause:
type: string
fix_suggestion:
type: string
// Load agent từ YAML — chỉ 3 dòng
var factory = new ChatClientPromptAgentFactory(chatClient);
var agent = await factory.CreateFromYamlAsync(
File.ReadAllText("agents/diagnostic-agent.yaml"));
var response = await agent!.RunAsync("Error: Connection pool exhausted after 500 concurrent requests");
YAML Agents + GitOps
Declarative agents hoạt động cực tốt với GitOps workflow: mọi thay đổi agent behavior đều qua PR review, có history, có rollback. Team QA có thể review instructions mà không cần đọc C# code.
7. Tool Registration và MCP Integration
Agent Framework hỗ trợ hai cách đăng ký tools: inline function tools (đơn giản, nhanh) và MCP servers (chuẩn hóa, tái sử dụng).
7.1 Inline Function Tools
var tools = new[]
{
AIFunctionFactory.Create(
(string orderId) =>
{
// Query database
var order = db.Orders.Find(orderId);
return order is null
? "Không tìm thấy đơn hàng"
: $"Đơn {orderId}: {order.Status}, ship ngày {order.ShipDate:dd/MM/yyyy}";
},
name: "lookup_order",
description: "Tra cứu trạng thái đơn hàng theo mã order ID"),
AIFunctionFactory.Create(
(string query, int limit = 5) =>
{
var results = searchService.Search(query, limit);
return JsonSerializer.Serialize(results);
},
name: "search_docs",
description: "Tìm kiếm trong knowledge base nội bộ")
};
var agent = chatClient.CreateAIAgent(
instructions: "Bạn là trợ lý CSKH. Dùng lookup_order để tra đơn, search_docs để tìm hướng dẫn.",
tools: tools);
7.2 MCP Server Integration
Agent Framework hỗ trợ MCP (Model Context Protocol) — agents có thể dynamically discover và invoke tools từ bất kỳ MCP-compliant server nào:
// Kết nối MCP Server qua Streamable HTTP
var mcpClient = new McpClient(new Uri("https://mcp.internal.company.com/tools"));
await mcpClient.InitializeAsync();
// Agent tự động discover tools từ MCP server
var agent = chatClient.CreateAIAgent(
instructions: "Bạn có quyền truy cập database và monitoring tools qua MCP.",
tools: mcpClient.GetAvailableTools());
MCP trong Agent Framework vs Claude Code
Cả Agent Framework và Claude Code đều implement MCP client. Khác biệt: Agent Framework dùng MCP như một integration layer trong ứng dụng bạn tự build, còn Claude Code là reference implementation sẵn dùng. Nếu bạn đã quen MCP từ Claude Code, kiến thức đó hoàn toàn transfer được sang Agent Framework.
8. Observability với OpenTelemetry
Agent Framework tích hợp sâu với OpenTelemetry, emit traces, logs, và metrics theo chuẩn OpenTelemetry GenAI Semantic Conventions. Đây là khác biệt lớn so với hầu hết các framework khác — thay vì vendor-locked telemetry, bạn dùng chuẩn mở.
Setup OpenTelemetry cho Agent
using OpenTelemetry;
using OpenTelemetry.Trace;
using OpenTelemetry.Metrics;
const string SourceName = "MyAgentApp";
// 1. Instrument chat client
var instrumentedClient = chatClient
.AsBuilder()
.UseOpenTelemetry(
sourceName: SourceName,
configure: cfg => cfg.EnableSensitiveData = true)
.Build();
// 2. Instrument agent
var agent = new ChatClientAgent(instrumentedClient,
name: "SupportAgent",
instructions: "Bạn là trợ lý hỗ trợ kỹ thuật.")
.WithOpenTelemetry(
sourceName: SourceName,
configure: cfg => cfg.EnableSensitiveData = true);
// 3. Export sang OTLP (Aspire Dashboard, Grafana, Jaeger...)
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("agent-app"))
.AddSource(SourceName)
.AddOtlpExporter(opt => opt.Endpoint = new Uri("http://localhost:4317"))
.Build();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(SourceName)
.AddOtlpExporter(opt => opt.Endpoint = new Uri("http://localhost:4317"))
.Build();
Các metrics và spans tự động
| Tên | Loại | Ý nghĩa |
|---|---|---|
invoke_agent <name> | Span | Toàn bộ vòng đời một lần gọi agent |
chat <model> | Span | Mỗi lần gọi LLM (bao gồm prompt + completion) |
execute_tool <func> | Span | Mỗi lần tool/function được thực thi |
gen_ai.client.operation.duration | Histogram | Latency của mỗi LLM operation |
gen_ai.client.token.usage | Histogram | Token consumption (input + output) |
agent_framework.function.invocation.duration | Histogram | Latency của tool execution |
graph LR
AF[Agent Framework] -->|OTLP| COL[OTel Collector]
COL --> TRACE[Tempo / Jaeger]
COL --> METRIC[Prometheus]
COL --> LOG[Loki]
TRACE --> GR[Grafana Dashboard]
METRIC --> GR
LOG --> GR
style AF fill:#e94560,stroke:#fff,color:#fff
style COL fill:#2c3e50,stroke:#fff,color:#fff
style TRACE fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style METRIC fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style LOG fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style GR fill:#4CAF50,stroke:#fff,color:#fff
DevUI — Debugger trực quan
Agent Framework đi kèm DevUI — browser-based debugger hiển thị real-time: message flows, tool calls, orchestration decisions, và agent transitions. Chỉ dùng trong development (thêm ~15-30ms latency mỗi step). Kết hợp DevUI + OpenTelemetry tạo thành observability hoàn chỉnh từ dev đến production.
9. Graph-based Workflows — Vượt xa Orchestration Patterns
Khi 5 orchestration patterns built-in không đủ linh hoạt, Agent Framework cung cấp graph-based workflows — cho phép thiết kế luồng xử lý phức tạp tùy ý bằng directed graph:
// Các khái niệm cốt lõi:
// - Executor: đơn vị xử lý (AI agent hoặc custom logic)
// - Edge: kết nối giữa executors, hỗ trợ conditional routing
// - Workflow: directed graph quản lý execution qua supersteps
var classifier = new ChatClientAgent(chatClient,
"Phân loại input: 'technical' hoặc 'business'. Chỉ trả về một từ.",
name: "classifier");
var techAgent = new ChatClientAgent(chatClient,
"Bạn giải đáp vấn đề kỹ thuật chi tiết.",
name: "tech_expert");
var bizAgent = new ChatClientAgent(chatClient,
"Bạn tư vấn chiến lược kinh doanh.",
name: "biz_advisor");
var summarizer = new ChatClientAgent(chatClient,
"Bạn tổng hợp kết quả thành báo cáo ngắn gọn.",
name: "summarizer");
// Build graph
var workflow = new AgentWorkflowBuilder()
.AddExecutor(classifier)
.AddExecutor(techAgent)
.AddExecutor(bizAgent)
.AddExecutor(summarizer)
.AddConditionalEdge(classifier, msg =>
msg.Contains("technical") ? techAgent.Name : bizAgent.Name)
.AddEdge(techAgent, summarizer)
.AddEdge(bizAgent, summarizer)
.SetEntryPoint(classifier)
.Build();
graph TD
CL[Classifier Agent] -->|"technical"| TE[Tech Expert]
CL -->|"business"| BA[Biz Advisor]
TE --> SU[Summarizer]
BA --> SU
style CL fill:#e94560,stroke:#fff,color:#fff
style TE fill:#2c3e50,stroke:#fff,color:#fff
style BA fill:#2c3e50,stroke:#fff,color:#fff
style SU fill:#4CAF50,stroke:#fff,color:#fff
10. So sánh với các Agent Framework khác
| Feature | MS Agent Framework 1.0 | LangGraph | CrewAI |
|---|---|---|---|
| Ngôn ngữ | C#/.NET + Python | Python, JS | Python |
| Kiến trúc | Graph workflows + 5 orchestrations | Cyclical graph + shared state | Role-based agent teams |
| Enterprise features | Middleware, telemetry, sessions, type safety | State management, checkpointing | Task delegation |
| Protocol support | MCP + A2A | LangChain ecosystem | Hạn chế |
| Observability | OpenTelemetry native + Aspire | LangSmith | Hạn chế |
| Declarative config | YAML agents + workflows | Không | YAML crews |
| Human-in-the-loop | Built-in (tool approval, request info) | Có | Hạn chế |
| Memory | Pluggable (Redis, Neo4j, Mem0) | Built-in state | Hạn chế |
| Thế mạnh | Unified .NET+Python, enterprise pipeline | Fine-grained graph, LangChain | Đơn giản nhất cho role-based |
Chọn framework nào?
Agent Framework 1.0 là lựa chọn tốt nhất nếu team bạn đã dùng .NET, cần enterprise features (middleware, telemetry, type safety), và muốn một framework có backing lâu dài từ Microsoft. LangGraph phù hợp hơn cho Python-first teams cần fine-grained graph control. CrewAI tốt cho prototype nhanh role-based multi-agent nhưng thiếu enterprise maturity.
11. Real-world Architecture: Interview Coach
Microsoft cung cấp một reference implementation đầy đủ — Interview Coach — minh họa cách kết hợp Agent Framework với Aspire, MCP, và Foundry trong production:
graph TB
UI[Blazor WebUI] --> AS[Agent Service
Agent Framework 1.0]
AS --> MCP1[MarkItDown MCP Server
Python - Parse documents]
AS --> MCP2[InterviewData MCP Server
.NET - SQLite queries]
AS --> FD[Microsoft Foundry
LLM Provider]
subgraph Agents
TR[Triage Agent]
RC[Receptionist Agent]
BH[Behavioural Agent]
TC[Technical Agent]
SM[Summariser Agent]
end
AS --> Agents
TR --> RC
RC --> BH
BH --> TC
TC --> SM
SM --> TR
ASPIRE[.NET Aspire] -.->|orchestrate| UI
ASPIRE -.->|orchestrate| AS
ASPIRE -.->|orchestrate| MCP1
ASPIRE -.->|orchestrate| MCP2
style UI fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style AS fill:#e94560,stroke:#fff,color:#fff
style MCP1 fill:#2c3e50,stroke:#fff,color:#fff
style MCP2 fill:#2c3e50,stroke:#fff,color:#fff
style FD fill:#4CAF50,stroke:#fff,color:#fff
style ASPIRE fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style TR fill:#e94560,stroke:#fff,color:#fff
style RC fill:#16213e,stroke:#fff,color:#fff
style BH fill:#16213e,stroke:#fff,color:#fff
style TC fill:#16213e,stroke:#fff,color:#fff
style SM fill:#16213e,stroke:#fff,color:#fff
Kiến trúc này thể hiện sức mạnh của Agent Framework khi kết hợp với hệ sinh thái .NET:
- .NET Aspire orchestrate toàn bộ services — service discovery, health checks, distributed tracing tự động.
- 5 agents sử dụng Handoff pattern — triage route đến receptionist (thu thập thông tin), rồi behavioural interview, technical interview, cuối cùng summariser tổng hợp feedback.
- 2 MCP Servers — một bằng Python (parse CV/resume), một bằng .NET (query interview database).
- Microsoft Foundry — model routing, content safety, managed hosting.
12. Migration từ Semantic Kernel / AutoGen
Nếu team bạn đang dùng Semantic Kernel hoặc AutoGen, đây là mapping cơ bản:
| Semantic Kernel | Agent Framework 1.0 |
|---|---|
Kernel + KernelPlugin | AIAgent + AIFunctionFactory |
KernelFunction | AIFunction (từ M.E.AI) |
ChatCompletionService | IChatClient (từ M.E.AI) |
KernelFilter | Middleware pipeline (3 layers) |
| AutoGen | Agent Framework 1.0 |
|---|---|
AssistantAgent | ChatClientAgent |
GroupChat | AgentWorkflowBuilder.BuildGroupChat() |
Magentic-One | AgentWorkflowBuilder.BuildMagenticOne() |
| Conversation routing | Handoff orchestration |
Lưu ý khi migrate
Semantic Kernel và AutoGen đã vào maintenance mode — chỉ nhận bug fixes và security patches. Không có tính năng mới. Microsoft khuyến nghị migrate sang Agent Framework cho tất cả dự án mới và dần migrate dự án cũ. Migration guide chính thức tại learn.microsoft.com/en-us/agent-framework/migration-guide/.
13. Quick Start — Từ 0 đến Agent đầu tiên
# 1. Tạo project .NET 10
dotnet new console -n MyFirstAgent
cd MyFirstAgent
# 2. Thêm packages
dotnet add package Microsoft.Agents.AI
dotnet add package Microsoft.Agents.AI.OpenAI
# Hoặc: Microsoft.Agents.AI.Foundry cho Azure AI Foundry
// Program.cs — Agent đơn giản nhất
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.OpenAI;
using OpenAI;
var openAiClient = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
var chatClient = openAiClient
.GetChatClient("gpt-4o")
.AsIChatClient();
var agent = chatClient.CreateAIAgent(
instructions: "Bạn là trợ lý lập trình .NET. Trả lời ngắn gọn, có code example.");
// Single turn
var response = await agent.RunAsync("Viết extension method convert string sang slug URL");
Console.WriteLine(response);
// Multi-turn với session
var session = new AgentSession();
await agent.RunAsync("Thêm hỗ trợ Unicode cho method trên", session: session);
Console.WriteLine(session.Messages.Last().Text);
Tip: Dùng Ollama cho development
Thay vì tốn tiền API khi develop, kết nối Agent Framework với Ollama chạy local:
dotnet add package Microsoft.Extensions.AI.Ollama
var chatClient = new OllamaChatClient(new Uri("http://localhost:11434"), "llama3.1");
Code business logic giữ nguyên — chỉ đổi chat client khi deploy production.
14. Best Practices cho Production
- Bắt đầu single-agent: 80% use case chỉ cần một agent với tools tốt. Chỉ thêm agent khi có bottleneck rõ ràng về chuyên môn hoặc parallelism.
- Middleware cho cross-cutting concerns: Logging, security, rate limiting — đừng nhồi vào agent instructions. Middleware tách biệt, testable, reusable.
- YAML agents cho behavior iteration: Khi cần thay đổi agent behavior thường xuyên, dùng declarative YAML thay vì hard-code. PM và domain expert có thể review instructions qua PR.
- OpenTelemetry từ ngày đầu: Đừng đợi production mới thêm telemetry. Setup ngay từ development — cost gần như zero nhưng debug value rất cao.
- Handoff > Group Chat cho customer-facing: Handoff cho conversation flow rõ ràng, predictable. Group Chat phù hợp cho internal brainstorming nhưng khó kiểm soát output quality.
- Function middleware cho tool safety: Validate mọi tool input, đặc biệt khi tool truy cập database hoặc external API. LLM có thể hallucinate parameters.
Kết luận
Microsoft Agent Framework 1.0 đánh dấu bước trưởng thành của hệ sinh thái AI agent trên .NET. Thay vì chọn giữa Semantic Kernel (enterprise) và AutoGen (multi-agent), giờ đây bạn có một SDK thống nhất kết hợp tinh hoa của cả hai, cộng thêm graph workflows, declarative YAML agents, MCP integration, và observability chuẩn OpenTelemetry.
Với 5 orchestration patterns built-in, 3 tầng middleware pipeline, hỗ trợ 7+ model providers, và tích hợp sâu với .NET Aspire — Agent Framework 1.0 là câu trả lời production-ready cho câu hỏi "build AI agents trên .NET như thế nào?"
Nếu bạn đang dùng Semantic Kernel hoặc AutoGen, đây là lúc bắt đầu lên kế hoạch migrate. Nếu bạn mới bắt đầu — Agent Framework 1.0 là điểm khởi đầu tốt nhất.
Tham khảo
- Microsoft Agent Framework Version 1.0 — Official Announcement
- Agent Framework Overview — Microsoft Learn
- Agent Framework GitHub Repository (MIT License)
- Workflow Orchestrations — Microsoft Learn
- Agent Middleware — Microsoft Learn
- Declarative Agents — Microsoft Learn
- Observability — Microsoft Learn
- Golden Triangle: AG-UI, DevUI & OpenTelemetry Deep Dive
- Real-World Example with Agent Framework, Foundry, MCP and Aspire
- Visual Studio Magazine: Microsoft Ships Agent Framework 1.0
Grafana LGTM Stack: Xây dựng Observability Platform miễn phí cho Production
API Gateway 2026 — Kiến trúc Cổng Trung Tâm cho Microservices với YARP, Kong và BFF Pattern
Disclaimer: The opinions expressed in this blog are solely my own and do not reflect the views or opinions of my employer or any affiliated organizations. The content provided is for informational and educational purposes only and should not be taken as professional advice. While I strive to provide accurate and up-to-date information, I make no warranties or guarantees about the completeness, reliability, or accuracy of the content. Readers are encouraged to verify the information and seek independent advice as needed. I disclaim any liability for decisions or actions taken based on the content of this blog.