RepoOpenAIOpenAIpublished Jul 22, 2024seen 6d

openai/openai-go

Go

Open original ↗

Captured source

source ↗
published Jul 22, 2024seen 6dcaptured 8hhttp 200method plain

openai/openai-go

Description: The official Go library for the OpenAI API

Language: Go

License: Apache-2.0

Stars: 3288

Forks: 325

Open issues: 166

Created: 2024-07-22T19:29:26Z

Pushed: 2026-06-05T16:49:41Z

Default branch: main

Fork: no

Archived: no

README:

OpenAI Go API Library

The OpenAI Go library provides convenient access to the OpenAI REST API from applications written in Go.

> [!WARNING] > The latest version of this package has small and limited breaking changes. > See the [changelog](CHANGELOG.md) for details.

Installation

import (
"github.com/openai/openai-go/v3" // imported as openai
)

Or to pin the version:

go get -u 'github.com/openai/openai-go/v3@v3.39.0'

Requirements

This library requires Go 1.22+.

Usage

The full API of this library can be found in [api.md](api.md).

The primary API for interacting with OpenAI models is the Responses API. You can generate text from the model with the code below.

package main

import (
"context"

"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)

func main() {
ctx := context.Background()
client := openai.NewClient(
option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("OPENAI_API_KEY")
)

question := "Write me a haiku about computers"

resp, err := client.Responses.New(ctx, responses.ResponseNewParams{
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(question)},
Model: openai.ChatModelGPT5_2,
})

if err != nil {
panic(err)
}

println(resp.OutputText())
}

Multi-turn Responses

response, err := client.Responses.New(ctx, responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("What is the capital of France?"),
},
})
if err != nil {
panic(err)
}
fmt.Println("First response:", response.OutputText())

// Use PreviousResponseID to continue the conversation
response, err = client.Responses.New(ctx, responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
PreviousResponseID: openai.String(response.ID),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("And what is the population of that city?"),
},
})
if err != nil {
panic(err)
}
fmt.Println("Second response:", response.OutputText())

Conversations

conv, err := client.Conversations.New(ctx, conversations.ConversationNewParams{})
if err != nil {
panic(err)
}
fmt.Println("Created conversation:", conv.ID)

response, err := client.Responses.New(ctx, responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Hello! Remember that my favorite color is blue."),
},
Conversation: responses.ResponseNewParamsConversationUnion{
OfConversationObject: &responses.ResponseConversationParam{
ID: conv.ID,
},
},
})
if err != nil {
panic(err)
}
fmt.Println("First response:", response.OutputText())

// Continue the conversation
response, err = client.Responses.New(ctx, responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("What is my favorite color?"),
},
Conversation: responses.ResponseNewParamsConversationUnion{
OfConversationObject: &responses.ResponseConversationParam{
ID: conv.ID,
},
},
})
if err != nil {
panic(err)
}
fmt.Println("Second response:", response.OutputText())

items, err := client.Conversations.Items.List(ctx, conv.ID, conversations.ItemListParams{})
if err != nil {
panic(err)
}
fmt.Println("Conversation has", len(items.Data), "items")

Streaming responses

ctx := context.Background()

stream := client.Responses.NewStreaming(ctx, responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Write a haiku about programming"),
},
})

for stream.Next() {
event := stream.Current()
print(event.Delta)
}

if stream.Err() != nil {
panic(stream.Err())
}

> See the [full streaming example](./examples/responses-streaming/main.go)

Tool calling

ctx := context.Background()

params := responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("What is the weather in New York City?"),
},
Tools: []responses.ToolUnionParam{{
OfFunction: &responses.FunctionToolParam{
Name: "get_weather",
Description: openai.String("Get weather at the given location"),
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]string{
"type": "string",
},
},
"required": []string{"location"},
},
},
}},
}

response, _ := client.Responses.New(ctx, params)

// Check for function calls in the response output
for _, item := range response.Output {
if item.Type == "function_call" {
toolCall := item.AsFunctionCall()
if toolCall.Name == "get_weather" {
// Extract arguments and call your function
var args map[string]any
json.Unmarshal([]byte(toolCall.Arguments), &args)
location := args["location"].(string)

// Simulate getting weather data
weatherData := getWeather(location)
fmt.Printf("Weather in %s: %s\n", location, weatherData)

// Continue conversation with function result
response, _ = client.Responses.New(ctx, responses.ResponseNewParams{
Model: openai.ChatModelGPT5_2,
PreviousResponseID: openai.String(response.ID),
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: []responses.ResponseInputItemUnionParam{{
OfFunctionCallOutput: &responses.ResponseInputItemFunctionCallOutputParam{
CallID: toolCall.CallID,
Output: responses.ResponseInputItemFunctionCallOutputOutputUnionParam{
OfString: openai.String(weatherData),
},
},
}},
},
})
}
}
}

Structured outputs

import (
"encoding/json"
"github.com/invopop/jsonschema"
// ...
)

// A struct that will be converted to a Structured Outputs response schema
type HistoricalComputer struct {
Origin Origin `json:"origin" jsonschema_description:"The origin of the computer"`
Name string `json:"full_name" jsonschema_description:"The name of the device model"`
Legacy string `json:"legacy" jsonschema:"enum=positive,enum=neutral,enum=negative" jsonschema_description:"Its influence on the field of computing"`
NotableFacts []string `json:"notable_facts" jsonschema_description:"A few key facts about the computer"`
}

type Origin struct {
YearBuilt int64…

Excerpt shown — open the source for the full document.

Notability

notability 8.0/10

OpenAI official Go client, 3k+ stars, notable launch