go-openai README

The project's README from github.com/sashabaranov/go-openai. As one markdown file: README.md.

Go OpenAI

Go Reference codecov

An unofficial Go client for the OpenAI API.

For new text-generation, reasoning, tool-calling, and multi-turn integrations, start with the Responses API. Chat Completions remains available for existing integrations.

The client also covers embeddings, images, audio, moderation, files, fine-tuning, batches, vector stores, and legacy Assistants API surfaces.

Installation

go get github.com/sashabaranov/go-openai

Go OpenAI requires Go 1.18 or later.

Quick start: Responses API

Set an OpenAI API key in your environment:

export OPENAI_API_KEY="<your key>"

Then create a response and read its generated text:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

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

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))

	response, err := client.CreateResponse(context.Background(), openai.CreateResponseRequest{
		Model:        openai.GPT5Dot6Sol,
		Instructions: "You are a concise technical explainer.",
		Input:        "Why is the sky blue?",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(response.GetOutputText())
}

Input can be a string or a slice of typed input items. For reasoning, tools, multimodal output, or custom processing, inspect response.Output instead of using the GetOutputText convenience method.

Continue a conversation

Use PreviousResponseID when OpenAI should carry the earlier response context. Resend Instructions on each call when they should continue to apply.

store := true

first, err := client.CreateResponse(ctx, openai.CreateResponseRequest{
	Model:        openai.GPT5Dot6Sol,
	Instructions: "Answer as a travel guide.",
	Input:        "What should I see in Lisbon?",
	Store:        &store,
})
if err != nil {
	return err
}

second, err := client.CreateResponse(ctx, openai.CreateResponseRequest{
	Model:              openai.GPT5Dot6Sol,
	Instructions:       "Answer as a travel guide.",
	Input:              "Which one is best on a rainy day?",
	PreviousResponseID: first.ID,
	Store:              &store,
})
if err != nil {
	return err
}

fmt.Println(second.GetOutputText())

Stream output

stream, err := client.CreateResponseStream(ctx, openai.CreateResponseRequest{
	Model: openai.GPT5Dot6Sol,
	Input: "Write a short story about a curious gopher.",
})
if err != nil {
	return err
}
defer stream.Close()

for {
	event, err := stream.Recv()
	if errors.Is(err, io.EOF) {
		break
	}
	if err != nil {
		return err
	}
	if event.Type == openai.ResponseStreamEventOutputTextDelta {
		fmt.Print(event.Delta)
	}
}

Choosing a model

The current GPT-5.6 family exposes separate capability, balance, and efficiency tiers. Pick the tier that matches the workload instead of using the flagship for every request.

Constant Model ID Typical use
GPT5Dot6Sol gpt-5.6-sol Complex reasoning and coding
GPT5Dot6Terra gpt-5.6-terra Balance of intelligence and cost
GPT5Dot6Luna gpt-5.6-luna Cost-sensitive, high-volume work
GPT5Dot6 gpt-5.6 Family alias that currently routes to Sol

See the OpenAI model catalog for capabilities and availability. Model IDs are accepted as strings, so you can use a model before a named constant is added to this package.

Chat Completions

Chat Completions remains supported for existing integrations:

response, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
	Model: openai.GPT4oMini,
	Messages: []openai.ChatCompletionMessage{
		{
			Role:    openai.ChatMessageRoleUser,
			Content: "Hello!",
		},
	},
})
if err != nil {
	return err
}

fmt.Println(response.Choices[0].Message.Content)

For a new integration, prefer Responses unless you specifically need the Chat Completions request or response shape.

Configuration

Use DefaultConfig to customize the HTTP client, base URL, organization, or headers before constructing a client:

config := openai.DefaultConfig(os.Getenv("OPENAI_API_KEY"))
config.BaseURL = "https://your-compatible-endpoint.example/v1"
client := openai.NewClientWithConfig(config)

For Azure OpenAI, start with DefaultAzureConfig and configure the deployment mapping or API version required by your Azure resource.

Error handling

API failures can be inspected with errors.As:

var apiError *openai.APIError
if errors.As(err, &apiError) {
	fmt.Printf("OpenAI error: status=%d code=%v message=%s\n",
		apiError.HTTPStatusCode, apiError.Code, apiError.Message)
}

Examples

Runnable examples live in examples/:

To run one:

go run ./examples/responses

Contributing

See the contributing guidelines before opening a pull request.

Thank you

Thank you to all of the project's contributors and sponsors, including Carson Kahn of Spindle AI.

go-openai (sashabaranov/go-openai)

Searching Database…

10.8K ·GitHub
这是什么?go-openai 是一个面向 OpenAI API 的非官方 Go 客户端库,让 Go 开发者能够以强类型的方式调用文本生成、聊天、图像、音频、嵌入、内容审核、微调、批处理和向量存储等功能。
这是框架,还是只是一个我可以导入的库?它就是一个普通的 Go 库,通过 go get 引入即可。它没有命令行工具,也没有服务端组件,只提供强类型的 API 客户端,覆盖嵌入、图像、音频、内容审核、文件、微调、批处理、向量存储以及旧版 Assistants API。
我该怎么把它加到我的 Go 项目里?运行 go get 拉取这个包,把你的 OpenAI API 密钥设置为环境变量,然后调用 Responses API 来创建并读取一次响应。
我需要 OpenAI API 密钥吗?它会引入其他库吗?你需要自己的 OpenAI API 密钥,并将其设置为环境变量。这个包本身没有外部依赖,因此不会额外引入第三方包。
我应该用 Chat Completions 还是更新的 Responses API?对于新的文本生成、推理、工具调用或多轮对话集成,应优先使用 Responses API;Chat Completions 主要保留给已经依赖其结构的现有集成使用。
这个客户端里 Responses API 和 Chat Completions 有什么区别?对于新的文本生成、推理、工具调用和多轮对话任务,Responses API 是推荐的方式,它还允许你通过 response.Output 查看多模态结果;而 Chat Completions 主要保留给已经依赖其请求和响应结构的集成使用。
我能让这个客户端改为连接 Azure OpenAI,而不是直接连接 OpenAI 吗?可以。先使用 DefaultAzureConfig,然后配置 Azure 资源所需的部署映射或 API 版本。
这个客户端支持流式输出吗?支持。Responses API 支持流式传输,你可以边接收边读取生成的文本,而不必等待完整响应。
这个库还提供哪些非聊天功能?除了聊天和 Responses API 之外,它还涵盖嵌入、图像生成、语音转文字、内容审核、文件上传、微调任务、批处理和向量存储。
Size
0.9 MB
Stars
10.8K
Age
6y
Commits · 90 Days