Logotipo de Llm Cost Optimization

Llm Cost Optimization

Comunidad
nimadorostkar
llm-cost-optimization

Use when an LLM feature costs too much. Covers prompt caching, context reduction, model routing, batching, output limits, and finding where the tokens actually go. Trigger on "our openai bill is too high", "llm costs are out of control", "where are all these tokens going", "set up prompt caching". Do not use for cloud infrastructure spend — see the aws-cost-optimization skill; for choosing a cheaper model, see the model-selection skill.

Descripción general

Editornimadorostkar
RepositorioClaude-Skills-collection
Nombre de la habilidadllm-cost-optimization
Estrellas
34
Forks
4
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por nimadorostkar en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Llm Cost Optimization en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/nimadorostkar/Claude-Skills-collection/tree/main/skills/ai/llm-cost-optimization
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/nimadorostkar/Claude-Skills-collection.git /tmp/Claude-Skills-collection
mkdir -p .claude/skills
cp -r /tmp/Claude-Skills-collection/skills/ai/llm-cost-optimization .claude/skills/llm-cost-optimization
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Llm Cost Optimization en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Llm Cost Optimization automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Llm Cost Optimization no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

LLM Cost Optimization

Purpose

Reduce the cost of an LLM feature without losing the quality that justified it. Most LLM bills are dominated by one or two things that nobody has measured, and the fix is usually structural rather than a matter of shaving tokens.

When to Use

  • An LLM feature that is too expensive at current or projected volume.
  • Before scaling a feature from pilot to production traffic.
  • A bill that grew and nobody can explain why.

Capabilities

  • Token accounting: where the spend actually is.
  • Prompt caching.
  • Context reduction and retrieval narrowing.
  • Model routing and downgrading.
  • Batch processing for non-interactive work.
  • Output-length control.

Inputs

  • Token counts per call, broken down: system, context, history, output.
  • Call volume, by feature and by tenant.
  • The quality bar that must be maintained.

Outputs

  • A ranked list of cost drivers.
  • Changes with measured cost reduction and no quality regression.
  • Per-feature cost tracking so the next increase is visible.

Workflow

  1. Measure where the tokens go — Input versus output, and within input: system prompt, tools, retrieved context, conversation history. The answer is frequently not what anyone expected.
  2. Cache the stable prefix — If the system prompt and tools are identical across calls, prompt caching reduces their cost by roughly 90%. This is usually the single largest and cheapest win.
  3. Cut the context, not the quality — Retrieving twenty chunks when five suffice costs four times as much and often produces a worse answer. Measure the quality at each k.
  4. Route to a smaller model — Most tasks do not need the largest model. Measure the small one before assuming it cannot.
  5. Batch what is not interactive — Batch APIs are typically half the price for work that can wait. Overnight classification does not need a synchronous call.
  6. Cap the output — Output tokens cost several times more than input tokens. A max_tokens that is generous "just in case" is a standing cost.

Best Practices

  • Output tokens typically cost 3-5x input tokens. A prompt that produces a verbose preamble before the answer is paying a premium for text nobody reads. Instruct the model to answer directly.
  • Prompt caching requires a byte-identical prefix. A timestamp, a request ID, or a shuffled tool order at the top of the prompt silently disables it and nobody notices — except the bill.
  • Conversation history is the cost that grows without anyone deciding to grow it. Compact it.
  • A retry that resends the whole context costs the whole context again. Retry budgets are a cost control, not only a reliability one.
  • Attribute cost per feature and per tenant. Without attribution, cost optimization is guesswork, and one customer's usage pattern can consume the margin invisibly.
  • The cheapest call is the one you do not make. Cache the answer, not just the prompt — many LLM calls in production are for questions already asked.

Examples

Finding where the money actually goes:

text
Feature: support-assistant. 4.2M calls/month. $18,400/month.

Token breakdown per call (mean):
  System prompt + tools     3,100    every call, identical
  Retrieved context         9,800    top-20 chunks
  Conversation history      6,400    grows unbounded within a session
  User message                180
  Output                      420
                          -------
  Input total              19,480
  Output total                420

Findings, in order of size:
  1. The system prompt is identical on every call and is not cached.
     -> Enable prompt caching. 3,100 tokens x 4.2M at 10% of the cost.
        Saving: ~$2,900/month. Effort: one line.

  2. Retrieval returns 20 chunks. Quality on the eval set peaks at k=6
     and is flat to k=20.
     -> Reduce to k=6. Saving: ~$6,100/month. Quality: unchanged (measured).

  3. History is never compacted; long sessions carry 40k+ tokens.
     -> Compact above 8k. Saving: ~$2,400/month.

  4. 31% of questions are near-duplicates of a previous question.
     -> Semantic cache on the answer. Saving: ~$3,700/month.

  Total: $18,400 -> $3,300/month. No measurable quality change.

The caching mistake that costs the most:

python
# This defeats prompt caching entirely, and it is not obvious.
system = f"You are a support assistant. Current time: {datetime.now()}. ..."
#                                                     ^^^^^^^^^^^^^^^^
# The prefix differs on every call, so nothing is ever a cache hit.

# Correct: keep the stable part stable; put the variable part after the
# cache breakpoint.
system = [
    {
        "type": "text",
        "text": STABLE_SYSTEM_PROMPT,           # byte-identical every call
        "cache_control": {"type": "ephemeral"},
    },
    {
        "type": "text",
        "text": f"Current time: {datetime.now().isoformat()}",   # after the breakpoint
    },
]

Notes

  • The single most common cost mistake is a variable value — a timestamp, a UUID, a user's name — near the top of an otherwise stable system prompt, which silently disables prompt caching. Check for this first.
  • Semantic caching (embedding the question, returning a stored answer on a close match) is powerful and dangerous. It must be scoped per tenant and invalidated when the underlying data changes, or it will serve one customer another's answer.
  • Reducing retrieved context often improves answer quality while cutting cost. It is the rare optimization with no trade-off, and it is available in most RAG systems that were built by increasing k until the answers looked good.

Preguntas frecuentes

¿Qué hace la habilidad de IA Llm Cost Optimization?

Use when an LLM feature costs too much. Covers prompt caching, context reduction, model routing, batching, output limits, and finding where the tokens actually go. Trigger on "our openai bill is too high", "llm costs are out of control", "where are all these tokens going", "set up prompt caching". Do not use for cloud infrastructure spend — see the aws-cost-optimization skill; for choosing a cheaper model, see the model-selection skill.

¿Por qué usar Llm Cost Optimization en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Llm Cost Optimization está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Llm Cost Optimization en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/nimadorostkar/Claude-Skills-collection/tree/main/skills/ai/llm-cost-optimization. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Llm Cost Optimization?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Llm Cost Optimization?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Llm Cost Optimization con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Llm Cost Optimization?

Sí. nimadorostkar la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇