Lesson 128 — Advanced

Model Routers & LLM Gateways

Do providers, teen teams, ek bill — aur har feature ke liye alag SDK. Gateway ek aisa layer hai jo sab providers ke peeche ek endpoint banata hai: credentials wahan, ek request format, aur ek usage view. Is lesson mein routing rules, failover, spend controls, gateway caching aur wo failure mode dekhenge jo gateway lagate hi introduce ho jaata hai.

⏱ 20 min• Advanced• Open-Weight Model Platforms

Gateway kya hai — ek endpoint, anek providers

Kya hai?

Gateway (router/proxy) tumhara ek endpoint rakhta hai jo kai upstream providers ko route karta hai. Credentials gateway ke paas, request format ek, aur upstream kaunsa model serve kare ye routing rule decide karta hai.

Kab kaam aata hai?

Jab do se zyada providers hon, kai teams hon jinke apne budgets hon, ya failover/spend governance chahiye ho. Sirf ek provider aur chhoti team ho toh seedha SDK kaafi hai.

Kahan milta hai?

Hosted routers (OpenRouter, Portkey jaise options), self-hosted proxies (LiteLLM jaisa), cloud platforms ke apne routing features, aur kuch frameworks ke gateway mode mein.

Mechanism: client gateway ko bulata hai, gateway upstream credentials apne paas rakhta hai, request ko ek standard format mein badalta hai, provider ko bhejta hai, aur usage log karta hai. Tumhara application code jaanta bhi nahi ki jawab kis model se aaya — jab tak tum rule ke through na dekho.

Yaad rakho: Gateway teen promises deta hai: credentials centrally governed + ek usage view across providers, aur failover. Chhooti hui teesri cheez sabse important hai — routing rule badalne se jawab dene wala model badal jaata hai, bina app code badle.

Hosted routers vs self-hosted proxies

gateway ke shapes:
  hosted router      -> third-party endpoint, aapka traffic unke through
                       (OpenRouter, Portkey jaise options)
  self-hosted proxy  -> tumhara infra, tumhara control
                       (LiteLLM jaisa open-source proxy)
  platform routing   -> cloud platform ka apna unified endpoint
  framework gateway  -> app framework ke andar built-in routing

har shape ka trade-off: setup effort vs control vs traffic boundary
Choice rule: Teams alag-alag providers chahti hain ya spend govern karna hai — gateway. Sab ek hi cloud ke aur ek hi team — platform ka unified API kaafi. Har gateway ka ek question zaroor poochho: "mera traffic kis network se guzarta hai?"

Routing rules aur automatic failover

# Routing rule ka shape (concept — har gateway ka syntax alag)
routes:
  - name: long-context
    match: { context_tokens: "> 64000" }
    target: long-context-model
  - name: cheap-bulk
    match: { task: "classification" }
    target: small-cheap-model
  - name: default
    target: primary-model
    fallbacks: [secondary-model, tertiary-model]
    retry: { on: [429, 5xx, timeout], backoff: "exponential+jitter" }
Test karo, assume mat karo: Primary ko deliberately fail karke dekho (fault injection): fallback hua ya nahi, kitne seconds lage, cost attribution sahi rahi ya nahi. Failover bina test ke ek diagram hai, feature nahi.

Virtual keys, budgets aur quotas

# Gateway spend controls ka shape (concept)
virtual_keys = {
    "team-search": { "monthly_budget": 5000, "rpm_limit": 60 },
    "feature-summarizer": { "monthly_budget": 800, "rpm_limit": 12 },
}
# app real provider key kabhi nahi dekhta — sirf virtual key
# budget hit -> gateway throttle ya block (policy par)
# per-key rate limit -> ek client doosre ki capacity nahi kha sakta
Governance point: Budget sirf number nahi, escalation policy hai: 80% par owner ko alert, 100% par throttle ya hard stop. Runaway agent loop wali raat spend monitoring se hi bachti hai, mahine ke bill se nahi.

Gateway ab critical path par hai — aur kuch farq chhupta nahi

Gateway lagate hi tumne ek naya single point of failure apne request path mein daal diya. Ab uski apni availability, timeouts aur bypass plan chahiye — warna provider theek hai par gateway gira toh sab ruk gaya.

Reality check: Gateway "providers interchangeable" nahi bolta — wo routing, credentials aur visibility deta hai. Behavioural differences (tool calls, structured output, tone) ab bhi tumhare integration tests aur evals ka hissa hain.

Gateway par caching — exact aur semantic

# Gateway cache ke do levels
# 1. exact-match: same request hash -> cached response (sasta, safe)
key = hash(normalize(messages) + model + params)
if key in cache:
    return cache[key]      # zero token cost

# 2. semantic: similar meaning -> milta jawab (sasta, par risky)
#    similarity threshold + scope se control

# kabhi cache se mat lo:
# - personalized / user-specific data
# - real-time info (price, stock, time)
# - tool outputs jo har turn pe badalte hain
Savings ka order: Cache savings real hain, par pehle exact-match se shuru karo, semantic tabhi jab sawaal ka domain bounded ho. Aur hamesha log karo: hit/miss, aur hit aaya kis rule se — debugging warna andhere mein hogi.

Router kab apni jagah banata hai — aur evals kyun chahiye

gateway rollout checklist:
  1. do providers configure + auth verify
  2. primary pe traffic chalao, usage view check
  3. primary ko fail karke fallback drill (latency + cost dono)
  4. virtual key budgets set (team/feature wise)
  5. exact-match cache on, semantic cache decide
  6. rule change ka eval gate — bina eval ke routing edit nahi
  7. bypass plan document — gateway down scenario
Rule of thumb: Jab tak "kai providers + kai teams ya spend" wali condition na ho, router ruko. Aur jab lo, toh usse ek service ki tarah treat karo: SLO, monitoring, drill — kyunki ab woh tumhare request path ka hissa hai.

Exercise

Question: Real provider credentials gateway ke paas rehte hain aur clients ko milti hain — un clients ki keys kya kehlati hain?

Question: Primary provider fail hone par automatically doosre model par shift ho jaana kya kehlata hai?

Question: Gateway par identical request ka cached response dene wali cache kis naam se jaani jaati hai? (exact-match / semantic)

Question: Routing rule badalne se kya badalta hai — app code ya jawab dene wala model?

Common mistakes

Desi example: Society ka ek hi gate

Jaise society ka ek hi gate hai jahan guard har visitor ka record rakhta hai, guest limit lagata hai, aur gate band ho toh doosre gate se entry dikhata hai — gateway bhi providers ke liye wahi karta hai:

text
visitor (request)  -> gate (gateway) -> guard ka record (usage log)
                    -> guest pass (virtual key) + budget
                    -> gate 1 band? -> gate 2 (failover)
andar: asli flat keys (provider credentials) bahar nahi jaatin
Interview angle — yahan se sawaal aate hain
  • Q: Gateway kya karta hai? — Ek endpoint aage, kai providers peeche: credentials centrally, ek request format, ek usage view, routing rules.
  • Q: Self-hosted proxy aur hosted router ka trade-off? — Control aur traffic boundary vs setup effort; availability responsibility alag ho jaati hai.
  • Q: Gateway critical path par aane ke baad kya chahiye? — Apni availability, timeouts, monitoring aur ek documented bypass plan.
  • Q: Routing rule change ka sabse bada risk? — Jawab dene wala model badal jaata hai bina app code badle; isliye eval gate zaroori.
  • Q: Gateway caching kahan safe hai? — Exact-match sabse safe; semantic sirf bounded domain mein; personalized/real-time kabhi nahi.
Lesson complete?

Gateway clear — ab tum ek endpoint se kai providers route kar sakte ho, spend govern kar sakte ho aur critical-path risk ko apne drill se pakad sakte ho. Agla lesson — Managed Building Blocks: Build or Buy — mein dekhenge har layer ka build-vs-buy kaise decide hota hai.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course