openai

package
v0.43.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: Apache-2.0 Imports: 19 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package openai implements agent.LLMProvider for the OpenAI Chat Completions API and any OpenAI-compatible endpoint (Ollama, Groq, Together AI, vLLM, ...), plus the OpenAI-backed embedder, vision analyzer, and history summary provider.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientOption added in v0.40.0

type ClientOption interface {
	Option
	// contains filtered or unexported methods
}

ClientOption configures transport for any client in this package — Provider, Embedder, VisionAnalyzer, SummaryProvider.

It is a strict subset of Option. Sampling has no meaning for an embedder, so NewEmbedder and friends accept only these: passing WithTemperature to one is a compile error rather than an option that silently does nothing.

func WithBaseURL added in v0.40.0

func WithBaseURL(url string) ClientOption

WithBaseURL points the client at an OpenAI-compatible endpoint — OpenRouter, Ollama, vLLM, Groq, Together, or any gateway speaking the same API.

This is the only way to keep an Embedder, VisionAnalyzer, or SummaryProvider off api.openai.com. Without it they call OpenAI directly, which on a deliberately local or gateway-only deployment means an unexpected egress and a key the operator may not hold.

url must be absolute, HTTP(S), and free of embedded credentials, a query, or a fragment; it is validated at construction. Prefer HTTPS except for local development endpoints.

func WithHTTPHeader added in v0.40.0

func WithHTTPHeader(name, value string) ClientOption

WithHTTPHeader adds a header to every request the client makes. It is useful for compatible gateways that accept attribution or routing headers.

Headers are applied after the SDK has built the request, so a name the SDK already sets is overwritten: passing "Authorization" replaces the bearer token derived from apiKey. Repeated calls with the same name keep the last value.

type Embedder

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

Embedder implements tools.Embedder using OpenAI's embeddings API.

text-embedding-3-small is the default — 1536 dimensions, ~$0.02/1M tokens, and more than enough lexical/semantic signal for tool-description ranking. Pass model = "" to use the default, or a specific model id (e.g. openai.LargeEmbedding3 for higher fidelity at ~6x the cost).

func NewEmbedder

func NewEmbedder(apiKey string, model string, opts ...ClientOption) (*Embedder, error)

NewEmbedder constructs an embedder. apiKey falls back to OPENAI_API_KEY. model defaults to text-embedding-3-small. Pass WithBaseURL to embed against an OpenAI-compatible endpoint (Ollama, vLLM, Together, a gateway) instead of api.openai.com.

func (*Embedder) Embed

func (e *Embedder) Embed(ctx context.Context, texts []string) ([][]float32, error)

Embed returns one vector per input in the same order. Empty input returns (nil, nil).

type JSONMode added in v0.42.0

type JSONMode int

JSONMode selects the wire encoding an endpoint accepts for a schema-constrained response.

api.openai.com takes response_format {type:"json_schema"} with the schema inline and enforces it server-side. Compatible endpoints implement an unknown subset of that: several publish only the older {type:"json_object"}, which guarantees JSON syntax but carries no schema field at all, and some publish neither. Sending json_schema to an endpoint that does not implement it is a 400 on every structured call, so the mode is configuration — the adapter cannot infer it from a base URL.

const (
	// JSONModeSchema sends response_format {type:"json_schema", ...} with the
	// schema inline, and the endpoint enforces it. Zero value because it is
	// what this package is named for; NewCompat overrides it.
	JSONModeSchema JSONMode = iota
	// JSONModeObject sends response_format {type:"json_object"} and appends
	// the schema to the prompt, because that wire format has nowhere to put
	// it. The endpoint guarantees only that the reply parses as JSON —
	// conformance to the schema degrades to a model instruction, so callers
	// should validate the result and be ready to retry.
	JSONModeObject
	// JSONModeNone declares no JSON mode. A structured-output request against
	// such an endpoint fails at the call, rather than silently downgrading to
	// free-form prose that the caller would then try to unmarshal.
	JSONModeNone
)

func (JSONMode) String added in v0.42.0

func (m JSONMode) String() string

String implements fmt.Stringer so the mode reads as its constant name in error messages instead of an integer.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a chat Provider. Both the sampling options (WithTemperature, WithTopP, WithSeed) and the transport options (WithBaseURL, WithHTTPHeader) satisfy it, so one call can mix them.

func WithImageInput added in v0.42.0

func WithImageInput(ok bool) Option

WithImageInput declares whether this endpoint accepts image parts on user messages. Same reasoning as WithJSONMode: New reports OpenAI's own support, NewCompat claims none until the caller declares it.

It sets Capabilities().ImageInput only. Media parts are rendered on the wire either way, so this changes what the provider promises, not what it sends — a caller that skips the capability check still reaches the endpoint's own rejection.

func WithJSONMode added in v0.42.0

func WithJSONMode(m JSONMode) Option

WithJSONMode declares which JSON mode this endpoint implements. It is meaningful only on a compatible endpoint: New already reports the mode api.openai.com implements, and NewCompat claims none until this says otherwise.

It also drives Capabilities().StructuredOutput, so declaring the mode is what lets a consumer that depends on schema enforcement accept the provider at construction.

func WithSeed

func WithSeed(n int64) Option

WithSeed requests best-effort deterministic sampling. Determinism is not guaranteed across model versions or backend changes — pair with a pinned temperature for the strongest reproducibility OpenAI offers.

func WithTemperature

func WithTemperature(t float64) Option

WithTemperature pins the sampling temperature (0.0–2.0 for OpenAI). Use 0 for maximally reproducible classification/extraction turns; unset keeps the provider default. An explicit 0 is honored (the SDK's omitempty would otherwise drop it and silently revert to the provider default).

func WithTopP

func WithTopP(v float64) Option

WithTopP pins nucleus sampling. OpenAI recommends adjusting either temperature or top_p, not both. Unset keeps the provider default.

type Provider

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

Provider implements agent.LLMProvider using the OpenAI Chat Completions API.

func New

func New(apiKey string, model string, opts ...Option) (*Provider, error)

New creates a wrapper over OpenAI's API. Auto-discovers OPENAI_API_KEY from environment if apiKey is empty.

Pass WithBaseURL to target an OpenAI-compatible endpoint instead; NewCompat is the same thing with baseURL required rather than optional.

func NewCompat

func NewCompat(apiKey string, model string, baseURL string, opts ...Option) (*Provider, error)

NewCompat creates a provider for any OpenAI-compatible API endpoint. This covers: OpenRouter, Google Gemini (via OpenAI compat), Ollama, Groq, Together AI, vLLM, etc. baseURL must be an absolute HTTP(S) URL without embedded credentials, a query, or a fragment. Prefer HTTPS except for local development endpoints.

It is New plus WithBaseURL, with baseURL required rather than optional and model required rather than defaulted — a compatible endpoint has no sensible default model. Note that this configures the chat provider only: point NewEmbedder, NewVisionAnalyzer, and NewSummaryProvider at the same endpoint with WithBaseURL, or they will call api.openai.com.

Two features default off here for the same reason the model is required: a compatible endpoint implements an unknown subset of the API, so the adapter declares nothing it cannot know.

  • JSON mode is JSONModeNone. A structured-output call fails until WithJSONMode says what the endpoint implements. Endpoints publishing OpenAI's json_schema take JSONModeSchema; those publishing only the older json_object take JSONModeObject.
  • Image input is unclaimed until WithImageInput(true).

Both feed Capabilities(), so a consumer that needs schema enforcement or vision can reject the provider at construction instead of at the first request.

Examples:

Gemini:  NewCompat("GEMINI_API_KEY", "gemini-2.0-flash", "https://generativelanguage.googleapis.com/v1beta/openai",
             WithJSONMode(JSONModeSchema), WithImageInput(true))
OpenRouter: NewCompat("OPENROUTER_API_KEY", "openai/gpt-4o", "https://openrouter.ai/api/v1",
             WithJSONMode(JSONModeSchema), WithImageInput(true))
DeepSeek: NewCompat("DEEPSEEK_API_KEY", "deepseek-v4-flash", "https://api.deepseek.com/v1",
             WithJSONMode(JSONModeObject))
Ollama:  NewCompat("ollama", "llama3", "http://localhost:11434/v1", WithJSONMode(JSONModeObject))
Groq:    NewCompat("GROQ_KEY", "llama-3.3-70b-versatile", "https://api.groq.com/openai/v1", WithJSONMode(JSONModeObject))

func (*Provider) Capabilities added in v0.40.0

func (p *Provider) Capabilities() agent.LLMCapabilities

Capabilities reports what this provider's endpoint accepts, as configured.

New reports api.openai.com's features. NewCompat claims nothing until the caller declares its endpoint with WithJSONMode / WithImageInput: a compatible endpoint implements an unknown subset, and the whole value of this signal is that a consumer can reject an unsuitable provider at construction — a blanket claim on behalf of every gateway in the ecosystem would hand that consumer a confident wrong answer instead.

func (*Provider) GenerateStream

func (p *Provider) GenerateStream(ctx context.Context, memory []history.Message, availableTools *tools.Registry, streamChan chan<- agent.StreamEvent) (agent.LLMResult, error)

GenerateStream maps GopherAgent history to OpenAI API format and triggers streaming generation.

type SummaryProvider

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

SummaryProvider implements history.SummaryProvider using OpenAI. It uses a cheap, fast model (default: gpt-4o-mini) to extract long-term behavioral patterns from conversation history, injected back into the system prompt on the next turn.

Usage:

sp, _ := openai.NewSummaryProvider("", "gpt-4o-mini")
sm := history.NewInMemSessionManager("You are an assistant.")
sm.SummaryProvider = sp

func NewSummaryProvider

func NewSummaryProvider(apiKey, model string, opts ...ClientOption) (*SummaryProvider, error)

NewSummaryProvider creates an OpenAI-backed SummaryProvider. Auto-discovers OPENAI_API_KEY from environment if apiKey is empty. model defaults to "gpt-4o-mini" (cheap + fast — ideal for background summarization). Pass WithBaseURL to summarize against an OpenAI-compatible endpoint instead of api.openai.com.

func (*SummaryProvider) SummarizeBehaviors

func (s *SummaryProvider) SummarizeBehaviors(ctx context.Context, newMsgs []history.Message, previousSummary string) (string, error)

SummarizeBehaviors analyzes recent messages and merges new evidence into the existing previousSummary, returning an updated behavioral profile paragraph. Only newMessages (since last summarization) are analyzed — not the full history.

type Transcriber added in v0.41.0

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

Transcriber implements audio.Transcriber against OpenAI's audio transcription endpoint.

Model choice changes the shape of the result. whisper-1 supports the verbose_json response format and so populates Transcript.Segments, Language, and Duration. The gpt-4o-transcribe family accepts only json and text, so it returns text alone with Segments nil — correct, but useless to a caller that needs timestamps. whisper-1 is the default for that reason.

Pass WithBaseURL to transcribe against an OpenAI-compatible endpoint (a self-hosted Whisper server, Groq) instead of api.openai.com.

func NewTranscriber added in v0.41.0

func NewTranscriber(apiKey string, model string, opts ...ClientOption) (*Transcriber, error)

NewTranscriber constructs a transcriber. apiKey falls back to OPENAI_API_KEY. model defaults to whisper-1.

func (*Transcriber) Transcribe added in v0.41.0

func (t *Transcriber) Transcribe(ctx context.Context, clip audio.Clip, opts audio.Options) (audio.Transcript, error)

Transcribe converts one clip to text.

type VisionAnalyzer

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

VisionAnalyzer calls a vision-capable OpenAI model (default gpt-4o) and returns a natural-language answer about the supplied image.

It satisfies pkg/tools/builtin.MediaAnalyzer by structural compatibility — no import of that package is needed.

media may be:

  • an https:// URL publicly reachable by the OpenAI API
  • a data URI ("data:image/png;base64,...") for locally hosted images

func NewVisionAnalyzer

func NewVisionAnalyzer(apiKey, model string, opts ...ClientOption) (*VisionAnalyzer, error)

NewVisionAnalyzer builds an analyzer. apiKey defaults to OPENAI_API_KEY; model defaults to "gpt-4o" (smallest model with reliable vision support across all image tasks). Pass WithBaseURL to analyze against an OpenAI-compatible endpoint instead of api.openai.com.

func (*VisionAnalyzer) Analyze

func (a *VisionAnalyzer) Analyze(ctx context.Context, media, prompt string) (string, error)

Analyze sends media + prompt to the vision model and returns the response.

Jump to

Keyboard shortcuts

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