AI / LangGraph LangChain Interview questions II
What are cost optimization techniques for LangChain?
LLM API costs are primarily driven by token usage. LangChain applications can apply several techniques at different layers to reduce costs without significantly degrading quality:
- Response caching — the single highest-impact technique for repetitive queries. InMemoryCache or RedisSemanticCache returns stored responses for identical or semantically similar prompts, paying zero tokens for cache hits.
- Model tiering — use cheaper models (GPT-4o-mini, Claude Haiku) for simple classification, routing, and extraction tasks; reserve expensive models (GPT-4o, Claude Sonnet) for complex reasoning. Implement this with
RunnableBranchrouting. - Prompt compression — use
LLMLingua(vialangchain-community) to compress retrieved context by removing low-information tokens before injecting into the prompt. - Token counting before calling — use
llm.get_num_tokens(text)to check prompt size; truncate or summarise if it exceeds a budget:
llm = ChatOpenAI()
token_count = llm.get_num_tokens(prompt_text)
if token_count > 3000:
# Summarise or truncate before proceeding
...
- Streaming — stream responses to clients early; use
max_tokensto cap output length for use cases where truncation is acceptable. - Batch processing — use
.batch()with appropriate concurrency for offline workloads to maximise throughput per dollar. - Avoid over-engineering with agents — a simple RAG chain is 10-50x cheaper per query than a multi-step agent. Only use agents when the task genuinely requires dynamic decision-making.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
