How to Call OpenAI API from Go

Web
Call the OpenAI API from Go using the sashabaranov/go-openai client library to send chat requests and receive text responses.

Use the github.com/sashabaranov/go-openai library to send HTTP requests to the OpenAI API with your API key.

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	client := openai.NewClient("YOUR_API_KEY")
	ctx := context.Background()

	resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
		Model: openai.GPT3Dot5Turbo,
		Messages: []openai.ChatCompletionMessage{
			{Role: openai.ChatMessageRoleUser, Content: "Hello!"},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Choices[0].Message.Content)
}