str: if len(query.split()) < 50: # simple short queries return ChatOpenAI(model='gpt-4o-mini').invoke(query).content return ChatOpenAI(model='gpt-4o').invoke(query).contentExact caching only hits the cache when the query is identical character-for-character; semantic caching uses embedding similarity to return cached responses for semantically equivalent but differently phrased queries — much higher cache hit rate at the cost of embedding computation"> str: if len(query.split()) < 50: # simple short queries return ChatOpenAI(model='gpt-4o-mini').invoke(query).content return ChatOpenAI(model='gpt-4o').invoke(query).contentExact caching only hits the cache when the query is identical character-for-character; semantic caching uses embedding similarity to return cached responses for semantically equivalent but differently phrased queries — much higher cache hit rate at the cost of embedding computation" />

Prev Next

Python / Python Modern Generative AI and Agents Interview Questions

How do you manage LLM API costs and implement caching to reduce redundant calls?

LLM API costs can escalate quickly in production. For context, GPT-4o costs $5/1M input tokens and $15/1M output tokens — a system making 10,000 calls/day with 2,000 tokens each consumes $100+/day. Several strategies keep costs manageable: choosing the right model for the task, caching repeated queries, reducing prompt size, and batching calls.

# ── LangChain in-memory caching (same query returns cached response)
from langchain_core.globals import set_llm_cache
from langchain_community.cache import InMemoryCache, RedisCache
from langchain_openai import ChatOpenAI

# Cache in memory (process-level; resets on restart)
set_llm_cache(InMemoryCache())

llm = ChatOpenAI(model='gpt-4o-mini')
result1 = llm.invoke('What is 2+2?')  # hits API
result2 = llm.invoke('What is 2+2?')  # returns cached; zero cost

# ── Redis semantic cache (caches based on query SIMILARITY)
from langchain_community.cache import RedisSemanticCache
from langchain_openai import OpenAIEmbeddings

semantic_cache = RedisSemanticCache(
    redis_url='redis://localhost:6379',
    embedding=OpenAIEmbeddings(model='text-embedding-3-small'),
    score_threshold=0.95,  # cache if query similarity > 95%
)
set_llm_cache(semantic_cache)
# 'What is two plus two?' -> retrieves cached response for 'What is 2+2?'

# ── Cost estimation before calling
import tiktoken

def estimate_cost(prompt: str, model: str = 'gpt-4o') -> float:
    enc = tiktoken.encoding_for_model(model)
    n   = len(enc.encode(prompt))
    cost_per_1M = {'gpt-4o': 5.0, 'gpt-4o-mini': 0.15}
    return n / 1e6 * cost_per_1M.get(model, 5.0)

print(f'Estimated cost: ${estimate_cost("Hello world", "gpt-4o"):.6f}')

# ── Model routing: cheap model first, expensive only if needed
def smart_route(query: str) -> str:
    if len(query.split()) < 50:  # simple short queries
        return ChatOpenAI(model='gpt-4o-mini').invoke(query).content
    return ChatOpenAI(model='gpt-4o').invoke(query).content
Why is model routing (using cheaper models for simple queries) a better cost strategy than always using the most capable model?
What is the difference between exact caching and semantic caching for LLM responses?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

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...

What are Large Language Models (LLMs) and how do they generate text? What is the Hugging Face Transformers pipeline API and how do you use it for common NLP and vision tasks? How does tokenisation work in Hugging Face and what are the key tokenizer concepts? What is the Auto-class pattern in Hugging Face and how do you run inference with a raw model? What is prompt engineering and what are the most effective techniques for getting better outputs from LLMs? What is Retrieval-Augmented Generation (RAG) and why is it preferred over full fine-tuning for knowledge-intensive tasks? What are vector databases and how do they enable semantic search in RAG pipelines? How do you build a complete RAG pipeline using LangChain? What are the most important text splitting strategies in RAG, and how do chunk size and overlap affect retrieval quality? What are LangChain's core abstractions — Chains, Runnables, and the LangChain Expression Language? How do you add conversation memory to an LLM application with LangChain? What is an AI agent and how does function calling / tool use work in LLM-based agents? What is the ReAct agent pattern and how does LangChain implement it? How do you efficiently load large Hugging Face models for inference, including quantization and device placement? How do you use Hugging Face's text-generation pipeline with open-source chat models like Mistral or Llama? How do you use the Hugging Face Inference API and the InferenceClient for production deployments? What is LoRA and how does the Hugging Face PEFT library simplify fine-tuning large models? How do you use the Hugging Face Datasets library for training and evaluation? How do you fine-tune a model using the Hugging Face Trainer API? How do you evaluate LLM outputs for quality, factual accuracy, and hallucination? How do you stream LLM responses token by token for a better user experience? How do you use multimodal models (vision-language) with Hugging Face for image understanding tasks? How do you reliably get structured JSON output from LLMs, and what tools does LangChain provide? How do you compute semantic similarity between texts using Hugging Face and OpenAI embeddings? What document loaders does LangChain provide, and how do you handle different file types in a RAG pipeline? What is the OpenAI Assistants API and how does it differ from the Chat Completions API? What is the Parent Document Retriever pattern and when does it improve RAG performance? How do you manage, version, and reuse prompts in production LLM applications? How do you generate and manipulate images using Hugging Face's Diffusers library? How do you handle documents or conversations that exceed an LLM's context window? What is LangGraph and how does it differ from LangChain's AgentExecutor for building agents? What embedding models should you use for production RAG systems, and how do you choose between OpenAI and open-source options? How do you add safety guardrails and input/output validation to LLM applications? How do you manage LLM API costs and implement caching to reduce redundant calls? What is LlamaIndex and how does it compare to LangChain for RAG use cases? What is the Hugging Face Hub and how do you push a trained model to share it? How do you build a demo web interface for an LLM application using Gradio? How do you monitor and debug LLM applications in production using LangSmith?
Show more question and Answers...

FastAPI Interview Questions

Comments & Discussions