LlamaIndex
Option 1: install() (recommended)
Section titled “Option 1: install() (recommended)”LlamaIndex’s OpenAI and Anthropic LLMs call the official SDKs, so
install() covers them, caching included:
import parryfrom llama_index.core import Settings, VectorStoreIndex, SimpleDirectoryReaderfrom llama_index.llms.openai import OpenAI
parry.install()Settings.llm = OpenAI(model="gpt-4o-mini")
index = VectorStoreIndex.from_documents(SimpleDirectoryReader("docs/").load_data())engine = index.as_query_engine()engine.query("What does max_cost_usd do?")engine.query("What does max_cost_usd do?") # the LLM call is a cache hitOption 2: ParryHandler
Section titled “Option 2: ParryHandler”The handler applies rate limiting, the budget and cost tracking at the LlamaIndex event level:
from llama_index.core import Settingsfrom llama_index.core.callbacks import CallbackManagerfrom parry import Parryfrom parry.integrations.llamaindex import ParryHandler
guard = Parry(max_cost_usd=1)Settings.callback_manager = CallbackManager([ParryHandler(guard)])
engine = index.as_query_engine()engine.query("...")print(guard.stats.summary())The handler reads token usage from the raw provider response, then from
additional_kwargs, and estimates with tiktoken as a last resort.
BudgetExceeded raised in on_event_start stops the query before the LLM is
called.
Using both
Section titled “Using both”As with LangChain, you can use both with the same guard without double counting:
guard = parry.install()Settings.callback_manager = CallbackManager([ParryHandler(guard)])Embeddings calls (OpenAIEmbedding) are not intercepted in v0.1. Only LLM
calls are.