ChatGPT Code Review Integration
Tags: chatgpt, codereview, react, javascript
Published: 2023-06-15 06:53:57

---
series: Building a React App with ChatGPT
---

Before we delve deeper into app development, let's explore the integration of ChatGPT code review. Instead of relying solely on ChatGPT to write all the code, you may find yourself making small fixes here and there. As a result, some commits may be created outside the collaborative development process.

Code reviews play a vital role in catching bugs, improving maintainability, and fostering quality of the code. If you’ve been there you know that code reviews manually can be time-consuming and prone to oversight. So this workflow could be interesting also for ongoing projects. 

**Setting the Stage:**

To get started, we need two key ingredients: a Node.js script and an OpenAI API key. The Node.js script will serve as the bridge between our codebase and the ChatGPT API. It will handle sending code snippets to ChatGPT and retrieving feedback for each commit. You can [see the final result here](https://github.com/pelayomendez/code-session-tracker-app/blob/main/scripts/code_review.js). 

![Write a Node.js script that connects to ChatGPT on precommit and reviews the code.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q22gov54pdkjmnzzuhsn.png)

ChatGPT's generated script constructs a message containing the code snippet to be reviewed and send it to the ChatGPT API. The response from ChatGPT contains feedback on the code, providing valuable insights for improvement.

The script handles the logic of invoking ChatGPT for code reviews. It takes the staged code, sends it to ChatGPT, and retrieves the generated feedback.

```javascript
const API_KEY = process.env.API_KEY;
const CHATGPT_API_URL = 'https://api.openai.com/v1/chat/completions';

async function sendMessage(message) {
  const response = await fetch(CHATGPT_API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      messages: [{ role: 'system', content: 'You: ' + message }],
      model: 'gpt-3.5-turbo'
    }),
  });

  const data = await response.json();
  console.log(data)
  if (data && data.choices && data.choices.length > 0) {
    return data.choices[0].message.content;
  }

  throw new Error('Unable to get response from ChatGPT');
}

``` 

**Run the script:**

Create a scripts folder in your project directory, if it doesn't exist already. Move the code review script into the scripts folder.Open your package.json file.Locate the "scripts" section in the package.json file.Add a new command entry to the "scripts" section. For example, you can name it "code-review".

```json
"scripts": {
  "code-review": "node scripts/code-review.js"
},
```
Run the code review script by executing the command npm run code-review and you will obtain the response from chat GPT.

```bash
npm run code-review
```

**Integrating the Pre-commit Hook:**

Now that our Node.js script is ready and working, we can integrate it into our Git workflow using pre-commit hooks. Pre-commit hooks allow us to automate tasks that should be performed before committing our code. By adding our script as a pre-commit hook, we can ensure that every commit is automatically reviewed by ChatGPT.

You can use a tool like [Husky](https://www.npmjs.com/package/husky) to simplify this step. After following the installation steps in the documentation, you will have a pre-commit bash script located at _.husky/pre-commit_ that will launch the script before any commit.

```bash
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run pre-commit
```

**Choosing the right model:**

When it comes to reviewing code with ChatGPT, you have a few options for choosing a suitable language model. Here are two recommended models for code-related tasks:

gpt-3.5-turbo: _This is the most advanced and powerful model available from OpenAI. It provides excellent performance for a wide range of tasks, including code review. It has been trained on a diverse range of internet text and can understand and generate code snippets effectively._

davinci: _Although not specifically designed for code-related tasks, the davinci model is also capable of understanding and reviewing code to a certain extent. It is a highly versatile model and can handle a wide range of tasks across different domains.Both of these models can be used for code review purposes._

**Provide its own feedback to ChatGPT:**

In this series, we interact with ChatGPT through the web interface. Once you have made changes in your code, it's always better to inform ChatGPT about the current state. Otherwise, it may get confused in future interactions.

![Hey! This is how the script looks after I made some modifications.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twokxw29d119yyntoixw.png)

![Hey! I got this code review. What do you think?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekatgzqjuvqzgind5qkc.png)

**Conclusion:**

Incorporating ChatGPT into your code review workflow through pre-commit hooks is a powerful way to enhance the quality and maintainability of your codebase.