ChatGPT is like that cool, incredibly talented artist every band wants to collaborate with. When you need something extra, something that will give your application a bit of zing, that's where ChatGPT comes in. It's got that rhythm that gets feet tapping.
This guide will take you step-by-step on how to bring together the text-generating wizardry of ChatGPT with the simplicity and efficiency of Golang, opening up exciting new possibilities for crafting more intelligent applications.
Before getting in the weeds with the steps though, here is the complete code block to call ChatGPT within Golang and get a response.
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/go-resty/resty/v2"
)
const (
apiEndpoint = "https://api.openai.com/v1/chat/completions"
)
func main() {
// Use your API KEY here
apiKey := "YOUR API KEY HERE"
client := resty.New()
response, err := client.R().
SetAuthToken(apiKey).
SetHeader("Content-Type", "application/json").
SetBody(map[string]interface{}{
"model": "gpt-3.5-turbo",
"messages": []interface{}{map[string]interface{}{"role": "system", "content": "Hi can you tell me what is the factorial of 10?"}},
"max_tokens": 50,
}).
Post(apiEndpoint)
if err != nil {
log.Fatalf("Error while sending send the request: %v", err)
}
body := response.Body()
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
fmt.Println("Error while decoding JSON response:", err)
return
}
// Extract the content from the JSON response
content := data["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
fmt.Println(content)
}
Output:
PS D: \chatgpt go> go run chatgpt.go
Yes, the factorial of 10 is calculated as follows:
10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1
= 3,
PS D: \chatgpt go>
That’s all there is to it. Now let’s break down this code step by step.
Step 1: Sign up for an OpenAI API key
Go to https://beta.openai.com/signup to register for OpenAI API access. You will receive an API key after registering, which you will use to authenticate your queries.
Step 2: Set up the Go project
Create a new directory for your project and then launch the terminal or command prompt inside of it to set up the Go project. Start the new Go module by running the command below:
go mod init chatgpt-api
This will create a go.mod
file to manage your project dependencies.
Step 3: Install Resty
Since you’ll be sending HTTP queries to the ChatGPT API, you’ll need to install resty
. Run the command shown below to install it:
go get github.com/go-resty/resty/v2
Step 4: Import the necessary packages
Now over to your IDE. You’ll need to import four packages. Here’s what each does:
encoding/json
: Allows JSON encoding and decoding.fmt
: Provides formatted I/O functions.log
: Enables logging capabilities.github.com/go-resty/resty/v2
: A popular HTTP client library for Go.
import (
"encoding/json"
"fmt"
"log"
"github.com/go-resty/resty/v2"
)
Step 5: Define the constant apiEndpoint
The constant apiEndpoint is set to the URL of the OpenAI API endpoint.
const (
apiEndpoint = "https://api.openai.com/v1/chat/completions"
)
Step 6: Send a request
Now in the main() function:
- Put the OpenAI API key in a string variable
apiKey
. - Then create a new
Resty
client usingresty.New()
func main() {
// Use your API KEY here
apiKey := "YOUR API KEY HERE"
client := resty.New()
Then send an HTTP POST request to the OpenAI API:
- Make use of Resty client's
R()
method to create a new request. - Set the authentication token with
SetAuthToken(apiKey)
- Set the content type header as JSON with
SetHeader("Content-Type", "application/json")
. - Set the request body using a
map
that represents the payload. - A
map
that represents the payload is used to set the request body. - In the map, specify the model, messages, and max_tokens.
- Use
Post(apiEndpoint)
to send the request to the OpenAI API endpoint.
response, err := client.R().
SetAuthToken(apiKey).
SetHeader("Content-Type", "application/json").
SetBody(map[string]interface{}{
"model": "gpt-3.5-turbo",
"messages": []interface{}{map[string]interface{}{"role": "system", "content": "Hi can you tell me what is the factorial of 10?"}},
"max_tokens": 50,
}).
Post(apiEndpoint)
if err != nil {
log.Fatalf("Error while sending send the request: %v", err)
}
Step 7: Get and interpret the response
Make use of the Body()
function to get the response as a byte slice.
- Interpret the JSON response:
- Create an empty map
data
to store the decoded JSON data. - Use
json.Unmarshal()
to decode the response body into thedata
map. - Take the following information from the response:
- Access the
data
map'schoices
field, which contains a number of options. - The array's first element should be taken out and transformed into a map.
- Access the created content by going to the message field on the map.
- Obtain the generated response content as a string from the
content
field.
body := response.Body()
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
fmt.Println("Error while decoding JSON response:", err)
return
}
// Extract the content from the JSON response
content := data["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
Step 8: Output the response
You’re nearly done! Simply output ChatGPT's response at this point.
fmt.Println(content)
Congrats! You’ve integrated ChatGPT with Golang using the OpenAI API.
It’s important to note that although ChatGPT is magical, it does not have human-level intelligence. Responses shown to your users should always be properly vetted and tested before being used in a production context. Don’t expect ChatGPT to understand the physical world, use logic, be good at math, or check facts.
How to handle errors from the ChatGPT API
It's a best practice to monitor exceptions that occur when interacting with any external API. For example, the API might be temporarily unavailable, or the expected parameters or response format may have changed and you might need to update your code, and your code should be the thing to tell you about this. Here's how to integrate the Rollbar SDK with Golang to monitor exceptions:
package main
import (
"github.com/rollbar/rollbar-go"
)
func main() {
rollbar.SetToken("YOUR_ROLLBAR_ACCESS_TOKEN")
rollbar.SetEnvironment("production")
rollbar.SetServerRoot("github.com/your-organization/your-re
po")
rollbar.Info("Message body")
rollbar.WrapAndWait(someFunctionThatMayProduceError)
rollbar.Close()
}
func someFunctionThatMayProduceError() {
// Some code that will panic
}
Make sure you replace the YOUR_ROLLBAR_ACCESS_TOKEN
with your access token obtained from Rollbar.
To get your Rollbar access token, sign up for free and follow the instructions for Golang.
We can't wait to see what you build with ChatGPT. Happy coding!