openai

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package openai / internal / config.go provides configuration for OpenAI API clients.

Package openai / internal / openai.go provides common functions, constants and types for OpenAI API wrappers.

Package openai / internal / stopreasons.go contains stop reasons that can be returned by OpenAI.

Package openai / internal / tools.go provides internal types for handling tool calls.

Index

Constants

View Source
const (
	FinishReasonStop         = "stop"
	FinishReasonLength       = "length"
	FinishReasonFilter       = "content_filter"
	FinishReasonFunctionCall = "function_call"
	FinishReasonToolCalls    = "tool_calls"
	FinishReasonNull         = "null"
)

Stop reason constants.

View Source
const DefaultBaseAPI = "https://api.openai.com/"

DefaultBaseAPI is the default base URL for OpenAI API endpoints.

Variables

View Source
var (
	TokenEncoderChat       *tiktoken.Tiktoken
	TokenEncoderCompletion *tiktoken.Tiktoken
)

Encoders for counting tokens.

View Source
var SupportedImageTypes = []string{"png", "jpeg", "jpg", "gif", "webp"}

SupportedImageTypes is a list of supported image file extensions.

Functions

func LoadTokenEncoders

func LoadTokenEncoders() error

LoadTokenEncoders loads token encoders for chat and completion models. Uses cache directory. Can be called repeatedly but will not reload encoders if they are already successfully loaded.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal marshals the given value to JSON. HTML escaping is disabled.

Types

type Config

type Config struct {

	// BaseAPI is the base URL for OpenAI API endpoints
	BaseAPI    string
	Token      string
	HTTPClient *HTTPClient
	Log        *slog.Logger
	Tools      *tools.Registry
	// contains filtered or unexported fields
}

Config contains configuration options for the OpenAI client.

func NewConfig

func NewConfig(token string) *Config

NewConfig creates a default configuration with the provided token.

func (*Config) AddHeaders

func (c *Config) AddHeaders(req *http.Request)

AddHeaders adds the basic required headers to given API request. Includes Authorization and Content-Type.

func (*Config) DisableLogTripper

func (c *Config) DisableLogTripper() error

DisableLogTripper turns off debug logging of HTTP requests and responses. Returns error if the expectation that HTTPClient has LoggingTransport is not met.

func (*Config) EnableLogTripper

func (c *Config) EnableLogTripper() error

EnableLogTripper turns on debug logging of HTTP requests and responses with slog instance from Config. Returns error if the expectation that HTTPClient has LoggingTransport is not met.

type FunctionCallData

type FunctionCallData struct {
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"` // has JSON object, but as a string
}

FunctionCall represents a function call in API response. Contains name of the function to be called and its arguments as a JSON object encoded into a string. Must be verified as AI may provide invalid JSON or incorrect arguments.

func (FunctionCallData) UnmarshalArguments

func (data FunctionCallData) UnmarshalArguments(target any) error

UnmarshalArguments decodes JSON-encoded arguments into target.

type HTTPClient

type HTTPClient struct {
	*http.Client

	// Number of attempts to make the request. 2 means one attempt and one retry.
	RequestAttempts int

	// Interval to wait before each retry.
	RetryInterval time.Duration

	// If true, LogTripper is enabled on errors and disabled on successes.
	AutoLogTripper bool
}

HTTPClient is a wrapper for http.Client with OpenAI-specific behaviors.

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient creates a new HTTPClient with default settings.

func (*HTTPClient) Do

func (c *HTTPClient) Do(req *http.Request) (*http.Response, error)

Do performs the HTTP request but makes a copy of body beforehand and sets it back afterwards to allow retrying the same request multiple times with no data loss.

func (*HTTPClient) WithRetry

func (c *HTTPClient) WithRetry(req *http.Request) (*http.Response, error)

WithRetry performs the HTTP request and retries it if it fails (err or not 200), according to the settings.

type LoggingTransport

type LoggingTransport struct {
	Log       *slog.Logger
	EnableLog bool
}

LoggingTransport is a custom HTTP transport that logs request and response dumps.

func (*LoggingTransport) RoundTrip

func (lt *LoggingTransport) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip logs the request and response while performing round trip, if logger is set.

type ToolCallData

type ToolCallData struct {
	ID       string            `json:"id,omitempty"`
	Type     string            `json:"type,omitempty"` // only "function" now
	Function *FunctionCallData `json:"function,omitempty"`
}

ToolCall represents a tool call in API response.

Directories

Path Synopsis
cmd
getmodels command
Package main / api.go contains types and functions for interacting with models.dev API.
Package main / api.go contains types and functions for interacting with models.dev API.
Package inchat provides a wrapper for the OpenAI Chat API.
Package inchat provides a wrapper for the OpenAI Chat API.
Package incompletion provides a wrapper for the OpenAI Completion API.
Package incompletion provides a wrapper for the OpenAI Completion API.
Package inmoderation provides a wrapper for the OpenAI Moderation API.
Package inmoderation provides a wrapper for the OpenAI Moderation API.
Package inresponses / conversations.go contains the implementation of the ConversationCli interface.
Package inresponses / conversations.go contains the implementation of the ConversationCli interface.

Jump to

Keyboard shortcuts

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