LLM gateway
One API for many models with LiteLLM: fallbacks, costs and caching, routing, logs and guardrails.
An LLM gateway stands between your applications and the model providers: one API for every model, and one place for fallbacks, routing, caching, cost tracking, logs and input checks. The module starts with what a gateway does to each request and when it is worth running one, then builds one with LiteLLM, a feature per lesson: the unified completion() call with fallbacks, costs and caching, a Router with aliases and load balancing, and callbacks for logs and guardrails. The last lesson puts LiteLLM under LangChain, routes each question to the model that suits it, and ends with the whole gateway in one script with Gemini. Run the notebook cells in order, and try each practice task before you open its solution.
Lessons
- 1What an LLM gateway doesWhy calling providers directly stops scaling, what a gateway is, its jobs in the order a request meets them, a library or a server and the proxy's config file, how it relates to LangChain's own provider switching and fallbacks, trade-offs and failure modes, popular gateways, a production checklist, interview questions and two practice tasks in plain Python.
- 2One API for every modelInstall LiteLLM, quiet its logs, load the keys, completion() and its model strings, the OpenAI-style response, many providers in one loop, one family of errors for every provider, testing without a key with mock_response, fallbacks when a model fails and how they work, retries and timeouts, interview questions and two practice tasks.
- 3Costs and cachingThe cost of one call with completion_cost, checking it with cost_per_token, LiteLLM's price table and models missing from it, the cost on every response, caching with Cache, what makes two requests the same, cache types, what goes wrong with caching, interview questions and two practice tasks.
- 4Routing and load balancingAliases with a model list, which deployment answered, several deployments behind one alias, the routing strategies (simple-shuffle, least-busy, latency-based, cost-based) and what each one needs, why cost-based routing failed, retries, fallbacks and cooldowns, interview questions and two practice tasks.
- 5Logs and guardrails with callbacksSuccess and failure callbacks, what they receive and why the log looked empty, logging integrations and privacy, redacting personal data, blocking prompt injections and topics, why input callbacks don't block or redact, checks that run before the call, what simple checks miss, guardrails on the proxy, interview questions and two practice tasks.
- 6The gateway in an appChatLiteLLM in an LCEL chain, swapping providers by string and the parameters that still differ, with_fallbacks on a chain compared with LiteLLM's fallbacks, ChatLiteLLMRouter, a task-aware chatbot that classifies, routes, falls back and prices each answer, the gateway in one script with Gemini, interview questions and two practice tasks.