Creating a ChatGPT-Integrated NPC in Roblox

Creating a ChatGPT-Integrated NPC in Roblox

Hello Roblox Developers!

I’m excited to share with you a detailed guide on creating an NPC in Roblox that integrates with OpenAI’s ChatGPT via a custom proxy server. This NPC can interact with players, respond to specific topics, and even execute code in-game. Below, you’ll find step-by-step instructions on setting up the proxy, coding the NPC, and making everything work seamlessly together.

Table of Contents:

  1. Overview

  2. Setting Up the ChatGPT Proxy

  3. Obtaining the Roblox Side

  4. Handling Keyword Filtering

  5. Executing Code from Chat

  6. Putting It All Together

1. Overview

This project involves creating an NPC in Roblox that can:

  • Chat with players using responses generated by ChatGPT.

  • Filter responses based on specific keywords.

  • Execute Lua code based on player input.

2. Setting Up the ChatGPT Proxy

First, you’ll need to set up a proxy server to handle requests to OpenAI’s ChatGPT API.

Steps:

  1. Set Up a Server: You can use any hosting service. For this example, we’ll assume you’re using a basic Node.js server.

Certainly! Let’s break down the process into two main parts: deploying the proxy server to AWS Lightsail and setting up the Roblox game with a UI similar to ChatGPT’s website.

Part 1: Deploying the Proxy Server to AWS Lightsail

Step 1: Set Up AWS Lightsail

  1. Sign in to AWS Lightsail:

  2. Create an instance:

    • Click on “Create instance”.
    • Choose the instance location (region).
    • Select the “Linux/Unix” platform.
    • Choose an instance plan that suits your needs (the $3.50/month plan should be sufficient for testing).
    • Select “Node.js” as the blueprint.
    • Give your instance a name and click “Create instance”.

Step 2: Configure the Instance

  1. Connect to your instance:

    • Once the instance is running, click on the “Connect” tab to open an SSH terminal.
  2. Install Node.js and npm (if not already installed):

    sudo apt update
    sudo apt install nodejs npm -y
    
  3. Set up your project:

    mkdir chatgpt-proxy
    cd chatgpt-proxy
    npm init -y
    npm install express axios
    
  4. Create server.js file:

    nano server.js
    

    Add the following code to server.js:

    const express = require('express');
    const axios = require('axios');
    const bodyParser = require('body-parser');
    
    const app = express();
    const port = 3000;
    
    app.use(bodyParser.json());
    
    app.post('/chat', async (req, res) => {
        const message = req.body.message;
        const apiKey = 'YOUR_OPENAI_API_KEY'; // Replace with your OpenAI API key
    
        try {
            const response = await axios.post('https://api.openai.com/v1/engines/gpt-3.5-turbo/completions', {
                prompt: message,
                max_tokens: 150,
                temperature: 0.7,
                n: 1,
                stop: null,
            }, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                },
            });
    
            res.json({ reply: response.data.choices[0].text });
        } catch (error) {
            console.error('Error contacting OpenAI:', error);
            res.status(500).json({ error: 'Failed to fetch response from OpenAI' });
        }
    });
    
    app.listen(port, () => {
        console.log(`Proxy server running at http://localhost:${port}`);
    });
    
  5. Run your server:

    node server.js
    
  6. Keep the server running (optional):

    • You might want to use a process manager like pm2 to keep your server running.
    npm install -g pm2
    pm2 start server.js
    
  7. Configure Security

  8. Set up firewall rules in Lightsail:

    • Go to the “Networking” tab of your instance.
    • Ensure that port 3000 is open for HTTP traffic.

8… Run the Server:

node server.js

3. Obtaining the Roblox Side

I’ve linked below the Roblox Open Source Game and the Gamefile I recommend to edit ChatGPTProxy to add your own server link to ChatGPT if you have one because the link/IP provided in the game/files will not be accessible forever and shutdown after a certain period of time.

Open Source Robloxside

My AI NPC - Roblox
My AI NPC.rbxl (83.7 KB)

4. Handling Keyword Filtering

You can toggle keyword filtering using the toggleKeywordFiltering function. By default, it’s set to false.

5. Executing Code from Chat

Players can execute code by sending a chat message starting with run code: followed by the Lua code they wish to execute. Ensure that you handle this feature with care to avoid any potential security risks.

6. Putting It All Together

With the proxy server running and the NPC script in place, you can now have an interactive NPC in your Roblox game that leverages the power of OpenAI’s ChatGPT to provide dynamic responses and execute code based on player input.

Summary

Feel free to customize and expand this project further. If you have any questions or run into issues, don’t hesitate to ask on the forum. Happy coding!

I hope you find this guide helpful! If you have any questions or need further assistance, feel free to reach out. Happy developing!


Hope this helps with some awesome game development let me know your thoughts and what you plan to use this for!

7 Likes

This sounds interesting but I’m pretty sure you can just use the ChatGPT endpoint in Luau without the need to use a proxy server.

1 Like

Just a side note to enable the NPC to run code you are required to enable loadstring() I do not personally recommend it, but if you do make sure to edit the code and add permissions to this feature.

1 Like

I recently released an Open Source template for an LLM integrated NPC in ROBLOX, I have Open Sourced it so feel free to use the code or check it out.

2 Likes

Agree with this because if it is running on the server anyways its already protected. Seems like extra work to use a proxy.