@contextual-io/tanstack-ai-adapter
v0.1.1
Published
TanStack AI v1 text adapter for the Contextual AI Gateway
Readme
@contextual-io/tanstack-ai-adapter
A TanStack AI v1 text adapter for the Contextual AI Gateway. It runs chat() through Gateway Routes with the caller's Contextual authorization.
import { chat } from "@tanstack/ai"
import { contextualText, createGatewayClient } from "@contextual-io/tanstack-ai-adapter"
const gateway = createGatewayClient({
url: process.env.CONTEXTUAL_AI_GATEWAY_URL!,
tenantId: process.env.CONTEXTUAL_TENANT_ID!,
credentials: { kind: "bearer", token: process.env.CONTEXTUAL_ACCESS_TOKEN! },
})
const stream = chat({
adapter: contextualText("support-route", { client: gateway }),
threadId: "conversation-42",
messages: [{ role: "user", content: "Where is order 42?" }],
})contextualText(route, { client }) takes a stored Route ID or an inline { id, name, modelProviders } Route whose model providers name a model and a providerConnectionId. The Route selects upstream models and Connections, so provider credentials never pass through the adapter. TanStack's chat() owns the thread, the tool loop, and approvals. client is the client from createGatewayClient or any object with the same generate(request, { signal, wrapFetch }) method. The adapter passes it the request's JSON form, GatewayGenerateRequestJson, which is what the HTTP client sends, reads whatever it resolves to as JSON, and checks that it is a Gateway response.
createGatewayClient options:
url: the Gateway's origin. The client posts to/api/v1/generatethere.tenantId: sent as thex-org-idheader and passed to token providers.credentials: the caller's authorization, described below.objectApiUrl(optional): passed to token providers; defaults tourl.fetch(optional): used instead of the globalfetch.
Credentials
Use the client on a server. Its credentials authorize Gateway calls as the caller, so tokens and client secrets must never reach browser code. Browsers should reach chat() through your server, for example with TanStack's chat transports.
credentials takes one of the Contextual SDK's credential forms:
{ kind: "bearer", token }sendsAuthorization: Bearer <token>on every request.{ kind: "provider", getBearerToken, invalidate? }callsgetBearerToken(signal, context)before every Gateway request and keeps no token itself, so caching and refresh belong to the provider, such as the SDK'sclientCredentials().signalis the request's abort signal, or one that never aborts when the request has none.contextis{ tenantId, objectApiUrl, serviceApiUrl }, with the client'surlasserviceApiUrl. IfgetBearerTokenthrows, the request fails before it is sent, with anabortederror when the request was aborted and otherwise acredentialserror, "Could not resolve the caller's Contextual credentials", whosecauseis the provider's error.{ kind: "apiKey", key, header }is accepted by the type so SDK credentials assign directly, but the Gateway accepts only bearer tokens. The request fails before it is sent with acredentialserror, "The Contextual AI Gateway accepts bearer tokens, not API key headers". Use a bearer token or a token provider instead.
When the Gateway answers 401 to a request whose token came from a provider, the adapter passes the rejected token and the same context to the provider's optional invalidate(token, context) and waits for it to finish, including a returned promise, before reporting the 401. The provider's next getBearerToken call can then acquire a fresh token. Aborting the request ends that wait early, so a request made before a slow invalidate finishes can still receive the rejected token. Other statuses do not call invalidate, and the adapter never resends a request. If invalidate throws or rejects before an abort ends the wait, the caller still gets the 401 GatewayError with that failure as its cause. When an abort ends the wait first, the 401 has no cause, and a later failure from invalidate is not reported.
Errors
Failures are GatewayErrors. gateway.generate() throws one with the code aborted, credentials, unreachable, invalid-response, or the Gateway's HTTP status as a string, such as "401". Before any request, the adapter raises unsupported for history, tool schemas, output schemas, or other request values the Gateway cannot take, such as a cycle or a NaN. It raises invalid-response when a client resolves to anything else, including a response with a tool call that lacks its ID, name, or object arguments. A GatewayError also carries status, retryAfterMs from a Retry-After header given in seconds, and effectMayHaveOccurred, which is true when the Gateway may already have done provider work. providerErrors lists failed route attempts with each provider's raw error text, which can echo request details, so keep it on the server. Error messages and the adapter's logs leave that text out.
In a chat() stream the adapter reports a GatewayError as a RUN_ERROR event with its message and code. With @tanstack/ai 1.0.0, retry timing is at event.metadata.tanstack.retryAfterMs. Its rawEvent holds the status, effectMayHaveOccurred, and the provider, model, and status code of each failed attempt. The event does not include the error's cause. Any other failure becomes a generic message with the code adapter-error.
Handle errors from the stream above:
for await (const event of stream) {
if (event.type === "RUN_ERROR") {
const retryAfterMs = event.metadata?.tanstack?.retryAfterMs
console.error(event.message, { code: event.code, retryAfterMs })
}
}Limitations
- The adapter calls the Gateway's HTTP generate endpoint, which returns a complete response, so each answer arrives as one text delta after generation finishes.
- Aborting ends the HTTP request, but provider work the Gateway already started may still finish, so a request aborted while it waits for the Gateway's response reports
effectMayHaveOccurred: true. - Multi-turn tool use and
toolChoiceneed Gateway support for tool results and tool choice. Without it, a request whose history includes a tool result fails, andtoolChoicehas no effect. The adapter sendstoolChoicein the Gateway's shape. - The Contextual SDK's
ctx.aitakes neither tool definitions nor, in a managed handler, an inline Route. With it as theclient, achat()that declares tools or uses an inline Route ends with anadapter-errorRUN_ERRORbefore any Gateway call. - History the Gateway cannot carry, such as audio or video parts, provider file handles, provider-executed tool calls, or redacted thinking, fails with an
unsupportederror before any request. - The Gateway reports unknown provider usage as zero tokens.
Requirements
- Node 22 or later; the package is ESM only, like
@tanstack/ai @tanstack/ai1.x (peer dependency)- Zod 4.2 or later for Zod tool and output schemas; the package itself depends on Zod 4.6.7
