# provider/openai

> Package openai implements the stateless OpenAI Responses provider port, retaining encrypted reasoning locally in zelk's portable history envelope.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/provider/openai (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
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.


## Client

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

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


### New

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

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

**Example**

```go
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:

```text
openai
```


### Client.Capabilities

```go
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).


### Client.Close

```go
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.


### Client.Compact

```go
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](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.


### Client.Family

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

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


### Client.Models

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

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


### Client.Reservation

```go
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.


### Client.SearchBackend

```go
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**

```go
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:

```text
*openai.Search
```


### Client.Stream

```go
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.


## Option

```go
type Option func(*Client)
```

Option configures a Client.


### WithAPIKey

```go
func WithAPIKey(key string) Option
```

WithAPIKey sets the bearer credential sent to the provider.


### WithCacheKey

```go
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.


### WithCapabilities

```go
func WithCapabilities(caps provider.Caps) Option
```

WithCapabilities supplies model limits and supported capabilities.


### WithHTTPClient

```go
func WithHTTPClient(hc *http.Client) Option
```

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


### WithModels

```go
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.


### WithPlanUsage

```go
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](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.


### WithStreamIdleTimeout

```go
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**

```go
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:

```text
client configured
```


### WithTokenSource

```go
func WithTokenSource(ts TokenSource) Option
```

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

**Example**

```go
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:

```text
openai
```


### WithToolLoading

```go
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.


## Search

```go
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.


### Search.Limit

```go
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**

```go
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:

```text
200000 2048
```


### Search.Search

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

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


## TokenSource

```go
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.
