Thực hành
25 phút
Bài 5/12

Copilot Chat - Đối thoại với AI

Sử dụng Copilot Chat để explain code, debug, refactor và generate code qua conversation

Copilot Chat - Đối thoại với AI

1. Giới thiệu Copilot Chat

Copilot Chat là chat interface trong VS Code cho phép bạn "nói chuyện" với AI về code. Khác với autocomplete, Chat cho phép:

  • Hỏi đáp về code
  • Debug với context
  • Refactor với instructions cụ thể
  • Generate code blocks dài

Cách mở Copilot Chat

MethodShortcut
Chat Panel (sidebar)Ctrl+Alt+I
Inline ChatCtrl+I
Quick ChatCtrl+Shift+I

2. Chat Panel vs Inline Chat

Chat Panel (Sidebar)

  • Persistent conversation history
  • Tốt cho complex discussions
  • Có thể reference multiple files

Inline Chat

  • Appears ngay trong editor
  • Quick edits cho selected code
  • Changes apply trực tiếp

Khi nào dùng cái nào?

ScenarioUse
Explain code blockInline Chat
Fix specific bugInline Chat
Discuss architectureChat Panel
Generate new fileChat Panel
Quick refactorInline Chat
Learn conceptChat Panel

3. Slash Commands

/explain - Giải thích code

Text
1/explain
2
3# Select code first, then use /explain
4# Copilot sẽ giải thích step by step

Example:

Python
1# Select this code:
2result = [x**2 for x in range(10) if x % 2 == 0]
3
4# Ask: /explain
5# Copilot: "This is a list comprehension that..."

/fix - Sửa lỗi

Text
1/fix The function returns None instead of the expected value

Example:

Python
1def get_max(numbers):
2 max_val = numbers[0]
3 for n in numbers:
4 if n > max_val:
5 max_val = n
6 # Bug: forgot to return!
7
8# /fix returns None
9# Copilot adds: return max_val

/tests - Generate tests

Text
1/tests Generate unit tests for this function using pytest

Example:

Python
1def add(a, b):
2 return a + b
3
4# /tests
5# Copilot generates:
6def test_add_positive():
7 assert add(2, 3) == 5
8
9def test_add_negative():
10 assert add(-1, -1) == -2

/doc - Generate documentation

Text
1/doc Generate detailed docstring with examples

/simplify - Đơn giản hóa code

Text
1/simplify Make this code more readable

4. Context Participants

@workspace - Project-wide context

Text
1@workspace What authentication method is used in this project?
2@workspace Find all TODO comments
3@workspace How is the database connected?

@vscode - VS Code settings/features

Text
1@vscode How to change keyboard shortcuts?
2@vscode What extensions are installed?

@terminal - Terminal commands

Text
1@terminal How to run pytest with coverage?
2@terminal Git command to undo last commit

5. Chat Patterns hiệu quả

5.1 Explain with Context

Text
1/explain
2What does this regex do and give me examples of strings it matches?

5.2 Debug with Error

Text
1I'm getting this error:

TypeError: 'NoneType' object is not subscriptable

Text
1The code is:
2```python
3data = get_user_data(user_id)
4name = data['name'] # Error here

What's wrong and how to fix it?

Text
1### 5.3 Refactor with Requirements

Refactor this code to:

  1. Use async/await instead of callbacks
  2. Add proper error handling
  3. Add type hints
  4. Follow PEP 8 style guide
Text
1### 5.4 Generate with Specifications

Create a Python class called CacheManager with:

  • LRU cache with configurable max size
  • Methods: get(key), set(key, value), delete(key), clear()
  • Automatic expiration after TTL seconds
  • Thread-safe operations
  • Logging for cache hits/misses
Text
1---
2
3## 6. Multi-turn Conversations
4
5Copilot Chat nhớ context trong conversation. Bạn có thể build on previous messages:
6
7### Example conversation
8
9**You:** Create a User class with name and email
10
11**Copilot:**
12```python
13class User:
14 def __init__(self, name: str, email: str):
15 self.name = name
16 self.email = email

You: Add email validation

Copilot:

Python
1import re
2
3class User:
4 def __init__(self, name: str, email: str):
5 self.name = name
6 self.email = self._validate_email(email)
7
8 def _validate_email(self, email: str) -> str:
9 pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
10 if not re.match(pattern, email):
11 raise ValueError("Invalid email format")
12 return email

You: Add a method to convert to dictionary

Copilot: Adds to_dict() method...


7. Inline Chat Workflows

Workflow 1: Quick Fix

  1. Select problematic code
  2. Press Ctrl+I
  3. Type: "fix the bug" or describe issue
  4. Review changes
  5. Accept or Reject

Workflow 2: Add Feature

  1. Select function
  2. Ctrl+I
  3. "Add caching with 5 minute TTL"
  4. Review
  5. Accept

Workflow 3: Improve Code

  1. Select code block
  2. Ctrl+I
  3. "Make this more efficient" or "Add error handling"
  4. Review
  5. Accept

8. Tips for Better Chat Responses

Be Specific

❌ "Fix this code"

✅ "Fix the IndexError when the list is empty"

Provide Context

❌ "Write a function to process data"

✅ "Write a function to process JSON data from the /api/users endpoint, extracting name and email fields"

Use Examples

❌ "Parse the date"

✅ "Parse dates in format 'DD/MM/YYYY' like '25/12/2024'"

Specify Output Format

❌ "Explain this"

✅ "Explain this in simple terms with a code example"


9. Hands-on Exercise

Challenge: Debug Session với Copilot Chat

Đây là code có bugs. Sử dụng Copilot Chat để tìm và fix:

Python
1def calculate_statistics(numbers):
2 """Calculate mean, median, and mode of a list of numbers."""
3
4 # Calculate mean
5 mean = sum(numbers) / len(numbers)
6
7 # Calculate median
8 sorted_nums = numbers.sort()
9 n = len(sorted_nums)
10 if n % 2 == 0:
11 median = (sorted_nums[n//2] + sorted_nums[n//2 - 1]) / 2
12 else:
13 median = sorted_nums[n//2]
14
15 # Calculate mode
16 frequency = {}
17 for num in numbers:
18 frequency[num] = frequency.get(num, 0) + 1
19 mode = max(frequency, key=frequency.values)
20
21 return {
22 'mean': mean,
23 'median': median,
24 'mode': mode
25 }
26
27# Test
28result = calculate_statistics([1, 2, 2, 3, 4, 4, 4, 5])
29print(result)

Instructions

  1. Copy code vào VS Code
  2. Run và observe errors
  3. Select code → Open Copilot Chat
  4. Ask: "Find and fix all bugs in this code"
  5. Apply fixes
  6. Verify với test case

Bugs to find (spoiler)

Click để xem bugs
  1. numbers.sort() returns None, should use sorted(numbers)
  2. sorted_nums is None so indexing fails
  3. frequency.values should be frequency.values()
  4. Original list is modified by sort()

Expected Output

Python
1{'mean': 3.125, 'median': 3.5, 'mode': 4}

10. Bonus: Chat Settings

Customize Chat Behavior

In VS Code Settings (Ctrl+,):

JSON
1{
2 // Response language
3 "github.copilot.chat.localeOverride": "vi",
4
5 // Welcome message
6 "github.copilot.chat.welcomeMessage": "enabled",
7
8 // Code suggestions in chat
9 "github.copilot.chat.runCommand.enabled": true
10}

Tiếp theo

Bài tiếp theo: Agent Mode - để Copilot tự động thực hiện các task phức tạp như edit nhiều files, chạy commands, và tự fix errors!