copilot-cli-for-beginners

Chapter 04: Agents and Custom Instructions

如果你能用一個工具,雇用 Python 程式碼審查員、測試專家和安全性審查員……會怎樣?

在第三章中,你已經掌握了基本的工作流程:程式碼審查、重構、除錯、測試產生,以及 git 整合。這些讓你能高效運用 GitHub Copilot CLI。現在,讓我們更進一步。

到目前為止,你一直把 Copilot CLI 當作通用型助手來使用。Agent 讓你能賦予它特定角色與內建標準,例如:強制型別標註與 PEP 8 的程式碼審查員,或是會撰寫 pytest 測試案例的測試助手。你將看到,同樣的提示詞,交給具備專屬指令的 agent 處理,結果會明顯更好。

🎯 學習目標

完成本章後,你將能夠:

⏱️ 預估時間:約 55 分鐘(20 分鐘閱讀 + 35 分鐘實作)


🧩 真實世界類比:雇用專家

當你需要修繕房子時,你不會只叫一個「通用幫手」。你會找專家:

問題 專家 為什麼
水管漏水 水電工 熟悉水管規範,擁有專業工具
重新配線 電工 了解安全規範,符合法規
換新屋頂 屋頂工 熟悉材料、在地氣候考量

Agent 的運作方式也是如此。與其使用通用型 AI,不如用專注於特定任務、懂得正確流程的 agent。只要設定一次指令,之後每次需要該專業時都能重複使用:程式碼審查、測試、安全、文件。

Hiring Specialists Analogy - Just as you call specialized tradespeople for house repairs, AI agents are specialized for specific tasks like code review, testing, security, and documentation


使用 Agent

立即開始使用內建與自訂 agent。


第一次接觸 Agent? 從這裡開始!

從沒用過或建立過 agent?這裡有你入門本課程所需的一切。

  1. 立刻試用一個內建 agent:
    copilot
    > /plan Add input validation for book year in the book app
    

    這會啟動 Plan agent,產生逐步實作計畫。

  2. 看看我們的自訂 agent 範例: 定義 agent 指令很簡單,參考我們提供的 python-reviewer.agent.md 檔案即可了解模式。

  3. 理解核心概念: Agent 就像諮詢專家而非通才。「前端 agent」會自動專注於無障礙與元件模式,你不必每次都提醒,因為這已經寫在 agent 的指令裡了。

內建 Agent

你在第三章開發流程中已經用過部分內建 agent!
/plan/review 其實就是內建 agent。現在你知道底層發生了什麼。完整清單如下:

Agent 如何啟動 功能說明
Plan /planShift+Tab(切換模式) 在寫程式前產生逐步實作計畫
Code-review /review 審查已暫存/未暫存變更,給予聚焦且可執行的回饋
Init /init 產生專案設定檔(指令、agent)
Explore 自動 當你請 Copilot 探索或分析程式庫時內部使用
Task 自動 執行測試、建置、靜態檢查、安裝相依套件等指令


內建 agent 實際運作範例 - 示範如何啟動 Plan、Code-review、Explore 與 Task

copilot

# 啟動 Plan agent 產生實作計畫
> /plan Add input validation for book year in the book app

# 啟動 Code-review agent 審查你的變更
> /review

# Explore 與 Task agent 會在相關時自動啟動:
> Run the test suite        # 使用 Task agent

> Explore how book data is loaded    # 使用 Explore agent

那 Task Agent 呢?它在幕後協助管理、追蹤執行狀況,並以清楚的格式回報:

結果 你會看到什麼
成功 簡短摘要(例如:「247 項測試全部通過」、「建置成功」)
失敗 完整輸出(包含堆疊追蹤、編譯錯誤、詳細日誌)

📚 官方文件GitHub Copilot CLI Agents


將 Agent 加入 Copilot CLI

你可以輕鬆定義自己的 agent,納入工作流程!只要定義一次,隨時指揮調度!

Four colorful AI robots standing together, each with different tools representing specialized agent capabilities

🗂️ 新增你的 agent

Agent 檔案是副檔名為 .agent.md 的 markdown 檔案。分為兩部分:YAML frontmatter(中繼資料)與 markdown 指令內容。

💡 不熟 YAML frontmatter? 它是檔案頂部、被 --- 包圍的一小段設定。YAML 就是 key: value 配對。其餘內容是一般 markdown。

以下是一個最小範例:

---
name: my-reviewer
description: Code reviewer focused on bugs and security issues
---

# Code Reviewer

You are a code reviewer focused on finding bugs and security issues.

When reviewing code, always check for:
- SQL injection vulnerabilities
- Missing error handling
- Hardcoded secrets

💡 必填與選填description 欄位為必填。其他如 nametoolsmodel 為選填。

Agent 檔案放哪裡

位置 作用範圍 適用情境
.github/agents/ 專案專屬 團隊共用、符合專案慣例的 agent
~/.copilot/agents/ 全域(所有專案) 你個人常用的 agent

本專案已在 .github/agents/ 資料夾內附上範例 agent 檔案。你可以自行撰寫,或修改現有檔案。

📂 查看本課程的範例 agent
檔案 說明
hello-world.agent.md 最小範例-從這裡開始
python-reviewer.agent.md Python 程式碼品質審查員
pytest-helper.agent.md Pytest 測試專家
# 或複製到你的個人 agent 資料夾(所有專案都可用)
cp .github/agents/python-reviewer.agent.md ~/.copilot/agents/

更多社群 agent,請見 github/awesome-copilot

🚀 使用自訂 agent 的兩種方式

互動模式

在互動模式下,使用 /agent 列出 agent 並選擇要合作的 agent。 選擇 agent 後即可繼續對話。

copilot
> /agent

若要切換到其他 agent,或回到預設模式,再次使用 /agent 指令即可。

程式化模式

直接用 agent 啟動新會話。

copilot --agent python-reviewer
> Review @samples/book-app-project/books.py

💡 切換 agent:你可隨時用 /agent--agent 切換 agent。若要回到標準 Copilot CLI 體驗,使用 /agent 並選擇無 agent


更深入運用 Agent

Robot being assembled on a workbench surrounded by components and tools representing custom agent creation

💡 本節為進階選讀。 內建 agent(/plan/review)已足夠應付多數工作流程。當你需要跨專案一致應用的專業知識時,再建立自訂 agent。

以下主題各自獨立。挑你有興趣的閱讀,不必一次看完。

我想要… 跳到
看看 agent 為何優於一般提示詞 專家 vs 通用
在一個功能上結合多個 agent 多 agent 協作
組織、命名與分享 agent 組織與分享 agent
設定專案常駐情境 Copilot 專案設定
查詢 YAML 屬性與工具 Agent 檔案參考

選擇下方情境展開細節。


專家 vs 通用:看見差異-為什麼 agent 產生的結果比一般提示詞更好

專家 vs 通用:看見差異

這正是 agent 價值所在。來看看差異:

沒有 Agent(通用 Copilot)

copilot

> Add a function to search books by year range in the book app

通用輸出

def search_by_year_range(books, start_year, end_year):
    results = []
    for book in books:
        if book['year'] >= start_year and book['year'] <= end_year:
            results.append(book)
    return results

很基本,可以用,但缺漏很多。


使用 Python Reviewer Agent

copilot

> /agent
# 選擇 "python-reviewer"

> Add a function to search books by year range in the book app

專家輸出

from typing import List, Dict, Any

def search_by_year_range(
    books: List[Dict[str, Any]],
    start_year: int,
    end_year: int
) -> List[Dict[str, Any]]:
    """
    Search for books within a specified year range.

    Args:
        books: List of book dictionaries
        start_year: Starting year (inclusive)
        end_year: Ending year (inclusive)

    Returns:
        List of books published within the year range

    Raises:
        ValueError: If start_year is greater than end_year
        TypeError: If year values are not integers
    """
    if not isinstance(start_year, int) or not isinstance(end_year, int):
        raise TypeError("Year values must be integers")

    if start_year > end_year:
        raise ValueError(f"Start year ({start_year}) cannot be greater than end year ({end_year})")

    return [
        book for book in books
        if isinstance(book.get('year'), int)
        and start_year <= book['year'] <= end_year
    ]

python-reviewer agent 自動包含:

差異:同樣的提示,產出卻大不相同。agent 補足你可能遺漏的專業細節。


多 agent 協作-結合專家、會話中切換、agent 當工具

多 agent 協作

真正的威力在於多位專家協作完成一個功能。

範例:打造一個簡單功能

copilot

> I want to add a "search by year range" feature to the book app

# 用 python-reviewer 設計
> /agent
# 選擇 "python-reviewer"

> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach?

# 切換到 pytest-helper 設計測試
> /agent
# 選擇 "pytest-helper"

> @samples/book-app-project/tests/test_books.py Design test cases for a find_by_year_range method.
> What edge cases should we cover?

# 綜合設計
> Create an implementation plan that includes the method implementation and comprehensive tests.

重點:你是總設計師,指揮專家。他們處理細節,你掌握全局。

🎬 實際操作影片! ![Python Reviewer Demo](/04-agents-custom-instructions/images/python-reviewer-demo.gif) *實際輸出會依模型、工具、回應而異,與此處示意不同。*

Agent 當工具

當 agent 已設定好,Copilot 也能在複雜任務中自動呼叫它們作為工具。若你要求全端功能,Copilot 可能自動將部分工作分派給合適的專家 agent。


組織與分享 agent-命名、檔案放置、指令檔、團隊共用

組織與分享 agent

命名你的 agent

建立 agent 檔案時,名稱很重要。這是你在 /agent--agent 後要輸入的,也是團隊成員在 agent 清單中看到的。

✅ 好名稱 ❌ 避免
frontend my-agent
backend-api agent1
security-reviewer helper
react-specialist code
python-backend assistant

命名慣例:


與團隊分享

將 agent 檔案放在 .github/agents/,就會納入版本控制。推送到 repo,所有團隊成員自動取得。但 agent 只是 Copilot 會讀取的其中一種檔案。它也支援指令檔,這類檔案會自動套用到每個會話,無需手動執行 /agent

換個角度想:agent 是你隨選的專家,指令檔則是團隊規則,永遠生效。

檔案放哪裡

你已知道兩個主要位置(見上方 Agent 檔案放哪裡)。用這個決策樹選擇:

Decision tree for where to put agent files: experimenting → current folder, team use → .github/agents/, everywhere → ~/.copilot/agents/

從簡單開始: 先在專案資料夾建立一個 *.agent.md。滿意後再移到正式位置。

除了 agent 檔案,Copilot 也會自動讀取專案層級指令檔,無需 /agent。詳見下方 Copilot 專案設定 介紹 AGENTS.md.instructions.md/init


Copilot 專案設定-AGENTS.md、指令檔與 /init 設定

Copilot 專案設定

Agent 是你隨選的專家。專案設定檔則不同:Copilot 會在每次會話自動讀取,了解你的專案慣例、技術棧與規則。沒有人需要執行 /agent,情境對所有協作者都自動生效。

用 /init 快速設定

最快的方式是讓 Copilot 幫你產生設定檔:

copilot
> /init

Copilot 會掃描專案並產生量身打造的指令檔。你可以事後編輯。

指令檔格式

檔案 作用範圍 備註
AGENTS.md 專案根目錄或子目錄 跨平台標準-Copilot 與其他 AI 助手皆支援
.github/copilot-instructions.md 專案 GitHub Copilot 專用
.github/instructions/*.instructions.md 專案 更細緻、主題式指令
CLAUDE.md, GEMINI.md 專案根目錄 相容性支援

🎯 剛開始?AGENTS.md 寫專案指令。其他格式可視需求再探索。

AGENTS.md

AGENTS.md 是推薦格式。開放標準,可跨 Copilot 與其他 AI 工具使用。放在 repo 根目錄,Copilot 會自動讀取。本專案的 AGENTS.md 就是實例。

一般 AGENTS.md 會描述專案情境、程式風格、安全需求、測試標準。可用 /init 產生,或參考我們的範例自行撰寫。

自訂指令檔(.instructions.md)

想更細緻控管,可將指令拆成主題式檔案。每個檔案聚焦一個重點,自動生效:

.github/
└── instructions/
    ├── python-standards.instructions.md
    ├── security-checklist.instructions.md
    └── api-design.instructions.md

💡 注意:指令檔支援任何語言。此例用 Python 配合課程專案,你也可為 TypeScript、Go、Rust 或任何技術建立類似檔案。

尋找社群指令檔:瀏覽 github/awesome-copilot 取得 .NET、Angular、Azure、Python、Docker 等多種現成指令檔。

關閉自訂指令

若需讓 Copilot 忽略所有專案設定(除錯或比對行為時很有用):

copilot --no-custom-instructions

Agent 檔案參考-YAML 屬性、工具別名、完整範例

Agent 檔案參考

更完整的範例

你已看過最小 agent 格式。以下是一個更完整、使用 tools 屬性的 agent。建立 ~/.copilot/agents/python-reviewer.agent.md

---
name: python-reviewer
description: Python code quality specialist for reviewing Python projects
tools: ["read", "edit", "search", "execute"]
---

# Python Code Reviewer

You are a Python specialist focused on code quality and best practices.

**Your focus areas:**
- Code quality (PEP 8, type hints, docstrings)
- Performance optimization (list comprehensions, generators)
- Error handling (proper exception handling)
- Maintainability (DRY principles, clear naming)

**Code style requirements:**
- Use Python 3.10+ features (dataclasses, type hints, pattern matching)
- Follow PEP 8 naming conventions
- Use context managers for file I/O
- All functions must have type hints and docstrings

**When reviewing code, always check:**
- Missing type hints on function signatures
- Mutable default arguments
- Proper error handling (no bare except)
- Input validation completeness

YAML 屬性

屬性 必填 說明
name 顯示名稱(預設為檔名)
description agent 功能說明-協助 Copilot 理解何時建議使用
tools 可用工具清單(省略=全部可用)。見下方工具別名。
target 限定 vscodegithub-copilot 專用

工具別名

tools 清單中可用這些名稱:

📖 官方文件自訂 agent 設定

⚠️ 僅限 VS Codemodel 屬性(選擇 AI 模型)僅支援於 VS Code,不支援 GitHub Copilot CLI。你可放心納入跨平台 agent 檔案,Copilot CLI 會自動忽略。

更多 agent 範本

💡 初學者注意:下方範例為範本。請將特定技術換成你的專案所用技術。 重要的是 agent 的結構,不是提到的技術名稱。

本專案於 .github/agents/ 夾內附有可用範例:

社群 agent 請見 github/awesome-copilot


練習

Warm desk setup with monitor showing code, lamp, coffee cup, and headphones ready for hands-on practice

建立你自己的 agent,實際體驗他們的威力。


▶️ 自己動手試試


# 建立 agents 資料夾(若尚未存在)
mkdir -p .github/agents

# 建立程式碼審查 agent
cat > .github/agents/reviewer.agent.md << 'EOF'
---
name: reviewer
description: Senior code reviewer focused on security and best practices
---

# Code Reviewer Agent

You are a senior code reviewer focused on code quality.

**Review priorities:**
1. Security vulnerabilities
2. Performance issues
3. Maintainability concerns
4. Best practice violations

**Output format:**
Provide issues as a numbered list with severity tags:
[CRITICAL], [HIGH], [MEDIUM], [LOW]
EOF

# 建立文件撰寫 agent
cat > .github/agents/documentor.agent.md << 'EOF'
---
name: documentor
description: Technical writer for clear and complete documentation
---

# Documentation Agent

You are a technical writer who creates clear documentation.

**Documentation standards:**
- Start with a one-sentence summary
- Include usage examples
- Document parameters and return values
- Note any gotchas or limitations
EOF

# 現在開始使用
copilot --agent reviewer
> Review @samples/book-app-project/books.py

# 或切換 agent
copilot
> /agent
# 選擇 "documentor"
> Document @samples/book-app-project/books.py

📝 作業

主要挑戰:打造專業 agent 團隊

實作範例已建立 reviewerdocumentor agent。現在請練習建立並運用 agent 處理另一項任務-提升書籍應用程式的資料驗證:

  1. 建立 3 個針對書籍應用程式的 agent 檔案(.agent.md),每個 agent 一個,放在 .github/agents/
  2. 你的 agent:
    • data-validator:檢查 data.json 是否有缺漏或格式錯誤資料(作者為空、year=0、缺欄位)
    • error-handler:審查 Python 程式碼的錯誤處理是否一致,並建議統一做法
    • doc-writer:產生或更新 docstring 與 README 內容
  3. 針對書籍應用程式運用每個 agent:
    • data-validator → 稽核 @samples/book-app-project/data.json
    • error-handler → 審查 @samples/book-app-project/books.py@samples/book-app-project/utils.py
    • doc-writer → 為 @samples/book-app-project/books.py 增加 docstring
  4. 協作:先用 error-handler 找出錯誤處理缺口,再用 doc-writer 記錄改進後的做法

成功標準:你有 3 個可用 agent,能產生一致且高品質的結果,並能用 /agent 在它們之間切換。

💡 提示(點擊展開)

起手範本:每個 agent 建立一個檔案於 .github/agents/

data-validator.agent.md:

---
description: Analyzes JSON data files for missing or malformed entries
---

You analyze JSON data files for missing or malformed entries.

**Focus areas:**
- Empty or missing author fields
- Invalid years (year=0, future years, negative years)
- Missing required fields (title, author, year, read)
- Duplicate entries

error-handler.agent.md:

---
description: Reviews Python code for error handling consistency
---

You review Python code for error handling consistency.

```**標準:**
- 不可使用裸露的 except 子句
- 適當時請使用自訂例外
- 所有檔案操作皆使用 context manager
- 成功/失敗時回傳型別需一致

doc-writer.agent.md:

---
description: 技術寫手,撰寫清晰的 Python 文件
---

你是一位技術寫手,負責撰寫清晰的 Python 文件。

**標準:**
- 採用 Google 風格的 docstring
- 包含參數型別與回傳值
- 為公開方法加入使用範例
- 註明會拋出的例外

測試你的 Agent:

💡 注意: 你應該已經在本地的這個 repo 裡有 samples/book-app-project/data.json。如果缺少,請從原始 repo 下載: data.json

copilot
> /agent
# 從清單中選擇 "data-validator"
> @samples/book-app-project/data.json 檢查書籍中作者欄位為空或年份無效的項目

提示: YAML frontmatter 中的 description 欄位是 Agent 正常運作的必要條件。

加分挑戰:指令庫

你已經建立了可隨選呼叫的 Agent。現在來試試另一種方式:指令檔,Copilot 會在每次對話自動讀取,無需 /agent

建立 .github/instructions/ 資料夾,並新增至少 3 個指令檔:

在書籍應用程式的程式碼上測試每個指令檔。


🔧 常見錯誤與疑難排解(點擊展開)

常見錯誤

錯誤 會發生什麼 修正方式
Agent frontmatter 缺少 description Agent 無法載入或無法被發現 一定要在 YAML frontmatter 中加入 description:
Agent 檔案放錯位置 使用時找不到 Agent 請放在 ~/.copilot/agents/(個人)或 .github/agents/(專案)
使用 .md 而非 .agent.md 可能無法識別為 Agent 檔案名稱應為 python-reviewer.agent.md 這類格式
Agent 提示過長 可能超過 30,000 字元限制 保持 Agent 定義精簡,詳細指令請用 Skill 實現

疑難排解

找不到 Agent — 請確認 Agent 檔案存在於下列其中一個位置:

列出所有可用 Agent:

copilot
> /agent
# 顯示所有可用的 Agent

Agent 沒有遵循指令 — 請在提示中明確說明,並在 Agent 定義中加入更多細節:

自訂指令未載入 — 在專案中執行 /init 以設定專案專屬指令:

copilot
> /init

或檢查是否被停用:

# 如果要載入自訂指令,請勿使用 --no-custom-instructions
copilot  # 預設會載入自訂指令

摘要

🔑 重點整理

  1. 內建 Agent/plan/review 需直接呼叫;Explore 與 Task 會自動運作
  2. 自訂 Agent 是在 .agent.md 檔案中定義的專家角色
  3. 優秀的 Agent 具備明確專業、標準與輸出格式
  4. 多 Agent 協作 可結合專業解決複雜問題
  5. 指令檔.instructions.md)可將團隊標準自動化套用
  6. 一致的輸出 來自明確定義的 Agent 指令

📋 快速參考:完整指令與捷徑請參閱 GitHub Copilot CLI 指令參考


➡️ 下一步

Agent 會改變 Copilot 處理與執行目標行動 的方式。接下來你將學習 Skill —— 這會改變 Copilot 採取哪些步驟。想知道 Agent 與 Skill 有何不同?第 05 章會直接說明。

第 05 章:Skills 系統,你將學到:


← 回到第 03 章 繼續前往第 05 章 →