OpenAI Text Generation

A simple guide to creating a script that can generate text with the OpenAI API!

  1. Sign up for an OpenAI account and obtain an API key by visiting this website

  2. In the script, replace YOUR_API_KEY with your own API key.

  3. Customize the request body by setting the model and prompt fields to the desired values. You can also adjust the max_tokens field to control the maximum number of tokens (i.e. words) in the generated text.

  4. Run the script. It will send a request to the OpenAI API using the specified model and prompt , and then print the generated text.

-- Set the API key and endpoint
local API_KEY = "YOUR_API_KEY"
local API_ENDPOINT = "https://api.openai.com/v1/text-davinci/generations"

-- Set the request body
local requestBody = {
	model = "davinci",
	prompt = "What is your name?",
	max_tokens = 100
}

-- Encode the request body as JSON
local requestBodyJson = HttpService:JSONEncode(requestBody)

-- Create the request headers
local requestHeaders = {
	["Content-Type"] = "application/json",
	["Authorization"] = "Bearer "..API_KEY
}

-- Send the request and get the response
local response = HttpService:PostAsync(API_ENDPOINT, requestBodyJson, Enum.HttpContentType.ApplicationJson, false, requestHeaders)

-- Parse the response as JSON
local responseJson = HttpService:JSONDecode(response)

-- Print the generated text
print(responseJson.choices[1].text)
15 Likes

I will have a example game coming up soon!

1 Like

Are the generated texts filtered by any chance?

1 Like

While this may sounds good, this script was generated by OpenAI and there’s one main issue.
Namely that this wouldn’t work in a large game, it may works for a while but you’ll only be overusing your API.
Considering OpenAI is slow at times due to high traffic and whatnot, you’re better off writing your very own chat bot for your game.

1 Like

I got this error
image

You would need to do this yourself, the code sample provided does not do this by default albeit it would be very easy to implement.

1 Like

I will have my own version soon with a model that can handle lots of requests, hopefully done by march.

Remove the Content Type header and try it again, not sure if it will work tho.

1 Like

Already tried that. Still not working.

I can’t do it myself if it won’t allow me to use some stuff.

1 Like