Lý thuyết
30 phút
Bài 6/12

Agent Mode - Copilot Tự Động

Sử dụng Copilot Agent để tự động edit nhiều files, chạy commands, và fix errors

Agent Mode - Copilot Tự Động

1. Agent Mode là gì?

Agent Mode (còn gọi là Copilot Edits) là tính năng nâng cao cho phép Copilot:

  • ✅ Edit nhiều files cùng lúc
  • Tạo files mới trong project
  • Chạy terminal commands
  • Tự động fix khi có lỗi
  • ✅ Thực hiện complex tasks end-to-end

So sánh các modes

FeatureAutocompleteChatAgent
Single file edit
Multi-file edit⚠️ Limited
Create new files
Run commands
Auto-fix errors
Complex refactoring⚠️

2. Kích hoạt Agent Mode

Cách 1: Từ Chat Panel

  1. Mở Copilot Chat (Ctrl+Alt+I)
  2. Ở góc trên, chọn dropdown "Chat"
  3. Chuyển sang "Edits" hoặc "Agent"

Cách 2: Command Palette

  1. Ctrl+Shift+P
  2. Tìm "Copilot: Start Agent Session"

Cách 3: Keyboard Shortcut

  • Ctrl+Shift+Alt+I - Mở trực tiếp Agent mode

3. Agent Mode Workflow

Agent Mode Flow


4. Use Cases cho Agent Mode

4.1 Scaffold New Features

Text
1Create a new REST API endpoint for user profile:
2- File: src/routes/profile.py
3- GET /profile - Get current user profile
4- PUT /profile - Update profile
5- Add proper validation
6- Add tests in tests/test_profile.py

Agent sẽ:

  • Tạo file profile.py
  • Implement endpoints
  • Tạo file test
  • Update routes/__init__.py để register

4.2 Refactor Across Files

Text
1Refactor the authentication system:
2- Move auth logic from routes/users.py to services/auth_service.py
3- Create AuthService class with login(), logout(), refresh_token() methods
4- Update all files that import from routes/users.py
5- Update tests accordingly

4.3 Add Feature to Existing Codebase

Text
1Add dark mode support to the React app:
2- Create ThemeContext with light/dark modes
3- Add toggle component
4- Update all components to use theme colors
5- Persist preference in localStorage

4.4 Fix Bugs Across Multiple Files

Text
1Fix the session timeout bug:
2- The session expires after 5 minutes instead of 30
3- Check config files
4- Check middleware
5- Check frontend timeout settings
6- Fix all related files

5. Working with Agent Mode

Adding Context

Trong Agent mode, bạn có thể add files vào context:

Text
1Add these files to context:
2- src/models/user.py
3- src/services/email_service.py
4- src/routes/auth.py
5
6Now, add email verification to the registration flow

Reviewing Changes

Agent sẽ show diff cho mỗi file:

diff
1// src/models/user.py
2
3class User:
4 def __init__(self, name, email):
5 self.name = name
6 self.email = email
7+ self.email_verified = False
8+ self.verification_token = None

Options:

  • Accept - Apply changes
  • Reject - Discard changes
  • Edit - Modify before accepting

Iterating

Sau khi review, bạn có thể yêu cầu thêm:

Text
1Good, but also:
2- Add expiration time for verification token
3- Send welcome email after verification

6. Terminal Integration

Agent có thể chạy terminal commands:

Example: Setup Project

Text
1Set up a new Python project:
2- Create virtual environment
3- Install dependencies: flask, pytest, black
4- Create requirements.txt
5- Run initial tests

Agent sẽ chạy:

Bash
1python -m venv venv
2source venv/bin/activate # or venv\Scripts\activate on Windows
3pip install flask pytest black
4pip freeze > requirements.txt
5pytest

Auto-fix After Commands

Nếu command fail, Agent có thể:

  1. Analyze error
  2. Suggest fix
  3. Re-run command

7. Best Practices

DO ✅

  1. Be specific about scope

    Text
    1Update ONLY the UserService class, don't touch other files
  2. Provide context

    Text
    1This is a Flask app using SQLAlchemy.
    2Database models are in src/models/
  3. Review carefully

    • Agent có thể miss edge cases
    • Check logic, not just syntax
  4. Iterate in small steps

    Text
    1First: Add the model
    2Then: Add the route
    3Finally: Add tests

DON'T ❌

  1. Don't blindly accept all

    • Luôn review diff trước khi accept
  2. Don't give conflicting instructions

    Text
    1# Bad
    2Create a simple function, also make it handle all edge cases
    3and be production-ready with full logging
  3. Don't skip the plan review

    • Agent shows plan trước khi execute
    • Review plan để catch issues sớm

8. Agent Mode Limitations

Current Limitations

  • ⚠️ May not understand complex business logic
  • ⚠️ Can make mistakes with imports
  • ⚠️ Sometimes creates circular dependencies
  • ⚠️ May not follow project conventions perfectly

How to Handle

  1. Provide conventions explicitly

    Text
    1Follow these conventions:
    2- Use snake_case for functions
    3- Use PascalCase for classes
    4- Put all imports at top
  2. Review generated code

    • Run linter
    • Run tests
    • Manual review

9. Hands-on Exercise

Challenge: Build Todo API với Agent Mode

Sử dụng Agent Mode để tạo một Todo API hoàn chỉnh:

Prompt:

Text
1Create a complete Todo API with Flask:
2
3Structure:
4- src/
5 - models/
6 - todo.py (Todo model with SQLAlchemy)
7 - routes/
8 - todos.py (CRUD endpoints)
9 - services/
10 - todo_service.py (Business logic)
11 - app.py (Main Flask app)
12- tests/
13 - test_todos.py
14
15Requirements:
16- Todo fields: id, title, description, completed, created_at, due_date
17- Endpoints: GET /todos, POST /todos, GET /todos/<id>, PUT /todos/<id>, DELETE /todos/<id>
18- Filter by completed status: GET /todos?completed=true
19- Proper error handling with 404 for not found
20- Input validation
21
22Create all files with working code.

Steps

  1. Open Agent Mode (Ctrl+Shift+Alt+I)
  2. Paste the prompt above
  3. Review the plan Agent provides
  4. Accept to execute
  5. Review each file's changes
  6. Test the API:
    Bash
    1pip install flask flask-sqlalchemy
    2python src/app.py
  7. Iterate nếu cần fix bugs

Expected Files

Text
1project/
2├── src/
3│ ├── __init__.py
4│ ├── app.py
5│ ├── models/
6│ │ ├── __init__.py
7│ │ └── todo.py
8│ ├── routes/
9│ │ ├── __init__.py
10│ │ └── todos.py
11│ └── services/
12│ ├── __init__.py
13│ └── todo_service.py
14└── tests/
15 ├── __init__.py
16 └── test_todos.py

10. What's New in Agent Mode

Recent Updates (2024-2025)

  • Workspace awareness: Better understanding of project structure
  • Improved planning: Shows detailed plan before execution
  • Better error recovery: Auto-retry with fixes
  • Terminal integration: Run commands and check output
  • Multi-turn improvements: Better memory of previous changes

Coming Soon

  • Image understanding (Copilot Vision)
  • Voice commands
  • Integration with GitHub Issues/PRs

Tiếp theo

Bài tiếp theo: Code Review với Copilot - sử dụng Copilot để review code quality, security, và best practices!