MCPcopy Index your code
hub / github.com/sashabaranov/go-openai

github.com/sashabaranov/go-openai @v1.41.2 sqlite

repository ↗ · DeepWiki ↗ · release v1.41.2 ↗
759 symbols 3,121 edges 90 files 241 documented · 32% 14 cross-repo links
README

Go OpenAI

Go Reference Go Report Card codecov

This library provides unofficial Go clients for OpenAI API. We support:

  • ChatGPT 4o, o1
  • GPT-3, GPT-4
  • DALL·E 2, DALL·E 3, GPT Image 1
  • Whisper

Installation

go get github.com/sashabaranov/go-openai

Currently, go-openai requires Go version 1.18 or greater.

Usage

ChatGPT example usage:

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

Getting an OpenAI API Key:

  1. Visit the OpenAI website at https://platform.openai.com/account/api-keys.
  2. If you don't have an account, click on "Sign Up" to create one. If you do, click "Log In".
  3. Once logged in, navigate to your API key management page.
  4. Click on "Create new secret key".
  5. Enter a name for your new key, then click "Create secret key".
  6. Your new API key will be displayed. Use this key to interact with the OpenAI API.

Note: Your API key is sensitive information. Do not share it with anyone.

Other examples:

ChatGPT streaming completion

package main

import (
    "context"
    "errors"
    "fmt"
    "io"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    c := openai.NewClient("your token")
    ctx := context.Background()

    req := openai.ChatCompletionRequest{
        Model:     openai.GPT3Dot5Turbo,
        MaxTokens: 20,
        Messages: []openai.ChatCompletionMessage{
            {
                Role:    openai.ChatMessageRoleUser,
                Content: "Lorem ipsum",
            },
        },
        Stream: true,
    }
    stream, err := c.CreateChatCompletionStream(ctx, req)
    if err != nil {
        fmt.Printf("ChatCompletionStream error: %v\n", err)
        return
    }
    defer stream.Close()

    fmt.Printf("Stream response: ")
    for {
        response, err := stream.Recv()
        if errors.Is(err, io.EOF) {
            fmt.Println("\nStream finished")
            return
        }

        if err != nil {
            fmt.Printf("\nStream error: %v\n", err)
            return
        }

        fmt.Printf(response.Choices[0].Delta.Content)
    }
}

GPT-3 completion

package main

import (
    "context"
    "fmt"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    c := openai.NewClient("your token")
    ctx := context.Background()

    req := openai.CompletionRequest{
        Model:     openai.GPT3Babbage002,
        MaxTokens: 5,
        Prompt:    "Lorem ipsum",
    }
    resp, err := c.CreateCompletion(ctx, req)
    if err != nil {
        fmt.Printf("Completion error: %v\n", err)
        return
    }
    fmt.Println(resp.Choices[0].Text)
}

GPT-3 streaming completion

package main

import (
    "errors"
    "context"
    "fmt"
    "io"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    c := openai.NewClient("your token")
    ctx := context.Background()

    req := openai.CompletionRequest{
        Model:     openai.GPT3Babbage002,
        MaxTokens: 5,
        Prompt:    "Lorem ipsum",
        Stream:    true,
    }
    stream, err := c.CreateCompletionStream(ctx, req)
    if err != nil {
        fmt.Printf("CompletionStream error: %v\n", err)
        return
    }
    defer stream.Close()

    for {
        response, err := stream.Recv()
        if errors.Is(err, io.EOF) {
            fmt.Println("Stream finished")
            return
        }

        if err != nil {
            fmt.Printf("Stream error: %v\n", err)
            return
        }


        fmt.Printf("Stream response: %v\n", response)
    }
}

Audio Speech-To-Text

package main

import (
    "context"
    "fmt"

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

func main() {
    c := openai.NewClient("your token")
    ctx := context.Background()

    req := openai.AudioRequest{
        Model:    openai.Whisper1,
        FilePath: "recording.mp3",
    }
    resp, err := c.CreateTranscription(ctx, req)
    if err != nil {
        fmt.Printf("Transcription error: %v\n", err)
        return
    }
    fmt.Println(resp.Text)
}

Audio Captions

package main

import (
    "context"
    "fmt"
    "os"

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

func main() {
    c := openai.NewClient(os.Getenv("OPENAI_KEY"))

    req := openai.AudioRequest{
        Model:    openai.Whisper1,
        FilePath: os.Args[1],
        Format:   openai.AudioResponseFormatSRT,
    }
    resp, err := c.CreateTranscription(context.Background(), req)
    if err != nil {
        fmt.Printf("Transcription error: %v\n", err)
        return
    }
    f, err := os.Create(os.Args[1] + ".srt")
    if err != nil {
        fmt.Printf("Could not open file: %v\n", err)
        return
    }
    defer f.Close()
    if _, err := f.WriteString(resp.Text); err != nil {
        fmt.Printf("Error writing to file: %v\n", err)
        return
    }
}

DALL-E 2 image generation

package main

import (
    "bytes"
    "context"
    "encoding/base64"
    "fmt"
    openai "github.com/sashabaranov/go-openai"
    "image/png"
    "os"
)

func main() {
    c := openai.NewClient("your token")
    ctx := context.Background()

    // Sample image by link
    reqUrl := openai.ImageRequest{
        Prompt:         "Parrot on a skateboard performs a trick, cartoon style, natural light, high detail",
        Size:           openai.CreateImageSize256x256,
        ResponseFormat: openai.CreateImageResponseFormatURL,
        N:              1,
    }

    respUrl, err := c.CreateImage(ctx, reqUrl)
    if err != nil {
        fmt.Printf("Image creation error: %v\n", err)
        return
    }
    fmt.Println(respUrl.Data[0].URL)

    // Example image as base64
    reqBase64 := openai.ImageRequest{
        Prompt:         "Portrait of a humanoid parrot in a classic costume, high detail, realistic light, unreal engine",
        Size:           openai.CreateImageSize256x256,
        ResponseFormat: openai.CreateImageResponseFormatB64JSON,
        N:              1,
    }

    respBase64, err := c.CreateImage(ctx, reqBase64)
    if err != nil {
        fmt.Printf("Image creation error: %v\n", err)
        return
    }

    imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON)
    if err != nil {
        fmt.Printf("Base64 decode error: %v\n", err)
        return
    }

    r := bytes.NewReader(imgBytes)
    imgData, err := png.Decode(r)
    if err != nil {
        fmt.Printf("PNG decode error: %v\n", err)
        return
    }

    file, err := os.Create("example.png")
    if err != nil {
        fmt.Printf("File creation error: %v\n", err)
        return
    }
    defer file.Close()

    if err := png.Encode(file, imgData); err != nil {
        fmt.Printf("PNG encode error: %v\n", err)
        return
    }

    fmt.Println("The image was saved as example.png")
}

GPT Image 1 image generation

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "os"

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

func main() {
    c := openai.NewClient("your token")
    ctx := context.Background()

    req := openai.ImageRequest{
        Prompt:            "Parrot on a skateboard performing a trick. Large bold text \"SKATE MASTER\" banner at the bottom of the image. Cartoon style, natural light, high detail, 1:1 aspect ratio.",
        Background:        openai.CreateImageBackgroundOpaque,
        Model:             openai.CreateImageModelGptImage1,
        Size:              openai.CreateImageSize1024x1024,
        N:                 1,
        Quality:           openai.CreateImageQualityLow,
        OutputCompression: 100,
        OutputFormat:      openai.CreateImageOutputFormatJPEG,
        // Moderation:       openai.CreateImageModerationLow,
        // User:                     "",
    }

    resp, err := c.CreateImage(ctx, req)
    if err != nil {
        fmt.Printf("Image creation Image generation with GPT Image 1error: %v\n", err)
        return
    }

    fmt.Println("Image Base64:", resp.Data[0].B64JSON)

    // Decode the base64 data
    imgBytes, err := base64.StdEncoding.DecodeString(resp.Data[0].B64JSON)
    if err != nil {
        fmt.Printf("Base64 decode error: %v\n", err)
        return
    }

    // Write image to file
    outputPath := "generated_image.jpg"
    err = os.WriteFile(outputPath, imgBytes, 0644)
    if err != nil {
        fmt.Printf("Failed to write image file: %v\n", err)
        return
    }

    fmt.Printf("The image was saved as %s\n", outputPath)
}

Configuring proxy

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)

See also: https://pkg.go.dev/github.com/sashabaranov/go-openai#ClientConfig

ChatGPT support context

package main

import (
    "bufio"
    "context"
    "fmt"
    "os"
    "strings"

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

func main() {
    client := openai.NewClient("your token")
    messages := make([]openai.ChatCompletionMessage, 0)
    reader := bufio.NewReader(os.Stdin)
    fmt.Println("Conversation")
    fmt.Println("---------------------")

    for {
        fmt.Print("-> ")
        text, _ := reader.ReadString('\n')
        // convert CRLF to LF
        text = strings.Replace(text, "\n", "", -1)
        messages = append(messages, openai.ChatCompletionMessage{
            Role:    openai.ChatMessageRoleUser,
            Content: text,
        })

        resp, err := client.CreateChatCompletion(
            context.Background(),
            openai.ChatCompletionRequest{
                Model:    openai.GPT3Dot5Turbo,
                Messages: messages,
            },
        )

        if err != nil {
            fmt.Printf("ChatCompletion error: %v\n", err)
            continue
        }

        content := resp.Choices[0].Message.Content
        messages = append(messages, openai.ChatCompletionMessage{
            Role:    openai.ChatMessageRoleAssistant,
            Content: content,
        })
        fmt.Println(content)
    }
}

Azure OpenAI ChatGPT

package main

import (
    "context"
    "fmt"

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

func main() {
    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)
    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: openai.GPT3Dot5Turbo,
            Messages: []openai.ChatCompletionMessage{
                {
                    Role:    openai.ChatMessageRoleUser,
                    Content: "Hello Azure OpenAI!",
                },
            },
        },
    )
    if err != nil {
        fmt.Printf("ChatCompletion error: %v\n", err)
        return
    }

    fmt.Println(resp.Choices[0].Message.Content)
}

Embedding Semantic Similarity

package main

import (
    "context"
    "log"
    openai "github.com/sashabaranov/go-openai"

)

func main() {
    client := openai.NewClient("your-token")

    // Create an EmbeddingRequest for the user query
    queryReq := openai.EmbeddingRequest{
        Input: []string{"How many chucks would a woodchuck chuck"},
        Model: openai.AdaEmbeddingV2,
    }

    // Create an embedding for the user query
    queryResponse, err := client.CreateEmbeddings(context.Background(), queryReq)
    if err != nil {
        log.Fatal("Error creating query embedding:", err)
    }

    // Create an EmbeddingRequest for the target text
    targetReq := openai.EmbeddingRequest{
        Input: []string{"How many chucks would a woodchuck chuck if the woodchuck could chuck wood"},
        Model: openai.AdaEmbeddingV2,
    }

    // Create an embedding for the target text
    targetResponse, err := client.CreateEmbeddings(context.Background(), targetReq)
    if err != nil {
        log.Fatal("Error creating target embedding:", err)
    }

    // Now that we have the embeddings for the user query and the target text, we
    // can calculate their similarity.
    queryEmbedding := queryResponse.Data[0]
    targetEmbedding := targetResponse.Data[0]

    similarity, err := queryEmbedding.DotProduct(&targetEmbedding)
    if err != nil {
        log.Fatal("Error calculating dot product:", err)
    }

    log.Printf("The similarity score between the query and the target is %f", similarity)
}

Azure OpenAI Embeddings

package main

import (
    "context"
    "fmt"

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

func main() {

    config := openai.DefaultAzureConfig("your Azure OpenAI Key", "https://your Azure OpenAI Endpoint")
    config.APIVersion = "2023-05-15" // optional update to latest API version

    //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]
    //}

    input := "Text to vectorize"

    client := openai.NewClientWithConfig(config)
    resp, err := client.CreateEmbeddings(
        context.Background(),
        openai.EmbeddingRequest{
            Input: []string{input},
            Model: openai.AdaEmbeddingV2,
        })

    if err != nil {
        fmt.Printf("CreateEmbeddings error: %v\n", err)
        return
    }

    vectors := resp.Data[0].Embedding // []float32 with 1536 dimensions

    fmt.Println(vectors[:10], "...", vectors[len(vectors)-10:])
}

JSON Schema for function cal

Extension points exported contracts — how you extend this code

BatchLineItem (Interface)
(no doc) [3 implementers]
batch.go
HTTPDoer (Interface)
upgrade to v2 to support vector store [1 implementers]
config.go
EmbeddingRequestConverter (Interface)
(no doc) [3 implementers]
embeddings.go
RequestBuilder (Interface)
(no doc) [3 implementers]
internal/request_builder.go
FormBuilder (Interface)
(no doc) [3 implementers]
internal/form_builder.go
Unmarshaler (Interface)
(no doc) [3 implementers]
internal/unmarshaler.go
Marshaller (Interface)
(no doc) [2 implementers]
internal/marshaller.go
ErrorAccumulator (Interface)
(no doc) [2 implementers]
internal/error_accumulator.go

Core symbols most depended-on inside this repo

NoError
called by 209
internal/test/checks/checks.go
RegisterHandler
called by 111
internal/test/server.go
Marshal
called by 110
internal/marshaller.go
fullURL
called by 82
client.go
newRequest
called by 80
client.go
sendRequest
called by 77
client.go
Error
called by 55
error.go
Close
called by 48
internal/form_builder.go

Shape

Function 294
Struct 225
Method 193
TypeAlias 31
Interface 11
FuncType 5

Languages

Go100%

Modules by API surface

chat.go40 symbols
client.go33 symbols
run.go32 symbols
batch.go26 symbols
chat_test.go25 symbols
vector_store.go24 symbols
assistant.go23 symbols
thread.go22 symbols
internal/form_builder_test.go20 symbols
embeddings.go19 symbols
messages.go17 symbols
chat_stream_test.go17 symbols

For agents

$ claude mcp add go-openai \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact