/ai-and-data:llm-cost-optimizationfrom ai-and-data
Production reference for LLM token economics and cost optimization on Azure. Covers tokenization, pricing asymmetry, prompt caching, model routing, PTU vs PAYG, compression techniques, and token-lean serialization.
Ships in ai-and-data. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Governance is architecture, not monitoring. Without per-request token logging and cost attribution, optimization is guesswork.
o200k_base (GPT-4o, o-series, GPT-4.1+): 200K-token vocabulary; ~10% fewer tokens for English than cl100k_base; 20–40% fewer tokens for non-Latin scripts (Chinese, Japanese, Arabic)cl100k_base (GPT-4/3.5/ada-002): 100K-token vocabularytiktoken.encoding_for_model() — never hardcode. Tokenizer drift across model generations can silently inflate per-request cost by up to ~35% at unchanged per-token prices.usage object (includes cached_tokens and reasoning_tokens breakdowns)output_tokens_details.reasoning_tokensmax_tokens budget — a complex task can burn 8,000+ reasoning tokens before a 300-token answermax_tokens too low yields finish_reason: "length" with empty content because reasoning consumed the entire budgetmax_tokens to ≥4× expected visible output for reasoning modelsRoutes PTU overage to a Standard deployment on non-200 responses (429 PTU-exhausted; 400 long-context >128K on gpt-4.1 PTU; 500/503).
Enable via:
spilloverDeploymentName (all requests)x-ms-spillover-deployment header (per-request)Billing: PTU requests = hourly only; spilled requests = standard token rates.
Pattern: size PTU for average load; spill peaks to PAYG. Monitor by splitting Azure OpenAI Requests metric by ModelDeploymentName + StatusCode.
Stable content first, dynamic content last.
Order:
A single byte of drift before the cached boundary invalidates the entire prefix. A documented production failure: team's system prompt opened with f"Today is {datetime.now().date()}…" which dropped cache hit rate to ~1%.
cached_tokens in prompt_tokens_detailsprompt_cache_retention: "24h"prompt_cache_key to improve routing/hit ratecache_control breakpoints (≤4 per request)Token budget is a first-class design constraint. Allocate explicit budgets per component:
Optimize for cost-per-task, not tokens-saved-in-isolation.
Store session state in Azure Cosmos DB or Azure Cache for Redis. Compact conversation history infrequently at predictable boundaries (compacting breaks the stable cache prefix).
Per Liu et al. (TACL 2024, arXiv:2307.03172): performance "significantly degrades when models must access relevant information in the middle of long contexts, even for explicitly long-context models." Place critical information first or last. Rerank retrieved docs so the gold passage sits at an extremity.
Caching and routing beat any prompt-rewriting trick — apply this section only after the structural levers above. Measure tokens-per-completed-task: over-compression triggers retries and clarifications that cost more than they save.
Extractive compression — selecting whole sentences — often outperforms fancier token-pruning and enables up to ~10× compression with minimal accuracy loss (UC Berkeley, "Characterizing Prompt Compression Methods for Long Context Inference," arXiv 2407.08892, ICML 2024 Es-FoMo). Reach for perplexity-based pruning (LLMLingua) only when query-aware long-context demands it.
pip install llmlingua; stacks with caching (cache the compressed prompt).pip install selective-context.Stripping articles, prepositions, pleasantries, and filler claims up to 75% savings; independent benchmarks land at 14–21% on real coding tasks (Guzik: Sonnet 14%, Opus 21%; ncvgl SWE-bench Pro ~14%) because input/context dominates the bill there, with quality staying 100%. Best for output-heavy interactive sessions. The middle ground — "Be concise, no filler, skip pleasantries" — captures most savings without unreadable telegraph. Politeness tokens are pure cost.
Roughly TOON < Markdown < YAML < compact JSON < pretty JSON < XML. XML needs ~80% more tokens than Markdown for the same nested data; YAML ~36% cheaper than JSON per record; TOON ~30–50% savings on uniform tabular arrays (weak on nested/irregular data). But use XML tags for prompt structure (semantic clarity, per Anthropic) and avoid forcing JSON output on reasoning — it can degrade quality 10–15%.
The single highest-ROI lever. Task-to-tier mapping:
| Task type | Recommended tier |
|---|---|
| Classification, extraction, simple formatting | Nano/Phi-4-class |
| Chat, summarization, standard Q&A | Mini-class |
| Complex reasoning, code refactoring, multi-step analysis | Frontier/reasoning |
Microsoft Foundry Model Router caveat: "Balanced" mode is conservative — selects within ~1–2% quality range; one Microsoft field test measured only 4.5–14.2% savings. Validate on your own traffic before projecting the 60–80% figure.
Deploy APIM as the AI gateway for every Azure OpenAI deployment. This enables per-consumer token limits, per-team cost attribution, semantic caching, PTU→standard spillover routing, and content safety — all before the request reaches the model.
| Policy | Function |
|---|---|
llm-token-limit | Per-key TPM/quota enforcement with prompt-token pre-calculation |
llm-emit-token-metric | Per-consumer token metrics to App Insights (up to 5 custom dimensions) |
llm-semantic-cache-lookup / store | Redis-backed vector semantic cache |
llm-content-safety | Azure Content Safety integration |
| Backend pool + circuit breaker | Priority/weighted routing + circuit breakers per backend |
PTU backend (priority 1) → PAYG Standard (priority 2 / overflow). Circuit breaker per backend. retry policy honoring Retry-After.
Azure-Samples/apim-genai-gateway-toolkit
llm-emit-token-metricAPIM + Redis Enterprise pattern for FAQ/support bots:
rate-limit after lookup to protect backend if cache is unavailablescore-threshold (lower = stricter match)Output cache (simple TTL) cuts FAQ/deterministic traffic 30–80%.
When NOT to use semantic caching: personalized queries, real-time data, high-diversity query patterns.
[Role and objective]
[Constraints and rules — positive instructions ("always do X") outperform negative]
[Output format specification]
[Examples if needed]
| Technique | Cost | When to use |
|---|---|---|
| Zero-shot CoT ("think step by step") | Moderate (adds output tokens) | Multi-step tasks on non-reasoning models |
| Few-shot CoT (3–8 exemplars) | Higher (adds input tokens) | Complex tasks needing demonstrated format |
| Self-consistency (sample N, vote) | N× cost | High-stakes decisions |
| Tree of Thoughts (branching) | Expensive | Deep search/planning problems |
| Dedicated reasoning model (o-series) | High but predictable | Genuine multi-step reasoning |
Rule: use dedicated reasoning models for genuine multi-step problems; use CoT-prompted standard models when you need to see/control the reasoning and cost matters.
Prefer Structured Outputs (JSON Schema, strict: true) over legacy JSON mode — guarantees schema adherence, not just valid JSON.
Azure constraints:
required (emulate optional via ["type","null"])additionalProperties: falseparallel_tool_calls (set to false) or On Your Data/Assistantsseed for deterministic/factual outputsmax_tokens — no cap means unbounded cost exposureRetrieve similar examples via embedding search rather than hardcoding — enables more relevant examples without growing the static system prompt.
parallel_tool_calls for independent calls (reduces round-trips)store: true on production frontier-model calls to capture completionsExpected result: ~90% quality at ~10% cost.
Azure fine-tuning specifics:
| Model | Dimensions | Price/1M | MTEB | Notes |
|---|---|---|---|---|
text-embedding-3-small | 1,536 | ~$0.02 | 62.3 | OpenAI-ecosystem default; 5× cheaper than ada-002 |
text-embedding-3-large | 3,072 | ~$0.13 | 64.6 | ~2.3 MTEB points better; Matryoshka-truncatable |
ada-002 | 1,536 | ~$0.10 | 61.0 | Legacy; replace with 3-small |
Matryoshka: store full-dim once; truncate per index (768 dims halves storage). Standard in modern models.
Cost reduction rules:
| Error | Meaning | Response |
|---|---|---|
| 429 | TPM/RPM quota or PTU 100% utilized | Respect Retry-After; exponential backoff with jitter |
| 503 | Capacity/server issue | Backoff + failover to another deployment |
Azure returns x-ratelimit-* headers. The APIM circuit breaker handles this automatically at the gateway layer.
Key metrics to track:
ProcessedPromptTokens, GeneratedTokens, TokenTransaction (Processed Inference = prompt+generated)InputTokens, OutputTokens, TotalTokensProvisionedUtilizationV2 (PTU utilization)AzureOpenAIContextTokensCacheMatchRate (Prompt Token Cache Match Rate)FineTunedTrainingHoursLatency metricDimensions: split by ModelDeploymentName / ModelName.
Export: diagnostic settings → Log Analytics (KQL); build workbooks/Managed Grafana dashboards.
llm-emit-token-metric policy supports OpenAI, Anthropic Messages, and Google Vertex schemas.
Build cost-per-task, not cost-per-token. RAG cost breakdown:
Multi-agent fan-out: multiplies LLM calls; "your average cost per task is a lie" (GrisLabs tracked 1,127 agent runs: median $1.22, p95 $22.14 — an 18× tail). Implement:
| Recipe | Expected savings | Requirement |
|---|---|---|
| R1 — Model routing | 60–80% on routine queries | Quality eval confirming <1–2% delta |
| R2 — Prompt caching | 40–50% on input tokens | Stable ≥1,024 token prefix; verify via cached_tokens |
| R3 — Semantic caching | 30–80% on repeat traffic | Low query diversity; non-personalized/non-realtime answers |
| R4 — Batch API | 50% at 24h SLA | Async workloads (evals, nightly processing, embedding refresh) |
| R5 — LLMLingua compression | Up to 20× token reduction | Long-doc RAG; accept ~1.5 point quality drop |
| R6 — Distillation | ~90% quality at ~10% cost | High-volume domain-specific tasks; hundreds of teacher completions |
| R7 — PTU right-sizing | Up to 70% vs hourly | 30–60 days telemetry; P95 hourly throughput; sustained >50% utilization |
Stack order: Instrument first → quick wins (caching + batch) → routing → semantic cache → PTU commitment → distillation.
Stage 1 — Instrument before optimizing (week 1). Deploy APIM as AI gateway with llm-emit-token-metric (dimensions: team/app/user). Enable diagnostic settings → Log Analytics. Tag every deployment by feature. Compute cost-per-task on your top 3 features. Threshold: attribute >90% of spend to a feature/team.
Stage 2 — Quick wins (weeks 2–3). (a) Restructure prompts for stable ≥1,024-token prefix; confirm cached_tokens > 0. (b) Cap max_tokens (600–800 chat). (c) Move async workloads to Batch API. (d) Cache static-doc embeddings by content hash. Expected: 30–50% reduction.
Stage 3 — Model routing (weeks 4–6). Default to mini/nano-class; build rule- or classifier-based router escalating on complexity/low-confidence. Re-run evals to confirm no quality regression. Expected: additional 40–70% on routine traffic. Hold routing if quality delta exceeds 1–2 eval points.
Stage 4 — Semantic caching + compression (weeks 6–8). Add APIM semantic cache (Redis Enterprise) for FAQ/support traffic. Apply LLMLingua to long-doc RAG passages. Threshold: only where query diversity is low and answers aren't personalized/real-time.
Stage 5 — PTU commitment (after 30–60 days telemetry). Pull P95 hourly throughput. If GPT-4o-class monthly volume >150–200M tokens AND sustained utilization >50%: deploy PTU for average load, enable spillover for peaks, buy 1-month reservation first, then 1-year once steady state confirmed.
Stage 6 — Distillation (ongoing). Set store: true for high-volume domain-specific tasks. Accumulate hundreds–thousands of frontier completions. Fine-tune nano/mini behind a quality gate. Delete idle fine-tuned deployments.
Re-evaluate model selection quarterly. Prices and quality move fast; a model that was your only option may now be 5× pricier than a newer SKU within 1–2 eval points.
parallel_tool_calls or asynciostrict: true JSON Schema insteadmax_tokens set — unbounded cost exposureusage object and Azure invoiceWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub theviziusgroup/vibe-engineering-skills --plugin ai-and-data4 skills in this plugin
/ai-ml-landscapeComprehensive practitioner reference for the 2025–2026 AI/ML landscape covering frontier model selection and routing, open-weight vs hosted API trade-offs, reasoning models and test-time compute, RAG and agent production patterns, classical ML for tabular data, deep learning foundations (transformers, attention, MoE, SSMs), LLM training and post-training (DPO/GRPO/LoRA/QLoRA), inference serving (vLLM/SGLang), evaluation benchmark skepticism, safety/alignment, EU AI Act governance, and hardware selection. Use when advising on model selection, AI architecture decisions, LLM deployment, fine-tuning strategy, benchmark interpretation, or AI governance compliance./data-engineeringProduction data engineering reference covering ELT/ETL patterns, dbt project structure, orchestration (Airflow/Dagster/Prefect), Python data stack (pandas/Polars/DuckDB/Spark), cloud warehouses (Snowflake/BigQuery/Azure Fabric), lakehouse formats (Iceberg/Delta/Hudi), CDC with Debezium, SCD2, data quality, feature stores, and ML productionization with MLflow. Use when answering questions about data pipelines, SQL optimization, warehouse cost control, Python data tools, gradient boosting, A/B testing, or modern data stack architecture.Other plugins' skills for the same job
2 plugins ship this exact skill · first indexed Aug 12, 2026