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
| Method | Shortcut |
|---|---|
| Chat Panel (sidebar) | Ctrl+Alt+I |
| Inline Chat | Ctrl+I |
| Quick Chat | Ctrl+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?
| Scenario | Use |
|---|---|
| Explain code block | Inline Chat |
| Fix specific bug | Inline Chat |
| Discuss architecture | Chat Panel |
| Generate new file | Chat Panel |
| Quick refactor | Inline Chat |
| Learn concept | Chat Panel |
3. Slash Commands
/explain - Giải thích code
1/explain2 3# Select code first, then use /explain4# Copilot sẽ giải thích step by stepExample:
1# Select this code:2result = [x**2 for x in range(10) if x % 2 == 0]34# Ask: /explain5# Copilot: "This is a list comprehension that..."/fix - Sửa lỗi
1/fix The function returns None instead of the expected valueExample:
1def get_max(numbers):2 max_val = numbers[0]3 for n in numbers:4 if n > max_val:5 max_val = n6 # Bug: forgot to return!78# /fix returns None9# Copilot adds: return max_val/tests - Generate tests
1/tests Generate unit tests for this function using pytestExample:
1def add(a, b):2 return a + b34# /tests5# Copilot generates:6def test_add_positive():7 assert add(2, 3) == 589def test_add_negative():10 assert add(-1, -1) == -2/doc - Generate documentation
1/doc Generate detailed docstring with examples/simplify - Đơn giản hóa code
1/simplify Make this code more readable4. Context Participants
@workspace - Project-wide context
1@workspace What authentication method is used in this project?2@workspace Find all TODO comments3@workspace How is the database connected?@vscode - VS Code settings/features
1@vscode How to change keyboard shortcuts?2@vscode What extensions are installed?@terminal - Terminal commands
1@terminal How to run pytest with coverage?2@terminal Git command to undo last commit5. Chat Patterns hiệu quả
5.1 Explain with Context
1/explain 2What does this regex do and give me examples of strings it matches?5.2 Debug with Error
1I'm getting this error:TypeError: 'NoneType' object is not subscriptable
1The code is:2```python3data = get_user_data(user_id)4name = data['name'] # Error hereWhat's wrong and how to fix it?
1### 5.3 Refactor with RequirementsRefactor this code to:
- Use async/await instead of callbacks
- Add proper error handling
- Add type hints
- Follow PEP 8 style guide
1### 5.4 Generate with SpecificationsCreate 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
1---2 3## 6. Multi-turn Conversations4 5Copilot Chat nhớ context trong conversation. Bạn có thể build on previous messages:6 7### Example conversation8 9**You:** Create a User class with name and email10 11**Copilot:** 12```python13class User:14 def __init__(self, name: str, email: str):15 self.name = name16 self.email = emailYou: Add email validation
Copilot:
1import re23class User:4 def __init__(self, name: str, email: str):5 self.name = name6 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 emailYou: Add a method to convert to dictionary
Copilot: Adds to_dict() method...
7. Inline Chat Workflows
Workflow 1: Quick Fix
- Select problematic code
- Press
Ctrl+I - Type: "fix the bug" or describe issue
- Review changes
- Accept or Reject
Workflow 2: Add Feature
- Select function
Ctrl+I- "Add caching with 5 minute TTL"
- Review
- Accept
Workflow 3: Improve Code
- Select code block
Ctrl+I- "Make this more efficient" or "Add error handling"
- Review
- 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:
1def calculate_statistics(numbers):2 """Calculate mean, median, and mode of a list of numbers."""3 4 # Calculate mean5 mean = sum(numbers) / len(numbers)6 7 # Calculate median8 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]) / 212 else:13 median = sorted_nums[n//2]14 15 # Calculate mode16 frequency = {}17 for num in numbers:18 frequency[num] = frequency.get(num, 0) + 119 mode = max(frequency, key=frequency.values)20 21 return {22 'mean': mean,23 'median': median,24 'mode': mode25 }2627# Test28result = calculate_statistics([1, 2, 2, 3, 4, 4, 4, 5])29print(result)Instructions
- Copy code vào VS Code
- Run và observe errors
- Select code → Open Copilot Chat
- Ask: "Find and fix all bugs in this code"
- Apply fixes
- Verify với test case
Bugs to find (spoiler)
Click để xem bugs
numbers.sort()returnsNone, should usesorted(numbers)sorted_numsisNoneso indexing failsfrequency.valuesshould befrequency.values()- Original list is modified by
sort()
Expected Output
1{'mean': 3.125, 'median': 3.5, 'mode': 4}10. Bonus: Chat Settings
Customize Chat Behavior
In VS Code Settings (Ctrl+,):
1{2 // Response language3 "github.copilot.chat.localeOverride": "vi",4 5 // Welcome message6 "github.copilot.chat.welcomeMessage": "enabled",7 8 // Code suggestions in chat9 "github.copilot.chat.runCommand.enabled": true10}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!
