Skip to content
AgentsKit

@agentskit/adapters — Functions

API functions for @agentskit/adapters.

#Function: anthropic()

anthropic(config): AdapterFactory

Defined in: adapters/src/anthropic.ts:14

#Parameters

#config

AnthropicConfig

#Returns

AdapterFactory


#Function: applyCarbonTable()

applyCarbonTable(candidates, options?): RouterCandidate[]

Defined in: adapters/src/carbon.ts:99

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: adapters/src/azure-openai.ts:20

#Parameters

#config

AzureOpenAIConfig

#Returns

AdapterFactory


#Function: bail()

bail(config): AdapterFactory

Defined in: adapters/src/bail.ts:19

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: adapters/src/bedrock.ts:190

#Parameters

#config

BedrockConfig

#Returns

AdapterFactory


#Function: cerebras()

cerebras(config): AdapterFactory

Defined in: adapters/src/cerebras.ts:17

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: adapters/src/utils.ts:470

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: cohere()

cohere(config): AdapterFactory

Defined in: adapters/src/cohere.ts:23

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: adapters/src/createAdapter.ts:5

#Parameters

#config

CreateAdapterConfig

#Returns

AdapterFactory


#Function: createEnsembleAdapter()

createEnsembleAdapter(options): AdapterFactory

Defined in: adapters/src/ensemble.ts:99

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: adapters/src/fallback.ts:30

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: createOpenAICompatibleEmbedder()

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

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

#Parameters

#provider

string

#defaultBaseUrl

string

#Returns

(config) => EmbedFn


#Function: createRotatingCredentials()

createRotatingCredentials(initial, options): RotatingCredentials

Defined in: adapters/src/credential-rotation.ts:49

#Parameters

#initial

string

#options

#id

string

#Returns

RotatingCredentials


#Function: createRouter()

createRouter(options): AdapterFactory

Defined in: adapters/src/router.ts:127

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: adapters/src/carbon.ts:119

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: adapters/src/utils.ts:413

Run a fetch with retries on transient failures. Returns the final Response (whether successful or not — caller decides), or throws if the AbortSignal fires or all attempts fail with a thrown error.

#Parameters

#doFetch

(signal) => Promise<Response>

#signal

AbortSignal

#retryOpt?

RetryOptions = \{\}

#Returns

Promise<Response>


#Function: gemini()

gemini(config): AdapterFactory

Defined in: adapters/src/gemini.ts:13

#Parameters

#config

GeminiConfig

#Returns

AdapterFactory


#Function: geminiEmbedder()

geminiEmbedder(config): EmbedFn

Defined in: adapters/src/embedders/gemini.ts:39

#Parameters

#config

GeminiEmbedderConfig

#Returns

EmbedFn


#Function: generic()

generic(config): AdapterFactory

Defined in: adapters/src/generic.ts:5

#Parameters

#config

GenericAdapterConfig

#Returns

AdapterFactory


#Function: groq()

groq(config): AdapterFactory

Defined in: adapters/src/groq.ts:17

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: adapters/src/mock.ts:223

In-memory recording sink — useful for tests and ephemeral capture.

#Returns

RecordingSink & object


#Function: langchain()

langchain(config): AdapterFactory

Defined in: adapters/src/langchain.ts:27

#Parameters

#config

LangChainConfig

#Returns

AdapterFactory


#Function: langgraph()

langgraph(config): AdapterFactory

Defined in: adapters/src/langchain.ts:103

#Parameters

#config

LangGraphConfig

#Returns

AdapterFactory


#Function: mockAdapter()

mockAdapter(options): AdapterFactory

Defined in: adapters/src/mock.ts:62

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: adapters/src/ollama.ts:11

#Parameters

#config

OllamaConfig

#Returns

AdapterFactory


#Function: ollamaEmbedder()

ollamaEmbedder(config): EmbedFn

Defined in: adapters/src/embedders/ollama.ts:33

#Parameters

#config

OllamaEmbedderConfig

#Returns

EmbedFn


#Function: openai()

openai(config): AdapterFactory

Defined in: adapters/src/openai.ts:22

#Parameters

#config

OpenAIConfig

#Returns

AdapterFactory


#Function: openaiEmbedder()

openaiEmbedder(config): EmbedFn

Defined in: adapters/src/embedders/openai.ts:37

#Parameters

#config

OpenAIEmbedderConfig

#Returns

EmbedFn


#Function: recordingAdapter()

recordingAdapter(inner, sink): AdapterFactory

Defined in: adapters/src/mock.ts:171

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: adapters/src/credential-rotation.ts:84

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: adapters/src/mock.ts:237

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: adapters/src/replicate.ts:77

#Parameters

#config

ReplicateConfig

#Returns

AdapterFactory


#Function: resolveModel()

resolveModel(input, policy): ResolveModelResult

Defined in: adapters/src/deprecation.ts:73

#Parameters

#input

ResolveModelInput

#policy

DeprecationPolicy

#Returns

ResolveModelResult


#Function: simulateStream()

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

Defined in: adapters/src/utils.ts:497

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: adapters/src/vercel-ai.ts:108

#Parameters

#config

VercelAIConfig

#Returns

AdapterFactory


#Function: vertex()

vertex(config): AdapterFactory

Defined in: adapters/src/vertex.ts:25

#Parameters

#config

VertexConfig

#Returns

AdapterFactory


#Function: webllm()

webllm(config): AdapterFactory

Defined in: adapters/src/webllm.ts:62

#Parameters

#config

WebLlmConfig

#Returns

AdapterFactory


#Function: withDeprecationPolicy()

withDeprecationPolicy<F>(factory, options): F

Defined in: adapters/src/deprecation.ts:127

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

Explore nearby

On this page

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