Chuyển đến nội dung chính

Bài 5: Agent Mode — Để AI tự viết code cho bạn

Agent là gì, cách Agent hoạt động (plan → execute → verify), Agent Loop, Chat view (Ctrl+Cmd+I), so sánh Agent vs Ask vs Plan mode. Permission levels: Default, Bypass Approvals, Autopilot. Hands-on: xây dựng web app đầu tiên với Agent.

💻 Lập trình — Bài 5 Bài 5: Agent Mode — Để AI tự viết code cho bạn

Vibe Coding với GitHub Copilot: Từ Cơ bản đến Nâng cao

Phần 2: Agent Mode — AI tự động viết code

xdev.asia

1. Agent là gì?

Trong GitHub Copilot, một Agent là trợ lý AI hoạt động tự chủ (autonomously) để hoàn thành một task lập trình hoàn chỉnh. Khác với inline suggestions chỉ gợi ý vài dòng, Agent có khả năng:

  • 📋 Lập kế hoạch (break down task thành steps)
  • 📝 Tạo và chỉnh sửa nhiều files cùng lúc
  • 💻 Chạy terminal commands (install packages, build, test)
  • 🔄 Tự sửa lỗi khi gặp error (self-correct)
  • 🔧 Sử dụng tools (read files, search, web, extensions)

Đây chính là nền tảng của Vibe Coding thực thụ — bạn mô tả yêu cầu, Agent thực hiện toàn bộ.

2. Agent Loop — Cách Agent hoạt động

┌─────────────────────────────────────────────────┐
│              AGENT LOOP                          │
├─────────────────────────────────────────────────┤
│                                                  │
│  User Prompt: "Build a REST API for blog posts"  │
│           ↓                                      │
│  ┌─── PLAN ───┐                                  │
│  │ 1. Setup project                              │
│  │ 2. Create models                              │
│  │ 3. Create routes                              │
│  │ 4. Add middleware                             │
│  │ 5. Test                                       │
│  └────────────┘                                  │
│           ↓                                      │
│  ┌─── EXECUTE ──┐                                │
│  │ Create files  │ ←─ Tool: createFile           │
│  │ Write code    │ ←─ Tool: editFile             │
│  │ Run commands  │ ←─ Tool: runInTerminal        │
│  └──────────────┘                                │
│           ↓                                      │
│  ┌─── VERIFY ───┐                                │
│  │ Check errors  │ ←─ Tool: getErrors            │
│  │ Run tests     │ ←─ Tool: runInTerminal        │
│  │ Self-correct  │ → Quay lại EXECUTE nếu fail   │
│  └──────────────┘                                │
│           ↓                                      │
│  ✅ Complete → User review                       │
│                                                  │
└─────────────────────────────────────────────────┘

3. Ba Built-in Agents

3.1. Agent (default)

Tự chủ plan và implement changes, tạo files, chạy commands, sử dụng tools. Đây là agent bạn dùng nhiều nhất cho Vibe Coding.

3.2. Plan

Tạo structured implementation plan nhưng không viết code. Sau khi plan OK, bạn hand off sang Agent để thực thi.

3.3. Ask

Trả lời câu hỏi về code, concepts, codebase mà không thay đổi files. Dùng khi cần hiểu trước khi code.

Chọn agent trong Chat view:

┌────────────────────────────┐
│  Agent ▼                   │  ← Click dropdown
├────────────────────────────┤
│  ● Agent    (implement)    │
│  ○ Plan     (plan only)    │
│  ○ Ask      (Q&A only)     │
│  ○ Reviewer (custom)       │
└────────────────────────────┘

4. Permission Levels — Kiểm soát quyền Agent

Agent cần chạy commands và thay đổi files — bạn quyết định mức autonomy:

Level Mô tả Phù hợp khi
Default Approvals Hỏi xác nhận cho write/run tools Lần đầu dùng, production code
Bypass Approvals Auto-approve tất cả tool calls Trusted tasks, prototype
Autopilot (Preview) Auto-approve + auto-respond questions Fully autonomous, side projects

⚠️ Lưu ý bảo mật: Ở level Autopilot, Agent có thể chạy bất kỳ command nào — chỉ dùng cho trusted projects trên local machine.

5. Hands-on: Xây dựng Web App với Agent Mode

Bước 1: Mở Chat View

Nhấn Ctrl+Cmd+I (macOS) hoặc Ctrl+Alt+I (Windows/Linux)

Bước 2: Chọn Agent mode

Từ dropdown, chọn "Agent"

Bước 3: Viết prompt

Create a modern expense tracker web application with:
- Add expenses with amount, category, and date
- View expenses in a table with sorting
- Dashboard with summary charts (total by category)
- Filter expenses by date range and category
- Local storage to persist data
- Modern dark theme UI with smooth animations
- Responsive design for mobile

Use vanilla HTML, CSS, and JavaScript. No frameworks needed.

Bước 4: Quan sát Agent làm việc

Agent sẽ:

  1. Phân tích requirements
  2. Tạo file structure: index.html, styles.css, app.js
  3. Viết HTML semantic structure
  4. Viết CSS với dark theme và responsive
  5. Viết JavaScript cho logic CRUD, charts, filters
  6. Có thể chạy preview

Bước 5: Review và Accept

Xem diff cho mỗi file → nhấn "Keep" để accept, hoặc request changes.

Bước 6: Iterate

Tiếp tục conversation để thêm features:

Add an export to CSV button and a monthly budget feature with progress bar

6. Agent Session Management

Mỗi task chạy trong một session riêng biệt:

  • Sessions List: xem tất cả sessions (active, paused, completed) trong Chat panel
  • Multiple sessions: chạy nhiều sessions song song cho nhiều tasks khác nhau
  • Resume session: quay lại session cũ để tiếp tục iterate
  • Review changes: xem tất cả file changes trong một session

7. Tools mà Agent sử dụng

Agent có quyền truy cập các tools built-in:

Tool Chức năng
read Đọc files trong workspace
editFile Tạo/chỉnh sửa files
runInTerminal Chạy shell commands
search Tìm kiếm trong codebase
listDir Liệt kê files trong thư mục
getErrors Lấy compile/lint errors
web Tìm kiếm trên web
usages Tìm references của symbol

8. Best Practices cho Agent Mode

✅ Nên:

  • Mô tả rõ ràng, chi tiết: include tech stack, patterns, constraints
  • Chia nhỏ tasks lớn: "Add auth" trước, "Add CRUD" sau, thay vì "Build everything"
  • Review từng step: đọc code Agent sinh ra, đặc biệt logic quan trọng
  • Dùng /init trước: tạo custom instructions để Agent hiểu conventions
  • Iterate, không redo: tiếp tục session thay vì bắt đầu lại

❌ Không nên:

  • Dùng Autopilot cho production code
  • Accept all mà không review bất kỳ file nào
  • Prompt quá mơ hồ: "Make it better"
  • Để Agent install packages mà bạn không biết
  • Skip error messages — đọc và cung cấp cho Agent

9. Debugging với Agent Mode

Agent đặc biệt mạnh cho debugging vì nó có thể:

  1. Đọc error message
  2. Trace root cause qua nhiều files
  3. Apply fix
  4. Re-run test để verify
// Prompt ví dụ:
The test in tests/auth.test.ts is failing with "TypeError: Cannot read properties
of undefined (reading 'token')". Find the root cause and fix it.

10. Tổng kết

Concept Key Takeaway
Agent AI assistant tự chủ: plan → execute → verify
3 built-in agents Agent (implement), Plan (plan), Ask (Q&A)
Permission levels Default → Bypass → Autopilot (tăng dần autonomy)
Agent Loop Lặp lại execute + verify cho đến khi task hoàn thành
Sessions Mỗi task = 1 session, có thể chạy song song
Best practice Clear prompt + review code + iterate

Bài tiếp theo sẽ đi sâu vào Plan Agent — kỹ thuật lập kế hoạch trước khi code, giúp bạn kiểm soát tốt hơn output của AI.