Commands/Provider Switching/ — Model & Provider Management

Model selection, authentication flows, and search provider configuration

The Provider Switching sub-module manages the complete lifecycle of LLM provider interactions. It handles model selection with availability probing, orchestrates multi-strategy authentication flows (API key, OAuth, plugin provider), configures fallback models, manages model aliases, and sets up search providers — all through both interactive wizards and non-interactive batch operations.

18
Model Files
15+
Auth Files
3
Auth Strategies
~3.5k
Lines

📚 What is this & why does it exist?

Provider Switching is how OpenClaw talks to different AI brains. Users can switch between models from OpenAI, Anthropic, and other providers on the fly. This sub-module handles all the complexity of setting up credentials, checking which models are available, falling back to alternatives when a primary model is down, and remembering user preferences through aliases.

💡 Real-world analogy

Imagine a travel agent (OpenClaw) who can book flights with multiple airlines (providers). When you say “I want to fly to Paris,” the agent checks which airlines have available seats (model probing), verifies your loyalty card is valid (auth flow), and if your preferred airline is sold out, automatically checks your backup airline (fallback). You can also set nicknames like “the fast one” for a specific flight number (aliases). The search provider setup is like adding a rental car company to your travel bundle.

Contents

Architecture

flowchart TD
  subgraph UserLayer["User Commands"]
    Set["models set
modelsSetCommand()"] List["models list
modelsListCommand()"] Alias["models aliases
modelsAliasesAddCommand()"] Auth["models auth
modelsAuthLoginCommand()"] Fallback["models fallbacks
modelsFallbacksAddCommand()"] end subgraph AuthLayer["Authentication"] Apply["applyAuthChoice()
auth-choice.apply.ts"] Plugin["Plugin Provider
auth-choice.apply.plugin-provider.ts"] OAuth["OAuth Flow
auth-choice.apply.oauth.ts"] APIKey["API Key
auth-choice.apply.api-providers.ts"] end subgraph ProbeLayer["Model Probing"] Probe["Model Probe
models/list.probe.ts"] Cache["Result Cache
TTL-based"] end subgraph SearchLayer["Search Setup"] Search["setupSearch()
onboard-search.ts"] SearchKey["applySearchKey()"] end Set --> Apply Auth --> Apply Apply --> Plugin Apply --> OAuth Apply --> APIKey List --> Probe Probe --> Cache

Key Classes

Class / FunctionFilePurpose
modelsSetCommand()models/set.tsSet default model with validation and auth check
modelsAliasesAddCommand()models/aliases.tsCreate model alias mapping
modelsAliasesListCommand()models/aliases.tsList all configured aliases with targets
modelsAuthLoginCommand()models/auth.tsInteractive provider authentication setup
modelsAuthOrderSetCommand()models/auth-order.tsSet provider auth priority ordering
modelsFallbacksAddCommand()models/fallbacks.tsConfigure fallback model chain
applyAuthChoice()auth-choice.apply.tsMulti-strategy auth dispatch (first match wins)
setupSearch()onboard-search.tsSearch provider configuration wizard
normalizeAlias()models/aliases.tsValidate and normalize alias strings

Data Structures

TypeNameDescription
interfaceApplyAuthChoiceParamsAuth dispatch params: authChoice, config, prompter, runtime, setDefaultModel, agentDir, opts
interfaceApplyAuthChoiceResultAuth result: updated config, optional agentModelOverride
interfaceModelStatusItemModel probe result: id, displayName, provider, available, pricing, fallback flag
typeAuthChoiceSelected auth strategy and credentials
interfaceSearchProviderSearch provider option with name, key, and config
interfaceSetupSearchOptionsOptions for search setup: provider, key, nonInteractive

Interactions

DirectionPartnerInterfaceDescription
→config/requireValidConfigFileSnapshot()Load config for model/alias/auth changes
→config/replaceConfigFile()Persist model selection and auth tokens
→plugin-sdk/authProviderSchemas()Plugin provider authentication schemas
→wizard/createClackPrompter()Interactive prompts for model and auth selection
→infra/providerUsage()Token/cost tracking for model usage stats
←agents/agentModelOverridePer-agent model override from auth result

Configuration

Knob / ParameterDefaultDescription
--model <id>current defaultModel identifier to set as default
--set <id>—Alias for --model in set command
--provider <name>auto-detectAuth provider name for login command
--fallbacknoneSecondary model ID if primary unavailable
--orderdefaultAuth provider priority ordering (comma-separated)
--jsonfalseOutput JSON for programmatic consumption

Directory Map

Source tree for Provider Switching
src/commands/
├── models/
│   ├── aliases.ts                  ← Alias CRUD (normalizeAlias, add, list, remove)
│   ├── auth.ts                     ← Provider auth login flow
│   ├── auth-order.ts               ← Auth provider priority
│   ├── fallbacks.ts                ← Model fallback configuration
│   ├── image-fallbacks.ts          ← Image model fallback chains
│   ├── list.ts                     ← Model listing
│   ├── list.probe.ts               ← Availability probing & pricing
│   ├── scan.ts                     ← Model scanning
│   ├── set.ts                      ← Default model selection
│   ├── shared.ts                   ← Shared model utilities
│   └── load-config.ts              ← Config loading helpers
├── auth-choice.ts                  ← Auth choice re-exports
├── auth-choice.apply.ts            ← Multi-strategy auth dispatch
├── auth-choice.apply.api-providers.ts ← API key authentication
├── auth-choice.apply.oauth.ts      ← OAuth flow handling
├── auth-choice.apply.plugin-provider.ts ← Plugin provider auth
├── auth-choice-prompt.ts           ← User auth prompting
├── auth-choice.preferred-provider.ts ← Provider preference
├── onboard-search.ts               ← Search provider setup
├── model-picker.ts                 ← Interactive model selection
├── model-default.ts                ← Default model resolution
└── model-allowlist.ts              ← Model access control

Deep-Dive Highlights

Core mechanisms from this sub-module have been extracted into dedicated focus pages for in-depth exploration.

Deep-Dive Pages

Model Picker Focus

Interactive model selection with availability probing, pricing display, and intelligent defaults. Covers the probe-cache-display pipeline and fallback suggestion logic.

Extracted topic page

Provider Auth Flow Focus

Multi-strategy authentication dispatch: plugin provider, OAuth, and API key handlers. First-match-wins chain pattern with per-provider credential management.

Extracted topic page

Search Setup Focus

Search provider configuration wizard. Covers provider option resolution, API key validation, config application, and integration with the onboarding flow.

Extracted topic page

Code Examples

Example: Auth Choice Application

export async function applyAuthChoice(
  params: ApplyAuthChoiceParams,
): Promise<ApplyAuthChoiceResult> {
  const handlers: Array<
    (p: ApplyAuthChoiceParams) => Promise<ApplyAuthChoiceResult | null>
  > = [
    applyAuthChoiceLoadedPluginProvider,
    applyAuthChoiceOAuth,
    applyAuthChoiceApiProviders,
  ];

  for (const handler of handlers) {
    const result = await handler(normalizedParams);
    if (result) return result;  // First match wins
  }

  return { config: normalizedParams.config };
}

Example: Model Status Probe

export type ModelStatusItem = {
  id: string;
  displayName: string;
  provider: string;
  available: boolean;
  pricing?: { input: number; output: number };
  fallback?: boolean;
};