# Rerouting and cost optimization

A reroute rule rewrites the model on a request **before** it is forwarded. The
application keeps asking for the expensive model; Spendline sends the cheaper
one.

## Create a rule

```http
POST /api/reroutes
x-spendline-key: <owner or admin credential>
Content-Type: application/json

{
  "from_model": "gpt-5.6",
  "to_model": "gpt-5.6-mini",
  "rollout_percent": 25,
  "scope": { "agent_id": "doc-summarizer" }
}
```

- `from_model` and `to_model` are normalized to canonical catalog names.
- They must differ (`400` otherwise).
- `to_model` must be routable (`400` otherwise): pick from optimizer suggestions.
- `rollout_percent` defaults to 100 and is clamped to 0–100. Start partial.
- `scope` is optional; omitting it makes the rule global for the account.

## Cross-provider reroutes need a provider key

Rerouting `gpt-5.6` → `claude-sonnet-5` sends traffic to a different provider, so
the account must already hold an **active provider key** for the target. Without
one:

```json
{
  "error": "Cross-provider reroute requires an active anthropic Provider Key for this account. ...",
  "error_type": "missing_provider_key",
  "provider": "anthropic"
}
```

Storing a provider key is **human-only**: it is a live spending credential. Ask
the human to add it in the dashboard. Do not ask them to paste it to you, and
never accept a provider key into your own context.

## Measure before and after

```bash
curl https://www.spendline.ai/api/reroutes/savings \
  -H "x-spendline-key: $SPENDLINE_API_KEY"
```

```bash
curl https://www.spendline.ai/api/reroutes/<id>/stats \
  -H "x-spendline-key: $SPENDLINE_API_KEY"
```

## Optimizer suggestions

```bash
curl https://www.spendline.ai/api/optimizer/summary \
  -H "x-spendline-key: $SPENDLINE_API_KEY"
```

Ranks candidate swaps by projected saving using real recorded traffic, not a
generic price table.

## Honest limits

- A reroute changes model behaviour. Quality is the user's call, recommend a
  partial `rollout_percent` and a comparison, never a silent 100% swap.
- Rerouting is not a budget. It reduces unit cost; it does not cap total spend.
  Pair it with a budget.
- Creating a reroute requires owner-or-admin authority.
