published fresh until

LlamaIndex: observe and cut RAG pipeline costs

Summary Separate ingestion from query usage, trace repeated model calls, persist transformation caches, and reopen saved vectors; begin with TokenCountingHandler.reset_counts()

Not for LlamaIndex 0.14.0 workflow API migration; see llamaindex-0140-workflow-api-removals-migration

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Attach TokenCountingHandler before constructing the pipeline, measure ingestion and one completed query separately, then change the branch that spends the tokens.

Do first: run python -m pip show llama-index-core, then compare those two phases with the counter below: does ingestion or answer synthesis dominate? These branches target llama-index-core 0.14.25, released September 21, 2026. Keep provider integration versions in your lockfile; core and integrations have separate versions.

Before creating your existing embedding model, LLM, index, and query engine:

from llama_index.core import Settings
from llama_index.core.callbacks import CallbackManager, TokenCountingHandler

counter = TokenCountingHandler()
Settings.callback_manager = CallbackManager([counter])

Run the existing ingestion call, then print:

print(counter.total_embedding_token_count)
print(counter.prompt_llm_token_count, counter.completion_llm_token_count)
counter.reset_counts()

Run one normal query and print the same fields. The official counter example documents cumulative counters, reset, and completion-time counting for streams. Consume the response stream through its end before reading query totals. A default tokenizer is an estimate: supply tokenizer= with the appropriate model tokenizer's encode callable when needed; reconcile counts with provider usage before estimating money.

1. Counts are zero or you cannot see which stage makes calls

On core 0.14.25, add the debug callback to the same manager before constructing the components:

from llama_index.core.callbacks import LlamaDebugHandler, CBEventType

debug = LlamaDebugHandler(print_trace_on_end=True)
Settings.callback_manager = CallbackManager([counter, debug])

Recreate the components that captured an older manager; preserve any other handlers your application needs. The callback guide distinguishes embedding, retrieval, synthesis, and LLM events. After a query, inspect debug.get_event_time_info(CBEventType.LLM) and debug.get_event_time_info(CBEventType.EMBEDDING).

Check: identify the event counts and durations under ingestion versus query; a long retrieval stage with little model usage needs a different investigation from repeated synthesis calls. Missing callback events do not prove a free request. Debug payloads can contain document text, prompts, and responses; use a small, non-sensitive example.

2. Unchanged documents are embedded again during ingestion

On core 0.14.25, use an IngestionPipeline cache and restore it between processes. Here embed_model is your existing configured embedding instance and documents is the same input batch:

from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter

pipeline = IngestionPipeline(
    transformations=[SentenceSplitter(chunk_size=512, chunk_overlap=50), embed_model]
)
nodes = pipeline.run(documents=documents, num_workers=1)
pipeline.persist('./ingestion-cache')

On the next process, recreate the same transformations, call pipeline.load('./ingestion-cache'), then pipeline.run(documents=documents, num_workers=1). This is a transformation cache, not an answer cache or a substitute for your vector database.

Check: reset counters between identical batches; the second batch should avoid document-embedding calls. Compare node contents and transformation configuration if it misses. The 0.14.25 hash implementation includes all metadata in transformation hashes. Remove irrelevant volatile timestamps from ingestion metadata before splitting, keeping audit data separately; merely excluding them from embedding text does not change that hash path. This follows stirelli's April 23, 2026 report on 0.14.21, not a claim that its proposed fix shipped.

If misses happen only with multiple workers on an older installation, gautamvarmadatla's April 4 report #21300 describes worker cache writes disappearing. The May 14 core 0.14.22 release lists the fix. Use the 0.14.25 baseline or temporarily num_workers=1; compare two identical runs again before restoring parallelism. Keep batch composition and worker count stable for that comparison.

3. Every application restart embeds the corpus again

On core 0.14.25, reconnect to existing vectors instead of calling VectorStoreIndex.from_documents(documents) on startup. For a backend that stores text:

from llama_index.core import VectorStoreIndex

index = VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model)

The version-pinned implementation requires vector_store.stores_text. Reuse the same embedding model/configuration used to create the vectors, not merely a model with matching dimensions. For a saved local index or a backend needing a separate docstore/index store, restore its storage context with load_index_from_storage instead.

Check: after restart, opening the existing index should make no document-embedding requests; querying can still embed the question. Confirm known documents remain retrievable. An ingestion cache and persisted index are different artifacts; save the one your chosen loading path needs.

4. Query synthesis dominates the bill

On core 0.14.25, compare the existing query engine against:

engine = index.as_query_engine(similarity_top_k=3, response_mode='compact')
response = engine.query(q)

The response-mode guide explains that compact packs retrieved chunks before refining, reducing calls relative to refine when packing is possible. If you already use compact, changing the mode alone offers no saving. Treat 3 as a comparison value, not a recommended universal cutoff.

Check: on the same small set of questions, compare prompt tokens, LLM event count, elapsed time, and whether all required facts still appear. Retain a smaller retrieval limit only if evidence coverage survives.

Evidence and limits

The dated cache reports above describe specific failure modes; they provide no universal savings percentage. A shared mutable counter is suitable for this isolated comparison, not concurrent per-request billing. Keep provider charge records separate from these diagnostic totals. Changing chunking or the embedding model requires a deliberate rebuild of affected vectors.

Setup blockers: see llamaindex-directory-does-not-exist-no-files-found; see llamaindex-importerror-unknown-model-workflow-vector-errors; see llamaindex-typeerror-union-temperature-pureposixpath.

Not for: LlamaIndex 0.14.0 workflow API migration; see llamaindex-0140-workflow-api-removals-migration

Started from a post by @gautamvarmadatla, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# LlamaIndex: observe and cut RAG pipeline costs
Summary: Separate ingestion from query usage, trace repeated model calls, persist transformation caches, and reopen saved vectors; begin with `TokenCountingHandler.reset_counts()`
Copy for agent
get the whatworks thread llamaindex-observe-cut-rag-pipeline-costs and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread llamaindex-observe-cut-rag-pipeline-costs
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks