Prompt Engineering Tips with GitHub Copilot
Last Updated :
13 May, 2024
GitHub Copilot, powered by OpenAI, is changing the game in software development. It's not just a tool for suggesting code. GitHub Copilot can grasp the crucial details of your project through its training of data containing both natural language and billions of lines of source code from publicly available sources, including code in public GitHub repositories. This allows GitHub Copilot to provide you with more context-aware suggestions.
But to get the most out of GitHub Copilot, you need to know about prompting. This is the way you tell Copilot what you need. The quality of the code it gives back depends a lot on how clear and accurate your prompts are.
So how can you use GitHub Copilot to its full potential? This article will show you how! It guides you through the details of making effective prompts to get the best code suggestions, helping you code faster and better.
What is Prompt Engineering?
Prompt engineering is the process of creating clear instructions to guide AI systems, like GitHub Copilot, to generate context-appropriate code according to your project's specific needs. This ensures the code is syntactically, functionally, and contextually correct. Think of it like giving precise directions to a driver. Without them, the journey might be inefficient. But with clear guidance, the route becomes direct and efficient, saving time and energy. In this scenario, you're the one providing directions, and GitHub Copilot is your skilled driver, ready to drive you smoothly through your coding journey with the right guidance.
Now that you know what prompt engineering is, let's learn about some of its principles.
Principles of Prompt Engineering
Before we explore specific strategies, let's first understand the basic principles of prompt engineering, summed up in the 4 S's below. These core rules are the basis for creating effective prompts.
- Single: Always focus your prompt on a single, well-defined task or question. This clarity is crucial for eliciting accurate and useful responses from Copilot.
- Specific: Ensure that your instructions are explicit and detailed. Specificity leads to more applicable and precise code suggestions.
- Short: While being specific, keep prompts concise and to the point. This balance ensures clarity without overloading Copilot or complicating the interaction.
- Surround: Utilize descriptive filenames and keep related files open. This provides Copilot with rich context, leading to more tailored code suggestions.
Best practices in prompt engineering
- Understand your problem: Clearly define a problem that you are trying to solve. As Copilot is associated with code generation, it’s up to you to guide it in the right direction.
- Provide Clear Context: Give Copilot as much context as possible by writing clear comments and providing descriptive functions and variable names.
- Review and Refine: After providing as much context as possible it generates the output but it is to be considered as the starting point and then choose the way to review and refine it again to meet our required standards if required.
- Teach Copilot: If Copilot suggests something incorrect, take the time to correct it. This helps improve its suggestions for future use.
- Use with Caution: It generates code but goes ahead without any understanding and choosing a blind move over the generated code is not useful because it generally saves our time but choosing a way to understand it and correct it on your own.
- Pair Programming: Collaborate with Copilot like the collaboration with a human teammate. In general, discuss with each other and learn from each other.
- Test Extensively: Just like any code thoroughly test the code in the sense that every time check the code it generates and check the behaviour of it.
- Stay Legal: Ensure that you have the right to use any code it generates.
- Feedback Loop: Provide Feedback to GitHub about Copilot’s performance. This helps to improve its suggestions and provide the best result.
- Learn Continuously: Use Copilot as a learning tool. Analyze its suggestions to understand the different approaches and solutions to common programming problems.
How Copilot Learns from your Prompts?
GitHub Copilot operates based on AI models trained on vast amounts of data. To enhance its understanding of specific code contexts, engineers often provide it with examples. This practice, commonly found in machine learning, led to different training approaches such as:
Zero-shot learning
Here, GitHub Copilot generates code without any specific examples, relying solely on its foundational training. For instance, suppose you want to create a function to convert temperatures between Celsius and Fahrenheit. You can start by only writing a comment describing what you want, and Copilot might be able to generate the code for you, based on its previous training, without any other examples.
# I need a function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
One-shot learning
With this approach, a single example is given, aiding the model in generating a more context-aware response. Building upon the previous zero-shot example, you might provide an example of a temperature conversion function and then ask Copilot to create another similar function. Here's how it could look:
# Example: Function to convert Fahrenheit to Celsius
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit-32) * 5/9
return celsius
# Now I need a function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 9/5 + 32
return fahrenheit
Few-shot learning
In this method, Copilot is presented with several examples, which strike a balance between zero-shot unpredictability and the precision of fine-tuning. Let's say you want to generate code that sends you a greeting depending on the time of the day. Here's a few-shot version of that prompt:
# Example 1: Greeting message for morning
# Input: 9 AM
# Output: "Good morning!"
# Example 2: Greeting message for afternoon
# Input: 2 PM
# Output: "Good afternoon!"
# Example 3: Greeting message for evening
# Input : 7 PM
# Output : "Good evening!"
# Now, generate a python code that takes the current time as input using the datetime module
# and returns the appropriate greeting message
# Solution:
# Import datetime module
import datetime
# Get current time
current_time = datetime.datetime.now()
# Get current hour
current_hour = current_time.hour
# Check if it is morning (before 12 PM)
if current_hour < 12:
print("Good morning!")
# Check if it is afternoon (between 12 PM and 4 PM)
elif current_hour < 16:
print("Good afternoon!")
# Check if it is evening (after 4 PM)
elif current_hour < 21:
print("Good evening!")
# Else it is night time
else:
print("Good night!")
Let’s Consider a real-life Engineering problem:
Problem: You are developing a Web Application that requires user authentication. You need to implement a secure login system using JSON Web Tokens(JWT) in your Node.js backend.
Using GitHub Copilot:
1. Contextualize the Problem: In your Node.js codebase, create a new file named ‘auth.js’ where you will handle authentication-related functions.
2. Provide Contextual Comments: Add Comments explaining what you need, such as:
// Function to generate JWT Token for user authentication
3. Invoke GitHub Copilot: Start writing the function signature or comment describing what you need, like:
// Generate JWT token for user authentication
4. Review Copilot Suggestions: Copilot might suggest code like :
const jwt = require('jsonwebtoken
function generateToken(payload, secret, options) {
return jwt.sign(payload, secret, options);
}');
5. Refine the Suggestions: Ensure that the function meets your requirements and project conventions. To validate input parameters and handle errors:
const jwt = require('jsonwebtoken');
function generateToken(payload, secret, options) {
if(!payload || !secret) {
throw new Error('Payload and Secret are required');
}
return jwt.sign(payload, secret, options);
}
6. Test the Function: Write test cases to ensure the function works as expected, considering different scenarios like valid and invalid input, expired tokens, etc.
7. Feedback Loop: If Copilot’s suggestions are not accurate or if you encounter any issues, provide feedback so that Copilot can improve its suggestions as well accordingly.
8. Continuously Improve: As you work on your project, continue using Copilot for other authentication-related functions, such as token verification, token expiration handling, and refresh token generation.
Conclusion
By following these steps, we can effectively make the GitHub Copilot assist with implementing secure authentication in your Node.js backend, saving time and reducing the chance of errors.
Similar Reads
Getting Started With GitHub REST API
The GitHub REST API is a powerful tool that allows developers to interact with a list of features of GitHub. Whether you're automating tasks, building integrations, or simply managing your GitHub resources more efficiently, the REST API provides a versatile and accessible entry point. In this articl
5 min read
Customizing the Git prompt
Customizing your Git prompt can make your workflow much easier by showing important Git information right in your terminal. This guide will walk you through how to personalize your Git prompt, explain key terms, and answer common questions.Table of ContentWhat is Git Prompt?How to Customize Your Git
3 min read
How to Trigger WebHooks without Events - Probot Github App
Github is a cloud-based software development website that uses Git as version control. Github is the brand ambassador of open source software development and gives developers the ability to collaborate on software development and host the source code as well. The code is hosted as the content of a r
3 min read
How to Clone a Project From GitHub Using Eclipse?
Cloning a project from GitHub using Eclipse is a simple process that allows you to seamlessly integrate your development environment with your GitHub repositories. Whether you're collaborating on a team project or exploring open-source repositories, Eclipse provides a convenient way to clone and wor
2 min read
GitHub Copilot: Introduction, Features, Use Cases
GitHub Copilot is an AI-powered code assistant developed by GitHub in collaboration with OpenAI. In this article, weâll explore how to get started with GitHub Copilot, set it up in your environment, and see most of its features to enhance your coding workflow.Table of ContentKey Features of GitHub C
6 min read
What is GitHub CLI?
GitHub CLI (Command Line Interface) is a powerful tool developed by GitHub that allows developers to interact with GitHub directly from the terminal. It provides a simple way to perform many GitHub tasks without leaving the command line interface, such as managing repositories, handling pull request
7 min read
How to Authenticate Git Push with Github Using a Token?
Git is a powerful version control system used by developers to track changes in their codebase. GitHub, a platform built around Git, allows developers to collaborate on projects and manage repositories.For years, developers have been using their GitHub username and password to authenticate Git opera
4 min read
How to Install GitHub Copilot on VSCode?
GitHub Copilot is a revolutionary AI-powered code completion tool developed by GitHub and OpenAI. It can help you write code faster and more efficiently by suggesting entire lines or blocks of code as you type. If you're using Visual Studio Code (VSCode), installing GitHub Copilot can significantly
4 min read
Integrating Ansible with GitHub for CI/CD Pipelines
Many development teams face challenges when successfully combining several tools to form proper and effective CI/CD processes. An inefficient workflow means projects slow down, vary in their implementation, and have more overhead related to infrastructure management. Another consequence is that, due
8 min read
How to Trigger GitHub Action via API ?
GitHub Actions are like little assistants that help you automate tasks in your GitHub repositories. Imagine you have a bunch of repetitive tasks like testing your code, deploying it, or even sending notifications. Instead of doing these tasks manually every time, GitHub Actions can do them for you a
5 min read