Use model providers
Wire OpenAI-compatible, Vercel AI Gateway, OpenCode Go, Codex, Claude, or Grok provider layers into an agent loop.
Provider layers implement LLMProvider. Your app chooses the provider, model id, credentials, HTTP layer, and policy.
Provider output-token limits are host-owned when the endpoint supports them. OpenAI-compatible chat, Vercel AI Gateway, OpenCode Go, Anthropic, and Grok require limits; ChatGPT Codex does not expose one. Yolk does not infer model limits or apply hidden fallbacks.
Install
pnpm add @yolk-sdk/agent@canary effect@4.2.0OpenAI-compatible chat
Use this for OpenAI Chat Completions or compatible gateways.
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiProviderLayer } from '@yolk-sdk/agent/providers/openai/provider'
const OpenAiLayer = makeOpenAiProviderLayer({
apiKey: Redacted.make(hostOpenAiApiKey),
maxCompletionTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))Use chatCompletionsUrl for generic OpenAI-compatible endpoints. Run-level reasoningEffort goes
to the native endpoint as reasoning_effort. A compatible endpoint needs reasoningEffortFormat
('reasoning-effort' or 'reasoning-object'); without it, a request with an effort fails with a
validation_error rather than being sent without it. reasoningEffortFormat: 'omit' never sends
the effort and never fails: use it for a model without reasoning (which rejects the field) when the
host shares one effort setting across models.
Vercel AI Gateway
Use this for Vercel's OpenAI-compatible Gateway endpoint and provider/model routing.
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeVercelAiGatewayProviderLayer } from '@yolk-sdk/agent/providers/vercel/ai-gateway-provider'
const GatewayLayer = makeVercelAiGatewayProviderLayer({
apiKey: Redacted.make(hostGatewayApiKeyOrOidcToken),
maxCompletionTokens: hostModelConfig.maxOutputTokens,
fallbackModels: hostFallbackModelIds,
routing: { only: hostAllowedGatewayProviders }
}).pipe(Layer.provide(FetchHttpClient.layer))The factory defaults to one JSON completion. Add streaming: true for SSE deltas and, independently,
reasoningContent: true to retain compatible models' reasoning output and assistant replay. Both
options default to false; replayed reasoning spends input tokens. These are explicit factory options,
not env-backed switches.
The factory sends maxCompletionTokens as Gateway max_tokens. Run-level reasoningEffort is
forwarded as { reasoning: { effort } } by default; reasoningEffortFormat: 'reasoning-effort' sends the literal field instead (e.g. for DeepSeek-style hosts, with an optional thinking: { type: 'enabled' | 'disabled' } toggle merged into the request body), and 'omit' never sends the effort and never fails, for a model without reasoning behind a shared effort setting. The host must restrict its
choices to efforts supported by the selected model. The env-backed VercelAiGatewayProviderLayer
reads AI_GATEWAY_API_KEY, falls back to
VERCEL_OIDC_TOKEN, and requires AI_GATEWAY_MAX_COMPLETION_TOKENS. The factory also accepts
extraHeaders for optional http-referer and x-title attribution. Required authorization and JSON
headers cannot be overridden. A custom chatCompletionsUrl must be a trusted proxy because it
receives the Bearer credential.
OpenCode Go
Server-side configuration fragment; the host supplies the API key and model policy:
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenCodeGoProviderLayer } from '@yolk-sdk/agent/providers/opencode/go-provider'
const GoLayer = makeOpenCodeGoProviderLayer({
apiKey: Redacted.make(hostOpenCodeGoApiKey),
protocol: 'messages',
maxOutputTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))Choose chat-completions, messages, or responses to match the selected Go model's
advertised endpoint. Supply the unprefixed API model ID in
the loop request. The factory validates a nonempty key and positive safe-integer limit when the
layer builds. It does not read environment variables or perform OAuth. Hosts using environment
configuration should load the key with Config.Redacted inside Effect.gen.
maxOutputTokens becomes max_tokens for Chat Completions/Messages or max_output_tokens for
Responses. Request reasoningEffort becomes reasoning_effort for chat, output_config.effort for
Messages (omitting minimal, rejecting none), or Responses reasoning.effort. Responses also sends
summary: 'auto' when effort is present; configure reasoningSummary to select another summary mode.
Only offer efforts supported by your model. Chat emits and replays provider reasoning_content (and host-normalized reasoning).
Optional extraHeaders cannot replace required protocol headers, even with different casing.
Override baseUrl only with a trusted proxy: it receives the API key. Messages and Responses require
explicit stream completion; truncated responses do not count as success. Chat defaults to one JSON
response before emitting events; set streaming: true on OpenAiProviderConfig to request
incremental chat.completion.chunk SSE deltas with usage instead. Unterminated chat streams fail
invalid_response without Done. OpenCode Go chat always streams. Only enable streaming against
endpoints that serve chat SSE. This adapter adds no model picker, catalog fetching,
credential persistence, or automatic subscription-allowance polling.
Read allowance on your host's schedule (server-side fragment):
import { Effect, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { fetchOpenCodeGoSubscriptionUsage } from '@yolk-sdk/agent/providers/opencode/usage'
const usageEffect = fetchOpenCodeGoSubscriptionUsage(Redacted.make(hostOpenCodeGoApiKey), {
requestTimeoutMs: 10_000
}).pipe(Effect.provide(FetchHttpClient.layer))The best-effort snapshot has five-hour, seven-day, and monthly used-percentage windows when
available. The fetcher defaults to openCodeGoSubscriptionUsageUrl (override url only with a
trusted proxy or local emulator, since it receives the API key), rejects redirects, and returns shared
ProviderSubscriptionUsageError variants without raw HTTP bodies or credential-bearing traces.
Use provider reset timestamps and keep allowance failures separate from inference; do not derive
subscription usage from token totals.
OpenAI Codex
Use this for Codex OAuth/token-broker flows and the Responses API.
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiCodexProviderLayer } from '@yolk-sdk/agent/providers/openai/codex-provider'
const CodexLayer = makeOpenAiCodexProviderLayer({
token: hostOAuthAccessToken,
defaultReasoningEffort: 'low',
reasoningSummary: 'auto'
}).pipe(Layer.provide(FetchHttpClient.layer))The ChatGPT subscription endpoint rejects vendor max_output_tokens, so the adapter does not expose
an output-token limit. The optional deprecated maxOutputTokens field is ignored for compatibility.
OAuth helpers live in @yolk-sdk/agent/providers/openai and @yolk-sdk/agent/providers/openai/codex.
xAI Grok subscription
Use this for consumer Grok subscriptions through xAI's CLI Responses proxy.
Configuration fragment (the host supplies the token, model policy, and HTTP layer):
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeXAiGrokProviderLayer } from '@yolk-sdk/agent/providers/xai/grok-provider'
const GrokLayer = makeXAiGrokProviderLayer({
token: hostOAuthAccessToken,
maxOutputTokens: hostModelConfig.maxOutputTokens,
clientVersion: hostGrokCliClientVersion
}).pipe(Layer.provide(FetchHttpClient.layer))The required clientVersion is sent as x-grok-client-version; the CLI proxy rejects missing or
outdated client versions with HTTP 426.
OAuth and broker helpers live in @yolk-sdk/agent/providers/xai and
@yolk-sdk/agent/providers/xai/grok. The package exports browser-PKCE and device-flow constants, not
a complete device polling service. The host must implement the chosen authorization flow, serialize
refreshes, persist replacement refresh tokens, verify token provider/freshness, and select an
available subscription model. The adapter defaults to the xAI CLI proxy rather than the developer
API-key endpoint. Treat a custom responsesUrl as a trusted credential-bearing proxy. xAI controls
the public CLI OAuth client and private, unsupported proxy contract; both may change and should be
used only when permitted by xAI's terms. Best-effort allowance snapshots are available from
@yolk-sdk/agent/providers/xai/usage; the fetcher requires the authenticated xAI user_id and your
host integration's truthful version as explicit options.
Anthropic Claude Code
Use this for Claude OAuth/token-broker flows and Claude Code-compatible requests.
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeAnthropicClaudeProviderLayer } from '@yolk-sdk/agent/providers/anthropic/claude-provider'
const ClaudeLayer = makeAnthropicClaudeProviderLayer({
token: hostOAuthAccessToken,
maxTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))OAuth helpers live in @yolk-sdk/agent/providers/anthropic and @yolk-sdk/agent/providers/anthropic/claude.
Add thinking: { display: 'summarized' } to stream thinking summaries from models that think by
default (Opus 5 and later). Signed thinking is replayed unchanged either way; see
Thinking.
Anthropic prompt-too-long responses are non-retryable context_overflow failures. If your host owns
durable compaction, wrap the provider with makeContextOverflowRetryProvider to compact and retry
once. See Implement durable compaction.
Claude responses that stop at max_tokens fail as non-retryable invalid_response; they do not emit
normal completion. Increase maxTokens, request a shorter response, or adjust host output policy.
The transport identifies as a pinned Claude Code release (anthropicClaudeCodeVersion). Anthropic
rejects newer models for outdated versions; see
claude_code_version_too_old.
Provide the layer
Merge the provider with your loop/tool layers:
import { Layer } from 'effect'
import { ContextTransformer, LoopConfig } from '@yolk-sdk/agent/loop'
import { makeToolExecutorLayer } from '@yolk-sdk/agent/tools'
const AppAgentLayer = Layer.mergeAll(
OpenAiLayer,
makeToolExecutorLayer(toolSet),
LoopConfig.defaultLayer,
ContextTransformer.identity
)Then provide AppAgentLayer to run or runRuntime.
Capability notes
| Provider | Media notes |
|---|---|
| OpenAI-compatible | text, image URLs/data URLs, inline text documents; PDF parts opt in with supportsPdfAttachments |
| Vercel AI Gateway | OpenAI-compatible text, tools, image URLs/data URLs, text documents, native PDF file parts by default |
| OpenCode Go | Protocol/model-dependent: chat images and text documents; Messages images/PDFs; Responses images/documents |
| OpenAI Codex | text, reasoning, tools, image URLs/data URLs, document data/files |
| Anthropic Claude Code | text, reasoning, tools, images, PDF URL/base64, inline text documents |
| xAI Grok subscription | text, reasoning, tools; can encode model-dependent image URL/data input |
Bound PDF attachment fetches
Generic OpenAI-compatible chat supports native PDF user-message and tool-result parts only when
supportsPdfAttachments: true; Vercel AI Gateway enables the same behavior by default and accepts
supportsPdfAttachments: false to disable it. Tool-result images and documents are lowered to
origin-labeled, untrusted supplementary user content after the complete tool-result block, without
changing canonical history. Assistant media remains unsupported on this Chat Completions path.
For a URL-backed PDF, Yolk uses the host-provided HttpClient to perform the GET and buffer the
response before sending base64 file data to the provider. Gateway does not fetch the source URL.
Authorize attachment URLs and enforce destination and redirect policy, streamed-byte limits,
timeouts, cancellation, and safe logging in that HTTP boundary. Do not let a shared client attach
provider credentials, cookies, or ambient auth to attachment destinations. The SDK's resolver does
not provide those guarantees; materialize authorized files as validated inline bytes when the host
cannot supply a bounded transport. Resolve Ref sources before the provider attempt and choose a
model whose advertised capabilities include PDFs. See
Resolve private attachments and
Media input rejected.
Codex preserves text, image, and document tool results as native function output content. Claude preserves text, images, inline text documents, and URL/base64 PDFs as nested tool-result content. Resolve host-owned attachment refs before provider execution; rich tool results do not support audio.
Set model capabilities in your request config so unsupported inputs fail before provider execution.
Host responsibilities
- Store and refresh API keys/OAuth tokens.
- Choose provider/model per run.
- Provide
HttpClientand provider layer at the server boundary. - Keep raw provider errors and secrets out of protocol events.
- Persist typed usage and safe
ProviderErrorInfoif your app needs accounting.