Everything you need to plug an LLM into your code: a code generator for every provider in the catalog, the parameters that matter, production best practices, and a guide to running a model on your own machine.
Generate integration code
Almost every provider exposes the same OpenAI-compatible API: only the base URL, the key and the model name change. Choose a provider and options, then copy the code.
Store the key in an environment variable or a .env file — never in front-end code or a Git repository.
Environment variable
# .env (add .env to .gitignore — never commit it)
GROQ_API_KEY=your-key-here
# or, for the current shell session:
export GROQ_API_KEY="your-key-here"# pip install openai
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.groq.com/openai/v1",
api_key=os.environ["GROQ_API_KEY"],
timeout=60,
max_retries=3, # retries 429 / 5xx with exponential backoff
)
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API is in one sentence."},
],
temperature=0.7,
max_tokens=512,
)
print(response.choices[0].message.content)
print(response.usage) # prompt / completion tokensKey parameters
These parameters are shared by all OpenAI-compatible APIs. Some providers ignore or limit some of them: check their documentation.
| Parameter | Role | Recommended values |
|---|---|---|
model | Model identifier, exactly as listed by the provider. | Copy it from the catalog page or from GET /v1/models. |
messages | Conversation: list of messages with a role (system, user, assistant) and a content. | Put instructions in the system message; resend the history for a multi-turn chat. |
temperature | Randomness of the answer (0 = deterministic, 2 = very creative). | 0–0.3 for extraction, code or JSON; 0.7 for chat; 1+ for brainstorming. |
top_p | Nucleus sampling: keeps only the most likely tokens. | Leave the default; change either temperature or top_p, not both. |
max_tokens | Maximum length of the answer, in tokens (≈ 0.75 English word per token). | Always set it to cap cost and latency; reasoning models need more (1,000+). |
stream | Sends the answer token by token (server-sent events). | Enable it for chat interfaces: the first words appear in a few hundred milliseconds. |
stop | Strings that stop generation. | Useful for templates, e.g. ["\n\n"]. |
seed | Fixed seed for more reproducible answers. | Handy for tests; not guaranteed by every provider. |
response_format | Forces a JSON answer ({"type": "json_object"}) or a JSON schema. | Also ask for JSON in the prompt and validate the result. |
tools | Functions the model can call (function calling). | Check the “tools” feature in the catalog before relying on it. |
Best practices
- Keep API keys on the server side (environment variables, secret manager); a key in a web page or a mobile app will be stolen.
- Always set a timeout and a max_tokens: a stuck request or an endless answer costs time and money.
- Handle 429 (rate limit) and 5xx errors with exponential backoff; do not retry 400, 401 or 403 errors.
- Free tiers have low and changing limits: plan a fallback to another provider or to a local model.
- Use streaming for interactive interfaces and measure the time to first token — the catalog shows it for each API.
- Log tokens used (response.usage) to watch costs, and cache identical requests.
- Never send personal or confidential data to a provider whose terms you have not read; prefer a local model for sensitive data.
Retry with exponential backoff
import random, time
from openai import OpenAI, RateLimitError, APIStatusError, APIConnectionError
def ask(client, model, messages, attempts=5):
"""Retries 429 / 5xx / network errors with exponential backoff and jitter."""
for i in range(attempts):
try:
return client.chat.completions.create(model=model, messages=messages)
except (RateLimitError, APIConnectionError) as e:
err = e
except APIStatusError as e:
if e.status_code < 500:
raise # 400 / 401 / 403 / 404: retrying will not help
err = e
time.sleep(min(30, 2 ** i) + random.random())
raise errFallback between free providers — Python
import os
from openai import OpenAI
# Free providers tried in order: if one is down or rate limited, the next one answers.
PROVIDERS = [
("https://api.groq.com/openai/v1", os.environ.get("GROQ_API_KEY"), "llama-3.3-70b-versatile"),
("https://api.cerebras.ai/v1", os.environ.get("CEREBRAS_API_KEY"), "llama3.1-8b"),
("https://openrouter.ai/api/v1", os.environ.get("OPENROUTER_API_KEY"), "openrouter/free"), # routes to an available free model
("http://localhost:11434/v1", "ollama", "qwen3:8b"), # local last resort
]
def ask(prompt):
errors = []
for base_url, key, model in PROVIDERS:
if not key:
continue
try:
client = OpenAI(base_url=base_url, api_key=key, timeout=30, max_retries=1)
r = client.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
except Exception as e: # rate limit, outage, timeout…
errors.append(f"{base_url}: {e}")
raise RuntimeError("All providers failed:\n" + "\n".join(errors))Fallback between free providers — JavaScript
import OpenAI from 'openai'
// Free providers tried in order: if one is down or rate limited, the next one answers.
const PROVIDERS = [
{ baseURL: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' },
{ baseURL: 'https://api.cerebras.ai/v1', apiKey: process.env.CEREBRAS_API_KEY, model: 'llama3.1-8b' },
{ baseURL: 'http://localhost:11434/v1', apiKey: 'ollama', model: 'qwen3:8b' }, // local last resort
]
export async function ask(prompt) {
const errors = []
for (const { baseURL, apiKey, model } of PROVIDERS) {
if (!apiKey) continue
try {
const client = new OpenAI({ baseURL, apiKey, timeout: 30_000, maxRetries: 1 })
const r = await client.chat.completions.create({ model, messages: [{ role: 'user', content: prompt }] })
return r.choices[0].message.content
} catch (err) {
errors.push(`${baseURL}: ${err.message}`)
}
}
throw new Error(`All providers failed:\n${errors.join('\n')}`)
}Run an LLM on your machine
A local model is free, private and works offline. What you can run depends mainly on your graphics card memory (VRAM) — or, on a Mac, on unified memory.
NVIDIA: works out of the box with Ollama, LM Studio, llama.cpp (CUDA) and vLLM. Install a recent driver; check with nvidia-smi.
Rule of thumb: in 4-bit, a model needs about 0.6 GB per billion parameters, plus 1–2 GB for the context. 8 GB of VRAM ≈ 7–8B models, 12 GB ≈ 14B, 24 GB ≈ 32B.
| Model | Usage | Download | Memory needed | On your machine |
|---|---|---|---|---|
Llama 3.2 1Bllama3.2:1b | Chat | ≈ 1.3 GB | 2.4 GB | |
Gemma 3 1Bgemma3:1b | Chat | ≈ 0.8 GB | 1.9 GB | |
Llama 3.2 3Bllama3.2:3b | Chat | ≈ 2 GB | 3.2 GB | |
Phi-4 miniphi4-mini | Chat, Reasoning | ≈ 2.5 GB | 3.7 GB | |
Qwen3 4Bqwen3:4b | Chat, Reasoning | ≈ 2.6 GB | 3.8 GB | |
Gemma 3 4Bgemma3:4b | Chat, Vision (images) | ≈ 3.3 GB | 4.6 GB | |
Mistral 7Bmistral:7b | Chat | ≈ 4.1 GB | 5.4 GB | |
Qwen2.5-Coder 7Bqwen2.5-coder:7b | Code | ≈ 4.7 GB | 6.1 GB | |
Llama 3.1 8Bllama3.1:8b | Chat | ≈ 4.9 GB | 6.3 GB | |
Qwen2.5-VL 7Bqwen2.5vl:7b | Vision (images) | ≈ 6 GB | 7.5 GB | |
Qwen3 8Bqwen3:8b | Chat, Reasoning, Code | ≈ 5.2 GB | 6.6 GB | |
DeepSeek-R1 8Bdeepseek-r1:8b | Reasoning | ≈ 5.2 GB | 6.6 GB | |
Gemma 3 12Bgemma3:12b | Chat, Vision (images) | ≈ 8.1 GB | 9.7 GB | |
Phi-4 14Bphi4:14b | Chat, Reasoning | ≈ 9.1 GB | 10.8 GB | |
Qwen3 14Bqwen3:14b | Chat, Reasoning, Code | ≈ 9.3 GB | 11 GB | |
Qwen2.5-Coder 14Bqwen2.5-coder:14b | Code | ≈ 9 GB | 10.7 GB | |
DeepSeek-R1 14Bdeepseek-r1:14b | Reasoning | ≈ 9 GB | 10.7 GB | |
gpt-oss 20Bgpt-oss:20b | Chat, Reasoning, Code | ≈ 14 GB | 16.1 GB | |
Mistral Small 24Bmistral-small:24b | Chat | ≈ 14 GB | 16.1 GB | |
Gemma 3 27Bgemma3:27b | Chat, Vision (images) | ≈ 17 GB | 19.4 GB | |
Qwen3 30B-A3Bqwen3:30b | Chat, Reasoning | ≈ 19 GB | 21.5 GB | |
Qwen3-Coder 30B-A3Bqwen3-coder:30b | Code | ≈ 19 GB | 21.5 GB | |
Qwen3 32Bqwen3:32b | Chat, Reasoning, Code | ≈ 20 GB | 22.6 GB | |
Qwen2.5-Coder 32Bqwen2.5-coder:32b | Code | ≈ 20 GB | 22.6 GB | |
DeepSeek-R1 32Bdeepseek-r1:32b | Reasoning | ≈ 20 GB | 22.6 GB | |
Llama 3.3 70Bllama3.3:70b | Chat | ≈ 43 GB | 47.4 GB | |
DeepSeek-R1 70Bdeepseek-r1:70b | Reasoning | ≈ 43 GB | 47.4 GB | |
gpt-oss 120Bgpt-oss:120b | Chat, Reasoning, Code | ≈ 65 GB | 71.2 GB |
Approximate sizes for the default 4-bit quantization (Q4). A longer context needs more memory. Check exact sizes on ollama.com/library. Click a model to see its commands.
Install and run
Ollama — the simplest: one command to download and run a model, with an OpenAI-compatible API on port 11434.
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# macOS
brew install ollama # or download the app from https://ollama.com/download
# Windows
winget install Ollama.OllamaQwen3 8B
ollama pull qwen3:8b
ollama run qwen3:8b
# check that it runs on the GPU (PROCESSOR column: "100% GPU")
ollama ps# Ollama exposes an OpenAI-compatible API on http://localhost:11434/v1
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "qwen3:8b", "messages": [{"role": "user", "content": "Hello"}]}'Call your local model with the same code as a cloud API: choose “Ollama” in the code generator above.
Docker (Ollama with NVIDIA GPU):
docker run -d --gpus=all -v ollama:/root/.ollama -p 127.0.0.1:11434:11434 --name ollama ollama/ollama
docker exec -it ollama ollama run qwen3:8bLM Studio — desktop app with a graphical interface: search a model, download it, then start the local server (port 1234). lmstudio.ai
llama.cpp — the lightweight engine behind most tools: full control over quantization, GPU layers (-ngl) and context (-c).
# macOS / Linux: brew install llama.cpp — Windows: winget install llama.cpp
# -ngl 99: all layers on the GPU (lower it if the model does not fit), -c: context size
llama-server -m ./model-Q4_K_M.gguf -ngl 99 -c 8192 --port 8080vLLM — for servers with large NVIDIA GPUs and many concurrent users (full-precision weights: about 2 GB per billion parameters).
pip install vllm
vllm serve Qwen/Qwen3-8B --max-model-len 8192 # OpenAI-compatible API on http://localhost:8000/v1Security: Ollama only listens on localhost by default. Do not expose port 11434 to the Internet without a reverse proxy and authentication.