QTM 350 - Data Science Computing

Lecture 12 - AI-Assisted Programming with GitHub Copilot

Danilo Freire

Emory University

09 October, 2024

Hello, everyone!
Hope all is well! 😊

A Nobel Prize for machine learning!

Geoffrey Hinton’s phone interview with the Nobel Prize Committee

Brief recap 📚

Last time, we discussed:

  • The impact of the Transformer architecture in natural language processing
  • How LLMs are trained, the role of self-attention, and the importance of pre-training
  • How LLMs are perhaps the ultimate high-level language, capable of generating code, text, images, and movies from a prompt
  • The limitations of LLMs, including the need for large amounts of data and computational resources, and the ethical dilemmas they raise (poorly paid workers, potential for misuse, bias, etc.)
  • The potential of LLMs to revolutionise and democratise programming, with tools like GitHub Copilot and OpenAI Codex

Last time, we discussed:

  • Despite their issues, LLMs can be very useful for generating code, especially for repetitive tasks, boilerplate code, and code snippets
  • How to improve the quality of code generated by LLMs, including using more specific prompts, providing more context, trying role-playing, and using the separators # and """ to delimit code blocks
  • How to install GitHub Copilot and use it in VS Code
  • Any problem installing GitHub Copilot?

Today’s plan 📅

Today, we will:

  • Discuss the pros and cons of AI-assisted programming with GitHub Copilot
  • Briefly compare it with other tools, such as TabNine, Kite, and IntelliCode
  • Learn how to install Copilot in the command line
  • Show some useful features of Copilot, including:
    • Code generation
    • Code explanations
    • Use of @ extensions for specific tasks (new feature!)
    • Optimisation or simplification of code
    • Run tests and examples

Copilot or not Copilot? 🤔

A short overview of existing AI coding tools

TabNine

  • TabNine: a code completion tool that uses a deep learning model to suggest code completions
  • It is a popular tool and one of the “oldest” in this category
  • Uses a proprietary model, fine-tuned on a large dataset of code, and can be used in many editors
  • It is not free, but it offers a free trial and it is cheaper than Copilot
  • In my view, it is only good for short completions and not as powerful as Copilot.
  • TabNine is surely more private and secure than Copilot: it does not send your code to the cloud
  • Unit tests are pretty good too!
  • TabNine vs. Copilot

A short overview of existing AI coding tools

Codeium

  • Codeium is another good tool for code completion
  • It is a free and open-source tool, and it is more private than Copilot
    • Yes, individual plans are free! 🎉
    • Pro plans start at $10/month and include GPT-4 and Claude Sonnet models
  • Codeium claims not to store or use your code for training purposes, which is also good for privacy
  • Also has a chatbot
  • In my experience, it works well and is on par with Copilot, if not a little better
  • VS Code extension here. Worth trying out 👍

A short overview of existing AI coding tools

Claude

  • Claude Sonnet is top-tier LLM, often better than ChatGPT and Copilot for many tasks
  • It is a paid service, free plan offers little
  • Cons: does not have access to the internet and it is not integrated into an IDE
  • Pros: it is very powerful and can generate code, text, and more. It also has a very cool feature called Artifacts that allows you to write and edit code together with the AI
  • It is my favourite tool for generating text

A short overview of existing AI coding tools

Claude Artifacts

A short overview of existing AI coding tools

Claude Artifacts

A short overview of existing AI coding tools

Cursor

  • Cursor is the new kid on the block
  • It is not only an LLM, but a whole editor (in fact, it’s a fork of VS Code)
    • So your extensions should work with it
  • It has the best code completion I’ve seen so far, and it includes a chatbot too
  • Cursor, like Codeium and Copilot, can scan your whole codebase and suggest improvements
  • It also has a “Privacy Mode” that does not send your code to the cloud
  • It’s paid, but it offers a (limited) free plan
    • 2000 completions per month
    • 1 workspace
    • 1 user

A short overview of existing AI coding tools

ChatGPT

  • This one needs no introduction 🤖
  • Works quite well for generating code, mainly in Python, JavaScript, and other popular languages (like Copilot)
  • Free tier and paid tiers available
  • They recently copied Claude’s Artifacts feature and called it Canvas
  • This is a huge improvement, as it allows you to write and edit code together with the AI
  • Try it out if you are a subscriber

A short overview of existing AI coding tools

ChatGPT

Installing GitHub Copilot in the command line 🖥️

Step 1: Install GitHub CLI

  • To use GitHub Copilot in the CLI, you need:
    • An active GitHub Copilot subscription
    • GitHub CLI installed
    • The Copilot CLI extension
  • MacOS and Linux users can install GitHub CLI with Homebrew:
brew install gh
  • Windows users can install GitHub CLI with Chocolatey:
choco install gh
gh extension install github/copilot-cli

Step 2: Authenticate with GitHub

  • To authenticate with GitHub, run:
gh auth login
  • Follow the instructions to authenticate with GitHub. Select GitHub.com
❯ gh auth login
? Where do you use GitHub?  [Use arrows to move, type to filter]
> GitHub.com
  Other
  • You will be asked to open a browser and authenticate with GitHub. Select HTTPS
❯ gh auth login
? Where do you use GitHub? GitHub.com
? What is your preferred protocol for Git operations on this host?  [Use arrows to move, type to filter]
> HTTPS
  SSH
? Authenticate Git with your GitHub credentials? (Y/n) Y
  • You will be asked to login
? How would you like to authenticate GitHub CLI?  [Use arrows to move, type to filter]
> Login with a web browser
  Paste an authentication token
  • Copy the code and press Enter to go to the browser. Press Continue, paste the code, and click on Authorize
! First copy your one-time code: 1111-AAAA
Press Enter to open github.com in your browser... 
  • If successful, you will see:
✓ Authentication complete.
- gh config set -h github.com git_protocol https
✓ Configured git protocol
✓ Logged in as danilofreire
  • And you’re done! 🎉

Step 3: Use Copilot in the CLI

gh extension install github/gh-copilot
  • And you should be ready to go! 🚀
  • GitHub Copilot in the CLI offers two primary commands
    • Explain Command: Use gh copilot explain followed by a command to get an explanation
    • Suggest Command: Use gh copilot suggest followed by a prompt to generate code
  • You can also create aliases for these commands. For example:
    • ghce for gh copilot explain
    • ghcs for gh copilot suggest
  • If you use zsh, you can just copy the commands below in your terminal:
echo 'eval "$(gh copilot alias -- zsh)"' >> ~/.zshrc && source ~/.zshrc
  • Or if you use bash:
echo 'eval "$(gh copilot alias -- bash)"' >> ~/.bashrc && source ~/.bashrc
  • Windows PowerShell users can use:
$GH_COPILOT_PROFILE = Join-Path -Path $(Split-Path -Path $PROFILE -Parent) -ChildPath "gh-copilot.ps1"
gh copilot alias -- pwsh | Out-File ( New-Item -Path $GH_COPILOT_PROFILE -Force )
echo ". `"$GH_COPILOT_PROFILE`"" >> $PROFILE
  • And you’re all set! 🎉

  • Let’s see some examples!

Copilot in action! 🚀

Example 01: Stop struggling with terminal commands 🖥️

  • Let’s start with gh copilot explain to get an explanation of a command
  • The command below searches for log files and then searches within them for the word error
    • find / -name '*.log' -exec grep 'error' {} +

Example 01: Stop struggling with terminal commands 🖥️

  • Now let’s use gh copilot suggest to generate a command
  • ghcs "create three txt files with names test1.txt, test2.txt, and test3.txt", then add the content "Hello, world!" to each file, then list the files, show the content of each file, and delete them"

Example 01: Stop struggling with terminal commands 🖥️

Example 02: Stop struggling with Git 🐙

  • Let’s see how Copilot can help with Git commands
  • ghcs "create a new branch called 'feature-branch', switch to it, create a new file called 'feature.txt', add some content to it, commit the changes, push the branch to the remote repository, and open a pull request"

Example 03: Stop struggling with GitHub CLI 🐙

  • ghcs "how can I use gh to create a new private repository on GitHub danilofreire/testing, clone it to my computer, add a README file, commit the changes, push the changes to the remote repository, and open a pull request?"

Cool, isn’t it? 🤩

Let’s see what Copilot can do for you in VS Code

  • If you have installed Copilot in VS Code, just click on the Copilot icon (a chat bubble) in the bottom left corner
  • You can then type a prompt and see the suggestions. As you know how to ask it to generate code (same as in ChatGPT), let’s see other things that Copilot can do for you
  • Type /help to see the available commands
  • You will also note that there are commands such as @workspace, @vscode, @terminal, and @github that allow you to interact with the workspace, VS Code, the terminal, and GitHub (including your account), respectively
  • You can also interact with files with #file
  • Let’s have a look at some examples

Example 04: Explain code 🤔

  • Type /explain followed by a code snippet to get an explanation. You can select the snippet directly in the terminal, then just type /explain

Example 05: Run tests 🧪

  • Type /tests followed by a code snippet to run tests
  • Let’s see how it tests this function:
class SimpleCalculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b

    def square_root(self, a):
        if a < 0:
            raise ValueError("Cannot calculate square root of a negative number")
        return a ** 0.5

Example 05: Run tests 🧪

Example 06: Fix code 🛠️

  • Type /fix followed by a code snippet to fix it
  • This function is supposed to check if a number is even, but it has a logical error. The division operation (number / 2) should be replaced with the modulo operation (number % 2)
  • If you hoover over the Fixed Code block, you will see the options:
    • Apply the fix in the editor
    • Insert the fixed code at the cursor
    • Copy the fixed code to the clipboard
    • Insert into a terminal
    • Insert into a new file
def is_even(number):
    return number / 2 == 0

Example 06: Fix code 🛠

Example 07: Create new file and generate text/code 🚀

  • Type /new and pass the information about the file you want to create
  • /new create a file.txt file with the first three lines of Homer's Odyssey

Example 08: Run code 🏃‍♂️

  • You can use the @terminal command to write and run code in the terminal. Click on the terminal icon to insert the code
  • @terminal create a file titled test.py and add print("Hello, world!") using the command line

Example 09: Interact with GitHub 🐙

  • You can use the @github command to interact with GitHub
  • For example, let’s see what are the latest 3 commits of this repository (danilofreire/qtm350)
  • You can also use @github to create a new repository, open a pull request, and more

Example 10: Interact with VS Code 🚀

  • You can use the @vscode command to interact with VS Code
  • For example, let’s see how to open a new file in the editor

Example 11: Interact with the workspace 💻

  • The @workspace command allows you to interact with the workspace, which are the files and folders you have open in VS Code
  • For example, let’s ask it to list the files in the workspace

Example 11: Interact with the workspace 💻

  • Another example: let’s ask it to find files that contains bash commands
  • Click on the icons and they will open!

Last Example: Searching for text in files 📄

  • You can use the #file command to search for text in files
  • Combine it with the @workspace command to search in all files in the workspace
  • Let’s search for Python code in this file

Summary

  • GitHub Copilot can save you a lot of time and make you more productive (and it’s fun!)
  • It is not perfect, but it is a good tool as it is 🤓
  • I hope you will make good use of AI coding tools from now on 🤖
  • Find out other uses for it, test the other tools available, and let me know what you think!

And that’s it for today! 🎉

Thank you for your attention and enjoy the Fall break! 🍂