# provider/openaicompat

> Package openaicompat is the provider adapter for OpenAI-compatible Chat Completions APIs: OpenAI itself and the servers that speak its chat format, hosted or local, such as vLLM, Ollama and OpenRouter.

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

```go
import "github.com/barevoidco/zelk/core/provider/openaicompat"
```

Package openaicompat is the provider adapter for OpenAI-compatible Chat Completions APIs: OpenAI itself and the servers that speak its chat format, hosted or local, such as vLLM, Ollama and OpenRouter.

It translates wire formats only and never changes behaviour, so one harness serves every model. It is a thin client written over net/http, reads nothing from the process environment, and uses only the \*http.Client it is given, or one that ignores proxy settings. Open tool schemas retain their server contract with non-strict rendering; canonical tools retain the adapter's existing schema dialect.

**Example**

```go
// A stand-in for a server such as Ollama or vLLM.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello.\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
}))
defer srv.Close()

c, err := openaicompat.New(srv.URL + "/v1")
if err != nil {
	panic(err)
}
stream, err := c.Stream(context.Background(), &provider.Request{
	Model:           "llama3",
	MaxOutputTokens: 1000,
	History:         []history.Item{{Role: history.RoleUser, Status: history.StatusCompleted, Parts: []history.Part{{Kind: history.KindText, Text: "Hi"}}}},
})
if err != nil {
	panic(err)
}
for ev, err := range stream {
	if err != nil {
		panic(err)
	}
	if ev.Kind == provider.EventDone {
		fmt.Println(ev.Response.StopReason, ev.Response.Items[0].Parts[0].Text)
	}
}
// Output: end_turn Hello.
```

Output:

```text
end_turn Hello.
```


## Variables

```go
var ErrUnsupported = errors.New("not supported by Chat Completions")
```

ErrUnsupported is wrapped by the error for a request holding what Chat Completions can't express, such as an image in a tool result. The error is a \*provider.Error of kind provider.ErrorInvalidRequest: sending the request again won't help.


## Client

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

Client calls a Chat Completions API. It is safe for concurrent use.


### New

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

New returns a client for the API at baseURL, such as [https://api.openai.com/v1](https://api.openai.com/v1) or [http://localhost:11434/v1](http://localhost:11434/v1); requests go to its chat/completions endpoint. baseURL must be http or https with a host and no credentials, query or fragment, which would reach logs and errors with the endpoint; send a key with APIKey.


### Client.Capabilities

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

Capabilities reports the capabilities the client was configured with.


### Client.Close

```go
func (c *Client) Close() error
```

Close releases the idle connections of the transport the client made for itself. A client given its own HTTPClient leaves it alone: its owner closes it. The client may be used again after Close.


### Client.Family

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

Family returns history.FamilyOpenAICompat: the client speaks Chat Completions.


### Client.Models

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

Models returns the models declared with WithModels.


### Client.Reservation

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

Reservation bounds the exact body this client renders for req. Invalid requests conservatively reserve the window; Stream still returns their rendering error if the budget permits an attempt. This method performs no I/O.


### Client.Stream

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

Stream returns the stream of the call req asks for. The request is sent when the stream is first read, so a stream that is never read sends nothing and holds no connection; reading it to the end, or breaking out of it, closes the response. Stream itself fails only for a request that can't be sent; everything after that arrives in the stream. The stream can be read only once.


## Option

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

Option configures a Client.


### WithAPIKey

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

WithAPIKey sets the key sent as a bearer token. Without one, requests carry no Authorization header, as local servers expect.


### WithCache

```go
func WithCache(enabled bool) Option
```

WithCache enables or disables requests asking the server to cache each request's prefix, with a top-level cache\_control the server moves forward as the conversation grows. Servers that cache automatically (OpenAI) don't need it; models that cache only on request, such as Anthropic's behind OpenRouter, are billed at the uncached rate without it. It is disabled by default.


### WithCapabilities

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

WithCapabilities sets what WithCapabilities reports for every model. Compatible servers don't describe their models, so the host does.


### WithHTTPClient

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

WithHTTPClient sets the HTTP client requests go through. The default sends requests directly, ignoring proxy settings in the environment: zelk reads nothing from the environment it wasn't given.


### WithLegacyMaxTokens

```go
func WithLegacyMaxTokens() Option
```

WithLegacyMaxTokens sends the output limit as max\_tokens, for servers that don't accept max\_completion\_tokens.


### 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.


### 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 := openaicompat.New("https://example.test/v1",
	openaicompat.WithStreamIdleTimeout(2*time.Minute))
if err != nil {
	panic(err)
}
defer client.Close()
fmt.Println("client configured")
// Output: client configured
```

Output:

```text
client configured
```


### WithStrict

```go
func WithStrict() Option
```

WithStrict sends canonical tool schemas in OpenAI's strict form, in which every property is required and optional ones are nullable, and maps the model's arguments back to the canonical form. Use it only with servers that enforce strict schemas; many compatible servers ignore the flag, and their models then leave out optional properties, which the strict form treats as an error. Open schemas always send strict:false and preserve nullable values.
