AI2023-09-28

Prompt Engineering With GitHub Copilot

Unlock the power of GitHub Copilot for prompt engineering. Learn how to boost productivity and code efficiency with expert guidance. Dive in now!
Prompt Engineering With GitHub Copilot

GitHub Copilot lives in the environment of an Integrated Development Environment (IDE), such as Visual Studio Code (VS Code), pulling relevant information swiftly and efficiently. In the fast-paced environment of software development, every millisecond counts.

Hence, GitHub Copilot is designed to quickly identify the language in use, file names, and other metadata to avoid syntax-related errors.

Additionally, GitHub Copilot is capable of utilizing context from the entire repository, especially when working with interconnected classes or functions.

Crafting compelling and effective prompts is essential when using GitHub Copilot. The ability to communicate your intentions clearly can enhance your software development process, making it more streamlined and efficient.

In this article, we’ll delve deeper into the art of prompt engineering with GitHub Copilot, providing insights that will help you better engage with the tool and maximize your productivity.

GitHub Copilot: Quick Overview

Before diving into specifics, it's crucial to paint a clear picture of your overarching goal. This is akin to giving GitHub Copilot the 'why' behind the 'what.' Without context, even the best AI pair programmer can falter. GitHub Copilot thrives on clear instructions. It’s essential to keep your descriptions detailed yet concise. 

What is GitHub Copilot

For instance, when you're developing a markdown editor using Next.js, a detailed comment specifying your goals helps GitHub Copilot understand what you're trying to achieve. This might include the intended features, the state for markdown, how the users will interact with the application, etc. The more explicit you are with your instructions, the more tailored the code GitHub Copilot generates will be.

For more detailed information on the functionalities and capabilities of GitHub Copilot, you may refer to this comprehensive guide by Hatica here. Similarly, for insights into other AI-based coding assistance tools such as Amazon CodeGuru, also known as CodeWhisperer, this Hatica article provides a worthwhile read.

Creating Effective Prompts With Copilot

After setting the context, it's time to guide GitHub Copilot's AI powered capabilities to accomplish the task. This process resembles crafting a recipe, where you break down the entire process into smaller, manageable steps. It's not about writing a verbose paragraph describing the end product, but more about articulating the path leading to it.

To get the most out of GitHub Copilot, let it generate code after each step. This approach allows you to review, modify, or accept the code before moving to the next instruction. This step-by-step guidance can ensure the AI stays on the right path, improving the overall efficiency of your programming session.

Just like humans, AI benefits significantly from examples. By providing a sample of what you want, you give GitHub Copilot a clearer vision of your goal. For instance, if you wish to extract specific data from an array, showing an example of the desired outcome can guide GitHub Copilot more effectively.

However, not providing an example might lead to errors or inefficiencies. On the other hand, a clear example can not only prevent such issues but also bring you closer to your desired outcome. It's a simple yet highly effective practice that can enhance the quality of the output.

In the realm of machine learning, we use terms like zero-shot learning, one-shot learning, and few-shot learning to describe how an AI model is trained:

Zero-shot learning involves exposing the model to new scenarios without specific training examples. The model makes predictions based on its training, much like an unsupervised child learning from their surroundings.

One-shot learning is when the model learns from a very limited number of examples. It's as if we've given some initial guidance and are now letting it explore on its own.

Few-shot learning, on the other hand, can be thought of as meticulous training. The model is provided with a few examples and trained to achieve high precision. It's akin to being taught in a highly controlled environment where every step is monitored and corrected.

In the case of GitHub Copilot, it's a bit of each. It uses zero-shot learning to generate code without explicit instruction, one-shot learning to adapt to user styles with minimal examples, and few-shot learning to refine its predictions over time, based on more extensive user interaction.

Consider this comparison:

Without specific guidance, Prompt:

#Fetch the current date and time in Python

from datetime import datetime
current_datetime = datetime.now()
print(current_datetime)

Here, GitHub Copilot correctly suggests a basic method to fetch the current date and time in Python. But we might need the date in a specific format or timezone.

With specific guidance,

Prompt

#Fetch the current date in 'YYYY-MM-DD' format and in 'UTC' timezone.

from datetime import datetime
import pytz
utc = pytz.UTC
current_datetime = datetime.now()
current_datetime = utc.localize(current_datetime)
print(current_datetime.isoformat())

With an example and more specific instructions, GitHub Copilot correctly suggests a method to fetch the current date and time in the required format and timezone. This makes the result more refined and suitable for our specific use case.

Optimizing Codebase With Copilot

Another significant use case for GitHub Copilot is optimizing code for performance. Imagine you've written a function to find a product by its ID in a product array:

function findProductById(id) {
  for(let i = 0; i < products.length; i++) {
    if(products[i].id === id) {
      return products[i];
    }
  }
  return null;
}

While this function works, it's not the most efficient. Ask Copilot to optimize it, and you might get this:

function findProductById(id) {
  return products.find(product => product.id === id) || null;
}

Here, Copilot replaces the for loop with the Array.prototype.find method, which is faster and more idiomatic in JavaScript.

Prompts For Effective Documentation

Perhaps one of the most tedious tasks in software development is writing thorough and accurate documentation. Luckily, Copilot can assist with this as well. Give it a function, and it can generate a detailed explanation of what the function does, its parameters, return type, and even examples of use.

Given this JavaScript function:

function add(x, y) {
  return x + y;
}

Copilot might generate the following documentation:

/**
* This function adds two numbers.
* @param {number} x - The first number.
* @param {number} y - The second number.
* @returns {number} The sum of x and y.
*
* @example
* add(1, 2);  // returns 3
* add(-1, 1);  // returns 0
*/
function add(x, y) {
  return x + y;
}

This feature is incredibly handy, ensuring that your code is not only functional but also clear and accessible to others. 

Prompt

/*
Build a basic Note-Taking App using React with the following features:
- Use react hooks
- Create state for the note with default text "Type your note here"
- A text area where users can input their notes
- The note text should be saved in the component's state and updated in real time
*/

GitHub Copilot prompt for creating a note-taking app

This prompt will guide GitHub Copilot to create a simple note-taking app where a user can input their notes, and their input is saved and updated in real-time in the component's state. This task is simpler since it doesn't require markdown parsing and rendering or the use of an external npm package.

Pro Tips: GitHub Copilot Labs

GitHub Copilot Labs is a complementary tool to the GitHub Copilot extension, enhancing it with unique features aimed at improving developers' experiences.

Screenshot of GitHub Copilot Labs

Copilot Labs, accessible via a sidebar in VS Code, currently offers two distinct features: "explain this code" and "translate this code." These capabilities prove invaluable in various scenarios.

One crucial application is in acquainting oneself with a new codebase. The task, often daunting and time-consuming, can be significantly eased by having Copilot Labs explain individual blocks of code. Likewise, when developers source solutions from resources like StackOverflow, Copilot Labs assists in understanding the copied code's workings. It's also an excellent tool for developers studying for exams or interviews, offering additional context for specific algorithms and data structures.

Copilot Labs also aids in mentoring, translating code snippets into familiar languages, and helping mentors provide relevant guidance even outside their primary tech stack. This tool brings clarity, not only about how code works but also why it works - an essential understanding for new developers.

Bottom Line: Crafting Effective Prompts With Copilot

From simplifying code explanations, translations, debugging, and refactoring to creating tests GitHub's Copilot is an assistant that offers invaluable support in daily tasks. But like any tool, it's not a replacement for a developer's insight and intuition, and it's important to always double-check the output it produces.

It's also worth noting that the output may still be non-deterministic. While we can guide the AI toward our desired outcome, we must understand that it might interpret our instructions differently. This is not a flaw, but a characteristic of AI, which adds an element of unpredictability and potential for creative solutions.

Subscribe to Hatica's blog

Get bi-weekly insights straight to your inbox

Share this article:
Table of Contents
  • GitHub Copilot: Quick Overview
  • Creating Effective Prompts With Copilot
  • Optimizing Codebase With Copilot
  • Prompts For Effective Documentation
  • Pro Tips: GitHub Copilot Labs
  • Bottom Line: Crafting Effective Prompts With Copilot

Ready to dive in? Start your free trial today

Overview dashboard from Hatica