go-openai README

README проекта с github.com/sashabaranov/go-openai. Одним файлом markdown: 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.

Building agents? Try Unreal Agent - Go-based, fully async harness that drives 40% cost savings compared to Codex!

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

Choose a model based on the workload's reasoning, latency, and cost requirements.

Constant Model ID Typical use
GPT6Dot2Astra gpt-6.2-astra Demanding reasoning and coding
GPT6Dot2Sol gpt-6.2-sol Everyday coding and agent workflows
GPT6Dot1Terra gpt-6.1-terra Visual reasoning, computer use, and writing
GPT6Dot1Sol gpt-6.1-sol Complex coding and professional work
GPT6Astra gpt-6-astra Most demanding reasoning and coding
GPT6Sol gpt-6-sol Previous Sol model
GPT6Luna gpt-6-luna Focused, high-volume work

GPT-6 models in the table support low, medium (default), high, xhigh, and max reasoning. GPT-6.1 Terra, GPT-6 Sol, and GPT-6 Luna also support none. Use Responses for tool calling with GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6.1 Sol, and GPT-6 Astra. GPT-6 Sol and GPT-6 Luna support Chat Completions function calling with reasoning_effort set to none. See GPT-6 guidance.

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)

Ищем в базе…

Что это такое?go-openai — неофициальная клиентская библиотека для Go, которая для API OpenAI. Она даёт разработчикам на Go типизированный доступ к генерации текста, чату, изображениям, аудио, эмбеддингам, модерации, дообучению, пакетной обработке (batches) и векторным хранилищам.
Это фреймворк или просто библиотека, которую я подключаю?Это обычная библиотека для Go, которую подключают командой go get. Никакого CLI или серверного компонента нет, только типизированные клиенты API для эмбеддингов, изображений, аудио, модерации, файлов, дообучения, пакетных заданий, векторных хранилищ и устаревшего Assistants API.
Как добавить её в мой проект на Go?Выполните go get, чтобы загрузить пакет, задайте ключ API OpenAI в виде переменной окружения, затем вызовите Responses API, чтобы создать ответ и прочитать его.
Нужен ли мне ключ API OpenAI и тянет ли библиотека другие библиотеки?Нужен собственный ключ API OpenAI, заданный в переменной окружения. Сам пакет не имеет зависимостей, поэтому не подтягивает сторонние пакеты.
Что лучше использовать: Chat Completions или более новый Responses API?Для новых интеграций генерации текста, рассуждений, вызова инструментов или многоходовых диалогов стоит начинать с Responses API. Chat Completions сохранён в основном для уже существующих интеграций, которые опираются на его структуру.
В чём разница между Responses API и Chat Completions в этом клиенте?Responses API рекомендуется для новых задач генерации текста, рассуждений, вызова инструментов и многоходовых диалогов. Он позволяет просматривать response.Output для мультимодальных результатов. Chat Completions в основном сохранён для интеграций, которые уже опираются на его формат запроса и ответа.
Можно ли направить этот клиент на Azure OpenAI вместо напрямую OpenAI?Да, начинаете с DefaultAzureConfig и настраиваете сопоставление развёртываний или версию API, которые требует ваш ресурс Azure.
Поддерживает ли клиент потоковый вывод?Да, Responses API поддерживает потоковую передачу. Так можно читать сгенерированный текст по мере поступления, а не ждать полного ответа.
Какие возможности, не связанные с чатом, предоставляет библиотека?Помимо чата и Responses API, она охватывает эмбеддинги, генерацию изображений, преобразование речи в текст, модерацию, загрузку файлов, задания дообучения, пакетные задания и векторные хранилища.
Какие есть похожие проекты?gpt4free, generative-ai-for-beginners, Hello-Python, ollama-python, unsloth, langchain4j, openai-node, mem0
Автор
sashabaranov
Размер
0.9 MB
Звёзды
10.8K
Возраст
6 г
Коммиты · 90 дней