Оптимизация LLM-расходов: стоимость успешной задачи
Что такое оптимизация стоимости LLM?
Оптимизация стоимости LLM снижает цену успешной задачи приложения при сохранении требований к качеству, latency, reliability, privacy и safety. Она учитывает tokens, routing, retries, caching, batch и инфраструктуру вокруг model call.
TL;DR
- -Оптимизируйте cost per successful task, а не цену токена или средний cost per request
- -До смены модели привяжите spend к task, tenant, prompt version, route, retries и outcome
- -Уберите случайные tokens и unbounded output до добавления routing или cache infrastructure
- -Продвигайте smaller model только после task-specific evals, shadow comparison и reversible canary
- -Semantic cache переиспользует старое решение: key обязан учитывать permissions, freshness, prompt, model и policy
«Сократить LLM cost на 60%» — не инженерная цель без baseline, traffic и quality bar. Дешёвый запрос, который дважды упал, попал к человеку или ухудшил conversion, может оказаться дороже исходного.
Считайте другое:
cost per successful task =
(model + embeddings + reranking + retries + cache + review + infrastructure)
/ tasks, прошедшие product outcome и quality contract
Production LLM stack описывает task contract. Здесь — cost controls внутри него.
Сначала постройте cost ledger
Provider invoice агрегирует spend, но не объясняет продуктовую причину. Пишите одну строку ledger на логическую задачу:
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 до смены модели
Первый проход механический:
- Deduplicate операции. Idempotency key не даёт client retry или queue redelivery сгенерировать дважды.
- Ограничьте retries. Все attempts делят end-to-end deadline и retry budget.
- Ограничьте output. У задачи есть maximum output и stopping format.
- Сократите context. Уберите повторные logs, старую history, unused tool schemas и нерелевантный retrieval.
- Остановите мёртвые workflows. Отмените downstream calls после validation failure или user abandonment.
- Перенесите 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 — позже.
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.
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.
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 как продуктовые релизы
- Запишите hypothesis и affected task.
- Зафиксируйте eval set и baseline route.
- Оцените tokens, infrastructure и review impact.
- Используйте shadow, если меняется output.
- Запустите небольшой canary.
- Следите за quality, latency, attempts и cost per success.
- 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
- OpenAI: Batch API
- Anthropic: Prompt caching
- Anthropic: Message Batches
- Google Cloud: Vertex AI context cache
Лучшая оптимизация — не минимальный invoice, а минимальная воспроизводимая стоимость задачи, которая всё ещё проходит contract.