跳至主要內容

AI Genius — 第 5 季第 2 集

🔥 Agent HQ:使用 GitHub Copilot SDK 建置零售分析助手

課程說明

代理程式在聊天視窗中的表現令人印象深刻,但真正的價值體現在將其嵌入團隊已經在使用的應用程式中。本課程基於 GitHub Copilot SDK 建置零售交易分析助手:使用 .NET 10 API 透過 SSE 串流傳輸模型回應,由 Blazor 前端即時呈現,並配備治理基礎架構(自訂代理程式、掛鉤、稽核追蹤和程式碼掃描),從而能夠安全交付。

課程投影片

請參閱 docs/ —「三個星期一」的敘事收錄於 Slide1.pngSlide3.png

🧠 學習成果

完成本課程後,你將能夠:

  • 將 GitHub Copilot SDK 執行階段嵌入 ASP.NET Core 應用程式
  • 透過伺服器傳送事件(SSE),逐一權杖將模型回應串流傳輸到瀏覽器
  • 在執行階段發現可用模型,而不是硬編碼可能過時的清單
  • 將企業治理能力(自訂代理程式、掛鉤、稽核記錄和程式碼掃描)應用於 AI 輔助開發

💬 使用 Copilot 持續學習

嘗試使用以下提示詞與 GitHub Copilot 互動,探索本課程涵蓋的主題。在 VS Code 中開啟 Copilot Chat(Windows/Linux 使用 Ctrl+Alt+I,Mac 使用 Cmd+Shift+I),貼上提示詞,看看能學到什麼。還可以嘗試連線 Microsoft Learn MCP Server,取得最新的官方文件。

可以從這些提示詞開始,也可以自行撰寫提示詞!

  • 我可以使用 GitHub Copilot SDK 建置什麼?
  • 如何在 ASP.NET Core 中透過伺服器傳送事件串流傳輸 Copilot SDK 回應?
  • 如何列出已登入 Copilot 帳號可用的模型?
  • 如何為 Copilot SDK 設定身分驗證?
  • 什麼是 Copilot 掛鉤?如何使用它們強制實施安全閘門?

📚 資源與後續行動

資源 說明
GitHub Copilot SDK 儲存庫 適用於所有受支援語言的 SDK
Copilot SDK 入門 建置你的第一個 Copilot 技術驅動的應用程式
Awesome Copilot 自訂代理程式、指令、技能、掛鉤、工作流程和外掛
GitHub Copilot 文件 官方產品文件

🌟 Microsoft Learn MCP Server

Microsoft Learn MCP Server 可讓 AI 代理程式直接存取 Microsoft 官方文件,為本課程涵蓋的產品和服務提供有可靠依據且保持最新的解答。

VS Code — 此儲存庫已包含 .vscode/mcp.json,因此開啟該資料夾時,伺服器即已完成設定。

GitHub Copilot CLI — 執行以下命令,將 Learn MCP Server 安裝為外掛:

/plugin install microsoftdocs/mcp

如需瞭解更多資訊、檢視其他用戶端或提交問題,請造訪 Learn MCP Server 儲存庫


✨ 此示範展示的功能

功能 你將看到的內容
多模型 AI 聊天 從 Copilot CLI 即時取得模型清單,隨時保持最新
零售分析領域 交易資料、客戶分群與分群預測
即時串流傳輸 逐一權杖 SSE 回應與批次轉譯
企業治理 稽核追蹤、原則掛鉤、安全閘門和程式碼掃描

🛠️ 技術堆疊

同一應用程式提供兩種實作,請選擇你偏好的語言。兩條學習路線講授相同的 SDK 概念,並公開完全一致的 HTTP 介面規格。

元件 .NET 學習路線 Python 學習路線
執行階段 .NET 10 LTS Python 3.11+ (uv)
AI SDK GitHub Copilot SDK v1.0.9 github-copilot-sdk v1.0.9
後端 ASP.NET Core Web API FastAPI
前端 Blazor WebAssembly 靜態 HTML + 原生 JS
資料庫 SQLite + EF Core SQLite + SQLModel
模型資料存取 MCP (ModelContextProtocol) MCP (mcp)
測試 xUnit (26) pytest (30)
程式碼品質檢查 Roslyn 分析器 Ruff
5050 API / 5051 UI 5070 (API + UI)
共用項目 技術
CI/CD GitHub Actions
安全性 CodeQL、自訂代理程式

🚀 快速開始

先決條件

執行專案 — .NET

dotnet restore src/AgentOrchestrator/AgentHQDemo.slnx
dotnet build   src/AgentOrchestrator/AgentHQDemo.slnx

# Terminal 1 — API (SQLite DB auto-created and seeded on first run)
dotnet run --project src/AgentOrchestrator/AgentHQDemo.Api --urls "http://localhost:5050"

# Terminal 2 — Blazor UI
dotnet run --project src/AgentOrchestrator/AgentHQDemo.Web --urls "http://localhost:5051"

然後開啟 http://localhost:5051。API 在連接埠 5050 執行。

執行專案 — Python

cd src/AgentOrchestrator-python
uv sync

# One server for both the API and the UI
uv run uvicorn app.main:app --port 5070

然後開啟 http://localhost:5070

兩套技術堆疊刻意使用不同的連接埠,因此可以同時執行。

GitHub Codespaces

  1. 按一下 Code在 main 分支上建立 codespace
  2. 等待環境設定完成(約 2 分鐘)
  3. 執行你所選學習路線對應的命令

Copilot CLI 二進位檔案

Copilot SDK 會在建置期間從 registry.npmjs.org 下載相符的 CLI 二進位檔案。如果該套件登錄站不可存取(例如使用企業代理或電腦離線),建置將失敗並顯示 MSB3923Directory.Build.props 會在偵測到全域安裝的 Copilot CLI 時重複使用它,從而避開此問題:

npm install -g @github/copilot

如有需要,可覆蓋或停用此偵測:

dotnet build -p:CopilotCliBinaryPath=/path/to/copilot   # use a specific binary
dotnet build -p:CopilotUseLocalCli=false                # always download

📡 API 端點

端點 方法 說明
/api/chat/stream POST 串流聊天(SSE)
/api/chat/models GET 可用 AI 模型(從 Copilot CLI 即時取得)
/api/chat/health GET 執行狀況檢查
/api/transactions GET/POST 列出或新增交易
/api/transactions/{id} GET/DELETE 依 ID 取得交易
/api/segments GET 客戶分群
/api/segments/{id} GET 分群詳細資料
/api/segments/predict/{customerId} GET 預測客戶分群

呼叫範例

# Stream a chat response
curl -N -X POST http://localhost:5050/api/chat/stream \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Which segment has the lowest retention?", "model": "claude-haiku-4.5"}'

# List transactions (10 seed records)
curl http://localhost:5050/api/transactions

# Predict customer segment
curl http://localhost:5050/api/segments/predict/C003
# → {"customerId":"C003","predictedSegment":"High Value","confidence":0.89,...}

🎯 可用模型

模型選擇器在執行階段透過 GET /api/chat/models 填入;該端點會詢問 Copilot CLI,確定已已登入帳號實際可用的模型。具體清單因帳號而異,並會隨時間變化;範例包括 claude-haiku-4.5(預設)、autoclaude-sonnet-*claude-opus-*gpt-5.*gemini-*

如果 API 無法存取 Copilot CLI,API 和使用者介面都會回復到一個精簡的靜態清單,以確保示範仍能正常呈現。

🏗️ 架構

graph TB
    subgraph "Frontend — Port 5051"
        UI[Blazor WebAssembly<br/>Batched Rendering]
    end

    subgraph "Backend — Port 5050"
        API[ASP.NET Core API]
        Chat[ChatController<br/>SSE Streaming]
        Txn[TransactionsController]
        Seg[SegmentsController]
        SDK[Copilot SDK<br/>Connection Recovery]
        SVC[RetailAnalyticsService]
        DB[(SQLite<br/>Auto-seeded)]
    end

    UI -->|SSE Stream| Chat
    UI -->|REST| Txn
    UI -->|REST| Seg
    Chat --> SDK
    Txn --> SVC
    Seg --> SVC
    SVC --> DB
    SDK --> Models[Claude / GPT / Gemini]

📂 專案結構

.
├── .devcontainer/              # Codespaces configuration
├── .github/
│   ├── agents/                 # Custom Copilot agents
│   ├── hooks/                  # Governance + audit hooks
│   ├── prompts/                # Reusable prompts
│   ├── skills/                 # Copilot skills
│   ├── workflows/              # CI, CodeQL, setup
│   ├── copilot-instructions.md # Coding standards for all agents
│   └── copilot-review-instructions.md
├── .vscode/mcp.json            # MS Learn MCP server
├── docs/                       # Labs, walkthroughs, and reference material
├── img/                        # Session branding
├── src/
│   ├── AgentOrchestrator/          # .NET implementation
│   │   ├── AgentHQDemo.Api/        # Web API — chat, transactions, segments
│   │   ├── AgentHQDemo.McpServer/  # Read-only MCP server over retail.db
│   │   ├── AgentHQDemo.Web/        # Blazor WebAssembly UI
│   │   ├── samples/SdkLabs/        # Runnable lab samples
│   │   ├── tests/                  # xUnit tests (26)
│   │   └── AgentHQDemo.slnx        # Solution
│   └── AgentOrchestrator-python/   # Python implementation
│       ├── app/                    # FastAPI — routers, services, models, UI
│       ├── mcp_server/             # Read-only MCP server over retail.db
│       ├── sdk_labs/               # Runnable lab samples
│       ├── tests/                  # pytest tests (30)
│       └── pyproject.toml          # uv project
├── AGENTS.md                   # Guidelines for AI agents
└── Directory.Build.props       # Copilot CLI resolution

🗄️ 種子資料

首次啟動時會自動建立 SQLite 資料庫,其中包含 10 條交易,涵蓋 5 位客戶(C001–C005)、4 個類別和 4 家門市,此外還包括:

分群 客戶數 平均消費額 留存率
高價值客群 150 $850 92%
一般客群 3,200 $180 78%
流失風險客群 890 $95 45%
新客群 420 $120 65%

🤖 自訂代理程式

代理程式 用途 專長
dotnet-reviewer .NET 程式碼檢閱 安全性、效能和最佳做法
security-scanner 漏洞偵測 OWASP 十大風險、注入風險
pr-summary PR 說明文件 情境感知說明

📋 示範教材

完整文件位於 docs/,並按學習路線分組:

學習路線 實作 示範
.NET 七個 Copilot SDK 實作練習(約 2 小時)— 從 實作 01 程式碼導覽,介紹 src/AgentOrchestrator/ 中的程式碼
Python 相同的七個實作練習 — 從 實作 01 程式碼導覽,介紹 src/AgentOrchestrator-python/ 中的程式碼

請選擇 一條 學習路線,而不是兩條都做;它們講授相同的內容。

不屬於任一語言學習路線的內容均位於 專題

分組 內容
參考資料 架構自訂代理程式掛鉤技能疑難排解
延伸實作 兩條學習路線共用的 Copilot CLI 實作練習 — 自訂代理程式治理掛鉤

🔐 安全說明

此示範 有意 包含存在缺陷的程式碼模式,以便在程式碼檢閱和靜態分析示範期間現場發現這些問題:

缺陷 .NET Python
N+1 查詢(效能檢閱) GetTransactionsWithSegmentsAsync get_transactions_with_segments
缺少 null 檢查(靜態分析) GetTransactionAsync get_transaction
缺少輸入驗證(安全性檢閱) AddTransactionAsync add_transaction
硬編碼門檻值(程式碼異味) PredictSegmentAsync predict_segment

兩種實作都包含相同的四項缺陷,因此同一份解答適用於任一學習路線。

相比之下,聊天功能的資料庫存取 並不是 上述缺陷之一。兩條學習路線都透過只讀 MCP 伺服器向模型公開 retail.dbAgentHQDemo.McpServer / mcp_server/),此伺服器使用 Mode=ReadOnly 開啟 SQLite,並發布五個特定領域工具,而不是通用查詢工具。REST API 仍保留直接 ORM 存取權限;MCP 面向模型,並非用於應用程式存取自己的資料庫。

解決這些問題之前,請勿用於生產環境。 請參閱 SECURITY.md

CodeQL 說明: 儲存庫為私人儲存庫時會跳過分析,因為程式碼掃描需要 GitHub Advanced Security。如果儲存庫轉為公開,分析會自動執行;也可以設定儲存庫變數 ENABLE_CODEQL=true

🤝 參與貢獻

請參閱 AGENTS.md 瞭解儲存庫指南, CODE_OF_CONDUCT.md 瞭解社群規範,以及 SUPPORT.md 瞭解如何取得幫助。

📄 授權條款


使用 GitHub Copilot SDK 以 ❤️ 建置