Learn / Python for AI / Lesson 5

Calling LLM APIs from Python

15 min Tested on Python 3.15Updated By
In short

You call an LLM by sending a list of messages to the provider's API — with their Python SDK — and reading the text that comes back. Keep the API key in an environment variable, give clear instructions in a system prompt, ask for structured JSON when code needs to use the answer, validate it with Pydantic, and always handle timeouts and retries.

Setup

terminal
uv add anthropic pydantic
export ANTHROPIC_API_KEY="sk-..."      # Windows PowerShell: $env:ANTHROPIC_API_KEY="sk-..."

Your first call

first_call.py · run on your computer
import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=300,
    system="You are a patient Python tutor. Answer in at most three sentences.",
    messages=[{"role": "user", "content": "What is a list comprehension?"}],
)
print(response.content[0].text)
print(response.usage.input_tokens, "in /", response.usage.output_tokens, "out tokens")
  • system sets the role and rules; messages is the conversation so far.
  • max_tokens caps the length of the answer — and the cost.
  • Tokens are pieces of words (roughly ¾ of an English word each). You pay per token in and out.
  • OpenAI, Google Gemini and other providers have very similar SDKs: a client, a model name and a list of messages. Check each provider's docs for current model names.

Conversations are just lists

Python
messages = []

def add(role: str, text: str) -> None:
    messages.append({"role": role, "content": text})

add("user", "Suggest a name for a Python study group.")
add("assistant", "How about 'The Indentation Club'?")
add("user", "Make it shorter.")

for m in messages:
    print(f"{m['role']:>9}: {m['content']}")
print(len(messages), "messages sent with the next request")
Output
     user: Suggest a name for a Python study group.
assistant: How about 'The Indentation Club'?
     user: Make it shorter.
3 messages sent with the next request

The model has no memory between calls. To continue a conversation, you send the whole history every time — which is why long chats cost more and eventually need trimming or summarising.

Streaming

stream.py · run on your computer
import anthropic

client = anthropic.Anthropic()
with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=400,
    messages=[{"role": "user", "content": "Explain Python generators to a beginner."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Streaming shows words as they're generated, so users see an answer start within a second instead of waiting for the whole reply. Chat interfaces almost always stream.

Structured output you can trust

Python
import json
from pydantic import BaseModel, ValidationError

class Review(BaseModel):
    sentiment: str
    score: int
    topics: list[str]

# what the model returned when asked for JSON matching the Review schema
reply = '{"sentiment": "positive", "score": 4, "topics": ["delivery", "price"]}'
review = Review.model_validate_json(reply)
print(review.sentiment, review.score, review.topics)

bad_reply = '{"sentiment": "positive", "score": "four"}'
try:
    Review.model_validate_json(bad_reply)
except ValidationError as err:
    print(err.error_count(), "problems found")

print(json.dumps(Review.model_json_schema()["required"]))
Output
positive 4 ['delivery', 'price']
2 problems found
["sentiment", "score", "topics"]

When code needs to use an answer, ask for JSON that matches a schema and validate it. Pydantic turns the reply into a typed object, or tells you exactly what's wrong so you can retry. Most SDKs can also send the schema to the model directly.

Retries and timeouts

Python
import random
import time

def call_with_retry(call, attempts: int = 4, base_delay: float = 0.01):
    for attempt in range(1, attempts + 1):
        try:
            return call()
        except TimeoutError:
            if attempt == attempts:
                raise
            delay = base_delay * 2 ** attempt + random.uniform(0, base_delay)
            print(f"attempt {attempt} timed out, retrying")
            time.sleep(delay)

results = iter([TimeoutError(), TimeoutError(), "Here is your answer."])

def flaky_llm():
    r = next(results)
    if isinstance(r, Exception):
        raise r
    return r

print(call_with_retry(flaky_llm))
Output
attempt 1 timed out, retrying
attempt 2 timed out, retrying
Here is your answer.

LLM APIs are busy services: requests sometimes time out or get rate-limited. Retry with exponential back-off plus a little randomness. The official SDKs already retry common errors, and let you set timeout and max_retries on the client.

Practice

Estimate cost before you call. Write estimate_cost(input_tokens, output_tokens, in_price, out_price) where prices are per million tokens, returning dollars. Print the cost of 12,000 input and 800 output tokens at $3 in / $15 out per million, rounded to 4 decimals, then the cost of 1,000 such calls rounded to 2 decimals.

Expected output:
0.048
48.0
Your code

Quick check

1. Where should an API key live?

2. Does the model remember your previous request?

3. Why validate JSON from a model with Pydantic?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →