Skip to content
AgentsKit

@agentskit/adapters β€” Functions

API functions for @agentskit/adapters.

#Function: anthropic()

anthropic(config): AdapterFactory

Defined in: packages/adapters/src/anthropic.ts:25

Creates an adapter for Anthropic Messages API.

#Parameters

#config

AnthropicConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = anthropic({ apiKey: '…', model: 'model-name' })

#Function: applyCarbonTable()

applyCarbonTable(candidates, options?): RouterCandidate[]

Defined in: packages/adapters/src/carbon.ts:105

Decorate a list of router candidates with gCO2PerKtok from a carbon table. Returns a new list β€” does not mutate the input.

const candidates = applyCarbonTable([
  { id: 'openai-eu',   adapter: openai({...}), region: 'swedencentral', cost: 0.6 },
  { id: 'anthropic-us', adapter: anthropic({...}), region: 'us-east-1',   cost: 0.5 },
])

const router = createRouter({ candidates, policy: 'green-cost' })

#Parameters

#candidates

RouterCandidate[]

#options?

ApplyCarbonOptions = \{\}

#Returns

RouterCandidate[]


#Function: azureOpenAI()

azureOpenAI(config): AdapterFactory

Defined in: packages/adapters/src/azure-openai.ts:31

Creates an adapter for Azure OpenAI chat completions.

#Parameters

#config

AzureOpenAIConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = azureOpenAI({ apiKey: '…', endpoint: 'https://example.openai.azure.com', deployment: 'chat' })

#Function: bail()

bail(config): AdapterFactory

Defined in: packages/adapters/src/bail.ts:22

Alibaba Bailian (Qwen) via the DashScope OpenAI-compatibility endpoint.

Supports the Qwen-2.5 / 3 chat series and Qwen-VL multimodal models. APAC users typically prefer this over OpenAI for latency + data residency.

Default model: qwen-max.

#Parameters

#config

Partial<BailConfig> & object

#Returns

AdapterFactory


#Function: bedrock()

bedrock(config): AdapterFactory

Defined in: packages/adapters/src/bedrock.ts:201

Creates an adapter for Amazon Bedrock Converse streaming.

#Parameters

#config

BedrockConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = bedrock({ model: 'anthropic.claude-3-5-sonnet-20241022-v2:0' })

#Function: cerebras()

cerebras(config): AdapterFactory

Defined in: packages/adapters/src/cerebras.ts:20

Cerebras β€” ultra-fast inference on wafer-scale chips. OpenAI-compatible endpoint serving Llama / Qwen models with very low first-token latency.

Default model: llama-3.3-70b.

#Parameters

#config

Partial<CerebrasConfig> & object

#Returns

AdapterFactory


#Function: chunkText()

chunkText(text, targetSize?): string[]

Defined in: packages/adapters/src/utils.ts:363

Chunk-splitter that turns one large string into N streamable text chunks. Useful when a provider returns the full response in one shot and you want to feed it to a UI that expects streaming.

Default splits by whitespace boundaries with a target chunk size of ~32 characters.

#Parameters

#text

string

#targetSize?

number = 32

#Returns

string[]


#Function: cloudflareAiGateway()

cloudflareAiGateway(config): AdapterFactory

Defined in: packages/adapters/src/cloudflare.ts:12

OpenAI-compatible AI Gateway endpoint; supports gateway-only authentication.

#Parameters

#config

CloudflareAiGatewayConfig

#Returns

AdapterFactory


#Function: cohere()

cohere(config): AdapterFactory

Defined in: packages/adapters/src/cohere.ts:26

Cohere Command models via Cohere's OpenAI-compatibility endpoint.

  • Streams tokens via SSE (OpenAI-compatible chunks).
  • Supports tool calls in the OpenAI tools shape.
  • Reports usage on the final stream chunk when the upstream model returns it (Cohere's compatibility layer mirrors OpenAI's stream_options: \{ include_usage: true \} semantics).
  • Inherits auto-retry from the shared OpenAI core (retry).

Default model: command-r-plus. Override via model.

#Parameters

#config

Partial<CohereConfig> & object

#Returns

AdapterFactory


#Function: createAdapter()

createAdapter(config): AdapterFactory

Defined in: packages/adapters/src/createAdapter.ts:10

Creates an adapter from send and stream parsing functions.

#Parameters

#config

CreateAdapterConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.


#Function: createEnsembleAdapter()

createEnsembleAdapter(options): AdapterFactory

Defined in: packages/adapters/src/ensemble.ts:111

Build an AdapterFactory that runs the same request against N candidates in parallel, then aggregates the results into a single text output. Unlike speculate (which picks a winner), ensemble combines β€” majority vote, concatenation, longest, or a custom fn.

The returned source emits a single \{ type: 'text' \} chunk with the aggregated output followed by \{ type: 'done' \}, so it plugs into any runtime that expects a regular streaming adapter.

#Parameters

#options

EnsembleOptions

#Returns

AdapterFactory


#Function: createFallbackAdapter()

createFallbackAdapter(candidates, options?): AdapterFactory

Defined in: packages/adapters/src/fallback.ts:36

Try adapters in order. If the first fails (throws while opening, or errors mid-stream before emitting any non-done chunk), fall through to the next. As soon as a candidate produces its first real chunk, that's the committed one β€” we don't retroactively retry mid-stream.

Errors that happen after committing are propagated; the caller sees a normal streaming failure, not a mysterious cross-candidate retry that could duplicate tool calls.

#Parameters

#candidates

FallbackCandidate[]

#options?

FallbackOptions = \{\}

#Returns

AdapterFactory


#Function: createModelProvider()

createModelProvider(config): AdapterFactory

Defined in: packages/adapters/src/provider.ts:30

Single port over OpenRouter, Anthropic, OpenAI and CLIProxyAPI.

#Parameters

#config

ModelProviderConfig

#Returns

AdapterFactory


#Function: createOpenAICompatibleEmbedder()

createOpenAICompatibleEmbedder(provider, defaultBaseUrl): (config) => EmbedFn

Defined in: packages/adapters/src/embedders/openai-compatible.ts:55

Creates an embedder for an OpenAI-compatible embeddings API.

#Parameters

#provider

string

Value passed to the function.

#defaultBaseUrl

string

Value passed to the function.

#Returns

The the function result result.

(config) => EmbedFn


#Function: createRotatingCredentials()

createRotatingCredentials(initial, options): RotatingCredentials

Defined in: packages/adapters/src/credential-rotation.ts:61

Creates a credential provider that refreshes expiring credentials.

#Parameters

#initial

string

Value passed to the function.

#options

Adapter configuration.

#id

string

#Returns

RotatingCredentials

The RotatingCredentials result.


#Function: createRouter()

createRouter(options): AdapterFactory

Defined in: packages/adapters/src/router.ts:136

Build an AdapterFactory that picks one of N candidates per request.

Resolution order:

  1. classify(request) returns a candidate id β†’ use it
  2. classify(request) returns tag(s) β†’ filter by tags, then policy
  3. Fall back to policy over all capability-matched candidates

#Parameters

#options

RouterOptions

#Returns

AdapterFactory


#Function: estimateCO2Grams()

estimateCO2Grams(gCO2PerKtok, tokens): number

Defined in: packages/adapters/src/carbon.ts:125

Estimated CO2 emitted by a single completion (grams). Multiply gCO2PerKtok by tokens / 1000. Provided as a convenience for dashboards / chargeback reports β€” runtimes typically derive this from token usage events.

#Parameters

#gCO2PerKtok

number | undefined

#tokens

number

#Returns

number


#Function: fetchWithRetry()

fetchWithRetry(doFetch, signal, retryOpt?): Promise<Response>

Defined in: packages/adapters/src/retry.ts:67

Run doFetch with retries; return the final response on status exhaustion and propagate the final transport error. Only the initial fetch retries; errors from onRetry or custom sleep stop the operation.

#Parameters

#doFetch

(signal) => Promise<Response>

Called once per attempt with the caller's abort signal.

#signal

AbortSignal

Caller-owned; abort rejects with AbortError.

#retryOpt?

RetryOptions = \{\}

Defaults to 3 attempts, 500/8000 ms, full jitter, and statuses 408/429/500/502/503/504.

#Returns

Promise<Response>

The successful or final response.

#Deprecated

Use retry from @agentskit/net; keep this wrapper through at least adapters 0.20.0 or 90 days after deprecation, whichever is later.

#Throws

The final transport error or AbortError.

#Throws

AK_CONFIG_INVALID for invalid maxAttempts.

#Example

`const response = await fetchWithRetry(signal => fetch(url, { signal }), controller.signal)`

#Function: gemini()

gemini(config): AdapterFactory

Defined in: packages/adapters/src/gemini.ts:24

Creates an adapter for Gemini streaming chat.

#Parameters

#config

GeminiConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = gemini({ apiKey: '…', model: 'model-name' })

#Function: geminiEmbedder()

geminiEmbedder(config): EmbedFn

Defined in: packages/adapters/src/embedders/gemini.ts:54

Creates an embedder for Gemini embeddings.

#Parameters

#config

GeminiEmbedderConfig

Adapter configuration.

#Returns

EmbedFn

The EmbedFn result.


#Function: generic()

generic(config): AdapterFactory

Defined in: packages/adapters/src/generic.ts:10

Creates an adapter from a generic request sender.

#Parameters

#config

GenericAdapterConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.


#Function: groq()

groq(config): AdapterFactory

Defined in: packages/adapters/src/groq.ts:20

Groq β€” OpenAI-compatible endpoint serving Llama / Mixtral on LPUs. Known for very low first-token latency.

Default model: openai/gpt-oss-120b.

#Parameters

#config

Partial<GroqConfig> & object

#Returns

AdapterFactory


#Function: inMemorySink()

inMemorySink(): RecordingSink & object

Defined in: packages/adapters/src/mock.ts:238

In-memory recording sink β€” useful for tests and ephemeral capture.

#Returns

RecordingSink & object


#Function: langchain()

langchain(config): AdapterFactory

Defined in: packages/adapters/src/langchain.ts:35

Wraps a LangChain chat model as an AgentsKit adapter.

#Parameters

#config

LangChainConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.


#Function: langgraph()

langgraph(config): AdapterFactory

Defined in: packages/adapters/src/langchain.ts:119

Wraps a LangGraph-compatible model as an AgentsKit adapter.

#Parameters

#config

LangGraphConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.


#Function: mockAdapter()

mockAdapter(options): AdapterFactory

Defined in: packages/adapters/src/mock.ts:68

A deterministic adapter for tests, demos, and dry-run experiments.

Conforms to ADR 0001 β€” Adapter contract:

  • createSource is pure (A1) β€” no work until stream() runs
  • Always emits a terminal chunk (A3)
  • abort() is safe (A6)
  • Does not mutate input messages (A7)

Examples:

// Static const adapter = mockAdapter({ response: [ { type: 'text', content: 'Hello!' }, { type: 'done' }, ], })

// Request-aware const adapter = mockAdapter({ response: req => { const last = req.messages[req.messages.length - 1]?.content ?? '' return [ { type: 'text', content: 'Echo: ' + last }, { type: 'done' }, ] }, })

// Sequenced β€” different output each call const adapter = mockAdapter({ response: [ [{ type: 'text', content: 'first' }, { type: 'done' }], [{ type: 'text', content: 'second' }, { type: 'done' }], ], })

#Parameters

#options

MockAdapterOptions

#Returns

AdapterFactory


#Function: ollama()

ollama(config): AdapterFactory

Defined in: packages/adapters/src/ollama.ts:24

Creates an adapter for Ollama chat.

#Parameters

#config

OllamaConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = ollama({ model: 'llama3.1' })

#Function: ollamaEmbedder()

ollamaEmbedder(config): EmbedFn

Defined in: packages/adapters/src/embedders/ollama.ts:48

Creates an embedder for the Ollama embeddings API.

#Parameters

#config

OllamaEmbedderConfig

Adapter configuration.

#Returns

EmbedFn

The EmbedFn result.


#Function: openai()

openai(config): AdapterFactory

Defined in: packages/adapters/src/openai.ts:36

Creates an adapter for OpenAI chat completions.

#Parameters

#config

OpenAIConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = openai({ apiKey: '…', model: 'model-name' })

#Function: openaiCompatible()

openaiCompatible(config): AdapterFactory

Defined in: packages/adapters/src/openai-compatible.ts:22

An OpenAI-compatible endpoint with explicit transport configuration.

#Parameters

#config

OpenAICompatibleTransportConfig

#Returns

AdapterFactory


#Function: openaiEmbedder()

openaiEmbedder(config): EmbedFn

Defined in: packages/adapters/src/embedders/openai.ts:52

Creates an embedder for the OpenAI embeddings API.

#Parameters

#config

OpenAIEmbedderConfig

Adapter configuration.

#Returns

EmbedFn

The EmbedFn result.


#Function: recordingAdapter()

recordingAdapter(inner, sink): AdapterFactory

Defined in: packages/adapters/src/mock.ts:186

Wrap a real adapter so every turn is captured to a sink. Use this in dev to build up a fixture, then replay with replayAdapter() in tests.

#Parameters

#inner

AdapterFactory

#sink

RecordingSink

#Returns

AdapterFactory


#Function: refreshCredentials()

refreshCredentials(adapter, next, options?): Promise<boolean>

Defined in: packages/adapters/src/credential-rotation.ts:96

Refresh credentials on any object that implements CredentialRefreshable. A no-op (with a debug log) if the adapter doesn't support rotation, so callers can run the rotation playbook across a heterogeneous set of adapters without branching.

Most stock adapters do not implement refreshCredentials β€” this remains an opt-in primitive unless an adapter documents support.

#Parameters

#adapter

unknown

#next

string

#options?

#id?

string

#logger?

(msg) => void

#Returns

Promise<boolean>


#Function: replayAdapter()

replayAdapter(fixture): AdapterFactory

Defined in: packages/adapters/src/mock.ts:252

Replay an adapter from a recorded fixture. Each turn maps 1:1 to a recorded entry by index β€” call N replays fixture[N % fixture.length].

#Parameters

#fixture

RecordingFixture

#Returns

AdapterFactory


#Function: replicate()

replicate(config): AdapterFactory

Defined in: packages/adapters/src/replicate.ts:66

Creates an adapter for Replicate streaming predictions.

#Parameters

#config

ReplicateConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = replicate({ apiKey: '…', model: 'model-name' })

#Function: resolveModel()

resolveModel(input, policy): ResolveModelResult

Defined in: packages/adapters/src/deprecation.ts:91

Resolves a model against the deprecation table and policy.

#Parameters

#input

ResolveModelInput

Input to resolve.

#policy

DeprecationPolicy

Policy used during resolution.

#Returns

ResolveModelResult

The resolved model and any deprecation information.


#Function: simulateStream()

simulateStream(doFetch, extractText, errorLabel, options?): StreamSource

Defined in: packages/adapters/src/utils.ts:390

Build a StreamSource from a non-streaming fetch. The adapter is auto-completing: it fetches once, then yields the text as a sequence of chunks so UIs see the same streaming shape they'd see from a native streaming provider.

Use this when you're wiring a provider that only has a non-streaming endpoint but you want consumers (useChat, the runtime) to get identical ergonomics.

#Parameters

#doFetch

(signal) => Promise<Response>

#extractText

(response) => Promise<string>

#errorLabel

string

#options?

#chunkSize?

number

#delayMs?

number

#retry?

RetryOptions

#Returns

StreamSource


#Function: vercelAI()

vercelAI(config): AdapterFactory

Defined in: packages/adapters/src/vercel-ai.ts:119

Creates an adapter for the Vercel AI SDK.

#Parameters

#config

VercelAIConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = vercelAI({ api: 'https://example.com/chat' })

#Function: vertex()

vertex(config): AdapterFactory

Defined in: packages/adapters/src/vertex.ts:36

Creates an adapter for Vertex AI Gemini streaming.

#Parameters

#config

VertexConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = vertex({ project: 'my-project', region: 'us-central1', model: 'gemini-2.5-pro' })

#Function: webllm()

webllm(config): AdapterFactory

Defined in: packages/adapters/src/webllm.ts:73

Creates an adapter for WebLLM chat generation.

#Parameters

#config

WebLlmConfig

Adapter configuration.

#Returns

AdapterFactory

An AgentsKit adapter factory.

#Example

const adapter = webllm({ model: 'Llama-3.1-8B-Instruct-q4f16_1-MLC' })

#Function: withDeprecationPolicy()

withDeprecationPolicy<F>(factory, options): F

Defined in: packages/adapters/src/deprecation.ts:145

Wrap an AdapterFactory so that any model field on its requests is checked against the deprecation policy at startup. Convenience for adapters that don't want to plumb the check into their own code:

const adapter = withDeprecationPolicy(openai({ apiKey, model: 'gpt-3.5-turbo-0301' }), {
  provider: 'openai',
  onDeprecation: 'remap',
})

For adapters with internal model state (most), prefer calling resolveModel() inside the factory and substituting before the first request β€” this wrapper is a fallback for opaque adapters.

#Type Parameters

#F

F extends AdapterFactory

#Parameters

#factory

F

#options

object & DeprecationPolicy

#Returns

F


#Function: workersAi()

workersAi(config): AdapterFactory

Defined in: packages/adapters/src/cloudflare.ts:29

Workers AI's OpenAI-compatible REST endpoint.

#Parameters

#config

WorkersAiConfig

#Returns

AdapterFactory

Explore nearby

On this page

Function: anthropic()ParametersconfigReturnsExampleFunction: applyCarbonTable()Parameterscandidatesoptions?ReturnsFunction: azureOpenAI()ParametersconfigReturnsExampleFunction: bail()ParametersconfigReturnsFunction: bedrock()ParametersconfigReturnsExampleFunction: cerebras()ParametersconfigReturnsFunction: chunkText()ParameterstexttargetSize?ReturnsFunction: cloudflareAiGateway()ParametersconfigReturnsFunction: cohere()ParametersconfigReturnsFunction: createAdapter()ParametersconfigReturnsFunction: createEnsembleAdapter()ParametersoptionsReturnsFunction: createFallbackAdapter()Parameterscandidatesoptions?ReturnsFunction: createModelProvider()ParametersconfigReturnsFunction: createOpenAICompatibleEmbedder()ParametersproviderdefaultBaseUrlReturnsFunction: createRotatingCredentials()ParametersinitialoptionsidReturnsFunction: createRouter()ParametersoptionsReturnsFunction: estimateCO2Grams()ParametersgCO2PerKtoktokensReturnsFunction: fetchWithRetry()ParametersdoFetchsignalretryOpt?ReturnsDeprecatedThrowsThrowsExampleFunction: gemini()ParametersconfigReturnsExampleFunction: geminiEmbedder()ParametersconfigReturnsFunction: generic()ParametersconfigReturnsFunction: groq()ParametersconfigReturnsFunction: inMemorySink()ReturnsFunction: langchain()ParametersconfigReturnsFunction: langgraph()ParametersconfigReturnsFunction: mockAdapter()ParametersoptionsReturnsFunction: ollama()ParametersconfigReturnsExampleFunction: ollamaEmbedder()ParametersconfigReturnsFunction: openai()ParametersconfigReturnsExampleFunction: openaiCompatible()ParametersconfigReturnsFunction: openaiEmbedder()ParametersconfigReturnsFunction: recordingAdapter()ParametersinnersinkReturnsFunction: refreshCredentials()Parametersadapternextoptions?id?logger?ReturnsFunction: replayAdapter()ParametersfixtureReturnsFunction: replicate()ParametersconfigReturnsExampleFunction: resolveModel()ParametersinputpolicyReturnsFunction: simulateStream()ParametersdoFetchextractTexterrorLabeloptions?chunkSize?delayMs?retry?ReturnsFunction: vercelAI()ParametersconfigReturnsExampleFunction: vertex()ParametersconfigReturnsExampleFunction: webllm()ParametersconfigReturnsExampleFunction: withDeprecationPolicy()Type ParametersFParametersfactoryoptionsReturnsFunction: workersAi()ParametersconfigReturns