Radondocs

API reference

Every method, option, and return type in @radonsdk/ai — the RadonAI class, ChatOptions, EmbedOptions, ChatResult, the StreamChunk union, and ChatStream.

The complete surface of @radonsdk/ai. For narrative guides start with Core concepts; this page is the exhaustive contract.

import { RadonAI, createAI } from "@radonsdk/ai";

Constructor

new RadonAI(config: RadonAIConfig)

Create a client. Registers the built-in adapters and prepares the license client if a key is present. Throws InvalidConfigError if providers is empty.

createAI(config: RadonAIConfig): RadonAI

Convenience factory. Equivalent to new RadonAI(config).

RadonAIConfig

providersPartial<Record<string, ProviderOptions>>required

Which providers to enable, keyed by slug (openai, anthropic, …). The value is that provider's options; leave it {} to rely on RADON_<SLUG>_* env vars.

defaultProviderstring

Provider used when a call names none. Defaults to the sole configured provider, or is required when several are configured.

licenseKeystring

Radon Pro license key. Required for any Pro provider or feature. Falls back to the RADON_LICENSE_KEY env var. Verified in init().

licenseLicenseConfig

Advanced license config: { key?, verifyUrl?, watermark?, fetch? }.

fetchtypeof fetch

Injectable fetch (proxies, instrumentation, tests). Defaults to global fetch.

now() => Date

Injectable clock (tests). Defaults to () => new Date().

ProviderOptions

apiKeystring

API key/token. Falls back to RADON_<SLUG>_API_KEY.

baseUrlstring

Override the provider's base URL (gateways, proxies, Azure, self-hosted).

defaultModelstring

Default chat model for this provider, overriding the adapter's built-in.

defaultEmbeddingModelstring

Default embedding model for this provider.

Provider options also accept arbitrary extra keys (e.g. OpenRouter's referer / title); unknown keys are ignored by adapters that don't use them.

Methods

ai.chat(options: ChatOptions): Promise<ChatResult>

Run one non-streaming completion. Enforces Pro-feature gates, resolves the provider (honoring fallback), and returns a normalized ChatResult. See Chat.

ai.stream(options: ChatOptions): ChatStream

Stream a completion. Returns a ChatStream (async-iterable). Gates are checked synchronously. fallback is not honored. See Streaming.

ai.embed(options: EmbedOptions): Promise<EmbedResult>Pro

Produce embeddings. Throws UnsupportedOperationError on providers without an embeddings endpoint. See Embeddings.

ai.init(): Promise<void>

Verify the Pro license (if a key is set or a Pro provider is configured), then eagerly load and initialize every configured provider so misconfiguration fails fast. Throws LicenseRequiredError / LicenseInvalidError. Free-only setups may skip it.

ai.provider(slug?: string): Promise<ModelProvider>

Lazy-load, construct, init(), and cache a configured provider by slug. Pro providers require a verified license. Throws ProviderNotConfiguredError for an unconfigured slug.

ai.native<T>(slug?: string): Promise<T>

The official provider SDK client, preconfigured with your credentials. Requires the optional peer dependency — throws NativeClientUnavailableError with an install hint otherwise. See the escape hatch.

ai.rawClient(slug?: string): Promise<HttpClient>

A preconfigured HttpClient (base URL + auth ready) for a provider. Zero-install escape hatch — always works.

Accessors

ai.defaultProviderstring

The provider used when a call names none. Throws InvalidConfigError if ambiguous or invalid.

ai.configuredProvidersstring[]

The configured provider slugs.

ai.isLicensedboolean

Whether a valid Pro license was confirmed in init().

ChatOptions

The one request shape for both chat() and stream().

messagesChatMessage[]required

The conversation so far. See ChatMessage.

modelstring

Model id. Falls back to the provider's defaultModel, then the adapter's built-in default.

toolsTool[]

Tools the model may call. Written once; translated per provider. See Tool.

toolChoice"auto" | "none" | "required" | { name: string }

How the model may use tools this turn.

temperaturenumber

Sampling temperature.

maxTokensnumber

Maximum tokens to generate. Anthropic requires it — Radon defaults to 4096.

topPnumber

Nucleus-sampling top-p.

stopstring | string[]

Stop sequence(s).

seednumber

Deterministic-sampling seed, where supported.

frequencyPenaltynumber

Penalize token frequency (OpenAI family).

presencePenaltynumber

Penalize token presence (OpenAI family).

responseFormatResponseFormatPro

Requested output shape. Any value other than "text" is a Pro feature. See ResponseFormat.

providerstring

Use this provider for this call instead of the default.

fallbackstring[]Pro

Ordered backup provider slugs to try if the primary fails. chat() only. Pro feature. See Fallback.

providerOptionsRecord<string, unknown>

Provider-specific request fields, shallow-merged into the body after Radon's own fields (so they can override them).

signalAbortSignal

Abort signal, forwarded to the underlying fetch.

Pro-feature gates

responseFormat other than "text" gates on structured output; any image content part gates on vision; a non-empty fallback gates on fallback. All three require a verified license.

ChatMessage

role"system" | "user" | "assistant" | "tool"required

Who authored the message.

contentstring | ContentPart[]required

Plain text, or an array of content parts for vision.

toolCallsToolCall[]

Present on an assistant turn that invoked tools.

toolCallIdstring

On a role: "tool" message: which call this is the result of.

namestring

The tool/function name for a role: "tool" message.

ContentPart

text{ type: 'text'; text: string }

A run of text.

image{ type: 'image'; source: ImageSource }

An image. ImageSource is { url: string } or { data: string; mimeType: string }.

Tool

namestringrequired

The tool's name.

descriptionstring

What the tool does — helps the model decide when to call it.

parametersJSONSchemarequired

A JSON Schema describing the arguments object.

ToolCall

idstring

Provider call id (synthesized where the provider supplies none).

namestring

The tool the model called.

argumentsRecord<string, unknown>

The parsed arguments object — never a JSON string.

ResponseFormat

One of:

text"text"default: "text"

Free-form text (the default; not a Pro feature).

json"json"

Ask for a valid JSON object (JSON mode).

json_schema{ type: 'json_schema'; schema: JSONSchema; name?: string; strict?: boolean }

Conform to a JSON Schema where the provider can enforce it. strict defaults to true; name defaults to "response".

ChatResult

idstring

The provider's completion id.

providerstring

The provider that produced the result.

modelstring

The model that produced it.

contentstring

Concatenated assistant text. Empty when the turn was only tool calls.

toolCallsToolCall[]

Tool calls made this turn ([] when none).

finishReason"stop" | "length" | "tool_calls" | "content_filter" | "error" | "other"

Why generation stopped, normalized.

usageUsage | undefined

{ promptTokens, completionTokens, totalTokens }. Fields are 0 when a provider doesn't report them.

rawunknown

The untouched provider response.

ChatStream

The value returned by ai.stream(). It is an AsyncIterable<StreamChunk> and is single-consumption. See Streaming.

for await (const chunk of stream)

Iterate normalized StreamChunks: text deltas, tool-call deltas, and a terminal finish chunk with the assembled result. Throws if the stream was already consumed.

stream.textStream(): AsyncGenerator<string>

Yield only the text deltas — the common "print tokens as they arrive" case.

stream.final(): Promise<ChatResult>

Drain the stream (if not already) and return the fully-assembled ChatResult, with tool-call arguments reassembled and parsed. Safe to call after iterating.

StreamChunk

A discriminated union on type:

text{ type: 'text'; delta: string }

A chunk of assistant text to append.

tool_call{ type: 'tool_call'; index: number; id?: string; name?: string; argumentsDelta?: string }

A tool-call fragment. id/name arrive on the first fragment; argumentsDelta is a piece of the JSON arguments string to concatenate; index is the 0-based call position.

finish{ type: 'finish'; finishReason: FinishReason; usage?: Usage; message: ChatResult }

The terminal event. message is the complete ChatResult.

EmbedOptions

inputstring | string[]required

One string or a batch.

modelstring

Embedding model id. Falls back to the provider's default embedding model.

providerstring

Use this provider instead of the default.

dimensionsnumber

Requested output dimensionality, where the provider supports truncation.

providerOptionsRecord<string, unknown>

Escape hatch merged into the outgoing request body.

signalAbortSignal

Abort signal.

EmbedResult

embeddingsnumber[][]

One vector per input string, in input order.

providerstring

The provider that produced the embeddings.

modelstring

The embedding model used.

usageUsage | undefined

Token accounting, when reported.

rawunknown

The untouched provider response.

Tiers helpers

FREE_PROVIDERSReadonlySet<string>

The free provider slugs: openai, anthropic, groq.

isProProvider(slug: string) => boolean

Whether a slug is Pro-gated (anything not in FREE_PROVIDERS).

PRO_FEATURESRecord<ProFeature, string>

Human-readable labels for the Pro features (embeddings, vision, structuredOutput, fallback).

Also exported

For bring-your-own adapters and advanced use: BaseProvider, OpenAICompatibleProvider, registerProvider, hasProvider, knownProviders, HttpClient, getFetch, safeText, parseSSE, the tool-normalization helpers (toOpenAITools, toAnthropicMessages, toGeminiContents, …), LicenseClient, and every typed error. All types (ChatMessage, Tool, ChatOptions, ChatResult, StreamChunk, EmbedOptions, ModelProvider, ProviderCapabilities, …) are exported.

Next steps

On this page