> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch16-model-providers-and-failover/16.1-model-selection-mechanism.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 16.1 Model Selection Mechanism

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~400,000 tokens, Output \~32,000 tokens (Chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

OpenClaw supports dozens of LLM providers and hundreds of models. When a user sends a message, the system must decide: which provider? which model? What if this model is unavailable? This is the problem that the **model selection and failover** mechanism solves. OpenClaw implements a three-tier fault tolerance strategy—primary model, fallback models, and Auth Profile rotation within a provider.

## 16.1.1 Primary Model → Fallback Models → Provider-Internal Auth Failover: Three-Tier Strategy

OpenClaw's model fault tolerance is divided into three levels:

```
                ┌──────────────────┐
    Tier 3      │ Auth Profile      │  Same model, different credentials
                │ Rotation          │
                └────────┬─────────┘
                         │ All profiles fail
                ┌────────▼─────────┐
    Tier 2      │ Fallback Model    │  Different models
                │ List              │
                └────────┬─────────┘
                         │ All fallback models fail
                ┌────────▼─────────┐
    Tier 1      │ Final Error       │  Display error to user
                │ Report            │
                └──────────────────┘
```

**Tier 3 (Attempted First) — Auth Profile Rotation**: A single provider may be configured with multiple authentication credentials (for example, two Anthropic API Keys). When one credential fails due to rate limiting or authentication errors, the system automatically switches to the next available credential. This occurs within the `while(true)` loop inside `runEmbeddedPiAgent` (see Section 15.2).

**Tier 2 — Fallback Model List**: If all Auth Profiles for a model fail (or the model itself is unavailable), the system throws a `FailoverError`, which is caught by `runWithModelFallback` and attempts the next model in the list.

**Tier 1 — Final Error Report**: If all fallback models also fail, the system aggregates the errors and reports them to the user.

## 16.1.2 Model Selection Source Code (`src/agents/model-selection.ts`)

The core responsibility of model selection is to parse user configuration (such as `"anthropic/claude-sonnet-4-20250514"`) into a standardized provider + model ID pair.

### ModelRef Type

```typescript
// src/agents/model-selection.ts
export type ModelRef = {
  provider: string;  // Provider identifier (e.g., "anthropic")
  model: string;     // Model identifier (e.g., "claude-sonnet-4-20250514")
};
```

### Provider ID Normalization

Provider names from different sources may have variants. `normalizeProviderId` unifies them:

```typescript
// src/agents/model-selection.ts
export function normalizeProviderId(provider: string): string {
  const normalized = provider.trim().toLowerCase();
  if (normalized === "z.ai" || normalized === "z-ai") return "zai";
  if (normalized === "opencode-zen") return "opencode";
  if (normalized === "qwen") return "qwen-portal";
  if (normalized === "kimi-code") return "kimi-coding";
  return normalized;
}
```

### Model Reference Parsing

Users can reference models via `provider/model` format or by model name alone:

```typescript
// src/agents/model-selection.ts
export function parseModelRef(raw: string, defaultProvider: string): ModelRef | null {
  const trimmed = raw.trim();
  if (!trimmed) return null;

  const slash = trimmed.indexOf("/");
  if (slash === -1) {
    // No "/" — use default provider
    const provider = normalizeProviderId(defaultProvider);
    const model = normalizeProviderModelId(provider, trimmed);
    return { provider, model };
  }

  // Has "/" — split it
  const provider = normalizeProviderId(trimmed.slice(0, slash));
  const model = normalizeProviderModelId(provider, trimmed.slice(slash + 1));
  return { provider, model };
}
```

### Model Aliases

Anthropic models support short aliases:

```typescript
const ANTHROPIC_MODEL_ALIASES: Record<string, string> = {
  "opus-4.6": "claude-opus-4-6",
  "opus-4.5": "claude-opus-4-5",
  "sonnet-4.5": "claude-sonnet-4-5",
};
```

Users can use `opus-4.6` instead of the full `claude-opus-4-6`, and the system automatically expands it.

### Model Allowlist

Administrators can configure a list of allowed models, restricting which models users can switch to via the `/model` command:

```typescript
// src/agents/model-selection.ts
export function buildAllowedModelSet(params: {
  cfg: OpenClawConfig;
  catalog: ModelCatalogEntry[];
  defaultProvider: string;
  defaultModel: string;
}): { allowedKeys: Set<string>; allowedCatalog: ModelCatalogEntry[] } {
  // Build allowlist from agents.defaults.models configuration
  const configuredKeys = buildConfiguredAllowlistKeys({ cfg, defaultProvider });
  // Default model is always in the allowlist
  // Models in the catalog matching the allowlist can be selected
}
```

### CLI Provider Detection

Some providers need to run as independent CLI processes (rather than in embedded mode):

```typescript
// src/agents/model-selection.ts
export function isCliProvider(provider: string, cfg?: OpenClawConfig): boolean {
  const normalized = normalizeProviderId(provider);
  if (normalized === "claude-cli" || normalized === "codex-cli") return true;
  // Also supports custom CLI backends
  const backends = cfg?.agents?.defaults?.cliBackends ?? {};
  return Object.keys(backends).some((key) => normalizeProviderId(key) === normalized);
}
```

## 16.1.3 Model Fallback (`src/agents/model-fallback.ts`)

Model fallback is the second tier of three-tier fault tolerance. The `runWithModelFallback` function manages an ordered list of candidate models, attempting each in sequence until one succeeds.

### Candidate List Construction

```typescript
// src/agents/model-fallback.ts (simplified)
function resolveFallbackCandidates(params: {
  cfg: OpenClawConfig;
  provider: string;
  model: string;
  fallbacksOverride?: string[];
}): ModelCandidate[] {
  const candidates: ModelCandidate[] = [];

  // 1. Primary model (the model requested in the current request)
  candidates.push({ provider: params.provider, model: params.model });

  // 2. Configured fallback model list
  const modelFallbacks = params.fallbacksOverride
    ?? params.cfg.agents?.defaults?.model?.fallbacks
    ?? [];
  for (const raw of modelFallbacks) {
    candidates.push(resolveModelRefFromString(raw));
  }

  // 3. Global default model (as final fallback)
  if (!params.fallbacksOverride) {
    const primary = resolveConfiguredModelRef({ cfg: params.cfg });
    candidates.push({ provider: primary.provider, model: primary.model });
  }

  return candidates; // Return after deduplication
}
```

The order of the candidate list determines the attempt priority: primary model → fallback model 1 → fallback model 2 → ... → global default model.

### Fallback Execution Loop

```typescript
// src/agents/model-fallback.ts
export async function runWithModelFallback<T>(params: {
  cfg: OpenClawConfig;
  provider: string;
  model: string;
  agentDir?: string;
  fallbacksOverride?: string[];
  run: (provider: string, model: string) => Promise<T>;
}): Promise<{ result: T; provider: string; model: string; attempts: FallbackAttempt[] }> {
  const candidates = resolveFallbackCandidates({ ... });
  const attempts: FallbackAttempt[] = [];

  for (let i = 0; i < candidates.length; i++) {
    const candidate = candidates[i];

    // Skip providers where all profiles are in cooldown
    if (authStore) {
      const profileIds = resolveAuthProfileOrder({ store: authStore, provider: candidate.provider });
      const anyAvailable = profileIds.some((id) => !isProfileInCooldown(authStore, id));
      if (profileIds.length > 0 && !anyAvailable) {
        attempts.push({ ...candidate, error: "Provider in cooldown", reason: "rate_limit" });
        continue;  // Skip, don't attempt
      }
    }

    try {
      const result = await params.run(candidate.provider, candidate.model);
      return { result, provider: candidate.provider, model: candidate.model, attempts };
    } catch (err) {
      // AbortError (user-initiated cancellation) should not trigger fallback
      if (shouldRethrowAbort(err)) throw err;

      // Non-FailoverError should not trigger fallback
      if (!isFailoverError(coerceToFailoverError(err, candidate))) throw err;

      attempts.push({ ...candidate, error: err.message, reason: err.reason });
    }
  }

  // All candidates failed
  throw new Error(`All models failed (${attempts.length}): ${summary}`);
}
```

Key design decisions:

1. **Cooldown Pre-check** — If all Auth Profiles for a provider are in cooldown, skip it directly without wasting time attempting
2. **AbortError Passthrough** — User-initiated cancellation should not trigger fallback; it should immediately abort the entire flow
3. **Non-FailoverError Passthrough** — Only errors explicitly marked as "failover-eligible" trigger fallback; other errors (such as configuration errors, programming errors) are thrown immediately
4. **Error Aggregation** — Details of all failed attempts are collected, so the final error report can display the complete failure chain

## 16.1.4 Model Compatibility Layer (`src/agents/model-compat.ts`)

Different LLM providers have varying levels of API support. For example, OpenAI's API format is widely used as an "industry standard," and many third-party providers (such as Z.AI) provide OpenAI-compatible interfaces, but don't support all features.

```typescript
// src/agents/model-compat.ts
export function normalizeModelCompat(model: Model<Api>): Model<Api> {
  const isZai = model.provider === "zai" || model.baseUrl?.includes("api.z.ai");
  if (!isZai || model.api !== "openai-completions") return model;

  // Z.AI does not support developer role, needs to be disabled in compatibility layer
  const compat = model.compat ?? {};
  model.compat = { ...compat, supportsDeveloperRole: false };
  return model;
}
```

> **Sidebar**: OpenAI's Chat Completions API defines multiple message roles: `system` (system prompt), `user` (user message), `assistant` (assistant reply), and the newer `developer` (developer instruction). The `developer` role was introduced by OpenAI in 2024 to replace developer-level instructions in the `system` role. However, many third-party providers with OpenAI-compatible APIs have not yet supported the `developer` role, and sending requests containing that role will result in errors. `normalizeModelCompat` avoids such issues by disabling unsupported features in the compatibility configuration.

The model compatibility layer is currently concise, but it provides a clear extension point — as more providers and models are added, more compatibility adaptation logic can be added here.

***

## Section Summary

1. **Three-tier fault tolerance strategy**: Auth Profile rotation (same model, different credentials) → Fallback model list (different models) → Final error report, progressing layer by layer to ensure service availability.
2. **Model selection** maps flexible user configuration to precise model references through provider ID normalization, model ID normalization, alias support, and allowlist maintenance.
3. **Model fallback** maintains an ordered candidate list, skips providers in cooldown, distinguishes between failover-eligible and non-failover-eligible errors, and aggregates details of all failed attempts.
4. **Model compatibility layer** handles differences in API standard support across providers, ensuring request format is compatible with the target provider.
