JavaScript

Setting Up CodeGPT: The AI-Powered Code Assistant

Fotis Adamakis
Fotis Adamakis
Senior Software Engineer / Technical Writer
10 min read
April 3, 2023

Setting Up CodeGPT: The AI-Powered Code Assistant

Setting Up CodeGPT: The AI-Powered Code Assistant

Artificial intelligence has disrupted numerous industries lately. Everyone and everywhere is talking about ChatGPT. One of the most exciting applications is its ability to understand and generate code. Several tools have been developed to leverage this functionality, one of them being CodeGPT, a Visual Studio Code extension that seamlessly integrates ChatGPT into the IDE. With CodeGPT, developers can harness the power of AI to streamline their coding workflow and boost productivity.

Setting Up

  1. Install the VSCode extension
  2. Create or Login to an Open AI account (Same as ChatGPT)
  3. Create an API Key
  4. Setup a payment method
  5. Save the API key in VSCode (Command Palette ⇒ CodeGPT: Set API KEY)

The first step is to install the extension from the Visual Studio Marketplace. The extension is free, but an OpenAI API key needs to be provided. You can create a new key in the OpenAI dashboard. This is the same account with ChatGTP. If you don’t have an account yet, [create one here](https://platform.openai.com/signup). Make sure that you copy the key at this point since this will be your only chance to do so. In order to save the key in VSCode open the command palette (cmd + P / ctrl + P) and type CodeGPT: Set API KEY

Alternative APIs to OpenAI are cohere.ai and AI21. The plugin usage is the same.

Pricing

Cost is insignificant for personal usage. It costs way less than my daily coffee consumption. The only problem is that it is way too complex to understand at first glance and requires some basic knowledge of how GPT tokenization works. As a general rule, you pay per usage, and it costs around 0.01€ per 24 prompts. To be more accurate, you can use [this tool](https://platform.openai.com/tokenizer) to find exactly how many tokens exist in an interaction and calculate the cost with the rate of 1k tokens cost 0.02€.

For example, when writing this article, I used the tool 19 times for a total bill of 0.01€

Setting Up CodeGPT: The AI-Powered Code Assistant

Features

CodeGPT features are available in the context menu after selecting a code snippet. The answer will appear in a new panel.

Setting Up CodeGPT: The AI-Powered Code Assistant

Let’s explore all the available options:

  1. Ask CodeGPT
  2. Compile & Run Code
  3. Find Problems
  4. Refactor Code
  5. Unit Test
  6. Generate Code from Comments
  7. Documentation
  8. Ask Stackoverflow
  9. Advanced Refactoring

1. Ask CodeGPT

Allows you to start a conversation with the chat interface. The chat, just like ChatGPT, remembers the last concepts of the conversation. This is the most powerful but a bit intimidating in the beginning. Refer to the bonus section at the end for some generic use cases.

2. Compile & Run

You can compile and run code without a development server running. Helpful but not really impressive compared to what comes next.

3. Find Problems

I wrote the above fibonacci snippet from memory since I wanted something small that everyone would be familiar with in order to focus on the tool itself. So when testing the “find problems” functionality, I was confident that the tool would be amazed by my code elegance. And I failed miserably. As you might have noticed fibonacci(0) should be zero. The tool correctly detected and fixed it.

function fibonacci(num) {
  if (num <= 1) return 1;

  return fibonacci(num - 1) + fibonacci(num - 2);
}

fibonacci(10);

<CodeGPT find errors>

There are no apparent syntax errors in the code, but there is a logic error. The current implementation of the _fibonacci()_ function always returns 1 when the input value is 1 or less. This is not accurate, as the Fibonacci sequence starts at 0 and 1, not 1 and 1. Here is an updated implementation of the _fibonacci()_ function:

function fibonacci(num) {
  if (num <= 0) return 0;
  if (num === 1) return 1;

  return fibonacci(num - 1) + fibonacci(num - 2);
}

fibonacci(10);

This implementation correctly handles the base cases of 0 and 1, and then recursively computes the values of the Fibonacci sequence for larger inputs.


4. Refactor Code

Another impressive feature is refactor mode. Let’s try it with the same fibonacci snippet.

function fibonacci(num) {
  if (num <= 1) return 1;

  return fibonacci(num - 1) + fibonacci(num - 2);
}

fibonacci(10);

<CodeGPT refactor>

The given code is a recursive function that calculates the nth number in the Fibonacci sequence. However, it has a small error in the base case as it returns 1 instead of 0 for num=0.

Here’s the refactored code with the correction:

function fibonacci(num) {
  if (num <= 0) return 0;
  if (num === 1) return 1;

  let fib1 = 0;
  let fib2 = 1;
  let fibCurr = 1;

  for (let i = 2; i <= num; i++) {
    fibCurr = fib1 + fib2;
    fib1 = fib2;
    fib2 = fibCurr;
  }

  return fibCurr;
}

console.log(fibonacci(10)); // Output: 55

Here are the changes made:

  1. Added a base case for num = 0, which returns 0.
  2. Switched to non-recursive method using a for loop.
  3. Declared three variables: fib1, fib2 and fibCurr.
  4. Loop through until the nth value in the sequence is calculated and return it.
  5. Added a console.log statement to output the return value.

This code calculates the nth number in the Fibonacci series in a more efficient way.


CodeGPT detected and fixed the error, converted the code to be non-recursive for better memory usage and readability and explained every change in detail. Really really impressive.

5. Explain Code

Explaining code is another powerful feature. In this example, I’m asking about a small function that performs a debounced search written in Vue.js

    performSearch: debounce(async function () {
      if (this.searchTerm === "") {
        this.products = [];
        return;
      }
      if (this.searchTerm.length < 2) {
        return;
      }
      const searchUrl = this.getSearchUrl();
      const response = await (await fetch(searchUrl)).json();

      this.products = response.products;
    }, 600),

<CodeGPT explain>

This code defines an async function called “performSearch” that utilizes a debounce function. The purpose of the debounce function is to delay invoking the “performSearch” function until a certain amount of time has elapsed (in this case, 600 milliseconds).

The first conditional statement checks if the input search term is an empty string. If so, it sets the “products” array to an empty array and returns.

The second conditional statement checks if the length of the search term is less than 2 characters. If so, it returns without executing any further code.

If both of these conditional statements are false, the code executes and fetches a JSON response from a URL (specified by the “getSearchUrl()” function), using the fetch method. The response is then parsed as JSON and assigned to the products array on the context of the function.

Overall, this code performs a search for products based on a user input search term and sets the results to an array. The debounce function prevents the search function from executing multiple times in quick succession.


Additionally, we can ask follow-up questions.

Q: What is debounced?

A: In this code, the performSearch function is debounced using the debounce function. Debouncing is a technique used in programming to prevent a function from being called multiple times within a short period of time. In this case, the performSearch function is debounced by 600 milliseconds, which means that it will only be executed after a 600 millisecond delay, and if the function is called again within that delay period, the timer will reset and the delay will start again. This is done to prevent excessive API requests in cases where the user types quickly or the search term changes frequently.

6. Unit Test

This is probably the most impressive one. Writing Unit tests can often be repetitive and time-consuming. These are good indicators that something needs to be automated.

First, let’s try the simple ficonacci code:

function fibonacci(num) {
  if (num <= 0) return 0;
  if (num === 1) return 1;

  return fibonacci(num - 1) + fibonacci(num - 2);
}

fibonacci(10);

<ChatGPT Unit Test>

Here’s the unit test code for the given _fibonacci_ function:

describe('fibonacci', () => {
  it('returns 0 for input 0', () => {
    expect(fibonacci(0)).toEqual(0);
  });

  it('returns 1 for input 1', () => {
    expect(fibonacci(1)).toEqual(1);
  });

  it('returns 55 for input 10', () => {
    expect(fibonacci(10)).toEqual(55);
  });
});

This code uses the Jest testing framework and contains three test cases, each with an assertion that checks the output of the _fibonacci_ function for a particular input. The first test case checks that input 0 returns 0, the second checks that input 1 returns 1, and the third checks that input 10 returns 55 (the correct value of the 10th number in the Fibonacci sequence).


That was an impressive explanation, but the code was nothing special. Let’s try the Vue Search snippet, which is more complex.

    performSearch: debounce(async function () {
      if (this.searchTerm === "") {
        this.products = [];
        return;
      }
      if (this.searchTerm.length < 2) {
        return;
      }
      const searchUrl = this.getSearchUrl();
      const response = await (await fetch(searchUrl)).json();

      this.products = response.products;
    }, 600),

<ChatGPT Unit Test>


// Import required dependencies for testing
import { performSearch } from "./search";

// Test suite for performSearch function
describe("performSearch function", () => {
  // Test case for empty search term
  it("should return empty array for empty search term", async () => {
    const context = {
      searchTerm: "",
      products: [],
      getSearchUrl: jest.fn(() => "https://example.com/search"),
    };

    await performSearch.call(context);

    expect(context.products).toEqual([]);
  });

  // Test case for search term less than 2 characters
  it("should not perform search for search term less than 2 characters", async () => {
    const context = {
      searchTerm: "a",
      products: [],
      getSearchUrl: jest.fn(() => "https://example.com/search"),
    };

    await performSearch.call(context);

    expect(context.products).toEqual([]);
    expect(context.getSearchUrl).not.toHaveBeenCalled();
  });

  // Test case for valid search term
  it("should perform search for valid search term and update products", async () => {
    const context = {
      searchTerm: "apple",
      products: [],
      getSearchUrl: jest.fn(() => "https://example.com/search"),
      fetch: jest.fn(() =>
        Promise.resolve({
          json: jest.fn(() =>
            Promise.resolve({
              products: [{ id: 1, name: "Apple iPhone 12" }],
            }),
          ),
        }),
      ),
    };

    await performSearch.call(context);

    expect(context.getSearchUrl).toHaveBeenCalled();
    expect(context.fetch).toHaveBeenCalled();
    expect(context.products).toEqual([{ id: 1, name: "Apple iPhone 12" }]);
  });
});

This is really impressive. Correctly detected all the branches, mocked the required dependencies and produced readable tests with 100% coverage.

7. Generate Code from Comments

Lastly, we can describe a behaviour in a comment and generate the code out of it with the shortcut (cmd + shift + i)

// Create  a function that returns the nth number in the Fibonacci sequence

<cmd + shift + i>

function fibonacci(n: number): number {
  if (n < 1) {
    throw new Error("Invalid input. 'n' should be greater than or equal to 1.");
  } else if (n === 1 || n === 2) {\\n    return 1;
  } else {\\n    let prev = 1;
    let current = 1;
    let result = 0;

    for (let i = 3; i <= n; i++) {
      result = prev + current;
      prev = current;
      current = result;
    }

    return result;
  }
}

Bonus

Creating Documentation

The only task more boring than reading documentation is writing it. CodeGPT can document code or create a proper readme file for your repository. It might not be perfect but its a good start when facing blank page anxiety.

Searching Stackoverflow

Press cmd + shift + p and search for Ask StackOverflow

This functionality allows you to get questions from Stackoverflow and compare the best human answer 🧠 with the answer from an artificial intelligence 🤖

Refactoring code

The built-in refactoring mode works well but combined with specific instructions can be extremely powerful. Converting files from JavaScript to TypeScript or Vue 2 to Vue 3 works surprisingly well.

Conclusion

In conclusion, CodeGPT is a cutting-edge tool that showcases the power of AI in the field of coding. By integrating ChatGPT’s natural language processing capabilities into the IDE, CodeGPT offers developers an innovative way to streamline their coding workflow and increase productivity. With CodeGPT, we can take advantage of intelligent code autocompletion and generation, automate the boring stuff and focus on the higher-level tasks. As AI technology continues to advance, it’s likely that we’ll see even more innovative applications of tools like CodeGPT in the field of software development, further transforming the way we approach programming.

The future of programming is already here. It’s just not evenly distributed yet.

Setting Up CodeGPT: The AI-Powered Code Assistant

Fotis Adamakis

Fotis Adamakis

Senior Software Engineer / Technical Writer

Experienced software engineer writing about front end architecture, accessibility, system design, and developer productivity. Lessons from building and maintaining large-scale frontend applications, with a focus on practical patterns that make codebases easier to understand, scale, and evolve.

Barcelona, Spain