Semantic Kernel & Microsoft Agent Framework 1.0 — Xây Dựng AI Agent Với C#
Posted on: 4/26/2026 8:12:36 PM
Table of contents
- Bối cảnh: Tại sao cần một AI Framework cho .NET?
- Từ Semantic Kernel đến Microsoft Agent Framework 1.0
- Kiến trúc tổng quan
- Semantic Kernel Core: Kernel, Plugin, Connector
- 5 Orchestration Patterns cho Multi-Agent
- Tích hợp MCP và A2A Protocol
- Declarative Agent — Định nghĩa Agent bằng YAML
- Memory và RAG tích hợp sẵn
- Semantic Kernel vs LangChain — Khi nào chọn gì?
- Ví dụ thực tế: Hệ thống Customer Support Multi-Agent
- Best Practices cho Production
- Kết luận
- Tài liệu tham khảo
Bối cảnh: Tại sao cần một AI Framework cho .NET?
Năm 2026, xây dựng ứng dụng AI không còn đơn giản là gọi một API chat completion rồi trả kết quả cho user. Các hệ thống thực tế đòi hỏi agent có khả năng tự chủ — đọc dữ liệu từ nhiều nguồn, gọi API ngoài, lập kế hoạch hành động nhiều bước, và phối hợp với các agent khác để hoàn thành nhiệm vụ phức tạp.
Với hệ sinh thái Python, LangChain và CrewAI đã chiếm lĩnh sớm. Nhưng đối với .NET developer — những người đang vận hành hệ thống enterprise bằng C# — thì thiếu một framework AI native, tích hợp tốt với dependency injection, middleware pipeline, và kiến trúc microservices quen thuộc. Microsoft Semantic Kernel ra đời để lấp đầy khoảng trống đó.
Từ Semantic Kernel đến Microsoft Agent Framework 1.0
Điểm mấu chốt
Agent Framework 1.0 không thay thế Semantic Kernel — nó xây dựng bên trên. Semantic Kernel vẫn là foundation layer (Kernel, Plugin, Connector), còn AutoGen cung cấp multi-agent orchestration engine. Nếu bạn đã dùng Semantic Kernel, mọi plugin và connector hiện tại vẫn hoạt động.
Kiến trúc tổng quan
graph TD
subgraph "Microsoft Agent Framework 1.0"
MAF["Agent Framework API"]
subgraph "Orchestration Layer"
SEQ["Sequential"]
CON["Concurrent"]
HO["Handoff"]
GC["Group Chat"]
MAG["Magentic-One"]
end
subgraph "Semantic Kernel Core"
K["Kernel"]
P["Plugins"]
M["Memory / RAG"]
C["AI Connectors"]
end
subgraph "Runtime"
IP["InProcess Runtime"]
DR["Distributed Runtime"]
end
end
MAF --> SEQ
MAF --> CON
MAF --> HO
MAF --> GC
MAF --> MAG
SEQ --> K
CON --> K
HO --> K
GC --> K
MAG --> K
K --> P
K --> M
K --> C
K --> IP
K --> DR
C --> OAI["OpenAI / Azure OpenAI"]
C --> HF["Hugging Face"]
C --> NV["NVIDIA"]
C --> OL["Ollama (Local)"]
style MAF fill:#e94560,stroke:#fff,color:#fff
style K fill:#2c3e50,stroke:#fff,color:#fff
style SEQ fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style CON fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style HO fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style GC fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style MAG fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Kiến trúc được chia thành 3 tầng rõ ràng:
- Semantic Kernel Core: Kernel xử lý AI model invocation, Plugin cung cấp khả năng mở rộng (native functions, OpenAPI, MCP tools), Memory/RAG kết nối knowledge base.
- Orchestration Layer: 5 patterns phối hợp multi-agent, kế thừa từ AutoGen research.
- Runtime: Quản lý lifecycle của agent — InProcess cho đơn giản, Distributed cho production scale.
Semantic Kernel Core: Kernel, Plugin, Connector
Kernel — Trái tim của hệ thống
Kernel là điểm trung tâm kết nối AI model với business logic. Nó quản lý AI service (chọn model nào, config thế nào), plugin registry, và memory providers. Kernel tích hợp trực tiếp với Microsoft.Extensions.DependencyInjection — điều này cực kỳ quen thuộc với .NET developer:
using Microsoft.SemanticKernel;
var builder = Kernel.CreateBuilder();
// Thêm AI service
builder.AddAzureOpenAIChatCompletion(
deploymentName: "gpt-4o",
endpoint: "https://your-resource.openai.azure.com/",
apiKey: "your-api-key"
);
// Thêm plugin từ class
builder.Plugins.AddFromType<WeatherPlugin>();
builder.Plugins.AddFromType<DatabasePlugin>();
// Build kernel
Kernel kernel = builder.Build();
Plugin — Mở rộng khả năng của AI
Plugin là cách bạn "dạy" AI model biết gọi code thực tế. Mỗi plugin là một class C# với các method được đánh dấu [KernelFunction]:
public class OrderPlugin
{
[KernelFunction, Description("Tra cứu thông tin đơn hàng theo mã")]
public async Task<OrderInfo> GetOrderAsync(
[Description("Mã đơn hàng")] string orderId,
IOrderService orderService)
{
return await orderService.GetByIdAsync(orderId);
}
[KernelFunction, Description("Tạo đơn hàng mới từ danh sách sản phẩm")]
public async Task<string> CreateOrderAsync(
[Description("Danh sách product ID")] List<int> productIds,
[Description("Địa chỉ giao hàng")] string shippingAddress,
IOrderService orderService)
{
var order = await orderService.CreateAsync(productIds, shippingAddress);
return $"Đã tạo đơn hàng #{order.Id}";
}
}
Khi user hỏi "Đơn hàng ORD-1234 của tôi đang ở đâu?", AI model sẽ tự nhận ra cần gọi GetOrderAsync với tham số "ORD-1234". Toàn bộ quá trình function calling được Semantic Kernel xử lý tự động.
Plugin từ nhiều nguồn
Ngoài native C# class, Semantic Kernel còn hỗ trợ import plugin từ OpenAPI spec (Swagger), Prompt template (YAML/JSON), và MCP Server — nghĩa là bạn có thể biến bất kỳ REST API nào thành tool cho AI mà không cần viết wrapper code.
AI Connectors — Không vendor lock-in
| Provider | NuGet Package | Model hỗ trợ |
|---|---|---|
| Azure OpenAI | Microsoft.SemanticKernel.Connectors.AzureOpenAI |
GPT-4o, GPT-4.1, o3, o4-mini |
| OpenAI | Microsoft.SemanticKernel.Connectors.OpenAI |
GPT-4o, GPT-4.1, DALL·E |
| Hugging Face | Microsoft.SemanticKernel.Connectors.HuggingFace |
Mistral, Llama, Phi |
| NVIDIA | Microsoft.SemanticKernel.Connectors.Nvidia |
NIM microservices |
| Ollama | Microsoft.SemanticKernel.Connectors.Ollama |
Mọi model local (Llama 3, Phi-3, Gemma) |
Microsoft.SemanticKernel.Connectors.Google |
Gemini Pro, Gemini Ultra |
5 Orchestration Patterns cho Multi-Agent
Đây là phần mạnh nhất của Agent Framework 1.0 — kế thừa từ nghiên cứu AutoGen của Microsoft Research, cung cấp 5 pattern phối hợp agent:
graph LR
subgraph "Sequential"
S1["Agent A"] --> S2["Agent B"] --> S3["Agent C"]
end
style S1 fill:#e94560,stroke:#fff,color:#fff
style S2 fill:#2c3e50,stroke:#fff,color:#fff
style S3 fill:#4CAF50,stroke:#fff,color:#fff
1. Sequential — Pipeline tuần tự
Agent A xử lý xong, truyền kết quả cho Agent B, rồi Agent C. Phù hợp cho workflow nhiều bước có thứ tự rõ ràng: phân tích → xử lý → review.
// Agent phân tích yêu cầu → Agent viết code → Agent review code
var analyst = new ChatCompletionAgent
{
Name = "Analyst",
Instructions = "Phân tích yêu cầu và tạo technical spec.",
Kernel = kernel
};
var coder = new ChatCompletionAgent
{
Name = "Coder",
Instructions = "Viết C# code dựa trên technical spec.",
Kernel = kernel
};
var reviewer = new ChatCompletionAgent
{
Name = "Reviewer",
Instructions = "Review code về security, performance, best practices.",
Kernel = kernel
};
SequentialOrchestration pipeline = new(analyst, coder, reviewer);
InProcessRuntime runtime = new();
await runtime.StartAsync();
var result = await pipeline.InvokeAsync(
"Tạo REST API endpoint cho quản lý sản phẩm với pagination và caching",
runtime);
string output = await result.GetValueAsync();
2. Concurrent — Xử lý song song
Broadcast cùng một task cho tất cả agent, thu thập kết quả độc lập. Lý tưởng cho phân tích đa chiều hoặc ensemble decision making:
var securityAnalyst = CreateAgent("SecurityAnalyst", "Phân tích code về lỗ hổng bảo mật.");
var perfAnalyst = CreateAgent("PerfAnalyst", "Phân tích code về hiệu năng.");
var uxAnalyst = CreateAgent("UXAnalyst", "Phân tích API design về developer experience.");
ConcurrentOrchestration ensemble = new(securityAnalyst, perfAnalyst, uxAnalyst);
// Cả 3 agent chạy song song, mỗi agent cho góc nhìn riêng
var result = await ensemble.InvokeAsync(codeToReview, runtime);
3. Handoff — Chuyển giao động
Agent tự quyết định khi nào cần chuyển task cho agent khác dựa trên ngữ cảnh. Giống hệ thống support escalation:
sequenceDiagram
participant U as User
participant T as Triage Agent
participant B as Billing Agent
participant S as Senior Support
U->>T: "Tôi bị tính tiền sai tháng này"
T->>B: Handoff → Billing Agent
B->>B: Kiểm tra invoice, phát hiện anomaly
B->>S: Handoff → Senior Support (cần refund approval)
S->>U: Xác nhận refund và gửi email
HandoffOrchestration handoff = new(
triageAgent, billingAgent, seniorSupport)
{
// Agent tự quyết định chuyển giao qua function call
InteractionMode = InteractionMode.Dynamic
};
4. Group Chat — Thảo luận nhóm
Nhiều agent tham gia một cuộc hội thoại chung, điều phối bởi Group Manager. Phù hợp cho brainstorming, collaborative problem solving, hoặc consensus building. Group Manager quyết định agent nào được phát biểu tiếp dựa trên ngữ cảnh cuộc trò chuyện.
5. Magentic-One — Multi-agent tổng quát
Lấy cảm hứng từ paper MagenticOne của Microsoft Research — một hệ multi-agent "generalist" có khả năng giải quyết task phức tạp. Bao gồm Orchestrator agent điều phối và các Specialist agents (WebSurfer, FileSurfer, Coder, Terminal). Pattern này mạnh nhất nhưng cũng phức tạp nhất.
| Pattern | Khi nào dùng | Độ phức tạp |
|---|---|---|
| Sequential | Pipeline có thứ tự rõ ràng (ETL, CI/CD automation) | Thấp |
| Concurrent | Phân tích song song, ensemble voting | Thấp |
| Handoff | Customer support, task routing động | Trung bình |
| Group Chat | Brainstorming, collaborative review | Trung bình |
| Magentic-One | Task phức tạp, cần nhiều specialist | Cao |
Tích hợp MCP và A2A Protocol
Agent Framework 1.0 hỗ trợ hai protocol quan trọng trong hệ sinh thái AI agent:
Model Context Protocol (MCP)
MCP cho phép agent discover và invoke tool từ MCP server bên ngoài một cách dynamic. Thay vì hardcode plugin, agent có thể kết nối tới MCP server và tự khám phá các tool available:
// Kết nối MCP server để import tool động
var mcpTools = await McpClientFactory.CreateAsync(
new SseClientTransport(new Uri("http://localhost:3001/sse")));
kernel.Plugins.AddFromMcpServer("ExternalTools", mcpTools);
Agent-to-Agent Protocol (A2A)
A2A (từ Google DeepMind) cho phép agent ở các runtime khác nhau giao tiếp với nhau qua HTTP. Một agent .NET có thể gọi agent Python hoặc agent Java thông qua A2A endpoint chuẩn. Điều này mở ra khả năng xây dựng hệ thống polyglot multi-agent — mỗi agent viết bằng ngôn ngữ phù hợp nhất.
graph TD
A["C# Agent
(Semantic Kernel)"] -->|A2A Protocol| B["Python Agent
(LangChain)"]
A -->|A2A Protocol| C["Java Agent
(Spring AI)"]
A -->|MCP| D["MCP Server
(Database Tools)"]
A -->|MCP| E["MCP Server
(File System)"]
style A fill:#e94560,stroke:#fff,color:#fff
style B fill:#2c3e50,stroke:#fff,color:#fff
style C fill:#2c3e50,stroke:#fff,color:#fff
style D fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style E fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Declarative Agent — Định nghĩa Agent bằng YAML
Một tính năng mới trong 1.0 là Declarative Agents — thay vì code C# cứng, bạn có thể định nghĩa agent instruction, tool binding, và orchestration topology trong file YAML version-controlled:
# agents/order-support.yaml
name: OrderSupport
instructions: |
Bạn là chuyên gia hỗ trợ đơn hàng. Tra cứu thông tin đơn hàng,
xử lý yêu cầu đổi trả, và escalate cho senior nếu cần.
model: gpt-4o
tools:
- plugin: OrderPlugin
- plugin: ShippingPlugin
- mcp: http://localhost:3001/sse
memory:
provider: azure-ai-search
index: order-knowledge-base
orchestration:
pattern: handoff
members:
- agent: agents/billing-agent.yaml
- agent: agents/senior-support.yaml
// Load và chạy agent từ YAML
var agent = await AgentFactory.CreateFromYamlAsync("agents/order-support.yaml");
var runtime = new InProcessRuntime();
await runtime.StartAsync();
var result = await agent.InvokeAsync("Đơn ORD-5678 giao trễ 3 ngày", runtime);
Lợi ích của Declarative Agents
YAML agent definitions có thể version control, review trong PR, và deploy qua CI/CD pipeline — không cần recompile code khi thay đổi agent behavior. Đây là pattern rất phù hợp cho team lớn khi AI engineer và backend developer làm việc song song.
Memory và RAG tích hợp sẵn
Agent Framework tích hợp native RAG (Retrieval-Augmented Generation) — cho phép agent truy vấn knowledge base riêng thay vì chỉ dựa vào training data của LLM:
// Cấu hình vector store cho memory
builder.AddAzureAISearchVectorStore(
endpoint: new Uri("https://your-search.search.windows.net"),
apiKey: "your-key");
// Hoặc dùng in-memory cho dev
builder.AddInMemoryVectorStore();
// Agent tự động search memory khi cần context
var agent = new ChatCompletionAgent
{
Name = "KnowledgeAgent",
Instructions = "Trả lời dựa trên knowledge base nội bộ.",
Kernel = kernel,
// Memory được inject tự động qua DI
};
Semantic Kernel hỗ trợ nhiều vector store backend: Azure AI Search, Qdrant, Pinecone, Weaviate, PostgreSQL (pgvector), Redis — bạn chọn backend phù hợp với infrastructure hiện tại.
Semantic Kernel vs LangChain — Khi nào chọn gì?
| Tiêu chí | Semantic Kernel / Agent Framework | LangChain |
|---|---|---|
| Ngôn ngữ chính | C# (.NET), Python | Python, JavaScript |
| Kiến trúc | Plugin model + DI container | Chain/Agent abstraction |
| Multi-agent | 5 built-in orchestration patterns | LangGraph (graph-based) |
| Enterprise integration | Native Azure, Microsoft 365, Dynamics | Community integrations |
| Ecosystem | Nhỏ hơn, tập trung .NET | Lớn hơn, nhiều third-party tool |
| Khi nào chọn | Team .NET, enterprise Microsoft stack | Team Python, cần nhiều pre-built integration |
Lưu ý khi migrate
Nếu đã dùng Semantic Kernel < 1.0, hãy kiểm tra breaking changes trong Agent Orchestration API — đặc biệt là cách tạo agent (từ AgentBuilder sang ChatCompletionAgent constructor) và cách invoke (từ agent.InvokeAsync trực tiếp sang qua Orchestration + Runtime).
Ví dụ thực tế: Hệ thống Customer Support Multi-Agent
Để minh họa sức mạnh của framework, hãy xây dựng một hệ thống customer support với 3 agent phối hợp qua Handoff pattern:
graph TD
U["Khách hàng"] --> T["Triage Agent"]
T -->|FAQ| F["FAQ Agent
(tra cứu knowledge base)"]
T -->|Kỹ thuật| TE["Technical Agent
(debug + log lookup)"]
T -->|Billing| B["Billing Agent
(invoice + refund)"]
F --> R["Response → Khách hàng"]
TE --> R
B --> R
style T fill:#e94560,stroke:#fff,color:#fff
style F fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style TE fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style B fill:#f8f9fa,stroke:#e94560,color:#2c3e50
// 1. Tạo các agent chuyên biệt
var triageAgent = new ChatCompletionAgent
{
Name = "TriageAgent",
Instructions = """
Phân loại yêu cầu khách hàng vào một trong 3 nhóm:
- FAQ: câu hỏi thường gặp về sản phẩm
- Technical: vấn đề kỹ thuật, bug, lỗi
- Billing: hóa đơn, thanh toán, hoàn tiền
Chuyển giao cho agent phù hợp.
""",
Kernel = kernel
};
var faqAgent = new ChatCompletionAgent
{
Name = "FAQAgent",
Instructions = "Trả lời FAQ dựa trên knowledge base sản phẩm.",
Kernel = kernelWithRAG // Kernel có vector store
};
var technicalAgent = new ChatCompletionAgent
{
Name = "TechnicalAgent",
Instructions = "Hỗ trợ kỹ thuật: tra cứu log, kiểm tra status service.",
Kernel = kernelWithTools // Kernel có LogPlugin, ServiceStatusPlugin
};
var billingAgent = new ChatCompletionAgent
{
Name = "BillingAgent",
Instructions = "Xử lý vấn đề billing: tra cứu invoice, xử lý refund request.",
Kernel = kernelWithBilling // Kernel có InvoicePlugin
};
// 2. Tạo Handoff orchestration
HandoffOrchestration support = new(triageAgent, faqAgent, technicalAgent, billingAgent);
// 3. Chạy
InProcessRuntime runtime = new();
await runtime.StartAsync();
var result = await support.InvokeAsync(
"Tháng này tôi bị charge 2 lần cho gói Premium, xin kiểm tra giúp.",
runtime);
Console.WriteLine(await result.GetValueAsync());
await runtime.RunUntilIdleAsync();
Best Practices cho Production
1. Giới hạn scope cho mỗi agent
Mỗi agent chỉ nên có 3-5 tool tối đa. Quá nhiều tool khiến LLM khó chọn đúng function call, tăng latency và giảm accuracy. Nếu cần nhiều capability, chia thành nhiều agent và dùng Handoff.
2. Streaming cho UX tốt hơn
Mọi orchestration pattern đều hỗ trợ streaming response. Với conversation dài, hãy bật streaming thay vì chờ toàn bộ response hoàn tất — user experience khác biệt rất lớn.
3. Human-in-the-loop checkpoint
Với các action có side-effect (gửi email, tạo refund, deploy code), luôn đặt checkpoint yêu cầu human approval trước khi agent thực thi. Agent Framework hỗ trợ native qua HumanInTheLoop middleware.
4. Observability với OpenTelemetry
Agent Framework tích hợp sẵn OpenTelemetry traces. Mỗi agent invocation tạo span riêng, giúp bạn track latency, token usage, và error rate trên Jaeger/Grafana Tempo. Đây là yếu tố bắt buộc cho production.
5. Dùng Distributed Runtime khi cần scale
InProcess runtime đủ cho prototype và service nhỏ. Khi agent workload tăng hoặc cần fault tolerance, chuyển sang Distributed Runtime — agent được deploy như microservice độc lập, giao tiếp qua message bus.
Kết luận
Microsoft Agent Framework 1.0 đánh dấu bước trưởng thành quan trọng cho AI agent development trên .NET. Bằng cách hợp nhất Semantic Kernel (foundation vững chắc) với AutoGen (multi-agent orchestration), Microsoft cung cấp một SDK thống nhất từ prototype đến production.
Với 5 orchestration patterns, plugin architecture mở rộng, native MCP/A2A support, và tích hợp sâu vào hệ sinh thái .NET — đây là framework cần nắm vững nếu bạn đang xây dựng ứng dụng AI bằng C#. Điểm mạnh nhất chính là developer không cần rời bỏ kiến trúc DI/middleware quen thuộc để bước vào thế giới AI agent.
Tài liệu tham khảo
GitHub Copilot Coding Agent — Khi AI Tự Viết Code Và Tạo Pull Request
Local-First Architecture — Khi ứng dụng web không cần chờ server để phản hồi
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.