LLMs with Python: Claude, OpenAI, and Gemini side by side (calls, streaming, structured output, and errors)
A practical guide to the official Anthropic, OpenAI, and Google SDKs in Python: setup, first call, streaming, structured output with Pydantic, errors and timeouts, a function to switch providers, token usage, and data safety.
AI$ pip install anthropic openai google-genai▍Testing a prompt in the browser takes a minute. Putting an LLM inside a script that classifies alerts or summarizes incidents takes more: a key stored in the right place, a streamed response, validated JSON, handled errors, and measured cost. This guide does all of that with the official SDKs for Claude (Anthropic), OpenAI, and Gemini (Google), side by side, so you can see what changes and what stays the same.
It’s part of the practical guide to AI with Python. If you don’t have an account or key yet, start with the step-by-step guides for the Claude API, the OpenAI API, and Google AI Studio.
Setting up the environment
Create a virtual environment and install the three SDKs plus Pydantic. The examples were written with Python 3.15, anthropic 2.14.0, openai 3.59.0, google-genai 3.6.1, and pydantic 2.14.4.
# option 1: venv + pip
python3 -m venv .venv
source .venv/bin/activate
pip install anthropic openai google-genai pydantic
# option 2: uv
uv venv
source .venv/bin/activate
uv pip install anthropic openai google-genai pydantic
Each SDK reads its key from an environment variable. Never write the key in your code or push it to Git: use environment variables or a secrets manager, as the 12-factor app recommends. The same goes for the model name: ids change often, so copy the current id from each provider’s models page and keep it in a variable.
export ANTHROPIC_API_KEY="..." # read by anthropic.Anthropic()
export OPENAI_API_KEY="..." # read by OpenAI()
export GEMINI_API_KEY="..." # read by genai.Client(); GOOGLE_API_KEY wins if both are set
export CLAUDE_MODEL="<id from Anthropic's models page>"
export OPENAI_MODEL="<id from OpenAI's models page>"
export GEMINI_MODEL="<id from the Gemini models page>"
The first call in each SDK
The question is the same in all three examples, and so is the system prompt. Only the shape of the call changes.
Claude (Anthropic)
Claude uses the Messages API. max_tokens is required and the system prompt goes in system. The response is a list of content blocks, and the text lives in the blocks of type text.
# claude_basic.py
import os
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
response = client.messages.create(
model=os.environ["CLAUDE_MODEL"],
max_tokens=512,
system="You are an experienced SRE. Answer in at most 3 sentences.",
messages=[{"role": "user", "content": "What is a readiness probe?"}],
)
for block in response.content:
if block.type == "text":
print(block.text)
OpenAI
At OpenAI, the API recommended for new projects is Responses. The system prompt goes in instructions and the question in input. The output_text property joins all the text in the response.
# openai_basic.py
import os
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY
response = client.responses.create(
model=os.environ["OPENAI_MODEL"],
instructions="You are an experienced SRE. Answer in at most 3 sentences.",
input="What is a readiness probe?",
)
print(response.output_text)
Gemini (Google)
In the google-genai SDK, options go in a GenerateContentConfig object, including the system prompt, in system_instruction.
# gemini_basic.py
import os
from google import genai
from google.genai import types
client = genai.Client() # reads GEMINI_API_KEY (or GOOGLE_API_KEY)
response = client.models.generate_content(
model=os.environ["GEMINI_MODEL"],
contents="What is a readiness probe?",
config=types.GenerateContentConfig(
system_instruction="You are an experienced SRE. Answer in at most 3 sentences.",
),
)
print(response.text)
Comparing the three
| Claude | OpenAI | Gemini | |
|---|---|---|---|
| Call | client.messages.create(...) |
client.responses.create(...) |
client.models.generate_content(...) |
| Where the text is | blocks with type == "text" in response.content |
response.output_text |
response.text |
| System prompt | system= |
instructions= |
system_instruction= in GenerateContentConfig |
| Output limit | max_tokens= (required) |
max_output_tokens= (optional) |
max_output_tokens= in the config (optional) |
Streaming
Without streaming, your program sits idle until the whole response arrives. With streaming, the text shows up as it’s generated, which makes chats and terminal tools feel much faster. In Claude, messages.stream is a context manager, and at the end get_final_message() returns the complete message, including token usage:
# claude_stream.py
import os
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model=os.environ["CLAUDE_MODEL"],
max_tokens=512,
messages=[{"role": "user", "content": "Explain what a rollback is in 3 sentences."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print()
print("output tokens:", final.usage.output_tokens)
At OpenAI, stream=True returns a sequence of typed events. The text arrives in response.output_text.delta events, and the response.completed event carries the final response:
# openai_stream.py
import os
from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
model=os.environ["OPENAI_MODEL"],
input="Explain what a rollback is in 3 sentences.",
stream=True,
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
elif event.type == "response.completed":
print()
print("output tokens:", event.response.usage.output_tokens)
Gemini has a dedicated method, generate_content_stream, which yields chunks with .text. A chunk may come without text, hence the or "":
# gemini_stream.py
import os
from google import genai
client = genai.Client()
for chunk in client.models.generate_content_stream(
model=os.environ["GEMINI_MODEL"],
contents="Explain what a rollback is in 3 sentences.",
):
print(chunk.text or "", end="", flush=True)
print()
Structured output with Pydantic
Free text is for humans. Your code wants JSON with fixed fields. All three providers accept a schema and return JSON that follows it. Define the model once, in a shared file:
# triage_model.py
from typing import Literal
from pydantic import BaseModel, Field
class Triage(BaseModel):
severity: Literal["low", "medium", "high", "critical"]
service: str = Field(description="Most affected service")
likely_cause: str
next_action: str
page_on_call: bool
INCIDENT = """\
14:02 alert: checkout p95 at 4.8 s (SLO: 800 ms)
14:03 payments: FATAL too many connections for role "app"
14:05 deploy v2.31 of the payments service finished at 13:58
"""
REQUEST = f"Triage this incident:\n{INCIDENT}"
In Claude, messages.parse takes the class in output_format, and the validated object lands in parsed_output:
# claude_triage.py
import os
import anthropic
from triage_model import REQUEST, Triage
client = anthropic.Anthropic()
response = client.messages.parse(
model=os.environ["CLAUDE_MODEL"],
max_tokens=1024,
messages=[{"role": "user", "content": REQUEST}],
output_format=Triage,
)
triage = response.parsed_output # already a Triage
print(triage.severity, triage.service, triage.page_on_call)
At OpenAI, responses.parse takes the class in text_format, and the result lands in output_parsed:
# openai_triage.py
import os
from openai import OpenAI
from triage_model import REQUEST, Triage
client = OpenAI()
response = client.responses.parse(
model=os.environ["OPENAI_MODEL"],
input=REQUEST,
text_format=Triage,
)
triage = response.output_parsed # already a Triage
print(triage.severity, triage.service, triage.page_on_call)
In Gemini, you pass the JSON Schema that Pydantic generates and validate the text yourself. In this mode, response.parsed holds a plain dict; model_validate_json gives you the typed object:
# gemini_triage.py
import os
from google import genai
from google.genai import types
from pydantic import ValidationError
from triage_model import REQUEST, Triage
client = genai.Client()
response = client.models.generate_content(
model=os.environ["GEMINI_MODEL"],
contents=REQUEST,
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_json_schema=Triage.model_json_schema(),
),
)
try:
triage = Triage.model_validate_json(response.text)
except ValidationError as error:
raise SystemExit(f"response does not match the schema: {error}")
print(triage.severity, triage.service, triage.page_on_call)
Even with a schema, treat the content as a suggestion: a critical severity can still be wrong. And not every JSON Schema feature is accepted by every provider; check the limitations in each one’s documentation.
Errors, retries, and timeouts
The Anthropic and OpenAI SDKs already retry transient failures on their own, with growing waits (backoff): HTTP 408, 409, 429, and 5xx, plus connection errors. The default is 2 retries, and the default read timeout is 10 minutes. google-genai doesn’t retry by default: you turn it on with HttpRetryOptions, and the timeout is in milliseconds.
# error_handling.py
import os
import anthropic
import openai
from google import genai
from google.genai import errors, types
claude = anthropic.Anthropic(max_retries=5, timeout=60.0) # timeout in seconds
gpt = openai.OpenAI(max_retries=5, timeout=60.0)
gemini = genai.Client(
http_options=types.HttpOptions(
timeout=60_000, # milliseconds
retry_options=types.HttpRetryOptions(attempts=5), # includes the first call
)
)
try:
claude.messages.create(
model=os.environ["CLAUDE_MODEL"], max_tokens=64,
messages=[{"role": "user", "content": "ping"}],
)
except anthropic.RateLimitError:
print("Claude: rate limited, even after retries")
except anthropic.APIStatusError as e:
print("Claude: HTTP", e.status_code)
except anthropic.APIConnectionError:
print("Claude: network failure or timeout")
try:
gpt.responses.create(model=os.environ["OPENAI_MODEL"], input="ping")
except openai.RateLimitError:
print("OpenAI: rate limited, even after retries")
except openai.APIStatusError as e:
print("OpenAI: HTTP", e.status_code)
except openai.APIConnectionError:
print("OpenAI: network failure or timeout")
try:
gemini.models.generate_content(model=os.environ["GEMINI_MODEL"], contents="ping")
except errors.ClientError as e: # 4xx, including 429
print("Gemini: HTTP", e.code, e.status)
except errors.ServerError as e: # 5xx
print("Gemini: HTTP", e.code, e.status)
The order of the except clauses matters: in the first two SDKs, RateLimitError and AuthenticationError are subclasses of APIStatusError, and APITimeoutError is a subclass of APIConnectionError. In Gemini, ClientError and ServerError inherit from errors.APIError; timeouts and network failures don’t become APIError, they arrive as exceptions from the HTTP library the SDK uses. To tweak a single call in Claude or OpenAI, use client.with_options(timeout=10.0). A 401 (invalid key) won’t get better with retries: log it and stop.
A function to switch providers
You don’t need a framework to switch providers. A dictionary of functions does the job, and clients are only created when used, so a missing key for one provider doesn’t break the others:
# llm.py
import functools
import os
import anthropic
import openai
from google import genai
from google.genai import types
SYSTEM = "Answer directly and concisely."
@functools.cache
def _client(provider: str):
# create each client only the first time its provider is used
if provider == "claude":
return anthropic.Anthropic()
if provider == "openai":
return openai.OpenAI()
return genai.Client()
def _claude(prompt: str) -> str:
r = _client("claude").messages.create(
model=os.environ["CLAUDE_MODEL"],
max_tokens=1024,
system=SYSTEM,
messages=[{"role": "user", "content": prompt}],
)
return "".join(b.text for b in r.content if b.type == "text")
def _openai(prompt: str) -> str:
r = _client("openai").responses.create(
model=os.environ["OPENAI_MODEL"], instructions=SYSTEM, input=prompt
)
return r.output_text
def _gemini(prompt: str) -> str:
r = _client("gemini").models.generate_content(
model=os.environ["GEMINI_MODEL"],
contents=prompt,
config=types.GenerateContentConfig(system_instruction=SYSTEM),
)
return r.text or ""
PROVIDERS = {"claude": _claude, "openai": _openai, "gemini": _gemini}
def ask(provider: str, prompt: str) -> str:
if provider not in PROVIDERS:
raise ValueError(f"unknown provider: {provider!r}")
return PROVIDERS[provider](prompt)
if __name__ == "__main__":
provider = os.environ.get("LLM_PROVIDER", "claude")
print(ask(provider, "Give me 3 tips to reduce MTTR."))
Run it with LLM_PROVIDER=gemini python llm.py. Switching providers becomes configuration, not a code change. Prompts, however, don’t always behave the same across models: compare the answers before switching in production. To run everything on your own machine, with no key and no per-token cost, see Ollama with Python; adding a fourth provider to the dictionary is easy.
Cost and latency: read the token usage
All three providers charge per token, and every response says how many were used. Log that on every call, along with latency:
| Provider | Input tokens | Output tokens |
|---|---|---|
| Claude | response.usage.input_tokens |
response.usage.output_tokens |
| OpenAI | response.usage.input_tokens |
response.usage.output_tokens (and total_tokens) |
| Gemini | response.usage_metadata.prompt_token_count |
response.usage_metadata.candidates_token_count (and total_token_count) |
# usage.py
import logging
import os
import time
import anthropic
import openai
from google import genai
logging.basicConfig(format="%(asctime)s %(message)s")
log = logging.getLogger("llm.usage")
log.setLevel(logging.INFO) # only our logger at INFO, without the HTTP noise
question = "Summarize what an SLO is in one sentence."
# keep each client in a variable and reuse it across calls
claude, gpt, gemini = anthropic.Anthropic(), openai.OpenAI(), genai.Client()
start = time.perf_counter()
r = claude.messages.create(
model=os.environ["CLAUDE_MODEL"], max_tokens=256,
messages=[{"role": "user", "content": question}],
)
log.info("claude input=%d output=%d %.2fs", r.usage.input_tokens,
r.usage.output_tokens, time.perf_counter() - start)
start = time.perf_counter()
r = gpt.responses.create(model=os.environ["OPENAI_MODEL"], input=question)
log.info("openai input=%d output=%d %.2fs", r.usage.input_tokens,
r.usage.output_tokens, time.perf_counter() - start)
start = time.perf_counter()
r = gemini.models.generate_content(
model=os.environ["GEMINI_MODEL"], contents=question
)
u = r.usage_metadata
log.info("gemini input=%s output=%s %.2fs", u.prompt_token_count,
u.candidates_token_count, time.perf_counter() - start)
Notice the clients in variables. In google-genai, chaining genai.Client().models.generate_content(...) fails: the temporary client is discarded and closes its HTTP connection before the call.
The usage objects have more fields, such as cache or reasoning tokens, and how each one is billed varies by provider; check the docs before you build a dashboard. Add these numbers up per request and per feature and you get to cost per token, the topic of the FinOps for AI guide. As for latency, streaming doesn’t cut the total time, but it does cut the time to the first word, which is what users feel.
About sampling parameters: in the current API version, Claude doesn’t accept temperature, top_p, or top_k, and SDK 2.14.0 rejects those arguments in messages.create. OpenAI and Gemini have their own parameters (for example, temperature in responses.create and in GenerateContentConfig), but support may vary by model. Check each provider’s documentation before copying settings from one to another.
Data and security
- What leaves your machine: everything in the prompt, including logs, tickets, and code snippets, is sent to the provider. Data retention and use for training vary by plan and contract; check your plan’s terms and your company’s policy.
- Privacy laws: before sending personal data, confirm the legal basis and the provider contract with your legal team or DPO, under privacy laws such as Brazil’s LGPD or the GDPR. Masking IDs, emails, and names before the call reduces the risk. If the data can’t leave, a local model with Ollama keeps the text on your machine.
- Prompt injection: a log line or an email can contain instructions aimed at the model. Treat the output as untrusted data: validate it with Pydantic, never pass the response to
eval,exec, or a shell, and require human review for actions that change anything. See the guide to AI application security. - Keys: one key per environment, with a spend limit in the provider’s dashboard and periodic rotation.
Checklist
- I created a venv (or used uv) and installed
anthropic,openai,google-genai, andpydantic - Keys and model ids live in environment variables, out of the code and out of Git
- I use streaming in interactive tools
- I validate every structured output with Pydantic
- I set
max_retriesandtimeout(andHttpRetryOptionsin Gemini) and catch the right exceptions - I log input tokens, output tokens, and latency for every call
- I know which data goes to the provider, and I never execute the model’s output
Three SDKs, one pattern: key in the environment, validated response, handled error, and measured tokens.