How to Use the OpenAI API in Go

Web
Initialize the OpenAI client in Go with your API key and call CreateChatCompletion to generate text responses.

Use the official github.com/sashabaranov/go-openai library to initialize a client with your API key and call the CreateChatCompletion method.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/sashabaranov/go-openai"
)

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: openai.GPT3Dot5Turbo,
			Messages: []openai.ChatCompletionMessage{
				{Role: openai.ChatMessageRoleUser, Content: "Hello, world!"},
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Choices[0].Message.Content)
}