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.
📚 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 / Function | File | Purpose |
|---|---|---|
modelsSetCommand() | models/set.ts | Set default model with validation and auth check |
modelsAliasesAddCommand() | models/aliases.ts | Create model alias mapping |
modelsAliasesListCommand() | models/aliases.ts | List all configured aliases with targets |
modelsAuthLoginCommand() | models/auth.ts | Interactive provider authentication setup |
modelsAuthOrderSetCommand() | models/auth-order.ts | Set provider auth priority ordering |
modelsFallbacksAddCommand() | models/fallbacks.ts | Configure fallback model chain |
applyAuthChoice() | auth-choice.apply.ts | Multi-strategy auth dispatch (first match wins) |
setupSearch() | onboard-search.ts | Search provider configuration wizard |
normalizeAlias() | models/aliases.ts | Validate and normalize alias strings |
Data Structures
| Type | Name | Description |
|---|---|---|
| interface | ApplyAuthChoiceParams | Auth dispatch params: authChoice, config, prompter, runtime, setDefaultModel, agentDir, opts |
| interface | ApplyAuthChoiceResult | Auth result: updated config, optional agentModelOverride |
| interface | ModelStatusItem | Model probe result: id, displayName, provider, available, pricing, fallback flag |
| type | AuthChoice | Selected auth strategy and credentials |
| interface | SearchProvider | Search provider option with name, key, and config |
| interface | SetupSearchOptions | Options for search setup: provider, key, nonInteractive |
Interactions
| Direction | Partner | Interface | Description |
|---|---|---|---|
| → | 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/ | agentModelOverride | Per-agent model override from auth result |
Configuration
| Knob / Parameter | Default | Description |
|---|---|---|
--model <id> | current default | Model identifier to set as default |
--set <id> | — | Alias for --model in set command |
--provider <name> | auto-detect | Auth provider name for login command |
--fallback | none | Secondary model ID if primary unavailable |
--order | default | Auth provider priority ordering (comma-separated) |
--json | false | Output 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.
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.
Search Setup Focus
Search provider configuration wizard. Covers provider option resolution, API key validation, config application, and integration with the onboarding flow.
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;
};