openai

package module
v1.42.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: Apache-2.0 Imports: 18 Imported by: 3,009

README

Go OpenAI

Go Reference Go Report Card 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.

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	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)
}
Example (Chatbot)
package main

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

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

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

	req := openai.ChatCompletionRequest{
		Model: openai.GPT3Dot5Turbo,
		Messages: []openai.ChatCompletionMessage{
			{
				Role:    openai.ChatMessageRoleSystem,
				Content: "you are a helpful chatbot",
			},
		},
	}
	fmt.Println("Conversation")
	fmt.Println("---------------------")
	fmt.Print("> ")
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		req.Messages = append(req.Messages, openai.ChatCompletionMessage{
			Role:    openai.ChatMessageRoleUser,
			Content: s.Text(),
		})
		resp, err := client.CreateChatCompletion(context.Background(), req)
		if err != nil {
			fmt.Printf("ChatCompletion error: %v\n", err)
			continue
		}
		fmt.Printf("%s\n\n", resp.Choices[0].Message.Content)
		req.Messages = append(req.Messages, resp.Choices[0].Message)
		fmt.Print("> ")
	}
}

Index

Examples

Constants

View Source
const (
	Whisper1               = "whisper-1"
	GPT4oTranscribe        = "gpt-4o-transcribe"
	GPT4oMiniTranscribe    = "gpt-4o-mini-transcribe"
	GPT4oTranscribeDiarize = "gpt-4o-transcribe-diarize"
	GPTTranscribe          = "gpt-transcribe"
)

Audio transcription models provided by OpenAI.

View Source
const (
	ChatMessageRoleSystem    = "system"
	ChatMessageRoleUser      = "user"
	ChatMessageRoleAssistant = "assistant"
	ChatMessageRoleFunction  = "function"
	ChatMessageRoleTool      = "tool"
	ChatMessageRoleDeveloper = "developer"
)

Chat message role defined by the OpenAI API.

View Source
const (
	O1Mini                  = "o1-mini"
	O1Mini20240912          = "o1-mini-2024-09-12"
	O1Preview               = "o1-preview"
	O1Preview20240912       = "o1-preview-2024-09-12"
	O1                      = "o1"
	O120241217              = "o1-2024-12-17"
	O3                      = "o3"
	O320250416              = "o3-2025-04-16"
	O3Mini                  = "o3-mini"
	O3Mini20250131          = "o3-mini-2025-01-31"
	O3Pro                   = "o3-pro"
	O3DeepResearch          = "o3-deep-research"
	O4Mini                  = "o4-mini"
	O4Mini20250416          = "o4-mini-2025-04-16"
	O4MiniDeepResearch      = "o4-mini-deep-research"
	GPT432K0613             = "gpt-4-32k-0613"
	GPT432K0314             = "gpt-4-32k-0314"
	GPT432K                 = "gpt-4-32k"
	GPT40613                = "gpt-4-0613"
	GPT40314                = "gpt-4-0314"
	GPT4o                   = "gpt-4o"
	GPT4o20240513           = "gpt-4o-2024-05-13"
	GPT4o20240806           = "gpt-4o-2024-08-06"
	GPT4o20241120           = "gpt-4o-2024-11-20"
	GPT4oLatest             = "chatgpt-4o-latest"
	GPT4oMini               = "gpt-4o-mini"
	GPT4oMini20240718       = "gpt-4o-mini-2024-07-18"
	GPT4Turbo               = "gpt-4-turbo"
	GPT4Turbo20240409       = "gpt-4-turbo-2024-04-09"
	GPT4Turbo0125           = "gpt-4-0125-preview"
	GPT4Turbo1106           = "gpt-4-1106-preview"
	GPT4TurboPreview        = "gpt-4-turbo-preview"
	GPT4VisionPreview       = "gpt-4-vision-preview"
	GPT4                    = "gpt-4"
	GPT4Dot1                = "gpt-4.1"
	GPT4Dot120250414        = "gpt-4.1-2025-04-14"
	GPT4Dot1Mini            = "gpt-4.1-mini"
	GPT4Dot1Mini20250414    = "gpt-4.1-mini-2025-04-14"
	GPT4Dot1Nano            = "gpt-4.1-nano"
	GPT4Dot1Nano20250414    = "gpt-4.1-nano-2025-04-14"
	GPT4Dot5Preview         = "gpt-4.5-preview"
	GPT4Dot5Preview20250227 = "gpt-4.5-preview-2025-02-27"
	GPT5                    = "gpt-5"
	GPT5Mini                = "gpt-5-mini"
	GPT5Nano                = "gpt-5-nano"
	GPT5Pro                 = "gpt-5-pro"
	GPT5ChatLatest          = "gpt-5-chat-latest"
	GPT5Codex               = "gpt-5-codex"
	GPT5Dot1                = "gpt-5.1"
	GPT5Dot1ChatLatest      = "gpt-5.1-chat-latest"
	GPT5Dot1Codex           = "gpt-5.1-codex"
	GPT5Dot1CodexMini       = "gpt-5.1-codex-mini"
	GPT5Dot1CodexMax        = "gpt-5.1-codex-max"
	GPT5Dot2                = "gpt-5.2"
	GPT5Dot2ChatLatest      = "gpt-5.2-chat-latest"
	GPT5Dot2Pro             = "gpt-5.2-pro"
	GPT5Dot2Codex           = "gpt-5.2-codex"
	GPT5Dot3ChatLatest      = "gpt-5.3-chat-latest"
	GPT5Dot3Codex           = "gpt-5.3-codex"
	GPT5Dot4                = "gpt-5.4"
	GPT5Dot4Mini            = "gpt-5.4-mini"
	GPT5Dot4Nano            = "gpt-5.4-nano"
	GPT5Dot4Pro             = "gpt-5.4-pro"
	GPT5Dot5                = "gpt-5.5"
	GPT5Dot5Pro             = "gpt-5.5-pro"
	GPT5Dot6                = "gpt-5.6"
	GPT5Dot6Sol             = "gpt-5.6-sol"
	GPT5Dot6Terra           = "gpt-5.6-terra"
	GPT5Dot6Luna            = "gpt-5.6-luna"
	GPT3Dot5Turbo0125       = "gpt-3.5-turbo-0125"
	GPT3Dot5Turbo1106       = "gpt-3.5-turbo-1106"
	GPT3Dot5Turbo0613       = "gpt-3.5-turbo-0613"
	GPT3Dot5Turbo0301       = "gpt-3.5-turbo-0301"
	GPT3Dot5Turbo16K        = "gpt-3.5-turbo-16k"
	GPT3Dot5Turbo16K0613    = "gpt-3.5-turbo-16k-0613"
	GPT3Dot5Turbo           = "gpt-3.5-turbo"
	GPT3Dot5TurboInstruct   = "gpt-3.5-turbo-instruct"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3TextDavinci003 = "text-davinci-003"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3TextDavinci002 = "text-davinci-002"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3TextCurie001 = "text-curie-001"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3TextBabbage001 = "text-babbage-001"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3TextAda001 = "text-ada-001"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3TextDavinci001 = "text-davinci-001"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3DavinciInstructBeta = "davinci-instruct-beta"
	// Deprecated: Model is shutdown. Use davinci-002 instead.
	GPT3Davinci    = "davinci"
	GPT3Davinci002 = "davinci-002"
	// Deprecated: Model is shutdown. Use gpt-3.5-turbo-instruct instead.
	GPT3CurieInstructBeta = "curie-instruct-beta"
	GPT3Curie             = "curie"
	GPT3Curie002          = "curie-002"
	// Deprecated: Model is shutdown. Use babbage-002 instead.
	GPT3Ada    = "ada"
	GPT3Ada002 = "ada-002"
	// Deprecated: Model is shutdown. Use babbage-002 instead.
	GPT3Babbage    = "babbage"
	GPT3Babbage002 = "babbage-002"
)

Text generation and reasoning models provided by OpenAI.

View Source
const (
	CodexCodeDavinci002 = "code-davinci-002"
	CodexCodeCushman001 = "code-cushman-001"
	CodexCodeDavinci001 = "code-davinci-001"
)

Codex Defines the models provided by OpenAI. These models are designed for code-specific tasks, and use a different tokenizer which optimizes for whitespace.

View Source
const (
	CreateImageSize256x256   = "256x256"
	CreateImageSize512x512   = "512x512"
	CreateImageSize1024x1024 = "1024x1024"

	// dall-e-3 supported only.
	CreateImageSize1792x1024 = "1792x1024"
	CreateImageSize1024x1792 = "1024x1792"

	// GPT Image models only.
	CreateImageSize1536x1024 = "1536x1024" // Landscape
	CreateImageSize1024x1536 = "1024x1536" // Portrait
)

Image sizes defined by the OpenAI API.

View Source
const (
	// dall-e-2 and dall-e-3 only.
	CreateImageResponseFormatB64JSON = "b64_json"
	CreateImageResponseFormatURL     = "url"
)
View Source
const (
	CreateImageModelDallE2             = "dall-e-2"
	CreateImageModelDallE3             = "dall-e-3"
	CreateImageModelGptImage1          = "gpt-image-1"
	CreateImageModelGptImage1Mini      = "gpt-image-1-mini"
	CreateImageModelGptImage1Dot5      = "gpt-image-1.5"
	CreateImageModelGptImage2          = "gpt-image-2"
	CreateImageModelChatGPTImageLatest = "chatgpt-image-latest"
)
View Source
const (
	CreateImageQualityHD       = "hd"
	CreateImageQualityStandard = "standard"

	// GPT Image models only.
	CreateImageQualityHigh   = "high"
	CreateImageQualityMedium = "medium"
	CreateImageQualityLow    = "low"
)
View Source
const (
	// dall-e-3 only.
	CreateImageStyleVivid   = "vivid"
	CreateImageStyleNatural = "natural"
)
View Source
const (
	// GPT Image models only.
	CreateImageBackgroundTransparent = "transparent"
	CreateImageBackgroundOpaque      = "opaque"
)
View Source
const (
	// GPT Image models only.
	CreateImageOutputFormatPNG  = "png"
	CreateImageOutputFormatJPEG = "jpeg"
	CreateImageOutputFormatWEBP = "webp"
)
View Source
const (
	ModerationOmniLatest   = "omni-moderation-latest"
	ModerationOmni20240926 = "omni-moderation-2024-09-26"
	ModerationTextStable   = "text-moderation-stable"
	ModerationTextLatest   = "text-moderation-latest"
	// Deprecated: use ModerationTextStable and ModerationTextLatest instead.
	ModerationText001 = "text-moderation-001"
)

The default is text-moderation-latest which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use text-moderation-stable, we will provide advanced notice before updating the model. Accuracy of text-moderation-stable may be slightly lower than for text-moderation-latest.

View Source
const (
	// TruncationStrategyAuto messages in the middle of the thread will be dropped to fit the context length of the model.
	TruncationStrategyAuto = TruncationStrategy("auto")
	// TruncationStrategyLastMessages the thread will be truncated to the n most recent messages in the thread.
	TruncationStrategyLastMessages = TruncationStrategy("last_messages")
)
View Source
const (
	AnthropicAPIVersion = "2023-06-01"
)
View Source
const AzureAPIKeyHeader = "api-key"
View Source
const (
	// GPT Image models only.
	CreateImageModerationLow = "low"
)

Variables

View Source
var (
	ErrChatCompletionInvalidModel       = errors.New("this model is not supported with this method, please use CreateCompletion client method instead") //nolint:lll
	ErrChatCompletionStreamNotSupported = errors.New("streaming is not supported with this method, please use CreateChatCompletionStream")              //nolint:lll
	ErrContentFieldsMisused             = errors.New("can't use both Content and MultiContent properties simultaneously")
)
View Source
var (
	// Deprecated: use ErrReasoningModelMaxTokensDeprecated instead.
	ErrO1MaxTokensDeprecated                   = errors.New("this model is not supported MaxTokens, please use MaxCompletionTokens")                               //nolint:lll
	ErrCompletionUnsupportedModel              = errors.New("this model is not supported with this method, please use CreateChatCompletion client method instead") //nolint:lll
	ErrCompletionStreamNotSupported            = errors.New("streaming is not supported with this method, please use CreateCompletionStream")                      //nolint:lll
	ErrCompletionRequestPromptTypeNotSupported = errors.New("the type of CompletionRequest.Prompt only supports string and []string")                              //nolint:lll
)
View Source
var (
	ErrO1BetaLimitationsMessageTypes = errors.New("this model has beta-limitations, user and assistant messages only, system messages are not supported")       //nolint:lll
	ErrO1BetaLimitationsTools        = errors.New("this model has beta-limitations, tools, function calling, and response format parameters are not supported") //nolint:lll
	// Deprecated: use ErrReasoningModelLimitations* instead.
	ErrO1BetaLimitationsLogprobs = errors.New("this model has beta-limitations, logprobs not supported")                                                                               //nolint:lll
	ErrO1BetaLimitationsOther    = errors.New("this model has beta-limitations, temperature, top_p and n are fixed at 1, while presence_penalty and frequency_penalty are fixed at 0") //nolint:lll
)
View Source
var (
	//nolint:lll
	ErrReasoningModelMaxTokensDeprecated = errors.New("this model is not supported MaxTokens, please use MaxCompletionTokens")
	ErrReasoningModelLimitationsLogprobs = errors.New("this model has beta-limitations, logprobs not supported")                                                                               //nolint:lll
	ErrReasoningModelLimitationsOther    = errors.New("this model has beta-limitations, temperature, top_p and n are fixed at 1, while presence_penalty and frequency_penalty are fixed at 0") //nolint:lll
)
View Source
var (
	ErrModerationInvalidModel = errors.New("this model is not supported with moderation, please use text-moderation-stable or text-moderation-latest instead") //nolint:lll
)
View Source
var ErrResponseStreamNotSupported = errors.New(
	"streaming is not supported with this method, please use CreateResponseStream",
)
View Source
var (
	ErrTooManyEmptyStreamMessages = errors.New("stream has sent too many empty messages")
)
View Source
var ErrVectorLengthMismatch = errors.New("vector length mismatch")

Functions

func WrapReader added in v1.40.2

func WrapReader(rdr io.Reader, filename string, contentType string) io.Reader

WrapReader wraps an io.Reader with filename and Content-type.

Types

type APIError

type APIError struct {
	Code           any         `json:"code,omitempty"`
	Message        string      `json:"message"`
	Param          *string     `json:"param,omitempty"`
	Type           string      `json:"type"`
	HTTPStatus     string      `json:"-"`
	HTTPStatusCode int         `json:"-"`
	InnerError     *InnerError `json:"innererror,omitempty"`
}

APIError provides error information returned by the OpenAI API. InnerError struct is only valid for Azure OpenAI Service.

Example

Open-AI maintains clear documentation on how to handle API errors.

see: https://platform.openai.com/docs/guides/error-codes/api-errors

package main

import (
	"errors"

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

func main() {
	var err error // Assume this is the error you are checking.
	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
		}
	}
}

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) UnmarshalJSON added in v1.8.0

func (e *APIError) UnmarshalJSON(data []byte) (err error)

type APIType added in v1.6.0

type APIType string
const (
	APITypeOpenAI          APIType = "OPEN_AI"
	APITypeAzure           APIType = "AZURE"
	APITypeAzureAD         APIType = "AZURE_AD"
	APITypeCloudflareAzure APIType = "CLOUDFLARE_AZURE"
	APITypeAnthropic       APIType = "ANTHROPIC"
)

type Assistant added in v1.17.0

type Assistant struct {
	ID             string                 `json:"id"`
	Object         string                 `json:"object"`
	CreatedAt      int64                  `json:"created_at"`
	Name           *string                `json:"name,omitempty"`
	Description    *string                `json:"description,omitempty"`
	Model          string                 `json:"model"`
	Instructions   *string                `json:"instructions,omitempty"`
	Tools          []AssistantTool        `json:"tools"`
	ToolResources  *AssistantToolResource `json:"tool_resources,omitempty"`
	FileIDs        []string               `json:"file_ids,omitempty"` // Deprecated in v2
	Metadata       map[string]any         `json:"metadata,omitempty"`
	Temperature    *float32               `json:"temperature,omitempty"`
	TopP           *float32               `json:"top_p,omitempty"`
	ResponseFormat any                    `json:"response_format,omitempty"`
	// contains filtered or unexported fields
}

func (*Assistant) GetRateLimitHeaders added in v1.17.0

func (h *Assistant) GetRateLimitHeaders() RateLimitHeaders

func (*Assistant) Header added in v1.17.0

func (h *Assistant) Header() http.Header

func (*Assistant) SetHeader added in v1.17.0

func (h *Assistant) SetHeader(header http.Header)

type AssistantDeleteResponse added in v1.17.3

type AssistantDeleteResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

func (*AssistantDeleteResponse) GetRateLimitHeaders added in v1.17.3

func (h *AssistantDeleteResponse) GetRateLimitHeaders() RateLimitHeaders

func (*AssistantDeleteResponse) Header added in v1.17.3

func (h *AssistantDeleteResponse) Header() http.Header

func (*AssistantDeleteResponse) SetHeader added in v1.17.3

func (h *AssistantDeleteResponse) SetHeader(header http.Header)

type AssistantFile added in v1.17.0

type AssistantFile struct {
	ID          string `json:"id"`
	Object      string `json:"object"`
	CreatedAt   int64  `json:"created_at"`
	AssistantID string `json:"assistant_id"`
	// contains filtered or unexported fields
}

func (*AssistantFile) GetRateLimitHeaders added in v1.17.0

func (h *AssistantFile) GetRateLimitHeaders() RateLimitHeaders

func (*AssistantFile) Header added in v1.17.0

func (h *AssistantFile) Header() http.Header

func (*AssistantFile) SetHeader added in v1.17.0

func (h *AssistantFile) SetHeader(header http.Header)

type AssistantFileRequest added in v1.17.0

type AssistantFileRequest struct {
	FileID string `json:"file_id"`
}

type AssistantFilesList added in v1.17.0

type AssistantFilesList struct {
	AssistantFiles []AssistantFile `json:"data"`
	// contains filtered or unexported fields
}

func (*AssistantFilesList) GetRateLimitHeaders added in v1.17.0

func (h *AssistantFilesList) GetRateLimitHeaders() RateLimitHeaders

func (*AssistantFilesList) Header added in v1.17.0

func (h *AssistantFilesList) Header() http.Header

func (*AssistantFilesList) SetHeader added in v1.17.0

func (h *AssistantFilesList) SetHeader(header http.Header)

type AssistantRequest added in v1.17.0

type AssistantRequest struct {
	Model          string                 `json:"model"`
	Name           *string                `json:"name,omitempty"`
	Description    *string                `json:"description,omitempty"`
	Instructions   *string                `json:"instructions,omitempty"`
	Tools          []AssistantTool        `json:"-"`
	FileIDs        []string               `json:"file_ids,omitempty"`
	Metadata       map[string]any         `json:"metadata,omitempty"`
	ToolResources  *AssistantToolResource `json:"tool_resources,omitempty"`
	ResponseFormat any                    `json:"response_format,omitempty"`
	Temperature    *float32               `json:"temperature,omitempty"`
	TopP           *float32               `json:"top_p,omitempty"`
}

AssistantRequest provides the assistant request parameters. When modifying the tools the API functions as the following: If Tools is undefined, no changes are made to the Assistant's tools. If Tools is empty slice it will effectively delete all of the Assistant's tools. If Tools is populated, it will replace all of the existing Assistant's tools with the provided tools.

func (AssistantRequest) MarshalJSON added in v1.20.4

func (a AssistantRequest) MarshalJSON() ([]byte, error)

MarshalJSON provides a custom marshaller for the assistant request to handle the API use cases If Tools is nil, the field is omitted from the JSON. If Tools is an empty slice, it's included in the JSON as an empty array ([]). If Tools is populated, it's included in the JSON with the elements.

type AssistantTool added in v1.17.0

type AssistantTool struct {
	Type     AssistantToolType   `json:"type"`
	Function *FunctionDefinition `json:"function,omitempty"`
}

type AssistantToolCodeInterpreter added in v1.17.0

type AssistantToolCodeInterpreter struct {
	FileIDs []string `json:"file_ids"`
}

type AssistantToolFileSearch added in v1.26.0

type AssistantToolFileSearch struct {
	VectorStoreIDs []string `json:"vector_store_ids"`
}

type AssistantToolResource added in v1.26.0

type AssistantToolResource struct {
	FileSearch      *AssistantToolFileSearch      `json:"file_search,omitempty"`
	CodeInterpreter *AssistantToolCodeInterpreter `json:"code_interpreter,omitempty"`
}

type AssistantToolType added in v1.17.3

type AssistantToolType string
const (
	AssistantToolTypeCodeInterpreter AssistantToolType = "code_interpreter"
	AssistantToolTypeRetrieval       AssistantToolType = "retrieval"
	AssistantToolTypeFunction        AssistantToolType = "function"
	AssistantToolTypeFileSearch      AssistantToolType = "file_search"
)

type AssistantsList added in v1.17.0

type AssistantsList struct {
	Assistants []Assistant `json:"data"`
	LastID     *string     `json:"last_id"`
	FirstID    *string     `json:"first_id"`
	HasMore    bool        `json:"has_more"`
	// contains filtered or unexported fields
}

AssistantsList is a list of assistants.

func (*AssistantsList) GetRateLimitHeaders added in v1.17.0

func (h *AssistantsList) GetRateLimitHeaders() RateLimitHeaders

func (*AssistantsList) Header added in v1.17.0

func (h *AssistantsList) Header() http.Header

func (*AssistantsList) SetHeader added in v1.17.0

func (h *AssistantsList) SetHeader(header http.Header)

type AudioRequest

type AudioRequest struct {
	Model string

	// FilePath is either an existing file in your filesystem or a filename representing the contents of Reader.
	FilePath string

	// Reader is an optional io.Reader when you do not want to use an existing file.
	Reader io.Reader

	Prompt                 string
	Temperature            float32
	Language               string // Only for transcription.
	Format                 AudioResponseFormat
	TimestampGranularities []TranscriptionTimestampGranularity // Only for transcription.

	// ChunkingStrategy controls how the audio is split before processing. Diarization models
	// such as gpt-4o-transcribe-diarize require it on longer audio, otherwise the API rejects
	// the request. Pass the string "auto" or a TranscriptionChunkingStrategy. Only for transcription.
	ChunkingStrategy any
}

AudioRequest represents a request structure for audio API.

func (AudioRequest) HasJSONResponse added in v1.9.1

func (r AudioRequest) HasJSONResponse() bool

HasJSONResponse returns true if the response format is JSON.

type AudioResponse

type AudioResponse struct {
	Task     string  `json:"task"`
	Language string  `json:"language"`
	Duration float64 `json:"duration"`
	Segments []struct {
		ID               int     `json:"id"`
		Seek             int     `json:"seek"`
		Start            float64 `json:"start"`
		End              float64 `json:"end"`
		Text             string  `json:"text"`
		Tokens           []int   `json:"tokens"`
		Temperature      float64 `json:"temperature"`
		AvgLogprob       float64 `json:"avg_logprob"`
		CompressionRatio float64 `json:"compression_ratio"`
		NoSpeechProb     float64 `json:"no_speech_prob"`
		Transient        bool    `json:"transient"`
	} `json:"segments"`
	Words []struct {
		Word  string  `json:"word"`
		Start float64 `json:"start"`
		End   float64 `json:"end"`
	} `json:"words"`
	Text string `json:"text"`
	// contains filtered or unexported fields
}

AudioResponse represents a response structure for audio API.

func (*AudioResponse) GetRateLimitHeaders added in v1.16.0

func (h *AudioResponse) GetRateLimitHeaders() RateLimitHeaders

func (*AudioResponse) Header added in v1.16.0

func (h *AudioResponse) Header() http.Header

func (*AudioResponse) SetHeader added in v1.16.0

func (h *AudioResponse) SetHeader(header http.Header)

type AudioResponseFormat added in v1.9.1

type AudioResponseFormat string

Response formats; Whisper uses AudioResponseFormatJSON by default.

const (
	AudioResponseFormatJSON        AudioResponseFormat = "json"
	AudioResponseFormatText        AudioResponseFormat = "text"
	AudioResponseFormatSRT         AudioResponseFormat = "srt"
	AudioResponseFormatVerboseJSON AudioResponseFormat = "verbose_json"
	AudioResponseFormatVTT         AudioResponseFormat = "vtt"
)

type Base64Embedding added in v1.15.3

type Base64Embedding struct {
	Object    string       `json:"object"`
	Embedding base64String `json:"embedding"`
	Index     int          `json:"index"`
}

Base64Embedding is a container for base64 encoded embeddings.

type Batch added in v1.25.0

type Batch struct {
	ID       string        `json:"id"`
	Object   string        `json:"object"`
	Endpoint BatchEndpoint `json:"endpoint"`
	Errors   *struct {
		Object string `json:"object,omitempty"`
		Data   []struct {
			Code    string  `json:"code,omitempty"`
			Message string  `json:"message,omitempty"`
			Param   *string `json:"param,omitempty"`
			Line    *int    `json:"line,omitempty"`
		} `json:"data"`
	} `json:"errors"`
	InputFileID      string             `json:"input_file_id"`
	CompletionWindow string             `json:"completion_window"`
	Status           string             `json:"status"`
	OutputFileID     *string            `json:"output_file_id"`
	ErrorFileID      *string            `json:"error_file_id"`
	CreatedAt        int                `json:"created_at"`
	InProgressAt     *int               `json:"in_progress_at"`
	ExpiresAt        *int               `json:"expires_at"`
	FinalizingAt     *int               `json:"finalizing_at"`
	CompletedAt      *int               `json:"completed_at"`
	FailedAt         *int               `json:"failed_at"`
	ExpiredAt        *int               `json:"expired_at"`
	CancellingAt     *int               `json:"cancelling_at"`
	CancelledAt      *int               `json:"cancelled_at"`
	RequestCounts    BatchRequestCounts `json:"request_counts"`
	Metadata         map[string]any     `json:"metadata"`
}

type BatchChatCompletionRequest added in v1.25.0

type BatchChatCompletionRequest struct {
	CustomID string                `json:"custom_id"`
	Body     ChatCompletionRequest `json:"body"`
	Method   string                `json:"method"`
	URL      BatchEndpoint         `json:"url"`
}

func (BatchChatCompletionRequest) MarshalBatchLineItem added in v1.25.0

func (r BatchChatCompletionRequest) MarshalBatchLineItem() []byte

type BatchCompletionRequest added in v1.25.0

type BatchCompletionRequest struct {
	CustomID string            `json:"custom_id"`
	Body     CompletionRequest `json:"body"`
	Method   string            `json:"method"`
	URL      BatchEndpoint     `json:"url"`
}

func (BatchCompletionRequest) MarshalBatchLineItem added in v1.25.0

func (r BatchCompletionRequest) MarshalBatchLineItem() []byte

type BatchEmbeddingRequest added in v1.25.0

type BatchEmbeddingRequest struct {
	CustomID string           `json:"custom_id"`
	Body     EmbeddingRequest `json:"body"`
	Method   string           `json:"method"`
	URL      BatchEndpoint    `json:"url"`
}

func (BatchEmbeddingRequest) MarshalBatchLineItem added in v1.25.0

func (r BatchEmbeddingRequest) MarshalBatchLineItem() []byte

type BatchEndpoint added in v1.25.0

type BatchEndpoint string
const (
	BatchEndpointChatCompletions BatchEndpoint = "/v1/chat/completions"
	BatchEndpointCompletions     BatchEndpoint = "/v1/completions"
	BatchEndpointEmbeddings      BatchEndpoint = "/v1/embeddings"
	BatchEndpointResponses       BatchEndpoint = "/v1/responses"
)

type BatchLineItem added in v1.25.0

type BatchLineItem interface {
	MarshalBatchLineItem() []byte
}

type BatchRequestCounts added in v1.25.0

type BatchRequestCounts struct {
	Total     int `json:"total"`
	Completed int `json:"completed"`
	Failed    int `json:"failed"`
}

type BatchResponse added in v1.25.0

type BatchResponse struct {
	Batch
	// contains filtered or unexported fields
}

func (*BatchResponse) GetRateLimitHeaders added in v1.25.0

func (h *BatchResponse) GetRateLimitHeaders() RateLimitHeaders

func (*BatchResponse) Header added in v1.25.0

func (h *BatchResponse) Header() http.Header

func (*BatchResponse) SetHeader added in v1.25.0

func (h *BatchResponse) SetHeader(header http.Header)

type BatchResponseRequest added in v1.42.0

type BatchResponseRequest struct {
	CustomID string                `json:"custom_id"`
	Body     CreateResponseRequest `json:"body"`
	Method   string                `json:"method"`
	URL      BatchEndpoint         `json:"url"`
}

func (BatchResponseRequest) MarshalBatchLineItem added in v1.42.0

func (r BatchResponseRequest) MarshalBatchLineItem() []byte

type ChatCompletionChoice

type ChatCompletionChoice struct {
	Index   int                   `json:"index"`
	Message ChatCompletionMessage `json:"message"`
	// FinishReason
	// stop: API returned complete message,
	// or a message terminated by one of the stop sequences provided via the stop parameter
	// length: Incomplete model output due to max_tokens parameter or token limit
	// function_call: The model decided to call a function
	// content_filter: Omitted content due to a flag from our content filters
	// null: API response still in progress or incomplete
	FinishReason         FinishReason         `json:"finish_reason"`
	LogProbs             *LogProbs            `json:"logprobs,omitempty"`
	ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
}

type ChatCompletionMessage

type ChatCompletionMessage struct {
	Role         string `json:"role"`
	Content      string `json:"content,omitempty"`
	Refusal      string `json:"refusal,omitempty"`
	MultiContent []ChatMessagePart

	// This property isn't in the official documentation, but it's in
	// the documentation for the official library for python:
	// - https://github.com/openai/openai-python/blob/main/chatml.md
	// - https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
	Name string `json:"name,omitempty"`

	// This property is used for the "reasoning" feature supported by deepseek-reasoner
	// which is not in the official documentation.
	// the doc from deepseek:
	// - https://api-docs.deepseek.com/api/create-chat-completion#responses
	ReasoningContent string `json:"reasoning_content,omitempty"`

	FunctionCall *FunctionCall `json:"function_call,omitempty"`

	// For Role=assistant prompts this may be set to the tool calls generated by the model, such as function calls.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`

	// For Role=tool prompts this should be set to the ID given in the assistant's prior request to call a tool.
	ToolCallID string `json:"tool_call_id,omitempty"`
}

func (ChatCompletionMessage) MarshalJSON added in v1.17.9

func (m ChatCompletionMessage) MarshalJSON() ([]byte, error)

func (*ChatCompletionMessage) UnmarshalJSON added in v1.17.9

func (m *ChatCompletionMessage) UnmarshalJSON(bs []byte) error

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model    string                  `json:"model"`
	Messages []ChatCompletionMessage `json:"messages"`
	// MaxTokens The maximum number of tokens that can be generated in the chat completion.
	// This value can be used to control costs for text generated via API.
	//
	// Deprecated: use MaxCompletionTokens. Not compatible with o1-series models.
	// refs: https://platform.openai.com/docs/api-reference/chat/create#chat-create-max_tokens
	MaxTokens int `json:"max_tokens,omitempty"`
	// MaxCompletionTokens An upper bound for the number of tokens that can be generated for a completion,
	// including visible output tokens and reasoning tokens https://platform.openai.com/docs/guides/reasoning
	MaxCompletionTokens int                           `json:"max_completion_tokens,omitempty"`
	Temperature         float32                       `json:"temperature,omitempty"`
	TopP                float32                       `json:"top_p,omitempty"`
	N                   int                           `json:"n,omitempty"`
	Stream              bool                          `json:"stream"`
	Stop                []string                      `json:"stop,omitempty"`
	PresencePenalty     float32                       `json:"presence_penalty,omitempty"`
	ResponseFormat      *ChatCompletionResponseFormat `json:"response_format,omitempty"`
	Seed                *int                          `json:"seed,omitempty"`
	FrequencyPenalty    float32                       `json:"frequency_penalty,omitempty"`
	// LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a word string.
	// incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}`
	// refs: https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias
	LogitBias map[string]int `json:"logit_bias,omitempty"`
	// LogProbs indicates whether to return log probabilities of the output tokens or not.
	// If true, returns the log probabilities of each output token returned in the content of message.
	// This option is currently not available on the gpt-4-vision-preview model.
	LogProbs bool `json:"logprobs,omitempty"`
	// TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to return at each
	// token position, each with an associated log probability.
	// logprobs must be set to true if this parameter is used.
	TopLogProbs int    `json:"top_logprobs,omitempty"`
	User        string `json:"user,omitempty"`
	// Deprecated: use Tools instead.
	Functions []FunctionDefinition `json:"functions,omitempty"`
	// Deprecated: use ToolChoice instead.
	FunctionCall any    `json:"function_call,omitempty"`
	Tools        []Tool `json:"tools,omitempty"`
	// This can be either a string or an ToolChoice object.
	ToolChoice any `json:"tool_choice,omitempty"`
	// Options for streaming response. Only set this when you set stream: true.
	StreamOptions *StreamOptions `json:"stream_options,omitempty"`
	// Disable the default behavior of parallel tool calls by setting it: false.
	ParallelToolCalls any `json:"parallel_tool_calls,omitempty"`
	// Store can be set to true to store the output of this completion request for use in distillations and evals.
	// https://platform.openai.com/docs/api-reference/chat/create#chat-create-store
	Store bool `json:"store,omitempty"`
	// Controls effort on reasoning for reasoning models. It can be set to "low", "medium", or "high".
	ReasoningEffort string `json:"reasoning_effort,omitempty"`
	// Metadata to store with the completion.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Configuration for a predicted output.
	Prediction *Prediction `json:"prediction,omitempty"`
	// ChatTemplateKwargs provides a way to add non-standard parameters to the request body.
	// Additional kwargs to pass to the template renderer. Will be accessible by the chat template.
	// Such as think mode for qwen3. "chat_template_kwargs": {"enable_thinking": false}
	// https://qwen.readthedocs.io/en/latest/deployment/vllm.html#thinking-non-thinking-modes
	ChatTemplateKwargs map[string]any `json:"chat_template_kwargs,omitempty"`
	// Specifies the latency tier to use for processing the request.
	ServiceTier ServiceTier `json:"service_tier,omitempty"`
	// Verbosity determines how many output tokens are generated. Lowering the number of
	// tokens reduces overall latency. It can be set to "low", "medium", or "high".
	// Note: This field is only confirmed to work with gpt-5, gpt-5-mini and gpt-5-nano.
	// Also, it is not in the API reference of chat completion at the time of writing,
	// though it is supported by the API.
	Verbosity string `json:"verbosity,omitempty"`
	// A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.
	// The IDs should be a string that uniquely identifies each user.
	// We recommend hashing their username or email address, in order to avoid sending us any identifying information.
	// https://platform.openai.com/docs/api-reference/chat/create#chat_create-safety_identifier
	SafetyIdentifier string `json:"safety_identifier,omitempty"`
	// Embedded struct for non-OpenAI extensions
	ChatCompletionRequestExtensions
}

ChatCompletionRequest represents a request structure for chat completion API.

type ChatCompletionRequestExtensions added in v1.41.0

type ChatCompletionRequestExtensions struct {
	// GuidedChoice is a vLLM-specific extension that restricts the model's output
	// to one of the predefined string choices provided in this field. This feature
	// is used to constrain the model's responses to a controlled set of options,
	// ensuring predictable and consistent outputs in scenarios where specific
	// choices are required.
	GuidedChoice []string `json:"guided_choice,omitempty"`
}

ChatCompletionRequestExtensions contains third-party OpenAI API extensions (e.g., vendor-specific implementations like vLLM).

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID                  string                 `json:"id"`
	Object              string                 `json:"object"`
	Created             int64                  `json:"created"`
	Model               string                 `json:"model"`
	Choices             []ChatCompletionChoice `json:"choices"`
	Usage               Usage                  `json:"usage"`
	SystemFingerprint   string                 `json:"system_fingerprint"`
	PromptFilterResults []PromptFilterResult   `json:"prompt_filter_results,omitempty"`
	ServiceTier         ServiceTier            `json:"service_tier,omitempty"`
	// contains filtered or unexported fields
}

ChatCompletionResponse represents a response structure for chat completion API.

func (*ChatCompletionResponse) GetRateLimitHeaders added in v1.16.0

func (h *ChatCompletionResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ChatCompletionResponse) Header added in v1.16.0

func (h *ChatCompletionResponse) Header() http.Header

func (*ChatCompletionResponse) SetHeader added in v1.16.0

func (h *ChatCompletionResponse) SetHeader(header http.Header)

type ChatCompletionResponseFormat added in v1.17.0

type ChatCompletionResponseFormat struct {
	Type       ChatCompletionResponseFormatType        `json:"type,omitempty"`
	JSONSchema *ChatCompletionResponseFormatJSONSchema `json:"json_schema,omitempty"`
}

type ChatCompletionResponseFormatJSONSchema added in v1.28.0

type ChatCompletionResponseFormatJSONSchema struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Schema      json.Marshaler `json:"schema"`
	Strict      bool           `json:"strict"`
}

func (*ChatCompletionResponseFormatJSONSchema) UnmarshalJSON added in v1.40.4

func (r *ChatCompletionResponseFormatJSONSchema) UnmarshalJSON(data []byte) error

type ChatCompletionResponseFormatType added in v1.17.0

type ChatCompletionResponseFormatType string
const (
	ChatCompletionResponseFormatTypeJSONObject ChatCompletionResponseFormatType = "json_object"
	ChatCompletionResponseFormatTypeJSONSchema ChatCompletionResponseFormatType = "json_schema"
	ChatCompletionResponseFormatTypeText       ChatCompletionResponseFormatType = "text"
)

type ChatCompletionStream

type ChatCompletionStream struct {
	// contains filtered or unexported fields
}

ChatCompletionStream Note: Perhaps it is more elegant to abstract Stream using generics.

func (ChatCompletionStream) Close

func (stream ChatCompletionStream) Close() error

func (ChatCompletionStream) Recv

func (stream ChatCompletionStream) Recv() (response T, err error)

func (ChatCompletionStream) RecvRaw added in v1.36.0

func (stream ChatCompletionStream) RecvRaw() ([]byte, error)

type ChatCompletionStreamChoice

type ChatCompletionStreamChoice struct {
	Index                int                                 `json:"index"`
	Delta                ChatCompletionStreamChoiceDelta     `json:"delta"`
	Logprobs             *ChatCompletionStreamChoiceLogprobs `json:"logprobs,omitempty"`
	FinishReason         FinishReason                        `json:"finish_reason"`
	ContentFilterResults ContentFilterResults                `json:"content_filter_results,omitempty"`
}

type ChatCompletionStreamChoiceDelta

type ChatCompletionStreamChoiceDelta struct {
	Content      string        `json:"content,omitempty"`
	Role         string        `json:"role,omitempty"`
	FunctionCall *FunctionCall `json:"function_call,omitempty"`
	ToolCalls    []ToolCall    `json:"tool_calls,omitempty"`
	Refusal      string        `json:"refusal,omitempty"`

	// This property is used for the "reasoning" feature supported by deepseek-reasoner
	// which is not in the official documentation.
	// the doc from deepseek:
	// - https://api-docs.deepseek.com/api/create-chat-completion#responses
	ReasoningContent string `json:"reasoning_content,omitempty"`
}

type ChatCompletionStreamChoiceLogprobs added in v1.32.5

type ChatCompletionStreamChoiceLogprobs struct {
	Content []ChatCompletionTokenLogprob `json:"content,omitempty"`
	Refusal []ChatCompletionTokenLogprob `json:"refusal,omitempty"`
}

type ChatCompletionStreamResponse

type ChatCompletionStreamResponse struct {
	ID                  string                       `json:"id"`
	Object              string                       `json:"object"`
	Created             int64                        `json:"created"`
	Model               string                       `json:"model"`
	Choices             []ChatCompletionStreamChoice `json:"choices"`
	SystemFingerprint   string                       `json:"system_fingerprint"`
	PromptAnnotations   []PromptAnnotation           `json:"prompt_annotations,omitempty"`
	PromptFilterResults []PromptFilterResult         `json:"prompt_filter_results,omitempty"`
	// An optional field that will only be present when you set stream_options: {"include_usage": true} in your request.
	// When present, it contains a null value except for the last chunk which contains the token usage statistics
	// for the entire request.
	Usage *Usage `json:"usage,omitempty"`
}

type ChatCompletionTokenLogprob added in v1.32.5

type ChatCompletionTokenLogprob struct {
	Token       string                                 `json:"token"`
	Bytes       []int64                                `json:"bytes,omitempty"`
	Logprob     float64                                `json:"logprob,omitempty"`
	TopLogprobs []ChatCompletionTokenLogprobTopLogprob `json:"top_logprobs"`
}

type ChatCompletionTokenLogprobTopLogprob added in v1.32.5

type ChatCompletionTokenLogprobTopLogprob struct {
	Token   string  `json:"token"`
	Bytes   []int64 `json:"bytes"`
	Logprob float64 `json:"logprob"`
}

type ChatMessageImageURL added in v1.17.9

type ChatMessageImageURL struct {
	URL    string         `json:"url,omitempty"`
	Detail ImageURLDetail `json:"detail,omitempty"`
}

type ChatMessagePart added in v1.17.9

type ChatMessagePart struct {
	Type     ChatMessagePartType  `json:"type,omitempty"`
	Text     string               `json:"text,omitempty"`
	ImageURL *ChatMessageImageURL `json:"image_url,omitempty"`
}

type ChatMessagePartType added in v1.17.9

type ChatMessagePartType string
const (
	ChatMessagePartTypeText     ChatMessagePartType = "text"
	ChatMessagePartTypeImageURL ChatMessagePartType = "image_url"
)

type ChunkingStrategy added in v1.25.0

type ChunkingStrategy struct {
	Type   ChunkingStrategyType    `json:"type"`
	Static *StaticChunkingStrategy `json:"static,omitempty"`
}

type ChunkingStrategyType added in v1.25.0

type ChunkingStrategyType string
const (
	ChunkingStrategyTypeAuto   ChunkingStrategyType = "auto"
	ChunkingStrategyTypeStatic ChunkingStrategyType = "static"
)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is OpenAI GPT-3 API client.

func NewClient

func NewClient(authToken string) *Client

NewClient creates new OpenAI API client.

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

NewClientWithConfig creates new OpenAI API client for specified config.

func NewOrgClient deprecated

func NewOrgClient(authToken, org string) *Client

NewOrgClient creates new OpenAI API client for specified Organization ID.

Deprecated: Please use NewClientWithConfig.

func (*Client) CancelBatch added in v1.25.0

func (c *Client) CancelBatch(
	ctx context.Context,
	batchID string,
) (response BatchResponse, err error)

CancelBatch — API call to Cancel batch.

func (*Client) CancelFineTune deprecated added in v1.5.0

func (c *Client) CancelFineTune(ctx context.Context, fineTuneID string) (response FineTune, err error)

CancelFineTune cancel a fine-tune job.

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*Client) CancelFineTuningJob added in v1.15.1

func (c *Client) CancelFineTuningJob(ctx context.Context, fineTuningJobID string) (response FineTuningJob, err error)

CancelFineTuningJob cancel a fine tuning job.

func (*Client) CancelResponse added in v1.42.0

func (c *Client) CancelResponse(ctx context.Context, responseID string) (response CreateResponseResponse, err error)

CancelResponse cancels a background response.

func (*Client) CancelRun added in v1.17.5

func (c *Client) CancelRun(
	ctx context.Context,
	threadID string,
	runID string) (response Run, err error)

CancelRun cancels a run.

func (*Client) CancelVectorStoreFileBatch added in v1.26.0

func (c *Client) CancelVectorStoreFileBatch(
	ctx context.Context,
	vectorStoreID string,
	batchID string,
) (response VectorStoreFileBatch, err error)

CancelVectorStoreFileBatch cancel a new vector store file batch.

func (*Client) CompactResponse added in v1.42.0

func (c *Client) CompactResponse(
	ctx context.Context,
	request CompactResponseRequest,
) (response ResponseCompaction, err error)

CompactResponse compacts a response context for use in a later request.

func (*Client) CountResponseInputTokens added in v1.42.0

func (c *Client) CountResponseInputTokens(
	ctx context.Context,
	request ResponseInputTokensRequest,
) (response ResponseInputTokensResponse, err error)

CountResponseInputTokens returns the number of input tokens a request would use.

func (*Client) CreateAssistant added in v1.17.0

func (c *Client) CreateAssistant(ctx context.Context, request AssistantRequest) (response Assistant, err error)

CreateAssistant creates a new assistant.

func (*Client) CreateAssistantFile added in v1.17.0

func (c *Client) CreateAssistantFile(
	ctx context.Context,
	assistantID string,
	request AssistantFileRequest,
) (response AssistantFile, err error)

CreateAssistantFile creates a new assistant file.

func (*Client) CreateBatch added in v1.25.0

func (c *Client) CreateBatch(
	ctx context.Context,
	request CreateBatchRequest,
) (response BatchResponse, err error)

CreateBatch — API call to Create batch.

func (*Client) CreateBatchWithUploadFile added in v1.25.0

func (c *Client) CreateBatchWithUploadFile(
	ctx context.Context,
	request CreateBatchWithUploadFileRequest,
) (response BatchResponse, err error)

CreateBatchWithUploadFile — API call to Create batch with upload file.

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(
	ctx context.Context,
	request ChatCompletionRequest,
) (response ChatCompletionResponse, err error)

CreateChatCompletion — API call to Create a completion for the chat message.

func (*Client) CreateChatCompletionStream

func (c *Client) CreateChatCompletionStream(
	ctx context.Context,
	request ChatCompletionRequest,
) (stream *ChatCompletionStream, err error)

CreateChatCompletionStream — API call to create a chat completion w/ streaming support. It sets whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"

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

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

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

	fmt.Print("Stream response: ")
	for {
		var response openai.ChatCompletionStreamResponse
		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.Println(response.Choices[0].Delta.Content)
	}
}

func (*Client) CreateCompletion

func (c *Client) CreateCompletion(
	ctx context.Context,
	request CompletionRequest,
) (response CompletionResponse, err error)

CreateCompletion — API call to create a completion. This is the main endpoint of the API. Returns new text as well as, if requested, the probabilities over each alternative token at each position.

If using a fine-tuned model, simply provide the model's ID in the CompletionRequest object, and the server will use the model's parameters to generate the completion.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	resp, err := client.CreateCompletion(
		context.Background(),
		openai.CompletionRequest{
			Model:     openai.GPT3Babbage002,
			MaxTokens: 5,
			Prompt:    "Lorem ipsum",
		},
	)
	if err != nil {
		fmt.Printf("Completion error: %v\n", err)
		return
	}
	fmt.Println(resp.Choices[0].Text)
}

func (*Client) CreateCompletionStream

func (c *Client) CreateCompletionStream(
	ctx context.Context,
	request CompletionRequest,
) (stream *CompletionStream, err error)

CreateCompletionStream — API call to create a completion w/ streaming support. It sets whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"

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

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	stream, err := client.CreateCompletionStream(
		context.Background(),
		openai.CompletionRequest{
			Model:     openai.GPT3Babbage002,
			MaxTokens: 5,
			Prompt:    "Lorem ipsum",
			Stream:    true,
		},
	)
	if err != nil {
		fmt.Printf("CompletionStream error: %v\n", err)
		return
	}
	defer stream.Close()

	for {
		var response openai.CompletionResponse
		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)
	}
}

func (*Client) CreateEditImage

func (c *Client) CreateEditImage(ctx context.Context, request ImageEditRequest) (response ImageResponse, err error)

CreateEditImage - API call to create an image. This is the main endpoint of the DALL-E API.

func (*Client) CreateEmbeddings

func (c *Client) CreateEmbeddings(
	ctx context.Context,
	conv EmbeddingRequestConverter,
) (res EmbeddingResponse, err error)

CreateEmbeddings returns an EmbeddingResponse which will contain an Embedding for every item in |body.Input|. https://beta.openai.com/docs/api-reference/embeddings/create

Body should be of type EmbeddingRequestStrings for embedding strings or EmbeddingRequestTokens for embedding groups of text already converted to tokens.

func (*Client) CreateFile

func (c *Client) CreateFile(ctx context.Context, request FileRequest) (file File, err error)

CreateFile uploads a jsonl file to GPT3 FilePath must be a local file path.

func (*Client) CreateFileBytes added in v1.17.7

func (c *Client) CreateFileBytes(ctx context.Context, request FileBytesRequest) (file File, err error)

CreateFileBytes uploads bytes directly to OpenAI without requiring a local file.

func (*Client) CreateFineTune deprecated added in v1.5.0

func (c *Client) CreateFineTune(ctx context.Context, request FineTuneRequest) (response FineTune, err error)

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*Client) CreateFineTuningJob added in v1.15.1

func (c *Client) CreateFineTuningJob(
	ctx context.Context,
	request FineTuningJobRequest,
) (response FineTuningJob, err error)

CreateFineTuningJob create a fine tuning job.

func (*Client) CreateImage

func (c *Client) CreateImage(ctx context.Context, request ImageRequest) (response ImageResponse, err error)

CreateImage - API call to create an image. This is the main endpoint of the DALL-E API.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

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

	respURL, err := client.CreateImage(
		context.Background(),
		openai.ImageRequest{
			Prompt:         "Parrot on a skateboard performs a trick, cartoon style, natural light, high detail",
			Size:           openai.CreateImageSize256x256,
			ResponseFormat: openai.CreateImageResponseFormatURL,
			N:              1,
		},
	)
	if err != nil {
		fmt.Printf("Image creation error: %v\n", err)
		return
	}
	fmt.Println(respURL.Data[0].URL)
}
Example (Base64)
package main

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

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

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

	resp, err := client.CreateImage(
		context.Background(),
		openai.ImageRequest{
			Prompt:         "Portrait of a humanoid parrot in a classic costume, high detail, realistic light, unreal engine",
			Size:           openai.CreateImageSize512x512,
			ResponseFormat: openai.CreateImageResponseFormatB64JSON,
			N:              1,
		},
	)
	if err != nil {
		fmt.Printf("Image creation error: %v\n", err)
		return
	}

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

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

	_, err = f.Write(b)
	if err != nil {
		fmt.Printf("File write error: %v\n", err)
		return
	}

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

func (*Client) CreateMessage added in v1.17.6

func (c *Client) CreateMessage(ctx context.Context, threadID string, request MessageRequest) (msg Message, err error)

CreateMessage creates a new message.

func (*Client) CreateResponse added in v1.42.0

func (c *Client) CreateResponse(
	ctx context.Context,
	request CreateResponseRequest,
) (response CreateResponseResponse, err error)

CreateResponse creates a non-streaming model response.

func (*Client) CreateResponseStream added in v1.42.0

func (c *Client) CreateResponseStream(
	ctx context.Context,
	request CreateResponseRequest,
) (stream *ResponseStream, err error)

CreateResponseStream creates a response and streams its generation events.

func (*Client) CreateRun added in v1.17.5

func (c *Client) CreateRun(
	ctx context.Context,
	threadID string,
	request RunRequest,
) (response Run, err error)

CreateRun creates a new run.

func (*Client) CreateSpeech added in v1.17.6

func (c *Client) CreateSpeech(ctx context.Context, request CreateSpeechRequest) (response RawResponse, err error)

func (*Client) CreateThread added in v1.17.4

func (c *Client) CreateThread(ctx context.Context, request ThreadRequest) (response Thread, err error)

CreateThread creates a new thread.

func (*Client) CreateThreadAndRun added in v1.17.5

func (c *Client) CreateThreadAndRun(
	ctx context.Context,
	request CreateThreadAndRunRequest) (response Run, err error)

CreateThreadAndRun submits tool outputs.

func (*Client) CreateTranscription

func (c *Client) CreateTranscription(
	ctx context.Context,
	request AudioRequest,
) (response AudioResponse, err error)

CreateTranscription — API call to create a transcription. Returns transcribed text.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	resp, err := client.CreateTranscription(
		context.Background(),
		openai.AudioRequest{
			Model:    openai.Whisper1,
			FilePath: "recording.mp3",
		},
	)
	if err != nil {
		fmt.Printf("Transcription error: %v\n", err)
		return
	}
	fmt.Println(resp.Text)
}
Example (Captions)
package main

import (
	"context"
	"fmt"
	"os"

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

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

	resp, err := client.CreateTranscription(
		context.Background(),
		openai.AudioRequest{
			Model:    openai.Whisper1,
			FilePath: os.Args[1],
			Format:   openai.AudioResponseFormatSRT,
		},
	)
	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
	}
}

func (*Client) CreateTranslation

func (c *Client) CreateTranslation(
	ctx context.Context,
	request AudioRequest,
) (response AudioResponse, err error)

CreateTranslation — API call to translate audio into English.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	resp, err := client.CreateTranslation(
		context.Background(),
		openai.AudioRequest{
			Model:    openai.Whisper1,
			FilePath: "recording.mp3",
		},
	)
	if err != nil {
		fmt.Printf("Translation error: %v\n", err)
		return
	}
	fmt.Println(resp.Text)
}

func (*Client) CreateVariImage added in v1.5.1

func (c *Client) CreateVariImage(ctx context.Context, request ImageVariRequest) (response ImageResponse, err error)

CreateVariImage - API call to create an image variation. This is the main endpoint of the DALL-E API. Use abbreviations(vari for variation) because ci-lint has a single-line length limit ...

func (*Client) CreateVectorStore added in v1.26.0

func (c *Client) CreateVectorStore(ctx context.Context, request VectorStoreRequest) (response VectorStore, err error)

CreateVectorStore creates a new vector store.

func (*Client) CreateVectorStoreFile added in v1.26.0

func (c *Client) CreateVectorStoreFile(
	ctx context.Context,
	vectorStoreID string,
	request VectorStoreFileRequest,
) (response VectorStoreFile, err error)

CreateVectorStoreFile creates a new vector store file.

func (*Client) CreateVectorStoreFileBatch added in v1.26.0

func (c *Client) CreateVectorStoreFileBatch(
	ctx context.Context,
	vectorStoreID string,
	request VectorStoreFileBatchRequest,
) (response VectorStoreFileBatch, err error)

CreateVectorStoreFileBatch creates a new vector store file batch.

func (*Client) DeleteAssistant added in v1.17.0

func (c *Client) DeleteAssistant(
	ctx context.Context,
	assistantID string,
) (response AssistantDeleteResponse, err error)

DeleteAssistant deletes an assistant.

func (*Client) DeleteAssistantFile added in v1.17.0

func (c *Client) DeleteAssistantFile(
	ctx context.Context,
	assistantID string,
	fileID string,
) (err error)

DeleteAssistantFile deletes an existing file.

func (*Client) DeleteFile

func (c *Client) DeleteFile(ctx context.Context, fileID string) (err error)

DeleteFile deletes an existing file.

func (*Client) DeleteFineTune deprecated added in v1.5.0

func (c *Client) DeleteFineTune(ctx context.Context, fineTuneID string) (response FineTuneDeleteResponse, err error)

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*Client) DeleteFineTuneModel added in v1.15.4

func (c *Client) DeleteFineTuneModel(ctx context.Context, modelID string) (
	response FineTuneModelDeleteResponse, err error)

DeleteFineTuneModel Deletes a fine-tune model. You must have the Owner role in your organization to delete a model.

func (*Client) DeleteMessage added in v1.28.3

func (c *Client) DeleteMessage(
	ctx context.Context,
	threadID, messageID string,
) (status MessageDeletionStatus, err error)

DeleteMessage deletes a message..

func (*Client) DeleteResponse added in v1.42.0

func (c *Client) DeleteResponse(ctx context.Context, responseID string) (response ResponseDeleteResponse, err error)

DeleteResponse deletes a stored response.

func (*Client) DeleteThread added in v1.17.4

func (c *Client) DeleteThread(
	ctx context.Context,
	threadID string,
) (response ThreadDeleteResponse, err error)

DeleteThread deletes a thread.

func (*Client) DeleteVectorStore added in v1.26.0

func (c *Client) DeleteVectorStore(
	ctx context.Context,
	vectorStoreID string,
) (response VectorStoreDeleteResponse, err error)

DeleteVectorStore deletes an vector store.

func (*Client) DeleteVectorStoreFile added in v1.26.0

func (c *Client) DeleteVectorStoreFile(
	ctx context.Context,
	vectorStoreID string,
	fileID string,
) (err error)

DeleteVectorStoreFile deletes an existing file.

func (*Client) Edits

func (c *Client) Edits(ctx context.Context, request EditsRequest) (response EditsResponse, err error)

Edits Perform an API call to the Edits endpoint.

Deprecated: Users of the Edits API and its associated models (e.g., text-davinci-edit-001 or code-davinci-edit-001)

will need to migrate to GPT-3.5 Turbo by January 4, 2024. You can use CreateChatCompletion or CreateChatCompletionStream instead.

func (*Client) GetEngine

func (c *Client) GetEngine(
	ctx context.Context,
	engineID string,
) (engine Engine, err error)

GetEngine Retrieves an engine instance, providing basic information about the engine such as the owner and availability.

func (*Client) GetFile

func (c *Client) GetFile(ctx context.Context, fileID string) (file File, err error)

GetFile Retrieves a file instance, providing basic information about the file such as the file name and purpose.

func (*Client) GetFileContent added in v1.11.0

func (c *Client) GetFileContent(ctx context.Context, fileID string) (content RawResponse, err error)

func (*Client) GetFineTune deprecated added in v1.5.0

func (c *Client) GetFineTune(ctx context.Context, fineTuneID string) (response FineTune, err error)

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*Client) GetModel added in v1.10.0

func (c *Client) GetModel(ctx context.Context, modelID string) (model Model, err error)

GetModel Retrieves a model instance, providing basic information about the model such as the owner and permissioning.

func (*Client) GetResponse added in v1.42.0

func (c *Client) GetResponse(
	ctx context.Context,
	responseID string,
	options ...RetrieveResponseOptions,
) (CreateResponseResponse, error)

GetResponse is an alias for RetrieveResponse.

func (*Client) ListAssistantFiles added in v1.17.0

func (c *Client) ListAssistantFiles(
	ctx context.Context,
	assistantID string,
	limit *int,
	order *string,
	after *string,
	before *string,
) (response AssistantFilesList, err error)

ListAssistantFiles Lists the currently available files for an assistant.

func (*Client) ListAssistants added in v1.17.0

func (c *Client) ListAssistants(
	ctx context.Context,
	limit *int,
	order *string,
	after *string,
	before *string,
) (response AssistantsList, err error)

ListAssistants Lists the currently available assistants.

func (*Client) ListBatch added in v1.25.0

func (c *Client) ListBatch(ctx context.Context, after *string, limit *int) (response ListBatchResponse, err error)

ListBatch API call to List batch.

func (*Client) ListEngines

func (c *Client) ListEngines(ctx context.Context) (engines EnginesList, err error)

ListEngines Lists the currently available engines, and provides basic information about each option such as the owner and availability.

func (*Client) ListFiles

func (c *Client) ListFiles(ctx context.Context) (files FilesList, err error)

ListFiles Lists the currently available files, and provides basic information about each file such as the file name and purpose.

func (*Client) ListFineTuneEvents deprecated added in v1.5.0

func (c *Client) ListFineTuneEvents(ctx context.Context, fineTuneID string) (response FineTuneEventList, err error)

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*Client) ListFineTunes deprecated added in v1.5.0

func (c *Client) ListFineTunes(ctx context.Context) (response FineTuneList, err error)

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*Client) ListFineTuningJobEvents added in v1.15.1

func (c *Client) ListFineTuningJobEvents(
	ctx context.Context,
	fineTuningJobID string,
	setters ...ListFineTuningJobEventsParameter,
) (response FineTuningJobEventList, err error)

ListFineTuningJobs list fine tuning jobs events.

func (*Client) ListMessage added in v1.17.6

func (c *Client) ListMessage(ctx context.Context, threadID string,
	limit *int,
	order *string,
	after *string,
	before *string,
	runID *string,
) (messages MessagesList, err error)

ListMessage fetches all messages in the thread.

func (*Client) ListMessageFiles added in v1.17.6

func (c *Client) ListMessageFiles(
	ctx context.Context,
	threadID, messageID string,
) (files MessageFilesList, err error)

ListMessageFiles fetches all files attached to a message.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) (models ModelsList, err error)

ListModels Lists the currently available models, and provides basic information about each model such as the model id and parent.

func (*Client) ListResponseInputItems added in v1.42.0

func (c *Client) ListResponseInputItems(
	ctx context.Context,
	responseID string,
	options ...ResponseInputItemsListOptions,
) (response ResponseInputItemsList, err error)

ListResponseInputItems lists the input items for a response.

func (*Client) ListRunSteps added in v1.17.5

func (c *Client) ListRunSteps(
	ctx context.Context,
	threadID string,
	runID string,
	pagination Pagination,
) (response RunStepList, err error)

ListRunSteps lists run steps.

func (*Client) ListRuns added in v1.17.5

func (c *Client) ListRuns(
	ctx context.Context,
	threadID string,
	pagination Pagination,
) (response RunList, err error)

ListRuns lists runs.

func (*Client) ListVectorStoreFiles added in v1.26.0

func (c *Client) ListVectorStoreFiles(
	ctx context.Context,
	vectorStoreID string,
	pagination Pagination,
) (response VectorStoreFilesList, err error)

ListVectorStoreFiles Lists the currently available files for a vector store.

func (*Client) ListVectorStoreFilesInBatch added in v1.26.0

func (c *Client) ListVectorStoreFilesInBatch(
	ctx context.Context,
	vectorStoreID string,
	batchID string,
	pagination Pagination,
) (response VectorStoreFilesList, err error)

ListVectorStoreFiles Lists the currently available files for a vector store.

func (*Client) ListVectorStores added in v1.26.0

func (c *Client) ListVectorStores(
	ctx context.Context,
	pagination Pagination,
) (response VectorStoresList, err error)

ListVectorStores Lists the currently available vector store.

func (*Client) Moderations

func (c *Client) Moderations(ctx context.Context, request ModerationRequest) (response ModerationResponse, err error)

Moderations — perform a moderation api call over a string. Input can be an array or slice but a string will reduce the complexity.

func (*Client) ModifyAssistant added in v1.17.0

func (c *Client) ModifyAssistant(
	ctx context.Context,
	assistantID string,
	request AssistantRequest,
) (response Assistant, err error)

ModifyAssistant modifies an assistant.

func (*Client) ModifyMessage added in v1.17.6

func (c *Client) ModifyMessage(
	ctx context.Context,
	threadID, messageID string,
	metadata map[string]string,
) (msg Message, err error)

ModifyMessage modifies a message.

func (*Client) ModifyRun added in v1.17.5

func (c *Client) ModifyRun(
	ctx context.Context,
	threadID string,
	runID string,
	request RunModifyRequest,
) (response Run, err error)

ModifyRun modifies a run.

func (*Client) ModifyThread added in v1.17.4

func (c *Client) ModifyThread(
	ctx context.Context,
	threadID string,
	request ModifyThreadRequest,
) (response Thread, err error)

ModifyThread modifies a thread.

func (*Client) ModifyVectorStore added in v1.26.0

func (c *Client) ModifyVectorStore(
	ctx context.Context,
	vectorStoreID string,
	request VectorStoreRequest,
) (response VectorStore, err error)

ModifyVectorStore modifies a vector store.

func (*Client) RetrieveAssistant added in v1.17.0

func (c *Client) RetrieveAssistant(
	ctx context.Context,
	assistantID string,
) (response Assistant, err error)

RetrieveAssistant retrieves an assistant.

func (*Client) RetrieveAssistantFile added in v1.17.0

func (c *Client) RetrieveAssistantFile(
	ctx context.Context,
	assistantID string,
	fileID string,
) (response AssistantFile, err error)

RetrieveAssistantFile retrieves an assistant file.

func (*Client) RetrieveBatch added in v1.25.0

func (c *Client) RetrieveBatch(
	ctx context.Context,
	batchID string,
) (response BatchResponse, err error)

RetrieveBatch — API call to Retrieve batch.

func (*Client) RetrieveFineTuningJob added in v1.15.1

func (c *Client) RetrieveFineTuningJob(
	ctx context.Context,
	fineTuningJobID string,
) (response FineTuningJob, err error)

RetrieveFineTuningJob retrieve a fine tuning job.

func (*Client) RetrieveMessage added in v1.17.6

func (c *Client) RetrieveMessage(
	ctx context.Context,
	threadID, messageID string,
) (msg Message, err error)

RetrieveMessage retrieves a Message.

func (*Client) RetrieveMessageFile added in v1.17.6

func (c *Client) RetrieveMessageFile(
	ctx context.Context,
	threadID, messageID, fileID string,
) (file MessageFile, err error)

RetrieveMessageFile fetches a message file.

func (*Client) RetrieveResponse added in v1.42.0

func (c *Client) RetrieveResponse(
	ctx context.Context,
	responseID string,
	options ...RetrieveResponseOptions,
) (response CreateResponseResponse, err error)

RetrieveResponse gets a stored response by ID.

func (*Client) RetrieveRun added in v1.17.5

func (c *Client) RetrieveRun(
	ctx context.Context,
	threadID string,
	runID string,
) (response Run, err error)

RetrieveRun retrieves a run.

func (*Client) RetrieveRunStep added in v1.17.5

func (c *Client) RetrieveRunStep(
	ctx context.Context,
	threadID string,
	runID string,
	stepID string,
) (response RunStep, err error)

RetrieveRunStep retrieves a run step.

func (*Client) RetrieveThread added in v1.17.4

func (c *Client) RetrieveThread(ctx context.Context, threadID string) (response Thread, err error)

RetrieveThread retrieves a thread.

func (*Client) RetrieveVectorStore added in v1.26.0

func (c *Client) RetrieveVectorStore(
	ctx context.Context,
	vectorStoreID string,
) (response VectorStore, err error)

RetrieveVectorStore retrieves an vector store.

func (*Client) RetrieveVectorStoreFile added in v1.26.0

func (c *Client) RetrieveVectorStoreFile(
	ctx context.Context,
	vectorStoreID string,
	fileID string,
) (response VectorStoreFile, err error)

RetrieveVectorStoreFile retrieves a vector store file.

func (*Client) RetrieveVectorStoreFileBatch added in v1.26.0

func (c *Client) RetrieveVectorStoreFileBatch(
	ctx context.Context,
	vectorStoreID string,
	batchID string,
) (response VectorStoreFileBatch, err error)

RetrieveVectorStoreFileBatch retrieves a vector store file batch.

func (*Client) SubmitToolOutputs added in v1.17.5

func (c *Client) SubmitToolOutputs(
	ctx context.Context,
	threadID string,
	runID string,
	request SubmitToolOutputsRequest) (response Run, err error)

SubmitToolOutputs submits tool outputs.

func (*Client) UploadBatchFile added in v1.25.0

func (c *Client) UploadBatchFile(ctx context.Context, request UploadBatchFileRequest) (File, error)

UploadBatchFile — upload batch file.

type ClientConfig

type ClientConfig struct {
	BaseURL              string
	OrgID                string
	APIType              APIType
	APIVersion           string // required when APIType is APITypeAzure or APITypeAzureAD or APITypeAnthropic
	AssistantVersion     string
	AzureModelMapperFunc func(model string) string // replace model to azure deployment name func
	HTTPClient           HTTPDoer

	EmptyMessagesLimit uint
	// contains filtered or unexported fields
}

ClientConfig is a configuration of a client.

Example (ClientWithProxy)
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"os"

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

func main() {
	config := openai.DefaultConfig(os.Getenv("OPENAI_API_KEY"))
	port := os.Getenv("OPENAI_PROXY_PORT")
	proxyURL, err := url.Parse(fmt.Sprintf("http://localhost:%s", port))
	if err != nil {
		panic(err)
	}
	transport := &http.Transport{
		Proxy: http.ProxyURL(proxyURL),
	}
	config.HTTPClient = &http.Client{
		Transport: transport,
	}

	client := openai.NewClientWithConfig(config)

	client.CreateChatCompletion( //nolint:errcheck // outside of the scope of this example.
		context.Background(),
		openai.ChatCompletionRequest{
			// etc...
		},
	)
}

func DefaultAnthropicConfig added in v1.38.0

func DefaultAnthropicConfig(apiKey, baseURL string) ClientConfig

func DefaultAzureConfig added in v1.6.0

func DefaultAzureConfig(apiKey, baseURL string) ClientConfig
Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	azureKey := os.Getenv("AZURE_OPENAI_API_KEY")       // Your azure API key
	azureEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT") // Your azure OpenAI endpoint
	config := openai.DefaultAzureConfig(azureKey, azureEndpoint)
	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)
}

func DefaultConfig

func DefaultConfig(authToken string) ClientConfig

func (ClientConfig) GetAzureDeploymentByModel added in v1.9.4

func (c ClientConfig) GetAzureDeploymentByModel(model string) string

func (ClientConfig) String added in v1.7.0

func (ClientConfig) String() string

type CodeInterpreterToolResources added in v1.25.0

type CodeInterpreterToolResources struct {
	FileIDs []string `json:"file_ids,omitempty"`
}

type CodeInterpreterToolResourcesRequest added in v1.25.0

type CodeInterpreterToolResourcesRequest struct {
	FileIDs []string `json:"file_ids,omitempty"`
}

type CompactResponseRequest added in v1.42.0

type CompactResponseRequest = CreateResponseRequest

CompactResponseRequest contains the response context to compact.

type CompletionChoice

type CompletionChoice struct {
	Text         string        `json:"text"`
	Index        int           `json:"index"`
	FinishReason string        `json:"finish_reason"`
	LogProbs     LogprobResult `json:"logprobs"`
}

CompletionChoice represents one of possible completions.

type CompletionRequest

type CompletionRequest struct {
	Model            string  `json:"model"`
	Prompt           any     `json:"prompt,omitempty"`
	BestOf           int     `json:"best_of,omitempty"`
	Echo             bool    `json:"echo,omitempty"`
	FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
	// LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a word string.
	// incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}`
	// refs: https://platform.openai.com/docs/api-reference/completions/create#completions/create-logit_bias
	LogitBias map[string]int `json:"logit_bias,omitempty"`
	// Store can be set to true to store the output of this completion request for use in distillations and evals.
	// https://platform.openai.com/docs/api-reference/chat/create#chat-create-store
	Store bool `json:"store,omitempty"`
	// Metadata to store with the completion.
	Metadata        map[string]string `json:"metadata,omitempty"`
	LogProbs        int               `json:"logprobs,omitempty"`
	MaxTokens       int               `json:"max_tokens,omitempty"`
	N               int               `json:"n,omitempty"`
	PresencePenalty float32           `json:"presence_penalty,omitempty"`
	Seed            *int              `json:"seed,omitempty"`
	Stop            []string          `json:"stop,omitempty"`
	Stream          bool              `json:"stream"`
	Suffix          string            `json:"suffix,omitempty"`
	Temperature     float32           `json:"temperature,omitempty"`
	TopP            float32           `json:"top_p,omitempty"`
	User            string            `json:"user,omitempty"`
	// Options for streaming response. Only set this when you set stream: true.
	StreamOptions *StreamOptions `json:"stream_options,omitempty"`
}

CompletionRequest represents a request structure for completion API.

type CompletionResponse

type CompletionResponse struct {
	ID      string             `json:"id"`
	Object  string             `json:"object"`
	Created int64              `json:"created"`
	Model   string             `json:"model"`
	Choices []CompletionChoice `json:"choices"`
	Usage   *Usage             `json:"usage,omitempty"`
	// contains filtered or unexported fields
}

CompletionResponse represents a response structure for completion API.

func (*CompletionResponse) GetRateLimitHeaders added in v1.16.0

func (h *CompletionResponse) GetRateLimitHeaders() RateLimitHeaders

func (*CompletionResponse) Header added in v1.16.0

func (h *CompletionResponse) Header() http.Header

func (*CompletionResponse) SetHeader added in v1.16.0

func (h *CompletionResponse) SetHeader(header http.Header)

type CompletionStream

type CompletionStream struct {
	// contains filtered or unexported fields
}

func (CompletionStream) Close

func (stream CompletionStream) Close() error

func (CompletionStream) Recv

func (stream CompletionStream) Recv() (response T, err error)

func (CompletionStream) RecvRaw added in v1.36.0

func (stream CompletionStream) RecvRaw() ([]byte, error)

type CompletionTokensDetails added in v1.31.0

type CompletionTokensDetails struct {
	AudioTokens              int `json:"audio_tokens"`
	ReasoningTokens          int `json:"reasoning_tokens"`
	AcceptedPredictionTokens int `json:"accepted_prediction_tokens"`
	RejectedPredictionTokens int `json:"rejected_prediction_tokens"`
}

CompletionTokensDetails Breakdown of tokens used in a completion.

type ContentFilterResults added in v1.14.1

type ContentFilterResults struct {
	Hate      Hate      `json:"hate,omitempty"`
	SelfHarm  SelfHarm  `json:"self_harm,omitempty"`
	Sexual    Sexual    `json:"sexual,omitempty"`
	Violence  Violence  `json:"violence,omitempty"`
	JailBreak JailBreak `json:"jailbreak,omitempty"`
	Profanity Profanity `json:"profanity,omitempty"`
}

type CreateBatchRequest added in v1.25.0

type CreateBatchRequest struct {
	InputFileID      string         `json:"input_file_id"`
	Endpoint         BatchEndpoint  `json:"endpoint"`
	CompletionWindow string         `json:"completion_window"`
	Metadata         map[string]any `json:"metadata"`
}

type CreateBatchWithUploadFileRequest added in v1.25.0

type CreateBatchWithUploadFileRequest struct {
	Endpoint         BatchEndpoint  `json:"endpoint"`
	CompletionWindow string         `json:"completion_window"`
	Metadata         map[string]any `json:"metadata"`
	UploadBatchFileRequest
}

type CreateResponseRequest added in v1.42.0

type CreateResponseRequest struct {
	Background           bool                        `json:"background,omitempty"`
	ContextManagement    []any                       `json:"context_management,omitempty"`
	Conversation         any                         `json:"conversation,omitempty"`
	Include              []ResponseInclude           `json:"include,omitempty"`
	Input                any                         `json:"input"`
	Instructions         string                      `json:"instructions,omitempty"`
	MaxOutputTokens      int                         `json:"max_output_tokens,omitempty"`
	MaxToolCalls         int                         `json:"max_tool_calls,omitempty"`
	Metadata             map[string]any              `json:"metadata,omitempty"`
	Model                string                      `json:"model,omitempty"`
	Moderation           any                         `json:"moderation,omitempty"`
	ParallelToolCalls    *bool                       `json:"parallel_tool_calls,omitempty"`
	PreviousResponseID   string                      `json:"previous_response_id,omitempty"`
	Prompt               *ResponsePrompt             `json:"prompt,omitempty"`
	PromptCacheKey       string                      `json:"prompt_cache_key,omitempty"`
	PromptCacheOptions   *ResponsePromptCacheOptions `json:"prompt_cache_options,omitempty"`
	PromptCacheRetention string                      `json:"prompt_cache_retention,omitempty"`
	Reasoning            *ResponseReasoning          `json:"reasoning,omitempty"`
	SafetyIdentifier     string                      `json:"safety_identifier,omitempty"`
	ServiceTier          string                      `json:"service_tier,omitempty"`
	Store                *bool                       `json:"store,omitempty"`
	Stream               bool                        `json:"stream,omitempty"`
	StreamOptions        *ResponseStreamOptions      `json:"stream_options,omitempty"`
	Temperature          *float32                    `json:"temperature,omitempty"`
	Text                 *ResponseTextConfig         `json:"text,omitempty"`
	ToolChoice           any                         `json:"tool_choice,omitempty"`
	Tools                []ResponseTool              `json:"tools,omitempty"`
	TopLogprobs          int                         `json:"top_logprobs,omitempty"`
	TopP                 *float32                    `json:"top_p,omitempty"`
	Truncation           ResponseTruncation          `json:"truncation,omitempty"`
	User                 string                      `json:"user,omitempty"`
	ExtraBody            map[string]any              `json:"-"`
}

CreateResponseRequest represents a request to the Responses API. Input may be a string or a slice of response input items.

func (CreateResponseRequest) MarshalJSON added in v1.42.0

func (r CreateResponseRequest) MarshalJSON() ([]byte, error)

MarshalJSON merges ExtraBody into the request payload. ExtraBody values take precedence over fields represented directly by CreateResponseRequest.

type CreateResponseResponse added in v1.42.0

type CreateResponseResponse struct {
	ID                   string                      `json:"id"`
	Object               string                      `json:"object"`
	Created              int64                       `json:"created_at"`
	CompletedAt          *int64                      `json:"completed_at,omitempty"`
	Status               ResponseStatus              `json:"status,omitempty"`
	Error                *ResponseError              `json:"error,omitempty"`
	IncompleteDetails    *ResponseIncompleteDetails  `json:"incomplete_details,omitempty"`
	Instructions         any                         `json:"instructions,omitempty"`
	MaxOutputTokens      *int                        `json:"max_output_tokens,omitempty"`
	MaxToolCalls         *int                        `json:"max_tool_calls,omitempty"`
	Metadata             map[string]any              `json:"metadata,omitempty"`
	Model                string                      `json:"model"`
	Moderation           any                         `json:"moderation,omitempty"`
	Output               []any                       `json:"output"`
	OutputText           string                      `json:"output_text,omitempty"`
	ParallelToolCalls    bool                        `json:"parallel_tool_calls,omitempty"`
	PreviousResponseID   string                      `json:"previous_response_id,omitempty"`
	Reasoning            *ResponseReasoning          `json:"reasoning,omitempty"`
	ServiceTier          string                      `json:"service_tier,omitempty"`
	Store                bool                        `json:"store,omitempty"`
	Temperature          *float32                    `json:"temperature,omitempty"`
	Text                 *ResponseTextConfig         `json:"text,omitempty"`
	ToolChoice           any                         `json:"tool_choice,omitempty"`
	Tools                []any                       `json:"tools,omitempty"`
	TopLogprobs          int                         `json:"top_logprobs,omitempty"`
	TopP                 *float32                    `json:"top_p,omitempty"`
	Truncation           ResponseTruncation          `json:"truncation,omitempty"`
	Usage                *ResponseUsage              `json:"usage,omitempty"`
	Background           *bool                       `json:"background,omitempty"`
	Conversation         *ResponseConversation       `json:"conversation,omitempty"`
	Prompt               *ResponsePrompt             `json:"prompt,omitempty"`
	PromptCacheKey       string                      `json:"prompt_cache_key,omitempty"`
	PromptCacheOptions   *ResponsePromptCacheOptions `json:"prompt_cache_options,omitempty"`
	PromptCacheRetention string                      `json:"prompt_cache_retention,omitempty"`
	SafetyIdentifier     string                      `json:"safety_identifier,omitempty"`
	User                 string                      `json:"user,omitempty"`
	// contains filtered or unexported fields
}

CreateResponseResponse represents a response returned by the Responses API.

func (CreateResponseResponse) GetOutputText added in v1.42.0

func (r CreateResponseResponse) GetOutputText() string

GetOutputText returns the aggregated text output. It uses the API's output_text convenience field when present and otherwise extracts output_text content parts.

func (*CreateResponseResponse) GetRateLimitHeaders added in v1.42.0

func (h *CreateResponseResponse) GetRateLimitHeaders() RateLimitHeaders

func (*CreateResponseResponse) Header added in v1.42.0

func (h *CreateResponseResponse) Header() http.Header

func (*CreateResponseResponse) SetHeader added in v1.42.0

func (h *CreateResponseResponse) SetHeader(header http.Header)

type CreateSpeechRequest added in v1.17.6

type CreateSpeechRequest struct {
	Model          SpeechModel          `json:"model"`
	Input          string               `json:"input"`
	Voice          SpeechVoice          `json:"voice"`
	Instructions   string               `json:"instructions,omitempty"`    // Optional, Doesnt work with tts-1 or tts-1-hd.
	ResponseFormat SpeechResponseFormat `json:"response_format,omitempty"` // Optional, default to mp3
	Speed          float64              `json:"speed,omitempty"`           // Optional, default to 1.0
}

type CreateThreadAndRunRequest added in v1.17.5

type CreateThreadAndRunRequest struct {
	RunRequest
	Thread ThreadRequest `json:"thread"`
}

type DeleteResponseResponse added in v1.42.0

type DeleteResponseResponse = ResponseDeleteResponse

DeleteResponseResponse is kept as a descriptive alias for ResponseDeleteResponse.

type EditsChoice

type EditsChoice struct {
	Text  string `json:"text"`
	Index int    `json:"index"`
}

EditsChoice represents one of possible edits.

type EditsRequest

type EditsRequest struct {
	Model       *string `json:"model,omitempty"`
	Input       string  `json:"input,omitempty"`
	Instruction string  `json:"instruction,omitempty"`
	N           int     `json:"n,omitempty"`
	Temperature float32 `json:"temperature,omitempty"`
	TopP        float32 `json:"top_p,omitempty"`
}

EditsRequest represents a request structure for Edits API.

type EditsResponse

type EditsResponse struct {
	Object  string        `json:"object"`
	Created int64         `json:"created"`
	Usage   Usage         `json:"usage"`
	Choices []EditsChoice `json:"choices"`
	// contains filtered or unexported fields
}

EditsResponse represents a response structure for Edits API.

func (*EditsResponse) GetRateLimitHeaders added in v1.16.0

func (h *EditsResponse) GetRateLimitHeaders() RateLimitHeaders

func (*EditsResponse) Header added in v1.16.0

func (h *EditsResponse) Header() http.Header

func (*EditsResponse) SetHeader added in v1.16.0

func (h *EditsResponse) SetHeader(header http.Header)

type Embedding

type Embedding struct {
	Object    string    `json:"object"`
	Embedding []float32 `json:"embedding"`
	Index     int       `json:"index"`
}

Embedding is a special format of data representation that can be easily utilized by machine learning models and algorithms. The embedding is an information dense representation of the semantic meaning of a piece of text. Each embedding is a vector of floating point numbers, such that the distance between two embeddings in the vector space is correlated with semantic similarity between two inputs in the original format. For example, if two texts are similar, then their vector representations should also be similar.

func (*Embedding) DotProduct added in v1.16.0

func (e *Embedding) DotProduct(other *Embedding) (float32, error)

DotProduct calculates the dot product of the embedding vector with another embedding vector. Both vectors must have the same length; otherwise, an ErrVectorLengthMismatch is returned. The method returns the calculated dot product as a float32 value.

type EmbeddingEncodingFormat added in v1.15.3

type EmbeddingEncodingFormat string

EmbeddingEncodingFormat is the format of the embeddings data. Currently, only "float" and "base64" are supported, however, "base64" is not officially documented. If not specified OpenAI will use "float".

const (
	EmbeddingEncodingFormatFloat  EmbeddingEncodingFormat = "float"
	EmbeddingEncodingFormatBase64 EmbeddingEncodingFormat = "base64"
)

type EmbeddingModel

type EmbeddingModel string

EmbeddingModel enumerates the models which can be used to generate Embedding vectors.

const (
	// Deprecated: The following block is shut down. Use text-embedding-ada-002 instead.
	AdaSimilarity         EmbeddingModel = "text-similarity-ada-001"
	BabbageSimilarity     EmbeddingModel = "text-similarity-babbage-001"
	CurieSimilarity       EmbeddingModel = "text-similarity-curie-001"
	DavinciSimilarity     EmbeddingModel = "text-similarity-davinci-001"
	AdaSearchDocument     EmbeddingModel = "text-search-ada-doc-001"
	AdaSearchQuery        EmbeddingModel = "text-search-ada-query-001"
	BabbageSearchDocument EmbeddingModel = "text-search-babbage-doc-001"
	BabbageSearchQuery    EmbeddingModel = "text-search-babbage-query-001"
	CurieSearchDocument   EmbeddingModel = "text-search-curie-doc-001"
	CurieSearchQuery      EmbeddingModel = "text-search-curie-query-001"
	DavinciSearchDocument EmbeddingModel = "text-search-davinci-doc-001"
	DavinciSearchQuery    EmbeddingModel = "text-search-davinci-query-001"
	AdaCodeSearchCode     EmbeddingModel = "code-search-ada-code-001"
	AdaCodeSearchText     EmbeddingModel = "code-search-ada-text-001"
	BabbageCodeSearchCode EmbeddingModel = "code-search-babbage-code-001"
	BabbageCodeSearchText EmbeddingModel = "code-search-babbage-text-001"

	AdaEmbeddingV2  EmbeddingModel = "text-embedding-ada-002"
	SmallEmbedding3 EmbeddingModel = "text-embedding-3-small"
	LargeEmbedding3 EmbeddingModel = "text-embedding-3-large"
)

type EmbeddingRequest

type EmbeddingRequest struct {
	Input          any                     `json:"input"`
	Model          EmbeddingModel          `json:"model"`
	User           string                  `json:"user,omitempty"`
	EncodingFormat EmbeddingEncodingFormat `json:"encoding_format,omitempty"`
	// Dimensions The number of dimensions the resulting output embeddings should have.
	// Only supported in text-embedding-3 and later models.
	Dimensions int `json:"dimensions,omitempty"`
	// The ExtraBody field allows for the inclusion of arbitrary key-value pairs
	// in the request body that may not be explicitly defined in this struct.
	ExtraBody map[string]any `json:"extra_body,omitempty"`
}

func (EmbeddingRequest) Convert added in v1.13.0

func (r EmbeddingRequest) Convert() EmbeddingRequest

type EmbeddingRequestConverter added in v1.13.0

type EmbeddingRequestConverter interface {
	// Needs to be of type EmbeddingRequestStrings or EmbeddingRequestTokens
	Convert() EmbeddingRequest
}

type EmbeddingRequestStrings added in v1.13.0

type EmbeddingRequestStrings struct {
	// Input is a slice of strings for which you want to generate an Embedding vector.
	// Each input must not exceed 8192 tokens in length.
	// OpenAPI suggests replacing newlines (\n) in your input with a single space, as they
	// have observed inferior results when newlines are present.
	// E.g.
	//	"The food was delicious and the waiter..."
	Input []string `json:"input"`
	// ID of the model to use. You can use the List models API to see all of your available models,
	// or see our Model overview for descriptions of them.
	Model EmbeddingModel `json:"model"`
	// A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
	User string `json:"user"`
	// EmbeddingEncodingFormat is the format of the embeddings data.
	// Currently, only "float" and "base64" are supported, however, "base64" is not officially documented.
	// If not specified OpenAI will use "float".
	EncodingFormat EmbeddingEncodingFormat `json:"encoding_format,omitempty"`
	// Dimensions The number of dimensions the resulting output embeddings should have.
	// Only supported in text-embedding-3 and later models.
	Dimensions int `json:"dimensions,omitempty"`
	// The ExtraBody field allows for the inclusion of arbitrary key-value pairs
	// in the request body that may not be explicitly defined in this struct.
	ExtraBody map[string]any `json:"extra_body,omitempty"`
}

EmbeddingRequestStrings is the input to a create embeddings request with a slice of strings.

func (EmbeddingRequestStrings) Convert added in v1.13.0

type EmbeddingRequestTokens added in v1.13.0

type EmbeddingRequestTokens struct {
	// Input is a slice of slices of ints ([][]int) for which you want to generate an Embedding vector.
	// Each input must not exceed 8192 tokens in length.
	// OpenAPI suggests replacing newlines (\n) in your input with a single space, as they
	// have observed inferior results when newlines are present.
	// E.g.
	//	"The food was delicious and the waiter..."
	Input [][]int `json:"input"`
	// ID of the model to use. You can use the List models API to see all of your available models,
	// or see our Model overview for descriptions of them.
	Model EmbeddingModel `json:"model"`
	// A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
	User string `json:"user"`
	// EmbeddingEncodingFormat is the format of the embeddings data.
	// Currently, only "float" and "base64" are supported, however, "base64" is not officially documented.
	// If not specified OpenAI will use "float".
	EncodingFormat EmbeddingEncodingFormat `json:"encoding_format,omitempty"`
	// Dimensions The number of dimensions the resulting output embeddings should have.
	// Only supported in text-embedding-3 and later models.
	Dimensions int `json:"dimensions,omitempty"`
	// The ExtraBody field allows for the inclusion of arbitrary key-value pairs
	// in the request body that may not be explicitly defined in this struct.
	ExtraBody map[string]any `json:"extra_body,omitempty"`
}

func (EmbeddingRequestTokens) Convert added in v1.13.0

type EmbeddingResponse

type EmbeddingResponse struct {
	Object string         `json:"object"`
	Data   []Embedding    `json:"data"`
	Model  EmbeddingModel `json:"model"`
	Usage  Usage          `json:"usage"`
	// contains filtered or unexported fields
}

EmbeddingResponse is the response from a Create embeddings request.

func (*EmbeddingResponse) GetRateLimitHeaders added in v1.16.0

func (h *EmbeddingResponse) GetRateLimitHeaders() RateLimitHeaders

func (*EmbeddingResponse) Header added in v1.16.0

func (h *EmbeddingResponse) Header() http.Header

func (*EmbeddingResponse) SetHeader added in v1.16.0

func (h *EmbeddingResponse) SetHeader(header http.Header)

type EmbeddingResponseBase64 added in v1.15.3

type EmbeddingResponseBase64 struct {
	Object string            `json:"object"`
	Data   []Base64Embedding `json:"data"`
	Model  EmbeddingModel    `json:"model"`
	Usage  Usage             `json:"usage"`
	// contains filtered or unexported fields
}

EmbeddingResponseBase64 is the response from a Create embeddings request with base64 encoding format.

func (*EmbeddingResponseBase64) GetRateLimitHeaders added in v1.16.0

func (h *EmbeddingResponseBase64) GetRateLimitHeaders() RateLimitHeaders

func (*EmbeddingResponseBase64) Header added in v1.16.0

func (h *EmbeddingResponseBase64) Header() http.Header

func (*EmbeddingResponseBase64) SetHeader added in v1.16.0

func (h *EmbeddingResponseBase64) SetHeader(header http.Header)

func (*EmbeddingResponseBase64) ToEmbeddingResponse added in v1.15.3

func (r *EmbeddingResponseBase64) ToEmbeddingResponse() (EmbeddingResponse, error)

ToEmbeddingResponse converts an embeddingResponseBase64 to an EmbeddingResponse.

type Engine

type Engine struct {
	ID     string `json:"id"`
	Object string `json:"object"`
	Owner  string `json:"owner"`
	Ready  bool   `json:"ready"`
	// contains filtered or unexported fields
}

Engine struct represents engine from OpenAPI API.

func (*Engine) GetRateLimitHeaders added in v1.16.0

func (h *Engine) GetRateLimitHeaders() RateLimitHeaders

func (*Engine) Header added in v1.16.0

func (h *Engine) Header() http.Header

func (*Engine) SetHeader added in v1.16.0

func (h *Engine) SetHeader(header http.Header)

type EnginesList

type EnginesList struct {
	Engines []Engine `json:"data"`
	// contains filtered or unexported fields
}

EnginesList is a list of engines.

func (*EnginesList) GetRateLimitHeaders added in v1.16.0

func (h *EnginesList) GetRateLimitHeaders() RateLimitHeaders

func (*EnginesList) Header added in v1.16.0

func (h *EnginesList) Header() http.Header

func (*EnginesList) SetHeader added in v1.16.0

func (h *EnginesList) SetHeader(header http.Header)

type ErrorResponse

type ErrorResponse struct {
	Error *APIError `json:"error,omitempty"`
}

type File

type File struct {
	Bytes         int    `json:"bytes"`
	CreatedAt     int64  `json:"created_at"`
	ID            string `json:"id"`
	FileName      string `json:"filename"`
	Object        string `json:"object"`
	Status        string `json:"status"`
	Purpose       string `json:"purpose"`
	StatusDetails string `json:"status_details"`
	// contains filtered or unexported fields
}

File struct represents an OpenAPI file.

func (*File) GetRateLimitHeaders added in v1.16.0

func (h *File) GetRateLimitHeaders() RateLimitHeaders

func (*File) Header added in v1.16.0

func (h *File) Header() http.Header

func (*File) SetHeader added in v1.16.0

func (h *File) SetHeader(header http.Header)

type FileBytesRequest added in v1.17.7

type FileBytesRequest struct {
	// the name of the uploaded file in OpenAI
	Name string
	// the bytes of the file
	Bytes []byte
	// the purpose of the file
	Purpose PurposeType
}

FileBytesRequest represents a file upload request.

type FileRequest

type FileRequest struct {
	FileName string `json:"file"`
	FilePath string `json:"-"`
	Purpose  string `json:"purpose"`
}

type FileSearchToolResources added in v1.25.0

type FileSearchToolResources struct {
	VectorStoreIDs []string `json:"vector_store_ids,omitempty"`
}

type FileSearchToolResourcesRequest added in v1.25.0

type FileSearchToolResourcesRequest struct {
	VectorStoreIDs []string                   `json:"vector_store_ids,omitempty"`
	VectorStores   []VectorStoreToolResources `json:"vector_stores,omitempty"`
}

type FilesList

type FilesList struct {
	Files []File `json:"data"`
	// contains filtered or unexported fields
}

FilesList is a list of files that belong to the user or organization.

func (*FilesList) GetRateLimitHeaders added in v1.16.0

func (h *FilesList) GetRateLimitHeaders() RateLimitHeaders

func (*FilesList) Header added in v1.16.0

func (h *FilesList) Header() http.Header

func (*FilesList) SetHeader added in v1.16.0

func (h *FilesList) SetHeader(header http.Header)

type FineTune deprecated added in v1.5.0

type FineTune struct {
	ID                string              `json:"id"`
	Object            string              `json:"object"`
	Model             string              `json:"model"`
	CreatedAt         int64               `json:"created_at"`
	FineTuneEventList []FineTuneEvent     `json:"events,omitempty"`
	FineTunedModel    string              `json:"fine_tuned_model"`
	HyperParams       FineTuneHyperParams `json:"hyperparams"`
	OrganizationID    string              `json:"organization_id"`
	ResultFiles       []File              `json:"result_files"`
	Status            string              `json:"status"`
	ValidationFiles   []File              `json:"validation_files"`
	TrainingFiles     []File              `json:"training_files"`
	UpdatedAt         int64               `json:"updated_at"`
	// contains filtered or unexported fields
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*FineTune) GetRateLimitHeaders added in v1.16.0

func (h *FineTune) GetRateLimitHeaders() RateLimitHeaders

func (*FineTune) Header added in v1.16.0

func (h *FineTune) Header() http.Header

func (*FineTune) SetHeader added in v1.16.0

func (h *FineTune) SetHeader(header http.Header)

type FineTuneDeleteResponse deprecated added in v1.5.0

type FineTuneDeleteResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*FineTuneDeleteResponse) GetRateLimitHeaders added in v1.16.0

func (h *FineTuneDeleteResponse) GetRateLimitHeaders() RateLimitHeaders

func (*FineTuneDeleteResponse) Header added in v1.16.0

func (h *FineTuneDeleteResponse) Header() http.Header

func (*FineTuneDeleteResponse) SetHeader added in v1.16.0

func (h *FineTuneDeleteResponse) SetHeader(header http.Header)

type FineTuneEvent deprecated added in v1.5.0

type FineTuneEvent struct {
	Object    string `json:"object"`
	CreatedAt int64  `json:"created_at"`
	Level     string `json:"level"`
	Message   string `json:"message"`
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

type FineTuneEventList deprecated added in v1.5.0

type FineTuneEventList struct {
	Object string          `json:"object"`
	Data   []FineTuneEvent `json:"data"`
	// contains filtered or unexported fields
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*FineTuneEventList) GetRateLimitHeaders added in v1.16.0

func (h *FineTuneEventList) GetRateLimitHeaders() RateLimitHeaders

func (*FineTuneEventList) Header added in v1.16.0

func (h *FineTuneEventList) Header() http.Header

func (*FineTuneEventList) SetHeader added in v1.16.0

func (h *FineTuneEventList) SetHeader(header http.Header)

type FineTuneHyperParams deprecated added in v1.5.0

type FineTuneHyperParams struct {
	BatchSize              int     `json:"batch_size"`
	LearningRateMultiplier float64 `json:"learning_rate_multiplier"`
	Epochs                 int     `json:"n_epochs"`
	PromptLossWeight       float64 `json:"prompt_loss_weight"`
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

type FineTuneList deprecated added in v1.5.0

type FineTuneList struct {
	Object string     `json:"object"`
	Data   []FineTune `json:"data"`
	// contains filtered or unexported fields
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

func (*FineTuneList) GetRateLimitHeaders added in v1.16.0

func (h *FineTuneList) GetRateLimitHeaders() RateLimitHeaders

func (*FineTuneList) Header added in v1.16.0

func (h *FineTuneList) Header() http.Header

func (*FineTuneList) SetHeader added in v1.16.0

func (h *FineTuneList) SetHeader(header http.Header)

type FineTuneModelDeleteResponse added in v1.15.4

type FineTuneModelDeleteResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

FineTuneModelDeleteResponse represents the deletion status of a fine-tuned model.

func (*FineTuneModelDeleteResponse) GetRateLimitHeaders added in v1.16.0

func (h *FineTuneModelDeleteResponse) GetRateLimitHeaders() RateLimitHeaders

func (*FineTuneModelDeleteResponse) Header added in v1.16.0

func (h *FineTuneModelDeleteResponse) Header() http.Header

func (*FineTuneModelDeleteResponse) SetHeader added in v1.16.0

func (h *FineTuneModelDeleteResponse) SetHeader(header http.Header)

type FineTuneRequest deprecated added in v1.5.0

type FineTuneRequest struct {
	TrainingFile                 string    `json:"training_file"`
	ValidationFile               string    `json:"validation_file,omitempty"`
	Model                        string    `json:"model,omitempty"`
	Epochs                       int       `json:"n_epochs,omitempty"`
	BatchSize                    int       `json:"batch_size,omitempty"`
	LearningRateMultiplier       float32   `json:"learning_rate_multiplier,omitempty"`
	PromptLossRate               float32   `json:"prompt_loss_rate,omitempty"`
	ComputeClassificationMetrics bool      `json:"compute_classification_metrics,omitempty"`
	ClassificationClasses        int       `json:"classification_n_classes,omitempty"`
	ClassificationPositiveClass  string    `json:"classification_positive_class,omitempty"`
	ClassificationBetas          []float32 `json:"classification_betas,omitempty"`
	Suffix                       string    `json:"suffix,omitempty"`
}

Deprecated: On August 22nd, 2023, OpenAI announced the deprecation of the /v1/fine-tunes API. This API will be officially deprecated on January 4th, 2024. OpenAI recommends to migrate to the new fine tuning API implemented in fine_tuning_job.go.

type FineTuningJob added in v1.15.1

type FineTuningJob struct {
	ID              string          `json:"id"`
	Object          string          `json:"object"`
	CreatedAt       int64           `json:"created_at"`
	FinishedAt      int64           `json:"finished_at"`
	Model           string          `json:"model"`
	FineTunedModel  string          `json:"fine_tuned_model,omitempty"`
	OrganizationID  string          `json:"organization_id"`
	Status          string          `json:"status"`
	Hyperparameters Hyperparameters `json:"hyperparameters"`
	TrainingFile    string          `json:"training_file"`
	ValidationFile  string          `json:"validation_file,omitempty"`
	ResultFiles     []string        `json:"result_files"`
	TrainedTokens   int             `json:"trained_tokens"`
	// contains filtered or unexported fields
}

func (*FineTuningJob) GetRateLimitHeaders added in v1.16.0

func (h *FineTuningJob) GetRateLimitHeaders() RateLimitHeaders

func (*FineTuningJob) Header added in v1.16.0

func (h *FineTuningJob) Header() http.Header

func (*FineTuningJob) SetHeader added in v1.16.0

func (h *FineTuningJob) SetHeader(header http.Header)

type FineTuningJobEvent added in v1.15.1

type FineTuningJobEvent struct {
	Object    string `json:"object"`
	ID        string `json:"id"`
	CreatedAt int    `json:"created_at"`
	Level     string `json:"level"`
	Message   string `json:"message"`
	Data      any    `json:"data"`
	Type      string `json:"type"`
}

type FineTuningJobEventList added in v1.15.1

type FineTuningJobEventList struct {
	Object  string          `json:"object"`
	Data    []FineTuneEvent `json:"data"`
	HasMore bool            `json:"has_more"`
	// contains filtered or unexported fields
}

func (*FineTuningJobEventList) GetRateLimitHeaders added in v1.16.0

func (h *FineTuningJobEventList) GetRateLimitHeaders() RateLimitHeaders

func (*FineTuningJobEventList) Header added in v1.16.0

func (h *FineTuningJobEventList) Header() http.Header

func (*FineTuningJobEventList) SetHeader added in v1.16.0

func (h *FineTuningJobEventList) SetHeader(header http.Header)

type FineTuningJobRequest added in v1.15.1

type FineTuningJobRequest struct {
	TrainingFile    string           `json:"training_file"`
	ValidationFile  string           `json:"validation_file,omitempty"`
	Model           string           `json:"model,omitempty"`
	Hyperparameters *Hyperparameters `json:"hyperparameters,omitempty"`
	Suffix          string           `json:"suffix,omitempty"`
}

type FinishReason added in v1.11.0

type FinishReason string
const (
	FinishReasonStop          FinishReason = "stop"
	FinishReasonLength        FinishReason = "length"
	FinishReasonFunctionCall  FinishReason = "function_call"
	FinishReasonToolCalls     FinishReason = "tool_calls"
	FinishReasonContentFilter FinishReason = "content_filter"
	FinishReasonNull          FinishReason = "null"
)

func (FinishReason) MarshalJSON added in v1.14.2

func (r FinishReason) MarshalJSON() ([]byte, error)

type FunctionCall added in v1.11.0

type FunctionCall struct {
	Name string `json:"name,omitempty"`
	// call function with arguments in JSON format
	Arguments string `json:"arguments,omitempty"`
}

type FunctionDefine deprecated added in v1.11.0

type FunctionDefine = FunctionDefinition

Deprecated: use FunctionDefinition instead.

type FunctionDefinition added in v1.11.3

type FunctionDefinition struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Strict      bool   `json:"strict,omitempty"`
	// Parameters is an object describing the function.
	// You can pass json.RawMessage to describe the schema,
	// or you can pass in a struct which serializes to the proper JSON schema.
	// The jsonschema package is provided for convenience, but you should
	// consider another specialized library if you require more complex schemas.
	Parameters any `json:"parameters"`
}

type HTTPDoer added in v1.28.3

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

type Hate added in v1.14.1

type Hate struct {
	Filtered bool   `json:"filtered"`
	Severity string `json:"severity,omitempty"`
}

type Hyperparameters added in v1.15.1

type Hyperparameters struct {
	Epochs                 any `json:"n_epochs,omitempty"`
	LearningRateMultiplier any `json:"learning_rate_multiplier,omitempty"`
	BatchSize              any `json:"batch_size,omitempty"`
}

type ImageEditRequest

type ImageEditRequest struct {
	Image          io.Reader `json:"image,omitempty"`
	Mask           io.Reader `json:"mask,omitempty"`
	Prompt         string    `json:"prompt,omitempty"`
	Model          string    `json:"model,omitempty"`
	N              int       `json:"n,omitempty"`
	Size           string    `json:"size,omitempty"`
	ResponseFormat string    `json:"response_format,omitempty"`
	Quality        string    `json:"quality,omitempty"`
	User           string    `json:"user,omitempty"`
}

ImageEditRequest represents the request structure for the image API. Use WrapReader to wrap an io.Reader with filename and Content-type.

type ImageFile added in v1.17.6

type ImageFile struct {
	FileID string `json:"file_id"`
}

type ImageRequest

type ImageRequest struct {
	Prompt            string `json:"prompt,omitempty"`
	Model             string `json:"model,omitempty"`
	N                 int    `json:"n,omitempty"`
	Quality           string `json:"quality,omitempty"`
	Size              string `json:"size,omitempty"`
	Style             string `json:"style,omitempty"`
	ResponseFormat    string `json:"response_format,omitempty"`
	User              string `json:"user,omitempty"`
	Background        string `json:"background,omitempty"`
	Moderation        string `json:"moderation,omitempty"`
	OutputCompression int    `json:"output_compression,omitempty"`
	OutputFormat      string `json:"output_format,omitempty"`
}

ImageRequest represents the request structure for the image API.

type ImageResponse

type ImageResponse struct {
	Created int64                    `json:"created,omitempty"`
	Data    []ImageResponseDataInner `json:"data,omitempty"`
	Usage   ImageResponseUsage       `json:"usage,omitempty"`
	// contains filtered or unexported fields
}

ImageResponse represents a response structure for image API.

func (*ImageResponse) GetRateLimitHeaders added in v1.16.0

func (h *ImageResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ImageResponse) Header added in v1.16.0

func (h *ImageResponse) Header() http.Header

func (*ImageResponse) SetHeader added in v1.16.0

func (h *ImageResponse) SetHeader(header http.Header)

type ImageResponseDataInner

type ImageResponseDataInner struct {
	URL           string `json:"url,omitempty"`
	B64JSON       string `json:"b64_json,omitempty"`
	RevisedPrompt string `json:"revised_prompt,omitempty"`
}

ImageResponseDataInner represents a response data structure for image API.

type ImageResponseInputTokensDetails added in v1.40.0

type ImageResponseInputTokensDetails struct {
	TextTokens  int `json:"text_tokens,omitempty"`
	ImageTokens int `json:"image_tokens,omitempty"`
}

ImageResponseInputTokensDetails represents the token breakdown for input tokens.

type ImageResponseUsage added in v1.40.0

type ImageResponseUsage struct {
	TotalTokens        int                             `json:"total_tokens,omitempty"`
	InputTokens        int                             `json:"input_tokens,omitempty"`
	OutputTokens       int                             `json:"output_tokens,omitempty"`
	InputTokensDetails ImageResponseInputTokensDetails `json:"input_tokens_details,omitempty"`
}

ImageResponseUsage represents the token usage information for image API.

type ImageURL added in v1.38.0

type ImageURL struct {
	URL    string `json:"url"`
	Detail string `json:"detail"`
}

type ImageURLDetail added in v1.17.9

type ImageURLDetail string
const (
	ImageURLDetailHigh ImageURLDetail = "high"
	ImageURLDetailLow  ImageURLDetail = "low"
	ImageURLDetailAuto ImageURLDetail = "auto"
)

type ImageVariRequest added in v1.5.1

type ImageVariRequest struct {
	Image          io.Reader `json:"image,omitempty"`
	Model          string    `json:"model,omitempty"`
	N              int       `json:"n,omitempty"`
	Size           string    `json:"size,omitempty"`
	ResponseFormat string    `json:"response_format,omitempty"`
	User           string    `json:"user,omitempty"`
}

ImageVariRequest represents the request structure for the image API. Use WrapReader to wrap an io.Reader with filename and Content-type.

type InnerError added in v1.14.2

type InnerError struct {
	Code                 string               `json:"code,omitempty"`
	ContentFilterResults ContentFilterResults `json:"content_filter_result,omitempty"`
}

InnerError Azure Content filtering. Only valid for Azure OpenAI Service.

type JailBreak added in v1.32.0

type JailBreak struct {
	Filtered bool `json:"filtered"`
	Detected bool `json:"detected"`
}

type ListBatchResponse added in v1.25.0

type ListBatchResponse struct {
	Object  string  `json:"object"`
	Data    []Batch `json:"data"`
	FirstID string  `json:"first_id"`
	LastID  string  `json:"last_id"`
	HasMore bool    `json:"has_more"`
	// contains filtered or unexported fields
}

func (*ListBatchResponse) GetRateLimitHeaders added in v1.25.0

func (h *ListBatchResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ListBatchResponse) Header added in v1.25.0

func (h *ListBatchResponse) Header() http.Header

func (*ListBatchResponse) SetHeader added in v1.25.0

func (h *ListBatchResponse) SetHeader(header http.Header)

type ListFineTuningJobEventsParameter added in v1.15.1

type ListFineTuningJobEventsParameter func(*listFineTuningJobEventsParameters)

func ListFineTuningJobEventsWithAfter added in v1.15.1

func ListFineTuningJobEventsWithAfter(after string) ListFineTuningJobEventsParameter

func ListFineTuningJobEventsWithLimit added in v1.15.1

func ListFineTuningJobEventsWithLimit(limit int) ListFineTuningJobEventsParameter

type LogProb added in v1.17.11

type LogProb struct {
	Token   string  `json:"token"`
	LogProb float64 `json:"logprob"`
	Bytes   []byte  `json:"bytes,omitempty"` // Omitting the field if it is null
	// TopLogProbs is a list of the most likely tokens and their log probability, at this token position.
	// In rare cases, there may be fewer than the number of requested top_logprobs returned.
	TopLogProbs []TopLogProbs `json:"top_logprobs"`
}

LogProb represents the probability information for a token.

type LogProbs added in v1.17.11

type LogProbs struct {
	// Content is a list of message content tokens with log probability information.
	Content []LogProb `json:"content"`
}

LogProbs is the top-level structure containing the log probability information.

type LogprobResult

type LogprobResult struct {
	Tokens        []string             `json:"tokens"`
	TokenLogprobs []float32            `json:"token_logprobs"`
	TopLogprobs   []map[string]float32 `json:"top_logprobs"`
	TextOffset    []int                `json:"text_offset"`
}

LogprobResult represents logprob result of Choice.

type Message added in v1.17.6

type Message struct {
	ID          string           `json:"id"`
	Object      string           `json:"object"`
	CreatedAt   int              `json:"created_at"`
	ThreadID    string           `json:"thread_id"`
	Role        string           `json:"role"`
	Content     []MessageContent `json:"content"`
	FileIds     []string         `json:"file_ids"` //nolint:revive //backwards-compatibility
	AssistantID *string          `json:"assistant_id,omitempty"`
	RunID       *string          `json:"run_id,omitempty"`
	Metadata    map[string]any   `json:"metadata"`
	// contains filtered or unexported fields
}

func (*Message) GetRateLimitHeaders added in v1.17.6

func (h *Message) GetRateLimitHeaders() RateLimitHeaders

func (*Message) Header added in v1.17.6

func (h *Message) Header() http.Header

func (*Message) SetHeader added in v1.17.6

func (h *Message) SetHeader(header http.Header)

type MessageContent added in v1.17.6

type MessageContent struct {
	Type      string       `json:"type"`
	Text      *MessageText `json:"text,omitempty"`
	ImageFile *ImageFile   `json:"image_file,omitempty"`
	ImageURL  *ImageURL    `json:"image_url,omitempty"`
}

type MessageDeletionStatus added in v1.28.3

type MessageDeletionStatus struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

func (*MessageDeletionStatus) GetRateLimitHeaders added in v1.28.3

func (h *MessageDeletionStatus) GetRateLimitHeaders() RateLimitHeaders

func (*MessageDeletionStatus) Header added in v1.28.3

func (h *MessageDeletionStatus) Header() http.Header

func (*MessageDeletionStatus) SetHeader added in v1.28.3

func (h *MessageDeletionStatus) SetHeader(header http.Header)

type MessageFile added in v1.17.6

type MessageFile struct {
	ID        string `json:"id"`
	Object    string `json:"object"`
	CreatedAt int    `json:"created_at"`
	MessageID string `json:"message_id"`
	// contains filtered or unexported fields
}

func (*MessageFile) GetRateLimitHeaders added in v1.17.6

func (h *MessageFile) GetRateLimitHeaders() RateLimitHeaders

func (*MessageFile) Header added in v1.17.6

func (h *MessageFile) Header() http.Header

func (*MessageFile) SetHeader added in v1.17.6

func (h *MessageFile) SetHeader(header http.Header)

type MessageFilesList added in v1.17.6

type MessageFilesList struct {
	MessageFiles []MessageFile `json:"data"`
	// contains filtered or unexported fields
}

func (*MessageFilesList) GetRateLimitHeaders added in v1.17.6

func (h *MessageFilesList) GetRateLimitHeaders() RateLimitHeaders

func (*MessageFilesList) Header added in v1.17.6

func (h *MessageFilesList) Header() http.Header

func (*MessageFilesList) SetHeader added in v1.17.6

func (h *MessageFilesList) SetHeader(header http.Header)

type MessageRequest added in v1.17.6

type MessageRequest struct {
	Role        string             `json:"role"`
	Content     string             `json:"content"`
	FileIds     []string           `json:"file_ids,omitempty"` //nolint:revive // backwards-compatibility
	Metadata    map[string]any     `json:"metadata,omitempty"`
	Attachments []ThreadAttachment `json:"attachments,omitempty"`
}

type MessageText added in v1.17.6

type MessageText struct {
	Value       string `json:"value"`
	Annotations []any  `json:"annotations"`
}

type MessagesList added in v1.17.6

type MessagesList struct {
	Messages []Message `json:"data"`

	Object  string  `json:"object"`
	FirstID *string `json:"first_id"`
	LastID  *string `json:"last_id"`
	HasMore bool    `json:"has_more"`
	// contains filtered or unexported fields
}

func (*MessagesList) GetRateLimitHeaders added in v1.17.6

func (h *MessagesList) GetRateLimitHeaders() RateLimitHeaders

func (*MessagesList) Header added in v1.17.6

func (h *MessagesList) Header() http.Header

func (*MessagesList) SetHeader added in v1.17.6

func (h *MessagesList) SetHeader(header http.Header)

type Model

type Model struct {
	CreatedAt  int64        `json:"created"`
	ID         string       `json:"id"`
	Object     string       `json:"object"`
	OwnedBy    string       `json:"owned_by"`
	Permission []Permission `json:"permission"`
	Root       string       `json:"root"`
	Parent     string       `json:"parent"`
	// contains filtered or unexported fields
}

Model struct represents an OpenAPI model.

func (*Model) GetRateLimitHeaders added in v1.16.0

func (h *Model) GetRateLimitHeaders() RateLimitHeaders

func (*Model) Header added in v1.16.0

func (h *Model) Header() http.Header

func (*Model) SetHeader added in v1.16.0

func (h *Model) SetHeader(header http.Header)

type ModelsList

type ModelsList struct {
	Models []Model `json:"data"`
	// contains filtered or unexported fields
}

ModelsList is a list of models, including those that belong to the user or organization.

func (*ModelsList) GetRateLimitHeaders added in v1.16.0

func (h *ModelsList) GetRateLimitHeaders() RateLimitHeaders

func (*ModelsList) Header added in v1.16.0

func (h *ModelsList) Header() http.Header

func (*ModelsList) SetHeader added in v1.16.0

func (h *ModelsList) SetHeader(header http.Header)

type ModerationRequest

type ModerationRequest struct {
	Input string `json:"input,omitempty"`
	Model string `json:"model,omitempty"`
}

ModerationRequest represents a request structure for moderation API.

type ModerationResponse

type ModerationResponse struct {
	ID      string   `json:"id"`
	Model   string   `json:"model"`
	Results []Result `json:"results"`
	// contains filtered or unexported fields
}

ModerationResponse represents a response structure for moderation API.

func (*ModerationResponse) GetRateLimitHeaders added in v1.16.0

func (h *ModerationResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ModerationResponse) Header added in v1.16.0

func (h *ModerationResponse) Header() http.Header

func (*ModerationResponse) SetHeader added in v1.16.0

func (h *ModerationResponse) SetHeader(header http.Header)

type ModifyThreadRequest added in v1.17.4

type ModifyThreadRequest struct {
	Metadata      map[string]any `json:"metadata"`
	ToolResources *ToolResources `json:"tool_resources,omitempty"`
}

type Pagination added in v1.17.5

type Pagination struct {
	Limit  *int
	Order  *string
	After  *string
	Before *string
}

type Permission

type Permission struct {
	CreatedAt          int64       `json:"created"`
	ID                 string      `json:"id"`
	Object             string      `json:"object"`
	AllowCreateEngine  bool        `json:"allow_create_engine"`
	AllowSampling      bool        `json:"allow_sampling"`
	AllowLogprobs      bool        `json:"allow_logprobs"`
	AllowSearchIndices bool        `json:"allow_search_indices"`
	AllowView          bool        `json:"allow_view"`
	AllowFineTuning    bool        `json:"allow_fine_tuning"`
	Organization       string      `json:"organization"`
	Group              interface{} `json:"group"`
	IsBlocking         bool        `json:"is_blocking"`
}

Permission struct represents an OpenAPI permission.

type Prediction added in v1.39.0

type Prediction struct {
	Content string `json:"content"`
	Type    string `json:"type"`
}

type Profanity added in v1.32.0

type Profanity struct {
	Filtered bool `json:"filtered"`
	Detected bool `json:"detected"`
}

type PromptAnnotation added in v1.14.1

type PromptAnnotation struct {
	PromptIndex          int                  `json:"prompt_index,omitempty"`
	ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
}

type PromptFilterResult added in v1.22.0

type PromptFilterResult struct {
	Index                int                  `json:"index"`
	ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
}

type PromptTokensDetails added in v1.32.0

type PromptTokensDetails struct {
	AudioTokens  int `json:"audio_tokens"`
	CachedTokens int `json:"cached_tokens"`
}

PromptTokensDetails Breakdown of tokens used in the prompt.

type PurposeType added in v1.17.7

type PurposeType string

PurposeType represents the purpose of the file when uploading.

const (
	PurposeFineTune         PurposeType = "fine-tune"
	PurposeFineTuneResults  PurposeType = "fine-tune-results"
	PurposeAssistants       PurposeType = "assistants"
	PurposeAssistantsOutput PurposeType = "assistants_output"
	PurposeBatch            PurposeType = "batch"
)

type RateLimitHeaders added in v1.16.0

type RateLimitHeaders struct {
	LimitRequests     int       `json:"x-ratelimit-limit-requests"`
	LimitTokens       int       `json:"x-ratelimit-limit-tokens"`
	RemainingRequests int       `json:"x-ratelimit-remaining-requests"`
	RemainingTokens   int       `json:"x-ratelimit-remaining-tokens"`
	ResetRequests     ResetTime `json:"x-ratelimit-reset-requests"`
	ResetTokens       ResetTime `json:"x-ratelimit-reset-tokens"`
}

RateLimitHeaders struct represents Openai rate limits headers.

type RawResponse added in v1.20.5

type RawResponse struct {
	io.ReadCloser
	// contains filtered or unexported fields
}

func (*RawResponse) GetRateLimitHeaders added in v1.20.5

func (h *RawResponse) GetRateLimitHeaders() RateLimitHeaders

func (*RawResponse) Header added in v1.20.5

func (h *RawResponse) Header() http.Header

func (*RawResponse) SetHeader added in v1.20.5

func (h *RawResponse) SetHeader(header http.Header)

type ReasoningValidator added in v1.37.0

type ReasoningValidator struct{}

ReasoningValidator handles validation for reasoning model requests.

func NewReasoningValidator added in v1.37.0

func NewReasoningValidator() *ReasoningValidator

NewReasoningValidator creates a new validator for reasoning models.

func (*ReasoningValidator) Validate added in v1.37.0

func (v *ReasoningValidator) Validate(request ChatCompletionRequest) error

Validate performs all validation checks for reasoning models.

type ReponseFormat added in v1.24.2

type ReponseFormat struct {
	Type string `json:"type"`
}

ReponseFormat specifies the format the model must output. https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-response_format. Type can either be text or json_object.

type RequestError

type RequestError struct {
	HTTPStatus     string
	HTTPStatusCode int
	Err            error
	Body           []byte
}

RequestError provides information about generic request errors.

func (*RequestError) Error

func (e *RequestError) Error() string

func (*RequestError) Unwrap

func (e *RequestError) Unwrap() error

type RequiredActionType added in v1.17.5

type RequiredActionType string
const (
	RequiredActionTypeSubmitToolOutputs RequiredActionType = "submit_tool_outputs"
)

type ResetTime added in v1.16.0

type ResetTime string

func (ResetTime) String added in v1.16.0

func (r ResetTime) String() string

func (ResetTime) Time added in v1.16.0

func (r ResetTime) Time() time.Time

type Response added in v1.16.0

type Response interface {
	SetHeader(http.Header)
}

type ResponseAnnotation added in v1.42.0

type ResponseAnnotation struct {
	Type       string `json:"type"`
	FileID     string `json:"file_id,omitempty"`
	Filename   string `json:"filename,omitempty"`
	Index      int    `json:"index,omitempty"`
	StartIndex int    `json:"start_index,omitempty"`
	EndIndex   int    `json:"end_index,omitempty"`
	URL        string `json:"url,omitempty"`
	Title      string `json:"title,omitempty"`
}

ResponseAnnotation describes a citation or file annotation in output text.

type ResponseCompaction added in v1.42.0

type ResponseCompaction struct {
	ID        string         `json:"id"`
	Object    string         `json:"object"`
	CreatedAt int64          `json:"created_at"`
	Output    []any          `json:"output"`
	Usage     *ResponseUsage `json:"usage,omitempty"`
	// contains filtered or unexported fields
}

ResponseCompaction is a compacted response context.

func (*ResponseCompaction) GetRateLimitHeaders added in v1.42.0

func (h *ResponseCompaction) GetRateLimitHeaders() RateLimitHeaders

func (*ResponseCompaction) Header added in v1.42.0

func (h *ResponseCompaction) Header() http.Header

func (*ResponseCompaction) SetHeader added in v1.42.0

func (h *ResponseCompaction) SetHeader(header http.Header)

type ResponseConversation added in v1.42.0

type ResponseConversation struct {
	ID string `json:"id"`
}

ResponseConversation identifies the conversation associated with a response.

type ResponseDeleteResponse added in v1.42.0

type ResponseDeleteResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

ResponseDeleteResponse is returned after deleting a stored response.

func (*ResponseDeleteResponse) GetRateLimitHeaders added in v1.42.0

func (h *ResponseDeleteResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ResponseDeleteResponse) Header added in v1.42.0

func (h *ResponseDeleteResponse) Header() http.Header

func (*ResponseDeleteResponse) SetHeader added in v1.42.0

func (h *ResponseDeleteResponse) SetHeader(header http.Header)

type ResponseError added in v1.42.0

type ResponseError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ResponseError is an error embedded in an otherwise successful Responses API request.

type ResponseFunctionCallOutput added in v1.42.0

type ResponseFunctionCallOutput struct {
	Type   string `json:"type"`
	CallID string `json:"call_id"`
	Output any    `json:"output"`
	Status string `json:"status,omitempty"`
}

ResponseFunctionCallOutput supplies the result of a prior function call.

type ResponseInclude added in v1.42.0

type ResponseInclude string

ResponseInclude identifies optional data to include in a response.

const (
	ResponseIncludeFileSearchCallResults      ResponseInclude = "file_search_call.results"
	ResponseIncludeWebSearchCallResults       ResponseInclude = "web_search_call.results"
	ResponseIncludeWebSearchCallActionSources ResponseInclude = "web_search_call.action.sources"
	ResponseIncludeInputImageURL              ResponseInclude = "message.input_image.image_url"
	ResponseIncludeComputerCallOutputImageURL ResponseInclude = "computer_call_output.output.image_url"
	ResponseIncludeCodeInterpreterCallOutputs ResponseInclude = "code_interpreter_call.outputs"
	ResponseIncludeReasoningEncryptedContent  ResponseInclude = "reasoning.encrypted_content"
	ResponseIncludeMessageOutputTextLogprobs  ResponseInclude = "message.output_text.logprobs"
)

type ResponseIncompleteDetails added in v1.42.0

type ResponseIncompleteDetails struct {
	Reason string `json:"reason,omitempty"`
}

ResponseIncompleteDetails explains why a response did not complete.

type ResponseInputFile added in v1.42.0

type ResponseInputFile struct {
	Type                  string                         `json:"type"`
	FileData              string                         `json:"file_data,omitempty"`
	FileID                string                         `json:"file_id,omitempty"`
	FileURL               string                         `json:"file_url,omitempty"`
	Filename              string                         `json:"filename,omitempty"`
	Detail                string                         `json:"detail,omitempty"`
	PromptCacheBreakpoint *ResponsePromptCacheBreakpoint `json:"prompt_cache_breakpoint,omitempty"`
}

ResponseInputFile is a file content part in a structured input message.

type ResponseInputImage added in v1.42.0

type ResponseInputImage struct {
	Type                  string                         `json:"type"`
	Detail                string                         `json:"detail,omitempty"`
	FileID                string                         `json:"file_id,omitempty"`
	ImageURL              string                         `json:"image_url,omitempty"`
	PromptCacheBreakpoint *ResponsePromptCacheBreakpoint `json:"prompt_cache_breakpoint,omitempty"`
}

ResponseInputImage is an image content part in a structured input message.

type ResponseInputItemsList added in v1.42.0

type ResponseInputItemsList struct {
	Object  string `json:"object"`
	Data    []any  `json:"data"`
	FirstID string `json:"first_id"`
	LastID  string `json:"last_id"`
	HasMore bool   `json:"has_more"`
	// contains filtered or unexported fields
}

ResponseInputItemsList contains the input items for a response.

func (*ResponseInputItemsList) GetRateLimitHeaders added in v1.42.0

func (h *ResponseInputItemsList) GetRateLimitHeaders() RateLimitHeaders

func (*ResponseInputItemsList) Header added in v1.42.0

func (h *ResponseInputItemsList) Header() http.Header

func (*ResponseInputItemsList) SetHeader added in v1.42.0

func (h *ResponseInputItemsList) SetHeader(header http.Header)

type ResponseInputItemsListOptions added in v1.42.0

type ResponseInputItemsListOptions struct {
	After   string
	Include []ResponseInclude
	Limit   int
	Order   string
}

ResponseInputItemsListOptions controls pagination for ListResponseInputItems.

type ResponseInputMessage added in v1.42.0

type ResponseInputMessage struct {
	Type    string `json:"type,omitempty"`
	Role    string `json:"role"`
	Content any    `json:"content"`
	Status  string `json:"status,omitempty"`
	Phase   string `json:"phase,omitempty"`
}

ResponseInputMessage is a message supplied as structured input.

type ResponseInputText added in v1.42.0

type ResponseInputText struct {
	Type                  string                         `json:"type"`
	Text                  string                         `json:"text"`
	PromptCacheBreakpoint *ResponsePromptCacheBreakpoint `json:"prompt_cache_breakpoint,omitempty"`
}

ResponseInputText is a text content part in a structured input message.

type ResponseInputTokensDetails added in v1.42.0

type ResponseInputTokensDetails struct {
	CachedTokens     int `json:"cached_tokens"`
	CacheWriteTokens int `json:"cache_write_tokens"`
}

ResponseInputTokensDetails is the input-token usage breakdown.

type ResponseInputTokensRequest added in v1.42.0

type ResponseInputTokensRequest = CreateResponseRequest

ResponseInputTokensRequest contains the response input whose tokens should be counted.

type ResponseInputTokensResponse added in v1.42.0

type ResponseInputTokensResponse struct {
	Object      string `json:"object"`
	InputTokens int    `json:"input_tokens"`
	// contains filtered or unexported fields
}

ResponseInputTokensResponse reports the token count for response input.

func (*ResponseInputTokensResponse) GetRateLimitHeaders added in v1.42.0

func (h *ResponseInputTokensResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ResponseInputTokensResponse) Header added in v1.42.0

func (h *ResponseInputTokensResponse) Header() http.Header

func (*ResponseInputTokensResponse) SetHeader added in v1.42.0

func (h *ResponseInputTokensResponse) SetHeader(header http.Header)

type ResponseLogprob added in v1.42.0

type ResponseLogprob struct {
	Token       string            `json:"token"`
	Bytes       []int64           `json:"bytes,omitempty"`
	Logprob     float64           `json:"logprob"`
	TopLogprobs []ResponseLogprob `json:"top_logprobs,omitempty"`
}

ResponseLogprob contains token log-probability information.

type ResponseOutputContent added in v1.42.0

type ResponseOutputContent struct {
	Type        string               `json:"type"`
	Text        string               `json:"text,omitempty"`
	Refusal     string               `json:"refusal,omitempty"`
	Annotations []ResponseAnnotation `json:"annotations,omitempty"`
	Logprobs    []ResponseLogprob    `json:"logprobs,omitempty"`
}

ResponseOutputContent is a text or refusal content part in an output message.

type ResponseOutputItem added in v1.42.0

type ResponseOutputItem struct {
	ID        string                  `json:"id,omitempty"`
	Type      string                  `json:"type"`
	Status    string                  `json:"status,omitempty"`
	Role      string                  `json:"role,omitempty"`
	Content   []ResponseOutputContent `json:"content,omitempty"`
	CallID    string                  `json:"call_id,omitempty"`
	Name      string                  `json:"name,omitempty"`
	Arguments string                  `json:"arguments,omitempty"`
	Summary   []ResponseSummaryPart   `json:"summary,omitempty"`
	Action    any                     `json:"action,omitempty"`
	Results   any                     `json:"results,omitempty"`
	Output    any                     `json:"output,omitempty"`
}

ResponseOutputItem contains the common fields shared by response output item variants. The top-level Output field remains []any so new variants can be consumed without a library release.

type ResponseOutputTokensDetails added in v1.42.0

type ResponseOutputTokensDetails struct {
	ReasoningTokens int `json:"reasoning_tokens"`
}

ResponseOutputTokensDetails is the output-token usage breakdown.

type ResponsePrompt added in v1.42.0

type ResponsePrompt struct {
	ID        string         `json:"id"`
	Variables map[string]any `json:"variables,omitempty"`
	Version   string         `json:"version,omitempty"`
}

ResponsePrompt references a reusable prompt template.

type ResponsePromptCacheBreakpoint added in v1.42.0

type ResponsePromptCacheBreakpoint struct {
	Mode string `json:"mode"`
}

ResponsePromptCacheBreakpoint marks the end of a reusable prompt prefix.

type ResponsePromptCacheOptions added in v1.42.0

type ResponsePromptCacheOptions struct {
	Mode string `json:"mode,omitempty"`
	TTL  string `json:"ttl,omitempty"`
}

ResponsePromptCacheOptions controls prompt cache creation.

type ResponseReasoning added in v1.42.0

type ResponseReasoning struct {
	Effort          string `json:"effort,omitempty"`
	GenerateSummary string `json:"generate_summary,omitempty"`
	Summary         string `json:"summary,omitempty"`
	Context         string `json:"context,omitempty"`
	Mode            string `json:"mode,omitempty"`
}

ResponseReasoning represents reasoning configuration for the Responses API.

type ResponseStatus added in v1.42.0

type ResponseStatus string

ResponseStatus is the lifecycle status of a response.

const (
	ResponseStatusQueued     ResponseStatus = "queued"
	ResponseStatusInProgress ResponseStatus = "in_progress"
	ResponseStatusCompleted  ResponseStatus = "completed"
	ResponseStatusFailed     ResponseStatus = "failed"
	ResponseStatusIncomplete ResponseStatus = "incomplete"
	ResponseStatusCancelling ResponseStatus = "cancelling"
	ResponseStatusCancelled  ResponseStatus = "cancelled"
)

type ResponseStream added in v1.42.0

type ResponseStream struct {
	// contains filtered or unexported fields
}

ResponseStream reads server-sent events from a streaming Responses API request.

func (ResponseStream) Close added in v1.42.0

func (stream ResponseStream) Close() error

func (ResponseStream) Recv added in v1.42.0

func (stream ResponseStream) Recv() (response T, err error)

func (ResponseStream) RecvRaw added in v1.42.0

func (stream ResponseStream) RecvRaw() ([]byte, error)

type ResponseStreamEvent added in v1.42.0

type ResponseStreamEvent struct {
	Type              ResponseStreamEventType `json:"type"`
	SequenceNumber    int                     `json:"sequence_number,omitempty"`
	Response          *CreateResponseResponse `json:"response,omitempty"`
	Item              *ResponseOutputItem     `json:"item,omitempty"`
	Part              *ResponseOutputContent  `json:"part,omitempty"`
	Annotation        *ResponseAnnotation     `json:"annotation,omitempty"`
	ItemID            string                  `json:"item_id,omitempty"`
	OutputIndex       int                     `json:"output_index,omitempty"`
	ContentIndex      int                     `json:"content_index,omitempty"`
	SummaryIndex      int                     `json:"summary_index,omitempty"`
	Delta             string                  `json:"delta,omitempty"`
	Text              string                  `json:"text,omitempty"`
	Arguments         string                  `json:"arguments,omitempty"`
	PartialImageB64   string                  `json:"partial_image_b64,omitempty"`
	PartialImageIndex int                     `json:"partial_image_index,omitempty"`
	Logprobs          []ResponseLogprob       `json:"logprobs,omitempty"`
	Code              string                  `json:"code,omitempty"`
	Message           string                  `json:"message,omitempty"`
	Param             any                     `json:"param,omitempty"`
	Error             *ResponseError          `json:"error,omitempty"`
	Obfuscation       string                  `json:"obfuscation,omitempty"`
	Raw               json.RawMessage         `json:"-"`
}

ResponseStreamEvent contains the common fields across Responses API SSE event variants.

func (*ResponseStreamEvent) UnmarshalJSON added in v1.42.0

func (e *ResponseStreamEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes known event fields and retains the complete event for forward compatibility with event variants added by the API.

type ResponseStreamEventType added in v1.42.0

type ResponseStreamEventType string

ResponseStreamEventType identifies an event emitted while a response is generated.

const (
	ResponseStreamEventCreated                     ResponseStreamEventType = "response.created"
	ResponseStreamEventQueued                      ResponseStreamEventType = "response.queued"
	ResponseStreamEventInProgress                  ResponseStreamEventType = "response.in_progress"
	ResponseStreamEventCompleted                   ResponseStreamEventType = "response.completed"
	ResponseStreamEventFailed                      ResponseStreamEventType = "response.failed"
	ResponseStreamEventIncomplete                  ResponseStreamEventType = "response.incomplete"
	ResponseStreamEventOutputItemAdded             ResponseStreamEventType = "response.output_item.added"
	ResponseStreamEventOutputItemDone              ResponseStreamEventType = "response.output_item.done"
	ResponseStreamEventContentPartAdded            ResponseStreamEventType = "response.content_part.added"
	ResponseStreamEventContentPartDone             ResponseStreamEventType = "response.content_part.done"
	ResponseStreamEventOutputTextDelta             ResponseStreamEventType = "response.output_text.delta"
	ResponseStreamEventOutputTextDone              ResponseStreamEventType = "response.output_text.done"
	ResponseStreamEventOutputTextAnnotationAdded   ResponseStreamEventType = "response.output_text.annotation.added"
	ResponseStreamEventRefusalDelta                ResponseStreamEventType = "response.refusal.delta"
	ResponseStreamEventRefusalDone                 ResponseStreamEventType = "response.refusal.done"
	ResponseStreamEventFunctionArgumentsDelta      ResponseStreamEventType = "response.function_call_arguments.delta"
	ResponseStreamEventFunctionArgumentsDone       ResponseStreamEventType = "response.function_call_arguments.done"
	ResponseStreamEventReasoningSummaryTextDelta   ResponseStreamEventType = "response.reasoning_summary_text.delta"
	ResponseStreamEventReasoningSummaryTextDone    ResponseStreamEventType = "response.reasoning_summary_text.done"
	ResponseStreamEventReasoningSummaryPartAdded   ResponseStreamEventType = "response.reasoning_summary_part.added"
	ResponseStreamEventReasoningSummaryPartDone    ResponseStreamEventType = "response.reasoning_summary_part.done"
	ResponseStreamEventReasoningTextDelta          ResponseStreamEventType = "response.reasoning_text.delta"
	ResponseStreamEventReasoningTextDone           ResponseStreamEventType = "response.reasoning_text.done"
	ResponseStreamEventAudioDelta                  ResponseStreamEventType = "response.audio.delta"
	ResponseStreamEventAudioDone                   ResponseStreamEventType = "response.audio.done"
	ResponseStreamEventAudioTranscriptDelta        ResponseStreamEventType = "response.audio.transcript.delta"
	ResponseStreamEventAudioTranscriptDone         ResponseStreamEventType = "response.audio.transcript.done"
	ResponseStreamEventWebSearchInProgress         ResponseStreamEventType = "response.web_search_call.in_progress"
	ResponseStreamEventWebSearchSearching          ResponseStreamEventType = "response.web_search_call.searching"
	ResponseStreamEventWebSearchCompleted          ResponseStreamEventType = "response.web_search_call.completed"
	ResponseStreamEventFileSearchInProgress        ResponseStreamEventType = "response.file_search_call.in_progress"
	ResponseStreamEventFileSearchSearching         ResponseStreamEventType = "response.file_search_call.searching"
	ResponseStreamEventFileSearchCompleted         ResponseStreamEventType = "response.file_search_call.completed"
	ResponseStreamEventCodeInterpreterInProgress   ResponseStreamEventType = "response.code_interpreter_call.in_progress"
	ResponseStreamEventCodeInterpreterInterpreting ResponseStreamEventType = "response.code_interpreter_call.interpreting"
	ResponseStreamEventCodeInterpreterCompleted    ResponseStreamEventType = "response.code_interpreter_call.completed"
	ResponseStreamEventCodeInterpreterCodeDelta    ResponseStreamEventType = "response.code_interpreter_call_code.delta"
	ResponseStreamEventCodeInterpreterCodeDone     ResponseStreamEventType = "response.code_interpreter_call_code.done"
	ResponseStreamEventCustomToolInputDelta        ResponseStreamEventType = "response.custom_tool_call_input.delta"
	ResponseStreamEventCustomToolInputDone         ResponseStreamEventType = "response.custom_tool_call_input.done"
	ResponseStreamEventImageGenerationInProgress   ResponseStreamEventType = "response.image_generation_call.in_progress"
	ResponseStreamEventImageGenerationGenerating   ResponseStreamEventType = "response.image_generation_call.generating"
	ResponseStreamEventImageGenerationCompleted    ResponseStreamEventType = "response.image_generation_call.completed"
	ResponseStreamEventImageGenerationPartialImage ResponseStreamEventType = "response.image_generation_call.partial_image"
	ResponseStreamEventMCPCallInProgress           ResponseStreamEventType = "response.mcp_call.in_progress"
	ResponseStreamEventMCPCallCompleted            ResponseStreamEventType = "response.mcp_call.completed"
	ResponseStreamEventMCPCallFailed               ResponseStreamEventType = "response.mcp_call.failed"
	ResponseStreamEventMCPCallArgumentsDelta       ResponseStreamEventType = "response.mcp_call_arguments.delta"
	ResponseStreamEventMCPCallArgumentsDone        ResponseStreamEventType = "response.mcp_call_arguments.done"
	ResponseStreamEventMCPListToolsInProgress      ResponseStreamEventType = "response.mcp_list_tools.in_progress"
	ResponseStreamEventMCPListToolsCompleted       ResponseStreamEventType = "response.mcp_list_tools.completed"
	ResponseStreamEventMCPListToolsFailed          ResponseStreamEventType = "response.mcp_list_tools.failed"
	ResponseStreamEventError                       ResponseStreamEventType = "error"
)

type ResponseStreamOptions added in v1.42.0

type ResponseStreamOptions struct {
	IncludeObfuscation *bool `json:"include_obfuscation,omitempty"`
}

ResponseStreamOptions controls Responses API streaming behavior.

type ResponseSummaryPart added in v1.42.0

type ResponseSummaryPart struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

ResponseSummaryPart is a reasoning summary content part.

type ResponseTextConfig added in v1.42.0

type ResponseTextConfig struct {
	Format    *ResponseTextFormat `json:"format,omitempty"`
	Verbosity string              `json:"verbosity,omitempty"`
}

ResponseTextConfig controls plain-text or structured response output.

type ResponseTextFormat added in v1.42.0

type ResponseTextFormat struct {
	Type        string `json:"type"`
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	Schema      any    `json:"schema,omitempty"`
	Strict      bool   `json:"strict,omitempty"`
}

ResponseTextFormat describes the requested output format.

type ResponseTool added in v1.42.0

type ResponseTool = Tool

ResponseTool is an alias for Tool. Responses API tool-specific properties can be supplied through Tool.Parameters.

func NewResponseFunctionTool added in v1.42.0

func NewResponseFunctionTool(function FunctionDefinition) ResponseTool

NewResponseFunctionTool converts a function definition to the inline function tool representation expected by the Responses API.

type ResponseTruncation added in v1.42.0

type ResponseTruncation string

ResponseTruncation controls how input that exceeds the context window is handled.

const (
	ResponseTruncationAuto     ResponseTruncation = "auto"
	ResponseTruncationDisabled ResponseTruncation = "disabled"
)

type ResponseUsage added in v1.42.0

type ResponseUsage struct {
	InputTokens         int                          `json:"input_tokens"`
	InputTokensDetails  *ResponseInputTokensDetails  `json:"input_tokens_details,omitempty"`
	OutputTokens        int                          `json:"output_tokens"`
	OutputTokensDetails *ResponseOutputTokensDetails `json:"output_tokens_details,omitempty"`
	TotalTokens         int                          `json:"total_tokens"`
}

ResponseUsage reports token use for a response.

type Result

type Result struct {
	Categories     ResultCategories     `json:"categories"`
	CategoryScores ResultCategoryScores `json:"category_scores"`
	Flagged        bool                 `json:"flagged"`
}

Result represents one of possible moderation results.

type ResultCategories

type ResultCategories struct {
	Hate                  bool `json:"hate"`
	HateThreatening       bool `json:"hate/threatening"`
	Harassment            bool `json:"harassment"`
	HarassmentThreatening bool `json:"harassment/threatening"`
	SelfHarm              bool `json:"self-harm"`
	SelfHarmIntent        bool `json:"self-harm/intent"`
	SelfHarmInstructions  bool `json:"self-harm/instructions"`
	Sexual                bool `json:"sexual"`
	SexualMinors          bool `json:"sexual/minors"`
	Violence              bool `json:"violence"`
	ViolenceGraphic       bool `json:"violence/graphic"`
}

ResultCategories represents Categories of Result.

type ResultCategoryScores

type ResultCategoryScores struct {
	Hate                  float32 `json:"hate"`
	HateThreatening       float32 `json:"hate/threatening"`
	Harassment            float32 `json:"harassment"`
	HarassmentThreatening float32 `json:"harassment/threatening"`
	SelfHarm              float32 `json:"self-harm"`
	SelfHarmIntent        float32 `json:"self-harm/intent"`
	SelfHarmInstructions  float32 `json:"self-harm/instructions"`
	Sexual                float32 `json:"sexual"`
	SexualMinors          float32 `json:"sexual/minors"`
	Violence              float32 `json:"violence"`
	ViolenceGraphic       float32 `json:"violence/graphic"`
}

ResultCategoryScores represents CategoryScores of Result.

type RetrieveResponseOptions added in v1.42.0

type RetrieveResponseOptions struct {
	Include            []ResponseInclude
	IncludeObfuscation *bool
	StartingAfter      *int
}

RetrieveResponseOptions controls optional data returned by RetrieveResponse.

type Run added in v1.17.5

type Run struct {
	ID             string             `json:"id"`
	Object         string             `json:"object"`
	CreatedAt      int64              `json:"created_at"`
	ThreadID       string             `json:"thread_id"`
	AssistantID    string             `json:"assistant_id"`
	Status         RunStatus          `json:"status"`
	RequiredAction *RunRequiredAction `json:"required_action,omitempty"`
	LastError      *RunLastError      `json:"last_error,omitempty"`
	ExpiresAt      int64              `json:"expires_at"`
	StartedAt      *int64             `json:"started_at,omitempty"`
	CancelledAt    *int64             `json:"cancelled_at,omitempty"`
	FailedAt       *int64             `json:"failed_at,omitempty"`
	CompletedAt    *int64             `json:"completed_at,omitempty"`
	Model          string             `json:"model"`
	Instructions   string             `json:"instructions,omitempty"`
	Tools          []Tool             `json:"tools"`
	FileIDS        []string           `json:"file_ids"` //nolint:revive // backwards-compatibility
	Metadata       map[string]any     `json:"metadata"`
	Usage          Usage              `json:"usage,omitempty"`

	Temperature *float32 `json:"temperature,omitempty"`
	// The maximum number of prompt tokens that may be used over the course of the run.
	// If the run exceeds the number of prompt tokens specified, the run will end with status 'incomplete'.
	MaxPromptTokens int `json:"max_prompt_tokens,omitempty"`
	// The maximum number of completion tokens that may be used over the course of the run.
	// If the run exceeds the number of completion tokens specified, the run will end with status 'incomplete'.
	MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
	// ThreadTruncationStrategy defines the truncation strategy to use for the thread.
	TruncationStrategy *ThreadTruncationStrategy `json:"truncation_strategy,omitempty"`
	// contains filtered or unexported fields
}

func (*Run) GetRateLimitHeaders added in v1.17.5

func (h *Run) GetRateLimitHeaders() RateLimitHeaders

func (*Run) Header added in v1.17.5

func (h *Run) Header() http.Header

func (*Run) SetHeader added in v1.17.5

func (h *Run) SetHeader(header http.Header)

type RunError added in v1.17.5

type RunError string
const (
	RunErrorServerError       RunError = "server_error"
	RunErrorRateLimitExceeded RunError = "rate_limit_exceeded"
)

type RunLastError added in v1.17.5

type RunLastError struct {
	Code    RunError `json:"code"`
	Message string   `json:"message"`
}

type RunList added in v1.17.5

type RunList struct {
	Runs []Run `json:"data"`
	// contains filtered or unexported fields
}

RunList is a list of runs.

func (*RunList) GetRateLimitHeaders added in v1.17.5

func (h *RunList) GetRateLimitHeaders() RateLimitHeaders

func (*RunList) Header added in v1.17.5

func (h *RunList) Header() http.Header

func (*RunList) SetHeader added in v1.17.5

func (h *RunList) SetHeader(header http.Header)

type RunModifyRequest added in v1.17.5

type RunModifyRequest struct {
	Metadata map[string]any `json:"metadata,omitempty"`
}

type RunRequest added in v1.17.5

type RunRequest struct {
	AssistantID            string          `json:"assistant_id"`
	Model                  string          `json:"model,omitempty"`
	Instructions           string          `json:"instructions,omitempty"`
	AdditionalInstructions string          `json:"additional_instructions,omitempty"`
	AdditionalMessages     []ThreadMessage `json:"additional_messages,omitempty"`
	Tools                  []Tool          `json:"tools,omitempty"`
	Metadata               map[string]any  `json:"metadata,omitempty"`

	// Sampling temperature between 0 and 2. Higher values like 0.8 are  more random.
	// lower values are more focused and deterministic.
	Temperature *float32 `json:"temperature,omitempty"`
	TopP        *float32 `json:"top_p,omitempty"`

	// The maximum number of prompt tokens that may be used over the course of the run.
	// If the run exceeds the number of prompt tokens specified, the run will end with status 'incomplete'.
	MaxPromptTokens int `json:"max_prompt_tokens,omitempty"`

	// The maximum number of completion tokens that may be used over the course of the run.
	// If the run exceeds the number of completion tokens specified, the run will end with status 'incomplete'.
	MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`

	// ThreadTruncationStrategy defines the truncation strategy to use for the thread.
	TruncationStrategy *ThreadTruncationStrategy `json:"truncation_strategy,omitempty"`

	// This can be either a string or a ToolChoice object.
	ToolChoice any `json:"tool_choice,omitempty"`
	// This can be either a string or a ResponseFormat object.
	ResponseFormat any `json:"response_format,omitempty"`
	// Disable the default behavior of parallel tool calls by setting it: false.
	ParallelToolCalls any `json:"parallel_tool_calls,omitempty"`
}

type RunRequiredAction added in v1.17.5

type RunRequiredAction struct {
	Type              RequiredActionType `json:"type"`
	SubmitToolOutputs *SubmitToolOutputs `json:"submit_tool_outputs,omitempty"`
}

type RunStatus added in v1.17.5

type RunStatus string
const (
	RunStatusQueued         RunStatus = "queued"
	RunStatusInProgress     RunStatus = "in_progress"
	RunStatusRequiresAction RunStatus = "requires_action"
	RunStatusCancelling     RunStatus = "cancelling"
	RunStatusFailed         RunStatus = "failed"
	RunStatusCompleted      RunStatus = "completed"
	RunStatusIncomplete     RunStatus = "incomplete"
	RunStatusExpired        RunStatus = "expired"
	RunStatusCancelled      RunStatus = "cancelled"
)

type RunStep added in v1.17.5

type RunStep struct {
	ID          string         `json:"id"`
	Object      string         `json:"object"`
	CreatedAt   int64          `json:"created_at"`
	AssistantID string         `json:"assistant_id"`
	ThreadID    string         `json:"thread_id"`
	RunID       string         `json:"run_id"`
	Type        RunStepType    `json:"type"`
	Status      RunStepStatus  `json:"status"`
	StepDetails StepDetails    `json:"step_details"`
	LastError   *RunLastError  `json:"last_error,omitempty"`
	ExpiredAt   *int64         `json:"expired_at,omitempty"`
	CancelledAt *int64         `json:"cancelled_at,omitempty"`
	FailedAt    *int64         `json:"failed_at,omitempty"`
	CompletedAt *int64         `json:"completed_at,omitempty"`
	Metadata    map[string]any `json:"metadata"`
	// contains filtered or unexported fields
}

func (*RunStep) GetRateLimitHeaders added in v1.17.5

func (h *RunStep) GetRateLimitHeaders() RateLimitHeaders

func (*RunStep) Header added in v1.17.5

func (h *RunStep) Header() http.Header

func (*RunStep) SetHeader added in v1.17.5

func (h *RunStep) SetHeader(header http.Header)

type RunStepList added in v1.17.5

type RunStepList struct {
	RunSteps []RunStep `json:"data"`

	FirstID string `json:"first_id"`
	LastID  string `json:"last_id"`
	HasMore bool   `json:"has_more"`
	// contains filtered or unexported fields
}

RunStepList is a list of steps.

func (*RunStepList) GetRateLimitHeaders added in v1.17.5

func (h *RunStepList) GetRateLimitHeaders() RateLimitHeaders

func (*RunStepList) Header added in v1.17.5

func (h *RunStepList) Header() http.Header

func (*RunStepList) SetHeader added in v1.17.5

func (h *RunStepList) SetHeader(header http.Header)

type RunStepStatus added in v1.17.5

type RunStepStatus string
const (
	RunStepStatusInProgress RunStepStatus = "in_progress"
	RunStepStatusCancelling RunStepStatus = "cancelled"
	RunStepStatusFailed     RunStepStatus = "failed"
	RunStepStatusCompleted  RunStepStatus = "completed"
	RunStepStatusExpired    RunStepStatus = "expired"
)

type RunStepType added in v1.17.5

type RunStepType string
const (
	RunStepTypeMessageCreation RunStepType = "message_creation"
	RunStepTypeToolCalls       RunStepType = "tool_calls"
)

type SelfHarm added in v1.14.1

type SelfHarm struct {
	Filtered bool   `json:"filtered"`
	Severity string `json:"severity,omitempty"`
}

type ServiceTier added in v1.40.4

type ServiceTier string
const (
	ServiceTierAuto     ServiceTier = "auto"
	ServiceTierDefault  ServiceTier = "default"
	ServiceTierFlex     ServiceTier = "flex"
	ServiceTierPriority ServiceTier = "priority"
)

type Sexual added in v1.14.1

type Sexual struct {
	Filtered bool   `json:"filtered"`
	Severity string `json:"severity,omitempty"`
}

type SpeechModel added in v1.17.6

type SpeechModel string
const (
	TTSModel1         SpeechModel = "tts-1"
	TTSModel1HD       SpeechModel = "tts-1-hd"
	TTSModelCanary    SpeechModel = "canary-tts"
	TTSModelGPT4oMini SpeechModel = "gpt-4o-mini-tts"
)

type SpeechResponseFormat added in v1.17.6

type SpeechResponseFormat string
const (
	SpeechResponseFormatMp3  SpeechResponseFormat = "mp3"
	SpeechResponseFormatOpus SpeechResponseFormat = "opus"
	SpeechResponseFormatAac  SpeechResponseFormat = "aac"
	SpeechResponseFormatFlac SpeechResponseFormat = "flac"
	SpeechResponseFormatWav  SpeechResponseFormat = "wav"
	SpeechResponseFormatPcm  SpeechResponseFormat = "pcm"
)

type SpeechVoice added in v1.17.6

type SpeechVoice string
const (
	VoiceAlloy   SpeechVoice = "alloy"
	VoiceAsh     SpeechVoice = "ash"
	VoiceBallad  SpeechVoice = "ballad"
	VoiceCoral   SpeechVoice = "coral"
	VoiceEcho    SpeechVoice = "echo"
	VoiceFable   SpeechVoice = "fable"
	VoiceOnyx    SpeechVoice = "onyx"
	VoiceNova    SpeechVoice = "nova"
	VoiceShimmer SpeechVoice = "shimmer"
	VoiceVerse   SpeechVoice = "verse"
)

type StaticChunkingStrategy added in v1.25.0

type StaticChunkingStrategy struct {
	MaxChunkSizeTokens int `json:"max_chunk_size_tokens"`
	ChunkOverlapTokens int `json:"chunk_overlap_tokens"`
}

type StepDetails added in v1.17.5

type StepDetails struct {
	Type            RunStepType                 `json:"type"`
	MessageCreation *StepDetailsMessageCreation `json:"message_creation,omitempty"`
	ToolCalls       []ToolCall                  `json:"tool_calls,omitempty"`
}

type StepDetailsMessageCreation added in v1.17.5

type StepDetailsMessageCreation struct {
	MessageID string `json:"message_id"`
}

type StreamOptions added in v1.23.1

type StreamOptions struct {
	// If set, an additional chunk will be streamed before the data: [DONE] message.
	// The usage field on this chunk shows the token usage statistics for the entire request,
	// and the choices field will always be an empty array.
	// All other chunks will also include a usage field, but with a null value.
	IncludeUsage bool `json:"include_usage,omitempty"`
}

type SubmitToolOutputs added in v1.17.5

type SubmitToolOutputs struct {
	ToolCalls []ToolCall `json:"tool_calls"`
}

type SubmitToolOutputsRequest added in v1.17.5

type SubmitToolOutputsRequest struct {
	ToolOutputs []ToolOutput `json:"tool_outputs"`
}

type Thread added in v1.17.4

type Thread struct {
	ID            string         `json:"id"`
	Object        string         `json:"object"`
	CreatedAt     int64          `json:"created_at"`
	Metadata      map[string]any `json:"metadata"`
	ToolResources ToolResources  `json:"tool_resources,omitempty"`
	// contains filtered or unexported fields
}

func (*Thread) GetRateLimitHeaders added in v1.17.4

func (h *Thread) GetRateLimitHeaders() RateLimitHeaders

func (*Thread) Header added in v1.17.4

func (h *Thread) Header() http.Header

func (*Thread) SetHeader added in v1.17.4

func (h *Thread) SetHeader(header http.Header)

type ThreadAttachment added in v1.27.0

type ThreadAttachment struct {
	FileID string                 `json:"file_id"`
	Tools  []ThreadAttachmentTool `json:"tools"`
}

type ThreadAttachmentTool added in v1.27.0

type ThreadAttachmentTool struct {
	Type string `json:"type"`
}

type ThreadDeleteResponse added in v1.17.4

type ThreadDeleteResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

func (*ThreadDeleteResponse) GetRateLimitHeaders added in v1.17.4

func (h *ThreadDeleteResponse) GetRateLimitHeaders() RateLimitHeaders

func (*ThreadDeleteResponse) Header added in v1.17.4

func (h *ThreadDeleteResponse) Header() http.Header

func (*ThreadDeleteResponse) SetHeader added in v1.17.4

func (h *ThreadDeleteResponse) SetHeader(header http.Header)

type ThreadMessage added in v1.17.4

type ThreadMessage struct {
	Role        ThreadMessageRole  `json:"role"`
	Content     string             `json:"content"`
	FileIDs     []string           `json:"file_ids,omitempty"`
	Attachments []ThreadAttachment `json:"attachments,omitempty"`
	Metadata    map[string]any     `json:"metadata,omitempty"`
}

type ThreadMessageRole added in v1.17.4

type ThreadMessageRole string
const (
	ThreadMessageRoleAssistant ThreadMessageRole = "assistant"
	ThreadMessageRoleUser      ThreadMessageRole = "user"
)

type ThreadRequest added in v1.17.4

type ThreadRequest struct {
	Messages      []ThreadMessage       `json:"messages,omitempty"`
	Metadata      map[string]any        `json:"metadata,omitempty"`
	ToolResources *ToolResourcesRequest `json:"tool_resources,omitempty"`
}

type ThreadTruncationStrategy added in v1.22.0

type ThreadTruncationStrategy struct {
	// default 'auto'.
	Type TruncationStrategy `json:"type,omitempty"`
	// this field should be set if the truncation strategy is set to LastMessages.
	LastMessages *int `json:"last_messages,omitempty"`
}

ThreadTruncationStrategy defines the truncation strategy to use for the thread. https://platform.openai.com/docs/assistants/how-it-works/truncation-strategy.

type Tool added in v1.17.1

type Tool struct {
	Type     ToolType            `json:"type"`
	Function *FunctionDefinition `json:"function,omitempty"`
	// Parameters contains Responses API tool properties that are serialized next to type.
	// For example: {"search_context_size": "low"} for a web search tool.
	Parameters map[string]any `json:"-"`
}

func (Tool) MarshalJSON added in v1.42.0

func (t Tool) MarshalJSON() ([]byte, error)

MarshalJSON preserves the nested Chat Completions function format while also supporting the inline properties used by built-in and function tools in the Responses API.

type ToolCall added in v1.17.1

type ToolCall struct {
	// Index is not nil only in chat completion chunk object
	Index    *int         `json:"index,omitempty"`
	ID       string       `json:"id,omitempty"`
	Type     ToolType     `json:"type"`
	Function FunctionCall `json:"function"`
}

type ToolChoice added in v1.17.4

type ToolChoice struct {
	Type     ToolType     `json:"type"`
	Function ToolFunction `json:"function,omitempty"`
}

type ToolFunction added in v1.17.1

type ToolFunction struct {
	Name string `json:"name"`
}

type ToolOutput added in v1.17.5

type ToolOutput struct {
	ToolCallID string `json:"tool_call_id"`
	Output     any    `json:"output"`
}

type ToolResources added in v1.25.0

type ToolResources struct {
	CodeInterpreter *CodeInterpreterToolResources `json:"code_interpreter,omitempty"`
	FileSearch      *FileSearchToolResources      `json:"file_search,omitempty"`
}

type ToolResourcesRequest added in v1.25.0

type ToolResourcesRequest struct {
	CodeInterpreter *CodeInterpreterToolResourcesRequest `json:"code_interpreter,omitempty"`
	FileSearch      *FileSearchToolResourcesRequest      `json:"file_search,omitempty"`
}

type ToolType added in v1.17.1

type ToolType string
const (
	ToolTypeFunction           ToolType = "function"
	ToolTypeWebSearch          ToolType = "web_search"
	ToolTypeWebSearchPreview   ToolType = "web_search_preview"
	ToolTypeFileSearch         ToolType = "file_search"
	ToolTypeComputer           ToolType = "computer"
	ToolTypeComputerUsePreview ToolType = "computer_use_preview"
	ToolTypeComputerUse        ToolType = "computer_use"
	ToolTypeCodeInterpreter    ToolType = "code_interpreter"
	ToolTypeImageGeneration    ToolType = "image_generation"
	ToolTypeMCP                ToolType = "mcp"
	ToolTypeCustom             ToolType = "custom"
	ToolTypeLocalShell         ToolType = "local_shell"
	ToolTypeShell              ToolType = "shell"
	ToolTypeApplyPatch         ToolType = "apply_patch"
	ToolTypeToolSearch         ToolType = "tool_search"
)

type TopLogProbs added in v1.17.11

type TopLogProbs struct {
	Token   string  `json:"token"`
	LogProb float64 `json:"logprob"`
	Bytes   []byte  `json:"bytes,omitempty"`
}

type TranscriptionChunkingStrategy added in v1.42.1

type TranscriptionChunkingStrategy struct {
	Type              string  `json:"type"` // "server_vad"
	PrefixPaddingMs   int     `json:"prefix_padding_ms,omitempty"`
	SilenceDurationMs int     `json:"silence_duration_ms,omitempty"`
	Threshold         float64 `json:"threshold,omitempty"`
}

TranscriptionChunkingStrategy configures server-side VAD chunking for transcription. Assign it to AudioRequest.ChunkingStrategy when you need explicit control; pass the string "auto" instead to let the server pick the boundaries.

type TranscriptionTimestampGranularity added in v1.23.1

type TranscriptionTimestampGranularity string
const (
	TranscriptionTimestampGranularityWord    TranscriptionTimestampGranularity = "word"
	TranscriptionTimestampGranularitySegment TranscriptionTimestampGranularity = "segment"
)

type TruncationStrategy added in v1.22.0

type TruncationStrategy string

TruncationStrategy defines the existing truncation strategies existing for thread management in an assistant.

type UploadBatchFileRequest added in v1.25.0

type UploadBatchFileRequest struct {
	FileName string
	Lines    []BatchLineItem
}

func (*UploadBatchFileRequest) AddChatCompletion added in v1.25.0

func (r *UploadBatchFileRequest) AddChatCompletion(customerID string, body ChatCompletionRequest)

func (*UploadBatchFileRequest) AddCompletion added in v1.25.0

func (r *UploadBatchFileRequest) AddCompletion(customerID string, body CompletionRequest)

func (*UploadBatchFileRequest) AddEmbedding added in v1.25.0

func (r *UploadBatchFileRequest) AddEmbedding(customerID string, body EmbeddingRequest)

func (*UploadBatchFileRequest) AddResponse added in v1.42.0

func (r *UploadBatchFileRequest) AddResponse(customerID string, body CreateResponseRequest)

func (*UploadBatchFileRequest) MarshalJSONL added in v1.25.0

func (r *UploadBatchFileRequest) MarshalJSONL() []byte

type Usage

type Usage struct {
	PromptTokens            int                      `json:"prompt_tokens"`
	CompletionTokens        int                      `json:"completion_tokens"`
	TotalTokens             int                      `json:"total_tokens"`
	PromptTokensDetails     *PromptTokensDetails     `json:"prompt_tokens_details"`
	CompletionTokensDetails *CompletionTokensDetails `json:"completion_tokens_details"`
}

Usage Represents the total token usage per request to OpenAI.

type VectorStore added in v1.26.0

type VectorStore struct {
	ID           string               `json:"id"`
	Object       string               `json:"object"`
	CreatedAt    int64                `json:"created_at"`
	Name         string               `json:"name"`
	UsageBytes   int                  `json:"usage_bytes"`
	FileCounts   VectorStoreFileCount `json:"file_counts"`
	Status       string               `json:"status"`
	ExpiresAfter *VectorStoreExpires  `json:"expires_after"`
	ExpiresAt    *int                 `json:"expires_at"`
	Metadata     map[string]any       `json:"metadata"`
	// contains filtered or unexported fields
}

func (*VectorStore) GetRateLimitHeaders added in v1.26.0

func (h *VectorStore) GetRateLimitHeaders() RateLimitHeaders

func (*VectorStore) Header added in v1.26.0

func (h *VectorStore) Header() http.Header

func (*VectorStore) SetHeader added in v1.26.0

func (h *VectorStore) SetHeader(header http.Header)

type VectorStoreDeleteResponse added in v1.26.0

type VectorStoreDeleteResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
	// contains filtered or unexported fields
}

func (*VectorStoreDeleteResponse) GetRateLimitHeaders added in v1.26.0

func (h *VectorStoreDeleteResponse) GetRateLimitHeaders() RateLimitHeaders

func (*VectorStoreDeleteResponse) Header added in v1.26.0

func (h *VectorStoreDeleteResponse) Header() http.Header

func (*VectorStoreDeleteResponse) SetHeader added in v1.26.0

func (h *VectorStoreDeleteResponse) SetHeader(header http.Header)

type VectorStoreExpires added in v1.26.0

type VectorStoreExpires struct {
	Anchor string `json:"anchor"`
	Days   int    `json:"days"`
}

type VectorStoreFile added in v1.26.0

type VectorStoreFile struct {
	ID            string `json:"id"`
	Object        string `json:"object"`
	CreatedAt     int64  `json:"created_at"`
	VectorStoreID string `json:"vector_store_id"`
	UsageBytes    int    `json:"usage_bytes"`
	Status        string `json:"status"`
	// contains filtered or unexported fields
}

func (*VectorStoreFile) GetRateLimitHeaders added in v1.26.0

func (h *VectorStoreFile) GetRateLimitHeaders() RateLimitHeaders

func (*VectorStoreFile) Header added in v1.26.0

func (h *VectorStoreFile) Header() http.Header

func (*VectorStoreFile) SetHeader added in v1.26.0

func (h *VectorStoreFile) SetHeader(header http.Header)

type VectorStoreFileBatch added in v1.26.0

type VectorStoreFileBatch struct {
	ID            string               `json:"id"`
	Object        string               `json:"object"`
	CreatedAt     int64                `json:"created_at"`
	VectorStoreID string               `json:"vector_store_id"`
	Status        string               `json:"status"`
	FileCounts    VectorStoreFileCount `json:"file_counts"`
	// contains filtered or unexported fields
}

func (*VectorStoreFileBatch) GetRateLimitHeaders added in v1.26.0

func (h *VectorStoreFileBatch) GetRateLimitHeaders() RateLimitHeaders

func (*VectorStoreFileBatch) Header added in v1.26.0

func (h *VectorStoreFileBatch) Header() http.Header

func (*VectorStoreFileBatch) SetHeader added in v1.26.0

func (h *VectorStoreFileBatch) SetHeader(header http.Header)

type VectorStoreFileBatchRequest added in v1.26.0

type VectorStoreFileBatchRequest struct {
	FileIDs []string `json:"file_ids"`
}

type VectorStoreFileCount added in v1.26.0

type VectorStoreFileCount struct {
	InProgress int `json:"in_progress"`
	Completed  int `json:"completed"`
	Failed     int `json:"failed"`
	Cancelled  int `json:"cancelled"`
	Total      int `json:"total"`
}

type VectorStoreFileRequest added in v1.26.0

type VectorStoreFileRequest struct {
	FileID string `json:"file_id"`
}

type VectorStoreFilesList added in v1.26.0

type VectorStoreFilesList struct {
	VectorStoreFiles []VectorStoreFile `json:"data"`
	FirstID          *string           `json:"first_id"`
	LastID           *string           `json:"last_id"`
	HasMore          bool              `json:"has_more"`
	// contains filtered or unexported fields
}

func (*VectorStoreFilesList) GetRateLimitHeaders added in v1.26.0

func (h *VectorStoreFilesList) GetRateLimitHeaders() RateLimitHeaders

func (*VectorStoreFilesList) Header added in v1.26.0

func (h *VectorStoreFilesList) Header() http.Header

func (*VectorStoreFilesList) SetHeader added in v1.26.0

func (h *VectorStoreFilesList) SetHeader(header http.Header)

type VectorStoreRequest added in v1.26.0

type VectorStoreRequest struct {
	Name         string              `json:"name,omitempty"`
	FileIDs      []string            `json:"file_ids,omitempty"`
	ExpiresAfter *VectorStoreExpires `json:"expires_after,omitempty"`
	Metadata     map[string]any      `json:"metadata,omitempty"`
}

VectorStoreRequest provides the vector store request parameters.

type VectorStoreToolResources added in v1.25.0

type VectorStoreToolResources struct {
	FileIDs          []string          `json:"file_ids,omitempty"`
	ChunkingStrategy *ChunkingStrategy `json:"chunking_strategy,omitempty"`
	Metadata         map[string]any    `json:"metadata,omitempty"`
}

type VectorStoresList added in v1.26.0

type VectorStoresList struct {
	VectorStores []VectorStore `json:"data"`
	LastID       *string       `json:"last_id"`
	FirstID      *string       `json:"first_id"`
	HasMore      bool          `json:"has_more"`
	// contains filtered or unexported fields
}

VectorStoresList is a list of vector store.

func (*VectorStoresList) GetRateLimitHeaders added in v1.26.0

func (h *VectorStoresList) GetRateLimitHeaders() RateLimitHeaders

func (*VectorStoresList) Header added in v1.26.0

func (h *VectorStoresList) Header() http.Header

func (*VectorStoresList) SetHeader added in v1.26.0

func (h *VectorStoresList) SetHeader(header http.Header)

type Violence added in v1.14.1

type Violence struct {
	Filtered bool   `json:"filtered"`
	Severity string `json:"severity,omitempty"`
}

Directories

Path Synopsis
examples
chatbot command
completion command
images command
responses command
voice-to-text command
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL