How to set up ChatGPT {AI} as a code reviewer on the GitLab Server | alvianaufan

BLOG IT SYSADMIN

Daftar akun digitalocean untuk mendapatkan free credit 100$.
DigitalOcean Referral Badge

Introduction

In this article, I want to explain through the process of reviewing your code on the GitLab server. We’ll explore the direct utilization of ChatGPT on the Merge Request menu page for an effective and streamlined code review experience.

ChatGPT has become incredibly important for developers. It helps them solve different issues in the code they’re working on, making it a really popular and much-needed AI tool.



Prerequisites

Prior to commencing with this guide, kindly install the specified packages on your Linux server. As an illustration, I am employing Ubuntu Server 22.04 in the latest version for demonstration purposes:

  • Install Python3 latest
    sudo apt update
    sudo apt upgrade
    python3 -V

Step 1 – setting up Gitlab Access Token

  • Login to your gitlab account
  • Navigate to user picture > edit profile > access token (checklist on “api”)
  • Copy and keep your gitlab access token

 

Step 2 – setting up ChatGPT openchat_api

Step 3 – setting up a reviewer application.

  1. First, you need to clone my sourcecode on github:
    git clone https://github.com/alvianaufan/chatgpt_gitlab-merge-request-reviewer.git
  2. Go to the chatgpt_gitlab-merge-request-reviewer folder and edit the reviewer.py file:
    cd chatgpt_gitlab-merge-request-reviewer 
    nano reviewer.py
    # Read OpenAI API key from environment variable
    openai.api_key = "insert_chatgpt_apikey_here"
    
    # Model for API requests
    model = "text-davinci-003"
    
    # GitLab API endpoint and personal access token
    gitlab_url = "https://gitlab.yourserver.com/api/v4"
    access_token = "insert-gitlab-access-token-here"

    – save and exit


  3. Then, please install package with name python3-pip and openai==0.28(with pip command):
    cd chatgpt_gitlab-merge-request-reviewer
    sudo apt install -y python3-pip
    pip install -r requirements.txt
    
    #you will have an error while installation and need to install specific openai version like below:
    pip install openai==0.28
  4. After that, please try running the command
    python3 reviewer.py

    run python reviewer chatgpt ai

  5. Attempt to open a web browser and access the URL http://ip-address:5000.url python reviewer– If the appearance of the browser display resembles the image above, there’s no cause for concern; the system is functioning normally. For additional verification, you can inspect the server’s log console.

 

Step 4 – setting up python running in a background

  1. Navigate to the systemd directory path and establish a service for running Python with the following commands:
    cd /etc/systemd/system/
    sudo nano reviewer_alvian.service
    [Unit]
       ConditionPathExists=/directory-path/user/chatgpt_gitlab-merge-request-reviewer
       After=network.target
    
    [Service]
        Type=simple
        User=user
        Group=user
    
        WorkingDirectory=/directory-path/user/chatgpt_gitlab-merge-request-reviewer
        ExecStart=/usr/bin/python3 reviewer.py
    
        Restart=on-failure
        RestartSec=10
    
        StandardOutput=file:/var/log/reviewer-alvian_out.log
        StandardError=file:/var/log/reviewer-alvian_error.log
        SyslogIdentifier=reviewer-alvian_service
    
        [Install]
        WantedBy=multi-user.target

    – save and exit

  2. Start the service with command:
    systemctl start reviewer-alvian.service
    systemctl enable reviewer-alvian.service
    systemctl status reviewer-alvian.service


    – If the service status is indicated as “active,” it signifies that Python is executing successfully as a service. This confirms that the Python script is running as intended within the systemd-managed service environment.



    – In the service file you’ve created, if you’ve specified a folder path for storing logs, such as “/var/log,” it implies that the service will log its activities in that directory. You can check the logs to monitor the behavior and performance of the Python script.

    cat /var/log/reviewer-alvian_out.log
    cat /var/log/reviewer-alvian_error.log

Step 5 – setting up a url proxy (optional)

Certainly, if you wish to access the URL without specifying the port, you can utilize a reverse proxy setup with either Apache or Nginx. Read this article for setup proxy pass in apache virtual host configuration Cara Menjalankan Lebih Dari Satu Website React JS dengan Apache

 

Step 6 – setting up webhook on a project

  1. Create a user account that will be used as a bot to run the webhook
  2. Invite your bot to the project with a developer role.
  3. To enhance visibility and recognition, it’s advisable to set a profile picture for the bot user.
  4. In your GitLab dashboard for the bot, click on a project and go to Settings > Webhooks. Setup like example: webhook gitlabUrl: http://ip-address:5000/webhook or https://yourgitlabdomain.com/webhook
    Triger: Comments, Confidential comments, Merge Request events
    SSL Verification: do not checklist if you use url without https
    – save
  5. Locate and select the “Merge Requests” menu > click the add New merge request button > select the source branch and target branch > click the Compare branches and continue button
  6. In the next page, fill the title or you can skip with click Create merge request button


  7. After you’ve made the merge request, give these commands a try in the comments:
    – Type /analyze to run an analysis.
    – Type /checkcode to check the code.
    – Type /optimization to optimize the code.These commands can help you perform specific actions and get information about your code.
  8. Also you can edit the command and prompt in reviewer.py like:
    def handle_analyze_command(project_id, mr_iid):
        # Your logic for handling the /analyze command
        # Fetch code changes, send to OpenAI, post the response, etc.
        prompt = "tolong analisis penggunaan code ini."
    
        # Prompt the bot with the custom prompt and generate a response
        response = openai.Completion.create(
            engine=model,
            prompt=prompt,
            max_tokens=500,
        )
        generated_response = response['choices'][0]['text']
    
        # Make a reply to the merge request with the generated response
        make_reply(project_id, mr_iid, generated_response)
    
    def handle_checkcode_command(project_id, mr_iid):
        # Your logic for handling the /checkstyle command
        # Implement the specific checks, provide feedback, etc.
        prompt = "apakah ada yang salah di code ini?"
    
        # Prompt the bot with the custom prompt and generate a response
        response = openai.Completion.create(
            engine=model,
            prompt=prompt,
            max_tokens=500,
        )
        generated_response = response['choices'][0]['text']
    
        # Make a reply to the merge request with the generated response
        make_reply(project_id, mr_iid, generated_response)
    
    def handle_custom_command(project_id, mr_iid):
        # Your logic for handling a custom command
        # Define a specific prompt and response for this command
        prompt = "apakah ada yang dapat di optimasikan di code ini?"
    
        # Prompt the bot with the custom prompt and generate a response
        response = openai.Completion.create(
            engine=model,
            prompt=prompt,
            max_tokens=500,
        )
        generated_response = response['choices'][0]['text']
  9. Certainly, here’s a simplified example of a response from ChatGPT after executing those commands:

Until now, you have successfully enabled ChatGPT to review code within the merge request process.

This concludes the tutorial on configuring ChatGPT {AI} as a code reviewer on GitLab Server. Please leave your questions or concerns in the comments section. 🙂



Write A Comment