go-openai

repository·master·Indexed 27 days ago

https://github.com/sashabaranov/go-openai

An 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.

Tokens
21.1K
Snippets
41
Records
148
Agent score
95%

What's inside go-openai

  1. Configure Azure OpenAI

    master

    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)
  2. Configure a Proxy for the OpenAI Client

    master

    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)
  3. Create a batch with an uploaded file

    master

    Use 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)
  4. Handle Base64 encoded embeddings

    master
    If you specify 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.
  5. Handle OpenAI API Errors

    master

    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
    	}
    }
  6. Achieve deterministic outputs with temperature 0

    master

    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.

  7. Generate Structured Outputs

    master

    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)
    }
  8. Use ChatGPT for Chat Completions

    master

    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)
    }