GitHub Copilot - Introduction
Overview
Estimated time: 30โ40 minutes
GitHub Copilot is Microsoft's AI-powered coding assistant that provides real-time code suggestions, completions, and explanations. This tutorial covers installation, basic features, and effective usage patterns.
Learning Objectives
- Install and configure GitHub Copilot in your preferred editor
- Understand how to write effective prompts and comments
- Use basic code generation and completion features
- Apply best practices for AI-assisted development
Prerequisites
- AI Agents - Introduction
- VS Code, JetBrains IDE, Neovim, or Sublime Text installed
- GitHub account with Copilot subscription
What is GitHub Copilot?
GitHub Copilot is an AI pair programmer that helps you write code faster and with less effort. It's powered by OpenAI Codex and trained on billions of lines of public code.
Key Features:
- Real-time code suggestions as you type
- Multi-line code completion
- Natural language to code conversion
- Code explanation and documentation
- Multiple programming languages supported
Installation & Setup
VS Code Setup
# 1. Install the GitHub Copilot extension
# Open VS Code โ Extensions โ Search "GitHub Copilot" โ Install
# 2. Sign in to GitHub
# Command Palette (Ctrl+Shift+P) โ "GitHub Copilot: Sign In"
# 3. Verify installation
# Look for Copilot icon in status bar
JetBrains IDEs Setup
# 1. Install plugin
# File โ Settings โ Plugins โ Search "GitHub Copilot" โ Install
# 2. Restart IDE and sign in
# Tools โ GitHub Copilot โ Login to GitHub
# 3. Configure settings
# File โ Settings โ Tools โ GitHub Copilot
Configuration Options
{
"github.copilot.enable": {
"*": true,
"yaml": false,
"plaintext": false
},
"github.copilot.inlineSuggest.enable": true,
"github.copilot.advanced": {
"secret_key": "your-key-here",
"length": 500
}
}
Basic Usage
Code Completion
Start typing and Copilot will suggest completions in gray text:
// Type this comment
// Function to calculate fibonacci sequence
// Copilot suggests:
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Natural Language Prompts
# Create a function that validates email addresses
def validate_email(email):
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
# Parse JSON and handle errors gracefully
def safe_json_parse(json_string):
try:
return json.loads(json_string), None
except json.JSONDecodeError as e:
return None, str(e)
Multi-line Suggestions
# Generate a REST API endpoint for user management
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/users', methods=['GET'])
def get_users():
# Copilot suggests complete implementation
users = database.get_all_users()
return jsonify([{
'id': user.id,
'name': user.name,
'email': user.email
} for user in users])
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
user = database.create_user(
name=data['name'],
email=data['email']
)
return jsonify({'id': user.id}), 201
Keyboard Shortcuts
VS Code Shortcuts
- Tab - Accept suggestion
- Esc - Dismiss suggestion
- Alt + ] - Next suggestion
- Alt + [ - Previous suggestion
- Ctrl + Enter - Open Copilot panel
JetBrains Shortcuts
- Tab - Accept suggestion
- Esc - Dismiss suggestion
- Alt + \ - Trigger suggestion
- Alt + Enter - Show actions
- Ctrl + Shift + A - Copilot commands
Effective Prompting Techniques
Be Specific and Descriptive
# โ Poor prompt
# Sort function
# โ
Good prompt
# Function to sort a list of dictionaries by a specified key in ascending order
def sort_dict_list(dict_list, key):
return sorted(dict_list, key=lambda x: x[key])
Provide Context
// User authentication system using JWT tokens
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
// Middleware to verify JWT token and extract user info
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
Use Examples
# Function to format currency
# Example: format_currency(1234.56, 'USD') โ '$1,234.56'
# Example: format_currency(1000, 'EUR') โ 'โฌ1,000.00'
def format_currency(amount, currency_code):
import locale
currency_symbols = {
'USD': '$', 'EUR': 'โฌ', 'GBP': 'ยฃ',
'JPY': 'ยฅ', 'CNY': 'ยฅ'
}
symbol = currency_symbols.get(currency_code, currency_code)
formatted = f"{amount:,.2f}"
return f"{symbol}{formatted}"
Best Practices
Code Quality
- Always review suggestions before accepting
- Test generated code thoroughly
- Understand the logic - don't blindly accept
- Refactor when needed to match your code style
Security Considerations
- Review for vulnerabilities - AI may suggest insecure patterns
- Don't commit secrets - Copilot may suggest placeholder keys
- Validate input handling - Check for injection vulnerabilities
- Follow security guidelines for your language/framework
Productivity Tips
- Write clear comments to guide code generation
- Break complex tasks into smaller, specific requests
- Use multiple suggestions to explore different approaches
- Combine with traditional coding - it's a tool, not a replacement
Common Use Cases
Boilerplate Generation
# Django model for blog post with common fields
from django.db import models
from django.contrib.auth.models import User
class BlogPost(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published = models.BooleanField(default=False)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
Test Generation
# Test cases for the fibonacci function
import unittest
class TestFibonacci(unittest.TestCase):
def test_fibonacci_base_cases(self):
self.assertEqual(fibonacci(0), 0)
self.assertEqual(fibonacci(1), 1)
def test_fibonacci_small_numbers(self):
self.assertEqual(fibonacci(2), 1)
self.assertEqual(fibonacci(3), 2)
self.assertEqual(fibonacci(4), 3)
def test_fibonacci_larger_numbers(self):
self.assertEqual(fibonacci(10), 55)
self.assertEqual(fibonacci(15), 610)
Common Pitfalls
- Over-reliance: Don't let Copilot think for you - understand the code
- Context confusion: Copilot may suggest code inconsistent with your codebase
- Outdated patterns: AI training data may include deprecated practices
- License concerns: Be aware of potential licensing issues with generated code
Checks for Understanding
- What keyboard shortcut accepts a Copilot suggestion in VS Code?
- How should you write comments to get better code suggestions?
- What security considerations should you keep in mind when using Copilot?
Show answers
- Tab key accepts the current suggestion
- Be specific, descriptive, and provide context and examples
- Review for vulnerabilities, don't commit secrets, validate input handling
Exercises
- Install GitHub Copilot in your preferred editor and complete the setup
- Write a comment describing a function you need, then let Copilot generate it
- Create a simple class with Copilot's help, then generate unit tests for it
- Practice using different prompting techniques and compare the results