openai

package module
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2025 License: MIT Imports: 16 Imported by: 6

README

openai-go

OpenAI API wrapper library for Go.

How to use

Generate API key from here,

and get organization id from here.

const apiKey = "ab-cdefHIJKLMNOPQRSTUVWXYZ0123456789"
const orgID = "org-0123456789ABCDefghijklmnopQRSTUVWxyz"

func main() {
    client := NewClient(apiKey, orgID)

    if models, err := client.ListModels(); err != nil {
        log.Printf("available models = %+v", models.Data)
    }
}

How to test

Export following environment variables:

$ export OPENAI_API_KEY=ab-cdefHIJKLMNOPQRSTUVWXYZ0123456789
$ export OPENAI_ORGANIZATION=org-0123456789ABCDefghijklmnopQRSTUVWxyz

# for verbose messages and http request dumps,
$ export VERBOSE=true

and then

$ go test

CAUTION: It is advised to set usage limits before running tests; running all tests at once costs about ~$0.2.

Todos/WIP

Implemented

All API functions so far (2023.11.07.) are implemented, but not all of them were tested on a paid account.

Responses API examples
// Simple text input
response, err := client.CreateResponse("gpt-4.1", "Hello, how can you help me?", nil)
if err != nil {
    log.Fatal(err)
}
log.Printf("Response: %s", response.Output[0].Content[0].Text)

// With message array input
messages := []openai.ResponseMessage{
    openai.NewResponseMessage("user", "What is the weather like?"),
    openai.NewResponseMessage("assistant", "I'd be happy to help with weather information. Could you please specify your location?"),
    openai.NewResponseMessage("user", "New York City"),
}

response, err := client.CreateResponse("gpt-4.1", messages, nil)
if err != nil {
    log.Fatal(err)
}

// With options
options := openai.ResponseOptions{}
options.SetInstructions("You are a helpful assistant.")
options.SetTemperature(0.7)
options.SetMaxOutputTokens(100)

response, err := client.CreateResponse("gpt-4.1", "Explain quantum computing", options)
if err != nil {
    log.Fatal(err)
}
Using Tools (Function Calling)
// Create a weather tool
weatherTool := openai.NewResponseTool("get_weather", 
    "Get current temperature for a given location.", 
    openai.NewToolFunctionParameters().
        AddPropertyWithDescription("location", "string", "City and country e.g. Bogotá, Colombia").
        SetRequiredParameters([]string{"location"}))

// Configure options with tools
options := openai.ResponseOptions{}
options.SetInstructions("You are a helpful weather assistant.")
options.SetTools([]any{weatherTool})
options.SetToolChoiceAuto() // or SetToolChoiceRequired(), SetToolChoiceFunction("get_weather")

// First call - model decides to call function
response, err := client.CreateResponse("gpt-4o", "What's the weather in Paris?", options)
if err != nil {
    log.Fatal(err)
}

// Check for function calls
for _, output := range response.Output {
    if output.Type == "function_call" {
        log.Printf("Function call: %s", output.Name)
        
        // Parse arguments
        args, err := output.ArgumentsParsed()
        if err != nil {
            log.Fatal(err)
        }
        
        // Execute your function (simulate)
        result := "22°C, sunny"
        
        // Create input with function result
        input := []any{
            openai.NewResponseMessage("user", "What's the weather in Paris?"),
            output, // Include the function call
            openai.NewResponseFunctionCallOutput(output.CallID, result),
        }
        
        // Second call - get final response with function result
        finalResponse, err := client.CreateResponse("gpt-4o", input, openai.ResponseOptions{})
        if err != nil {
            log.Fatal(err)
        }
        
        log.Printf("Final response: %s", finalResponse.Output[0].Content[0].Text)
        break
    }
}
Streaming Responses
err := client.CreateResponseStream("gpt-4.1", "Tell me a story", nil, func(event openai.ResponseStreamEvent, done bool, err error) {
    if err != nil {
        log.Printf("Stream error: %v", err)
        return
    }
    
    switch event.Type {
    case "response.output_text.delta":
        if event.Delta != nil {
            fmt.Print(*event.Delta)
        }
    case "response.completed":
        fmt.Println("\nStream completed")
    }
    
    if done {
        return
    }
})

if err != nil {
    log.Fatal(err)
}
Streaming with Tools
weatherTool := openai.NewResponseTool("get_weather", "Get weather info", 
    openai.NewToolFunctionParameters().
        AddPropertyWithDescription("location", "string", "City name").
        SetRequiredParameters([]string{"location"}))

options := openai.ResponseOptions{}
options.SetTools([]any{weatherTool})
options.SetToolChoiceAuto()

err := client.CreateResponseStream("gpt-4o", "Weather in Tokyo?", options, 
    func(event openai.ResponseStreamEvent, done bool, err error) {
        if err != nil {
            log.Printf("Stream error: %v", err)
            return
        }
        
        switch event.Type {
        case "response.output_item.added":
            if event.Item != nil && event.Item.Type == "function_call" {
                log.Printf("Function call started: %s", event.Item.Name)
            }
        case "response.function_call_arguments.delta":
            if event.Delta != nil {
                fmt.Print(*event.Delta) // Print argument deltas
            }
        case "response.function_call_arguments.done":
            if event.Arguments != nil {
                log.Printf("\nFunction arguments complete: %s", *event.Arguments)
            }
        case "response.completed":
            log.Println("Stream completed")
        }
        
        if done {
            return
        }
    })

if err != nil {
    log.Fatal(err)
}
Beta
Note

Beta API functions require beta header like this:

client.SetBetaHeader(`assistants=v1`)
Help Wanted
  • Stream(server-sent events) options are not implemented yet. thanks to @tectiv3 :-)
  • Add some sample applications.

Documentation

Index

Constants

View Source
const (
	// timeout seconds
	DialTimeout           = 5 * 60 * time.Second
	KeepAlive             = 60 * time.Second
	IdleConnTimeout       = 60 * time.Second
	TLSHandshakeTimeout   = 10 * time.Second
	ResponseHeaderTimeout = DialTimeout
	ExpectContinueTimeout = 1 * time.Second
)
View Source
const (
	ResponseToolChoiceAuto     = "auto"
	ResponseToolChoiceRequired = "required"
	ResponseToolChoiceNone     = "none"
)

Tool choice constants

Variables

View Source
var (
	StreamData = []byte("data: ")
	StreamDone = []byte("[DONE]")
)

Functions

func NewResponseTextInput added in v0.4.8

func NewResponseTextInput(text string) string

NewResponseTextInput creates input from a text string

Types

type Annotation added in v0.4.8

type Annotation struct {
	Type       string `json:"type"`
	StartIndex int    `json:"start_index,omitempty"`
	EndIndex   int    `json:"end_index,omitempty"`
	URL        string `json:"url,omitempty"`
	Title      string `json:"title,omitempty"`
}

Annotation represents an annotation in the content

type Assistant

type Assistant struct {
	CommonResponse

	ID           string            `json:"id"`
	CreatedAt    int               `json:"created_at"`
	Name         *string           `json:"name,omitempty"`
	Description  *string           `json:"description,omitempty"`
	Model        string            `json:"model"`
	Instructions *string           `json:"instructions,omitempty"`
	Tools        []Tool            `json:"tools"`
	FileIDs      []string          `json:"file_ids"`
	Metadata     map[string]string `json:"metadata"`
}

Assistant struct for assistant object

https://platform.openai.com/docs/api-reference/assistants/object

type AssistantDeletionStatus

type AssistantDeletionStatus struct {
	CommonResponse

	ID      string `json:"id"`
	Deleted bool   `json:"deleted"`
}

AssistantDeletionStatus struct for API response

type AssistantFile

type AssistantFile struct {
	CommonResponse

	ID          string `json:"id"`
	CreatedAt   int    `json:"created_at"`
	AssistantID string `json:"assistant_id"`
}

AssistantFile struct for attached files of assistants

https://platform.openai.com/docs/api-reference/assistants/file-object

type AssistantFileDeletionStatus

type AssistantFileDeletionStatus struct {
	CommonResponse

	ID      string `json:"id"`
	Deleted bool   `json:"deleted"`
}

AssistantFileDeletionStatus struct for API response

type AssistantFiles

type AssistantFiles struct {
	CommonResponse

	Data    []AssistantFile `json:"data"`
	FirstID string          `json:"first_id"`
	LastID  string          `json:"last_id"`
	HasMore bool            `json:"has_more"`
}

AssistantFiless struct for API response

type Assistants

type Assistants struct {
	CommonResponse

	Data    []Assistant `json:"data"`
	FirstID string      `json:"first_id"`
	LastID  string      `json:"last_id"`
	HasMore bool        `json:"has_more"`
}

Assistants struct for API response

type ChatCompletion

type ChatCompletion struct {
	CommonResponse

	ID      string                 `json:"id"`
	Created int64                  `json:"created"`
	Choices []ChatCompletionChoice `json:"choices"`
	Usage   Usage                  `json:"usage"`
}

ChatCompletion struct for chat completion response

type ChatCompletionChoice

type ChatCompletionChoice struct {
	Index        int         `json:"index"`
	Message      ChatMessage `json:"message"`
	FinishReason string      `json:"finish_reason"`
	Delta        ChatMessage `json:"delta"` // Only appears in stream response
}

ChatCompletionChoice struct for chat completion response

type ChatCompletionOptions

type ChatCompletionOptions map[string]any

ChatCompletionOptions for creating chat completions

func (ChatCompletionOptions) SetFrequencyPenalty

func (o ChatCompletionOptions) SetFrequencyPenalty(frequencyPenalty float64) ChatCompletionOptions

SetFrequencyPenalty sets the `frequency_penalty` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-frequency_penalty

func (ChatCompletionOptions) SetLogitBias

func (o ChatCompletionOptions) SetLogitBias(logitBias map[string]any) ChatCompletionOptions

SetLogitBias sets the `logit_bias` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias

func (ChatCompletionOptions) SetMaxTokens

func (o ChatCompletionOptions) SetMaxTokens(maxTokens int) ChatCompletionOptions

SetMaxTokens sets the `max_tokens` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-max_tokens

func (ChatCompletionOptions) SetN

SetN sets the `n` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-n

func (ChatCompletionOptions) SetPresencePenalty

func (o ChatCompletionOptions) SetPresencePenalty(presencePenalty float64) ChatCompletionOptions

SetPresencePenalty sets the `presence_penalty` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-presence_penalty

func (ChatCompletionOptions) SetResponseFormat

SetResponseFormat sets the `response_format` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format

func (ChatCompletionOptions) SetSeed

SetSeed sets the `seed` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat-create-seed

func (ChatCompletionOptions) SetStop

SetStop sets the `stop` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-stop

func (ChatCompletionOptions) SetTemperature

func (o ChatCompletionOptions) SetTemperature(temperature float64) ChatCompletionOptions

SetTemperature sets the `temperature` parameter of chat completion request.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-temperature

func (ChatCompletionOptions) SetToolChoice

SetToolChoice sets the `tool_choice` parameter of chat completion request.

https://platform.openai.com/docs/api-reference/chat/create#chat-create-tool_choice

func (ChatCompletionOptions) SetToolChoiceWithName

func (o ChatCompletionOptions) SetToolChoiceWithName(name string) ChatCompletionOptions

SetToolChoiceWithName sets the `tool_choice` parameter of chat completion request with given function name.

https://platform.openai.com/docs/api-reference/chat/create#chat-create-tool_choice

func (ChatCompletionOptions) SetTools

SetTools sets the `tools` parameter of chat completion request.

https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools

func (ChatCompletionOptions) SetTopP

SetTopP sets the `top_p` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-top_p

func (ChatCompletionOptions) SetUser

SetUser sets the `user` parameter of chat completions.

https://platform.openai.com/docs/api-reference/chat/create#chat/create-user

type ChatCompletionResponseFormat

type ChatCompletionResponseFormat struct {
	Type ChatCompletionResponseFormatType `json:"type,omitempty"`
}

ChatCompletionResponseFormat struct for chat completion request

type ChatCompletionResponseFormatType

type ChatCompletionResponseFormatType string

ChatCompletionResponseFormatType type for constants

const (
	ChatCompletionResponseFormatTypeText       ChatCompletionResponseFormatType = "text"
	ChatCompletionResponseFormatTypeJSONObject ChatCompletionResponseFormatType = "json_object"
)

ChatCompletionResponseFormatType constants

type ChatCompletionTool

type ChatCompletionTool struct {
	Type     string                     `json:"type"` // == 'function'
	Function ChatCompletionToolFunction `json:"function"`
}

ChatCompletionTool struct for chat completion function

https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools

func NewChatCompletionTool

func NewChatCompletionTool(name, description string, parameters ToolFunctionParameters) ChatCompletionTool

NewChatCompletionTool returns a ChatCompletionTool.

type ChatCompletionToolChoiceMode

type ChatCompletionToolChoiceMode string

ChatCompletionToolChoiceMode type

https://platform.openai.com/docs/api-reference/chat/create#chat-create-tool_choice

const (
	ChatCompletionToolChoiceNone ChatCompletionToolChoiceMode = "none"
	ChatCompletionToolChoiceAuto ChatCompletionToolChoiceMode = "auto"
)

ChatCompletionToolChoiceMode constants

type ChatCompletionToolFunction

type ChatCompletionToolFunction struct {
	Name        string                 `json:"name"`
	Description *string                `json:"description,omitempty"`
	Parameters  ToolFunctionParameters `json:"parameters"`
}

ChatCompletionToolFunction struct

type ChatMessage

type ChatMessage struct {
	Role    ChatMessageRole `json:"role"`
	Content any             `json:"content,omitempty"` // NOTE: string | []ChatMessageContent

	// for function call
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`   // when role == 'assistant'
	ToolCallID *string    `json:"tool_call_id,omitempty"` // when role == 'tool'
}

ChatMessage struct for chat completion

https://platform.openai.com/docs/guides/chat/introduction

func NewChatAssistantMessage

func NewChatAssistantMessage(message string) ChatMessage

NewChatAssistantMessage returns a new ChatMessage with assistant role.

func NewChatSystemMessage

func NewChatSystemMessage(message string) ChatMessage

NewChatSystemMessage returns a new ChatMessage with system role.

func NewChatToolMessage

func NewChatToolMessage(toolCallID, content string) ChatMessage

NewChatToolMessage returns a new ChatMesssage with tool role.

func NewChatUserMessage

func NewChatUserMessage[T ChatUserMessageContentTypes](contents T) ChatMessage

NewChatUserMessage returns a new ChatMessage with user role.

func (ChatMessage) ContentArray

func (m ChatMessage) ContentArray() ([]ChatMessageContent, error)

ContentArray tries to return the `content` value as a content array.

func (ChatMessage) ContentString

func (m ChatMessage) ContentString() (string, error)

ContentString tries to return the `content` value as a string.

type ChatMessageContent

type ChatMessageContent struct {
	Type string `json:"type"`

	Text     *string `json:"text,omitempty"`
	ImageURL any     `json:"image_url,omitempty"`
}

ChatMessageContent struct

func NewChatMessageContentWithBytes

func NewChatMessageContentWithBytes(bytes []byte) ChatMessageContent

NewChatMessageContentWithBytes returns a ChatMessageContent struct with given `bytes`.

func NewChatMessageContentWithFileParam

func NewChatMessageContentWithFileParam(file FileParam) ChatMessageContent

NewChatMessageContentWithFileParam returns a ChatMessageContent struct with given `file`.

func NewChatMessageContentWithImageURL

func NewChatMessageContentWithImageURL(url string) ChatMessageContent

NewChatMessageContentWithImageURL returns a ChatMessageContent struct with given `url`.

func NewChatMessageContentWithText

func NewChatMessageContentWithText(text string) ChatMessageContent

NewChatMessageContentWithText returns a ChatMessageContent struct with given `text`.

type ChatMessageRole

type ChatMessageRole string

ChatMessageRole type for constants

const (
	ChatMessageRoleSystem    ChatMessageRole = "system"
	ChatMessageRoleUser      ChatMessageRole = "user"
	ChatMessageRoleAssistant ChatMessageRole = "assistant"
	ChatMessageRoleTool      ChatMessageRole = "tool"
)

type ChatUserMessageContentTypes

type ChatUserMessageContentTypes interface {
	string | []ChatMessageContent
}

ChatUserMessageContentTypes interface for type constraints in `NewChatUserMessage`

type Classification

type Classification struct {
	Categories     map[string]bool    `json:"categories"`
	CategoryScores map[string]float64 `json:"category_scores"`
	Flagged        bool               `json:"flagged"`
}

Classification struct for Moderation strcut

type Client

type Client struct {
	APIKey         string `json:"api_key"`
	OrganizationID string `json:"organization_id"`

	Verbose bool
	// contains filtered or unexported fields
}

Client struct which holds its API key, Organization ID, and HTTP client.

func NewClient

func NewClient(apiKey, organizationID string) *Client

NewClient returns a new API client

func (*Client) CancelFineTuningJob

func (c *Client) CancelFineTuningJob(fineTuningJobID string) (response FineTuningJob, err error)

CancelFineTuningJob cancels a fine-tuning job.

https://platform.openai.com/docs/api-reference/fine-tuning/cancel

func (*Client) CancelRun

func (c *Client) CancelRun(threadID, runID string) (response Run, err error)

CancelRun cancels a run with given `threadID` and `runID`.

This can be called when

run.Status == RunStatusInProgress.

https://platform.openai.com/docs/api-reference/runs/cancelRun

func (*Client) CreateAssistant

func (c *Client) CreateAssistant(model string, options CreateAssistantOptions) (response Assistant, err error)

CreateAssistant creates an assitant with given `model` and `options`.

https://platform.openai.com/docs/api-reference/assistants/createAssistant

func (*Client) CreateAssistantFile

func (c *Client) CreateAssistantFile(assistantID, fileID string) (response AssistantFile, err error)

CreateAssistantFile creates an assistant file by attaching given `fileID` to an assistant with `assistantID`.

https://platform.openai.com/docs/api-reference/assistants/createAssistantFile

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(model string, messages []ChatMessage, options ChatCompletionOptions) (response ChatCompletion, err error)

CreateChatCompletion creates a completion for chat messages.

https://platform.openai.com/docs/api-reference/chat/create

func (*Client) CreateChatCompletionStreamWithContext added in v0.4.8

func (c *Client) CreateChatCompletionStreamWithContext(ctx context.Context, model string, messages []ChatMessage, options ChatCompletionOptions, cb callback) (err error)

CreateChatCompletionStreamWithContext creates a completion for the chat message with context and streaming support.

https://platform.openai.com/docs/api-reference/chat/create

func (*Client) CreateChatCompletionWithContext added in v0.4.8

func (c *Client) CreateChatCompletionWithContext(ctx context.Context, model string, messages []ChatMessage, options ChatCompletionOptions) (response ChatCompletion, err error)

CreateChatCompletionWithContext creates a completion for the chat message with context support.

https://platform.openai.com/docs/api-reference/chat/create

func (*Client) CreateCompletion

func (c *Client) CreateCompletion(model string, options CompletionOptions) (response Completion, err error)

CreateCompletion creates a completion.

https://platform.openai.com/docs/api-reference/completions/create

func (*Client) CreateEmbedding

func (c *Client) CreateEmbedding(model string, input any, options EmbeddingOptions) (response Embeddings, err error)

CreateEmbedding creates an embedding with given input.

https://platform.openai.com/docs/api-reference/embeddings/create

func (*Client) CreateFineTuningJob

func (c *Client) CreateFineTuningJob(trainingFileID, model string, options FineTuningJobOptions) (response FineTuningJob, err error)

CreateFineTuningJob creates a job that fine-tunes a specified model from given data

https://platform.openai.com/docs/api-reference/fine-tuning/create

func (*Client) CreateImage

func (c *Client) CreateImage(prompt string, options ImageOptions) (response GeneratedImages, err error)

CreateImage creates an image with given prompt.

https://platform.openai.com/docs/api-reference/images/create

func (*Client) CreateImageEdit

func (c *Client) CreateImageEdit(image FileParam, prompt string, options ImageEditOptions) (response GeneratedImages, err error)

CreateImageEdit creates an edited or extended image with given file and prompt.

https://platform.openai.com/docs/api-reference/images/create-edit

func (*Client) CreateImageVariation

func (c *Client) CreateImageVariation(image FileParam, options ImageVariationOptions) (response GeneratedImages, err error)

CreateImageVariation creates a variation of a given image.

https://platform.openai.com/docs/api-reference/images/create-variation

func (*Client) CreateMessage

func (c *Client) CreateMessage(threadID, role, content string, options CreateMessageOptions) (response Message, err error)

CreateMessage creates a message with given `threadID`, `role`, `content`, and `options`.

https://platform.openai.com/docs/api-reference/messages/createMessage

func (*Client) CreateModeration

func (c *Client) CreateModeration(input any, options ModerationOptions) (response Moderation, err error)

CreateModeration classifies given text.

https://platform.openai.com/docs/api-reference/moderations/create

func (*Client) CreateResponse added in v0.4.8

func (c *Client) CreateResponse(model string, input any, options ResponseOptions) (response Response, err error)

CreateResponse creates a response using the OpenAI Responses API

func (*Client) CreateResponseStream added in v0.4.8

func (c *Client) CreateResponseStream(model string, input any, options ResponseOptions, cb responseCallback) (err error)

CreateResponseStream creates a streaming response

func (*Client) CreateResponseStreamWithContext added in v0.4.8

func (c *Client) CreateResponseStreamWithContext(ctx context.Context, model string, input any, options ResponseOptions, cb responseCallback) (err error)

CreateResponseStreamWithContext creates a streaming response with context support

func (*Client) CreateResponseWithContext added in v0.4.8

func (c *Client) CreateResponseWithContext(ctx context.Context, model string, input any, options ResponseOptions) (response Response, err error)

CreateResponseWithContext creates a response with context support

func (*Client) CreateRun

func (c *Client) CreateRun(threadID, assistantID string, options CreateRunOptions) (response Run, err error)

CreateRun creates a run with given `threadID`, `assistantID`, and `options`.

https://platform.openai.com/docs/api-reference/runs/createRun

func (*Client) CreateSpeech

func (c *Client) CreateSpeech(model string, input string, voice SpeechVoice, options SpeechOptions) (audio []byte, err error)

CreateSpeech generates audio from the input text.

https://platform.openai.com/docs/api-reference/audio/createSpeech

func (*Client) CreateThread

func (c *Client) CreateThread(options CreateThreadOptions) (response Thread, err error)

CreateThread creates a thread with given `options`.

https://platform.openai.com/docs/api-reference/threads/createThread

func (*Client) CreateThreadAndRun

func (c *Client) CreateThreadAndRun(assistantID string, options CreateThreadAndRunOptions) (response Run, err error)

CreateThreadAndRun creates a thread and runs it with given `assistantID` and `options`.

https://platform.openai.com/docs/api-reference/runs/createThreadAndRun

func (*Client) CreateTranscription

func (c *Client) CreateTranscription(file FileParam, model string, options TranscriptionOptions) (response Transcription, err error)

CreateTranscription transcribes given audio file into the input language.

https://platform.openai.com/docs/api-reference/audio/create

func (*Client) CreateTranslation

func (c *Client) CreateTranslation(file FileParam, model string, options TranslationOptions) (response Translation, err error)

CreateTranslation translates given audio file into English.

https://platform.openai.com/docs/api-reference/audio/create

func (*Client) DeleteAssistant

func (c *Client) DeleteAssistant(assistantID string) (response AssistantDeletionStatus, err error)

DeleteAssistant deletes an assistant with given `assistantID`.

https://platform.openai.com/docs/api-reference/assistants/deleteAssistant

func (*Client) DeleteAssistantFile

func (c *Client) DeleteAssistantFile(assistantID, fileID string) (response AssistantFileDeletionStatus, err error)

DeleteAssistantFile deletes an assistant file by given `assistantID` and `fileID`.

https://platform.openai.com/docs/api-reference/assistants/deleteAssistantFile

func (*Client) DeleteFile

func (c *Client) DeleteFile(fileID string) (response DeletedFile, err error)

DeleteFile deletes given file.

https://platform.openai.com/docs/api-reference/files/delete

func (*Client) DeleteFineTuneModel

func (c *Client) DeleteFineTuneModel(model string) (response ModelDeletionStatus, err error)

DeleteFineTuneModel deletes a fine-tuned model.

https://platform.openai.com/docs/api-reference/models/delete

func (*Client) DeleteThread

func (c *Client) DeleteThread(threadID string) (response ThreadDeletionStatus, err error)

DeleteThread deletes a thread with given `threadID`.

https://platform.openai.com/docs/api-reference/threads/deleteThread

func (*Client) ListAssistantFiles

func (c *Client) ListAssistantFiles(assistantID string, options ListAssistantFilesOptions) (response AssistantFiles, err error)

ListAssistantFiles lists all assistant files with given `assistantID` and `options`.

https://platform.openai.com/docs/api-reference/assistants/listAssistantFiles

func (*Client) ListAssistants

func (c *Client) ListAssistants(options ListAssistantsOptions) (response Assistants, err error)

ListAssistants lists all assistants with given `options`.

https://platform.openai.com/docs/api-reference/assistants/getAssistants

func (*Client) ListFiles

func (c *Client) ListFiles() (response Files, err error)

ListFiles returns a list of files that belong to the requested organization id.

https://platform.openai.com/docs/api-reference/files/list

func (*Client) ListFineTuningJobEvents

func (c *Client) ListFineTuningJobEvents(fineTuningJobID string, options FineTuningJobEventsOptions) (response FineTuningJobEvents, err error)

ListFineTuningJobEvents lists status updates for a given fine-tuning job.

https://platform.openai.com/docs/api-reference/fine-tuning/list-events

func (*Client) ListFineTuningJobs

func (c *Client) ListFineTuningJobs(options FineTuningJobsOptions) (response FineTuningJobs, err error)

ListFineTuningJobs lists your organization's fine-tuning jobs.

https://platform.openai.com/docs/api-reference/fine-tuning/list

func (*Client) ListMessageFiles

func (c *Client) ListMessageFiles(threadID, messageID string, options ListMessageFilesOptions) (response MessageFiles, err error)

ListMessageFiles fetches message files with given `threadID`, `mesageID`, and `options`.

https://platform.openai.com/docs/api-reference/messages/listMessageFiles

func (*Client) ListMessages

func (c *Client) ListMessages(threadID string, options ListMessagesOptions) (response Messages, err error)

ListMessages fetches messages with given `threadID`, and `options`.

https://platform.openai.com/docs/api-reference/messages/listMessages

func (*Client) ListModels

func (c *Client) ListModels() (response ModelsList, err error)

ListModels lists currently available models.

https://platform.openai.com/docs/api-reference/models/list

func (*Client) ListRunSteps

func (c *Client) ListRunSteps(threadID, runID string, options ListRunStepsOptions) (response RunSteps, err error)

ListRunSteps fetches run steps with given `threadID`, `runID` and `options`.

https://platform.openai.com/docs/api-reference/runs/listRunSteps

func (*Client) ListRuns

func (c *Client) ListRuns(threadID string, options ListRunsOptions) (response Runs, err error)

ListRuns fetches runs with given `threadID` and `options`.

https://platform.openai.com/docs/api-reference/runs/listRuns

func (*Client) ModifyAssistant

func (c *Client) ModifyAssistant(assistantID string, options ModifyAssistantOptions) (response Assistant, err error)

ModifyAssistant modifies an assistant with given `assistantID` and `options`.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant

func (*Client) ModifyMessage

func (c *Client) ModifyMessage(threadID, messageID string, options ModifyMessageOptions) (response Message, err error)

ModifyMessage modifies a message with given `threadID`, `messageID`, and `options`.

https://platform.openai.com/docs/api-reference/messages/modifyMessage

func (*Client) ModifyRun

func (c *Client) ModifyRun(threadID, runID string, options ModifyRunOptions) (response Run, err error)

ModifyRun modifies a run with given `threadID`, `runID`, and `options`.

https://platform.openai.com/docs/api-reference/runs/modifyRun

func (*Client) ModifyThread

func (c *Client) ModifyThread(threadID string, options ModifyThreadOptions) (response Thread, err error)

ModifyThread modifies a thread with given `threadID` and `options`.

https://platform.openai.com/docs/api-reference/threads/modifyThread

func (*Client) RetrieveAssistant

func (c *Client) RetrieveAssistant(assistantID string) (response Assistant, err error)

RetrieveAssistant retrieves an assistant with given `assistantID`.

https://platform.openai.com/docs/api-reference/assistants/getAssistant

func (*Client) RetrieveAssistantFile

func (c *Client) RetrieveAssistantFile(assistantID, fileID string) (response AssistantFile, err error)

RetrieveAssistantFile retrieves an assistant file by given `assistantID` and `fileID`.

https://platform.openai.com/docs/api-reference/assistants/getAssistantFile

func (*Client) RetrieveFile

func (c *Client) RetrieveFile(fileID string) (response RetrievedFile, err error)

RetrieveFile returns the information of given file.

https://platform.openai.com/docs/api-reference/files/retrieve

func (*Client) RetrieveFileContent

func (c *Client) RetrieveFileContent(fileID string) (response []byte, err error)

RetrieveFileContent returns the content of given file.

https://platform.openai.com/docs/api-reference/files/retrieve-content

func (*Client) RetrieveFineTuningJob

func (c *Client) RetrieveFineTuningJob(fineTuningJobID string) (response FineTuningJob, err error)

RetrieveFineTuningJob retrieves a fine-tuning job.

https://platform.openai.com/docs/api-reference/fine-tuning/retrieve

func (*Client) RetrieveMessage

func (c *Client) RetrieveMessage(threadID, messageID string) (response Message, err error)

RetrieveMessage retrieves a message with given `threadID` and `messageID`.

https://platform.openai.com/docs/api-reference/messages/getMessage

func (*Client) RetrieveMessageFile

func (c *Client) RetrieveMessageFile(threadID, messageID, fileID string) (response MessageFile, err error)

RetrieveMessageFile retrieves a message file with given `threadID`, `messageID`, and `fileID`.

https://platform.openai.com/docs/api-reference/messages/getMessageFile

func (*Client) RetrieveModel

func (c *Client) RetrieveModel(id string) (response Model, err error)

RetrieveModel retrieves a model instance.

https://platform.openai.com/docs/api-reference/models/retrieve

func (*Client) RetrieveRun

func (c *Client) RetrieveRun(threadID, runID string) (response Run, err error)

RetrieveRun retrieves a run with given `threadID` and `runID`.

https://platform.openai.com/docs/api-reference/runs/getRun

func (*Client) RetrieveRunStep

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

RetrieveRunStep retrieves a run step with given `threadID`, `runID` and `stepID`.

https://platform.openai.com/docs/api-reference/runs/getRunStep

func (*Client) RetrieveThread

func (c *Client) RetrieveThread(threadID string) (response Thread, err error)

RetrieveThread retrieves the thread with given `threadID`.

https://platform.openai.com/docs/api-reference/threads/getThread

func (*Client) SetBaseURL added in v0.4.7

func (c *Client) SetBaseURL(baseURL string) *Client

func (*Client) SetBetaHeader

func (c *Client) SetBetaHeader(beta string) *Client

SetBetaHeader sets the beta HTTP header for beta features.

func (*Client) SubmitToolOutputs

func (c *Client) SubmitToolOutputs(threadID, runID string, toolOutputs []ToolOutput) (response Run, err error)

SubmitToolOutputs submits tool outputs with given `threadID` and `runID`.

This can be called when

run.Status == RunStatusRequiresAction && run.RequiredAction.Type == "submit_tool_outputs".

https://platform.openai.com/docs/api-reference/runs/submitToolOutputs

func (*Client) UploadFile

func (c *Client) UploadFile(file FileParam, purpose string) (response UploadedFile, err error)

UploadFile uploads given file.

https://platform.openai.com/docs/api-reference/files/create

type CommonResponse

type CommonResponse struct {
	Object *string `json:"object,omitempty"`
	Error  *Error  `json:"error,omitempty"`
	Type   *string `json:"type,omitempty"`
}

CommonResponse struct for responses with common properties

type Completion

type Completion struct {
	CommonResponse

	ID      string             `json:"id"`
	Created int64              `json:"created"`
	Model   string             `json:"model"`
	Choices []CompletionChoice `json:"choices"`
	Usage   Usage              `json:"usage"`
}

Completion struct for response

type CompletionChoice

type CompletionChoice struct {
	Text         string `json:"text"`
	Index        int    `json:"index"`
	Logprobs     *int   `json:"logprobs,omitempty"`
	FinishReason string `json:"finish_reason"`
}

CompletionChoice struct for completion response

type CompletionOptions

type CompletionOptions map[string]any

CompletionOptions for creating completions

func (CompletionOptions) SetBestOf

func (o CompletionOptions) SetBestOf(bestOf int) CompletionOptions

SetBestOf sets the `best_of` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-best_of

func (CompletionOptions) SetEcho

func (o CompletionOptions) SetEcho(echo bool) CompletionOptions

SetEcho sets the `echo` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-echo

func (CompletionOptions) SetFrequencyPenalty

func (o CompletionOptions) SetFrequencyPenalty(frequencyPenalty float64) CompletionOptions

SetFrequencyPenalty sets the `frequency_penalty` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-frequency_penalty

func (CompletionOptions) SetLogProbabilities

func (o CompletionOptions) SetLogProbabilities(logprobs int) CompletionOptions

SetLogProbabilities sets the `logprobs` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-logprobs

func (CompletionOptions) SetLogitBias

func (o CompletionOptions) SetLogitBias(logitBias map[string]any) CompletionOptions

SetLogitBias sets the `logit_bias` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-logit_bias

func (CompletionOptions) SetMaxTokens

func (o CompletionOptions) SetMaxTokens(maxTokens int) CompletionOptions

SetMaxTokens sets the `max_tokens` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-max_tokens

func (CompletionOptions) SetN

SetN sets the `n` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-n

func (CompletionOptions) SetPresencePenalty

func (o CompletionOptions) SetPresencePenalty(presencePenalty float64) CompletionOptions

SetPresencePenalty sets the `presence_penalty` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-presence_penalty

func (CompletionOptions) SetPrompt

func (o CompletionOptions) SetPrompt(prompt any) CompletionOptions

SetPrompt sets the `prompt` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-prompt

func (CompletionOptions) SetStop

func (o CompletionOptions) SetStop(stop any) CompletionOptions

SetStop sets the `stop` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-stop

func (CompletionOptions) SetSuffix

func (o CompletionOptions) SetSuffix(suffix string) CompletionOptions

SetSuffix sets the `suffix` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-suffix

func (CompletionOptions) SetTemperature

func (o CompletionOptions) SetTemperature(temperature float64) CompletionOptions

SetTemperature sets the `temperature` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-temperature

func (CompletionOptions) SetTopP

SetTopP sets the `top_p` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-top_p

func (CompletionOptions) SetUser

func (o CompletionOptions) SetUser(user string) CompletionOptions

SetUser sets the `user` parameter of completion request.

https://platform.openai.com/docs/api-reference/completions/create#completions/create-user

type CreateAssistantOptions

type CreateAssistantOptions map[string]any

CreateAssistantOptions for creating assistant

func (CreateAssistantOptions) SetDescription

func (o CreateAssistantOptions) SetDescription(description string) CreateAssistantOptions

SetDescription sets the `description` parameter of assistant creation.

https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-description

func (CreateAssistantOptions) SetFileIDs

func (o CreateAssistantOptions) SetFileIDs(fileIDs []string) CreateAssistantOptions

SetFileIDs sets the `file_ids` parameter of assistant creation.

https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-file_ids

func (CreateAssistantOptions) SetInstructions

func (o CreateAssistantOptions) SetInstructions(instructions string) CreateAssistantOptions

SetInstructions sets the `instructions` parameter of assistant creation.

https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-instructions

func (CreateAssistantOptions) SetMetadata

func (o CreateAssistantOptions) SetMetadata(metadata map[string]string) CreateAssistantOptions

SetMetadata sets the `metadata` parameter of assistant creation.

https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-metadata

func (CreateAssistantOptions) SetName

SetName sets the `name` parameter of assistant creation.

https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-name

func (CreateAssistantOptions) SetTools

SetTools sets the `tools` parameter of assistant creation.

https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-tools

type CreateMessageOptions

type CreateMessageOptions map[string]any

CreateMessageOptions for creating message

func (CreateMessageOptions) SetFileIDs

func (o CreateMessageOptions) SetFileIDs(fileIDs []string) CreateMessageOptions

SetFileIDs sets the `file_ids` parameter of CreateMessageOptions.

https://platform.openai.com/docs/api-reference/messages/createMessage#messages-createmessage-file_ids

func (CreateMessageOptions) SetMetadata

func (o CreateMessageOptions) SetMetadata(metadata map[string]string) CreateMessageOptions

SetMetadata sets the `metadata` parameter of CreateMessageOptions.

https://platform.openai.com/docs/api-reference/messages/createMessage#messages-createmessage-metadata

type CreateRunOptions

type CreateRunOptions map[string]any

CreateRunOptions for creating run

func (CreateRunOptions) SetInstructions

func (o CreateRunOptions) SetInstructions(instructions string) CreateRunOptions

SetInstructions sets the `instructions` parameter of CreateRunOptions.

https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-instructions

func (CreateRunOptions) SetMetadata

func (o CreateRunOptions) SetMetadata(metadata map[string]string) CreateRunOptions

SetMetadata sets the `metadata` parameter of CreateRunOptions.

https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-metadata

func (CreateRunOptions) SetModel

func (o CreateRunOptions) SetModel(model string) CreateRunOptions

SetModel sets the `model` parameter of CreateRunOptions.

https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-model

func (CreateRunOptions) SetTools

func (o CreateRunOptions) SetTools(tools []Tool) CreateRunOptions

SetTools sets the `tools` parameter of CreateRunOptions.

https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-tools

type CreateThreadAndRunOptions

type CreateThreadAndRunOptions map[string]any

CreateThreadAndRunOptions for creating thread and running it

func (CreateThreadAndRunOptions) SetInstructions

func (o CreateThreadAndRunOptions) SetInstructions(instructions string) CreateThreadAndRunOptions

SetInstructions sets the `instructions` parameter of CreateThreadAndRunOptions.

https://platform.openai.com/docs/api-reference/runs/createThreadAndRun#runs-createthreadandrun-instructions

func (CreateThreadAndRunOptions) SetMetadata

SetMetadata sets the `metadata` parameter of CreateThreadAndRunOptions.

https://platform.openai.com/docs/api-reference/runs/createThreadAndRun#runs-createthreadandrun-metadata

func (CreateThreadAndRunOptions) SetModel

SetModel sets the `model` parameter of CreateThreadAndRunOptions.

https://platform.openai.com/docs/api-reference/runs/createThreadAndRun#runs-createthreadandrun-model

func (CreateThreadAndRunOptions) SetThread

SetThread sets the `thread` parameter of CreateThreadAndRunOptions.

https://platform.openai.com/docs/api-reference/runs/createThreadAndRun#runs-createthreadandrun-thread

func (CreateThreadAndRunOptions) SetTools

SetTools sets the `tools` parameter of CreateThreadAndRunOptions.

https://platform.openai.com/docs/api-reference/runs/createThreadAndRun#runs-createthreadandrun-tools

type CreateThreadOptions

type CreateThreadOptions map[string]any

CreateThreadOptions for creating thread

func (CreateThreadOptions) SetMessages

func (o CreateThreadOptions) SetMessages(messages []ThreadMessage) CreateThreadOptions

SetMessages sets the `messages` parameter of CreateThreadOptions.

https://platform.openai.com/docs/api-reference/threads/createThread#threads-createthread-messages

func (CreateThreadOptions) SetMetadata

func (o CreateThreadOptions) SetMetadata(metadata map[string]string) CreateThreadOptions

SetMetadata sets the `metadata` parameter of CreateThreadOptions.

https://platform.openai.com/docs/api-reference/threads/createThread#threads-createthread-metadata

type DeletedFile

type DeletedFile struct {
	CommonResponse

	ID      string `json:"id"`
	Deleted bool   `json:"deleted"`
}

DeletedFile struct for response

type Embedding

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

Embedding struct for Embeddings struct

type EmbeddingEncodingFormat

type EmbeddingEncodingFormat string

EmbeddingEncodingFormat type for constants

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

type EmbeddingOptions

type EmbeddingOptions map[string]any

EmbeddingOptions for creating embedding

func (EmbeddingOptions) SetEncodingFormat

func (o EmbeddingOptions) SetEncodingFormat(format EmbeddingEncodingFormat) EmbeddingOptions

SetEncodingFormat sets the `encoding_format` parameter of create embedding request.

https://platform.openai.com/docs/api-reference/embeddings/create#embeddings-create-encoding_format

func (EmbeddingOptions) SetUser

func (o EmbeddingOptions) SetUser(user string) EmbeddingOptions

SetUser sets the `user` parameter of create embedding request.

https://platform.openai.com/docs/api-reference/embeddings/create#embeddings/create-user

type Embeddings

type Embeddings struct {
	CommonResponse

	Data  []Embedding `json:"data"`
	Model string      `json:"model"`
	Usage struct {
		PromptTokens int `json:"prompt_tokens"`
		TotalTokens  int `json:"total_tokens"`
	} `json:"usage"`
}

Embeddings struct for response

type Error

type Error struct {
	Message string  `json:"message"`
	Type    string  `json:"type"`
	Param   any     `json:"param,omitempty"`
	Code    *string `json:"code,omitempty"`
}

Error struct for response error property

type File

type File struct {
	CommonResponse

	ID        string `json:"id"`
	Bytes     int    `json:"bytes"`
	CreatedAt int64  `json:"created_at"`
	Filename  string `json:"filename"`
	Purpose   string `json:"purpose"`
}

File struct for file items

type FileParam

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

FileParam struct for multipart requests

func NewFileParamFromBytes

func NewFileParamFromBytes(bs []byte) FileParam

NewFileParamFromBytes returns a new FileParam with given bytes

func NewFileParamFromFilepath

func NewFileParamFromFilepath(path string) (f FileParam, err error)

NewFileParamFromFilepath returns a new FileParam with bytes read from given filepath

type Files

type Files struct {
	CommonResponse

	Data []File `json:"data"`
}

Files struct for response

type FineTuningHyperparameters

type FineTuningHyperparameters struct {
	NEpochs any `json:"n_epochs"` // string("Auto") or int
}

FineTuningHyperparameters struct

type FineTuningJob

type FineTuningJob struct {
	CommonResponse

	ID              string                    `json:"id"`
	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          FineTuningJobStatus       `json:"status"`
	Hyperparameters FineTuningHyperparameters `json:"hyperparameters"`
	TrainingFile    string                    `json:"training_file"`
	ValidationFile  *string                   `json:"validation_file,omitempty"`
	ResultFiles     []string                  `json:"result_files"`
	TrainedTokens   int                       `json:"trained_tokens"`
}

FineTuningJob struct

type FineTuningJobEvent

type FineTuningJobEvent struct {
	CommonResponse

	ID        string `json:"id"`
	CreatedAt int    `json:"created_at"`
	Level     string `json:"level"`
	Message   string `json:"message"`
	Data      any    `json:"data,omitempty"`
	Type      string `json:"type"`
}

FineTuningJobEvent struct

type FineTuningJobEvents

type FineTuningJobEvents struct {
	CommonResponse

	Data []FineTuningJobEvent `json:"data"`

	HasMore bool `json:"has_more"`
}

FineTuningJobEvents struct

type FineTuningJobEventsOptions

type FineTuningJobEventsOptions map[string]any

FineTuningJobEventsOptions for listing fine-tuning job events

func (FineTuningJobEventsOptions) SetAfter

func (o FineTuningJobEventsOptions) SetAfter(fineTuningJobEventID string) FineTuningJobEventsOptions

SetAfter sets the `after` parameter of fine-tuning events request.

https://platform.openai.com/docs/api-reference/fine-tuning/list-events#after

func (FineTuningJobEventsOptions) SetLimit

SetLimit sets the `limit` parameter of fine-tuning events request.

https://platform.openai.com/docs/api-reference/fine-tuning/list-events#limit

type FineTuningJobOptions

type FineTuningJobOptions map[string]any

FineTuningJobOptions for retrieving fine-tuning jobs

func (FineTuningJobOptions) SetHyperparameters

func (o FineTuningJobOptions) SetHyperparameters(hyperparameters FineTuningHyperparameters) FineTuningJobOptions

SetHyperparameters sets the `hyperparameters` parameter of fine-tuning job request.

https://platform.openai.com/docs/api-reference/fine-tuning/create#model

func (FineTuningJobOptions) SetSuffix

func (o FineTuningJobOptions) SetSuffix(suffix string) FineTuningJobOptions

SetSuffix sets the `suffix` parameter of fine-tuning job request.

https://platform.openai.com/docs/api-reference/fine-tuning/create#suffix

func (FineTuningJobOptions) SetValidationFile

func (o FineTuningJobOptions) SetValidationFile(validationFileID string) FineTuningJobOptions

SetValidationFile sets the `validation_file` parameter of fine-tuning job request.

https://platform.openai.com/docs/api-reference/fine-tuning/create#validation_file

type FineTuningJobStatus

type FineTuningJobStatus string

FineTuningJobStatus type

const (
	FineTuningJobStatusCreated   FineTuningJobStatus = "created"
	FineTuningJobStatusPending   FineTuningJobStatus = "pending"
	FineTuningJobStatusRunning   FineTuningJobStatus = "running"
	FineTuningJobStatusSucceeded FineTuningJobStatus = "succeeded"
	FineTuningJobStatusFailed    FineTuningJobStatus = "failed"
	FineTuningJobStatusCancelled FineTuningJobStatus = "cancelled"
)

FineTuningJobStatus constants

type FineTuningJobs

type FineTuningJobs struct {
	CommonResponse

	Data    []FineTuningJob `json:"data"`
	HasMore bool            `json:"has_more"`
}

FineTuningJobs struct

type FineTuningJobsOptions

type FineTuningJobsOptions map[string]any

FineTuningJobsOptions for listing fine-tuning jobs

func (FineTuningJobsOptions) SetAfter

SetAfter sets the `after` parameter of fine-tuning jobs listing request.

https://platform.openai.com/docs/api-reference/fine-tuning/list#fine-tuning-list-after

func (FineTuningJobsOptions) SetLimit

SetLimit sets the `limit` parameter of fine-tuning jobs listing request.

https://platform.openai.com/docs/api-reference/fine-tuning/list#fine-tuning-list-limit

type GeneratedImages

type GeneratedImages struct {
	CommonResponse

	Created int64 `json:"created"`
	Data    []struct {
		URL        *string `json:"url,omitempty"`
		Base64JSON *string `json:"b64_json,omitempty"`
	} `json:"data"`
}

GeneratedImages struct for image creation responses

type ImageEditOptions

type ImageEditOptions map[string]any

ImageEditOptions for creating image edits

func (ImageEditOptions) SetMask

SetMask sets the `mask` parameter of image edit request.

https://platform.openai.com/docs/api-reference/images/create-edit#images/create-edit-mask

func (ImageEditOptions) SetModel

func (o ImageEditOptions) SetModel(model string) ImageEditOptions

SetModel sets the `model` parameter of image edit request.

NOTE: only `dall-e-2` is supported at this time.

https://platform.openai.com/docs/api-reference/images/createEdit#images-createedit-model

func (ImageEditOptions) SetN

SetN sets the `n` parameter of image edit request.

https://platform.openai.com/docs/api-reference/images/create-edit#images/create-edit-n

func (ImageEditOptions) SetResponseFormat

func (o ImageEditOptions) SetResponseFormat(responseFormat ImageResponseFormat) ImageEditOptions

SetResponseFormat sets the `response_format` parameter of image edit request.

https://platform.openai.com/docs/api-reference/images/create-edit#images/create-edit-response_format

func (ImageEditOptions) SetSize

SetSize sets the `size` parameter of image edit request.

https://platform.openai.com/docs/api-reference/images/create-edit#images/create-edit-size

func (ImageEditOptions) SetUser

func (o ImageEditOptions) SetUser(user string) ImageEditOptions

SetUser sets the `user` parameter of image edit request.

https://platform.openai.com/docs/api-reference/images/create-edit#images/create-edit-user

type ImageOptions

type ImageOptions map[string]any

ImageOptions for creating images

func (ImageOptions) SetModel

func (o ImageOptions) SetModel(model string) ImageOptions

SetModel sets the `model` parameter of image generation request.

https://platform.openai.com/docs/api-reference/images/create#images-create-model

func (ImageOptions) SetN

func (o ImageOptions) SetN(n int) ImageOptions

SetN sets the `n` parameter of image generation request.

NOTE: only 1 supported for model: `dall-e-3`

https://platform.openai.com/docs/api-reference/images/create#images/create-n

func (ImageOptions) SetQuality

func (o ImageOptions) SetQuality(quality string) ImageOptions

SetQuality sets the `quality` parameter of image generation request.

NOTE: 'hd' supported only for model: `dall-e-3`

https://platform.openai.com/docs/api-reference/images/create#images-create-quality

func (ImageOptions) SetResponseFormat

func (o ImageOptions) SetResponseFormat(responseFormat ImageResponseFormat) ImageOptions

SetResponseFormat sets the `response_format` parameter of image generation request.

https://platform.openai.com/docs/api-reference/images/create#images/create-response_format

func (ImageOptions) SetSize

func (o ImageOptions) SetSize(size ImageSize) ImageOptions

SetSize sets the `size` parameter of image generation request.

https://platform.openai.com/docs/api-reference/images/create#images/create-size

func (ImageOptions) SetStyle

func (o ImageOptions) SetStyle(style ImageStyle) ImageOptions

SetStyle set the `style` parameter of image generation request.

NOTE: supported only for model: `dall-e-3`

https://platform.openai.com/docs/api-reference/images/create#images-create-style

func (ImageOptions) SetUser

func (o ImageOptions) SetUser(user string) ImageOptions

SetUser sets the `user` parameter of image generation request.

https://platform.openai.com/docs/api-reference/images/create#images/create-user

type ImageResponseFormat

type ImageResponseFormat string

ImageResponseFormat type for constants

const (
	IamgeResponseFormatURL        ImageResponseFormat = "url"
	IamgeResponseFormatBase64JSON ImageResponseFormat = "b64_json"
)

type ImageSize

type ImageSize string

ImageSize type for constants

const (
	// for Dall-E-2
	ImageSize256x256_DallE2   ImageSize = "256x256"
	ImageSize512x512_DallE2   ImageSize = "512x512"
	ImageSize1024x1024_DallE2 ImageSize = "1024x1024"

	// for Dall-E-3
	ImageSize1024x1024_DallE3 ImageSize = "1024x1024"
	ImageSize1792x1024_DallE3 ImageSize = "1792x1024"
	ImageSize1024x1792_DallE3 ImageSize = "1024x1792"
)

type ImageStyle

type ImageStyle string

ImageStyle type for constants

const (
	ImageStyleVivid   ImageStyle = "vivid"
	ImageStyleNatural ImageStyle = "natural"
)

type ImageVariationOptions

type ImageVariationOptions map[string]any

ImageVariationOptions for creating image variations

func (ImageVariationOptions) SetModel

SetModel sets the `model` parameter of image variation request.

NOTE: only `dall-e-2` is supported at this time.

https://platform.openai.com/docs/api-reference/images/createVariation#images-createvariation-model

func (ImageVariationOptions) SetN

SetN sets the `n` parameter of image variation request.

https://platform.openai.com/docs/api-reference/images/create-variation#images/create-variation-n

func (ImageVariationOptions) SetResponseFormat

func (o ImageVariationOptions) SetResponseFormat(responseFormat ImageResponseFormat) ImageVariationOptions

SetResponseFormat sets the `response_format` parameter of image variation request.

https://platform.openai.com/docs/api-reference/images/create-variation#images/create-variation-response_format

func (ImageVariationOptions) SetSize

SetSize sets the `size` parameter of image variation request.

https://platform.openai.com/docs/api-reference/images/create-variation#images/create-variation-size

func (ImageVariationOptions) SetUser

SetUser sets the `user` parameter of image variation request.

https://platform.openai.com/docs/api-reference/images/create-variation#images/create-variation-user

type ListAssistantFilesOptions

type ListAssistantFilesOptions map[string]any

ListAssistantFilesOptions for listing assistant files

func (ListAssistantFilesOptions) SetAfter

SetAfter sets the `after` parameter of assistant files' listing request.

https://platform.openai.com/docs/api-reference/assistants/listAssistantFiles#assistants-listassistantfiles-after

func (ListAssistantFilesOptions) SetBefore

SetBefore sets the `before` parameter of assistant files' listing request.

https://platform.openai.com/docs/api-reference/assistants/listAssistantFiles#assistants-listassistantfiles-before

func (ListAssistantFilesOptions) SetLimit

SetLimit sets the `limit` parameter of assistant files' listing request.

https://platform.openai.com/docs/api-reference/assistants/listAssistantFiles#assistants-listassistantfiles-limit

func (ListAssistantFilesOptions) SetOrder

SetOrder sets the `order` parameter of assistant files' listing request.

`order` can be one of 'asc' or 'desc'. (default: 'desc')

https://platform.openai.com/docs/api-reference/assistants/listAssistantFiles#assistants-listassistantfiles-order

type ListAssistantsOptions

type ListAssistantsOptions map[string]any

ListAssistantsOptions for listing assistants

func (ListAssistantsOptions) SetAfter

SetAfter sets the `after` parameter of assistants' listing request.

https://platform.openai.com/docs/api-reference/assistants/listAssistants#assistants-listassistants-after

func (ListAssistantsOptions) SetBefore

SetBefore sets the `before` parameter of assistants' listing request.

https://platform.openai.com/docs/api-reference/assistants/listAssistants#assistants-listassistants-before

func (ListAssistantsOptions) SetLimit

SetLimit sets the `limit` parameter of assistants' listing request.

https://platform.openai.com/docs/api-reference/assistants/listAssistants#assistants-listassistants-limit

func (ListAssistantsOptions) SetOrder

SetOrder sets the `order` parameter of assistants' listing request.

`order` can be one of 'asc' or 'desc'. (default: 'desc')

https://platform.openai.com/docs/api-reference/assistants/listAssistants#assistants-listassistants-order

type ListMessageFilesOptions

type ListMessageFilesOptions map[string]any

ListMessageFilesOptions for listing message files

func (ListMessageFilesOptions) SetAfter

SetAfter sets the `after` parameter of message files' listing request.

https://platform.openai.com/docs/api-reference/messages/listMessageFiles#messages-listmessagefiles-after

func (ListMessageFilesOptions) SetBefore

SetBefore sets the `before` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/messages/listMessageFiles#messages-listmessagefiles-before

func (ListMessageFilesOptions) SetLimit

SetLimit sets the `limit` parameter of message files' listing request.

https://platform.openai.com/docs/api-reference/messages/listMessageFiles#messages-listmessagefiles-limit

func (ListMessageFilesOptions) SetOrder

SetOrder sets the `order` parameter of message files' listing request.

`order` can be one of 'asc' or 'desc'. (default: 'desc')

https://platform.openai.com/docs/api-reference/messages/listMessageFiles#messages-listmessagefiles-order

type ListMessagesOptions

type ListMessagesOptions map[string]any

ListMessagesOptions for listing messages

func (ListMessagesOptions) SetAfter

SetAfter sets the `after` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/messages/listMessages#messages-listmessages-after

func (ListMessagesOptions) SetBefore

func (o ListMessagesOptions) SetBefore(before string) ListMessagesOptions

SetBefore sets the `before` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/messages/listMessages#messages-listmessages-before

func (ListMessagesOptions) SetLimit

func (o ListMessagesOptions) SetLimit(limit int) ListMessagesOptions

SetLimit sets the `limit` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/messages/listMessages#messages-listmessages-limit

func (ListMessagesOptions) SetOrder

SetOrder sets the `order` parameter of messages' listing request.

`order` can be one of 'asc' or 'desc'. (default: 'desc')

https://platform.openai.com/docs/api-reference/messages/listMessages#messages-listmessages-order

type ListRunStepsOptions

type ListRunStepsOptions map[string]any

ListRunStepsOptions type for listing run steps

func (ListRunStepsOptions) SetAfter

SetAfter sets the `after` parameter of run steps' listing request.

https://platform.openai.com/docs/api-reference/runs/listRunSteps#runs-listrunsteps-after

func (ListRunStepsOptions) SetBefore

func (o ListRunStepsOptions) SetBefore(before string) ListRunStepsOptions

SetBefore sets the `before` parameter of run steps' listing request.

https://platform.openai.com/docs/api-reference/runs/listRunSteps#runs-listrunsteps-before

func (ListRunStepsOptions) SetLimit

func (o ListRunStepsOptions) SetLimit(limit int) ListRunStepsOptions

SetLimit sets the `limit` parameter of run steps' listing request.

https://platform.openai.com/docs/api-reference/runs/listRunSteps#runs-listrunsteps-limit

func (ListRunStepsOptions) SetOrder

SetOrder sets the `order` parameter of run steps' listing request.

`order` can be one of 'asc' or 'desc'. (default: 'desc')

https://platform.openai.com/docs/api-reference/runs/listRunSteps#runs-listrunsteps-order

type ListRunsOptions

type ListRunsOptions map[string]any

ListRunsOptions for listing runs

func (ListRunsOptions) SetAfter

func (o ListRunsOptions) SetAfter(after string) ListRunsOptions

SetAfter sets the `after` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/runs/listRuns#runs-listruns-after

func (ListRunsOptions) SetBefore

func (o ListRunsOptions) SetBefore(before string) ListRunsOptions

SetBefore sets the `before` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/runs/listRuns#runs-listruns-before

func (ListRunsOptions) SetLimit

func (o ListRunsOptions) SetLimit(limit int) ListRunsOptions

SetLimit sets the `limit` parameter of messages' listing request.

https://platform.openai.com/docs/api-reference/runs/listRuns#runs-listruns-limit

func (ListRunsOptions) SetOrder

func (o ListRunsOptions) SetOrder(order string) ListRunsOptions

SetOrder sets the `order` parameter of messages' listing request.

`order` can be one of 'asc' or 'desc'. (default: 'desc')

https://platform.openai.com/docs/api-reference/runs/listRuns#runs-listruns-order

type Message

type Message struct {
	CommonResponse

	ID          string            `json:"id"`
	CreatedAt   int               `json:"created_at"`
	ThreadID    string            `json:"thread_id"`
	Role        string            `json:"role"` // 'user' | 'assistant'
	Content     []MessageContent  `json:"content"`
	AssistantID *string           `json:"assistant_id,omitempty"`
	RunID       *string           `json:"run_id,omitempty"`
	FileIDs     []string          `json:"file_ids"`
	Metadata    map[string]string `json:"metadata"`
}

https://platform.openai.com/docs/api-reference/messages/object

type MessageContent

type MessageContent struct {
	Type MessageContentType `json:"type"`

	ImageFile *MessageContentImageFile `json:"image_file,omitempty"` // Type == 'image_file'
	Text      *MessageContentText      `json:"text,omitempty"`       // Type == 'text'
}

MessageContent struct for Message

type MessageContentImageFile

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

MessageContentImageFile struct for MessageContent

type MessageContentText

type MessageContentText struct {
	Value       string                         `json:"value"`
	Annotations []MessageContentTextAnnotation `json:"annotations"`
}

MessageContentText struct for MessageContent

type MessageContentTextAnnotation

type MessageContentTextAnnotation struct {
	Type MessageContentTextAnnotationType `json:"type"`
	Text string                           `json:"text"`

	FileCitation *MessageContentTextAnnotationFileCitation `json:"file_citation,omitempty"`
	FilePath     *MessageContentTextAnnotationFilePath     `json:"file_path,omitempty"`

	StartIndex int `json:"start_index"`
	EndIndex   int `json:"end_index"`
}

MessageContentTextAnntation struct for MessageContentText

type MessageContentTextAnnotationFileCitation

type MessageContentTextAnnotationFileCitation struct {
	FileID string `json:"file_id"`
	Quote  string `json:"quote"`
}

MessageContentTextAnnotationFileCitation struct

type MessageContentTextAnnotationFilePath

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

MessageContentTextAnnotationFilePath struct

type MessageContentTextAnnotationType

type MessageContentTextAnnotationType string

MessageContentTextAnnotationType type for constants

const (
	MessageContentTextAnnotationTypeFileCitation MessageContentTextAnnotationType = "file_citation"
	MessageContentTextAnnotationTypeFilePath     MessageContentTextAnnotationType = "file_path"
)

MessageContentTextAnnotationType constants

type MessageContentType

type MessageContentType string

MessageContentType type for constants

const (
	MessageContentTypeImageFile MessageContentType = "image_file"
	MessageContentTypeText      MessageContentType = "text"
)

MessageContentType constants

type MessageFile

type MessageFile struct {
	CommonResponse

	ID        string `json:"id"`
	CreatedAt int    `json:"created_at"`
	MessageID string `json:"message_id"`
}

https://platform.openai.com/docs/api-reference/messages/file-object

type MessageFiles

type MessageFiles struct {
	CommonResponse

	Data    []MessageFile `json:"data"`
	FirstID string        `json:"first_id"`
	LastID  string        `json:"last_id"`
	HasMore bool          `json:"has_more"`
}

MessageFiles struct for API response

type Messages

type Messages struct {
	CommonResponse

	Data    []Message `json:"data"`
	FirstID string    `json:"first_id"`
	LastID  string    `json:"last_id"`
	HasMore bool      `json:"has_more"`
}

Messages struct for API response

type Model

type Model struct {
	CommonResponse

	ID         string       `json:"id"`
	Created    int64        `json:"created"`
	OwnedBy    string       `json:"owned_by"`
	Permission []Permission `json:"permission"`
	Root       string       `json:"root"`
	Parent     *string      `json:"parent,omitempty"`
}

Model struct

type ModelDeletionStatus

type ModelDeletionStatus struct {
	CommonResponse

	ID      string `json:"id"`
	Deleted bool   `json:"deleted"`
}

ModelDeletionStatus struct for API response

type ModelsList

type ModelsList struct {
	CommonResponse

	Data []Model `json:"data"`
}

ModelList struct for API response

type Moderation

type Moderation struct {
	CommonResponse

	ID      string           `json:"id"`
	Model   string           `json:"model"`
	Results []Classification `json:"results"`
}

Moderation struct for response

type ModerationOptions

type ModerationOptions map[string]any

ModerationOptions for creating moderation

func (ModerationOptions) SetModel

func (o ModerationOptions) SetModel(model string) ModerationOptions

SetModel sets the `model` parameter of moderation request.

https://platform.openai.com/docs/api-reference/moderations/create#moderations/create-model

type ModifyAssistantOptions

type ModifyAssistantOptions map[string]any

ModifyAssistantOptions for modifying assistant

func (ModifyAssistantOptions) SetDescription

func (o ModifyAssistantOptions) SetDescription(description string) ModifyAssistantOptions

SetDescription sets the `description` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-description

func (ModifyAssistantOptions) SetFileIDs

func (o ModifyAssistantOptions) SetFileIDs(fileIDs []string) ModifyAssistantOptions

SetFileIDs sets the `file_ids` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-file_ids

func (ModifyAssistantOptions) SetInstructions

func (o ModifyAssistantOptions) SetInstructions(instructions string) ModifyAssistantOptions

SetInstructions sets the `instructions` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-instructions

func (ModifyAssistantOptions) SetMetadata

func (o ModifyAssistantOptions) SetMetadata(metadata map[string]string) ModifyAssistantOptions

SetMetadata sets the `metadata` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-metadata

func (ModifyAssistantOptions) SetModel

SetModel sets the `model` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-model

func (ModifyAssistantOptions) SetName

SetName sets the `name` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-name

func (ModifyAssistantOptions) SetTools

SetTools sets the `tools` parameter of assistant modification.

https://platform.openai.com/docs/api-reference/assistants/modifyAssistant#assistants-modifyassistant-tools

type ModifyMessageOptions

type ModifyMessageOptions map[string]any

ModifyMessageOptions for modifying message

func (ModifyMessageOptions) SetMetadata

func (o ModifyMessageOptions) SetMetadata(metadata map[string]string) ModifyMessageOptions

SetMetadata sets the `metadata` parameter of ModifyMessageOptions.

https://platform.openai.com/docs/api-reference/messages/modifyMessage#messages-modifymessage-metadata

type ModifyRunOptions

type ModifyRunOptions map[string]any

ModifyRunOptions for modifying run

func (ModifyRunOptions) SetMetadata

func (o ModifyRunOptions) SetMetadata(metadata map[string]string) ModifyRunOptions

SetMetadata sets the `metadata` parameter of ModifyRunOptions.

https://platform.openai.com/docs/api-reference/runs/modifyRun#runs-modifyrun-metadata

type ModifyThreadOptions

type ModifyThreadOptions map[string]any

ModifyThreadOptions for modifying thread

func (ModifyThreadOptions) SetMetadata

func (o ModifyThreadOptions) SetMetadata(metadata map[string]string) ModifyThreadOptions

SetMetadata sets the `metadata` parameter of ModifyThreadOptions.

https://platform.openai.com/docs/api-reference/threads/modifyThread#threads-modifythread-metadata

type OutputContent added in v0.4.8

type OutputContent struct {
	Type        string       `json:"type"`
	Text        string       `json:"text,omitempty"`
	Annotations []Annotation `json:"annotations,omitempty"`
}

type Permission

type Permission struct {
	ID                 string  `json:"id"`
	Object             string  `json:"object"`
	Created            int64   `json:"created"`
	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              *string `json:"group,omitempty"`
	IsBlocking         bool    `json:"is_blocking"`
}

Permission struct

type Response added in v0.4.8

type Response struct {
	CommonResponse

	ID                 string           `json:"id"`
	Object             string           `json:"object"`
	CreatedAt          int64            `json:"created_at"`
	Status             string           `json:"status"`
	Error              *Error           `json:"error"`
	IncompleteDetails  any              `json:"incomplete_details"`
	Instructions       string           `json:"instructions,omitempty"`
	MaxOutputTokens    *int             `json:"max_output_tokens"`
	Model              string           `json:"model"`
	Output             []ResponseOutput `json:"output"`
	ParallelToolCalls  *bool            `json:"parallel_tool_calls,omitempty"`
	PreviousResponseID *string          `json:"previous_response_id"`
	Reasoning          any              `json:"reasoning,omitempty"`
	Store              *bool            `json:"store,omitempty"`
	Temperature        *float64         `json:"temperature,omitempty"`
	Text               any              `json:"text,omitempty"`
	ToolChoice         any              `json:"tool_choice,omitempty"`
	Tools              []any            `json:"tools,omitempty"`
	TopP               *float64         `json:"top_p,omitempty"`
	Truncation         string           `json:"truncation,omitempty"`
	Usage              *ResponseUsage   `json:"usage,omitempty"`
	User               *string          `json:"user,omitempty"`
	Metadata           map[string]any   `json:"metadata,omitempty"`
}

Response represents a response from the OpenAI Responses API

type ResponseFunctionCallOutput added in v0.4.8

type ResponseFunctionCallOutput struct {
	Type   string `json:"type"`    // "function_call_output"
	CallID string `json:"call_id"` // The call_id from function call
	Output string `json:"output"`  // Function execution result
}

ResponseFunctionCallOutput represents function call output for input

func NewResponseFunctionCallOutput added in v0.4.8

func NewResponseFunctionCallOutput(callID, output string) ResponseFunctionCallOutput

NewResponseFunctionCallOutput creates a function call output for input

type ResponseMessage added in v0.4.8

type ResponseMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ResponseMessage represents a message input for the responses API

func NewResponseMessage added in v0.4.8

func NewResponseMessage(role, content string) ResponseMessage

NewResponseMessage creates a new ResponseMessage

func NewResponseMessageInput added in v0.4.8

func NewResponseMessageInput(messages []ResponseMessage) []ResponseMessage

NewResponseMessageInput creates input from a slice of ResponseMessage

type ResponseOptions added in v0.4.8

type ResponseOptions map[string]any

ResponseOptions for creating responses

func (ResponseOptions) SetInstructions added in v0.4.8

func (o ResponseOptions) SetInstructions(instructions string) ResponseOptions

SetInstructions sets the instructions parameter

func (ResponseOptions) SetMaxOutputTokens added in v0.4.8

func (o ResponseOptions) SetMaxOutputTokens(maxTokens int) ResponseOptions

SetMaxOutputTokens sets the max_output_tokens parameter

func (ResponseOptions) SetMetadata added in v0.4.8

func (o ResponseOptions) SetMetadata(metadata map[string]any) ResponseOptions

SetMetadata sets the metadata parameter

func (ResponseOptions) SetParallelToolCalls added in v0.4.8

func (o ResponseOptions) SetParallelToolCalls(parallel bool) ResponseOptions

SetParallelToolCalls sets the parallel_tool_calls parameter

func (ResponseOptions) SetStore added in v0.4.8

func (o ResponseOptions) SetStore(store bool) ResponseOptions

SetStore sets the store parameter

func (ResponseOptions) SetStream added in v0.4.8

func (o ResponseOptions) SetStream(cb responseCallback) ResponseOptions

SetStream sets the stream parameter with callback

func (ResponseOptions) SetTemperature added in v0.4.8

func (o ResponseOptions) SetTemperature(temperature float64) ResponseOptions

SetTemperature sets the temperature parameter

func (ResponseOptions) SetToolChoice added in v0.4.8

func (o ResponseOptions) SetToolChoice(toolChoice any) ResponseOptions

SetToolChoice sets the tool_choice parameter

func (ResponseOptions) SetToolChoiceAuto added in v0.4.8

func (o ResponseOptions) SetToolChoiceAuto() ResponseOptions

SetToolChoiceAuto sets tool_choice to "auto"

func (ResponseOptions) SetToolChoiceFunction added in v0.4.8

func (o ResponseOptions) SetToolChoiceFunction(functionName string) ResponseOptions

SetToolChoiceFunction sets tool_choice to force a specific function

func (ResponseOptions) SetToolChoiceNone added in v0.4.8

func (o ResponseOptions) SetToolChoiceNone() ResponseOptions

SetToolChoiceNone sets tool_choice to "none"

func (ResponseOptions) SetToolChoiceRequired added in v0.4.8

func (o ResponseOptions) SetToolChoiceRequired() ResponseOptions

SetToolChoiceRequired sets tool_choice to "required"

func (ResponseOptions) SetTools added in v0.4.8

func (o ResponseOptions) SetTools(tools []any) ResponseOptions

SetTools sets the tools parameter

func (ResponseOptions) SetTopP added in v0.4.8

func (o ResponseOptions) SetTopP(topP float64) ResponseOptions

SetTopP sets the top_p parameter

func (ResponseOptions) SetUser added in v0.4.8

func (o ResponseOptions) SetUser(user string) ResponseOptions

SetUser sets the user parameter

type ResponseOutput added in v0.4.8

type ResponseOutput struct {
	ID      string          `json:"id"`
	Type    string          `json:"type"`
	Status  string          `json:"status"`
	Role    string          `json:"role,omitempty"`
	Content []OutputContent `json:"content,omitempty"`

	// Function call fields (when Type == "function_call")
	CallID    string `json:"call_id,omitempty"`
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`

} // OutputContent represents content within a response output

ResponseOutput represents an output item in the response

func (ResponseOutput) ArgumentsInto added in v0.4.8

func (r ResponseOutput) ArgumentsInto(out any) (err error)

ArgumentsInto parses the function call arguments into a given interface

func (ResponseOutput) ArgumentsParsed added in v0.4.8

func (r ResponseOutput) ArgumentsParsed() (result map[string]any, err error)

ArgumentsParsed returns the parsed arguments from a function call ResponseOutput

type ResponseStreamEvent added in v0.4.8

type ResponseStreamEvent struct {
	Type string `json:"type"`

	// For response events
	Response   *Response `json:"response,omitempty"`
	ResponseID *string   `json:"response_id,omitempty"`

	// For output item events
	OutputIndex *int            `json:"output_index,omitempty"`
	Item        *ResponseOutput `json:"item,omitempty"`

	// For content part events
	ItemID       *string        `json:"item_id,omitempty"`
	ContentIndex *int           `json:"content_index,omitempty"`
	Part         *OutputContent `json:"part,omitempty"`

	// For delta events
	Delta *string `json:"delta,omitempty"`

	// For done events
	Text      *string `json:"text,omitempty"`
	Arguments *string `json:"arguments,omitempty"`
}

ResponseStreamEvent represents a streaming event from the responses API

type ResponseTokensDetails added in v0.4.8

type ResponseTokensDetails struct {
	CachedTokens    int `json:"cached_tokens,omitempty"`
	ReasoningTokens int `json:"reasoning_tokens,omitempty"`
}

ResponseTokensDetails provides detailed token usage information

type ResponseTool added in v0.4.8

type ResponseTool struct {
	Type        string                 `json:"type"`
	Name        string                 `json:"name,omitempty"`
	Description string                 `json:"description,omitempty"`
	Parameters  ToolFunctionParameters `json:"parameters,omitempty"`
}

func NewResponseTool added in v0.4.8

func NewResponseTool(name, description string, parameters ToolFunctionParameters) ResponseTool

NewResponseTool creates a function tool for responses API

type ResponseToolChoice added in v0.4.8

type ResponseToolChoice struct {
	Type string `json:"type,omitempty"`
	Name string `json:"name,omitempty"`
}

ResponseToolChoice represents tool choice options

type ResponseUsage added in v0.4.8

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

ResponseUsage represents token usage information

type RetrievedFile

type RetrievedFile File

RetrievedFile struct for response

type Run

type Run struct {
	CommonResponse

	ID             string            `json:"id"`
	CreatedAt      int               `json:"created_at"`
	ThreadID       string            `json:"thread_id"`
	AssistantID    string            `json:"assistant_id"`
	Status         RunStatus         `json:"status"`
	RequiredAction *RunAction        `json:"required_action,omitempty"`
	LastError      *RunError         `json:"last_error,omitempty"`
	ExpiresAt      int               `json:"expires_at"`
	StartedAt      *int              `json:"started_at,omitempty"`
	CancelledAt    *int              `json:"cancelled_at,omitempty"`
	FailedAt       *int              `json:"failed_at,omitempty"`
	CompletedAt    *int              `json:"completed_at,omitempty"`
	Model          string            `json:"model"`
	Instructions   string            `json:"instructions"`
	Tools          []Tool            `json:"tools"`
	FileIDs        []string          `json:"file_ids"`
	Metadata       map[string]string `json:"metadata"`
}

https://platform.openai.com/docs/api-reference/runs/object

type RunAction

type RunAction struct {
	Type              string `json:"type"` // == 'submit_tool_outputs'
	SubmitToolOutputs struct {
		ToolCalls []ToolCall `json:"tool_calls"`
	} `json:"submit_tool_outputs"`
}

RunAction struct for Run struct

type RunError

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

RunError struct for Run struct

type RunErrorCode

type RunErrorCode string

RunErrorCode type for constants

const (
	RunErrorCodeServerError   RunErrorCode = "server_error"
	RunErrorRateLimitExceeded RunErrorCode = "rate_limit_exceeded"
)

RunErrorCode constants

type RunStatus

type RunStatus string

RunStatus type for constants

const (
	RunStatusQueued         RunStatus = "queued"
	RunStatusInProgress     RunStatus = "in_progress"
	RunStatusRequiresAction RunStatus = "requires_action"
	RunStatusCanceling      RunStatus = "cancelling"
	RunStatusCanceled       RunStatus = "cancelled"
	RunStatusFailed         RunStatus = "failed"
	RunStatusCompleted      RunStatus = "completed"
	RunStatusExpired        RunStatus = "expired"
)

RunStatus constants

type RunStep

type RunStep struct {
	CommonResponse

	ID          string            `json:"id"`
	CreatedAt   int               `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 RunStepDetails    `json:"step_details"`
	LastError   *RunError         `json:"last_error,omitempty"`
	ExpiredAt   *int              `json:"expired_at,omitempty"`
	CancelledAt *int              `json:"cancelled_at,omitempty"`
	FailedAt    *int              `json:"failed_at,omitempty"`
	CompletedAt *int              `json:"completed_at,omitempty"`
	Metadata    map[string]string `json:"metadata"`
}

https://platform.openai.com/docs/api-reference/runs/step-object

type RunStepDetails

type RunStepDetails struct {
	Type RunStepType `json:"type"`

	MessageCreation *RunStepDetailsMessageCreation `json:"message_creation,omitempty"` // Type == RunStepTypeMessageCreation
	ToolCalls       []RunStepDetailsToolCall       `json:"tool_calls,omitempty"`       // Type == RunStepTypeToolCalls
}

RunStepDetails struct for RunStepObject struct

type RunStepDetailsMessageCreation

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

RunStepDetailsMessageCreation struct for RunStepDetails struct

type RunStepDetailsToolCall

type RunStepDetailsToolCall struct {
	ID   string `json:"id"`
	Type string `json:"type"`

	CodeInterpreter *RunStepDetailsToolCallCodeInterpreter `json:"code_interpreter,omitempty"` // Type == ToolTypeCodeInterpreter
	Retrieval       *RunStepDetailsToolCallRetrieval       `json:"retrieval,omitempty"`        // Type -== ToolTypeRetrieval
	Function        *RunStepDetailsToolCallFunction        `json:"function,omitempty"`         // Type == ToolTypeFunction
}

RunStepDetailsToolCall struct for RunStepDetails struct

type RunStepDetailsToolCallCodeInterpreter

type RunStepDetailsToolCallCodeInterpreter struct {
	Input   string                          `json:"input"`
	Outputs []ToolCallCodeInterpreterOutput `json:"outputs"`
}

RunStepDetailsToolCallCodeInterpreter struct for RunStepDetailsToolCall struct

type RunStepDetailsToolCallFunction

type RunStepDetailsToolCallFunction struct {
	Name      string  `json:"name"`
	Arguments string  `json:"arguments"`
	Output    *string `json:"output,omitempty"`
}

RunStepDetailsToolCallsFunction struct for RunStepDetailsToolCall struct

type RunStepDetailsToolCallRetrieval

type RunStepDetailsToolCallRetrieval struct{}

RunStepDetailsToolCallRetrieval struct for RunStepDetailsToolCall struct (empty object for now)

type RunStepStatus

type RunStepStatus string

RunStepStatus type for constants

const (
	RunStepStatusInProgress RunStepStatus = "in_progress"
	RunStepStatusCancelled  RunStepStatus = "cancelled"
	RunStepStatusFailed     RunStepStatus = "failed"
	RunStepStatusCompleted  RunStepStatus = "completed"
	RunStepStatusExpired    RunStepStatus = "expired"
)

RunStepStatus constants

type RunStepType

type RunStepType string

RunStepType type for constants

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

RunStepType constants

type RunSteps

type RunSteps struct {
	CommonResponse

	Data    []RunStep `json:"data"`
	FirstID string    `json:"first_id"`
	LastID  string    `json:"last_id"`
	HasMore bool      `json:"has_more"`
}

RunSteps struct for API response

type RunnableThread

type RunnableThread struct {
	Messages []RunnableThreadMessage `json:"messages,omitempty"`
	Metadata map[string]string       `json:"metadata,omitempty"`
}

RunnableThread struct for CreateThreadAndRunOptions

type RunnableThreadMessage

type RunnableThreadMessage struct {
	Role     string            `json:"role"` // == 'user'
	Content  string            `json:"content"`
	FileIDs  []string          `json:"file_ids,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

RunnableThreadMessage struct for RunnableThread struct

type Runs

type Runs struct {
	CommonResponse

	Data    []Run  `json:"data"`
	FirstID string `json:"first_id"`
	LastID  string `json:"last_id"`
	HasMore bool   `json:"has_more"`
}

Runs struct for API response

type SpeechOptions

type SpeechOptions map[string]any

SpeechOptions for creating speech

func (SpeechOptions) SetResponseFormat

func (o SpeechOptions) SetResponseFormat(format SpeechResponseFormat) SpeechOptions

SetResponseFormat sets the `response_format` parameter of speech request.

func (SpeechOptions) SetSpeed

func (o SpeechOptions) SetSpeed(speed float32) SpeechOptions

SetSpeed sets the `speed` parameter of speech request.

type SpeechResponseFormat

type SpeechResponseFormat string

SpeechResponseFormat type for constants

const (
	SpeechResponseFormatMP3  SpeechResponseFormat = "mp3"
	SpeechResponseFormatOpus SpeechResponseFormat = "opus"
	SpeechResponseFormatAAC  SpeechResponseFormat = "aac"
	SpeechResponseFormatFLAC SpeechResponseFormat = "flac"
)

type SpeechVoice

type SpeechVoice string

SpeechVoice type for constants

const (
	SpeechVoiceAlloy   SpeechVoice = "alloy"
	SpeechVoiceEcho    SpeechVoice = "echo"
	SpeechVoiceFable   SpeechVoice = "fable"
	SpeechVoiceOnyx    SpeechVoice = "onyx"
	SpeechVoiceNova    SpeechVoice = "nova"
	SpeechVoiceShimmer SpeechVoice = "shimmer"
)

type Thread

type Thread struct {
	CommonResponse

	ID        string            `json:"id"`
	CreatedAt int               `json:"created_at"`
	Metadata  map[string]string `json:"metadata"`
}

Thread struct

https://platform.openai.com/docs/api-reference/threads/object

type ThreadDeletionStatus

type ThreadDeletionStatus struct {
	CommonResponse

	ID      string `json:"id"`
	Deleted bool   `json:"deleted"`
}

ThreadDeletionStatus for API response

type ThreadMessage

type ThreadMessage struct {
	Role     string            `json:"role"` // == 'user'
	Content  string            `json:"content"`
	FileIDs  []string          `json:"file_ids,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

ThreadMessage struct for Thread

func NewThreadMessage

func NewThreadMessage(content string) ThreadMessage

NewThreadMessage returns a new ThreadMessage with given `content`.

func (ThreadMessage) SetFileIDs

func (m ThreadMessage) SetFileIDs(fileIDs []string) ThreadMessage

SetFileIDs sets the `file_ids` value of ThreadMessage and return it.

func (ThreadMessage) SetMetadata

func (m ThreadMessage) SetMetadata(metadata map[string]string) ThreadMessage

SetMetadata sets the `metadata` value of ThreadMessage and return it.

type Tool

type Tool struct {
	Type     string        `json:"type"`
	Function *ToolFunction `json:"function,omitempty"`
}

Tool struct for assistant object

https://platform.openai.com/docs/api-reference/assistants/object#assistants/object-tools

func NewBuiltinTool added in v0.4.8

func NewBuiltinTool(fn string) Tool

NewBuiltinTool returns a tool with a specified type.

func NewCodeInterpreterTool

func NewCodeInterpreterTool() Tool

NewCodeInterpreterTool returns a tool with type: 'code_interpreter'.

func NewFunctionTool

func NewFunctionTool(fn ToolFunction) Tool

NewFunctionTool returns a tool with type: 'function'.

func NewRetrievalTool

func NewRetrievalTool() Tool

NewRetrievalTool returns a tool with type: 'retrieval'.

type ToolCall

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

ToolCall struct

func (ToolCall) ArgumentsInto

func (c ToolCall) ArgumentsInto(out any) (err error)

ArgumentsInto parses the generated arguments into a given interface

func (ToolCall) ArgumentsParsed

func (c ToolCall) ArgumentsParsed() (result map[string]any, err error)

ArgumentsParsed returns the parsed map from ToolCall.

type ToolCallCodeInterpreterOutput

type ToolCallCodeInterpreterOutput struct {
	Type ToolCallCodeInterpreterOutputType `json:"type"`

	Logs  *string                             `json:"logs,omitempty"`  // Type == ToolCallCodeInterpreterOutputTypeLogs
	Image *ToolCallCodeInterpreterOutputImage `json:"image,omitempty"` // Type == ToolCallCodeInterpreterOutputTypeImage
}

ToolCallCodeInterpreterOutput struct for RunStepDetailsToolCallCodeInterpreter struct

type ToolCallCodeInterpreterOutputImage

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

ToolCallCodeInterpreterOutputImage struct for ToolCallCodeInterpreterOutput struct

type ToolCallCodeInterpreterOutputType

type ToolCallCodeInterpreterOutputType string

ToolCallCodeInterpreterOutputType type for constants

const (
	ToolCallCodeInterpreterOutputTypeLogs  ToolCallCodeInterpreterOutputType = "logs"
	ToolCallCodeInterpreterOutputTypeImage ToolCallCodeInterpreterOutputType = "image"
)

ToolCallCodeInterpreterOutputType constants

type ToolCallFunction

type ToolCallFunction struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCallFunction struct for ToolCall

type ToolFunction

type ToolFunction struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Parameters  ToolFunctionParameters `json:"parameters"`
}

ToolFunction struct for Tool struct

type ToolFunctionParameters

type ToolFunctionParameters map[string]any

ToolFunctionParameters type

func NewToolFunctionParameters

func NewToolFunctionParameters() ToolFunctionParameters

NewToolFunctionParameters returns an empty ToolFunctionParameters.

func (ToolFunctionParameters) AddArrayPropertyWithDescription

func (p ToolFunctionParameters) AddArrayPropertyWithDescription(name, elemType, description string) ToolFunctionParameters

AddArrayPropertyWithDescription adds/overwrites an array property in chat completion function parameters with a description.

func (ToolFunctionParameters) AddPropertyWithDescription

func (p ToolFunctionParameters) AddPropertyWithDescription(name, typ3, description string) ToolFunctionParameters

AddPropertyWithDescription adds/overwrites a property in chat completion function parameters with a description.

func (ToolFunctionParameters) AddPropertyWithEnums

func (p ToolFunctionParameters) AddPropertyWithEnums(name, typ3, description string, enums []string) ToolFunctionParameters

AddPropertyWithEnums adds/overwrites a property in chat completion function parameters with enums.

func (ToolFunctionParameters) SetRequiredParameters

func (p ToolFunctionParameters) SetRequiredParameters(names []string) ToolFunctionParameters

SetRequiredParameters sets/overwrites required parameter names for chat completion function parameters.

type ToolOutput

type ToolOutput struct {
	ToolCallID *string `json:"tool_call_id,omitempty"`
	Output     *string `json:"output,omitempty"`
}

ToolOutput struct for API request

type Transcription

type Transcription struct {
	CommonResponse

	JSON        *string `json:"json,omitempty"`
	Text        *string `json:"text,omitempty"`
	SRT         *string `json:"srt,omitempty"`
	VerboseJSON *string `json:"verbose_json,omitempty"`
	VTT         *string `json:"vtt,omitempty"`
}

Transcription struct for response

type TranscriptionOptions

type TranscriptionOptions map[string]any

TranscriptionOptions for creating transcription

func (TranscriptionOptions) SetLanguage

func (o TranscriptionOptions) SetLanguage(language string) TranscriptionOptions

SetLanguage sets the `language` parameter of transcription request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-language

func (TranscriptionOptions) SetPrompt

func (o TranscriptionOptions) SetPrompt(prompt string) TranscriptionOptions

SetPrompt sets the `prompt` parameter of transcription request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-prompt

func (TranscriptionOptions) SetResponseFormat

func (o TranscriptionOptions) SetResponseFormat(responseFormat TranscriptionResponseFormat) TranscriptionOptions

SetResponseFormat sets the `response_format` parameter of transcription request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-response_format

func (TranscriptionOptions) SetTemperature

func (o TranscriptionOptions) SetTemperature(temperature float64) TranscriptionOptions

SetTemperature sets the `temperature` parameter of transcription request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-temperature

type TranscriptionResponseFormat

type TranscriptionResponseFormat string

TranscriptionResponseFormat type for constants

const (
	TranscriptionResponseFormatJSON        TranscriptionResponseFormat = "json"
	TranscriptionResponseFormatText        TranscriptionResponseFormat = "text"
	TranscriptionResponseFormatSRT         TranscriptionResponseFormat = "srt"
	TranscriptionResponseFormatVerboseJSON TranscriptionResponseFormat = "verbose_json"
	TranscriptionResponseFormatVTT         TranscriptionResponseFormat = "vtt"
)

type Translation

type Translation Transcription

Transcription struct for response

type TranslationOptions

type TranslationOptions map[string]any

TranslationOptions for creating transcription

func (TranslationOptions) SetPrompt

func (o TranslationOptions) SetPrompt(prompt string) TranslationOptions

SetPrompt sets the `prompt` parameter of translation request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-prompt

func (TranslationOptions) SetResponseFormat

func (o TranslationOptions) SetResponseFormat(responseFormat TranslationResponseFormat) TranslationOptions

SetResponseFormat sets the `response_format` parameter of translation request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-response_format

func (TranslationOptions) SetTemperature

func (o TranslationOptions) SetTemperature(temperature float64) TranslationOptions

SetTemperature sets the `temperature` parameter of translation request.

https://platform.openai.com/docs/api-reference/audio/create#audio/create-temperature

type TranslationResponseFormat

type TranslationResponseFormat TranscriptionResponseFormat

TransclationResponseFormat type for constants

type UploadedFile

type UploadedFile File

UploadedFile struct for response

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage struct for reponses

Jump to

Keyboard shortcuts

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