Skip to main content

@flow-state-dev/core/models

Interfaces​

FallbackModelEntry​

Properties​

model​
model: GeneratorModel;
modelId​
modelId: string;
providerName​
providerName: string;

The provider the entry's call reaches (openai for openai/gpt-6.1-sol, anthropic for vercel:anthropic/…). Keys per-provider defaults.


GatewayConfig​

Properties​

apiKey?​
apiKey?: string;
type​
type: "vercel" | "openrouter";

ModelGroupDefaults​

Internal merge type used by createFallbackModel to apply per-provider defaults under call-site options. Not part of the public API — the public surface for per-intent defaults is IntentDefaults.

providerOptions is filtered by the resolved candidate's provider name before merging, so keys for other providers are dropped silently.

Properties​

maxTokens?​
maxTokens?: number;
providerOptions?​
providerOptions?: Record<string, Record<string, unknown>>;

Per-provider options (only applied when the resolved model matches the provider).


ModelRetryPolicy​

How the model resolver retries one model before falling back to the next. Not a block's RetryPolicy.

Properties​

baseDelayMs?​
baseDelayMs?: number;

Base delay between retries in ms. Default: 1000.

maxAttemptsPerModel?​
maxAttemptsPerModel?: number;

Max attempts per model before falling back. Default: 2.

maxDelayMs?​
maxDelayMs?: number;

Max delay between retries in ms. Default: 10000.


ProviderAvailability​

Properties​

apiKey?​
apiKey?: string;
gatewayName?​
gatewayName?: string;
gatewayType?​
gatewayType?: string;
provider​
provider: string;
source​
source: "key" | "gateway";

Type Aliases​

GatewayEntry​

type GatewayEntry = GatewayConfig | unknown;

Gateway value: either a config object for auto-detection, or a pre-created gateway instance (e.g., createGateway({ apiKey })). Instances bypass dynamic package loading — essential for bundled environments like Next.js.


GatewayType​

type GatewayType = typeof gatewayTypes[number];

LLMToolCallPart​

type LLMToolCallPart = object;

One requested tool call, keyed by the model-facing alias.

Properties​

input​
input: unknown;

Parsed call arguments.

toolCallId​
toolCallId: string;
toolName​
toolName: string;

Model-facing tool alias (what the model's tool dictionary uses).


LLMToolResultOutput​

type LLMToolResultOutput =
| {
type: "text";
value: string;
}
| {
type: "json";
value: unknown;
}
| {
type: "error-text";
value: string;
}
| {
type: "content";
value: object[];
};

Model-facing payload of a tool result, mirroring the AI SDK's ToolResultOutput variants this framework produces:

  • text — plain string output (and history replay's stringified form)
  • json — structured output, verbatim
  • error-text — a failed call surfaced to the model as an error message
  • content — a mapModelOutput-mapped string in the SDK v7 content envelope (matches the adapter's toModelOutput bridge)

ParsedModelString​

type ParsedModelString =
| {
modelId: string;
provider: string;
type: "direct";
}
| {
alias: string;
modelId: string;
type: "alias";
}
| {
intentName: string;
type: "intent";
};

A model string split into a lane. Whether an alias is a gateway or a provider is the resolver's call.

Union Members​

Type Literal​
{
modelId: string;
provider: string;
type: "direct";
}
modelId​
modelId: string;

The part after the slash (gpt-6.1-sol).

provider​
provider: string;

Provider name (e.g., "openai").

type​
type: "direct";

Type Literal​
{
alias: string;
modelId: string;
type: "alias";
}
alias​
alias: string;

The route name before the first colon (e.g., "vercel", "triage").

modelId​
modelId: string;

Everything after the first colon, untouched (anthropic/claude-sonnet-5-5).

type​
type: "alias";

Type Literal​
{
intentName: string;
type: "intent";
}
intentName​
intentName: string;

Intent name (e.g., "utility").

type​
type: "intent";

ProviderName​

type ProviderName = typeof providerNames[number];

ResolveAiSdkLanguageModel​

type ResolveAiSdkLanguageModel = (modelId) => unknown;

Parameters​

modelId​

string

Returns​

unknown

Variables​

DEFAULT_CACHING_CONFIG​

const DEFAULT_CACHING_CONFIG: Required<CachingConfig>;

Defaults applied when the generator omits a field (or the whole config).

Functions​

applyCaching()​

function applyCaching(
request,
config,
languageModel
): void;

Applies cache markers to an AI SDK request in place based on the framework's caching config and the resolved language model's provider. Called by buildAiSdkRequest right before dispatch. Safe to call with any config (including undefined) and any model.

Parameters​

request​

Record<string, unknown>

config​

CachingConfig | undefined

languageModel​

unknown

Returns​

void


buildAssistantToolCallMessage()​

function buildAssistantToolCallMessage(calls, text?): LLMMessage;

Builds ONE assistant message for a model step from its full tool-call array plus the step's optional text. A step with multiple parallel tool calls produced a single assistant turn containing all of them — splitting it into per-call messages changes the conversation shape provider APIs validate against. Empty text is omitted (matching the AI SDK, which skips empty text parts).

Parameters​

calls​

LLMToolCallPart[]

text?​

string

Returns​

LLMMessage


buildToolResultMessage()​

function buildToolResultMessage(call, output): LLMMessage;

Builds the tool role message carrying one settled call's result. One message per call, appended in call order after the step's assistant message.

Parameters​

call​
toolCallId​

string

toolName​

string

output​

LLMToolResultOutput

Returns​

LLMMessage


createAiSdkModelResolver()​

function createAiSdkModelResolver(resolveLanguageModel): ModelResolver;

Creates a framework ModelResolver backed by Vercel AI SDK generateText and streamText. Accepts a provider function that maps model ID strings to AI SDK language model instances (e.g. the openai export from @ai-sdk/openai).

When the resolver is a provider object with .tools (e.g., the openai or anthropic export), provider-native search tools are automatically available via generator's search config field.

Both generate and stream paths use a shared request builder, so tools, maxSteps, outputSchema, etc. are compiled identically regardless of whether the caller requests full or streamed output.

Parameters​

resolveLanguageModel​

ResolveAiSdkLanguageModel

Returns​

ModelResolver


createFallbackModel()​

function createFallbackModel(config): GeneratorModel;

Creates a GeneratorModel that tries models in order with retry-per-model. On retryable errors, retries the current model up to maxAttemptsPerModel, then falls back to the next model in the list.

Exposes the single-step generateStep/streamStep — but only over the subset of candidates that implement them — so a generator using a fallback model group can drive the framework-owned per-step loop (and the in-loop suspension built on it). Each step call runs the same per-candidate retry / default-merge / onResolved fallback wrapping generate/stream already use. When no candidate implements the step methods, they are absent and the generator falls back to the SDK-owned generate({ maxSteps }) path (checked via model.generateStep === undefined).

NOTE (deliberate v1 limitation): this instance is CACHED and shared across concurrent requests (see createModelResolver's intentCache), so it holds no cross-call "pinned candidate" state — each step call independently selects a candidate. A candidate that transient-fails mid-loop can therefore hand its successor another provider's accumulated turn history (including provider-specific reasoning-signature blocks). True per-loop candidate pinning needs loop-scoped state that the shared instance cannot safely carry; see the report. In practice a candidate that succeeded on step 0 typically continues to win.

Parameters​

config​

FallbackModelConfig

Returns​

GeneratorModel


describeModelRoute()​

function describeModelRoute(modelString, env?):
| {
available: true;
via: string;
}
| {
available: false;
reason: string;
};

Where a model string would go with no resolver configuration, from the keys in env: through a provider's own key, a gateway, or nowhere (and why). For a picker that shows the route beside each model. It reads env names only and returns no key. An intent, or a named route that isn't a known gateway, depends on the app's resolver config, so it reports that rather than a guess.

Parameters​

modelString​

string

env?​

Record<string, string | undefined>

Returns​

| { available: true; via: string; } | { available: false; reason: string; }


detectAvailableProviders()​

function detectAvailableProviders(config): Map<string, ProviderAvailability>;

Detect which providers are available based on:

  1. Explicit keys (highest priority)
  2. Environment variables for direct provider keys
  3. Gateway keys (Vercel AI Gateway, OpenRouter) — make all providers available

Accepts an optional env parameter for testing (defaults to process.env).

Parameters​

config​
env?​

Record<string, string | undefined>

gateways?​

Record<string, unknown>

keys?​

Partial<Record<string, string>>

Returns​

Map<string, ProviderAvailability>


extractProviderName()​

function extractProviderName(modelString): string;

Provider name with no app config. A named route uses the model id's first slash segment, else the name itself. "unknown" for an intent or a bad string. Use it only without a resolver: ModelResolver.providerOf classifies against the app's maps, and agrees with this on every string whose route does not depend on them.

Parameters​

modelString​

string

Returns​

string


failedToolResultText()​

function failedToolResultText(toolName, errorMessage): string;

The failed-tool result text shape used by history replay for a tool_output with status: "failed". Kept here so live and replay paths can't drift apart.

Parameters​

toolName​

string

errorMessage​

string

Returns​

string


hasPreferredProvider()​

function hasPreferredProvider<T>(items, prefer): boolean;

Returns true when any item in items has a providerName matching an entry in prefer. Used by strict-mode checks to decide whether the preference could be honored at all.

Type Parameters​

T​

T extends ProviderTagged

Parameters​

items​

readonly T[]

prefer​

ProviderPreference | null | undefined

Returns​

boolean


isModelSelection()​

function isModelSelection(v): v is { model: string | string[]; preferProvider?: ProviderPreference };

Type-guard for the structured ModelSelection object form. Returns true when v is { model, preferProvider? }.

Parameters​

v​

unknown

Returns​

v is { model: string | string[]; preferProvider?: ProviderPreference }


isRetryableError()​

function isRetryableError(error): boolean;

Parameters​

error​

unknown

Returns​

boolean


normalizePreference()​

function normalizePreference(prefer): string[] | null;

Normalize a ProviderPreference to a deduplicated array of provider names. Returns null when preference is absent or empty — callers should treat null as "no reorder".

Parameters​

prefer​

ProviderPreference | null | undefined

Returns​

string[] | null


parseModelString()​

function parseModelString(modelString): ParsedModelString;

Parse a model string into its lane: provider/model, intent/name, or name:model (first : before the first /, so openai/gpt-oss:free stays a slash id). Any other shape throws as an invalid format.

Parameters​

modelString​

string

Returns​

ParsedModelString


reorderByPreference()​

function reorderByPreference<T>(items, prefer): T[];

Stable reorder: bucket items by prefer[i] provider match, then the rest (in original order). Relative order within each bucket is preserved.

  • prefer absent / empty → returns items unchanged (by identity).
  • Unknown provider names in prefer silently produce empty buckets.
  • Duplicates in prefer are deduplicated (first occurrence wins).

Type Parameters​

T​

T extends ProviderTagged

Parameters​

items​

readonly T[]

prefer​

ProviderPreference | null | undefined

Returns​

T[]


toolResultOutputForModel()​

function toolResultOutputForModel(output, mappedText?): LLMToolResultOutput;

Computes the model-facing result payload for a successfully settled tool call, applying the same rules the AI SDK applies when it owns the loop:

  • a mapModelOutput-mapped string (when the tool declares a mapper) is wrapped in the v7 content envelope, exactly like the adapter's toModelOutput bridge;
  • otherwise a string output becomes a text payload and anything else a json payload (undefined normalized to null, matching the SDK).

Parameters​

output​

unknown

mappedText?​

string

Returns​

LLMToolResultOutput


wrapAiSdkModel()​

function wrapAiSdkModel(
languageModel,
modelId?,
identityHints?
): GeneratorModel;

Wraps an AI SDK language model instance into a framework GeneratorModel. Use this when you already have a resolved model (e.g. openai("gpt-6.1-sol")) and want to pass it directly as a generator's model config.

Identity hints (requested, gateway) thread through so that ModelIdentity surfaced on emitted items reflects what the caller asked for in addition to what the provider reported.

Parameters​

languageModel​

unknown

modelId?​

string

identityHints?​

WrapAiSdkModelIdentityHints

Returns​

GeneratorModel

References​

assertStrictCompatible​

Re-exports assertStrictCompatible


createModelResolver​

Re-exports createModelResolver


CreateModelResolverOptions​

Re-exports CreateModelResolverOptions


IntentDefaults​

Re-exports IntentDefaults


makeSchemaStrict​

Re-exports makeSchemaStrict


MakeSchemaStrictOptions​

Re-exports MakeSchemaStrictOptions


ModelRule​

Re-exports ModelRule


ModelSelection​

Re-exports ModelSelection


PreferProviderRule​

Re-exports PreferProviderRule


ProviderPreference​

Re-exports ProviderPreference


ResolveModelCallOptions​

Re-exports ResolveModelCallOptions


selectModel​

Re-exports selectModel


StrictViolation​

Re-exports StrictViolation


WhenRule​

Re-exports WhenRule