How to use OpenAI's new ChatGPT API in roblox

Recently, OpenAI just released the ability to use ChatGPT using their API.
This topic discusses my implementation of a the new chatgpt AI in Roblox using OpenAI’s API.

Requirements:

  • Account on Open AI
  • Open AI, API key (Google how to get one)
  • Basic Luau and Roblox API knowledge

The Tutorial is below. More information is in the comments of the script.
Tutorial:

local url = "https://api.openai.com/v1/chat/completions" -- Sets the URL of the OpenAI API endpoint to request from

local headers = { -- Sets the authentication header for the API request. The API-KEY should be replaced with an actual OpenAI API key
	["Authorization"] = "Bearer API-KEY",
}

local body = HTTP:JSONEncode({ -- Constructs the request body to be sent to the API. It contains the model name and a list of messages
	model = "gpt-3.5-turbo",
	messages = {{
		role = "user",
		content = "your message" -- The text message to be sent to the OpenAI API for generating the response
	}}
})

local response = HTTP:PostAsync(url, body, Enum.HttpContentType.ApplicationJson, nil, headers) -- Sends a POST request to the OpenAI API endpoint with the request body and authentication header, and receives the API response. Don't change this if you don't know what you are doing.

local decoded = HTTP:JSONDecode(response) -- Decodes the JSON response from the OpenAI API into a Lua table

-- you can print decoded and look at everything openAI sends you. It's a huge table with a ton of information.

local message = decoded["choices"][1]["message"]["content"] -- Extracts the generated text response from the decoded JSON response and assigns it to the `message` variable.
49 Likes

How do you get the bearer-api-key?

4 Likes

To get the bearer-api-key, you need to create an account on OpenAI and then create an API key. Once you have an API key, you can use it as the bearer token in the header of your HTTP request. To get an API key, you can go to the OpenAI dashboard, click on the “API Keys” tab, and then click on the “Create new API Key” button. Follow the instructions to create a new API key, and then copy the value of the key to use as the bearer token in your API requests.

2 Likes

uhh you can go here if you want to know how

2 Likes

This isn’t working for me, I keep getting this error;
HTTP 429 (Too Many Requests), it happens on

local response = HttpService:PostAsync(url, body, Enum.HttpContentType.ApplicationJson, nil, headers)
3 Likes

I am receiving the error HTTP 401 (Unauthorized) , even though I know I followed everything correctly. I even checked OpenAI’s API webpage.

2 Likes

Considering that users are encountering errors within the API, I’ll be releasing a ChatGPT Module in a couple hours.

2 Likes

Figured it out, heres the OpenAI API reference page if you need help!

What did u do to fix it? I have the same problem

1 Like

Did you keep in the part that says "Bearer "?

2 Likes

As you can’t really trust custom contents made by anything other than the game, I must say that filtering is still a required thing. Also any external requests such as HTTP requests (and FilterString too) should be wrapped in pcall for both safety and error diagnosis.

local HTTP = game:GetService("HttpService")
local textSrv = game:GetService("TextService")

local url = "https://api.openai.com/v1/chat/completions" -- Sets the URL of the OpenAI API endpoint to request from

local headers = { -- Sets the authentication header for the API request. The API-KEY should be replaced with an actual OpenAI API key
	["Authorization"] = "Bearer API-KEY",
}

local body = HTTP:JSONEncode({ -- Constructs the request body to be sent to the API. It contains the model name and a list of messages
	model = "gpt-3.5-turbo",
	messages = {{
		role = "user",
		content = "your message" -- The text message to be sent to the OpenAI API for generating the response
	}}
})

local sa, response = pcall(function()
	return HTTP:PostAsync(url, body, Enum.HttpContentType.ApplicationJson, nil, headers)
end) 		-- Sends a POST request to the OpenAI API endpoint with the request body and authentication header, and receives the API response. Don't change this if you don't know what you are doing.

if not sa then
	warn("Error when fetching a response message: "..response)
end

local decoded = HTTP:JSONDecode(response) -- Decodes the JSON response from the OpenAI API into a Lua table

-- you can print decoded and look at everything openAI sends you. It's a huge table with a ton of information.

local message = decoded["choices"][1]["message"]["content"] -- Extracts the generated text response from the decoded JSON response and assigns it to the `message` variable.
local sb, filteredMessage = pcall(function() -- Filters the generated text response for Roblox ToS compliance
	return textSrv:FilterStringAsync(tostring(message), game.CreatorId):GetNonChatStringForBroadcastAsync()
end)
if sb then
	text.Text = filteredMessage
else
	warn("Error when filtering response message: "..filteredMessage)
	text.Text = "####"
end
3 Likes

Where do i put this script? I’m a little bit confused

2 Likes

Guys the code is all correct no need for additional edit.

  • you have to change the “bearer api-key” to
    "Bearer " . . {your api key} (ignore the space between dots, just remove it)

  • The api is not free. You have to purchase it in chatGPT API site.

  • Use pcall to block some errors.

  • This is not necessary but you can put this.

	messages = {{
		role = "user",
		content = "your message",
        name = {Requesting player}.Name
	}}
3 Likes

sorry im a bit late, but do you put this in a localscript or just a normal script or serverscriptservice or what? im not very good at scripting, i can only design very very basic stuff so this is wayyy over my head

1 Like

for everyone getting the “Too Many Requests”. ChatGPT gives certain users a free trial of API usage. Mine was $15, but it expires after a few months. New accounts don’t get this until after a certain period of time. You’ll have to pay around $1 for every ~40 thousand messages. So if you get that error just check your usage and free credit here: OpenAI API

2 Likes

Beautifully basic I’ll grow this. Thank you.
roblox chatgpt

3 Likes

im getting error: HTTP 429 (Too Many Requests) despite running the code once in the command bar with only the api key changed

POV most helpful Dev Forum member (Sarcasm):

I am getting the same issue, if you ended up finding a solution I would really appreciate if you could share it here. (edit I have solved it myself)