# Оптимизация LLM-расходов: стоимость успешной задачи

> Снижаем LLM spend без скрытой потери качества: cost attribution, output budgets, проверка smaller models, безопасный cache, batch и контроль retries.
> Author: Roman Belov · Published: 2026-06-09 · Source: https://futurecraft.pro/ru/blog/ai-cost-optimization/

«Сократить LLM cost на 60%» — не инженерная цель без baseline, traffic и quality
bar. Дешёвый запрос, который дважды упал, попал к человеку или ухудшил conversion,
может оказаться дороже исходного.

Считайте другое:

```text
cost per successful task =
  (model + embeddings + reranking + retries + cache + review + infrastructure)
  / tasks, прошедшие product outcome и quality contract
```

[Production LLM stack](/ru/blog/production-llm-stack/) описывает task contract.
Здесь — cost controls внутри него.

## Сначала постройте cost ledger

Provider invoice агрегирует spend, но не объясняет продуктовую причину. Пишите
одну строку ledger на логическую задачу:

```typescript
interface LlmCostEvent {
  taskId: string;
  taskType: string;
  tenantId: string;
  promptVersion: string;
  routeVersion: string;
  provider: string;
  model: string;
  attempt: number;
  inputTokens?: number;
  cachedInputTokens?: number;
  outputTokens?: number;
  estimatedCost: number;
  latencyMs: number;
  outcome: 'passed' | 'failed' | 'escalated' | 'abandoned';
}
```

Версионируйте price table по provider, model, region, service tier и date.
Сверяйте estimate с invoice. Не логируйте raw prompts и PII ради cost analytics.

Dashboard нужен по task и outcome:

- total и marginal spend;
- cost per passed task;
- tokens по секциям: policy, retrieval, history, tools, output;
- attempts и fallback share;
- cache read/write tokens и hit rate;
- quality pass, escalation и abandonment;
- P50/P95 latency;
- spend by tenant и budget alerts.

Average cost per request скрывает дорогой tail и неудачную работу.

## Уберите waste до смены модели

Первый проход механический:

1. **Deduplicate операции.** Idempotency key не даёт client retry или queue
   redelivery сгенерировать дважды.
2. **Ограничьте retries.** Все attempts делят end-to-end deadline и retry budget.
3. **Ограничьте output.** У задачи есть maximum output и stopping format.
4. **Сократите context.** Уберите повторные logs, старую history, unused tool
   schemas и нерелевантный retrieval.
5. **Остановите мёртвые workflows.** Отмените downstream calls после validation
   failure или user abandonment.
6. **Перенесите deterministic работу в code.** Parsing, arithmetic, permissions и
   exact formatting не требуют generation.

Каждое изменение проверяйте на прежнем eval set. Удалённый context мог содержать
нужный evidence.

## Подготовьте prompt к provider cache

Provider prompt cache обычно работает со стабильным prefix. Durable instructions,
schemas и shared examples размещайте до user-specific data. Volatile timestamps,
IDs и conversation state — позже.

```text
stable policy and output schema
shared task examples
retrieved or tenant-specific context
current user input
```

Не дополняйте prompt ради cache threshold. Лишний input влияет на latency, privacy
и quality. По usage fields сравнивайте eligible tokens, writes, reads, hit rate,
billed cost и совместимость retention с data policy.

Правила, thresholds и prices меняются. Финансовая модель должна опираться на
current provider docs и живые метрики, а не на числа из статьи.

## Задайте output budget для task

Output способен доминировать в счёте. Global `maxTokens` — не product requirement.

| Task | Более точный контракт |
|---|---|
| Classification | Только enum |
| Extraction | JSON Schema с required fields |
| Search summary | Фиксированное число cited bullets |
| Agent planning | Bounded steps и tool budget |
| Long report | Section limits и continuation workflow |

Сравнивайте requested и used output. Если ответы постоянно короче — снижайте
ceiling. Если упираются в cap и не проходят validation — исправляйте task design,
а не повышайте лимит всем.

## Маршрутизируйте стабильные tasks

Routing экономит только при task-based eligibility. Cheap classifier, решающий,
что произвольный prompt «лёгкий», добавляет call и failure mode.

Для каждого candidate сравните:

- task-contract pass rate;
- harmful failure rate;
- latency distribution;
- attempts и fallback rate;
- cost per passed task;
- language и customer slices.

Сначала offline evals, затем shadow, reversible canary и promotion только на
прошедшие tasks. Подробнее — в
[multi-provider routing guide](/ru/blog/multi-provider-llm-architecture/).

Cheaper model без нужного region, safety policy или structured output не eligible.

## Перенесите delay-tolerant работу в batch

Batch endpoints подходят уже асинхронным задачам: nightly evals, document
enrichment, offline classification, embedding backfill и reports с ясным deadline.

Batch меняет operations. Нужны stable item IDs, partial-failure handling, expiry,
retries, output validation и reconciliation. Не полагайтесь на порядок output;
соединяйте по custom identifier.

Считайте storage, polling/webhooks, failed items и missed deadlines. Перед запуском
проверяйте current provider docs по price и completion window.

## Используйте exact cache до semantic cache

Exact cache проще проверить. Он подходит для immutable document hash плюс prompt
version.

```text
tenant + permissions + task + normalized input hash + source versions +
prompt version + model version + locale + policy version
```

Semantic cache переиспользует ответ на лишь похожий запрос. Похожая формулировка
не гарантирует одинаковые intent, authorization, time и source state. Для legal,
medical, financial, account, personalized и быстро меняющихся ответов лучше не
применять его без task-specific validation.

Если применяете:

- scope entries по tenant и permissions;
- freshness определяется source, не universal TTL;
- храните provenance и exact input;
- повторяйте deterministic policy checks на hit;
- инвалидируйте при prompt, model, policy или source change;
- аудитите false hits на human-labeled examples;
- учитывайте embedding, vector store и miss path.

Cache hit — product decision, а не автоматический success.

## Контролируйте budgets на трёх уровнях

**Request:** input/output ceiling, deadline, attempts, tools и fallback.

**Tenant:** daily/monthly spend, alerts, feature limits и degraded mode.

**System:** provider commitments, capacity, incident reserve и forecast.

Spend enforcement может быть eventually consistent. Для точного stop нужны
application-side limits. Заранее определите UX при исчерпании: smaller eligible
route, queued processing, limited feature или отказ от generation.

## Выпускайте cost changes как продуктовые релизы

1. Запишите hypothesis и affected task.
2. Зафиксируйте eval set и baseline route.
3. Оцените tokens, infrastructure и review impact.
4. Используйте shadow, если меняется output.
5. Запустите небольшой canary.
6. Следите за quality, latency, attempts и cost per success.
7. Promote или rollback с причиной.

Не объединяйте prompt trimming, model swap, новый cache и retry policy. Иначе
невозможно понять, что сэкономило или сломало качество.

## Production checklist

- [ ] Spend привязан к task, route, attempt, tenant и outcome.
- [ ] Price tables версионируются и сверяются с invoices.
- [ ] Есть idempotency, bounded retries, cancellation и output limits.
- [ ] Context sections измеряются и сокращаются через evals.
- [ ] Cache economics основана на observed reads, writes и billed tokens.
- [ ] Smaller models прошли task eval, shadow и canary.
- [ ] Batch jobs обрабатывают identity, partial failure, expiry и validation.
- [ ] Cache keys учитывают authorization, freshness и behavior versions.
- [ ] Budget exhaustion имеет safe user-visible outcome.
- [ ] Dashboard показывает cost per successful task.

## Первоисточники

- [OpenAI: Prompt caching](https://platform.openai.com/docs/guides/prompt-caching)
- [OpenAI: Batch API](https://platform.openai.com/docs/guides/batch)
- [Anthropic: Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
- [Anthropic: Message Batches](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
- [Google Cloud: Vertex AI context cache](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview)

Лучшая оптимизация — не минимальный invoice, а минимальная воспроизводимая
стоимость задачи, которая всё ещё проходит contract.
