Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/provider/openai"

Package openai implements the stateless OpenAI Responses provider port, retaining encrypted reasoning locally in zelk’s portable history envelope. Open tool schemas retain their server contract with non-strict rendering; canonical tools retain the adapter’s existing schema dialect.

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

Client calls OpenAI Responses. It is safe for concurrent use.

func New(baseURL string, opts ...Option) (*Client, error)

New creates a client for baseURL, normally https://api.openai.com/v1. It performs no I/O or process configuration discovery.

Example

c, err := openai.New("https://api.openai.com/v1", openai.WithAPIKey("host-supplied-key"))
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
fmt.Println(c.Family())
// Output: openai

Output:

openai
func (c *Client) Capabilities(ctx context.Context, model string) (provider.Caps, error)

Capabilities returns the injected capability snapshot without network I/O. Responses can compact natively (provider.Compactor), except on a ChatGPT plan (WithPlanUsage).

func (c *Client) Close() error

Close releases idle connections created by this client. Injected HTTP clients remain the caller’s responsibility; active requests keep their contexts.

func (c *Client) Compact(ctx context.Context, req *provider.Request) (provider.Compaction, error)

Compact asks the standalone compaction endpoint for a compacted window of what req would send (https://developers.openai.com/api/docs/guides/compaction). The endpoint is stateless. Its output is the canonical next window: every item is kept, unpruned and byte for byte, with role and raw payload, to send in place of req’s history to Responses only.

func (c *Client) Family() history.Family

Family identifies the Responses wire format, distinct from Chat Completions.

func (c *Client) Models(ctx context.Context) ([]provider.Model, error)

Models returns the models declared with WithModels, with native compaction as Capabilities reports it.

func (c *Client) Reservation(req *provider.Request, caps provider.Caps) event.Tokens

Reservation conservatively bounds the exact rendered request when the host records a byte bound; unknown tokenizers reserve the full context window. Plan usage reserves caps.MaxOutputTokens because no request cap is sent; zero means the output bound is unknown.

func (c *Client) SearchBackend(model string) (*Search, error)

SearchBackend returns a backend using model and this client’s credentials. The caller must keep the client open until all searches finish. The endpoint and model must support the web_search tool; no request is made here.

Example

c, err := openai.New("https://api.openai.com/v1", openai.WithAPIKey("host-supplied-key"))
if err != nil {
panic(err)
}
defer c.Close()
backend, err := c.SearchBackend("gpt-6-luna")
if err != nil {
panic(err)
}
// Inject backend with zelk.WithSearch; this example makes no requests.
fmt.Printf("%T\n", backend)
// Output: *openai.Search

Output:

*openai.Search
func (c *Client) Stream(ctx context.Context, req *provider.Request) (provider.Stream, error)

Stream returns a lazy, single-use stream. Iteration owns the response body; cancellation and early termination close it. Requests always use store:false.

type Option func(*Client)

Option configures a Client.

func WithAPIKey(key string) Option

WithAPIKey sets the bearer credential sent to the provider.

func WithCacheKey(key string) Option

WithCacheKey sets the prompt cache routing key every request sends, in place of the request’s own CacheKey. An empty key leaves each request’s.

func WithCapabilities(caps provider.Caps) Option

WithCapabilities supplies model limits and supported capabilities.

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient injects a caller-owned HTTP client, safe for concurrent use.

func WithModels(models ...provider.Model) Option

WithModels declares the models the client offers, each with its own capabilities, for Capabilities and WithModels to report. Capabilities remain those of any model not declared.

func WithPlanUsage() Option

WithPlanUsage shapes requests as ChatGPT plan usage through Sign in with ChatGPT accepts them (https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations): without max_output_tokens, so the model’s own output limit applies, and without native compaction, which plan tokens may not use. Pair it with a TokenSource of plan access tokens. Reservations use the recorded model output bound, not the requested limit; an unknown bound cannot support hard budgets.

func WithStreamIdleTimeout(d time.Duration) Option

WithStreamIdleTimeout sets the maximum interval without response bytes on a stream, including with an injected HTTP client. It must be positive and defaults to five minutes. Expiry closes the body and returns ErrorTransient.

Example

client, err := openai.New("https://example.test/v1",
openai.WithStreamIdleTimeout(2*time.Minute))
if err != nil {
panic(err)
}
defer client.Close()
fmt.Println("client configured")
// Output: client configured

Output:

client configured
func WithTokenSource(ts TokenSource) Option

WithTokenSource sets where each request’s bearer credential comes from, in place of WithAPIKey.

Example

c, err := openai.New("https://api.openai.com/v1", openai.WithTokenSource(staticToken("access-token")))
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
fmt.Println(c.Family())
// Output: openai

Output:

openai
func WithToolLoading(loads func(model string) bool) Option

WithToolLoading says which models load deferred tools natively, through client-executed tool search (docs/design/tools.md, deferred tools): OpenAI documents it for gpt-5.4 and later on the Responses API. A host sets it only for an endpoint known to accept it. A model declared with DeferredTools loads them regardless.

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

Search is a native Responses web search backend. It borrows its client’s transport and credentials, and is safe for concurrent use.

func (s *Search) Limit() event.Tokens

Limit bounds the entire native request, including server-supplied search context. Unknown model limits are zero and cannot support hard token budgets.

Example

c, err := openai.New("https://unused.test/v1", openai.WithCapabilities(provider.Caps{ContextWindow: 200000}))
if err != nil {
panic(err)
}
defer c.Close()
backend, err := c.SearchBackend("fast")
if err != nil {
panic(err)
}
limit := backend.Limit()
fmt.Println(limit.Input, limit.Output)
// Output: 200000 2048

Output:

200000 2048
func (s *Search) Search(ctx context.Context, q search.Query) (search.Response, error)

Search makes one bounded, stateless request with native web search enabled.

type TokenSource interface {
// Token returns the credential to send now. A *provider.Error keeps
// its classification, so a renewal that never reached the server can
// be retried; any other error is a credential failure.
Token(ctx context.Context) (string, error)
}

TokenSource supplies the bearer credential of each request, such as an OAuth access token that expires and is renewed. It must be safe for concurrent use.