[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AK5QEKVDF6C74XE4SWT2A3":3,"skill-same:01M7AK5QEKVDF6C74XE4SWT2A3":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AK5QEKVDF6C74XE4SWT2A3","llm-cost-optimization",null,"Production reference for LLM token economics, cost optimization, and prompt engineering on Azure. Covers tokenization and pricing asymmetry, prompt caching (Azure\u002FAnthropic\u002FGoogle), model routing and cascades, PTU vs PAYG break-even, Azure APIM AI gateway, semantic caching, context window engineering, prompt\u002Fcontext compression (LLMLingua, LongLLMLingua, RECOMP, Selective Context, extractive compression), caveman\u002Ftelegraphic prompting, token-lean serialization formats (TOON\u002FMarkdown\u002FYAML vs JSON\u002FXML), output control (Concise CoT, Chain-of-Draft), fine-tuning for cost, Batch API, structured outputs, conversation history management, and Azure-specific deployment patterns. Use when optimizing LLM spend, compressing prompts or context, choosing a compression library, picking token-lean formats, reducing output verbosity, designing cost-efficient AI architectures, troubleshooting token costs, engineering prompts for performance, or sizing Azure OpenAI deployments.","the-vibey-project\u002Fvibey","the-vibey-project","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F329298758?v=4","01M7AJHGZ9722CTJ4JNQZVRH0Q","the vibey project","01M7AJHGZVMG2K7TGXQ6XFHVG3",5,"MIT","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fai-and-data\u002Fskills\u002Fllm-cost-optimization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: llm-cost-optimization\ndescription: \"Production reference for LLM token economics, cost optimization, and prompt engineering on Azure. Covers tokenization and pricing asymmetry, prompt caching (Azure\u002FAnthropic\u002FGoogle), model routing and cascades, PTU vs PAYG break-even, Azure APIM AI gateway, semantic caching, context window engineering, prompt\u002Fcontext compression (LLMLingua, LongLLMLingua, RECOMP, Selective Context, extractive compression), caveman\u002Ftelegraphic prompting, token-lean serialization formats (TOON\u002FMarkdown\u002FYAML vs JSON\u002FXML), output control (Concise CoT, Chain-of-Draft), fine-tuning for cost, Batch API, structured outputs, conversation history management, and Azure-specific deployment patterns. Use when optimizing LLM spend, compressing prompts or context, choosing a compression library, picking token-lean formats, reducing output verbosity, designing cost-efficient AI architectures, troubleshooting token costs, engineering prompts for performance, or sizing Azure OpenAI deployments.\"\n---\n\n# LLM Cost Optimization, Prompt Engineering & Context Engineering — Azure Reference\n\n## The Three Core Levers (in ROI order)\n\n1. **Model routing** — route routine traffic to cheaper models, escalate only uncertain requests (60–80% cost reduction on routine queries per Microsoft guidance; validated RouteLLM benchmark: 95% GPT-4 quality at 26% GPT-4 calls, ~48% cheaper)\n2. **Prompt caching** — restructure prompts for a stable prefix (Azure: ~50% off input; Anthropic: 90% off cache reads)\n3. **Deployment pricing** — Batch API (50% off), PTU reservations (up to 70% off hourly), right-tier matching\n\n**Governance is architecture, not monitoring.** Without per-request token logging and cost attribution, optimization is guesswork.\n\n---\n\n## Token Economics Fundamentals\n\n### Tokenization\n- **`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)\n- **`cl100k_base`** (GPT-4\u002F3.5\u002Fada-002): 100K-token vocabulary\n- Always resolve encodings with `tiktoken.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.\n- The only ground truth for billing is the API's `usage` object (includes `cached_tokens` and `reasoning_tokens` breakdowns)\n\n### Input\u002FOutput Pricing Asymmetry — **Architectural Implication**\n- Input (prefill): one parallel forward pass over all tokens\n- Output (decode): one sequential forward pass **per token** → output costs 3–8× input\n- Azure GPT-4o example: input $2.50\u002F1M vs output $10\u002F1M (4×)\n- **Design implication**: minimize output length for cost-sensitive paths; be explicit about output length in the prompt\n\n### Reasoning Tokens\n- Billed at **output rates** (expensive)\n- Invisible in the response body; surfaced in `output_tokens_details.reasoning_tokens`\n- Do NOT persist across turns\n- Consume the `max_tokens` budget — a complex task can burn 8,000+ reasoning tokens before a 300-token answer\n- **Anti-pattern trap**: setting `max_tokens` too low yields `finish_reason: \"length\"` with empty content because reasoning consumed the entire budget\n- **Rule**: set `max_tokens` to ≥4× expected visible output for reasoning models\n- Track reasoning tokens as a first-class metric\n- Worth it for genuine multi-step reasoning (math, code, legal analysis); wasteful on pipelines expecting short outputs\n\n---\n\n## Azure Pricing Models\n\n### Standard (PAYG)\n- Per-token billing; quota in TPM\u002FRPM\n- **Global Standard**: routed worldwide, highest throughput, lowest rate\n- **Data Zone Standard**: US\u002FEU data residency\n- **Regional Standard**: single region, highest per-token cost\n- Prompt caching and Batch discounts apply automatically\n\n### PTU (Provisioned Throughput Units)\n- Reserved capacity; predictable latency\n- Hourly: ~$1\u002FPTU\u002Fhr (GPT-4o Global, Jan 2025)\n- Monthly reservation: up to 64% off hourly\n- 1-year reservation: up to 70% off (~$0.30\u002FPTU\u002Fhr)\n- Minimums: 15 PTU (Global\u002FData Zone, increments of 5), 50 PTU (Regional, increments of 50)\n- PTU sizing depends on output:input ratios (gpt-5: 1 output = 8 input tokens; gpt-4.1: 1 output = 4 input)\n- **Best practice**: deploy first, then buy the reservation — reservations guarantee discount, not capacity\n- Cached tokens count 0% toward PTU utilization (100% off on Provisioned)\n\n### Break-Even: PTU vs PAYG\n- PTU generally wins above ~50% sustained utilization and ~150–200M tokens\u002Fmonth on GPT-4o\n- This is a practitioner rule-of-thumb — not a single official Microsoft figure\n- Bursty workloads may justify PTU earlier than the token volume suggests (for latency predictability)\n\n### Batch API\n- **50% off** Global Standard pricing\n- Async, 24h SLA (often 1–6h in practice)\n- Up to 50K requests \u002F 200MB per input file\n- **Ideal for**: evals, nightly summarization, classification queues, embedding refreshes\n\n### Azure Credits Warning\n- Microsoft for Startups credits (up to $150K) cover only \"models sold directly by Azure\" (Azure OpenAI)\n- **Does NOT cover** third-party Marketplace models (Anthropic Claude, Meta Llama via Marketplace, etc.) — a documented billing trap that hit ≥20 startups with surprise invoices in early 2026\n- Filter the catalog by \"Direct from Azure\" to stay covered\n- Billing data lags 24–72h\n\n---\n\n## PTU Spillover (GA August 2025)\n\nRoutes PTU overage to a Standard deployment on non-200 responses (429 PTU-exhausted; 400 long-context >128K on gpt-4.1 PTU; 500\u002F503).\n\n**Enable via:**\n- `spilloverDeploymentName` (all requests)\n- `x-ms-spillover-deployment` header (per-request)\n\n**Billing:** PTU requests = hourly only; spilled requests = standard token rates.\n\n**Pattern**: size PTU for average load; spill peaks to PAYG. Monitor by splitting `Azure OpenAI Requests` metric by `ModelDeploymentName` + `StatusCode`.\n\n---\n\n## Prompt Caching — The Cache Golden Rule\n\n**Stable content first, dynamic content last.**\n\nOrder:\n1. System prompt (most stable)\n2. Tool definitions\n3. Static documents\u002Fcorpus\n4. Conversation history (older first)\n5. Current user message (most dynamic, last)\n\n**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%.\n\n### Azure\u002FOpenAI Caching\n- Automatic; no opt-in required\n- ~50% input discount (some 2026 sources cite up to 90% on newer families); no write penalty\n- Minimum: ≥1,024 tokens with identical first 1,024-token prefix\n- Cache hits accrue every 128 tokens after the initial 1,024\n- Verify via `cached_tokens` in `prompt_tokens_details`\n- In-memory caches: clear after 5–10 min of inactivity (max 1h)\n- GPT-4.1 \u002F GPT-5 family: extended retention up to 24h via `prompt_cache_retention: \"24h\"`\n- Use `prompt_cache_key` to improve routing\u002Fhit rate\n- Regional\u002Fmodel-version splits do NOT share caches\n\n### Anthropic Caching\n- Explicit `cache_control` breakpoints (≤4 per request)\n- Cache read = 0.1× input cost (90% off)\n- Cache write = 1.25× (5-min TTL) or 2× (1-hr TTL)\n- Break-even: ~2–3 cache reads per write\n- Expanded to a 5M-token cache\n- Real-world result: one developer cut $8,000→$800\u002Fmonth on a RAG system\n\n### Google Gemini Caching\n- Explicit user-managed cache objects with multi-day TTLs\n\n### Caveats\n- Tool-definition churn invalidates the tool-list cache\n- Compacting conversation history destroys its cached prefix\n\n---\n\n## Context Window Engineering\n\n### Token Budget Allocation\n**Token budget is a first-class design constraint.** Allocate explicit budgets per component:\n- System prompt\n- Tool definitions\n- Conversation history\n- Retrieved context (RAG)\n- Output headroom (especially for reasoning models)\n\nOptimize for **cost-per-task**, not tokens-saved-in-isolation.\n\n### Conversation History Management (Cost Tiers)\n1. **Naive** (full history): linear cost growth — only for short sessions\n2. **Sliding window**: keep last N turns\n3. **Rolling summarization** (MapReduce): summarize old turns, keep recent full\n4. **Embedding-based selective retention**: retrieve most-relevant past turns\n5. **Hybrid**: recent full + rolling summary + pinned facts\n6. **External memory** (MemGPT\u002FLetta): LLM-managed memory tiers; Cosmos DB\u002FRedis\u002FAI Search as backing store\n\nStore session state in Azure Cosmos DB or Azure Cache for Redis. Compact conversation history infrequently at predictable boundaries (compacting breaks the stable cache prefix).\n\n### LLMLingua Prompt Compression (Microsoft Research)\n- **LLMLingua** (arXiv 2310.05736, EMNLP 2023): up to 20× compression with only ~1.5 point performance drop\n- **LLMLingua-2**: 3–6× faster than LLMLingua-1; task-agnostic\n- **LongLLMLingua**: improves RAG by up to 21.4% using only 1\u002F4 of the tokens\n- Stacks with caching — cache the compressed prompt\n- Use when: long-doc RAG with many retrieved passages; cost-sensitive pipelines; large static context\n\n### \"Lost in the Middle\"\nPer 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.\n\n---\n\n## Prompt & Context Compression (Provider-Agnostic)\n\nCaching 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.\n\n### The Counterintuitive Research Consensus\n**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.\n\n### Compression Libraries\n- **LLMLingua \u002F LongLLMLingua \u002F LLMLingua-2** — see the LLMLingua subsection above. `pip install llmlingua`; stacks with caching (cache the compressed prompt).\n- **RECOMP** (arXiv 2310.04408): \"Retrieve, Compress, Prepend\" for RAG. Extractive + abstractive compressors to **~6%** of original; emits an empty summary on irrelevant docs (selective augmentation). Can over-compress on multi-hop queries.\n- **Selective Context** (EMNLP 2023): self-information pruning via a base LM; process 2× more content, save 40% memory\u002FGPU. `pip install selective-context`.\n- **Soft-prompt \u002F learned** (need fine-tuning + weight access): Gist tokens (up to 26×, NeurIPS 2023), AutoCompressor (~30:1), ICAE (512→32\u002F64\u002F128 memory tokens).\n- **PCToolkit** bundles Selective Context, LLMLingua, LongLLMLingua, SCRL, KiS as plug-and-play.\n\n### Caveman \u002F Telegraphic Prompting — Oversold\nStripping 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\u002Fcontext 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.\n\n### Serialization Format Choice (20–80% Token Swing)\nRoughly **TOON \u003C Markdown \u003C YAML \u003C compact JSON \u003C pretty JSON \u003C 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\u002Firregular 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%.\n\n### Output Verbosity Control\n- **Concise CoT** (arXiv 2401.05618): −48.70% response length, −22.67% per-token cost; watch a −27.69% accuracy hit on GPT-3.5 math.\n- **Chain-of-Draft** (~5 words\u002Fstep, arXiv 2502.18600): as little as **7.6% of CoT tokens** while matching\u002Fbeating accuracy; on Claude 3.5 Sonnet's sports task, 189.4→14.3 output tokens (−92.4%) with accuracy rising 93.2%→97.3%.\n- **Structured output does NOT save tokens** — JSON adds ~40% over free text; constrained decoding adds schema tokens + 10–30% latency. It guards weak models (Qwen2.5-Coder-7B 0%→75%) but degrades strong ones (GPT-5 extraction 86.9%→70% on complex schemas). For reasoning: two-step (free-form think → constrained format). See Structured Outputs below for the Azure API specifics.\n\n---\n\n## Model Routing & Cascades\n\n**The single highest-ROI lever.** Task-to-tier mapping:\n\n| Task type | Recommended tier |\n|---|---|\n| Classification, extraction, simple formatting | Nano\u002FPhi-4-class |\n| Chat, summarization, standard Q&A | Mini-class |\n| Complex reasoning, code refactoring, multi-step analysis | Frontier\u002Freasoning |\n\n### RouteLLM (UC Berkeley\u002FAnyscale\u002FCanva, ICLR 2025)\n- Matrix-factorization routing between strong\u002Fweak models\n- Achieves 95% of GPT-4 performance using 26% GPT-4 calls (~48% cheaper)\n- With LLM-judge-augmented training data: 14% of total calls (75% cheaper)\n- Routers generalize to new model pairs without retraining\n\n**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.\n\n### Implementation Options\n- Rule-based: query length, keyword triggers, explicit complexity signals\n- Classifier-based: fine-tuned on your traffic\n- RouteLLM: research-grade, open-source\n- Semantic Router: embedding-based intent classification\n\n---\n\n## APIM AI Gateway — Reference Architecture\n\n**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.\n\n### Five AI-Gateway Policies\n| Policy | Function |\n|---|---|\n| `llm-token-limit` | Per-key TPM\u002Fquota enforcement with prompt-token pre-calculation |\n| `llm-emit-token-metric` | Per-consumer token metrics to App Insights (up to 5 custom dimensions) |\n| `llm-semantic-cache-lookup` \u002F `store` | Redis-backed vector semantic cache |\n| `llm-content-safety` | Azure Content Safety integration |\n| Backend pool + circuit breaker | Priority\u002Fweighted routing + circuit breakers per backend |\n\n### Backend Pool Pattern\nPTU backend (priority 1) → PAYG Standard (priority 2 \u002F overflow). Circuit breaker per backend. `retry` policy honoring `Retry-After`.\n\n### Reference Implementation\nAzure-Samples\u002Fapim-genai-gateway-toolkit\n\n### Cost Attribution\n- Subscription keys map to cost attribution\n- JWT enables per-user attribution\n- Up to 5 custom dimensions on `llm-emit-token-metric`\n- Note Azure Monitor's 10-dimension\u002F50,000-time-series limits when designing custom dimensions\n\n---\n\n## Semantic Caching\n\n**APIM + Redis Enterprise pattern** for FAQ\u002Fsupport bots:\n- Embed query → vector search cache → return if cosine similarity above threshold (~0.95)\n- Add `rate-limit` after lookup to protect backend if cache is unavailable\n- Tune `score-threshold` (lower = stricter match)\n\n**Output cache** (simple TTL) cuts FAQ\u002Fdeterministic traffic 30–80%.\n\n**When NOT to use semantic caching**: personalized queries, real-time data, high-diversity query patterns.\n\n---\n\n## Advanced Prompt Engineering\n\n### System Prompt Structure\n```\n[Role and objective]\n[Constraints and rules — positive instructions (\"always do X\") outperform negative]\n[Output format specification]\n[Examples if needed]\n```\n\n### Reasoning Techniques (with cost trade-offs)\n| Technique | Cost | When to use |\n|---|---|---|\n| Zero-shot CoT (\"think step by step\") | Moderate (adds output tokens) | Multi-step tasks on non-reasoning models |\n| Few-shot CoT (3–8 exemplars) | Higher (adds input tokens) | Complex tasks needing demonstrated format |\n| Self-consistency (sample N, vote) | N× cost | High-stakes decisions |\n| Tree of Thoughts (branching) | Expensive | Deep search\u002Fplanning problems |\n| Dedicated reasoning model (o-series) | High but predictable | Genuine multi-step reasoning |\n\n**Rule**: use dedicated reasoning models for genuine multi-step problems; use CoT-prompted standard models when you need to see\u002Fcontrol the reasoning and cost matters.\n\n### Structured Outputs\n**Prefer Structured Outputs (JSON Schema, `strict: true`)** over legacy JSON mode — guarantees schema adherence, not just valid JSON.\n\nAzure constraints:\n- All fields must be `required` (emulate optional via `[\"type\",\"null\"]`)\n- `additionalProperties: false`\n- ≤100 properties, ≤5 nesting levels\n- Not compatible with `parallel_tool_calls` (set to false) or On Your Data\u002FAssistants\n- Supported on: gpt-4o (2024-08-06+), gpt-4.1 family, o1\u002Fo3\u002Fo3-mini\u002Fo4-mini\n\n### Sampling Parameters\n- Temperature 0 + `seed` for deterministic\u002Ffactual outputs\n- Higher temperature\u002Ftop-p for creative generation\n- Always set `max_tokens` — no cap means unbounded cost exposure\n\n### Dynamic Few-Shot\nRetrieve similar examples via embedding search rather than hardcoding — enables more relevant examples without growing the static system prompt.\n\n### Prompt-as-Code\n- Git-version prompts\n- Test against golden eval sets before deploying\n- Store prompts in Azure App Configuration for runtime updates without redeploy\n- A\u002FB test prompt changes with proper statistical significance\n\n---\n\n## Tool Calling Cost Optimization\n\n- **Write terse tool descriptions** — verbose schemas waste input tokens\n- **Limit tools** — performance degrades past ~10 tools per call\n- **Progressive\u002Fintent-based tool exposure** — send only relevant tools per query type\n- Use `parallel_tool_calls` for independent calls (reduces round-trips)\n- Cache tool definitions in the system prefix (they're stable → high cache hit rate)\n- Fine-tuning with tool examples can replace verbose tool definitions at inference time\n\n---\n\n## Fine-Tuning for Cost (Distillation Pattern)\n\n1. Set `store: true` on production frontier-model calls to capture completions\n2. Accumulate hundreds–thousands of high-quality examples (minimum 10 stored completions)\n3. Fine-tune a smaller model (e.g., GPT-4.1-nano) on teacher's outputs\n4. Validate quality delta is acceptable before routing production traffic\n\n**Expected result**: ~90% quality at ~10% cost.\n\n**Azure fine-tuning specifics:**\n- Training files: JSONL format; per-token training fee + hourly hosting cost for deployed custom models\n- **\"Fine-tune zombie\" trap**: delete unused fine-tuned deployments to avoid hourly hosting cost\n- Supported: gpt-4o, gpt-4o-mini, gpt-4.1, gpt-4.1-nano, o4-mini (Reinforcement Fine-Tuning), Llama 4 Scout\n- Global Standard is the default deployment for new fine-tunes (cheaper than regional)\n- Prompt caching works on fine-tuned models\n\n---\n\n## Embeddings Cost Optimization\n\n| Model | Dimensions | Price\u002F1M | MTEB | Notes |\n|---|---|---|---|---|\n| `text-embedding-3-small` | 1,536 | ~$0.02 | 62.3 | OpenAI-ecosystem default; 5× cheaper than ada-002 |\n| `text-embedding-3-large` | 3,072 | ~$0.13 | 64.6 | ~2.3 MTEB points better; Matryoshka-truncatable |\n| `ada-002` | 1,536 | ~$0.10 | 61.0 | Legacy; replace with 3-small |\n\n**Matryoshka**: store full-dim once; truncate per index (768 dims halves storage). Standard in modern models.\n\n**Cost reduction rules:**\n- Cache static-document embeddings by content hash — never re-embed unchanged docs\n- Cache common-query embeddings\n- Quantize stored vectors (fp32→fp16\u002Fint8)\n- Batch embedding requests to respect rate limits\n- Use ANN over exact search at scale\n\n---\n\n## Rate Limiting & 429 Handling\n\n| Error | Meaning | Response |\n|---|---|---|\n| 429 | TPM\u002FRPM quota or PTU 100% utilized | Respect `Retry-After`; exponential backoff with jitter |\n| 503 | Capacity\u002Fserver issue | Backoff + failover to another deployment |\n\nAzure returns `x-ratelimit-*` headers. The APIM circuit breaker handles this automatically at the gateway layer.\n\n---\n\n## Azure Monitor Metrics Reference\n\n**Key metrics to track:**\n- `ProcessedPromptTokens`, `GeneratedTokens`, `TokenTransaction` (Processed Inference = prompt+generated)\n- `InputTokens`, `OutputTokens`, `TotalTokens`\n- `ProvisionedUtilizationV2` (PTU utilization)\n- `AzureOpenAIContextTokensCacheMatchRate` (`Prompt Token Cache Match Rate`)\n- `FineTunedTrainingHours`\n- Latency: Time to Response, Time to Last Byte, Time Between Tokens — **do NOT use the legacy Cognitive Services `Latency` metric**\n\n**Dimensions**: split by `ModelDeploymentName` \u002F `ModelName`.\n\n**Export**: diagnostic settings → Log Analytics (KQL); build workbooks\u002FManaged Grafana dashboards.\n\n**`llm-emit-token-metric` policy** supports OpenAI, Anthropic Messages, and Google Vertex schemas.\n\n---\n\n## Cost Unit Economics\n\n**Build cost-per-task, not cost-per-token.** RAG cost breakdown:\n- Embedding (one-time per document)\n- Storage\n- Retrieval query embedding (per query)\n- Generation (retrieved context dominates — often 80%+ of per-query cost)\n\n**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:\n- Per-user\u002Fsession\u002Ffeature anomaly detection\n- Per-feature token budgets\n- Hard per-run token\u002Fcost ceilings\n\n---\n\n## Real-World Optimization Recipes\n\n| Recipe | Expected savings | Requirement |\n|---|---|---|\n| **R1 — Model routing** | 60–80% on routine queries | Quality eval confirming \u003C1–2% delta |\n| **R2 — Prompt caching** | 40–50% on input tokens | Stable ≥1,024 token prefix; verify via `cached_tokens` |\n| **R3 — Semantic caching** | 30–80% on repeat traffic | Low query diversity; non-personalized\u002Fnon-realtime answers |\n| **R4 — Batch API** | 50% at 24h SLA | Async workloads (evals, nightly processing, embedding refresh) |\n| **R5 — LLMLingua compression** | Up to 20× token reduction | Long-doc RAG; accept ~1.5 point quality drop |\n| **R6 — Distillation** | ~90% quality at ~10% cost | High-volume domain-specific tasks; hundreds of teacher completions |\n| **R7 — PTU right-sizing** | Up to 70% vs hourly | 30–60 days telemetry; P95 hourly throughput; sustained >50% utilization |\n\n**Stack order**: Instrument first → quick wins (caching + batch) → routing → semantic cache → PTU commitment → distillation.\n\n---\n\n## Staged Implementation Roadmap\n\n**Stage 1 — Instrument before optimizing (week 1).** Deploy APIM as AI gateway with `llm-emit-token-metric` (dimensions: team\u002Fapp\u002Fuser). 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\u002Fteam.\n\n**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.\n\n**Stage 3 — Model routing (weeks 4–6).** Default to mini\u002Fnano-class; build rule- or classifier-based router escalating on complexity\u002Flow-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.\n\n**Stage 4 — Semantic caching + compression (weeks 6–8).** Add APIM semantic cache (Redis Enterprise) for FAQ\u002Fsupport traffic. Apply LLMLingua to long-doc RAG passages. Threshold: only where query diversity is low and answers aren't personalized\u002Freal-time.\n\n**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.\n\n**Stage 6 — Distillation (ongoing).** Set `store: true` for high-volume domain-specific tasks. Accumulate hundreds–thousands of frontier completions. Fine-tune nano\u002Fmini behind a quality gate. Delete idle fine-tuned deployments.\n\n**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.\n\n---\n\n## Anti-Patterns\n\n1. **Full history every turn** — linear cost growth; use sliding window or summarization\n2. **Dynamic content before static** (e.g., timestamp in system prompt) — breaks prompt caching\n3. **Frontier model for trivial tasks** — use routing\n4. **Verbose tool schemas** — wastes input tokens; cache them in stable prefix\n5. **Sequential calls for independent subtasks** — parallelize with `parallel_tool_calls` or asyncio\n6. **JSON mode over Structured Outputs** — use `strict: true` JSON Schema instead\n7. **No `max_tokens` set** — unbounded cost exposure\n8. **Re-embedding unchanged documents** — cache by content hash\n9. **Unsanitized injection vectors** — RAG retrieved content can carry injection payloads\n10. **Optimizing without evals** — cost savings are assumed quality-neutral; they are not\n11. **Ignoring reasoning token billing** — reconcile against API `usage` object and Azure invoice\n12. **Using Marketplace models without checking billing coverage** — not covered by Azure credits\u002Fsponsorship\n","# LLM Cost Optimization, Prompt Engineering & Context Engineering — Azure Reference\n\n## The Three Core Levers (in ROI order)\n\n1. **Model routing** — route routine traffic to cheaper models, escalate only uncertain requests (60–80% cost reduction on routine queries per Microsoft guidance; validated RouteLLM benchmark: 95% GPT-4 quality at 26% GPT-4 calls, ~48% cheaper)\n2. **Prompt caching** — restructure prompts for a stable prefix (Azure: ~50% off input; Anthropic: 90% off cache reads)\n3. **Deployment pricing** — Batch API (50% off), PTU reservations (up to 70% off hourly), right-tier matching\n\n**Governance is architecture, not monitoring.** Without per-request token logging and cost attribution, optimization is guesswork.\n\n---\n\n## Token Economics Fundamentals\n\n### Tokenization\n- **`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)\n- **`cl100k_base`** (GPT-4\u002F3.5\u002Fada-002): 100K-token vocabulary\n- Always resolve encodings with `tiktoken.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.\n- The only ground truth for billing is the API's `usage` object (includes `cached_tokens` and `reasoning_tokens` breakdowns)\n\n### Input\u002FOutput Pricing Asymmetry — **Architectural Implication**\n- Input (prefill): one parallel forward pass over all tokens\n- Output (decode): one sequential forward pass **per token** → output costs 3–8× input\n- Azure GPT-4o example: input $2.50\u002F1M vs output $10\u002F1M (4×)\n- **Design implication**: minimize output length for cost-sensitive paths; be explicit about output length in the prompt\n\n### Reasoning Tokens\n- Billed at **output rates** (expensive)\n- Invisible in the response body; surfaced in `output_tokens_details.reasoning_tokens`\n- Do NOT persist across turns\n- Consume the `max_tokens` budget — a complex task can burn 8,000+ reasoning tokens before a 300-token answer\n- **Anti-pattern trap**: setting `max_tokens` too low yields `finish_reason: \"length\"` with empty content because reasoning consumed the entire budget\n- **Rule**: set `max_tokens` to ≥4× expected visible output for reasoning models\n- Track reasoning tokens as a first-class metric\n- Worth it for genuine multi-step reasoning (math, code, legal analysis); wasteful on pipelines expecting short outputs\n\n---\n\n## Azure Pricing Models\n\n### Standard (PAYG)\n- Per-token billing; quota in TPM\u002FRPM\n- **Global Standard**: routed worldwide, highest throughput, lowest rate\n- **Data Zone Standard**: US\u002FEU data residency\n- **Regional Standard**: single region, highest per-token cost\n- Prompt caching and Batch discounts apply automatically\n\n### PTU (Provisioned Throughput Units)\n- Reserved capacity; predictable latency\n- Hourly: ~$1\u002FPTU\u002Fhr (GPT-4o Global, Jan 2025)\n- Monthly reservation: up to 64% off hourly\n- 1-year reservation: up to 70% off (~$0.30\u002FPTU\u002Fhr)\n- Minimums: 15 PTU (Global\u002FData Zone, increments of 5), 50 PTU (Regional, increments of 50)\n- PTU sizing depends on output:input ratios (gpt-5: 1 output = 8 input tokens; gpt-4.1: 1 output = 4 input)\n- **Best practice**: deploy first, then buy the reservation — reservations guarantee discount, not capacity\n- Cached tokens count 0% toward PTU utilization (100% off on Provisioned)\n\n### Break-Even: PTU vs PAYG\n- PTU generally wins above ~50% sustained utilization and ~150–200M tokens\u002Fmonth on GPT-4o\n- This is a practitioner rule-of-thumb — not a single official Microsoft figure\n- Bursty workloads may justify PTU earlier than the token volume suggests (for latency predictability)\n\n### Batch API\n- **50% off** Global Standard pricing\n- Async, 24h SLA (often 1–6h in practice)\n- Up to 50K requests \u002F 200MB per input file\n- **Ideal for**: evals, nightly summarization, classification queues, embedding refreshes\n\n### Azure Credits Warning\n- Microsoft for Startups credits (up to $150K) cover only \"models sold directly by Azure\" (Azure OpenAI)\n- **Does NOT cover** third-party Marketplace models (Anthropic Claude, Meta Llama via Marketplace, etc.) — a documented billing trap that hit ≥20 startups with surprise invoices in early 2026\n- Filter the catalog by \"Direct from Azure\" to stay covered\n- Billing data lags 24–72h\n\n---\n\n## PTU Spillover (GA August 2025)\n\nRoutes PTU overage to a Standard deployment on non-200 responses (429 PTU-exhausted; 400 long-context >128K on gpt-4.1 PTU; 500\u002F503).\n\n**Enable via:**\n- `spilloverDeploymentName` (all requests)\n- `x-ms-spillover-deployment` header (per-request)\n\n**Billing:** PTU requests = hourly only; spilled requests = standard token rates.\n\n**Pattern**: size PTU for average load; spill peaks to PAYG. Monitor by splitting `Azure OpenAI Requests` metric by `ModelDeploymentName` + `StatusCode`.\n\n---\n\n## Prompt Caching — The Cache Golden Rule\n\n**Stable content first, dynamic content last.**\n\nOrder:\n1. System prompt (most stable)\n2. Tool definitions\n3. Static documents\u002Fcorpus\n4. Conversation history (older first)\n5. Current user message (most dynamic, last)\n\n**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%.\n\n### Azure\u002FOpenAI Caching\n- Automatic; no opt-in required\n- ~50% input discount (some 2026 sources cite up to 90% on newer families); no write penalty\n- Minimum: ≥1,024 tokens with identical first 1,024-token prefix\n- Cache hits accrue every 128 tokens after the initial 1,024\n- Verify via `cached_tokens` in `prompt_tokens_details`\n- In-memory caches: clear after 5–10 min of inactivity (max 1h)\n- GPT-4.1 \u002F GPT-5 family: extended retention up to 24h via `prompt_cache_retention: \"24h\"`\n- Use `prompt_cache_key` to improve routing\u002Fhit rate\n- Regional\u002Fmodel-version splits do NOT share caches\n\n### Anthropic Caching\n- Explicit `cache_control` breakpoints (≤4 per request)\n- Cache read = 0.1× input cost (90% off)\n- Cache write = 1.25× (5-min TTL) or 2× (1-hr TTL)\n- Break-even: ~2–3 cache reads per write\n- Expanded to a 5M-token cache\n- Real-world result: one developer cut $8,000→$800\u002Fmonth on a RAG system\n\n### Google Gemini Caching\n- Explicit user-managed cache objects with multi-day TTLs\n\n### Caveats\n- Tool-definition churn invalidates the tool-list cache\n- Compacting conversation history destroys its cached prefix\n\n---\n\n## Context Window Engineering\n\n### Token Budget Allocation\n**Token budget is a first-class design constraint.** Allocate explicit budgets per component:\n- System prompt\n- Tool definitions\n- Conversation history\n- Retrieved context (RAG)\n- Output headroom (especially for reasoning models)\n\nOptimize for **cost-per-task**, not tokens-saved-in-isolation.\n\n### Conversation History Management (Cost Tiers)\n1. **Naive** (full history): linear cost growth — only for short sessions\n2. **Sliding window**: keep last N turns\n3. **Rolling summarization** (MapReduce): summarize old turns, keep recent full\n4. **Embedding-based selective retention**: retrieve most-relevant past turns\n5. **Hybrid**: recent full + rolling summary + pinned facts\n6. **External memory** (MemGPT\u002FLetta): LLM-managed memory tiers; Cosmos DB\u002FRedis\u002FAI Search as backing store\n\nStore session state in Azure Cosmos DB or Azure Cache for Redis. Compact conversation history infrequently at predictable boundaries (compacting breaks the stable cache prefix).\n\n### LLMLingua Prompt Compression (Microsoft Research)\n- **LLMLingua** (arXiv 2310.05736, EMNLP 2023): up to 20× compression with only ~1.5 point performance drop\n- **LLMLingua-2**: 3–6× faster than LLMLingua-1; task-agnostic\n- **LongLLMLingua**: improves RAG by up to 21.4% using only 1\u002F4 of the tokens\n- Stacks with caching — cache the compressed prompt\n- Use when: long-doc RAG with many retrieved passages; cost-sensitive pipelines; large static context\n\n### \"Lost in the Middle\"\nPer 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.\n\n---\n\n## Prompt & Context Compression (Provider-Agnostic)\n\nCaching 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.\n\n### The Counterintuitive Research Consensus\n**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.\n\n### Compression Libraries\n- **LLMLingua \u002F LongLLMLingua \u002F LLMLingua-2** — see the LLMLingua subsection above. `pip install llmlingua`; stacks with caching (cache the compressed prompt).\n- **RECOMP** (arXiv 2310.04408): \"Retrieve, Compress, Prepend\" for RAG. Extractive + abstractive compressors to **~6%** of original; emits an empty summary on irrelevant docs (selective augmentation). Can over-compress on multi-hop queries.\n- **Selective Context** (EMNLP 2023): self-information pruning via a base LM; process 2× more content, save 40% memory\u002FGPU. `pip install selective-context`.\n- **Soft-prompt \u002F learned** (need fine-tuning + weight access): Gist tokens (up to 26×, NeurIPS 2023), AutoCompressor (~30:1), ICAE (512→32\u002F64\u002F128 memory tokens).\n- **PCToolkit** bundles Selective Context, LLMLingua, LongLLMLingua, SCRL, KiS as plug-and-play.\n\n### Caveman \u002F Telegraphic Prompting — Oversold\nStripping 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\u002Fcontext 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.\n\n### Serialization Format Choice (20–80% Token Swing)\nRoughly **TOON \u003C Markdown \u003C YAML \u003C compact JSON \u003C pretty JSON \u003C 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\u002Firregular 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%.\n\n### Output Verbosity Control\n- **Concise CoT** (arXiv 2401.05618): −48.70% response length, −22.67% per-token cost; watch a −27.69% accuracy hit on GPT-3.5 math.\n- **Chain-of-Draft** (~5 words\u002Fstep, arXiv 2502.18600): as little as **7.6% of CoT tokens** while matching\u002Fbeating accuracy; on Claude 3.5 Sonnet's sports task, 189.4→14.3 output tokens (−92.4%) with accuracy rising 93.2%→97.3%.\n- **Structured output does NOT save tokens** — JSON adds ~40% over free text; constrained decoding adds schema tokens + 10–30% latency. It guards weak models (Qwen2.5-Coder-7B 0%→75%) but degrades strong ones (GPT-5 extraction 86.9%→70% on complex schemas). For reasoning: two-step (free-form think → constrained format). See Structured Outputs below for the Azure API specifics.\n\n---\n\n## Model Routing & Cascades\n\n**The single highest-ROI lever.** Task-to-tier mapping:\n\n| Task type | Recommended tier |\n|---|---|\n| Classification, extraction, simple formatting | Nano\u002FPhi-4-class |\n| Chat, summarization, standard Q&A | Mini-class |\n| Complex reasoning, code refactoring, multi-step analysis | Frontier\u002Freasoning |\n\n### RouteLLM (UC Berkeley\u002FAnyscale\u002FCanva, ICLR 2025)\n- Matrix-factorization routing between strong\u002Fweak models\n- Achieves 95% of GPT-4 performance using 26% GPT-4 calls (~48% cheaper)\n- With LLM-judge-augmented training data: 14% of total calls (75% cheaper)\n- Routers generalize to new model pairs without retraining\n\n**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.\n\n### Implementation Options\n- Rule-based: query length, keyword triggers, explicit complexity signals\n- Classifier-based: fine-tuned on your traffic\n- RouteLLM: research-grade, open-source\n- Semantic Router: embedding-based intent classification\n\n---\n\n## APIM AI Gateway — Reference Architecture\n\n**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.\n\n### Five AI-Gateway Policies\n| Policy | Function |\n|---|---|\n| `llm-token-limit` | Per-key TPM\u002Fquota enforcement with prompt-token pre-calculation |\n| `llm-emit-token-metric` | Per-consumer token metrics to App Insights (up to 5 custom dimensions) |\n| `llm-semantic-cache-lookup` \u002F `store` | Redis-backed vector semantic cache |\n| `llm-content-safety` | Azure Content Safety integration |\n| Backend pool + circuit breaker | Priority\u002Fweighted routing + circuit breakers per backend |\n\n### Backend Pool Pattern\nPTU backend (priority 1) → PAYG Standard (priority 2 \u002F overflow). Circuit breaker per backend. `retry` policy honoring `Retry-After`.\n\n### Reference Implementation\nAzure-Samples\u002Fapim-genai-gateway-toolkit\n\n### Cost Attribution\n- Subscription keys map to cost attribution\n- JWT enables per-user attribution\n- Up to 5 custom dimensions on `llm-emit-token-metric`\n- Note Azure Monitor's 10-dimension\u002F50,000-time-series limits when designing custom dimensions\n\n---\n\n## Semantic Caching\n\n**APIM + Redis Enterprise pattern** for FAQ\u002Fsupport bots:\n- Embed query → vector search cache → return if cosine similarity above threshold (~0.95)\n- Add `rate-limit` after lookup to protect backend if cache is unavailable\n- Tune `score-threshold` (lower = stricter match)\n\n**Output cache** (simple TTL) cuts FAQ\u002Fdeterministic traffic 30–80%.\n\n**When NOT to use semantic caching**: personalized queries, real-time data, high-diversity query patterns.\n\n---\n\n## Advanced Prompt Engineering\n\n### System Prompt Structure\n```\n[Role and objective]\n[Constraints and rules — positive instructions (\"always do X\") outperform negative]\n[Output format specification]\n[Examples if needed]\n```\n\n### Reasoning Techniques (with cost trade-offs)\n| Technique | Cost | When to use |\n|---|---|---|\n| Zero-shot CoT (\"think step by step\") | Moderate (adds output tokens) | Multi-step tasks on non-reasoning models |\n| Few-shot CoT (3–8 exemplars) | Higher (adds input tokens) | Complex tasks needing demonstrated format |\n| Self-consistency (sample N, vote) | N× cost | High-stakes decisions |\n| Tree of Thoughts (branching) | Expensive | Deep search\u002Fplanning problems |\n| Dedicated reasoning model (o-series) | High but predictable | Genuine multi-step reasoning |\n\n**Rule**: use dedicated reasoning models for genuine multi-step problems; use CoT-prompted standard models when you need to see\u002Fcontrol the reasoning and cost matters.\n\n### Structured Outputs\n**Prefer Structured Outputs (JSON Schema, `strict: true`)** over legacy JSON mode — guarantees schema adherence, not just valid JSON.\n\nAzure constraints:\n- All fields must be `required` (emulate optional via `[\"type\",\"null\"]`)\n- `additionalProperties: false`\n- ≤100 properties, ≤5 nesting levels\n- Not compatible with `parallel_tool_calls` (set to false) or On Your Data\u002FAssistants\n- Supported on: gpt-4o (2024-08-06+), gpt-4.1 family, o1\u002Fo3\u002Fo3-mini\u002Fo4-mini\n\n### Sampling Parameters\n- Temperature 0 + `seed` for deterministic\u002Ffactual outputs\n- Higher temperature\u002Ftop-p for creative generation\n- Always set `max_tokens` — no cap means unbounded cost exposure\n\n### Dynamic Few-Shot\nRetrieve similar examples via embedding search rather than hardcoding — enables more relevant examples without growing the static system prompt.\n\n### Prompt-as-Code\n- Git-version prompts\n- Test against golden eval sets before deploying\n- Store prompts in Azure App Configuration for runtime updates without redeploy\n- A\u002FB test prompt changes with proper statistical significance\n\n---\n\n## Tool Calling Cost Optimization\n\n- **Write terse tool descriptions** — verbose schemas waste input tokens\n- **Limit tools** — performance degrades past ~10 tools per call\n- **Progressive\u002Fintent-based tool exposure** — send only relevant tools per query type\n- Use `parallel_tool_calls` for independent calls (reduces round-trips)\n- Cache tool definitions in the system prefix (they're stable → high cache hit rate)\n- Fine-tuning with tool examples can replace verbose tool definitions at inference time\n\n---\n\n## Fine-Tuning for Cost (Distillation Pattern)\n\n1. Set `store: true` on production frontier-model calls to capture completions\n2. Accumulate hundreds–thousands of high-quality examples (minimum 10 stored completions)\n3. Fine-tune a smaller model (e.g., GPT-4.1-nano) on teacher's outputs\n4. Validate quality delta is acceptable before routing production traffic\n\n**Expected result**: ~90% quality at ~10% cost.\n\n**Azure fine-tuning specifics:**\n- Training files: JSONL format; per-token training fee + hourly hosting cost for deployed custom models\n- **\"Fine-tune zombie\" trap**: delete unused fine-tuned deployments to avoid hourly hosting cost\n- Supported: gpt-4o, gpt-4o-mini, gpt-4.1, gpt-4.1-nano, o4-mini (Reinforcement Fine-Tuning), Llama 4 Scout\n- Global Standard is the default deployment for new fine-tunes (cheaper than regional)\n- Prompt caching works on fine-tuned models\n\n---\n\n## Embeddings Cost Optimization\n\n| Model | Dimensions | Price\u002F1M | MTEB | Notes |\n|---|---|---|---|---|\n| `text-embedding-3-small` | 1,536 | ~$0.02 | 62.3 | OpenAI-ecosystem default; 5× cheaper than ada-002 |\n| `text-embedding-3-large` | 3,072 | ~$0.13 | 64.6 | ~2.3 MTEB points better; Matryoshka-truncatable |\n| `ada-002` | 1,536 | ~$0.10 | 61.0 | Legacy; replace with 3-small |\n\n**Matryoshka**: store full-dim once; truncate per index (768 dims halves storage). Standard in modern models.\n\n**Cost reduction rules:**\n- Cache static-document embeddings by content hash — never re-embed unchanged docs\n- Cache common-query embeddings\n- Quantize stored vectors (fp32→fp16\u002Fint8)\n- Batch embedding requests to respect rate limits\n- Use ANN over exact search at scale\n\n---\n\n## Rate Limiting & 429 Handling\n\n| Error | Meaning | Response |\n|---|---|---|\n| 429 | TPM\u002FRPM quota or PTU 100% utilized | Respect `Retry-After`; exponential backoff with jitter |\n| 503 | Capacity\u002Fserver issue | Backoff + failover to another deployment |\n\nAzure returns `x-ratelimit-*` headers. The APIM circuit breaker handles this automatically at the gateway layer.\n\n---\n\n## Azure Monitor Metrics Reference\n\n**Key metrics to track:**\n- `ProcessedPromptTokens`, `GeneratedTokens`, `TokenTransaction` (Processed Inference = prompt+generated)\n- `InputTokens`, `OutputTokens`, `TotalTokens`\n- `ProvisionedUtilizationV2` (PTU utilization)\n- `AzureOpenAIContextTokensCacheMatchRate` (`Prompt Token Cache Match Rate`)\n- `FineTunedTrainingHours`\n- Latency: Time to Response, Time to Last Byte, Time Between Tokens — **do NOT use the legacy Cognitive Services `Latency` metric**\n\n**Dimensions**: split by `ModelDeploymentName` \u002F `ModelName`.\n\n**Export**: diagnostic settings → Log Analytics (KQL); build workbooks\u002FManaged Grafana dashboards.\n\n**`llm-emit-token-metric` policy** supports OpenAI, Anthropic Messages, and Google Vertex schemas.\n\n---\n\n## Cost Unit Economics\n\n**Build cost-per-task, not cost-per-token.** RAG cost breakdown:\n- Embedding (one-time per document)\n- Storage\n- Retrieval query embedding (per query)\n- Generation (retrieved context dominates — often 80%+ of per-query cost)\n\n**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:\n- Per-user\u002Fsession\u002Ffeature anomaly detection\n- Per-feature token budgets\n- Hard per-run token\u002Fcost ceilings\n\n---\n\n## Real-World Optimization Recipes\n\n| Recipe | Expected savings | Requirement |\n|---|---|---|\n| **R1 — Model routing** | 60–80% on routine queries | Quality eval confirming \u003C1–2% delta |\n| **R2 — Prompt caching** | 40–50% on input tokens | Stable ≥1,024 token prefix; verify via `cached_tokens` |\n| **R3 — Semantic caching** | 30–80% on repeat traffic | Low query diversity; non-personalized\u002Fnon-realtime answers |\n| **R4 — Batch API** | 50% at 24h SLA | Async workloads (evals, nightly processing, embedding refresh) |\n| **R5 — LLMLingua compression** | Up to 20× token reduction | Long-doc RAG; accept ~1.5 point quality drop |\n| **R6 — Distillation** | ~90% quality at ~10% cost | High-volume domain-specific tasks; hundreds of teacher completions |\n| **R7 — PTU right-sizing** | Up to 70% vs hourly | 30–60 days telemetry; P95 hourly throughput; sustained >50% utilization |\n\n**Stack order**: Instrument first → quick wins (caching + batch) → routing → semantic cache → PTU commitment → distillation.\n\n---\n\n## Staged Implementation Roadmap\n\n**Stage 1 — Instrument before optimizing (week 1).** Deploy APIM as AI gateway with `llm-emit-token-metric` (dimensions: team\u002Fapp\u002Fuser). 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\u002Fteam.\n\n**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.\n\n**Stage 3 — Model routing (weeks 4–6).** Default to mini\u002Fnano-class; build rule- or classifier-based router escalating on complexity\u002Flow-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.\n\n**Stage 4 — Semantic caching + compression (weeks 6–8).** Add APIM semantic cache (Redis Enterprise) for FAQ\u002Fsupport traffic. Apply LLMLingua to long-doc RAG passages. Threshold: only where query diversity is low and answers aren't personalized\u002Freal-time.\n\n**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.\n\n**Stage 6 — Distillation (ongoing).** Set `store: true` for high-volume domain-specific tasks. Accumulate hundreds–thousands of frontier completions. Fine-tune nano\u002Fmini behind a quality gate. Delete idle fine-tuned deployments.\n\n**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.\n\n---\n\n## Anti-Patterns\n\n1. **Full history every turn** — linear cost growth; use sliding window or summarization\n2. **Dynamic content before static** (e.g., timestamp in system prompt) — breaks prompt caching\n3. **Frontier model for trivial tasks** — use routing\n4. **Verbose tool schemas** — wastes input tokens; cache them in stable prefix\n5. **Sequential calls for independent subtasks** — parallelize with `parallel_tool_calls` or asyncio\n6. **JSON mode over Structured Outputs** — use `strict: true` JSON Schema instead\n7. **No `max_tokens` set** — unbounded cost exposure\n8. **Re-embedding unchanged documents** — cache by content hash\n9. **Unsanitized injection vectors** — RAG retrieved content can carry injection payloads\n10. **Optimizing without evals** — cost savings are assumed quality-neutral; they are not\n11. **Ignoring reasoning token billing** — reconcile against API `usage` object and Azure invoice\n12. **Using Marketplace models without checking billing coverage** — not covered by Azure credits\u002Fsponsorship\n",{"name":5,"description":7},"develop","ae32736a1aabddabca5d2c96d665aa0ebc7d8700","src\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fai-and-data\u002Fskills\u002Fllm-cost-optimization",3,"https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey","https:\u002F\u002Fthe-vibey-project.github.io\u002Fvibey\u002F","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project","https:\u002F\u002Fvibewithadam.matthewsteinberger.com","freedom for software engineers","2026-11-15 05:47:42",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add the-vibey-project\u002Fvibey --skill llm-cost-optimization",{"tool":40,"command":41},"bunx","bunx skills add the-vibey-project\u002Fvibey --skill llm-cost-optimization",{"tool":43,"command":44},"pnpm","pnpm dlx skills add the-vibey-project\u002Fvibey --skill llm-cost-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fai-and-data\u002Fskills\u002Fllm-cost-optimization\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7AT1FQJAE1FQYAMDTF490Y4","white-paper-writing","Use when writing white papers, technical reports, policy documents, thought leadership pieces, or any long-form authoritative document. Triggers on requests to write, structure, outline, or review white papers, technical reports, position papers, policy briefs, or evidence-driven arguments. Also use for B2B content marketing strategy, technical documentation requiring authority, academic-style reports, or any document that must educate while persuading. Use when someone asks \"how should I structure this\" for a long-form document.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fwhite-paper-writing\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7AT16BJRJJKK2MASXRZS76G","prose-technical-mechanics","Use when editing or writing prose at a technical\u002Fmechanical level: choosing between Anglo-Saxon and Latinate diction, placing information in topic vs stress positions, writing periodic vs cumulative sentences, handling sentence rhythm, punctuation as logic, transitions, paragraph structure, or phonesthetics. Use when someone wants to understand WHY prose works or doesn't, not just surface-level style advice. Triggers on word choice, sentence structure, emphasis, rhythm, diction, or any deep writing mechanics question.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-technical-mechanics\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7AT0W9HT0ZZ9Y287NW99MR3","prose-mechanics","Use when writing, editing, or analyzing prose style; when trying to avoid generic AI-sounding writing; when applying specific prose styles such as journalistic, academic, narrative, KJV biblical, Hemingway plain, Latinate\u002FJamesian, Orwellian, Augustan, Victorian, Early Modern (Bacon, Browne, Milton), or free indirect discourse; or when coaching someone on writing voice and mechanics. Triggers on any request to improve, analyze, or write in a specific prose style, to fix \"AI-sounding\" writing, to make prose more vivid or concrete, to vary sentence rhythm, or to understand how a particular writer achieves their effects.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-mechanics\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7AT0KR635JX66X2X6F3E2CP","narrative-structure","Use when structuring stories, pitches, presentations, white papers, or any persuasive narrative; analyzing the hero's journey in fiction or non-fiction; applying StoryBrand for business communication; designing narrative arcs for thought leadership; or understanding Vogler, Snyder, Propp, or Campbell frameworks. Triggers on any narrative structure, storytelling, pitch structure, StoryBrand, hero's journey, three-act structure, Freytag, Save the Cat, narrative arc, or \"how should I structure this story\u002Fpitch\u002Fpresentation\" request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fnarrative-structure\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AT0AKGW09NKKZDYBT8VRDE","legal-brief-writing","Use when writing legal briefs, motions, or any court filing; when analyzing judicial cognition and persuasion; when applying elite brief-writing techniques from Roberts, Clement, Kagan, Garner; or when structuring legal arguments for maximum persuasion. Also use for autistic\u002Fneurodivergent advocates who need to understand how their natural communication style maps to elite legal advocacy. Triggers on any legal writing, brief drafting, motion preparation, or legal argument structuring request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Flegal-brief-writing\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7AT00VWPS4Q8B5VEMXX9NQT","journal-publishability-criteria","Use whenever a research paper, article or preprint is being written, revised, reviewed or published, and specifically before every publication of docs\u002Fpaper.md. Covers what legitimate journals actually gate on, in order of gating — the editor's desk screen (scope, novelty, package problems), what reviewers judge (methodological soundness, claims the evidence can carry, statistical and qualitative reporting), EQUATOR reporting guidelines, the ICMJE authorship criteria, COPE's view of text recycling, the near-universal generative-AI policy (no AI author, disclosure, author responsibility), TOP 2025 transparency standards, how to verify a journal is legitimate, submitting without an institution, and a pre-submission checklist. Triggers on requests to evaluate, review, prepare or submit a paper, to judge publishability, to write a declarations or data-availability section, to disclose AI use, or to check a journal.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fjournal-publishability-criteria\u002FSKILL.md",[],[]]