Overview of supported OpenAI models
masterThe go-openai library provides unofficial Go clients for various OpenAI API features, including:
- ChatGPT (4o, o1)
- GPT-3 and GPT-4
- DALL·E 2, DALL·E 3, and GPT Image 1
- Whisper
repository·master·Indexed 27 days ago
https://github.com/sashabaranov/go-openaiAn unofficial Go client library for the OpenAI API. It supports a wide range of models including ChatGPT (4o, o1), GPT-4, GPT-3, DALL·E (2, 3, and GPT Image 1), and Whisper. The library provides functionality for chat completions, streaming, text completions, audio transcription and translation, image generation, and management of OpenAI Assistants and their associated files and tools. It also includes support for Azure OpenAI configurations and structured outputs using JSON schema.
The go-openai library provides unofficial Go clients for various OpenAI API features, including:
To use Azure OpenAI, use openai.DefaultAzureConfig(apiKey, endpoint). You can also customize config.AzureModelMapperFunc if your deployment names differ from the standard model names.
config := openai.DefaultAzureConfig("your Azure OpenAI Key", "https://your Azure OpenAI Endpoint")
// If you use a deployment name different from the model name, you can customize the AzureModelMapperFunc function
// config.AzureModelMapperFunc = func(model string) string {
// azureModelMapping := map[string]string{
// "gpt-3.5-turbo": "your gpt-3.5-turbo deployment name",
// }
// return azureModelMapping[model]
// }
client := openai.NewClientWithConfig(config)To use a proxy, use openai.DefaultConfig to create a configuration, then set the HTTPClient field with a custom http.Client containing a configured http.Transport with your Proxy URL. Finally, initialize the client using openai.NewClientWithConfig(config).
config := openai.DefaultConfig("token")
proxyUrl, err := url.Parse("http://localhost:{port}")
if err != nil {
panic(err)
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
}
config.HTTPClient = &http.Client{
Transport: transport,
}
c := openai.NewClientWithConfig(config)Install the unofficial Go client for the OpenAI API using go get. This library requires Go version 1.18 or greater.
go get github.com/sashabaranov/go-openaiUse CreateBatchWithUploadFile to perform a two-step process: upload a .jsonl file containing multiple requests and immediately start a batch job using that file. This is the most convenient way to handle batch processing.
To prepare the file, use UploadBatchFileRequest and its helper methods like AddChatCompletion to populate the lines. Supported endpoints include:
BatchEndpointChatCompletions (/v1/chat/completions)BatchEndpointCompletions (/v1/completions)BatchEndpointEmbeddings (/v1/embeddings)NewClient for standard authentication or NewClientWithConfig for advanced configurations (such as custom base URLs, organization IDs, or specific API types like Azure).EmbeddingEncodingFormatBase64 in your request, the API returns data in a base64 format. The library provides EmbeddingResponseBase64 and a ToEmbeddingResponse() method to automatically decode these into standard EmbeddingResponse objects containing []float32 vectors.Use errors.As to check if an error is an *openai.APIError. You can then switch on the HTTPStatusCode to handle specific cases like 401 (invalid auth), 429 (rate limiting), or 500 (server error).
e := &openai.APIError{}
if errors.As(err, &e) {
switch e.HTTPStatusCode {
case 401:
// invalid auth or key (do not retry)
case 429:
// rate limiting or engine overload (wait and retry)
case 500:
// openai server error (retry)
default:
// unhandled
}
}go-openai library does not provide a built-in method for counting tokens. To count tokens for your requests, it is recommended to use a dedicated library such as tiktoken-go.In go-openai, setting the Temperature field to 0 may not work as expected because the omitempty JSON tag causes the field to be removed from the request, resulting in the OpenAI API applying its default value of 1.
To achieve behavior similar to a temperature of 0, use math.SmallestNonzeroFloat32 instead of 0 in the temperature field.
To enforce a specific JSON schema in chat completions, use the ResponseFormat field in ChatCompletionRequest. Set the type to openai.ChatCompletionResponseFormatTypeJSONSchema and provide a JSONSchema object. You can use the jsonschema package to generate schemas from Go structs.
package main
import (
"context"
"fmt"
"log"
"github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/jsonschema"
)
func main() {
client := openai.NewClient("your token")
ctx := context.Background()
type Result struct {
Steps []struct {
Explanation string `json:"explanation"`
Output string `json:"output"`
} `json:"steps"`
FinalAnswer string `json:"final_answer"`
}
var result Result
schema, err := jsonschema.GenerateSchemaForType(result)
if err != nil {
log.Fatalf("GenerateSchemaForType error: %v", err)
}
resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
Model: openai.GPT4oMini,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "You are a helpful math tutor. Guide the user through the solution step by step.",
},
{
Role: openai.ChatMessageRoleUser,
Content: "how can I solve 8x + 7 = -23",
},
},
ResponseFormat: &openai.ChatCompletionResponseFormat{
Type: openai.ChatCompletionResponseFormatTypeJSONSchema,
JSONSchema: &openai.ChatCompletionResponseFormatJSONSchema{
Name: "math_reasoning",
Schema: schema,
Strict: true,
},
},
})
if err != nil {
log.Fatalf("CreateChatCompletion error: %v", err)
}
err = schema.Unmarshal(resp.Choices[0].Message.Content, &result)
if err != nil {
log.Fatalf("Unmarshal schema error: %v", err)
}
fmt.Println(result)
}To interact with ChatGPT models, use the CreateChatCompletion method. You must provide a ChatCompletionRequest containing the model (e.g., openai.GPT3Dot5Turbo) and a slice of ChatCompletionMessage objects defining the conversation roles (e.g., openai.ChatMessageRoleUser).
package main
import (
"context"
"fmt"
openai "github.com/sashabaranov/go-openai"
)
func main() {
client := openai.NewClient("your token")
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Hello!",
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return
}
fmt.Println(resp.Choices[0].Message.Content)
}