Lesson 4 of 8 · 2 min
Providers with fallback
Keep model calls behind one function so you can change provider without touching the rest. Save as app/llm.py.
# run locally: needs Ollama, or any OpenAI-compatible host
import os, httpx
PROVIDERS = [
{"name": "local", "url": "http://127.0.0.1:11434/v1", "key": "ollama", "model": os.getenv("LOCAL_MODEL", "gpt-oss:20b")},
{"name": "cloud", "url": os.getenv("CLOUD_URL", ""), "key": os.getenv("CLOUD_KEY", ""), "model": os.getenv("CLOUD_MODEL", "")},
]
def chat(messages, timeout=60):
errors = []
for p in PROVIDERS:
if not p["url"]:
continue
try:
r = httpx.post(f"{p['url']}/chat/completions", headers={"Authorization": f"Bearer {p['key']}"},
json={"model": p["model"], "messages": messages}, timeout=timeout)
r.raise_for_status()
return r.json()["choices"][0]["message"]["content"], p["name"]
except (httpx.HTTPError, KeyError) as e:
errors.append(f"{p['name']}: {type(e).__name__}")
raise RuntimeError("all providers failed: " + ", ".join(errors))