Module 5 of 6 · 55 minutes

Calling AI model APIs

Now connect Python to an AI model. This module shows how to call an API securely and turn its output into data your code can use.

By · Last updated

Learning objectives

  • Explain the request–response pattern of AI APIs
  • Store and use API keys securely
  • Make an API call with an official SDK
  • Get structured output, first by asking for JSON and then with a schema
  • Describe how tool use and MCP let a model take actions
  • Handle errors, rate limits and cost
  • Track token use and estimate cost
  • Cache answers and explain how multi-turn conversations work

5.1 How AI APIs work

An AI model API is a web service: your code sends a request (your prompt, settings and an API key) and receives a response (the model's output, plus information such as token usage). Providers publish official Python SDKs that handle the details.

Practice mode on this page

Calling a real model needs a secret API key, and a key must never sit in a web page. So the cells in this module talk to a small pretend model built into the page. The code is exactly what you'd write for the real thing, but the replies are canned, not real AI. To use a real model, copy the code into Colab and add your own key (see 5.2).

Your Python codeask(prompt)Provider APImodel runs hererequest: key + model + messagesresponse: text + token usageKey from env /Colab Secrets
Calling an AI API: your code sends the prompt with a secret key; the provider returns the output and how many tokens it used.

5.2 Keep your API key secret

  • Never put keys in your code, notebooks you share, or prompts
  • Store them as environment variables — or in Colab, use the Secrets panel (key icon)
  • Set spending limits in your provider account
  • If a key leaks, revoke it immediately
Python · reading a key safely (for Colab or your own computer)import os
# In Colab: from google.colab import userdata; os.environ["ANTHROPIC_API_KEY"] = userdata.get("ANTHROPIC_API_KEY")
assert "ANTHROPIC_API_KEY" in os.environ, "Set your API key as an environment variable first"

5.3 Your first API call

Python · calling a model (Anthropic SDK; OpenAI and Gemini SDKs are very similar)# In Colab, first run: !pip install anthropic
import anthropic

client = anthropic.Anthropic()          # with the real SDK, this reads ANTHROPIC_API_KEY
response = client.messages.create(
    model="YOUR-MODEL-NAME",            # copy a current model name from the provider's docs
    max_tokens=300,
    system="You are a concise assistant for a UK kitchenware shop.",
    messages=[{"role": "user", "content": "Suggest three names for a bamboo utensil set."}],
)
print(response.content[0].text)
print(response.usage)                   # input and output tokens — this is what you pay for

5.4 A reusable helper function

def ask(prompt, system="You are a helpful assistant.", max_tokens=500):
    r = client.messages.create(model="YOUR-MODEL-NAME", max_tokens=max_tokens, system=system,
                               messages=[{"role": "user", "content": prompt}])
    return r.content[0].text

print(ask("Explain a Python dictionary in two sentences."))

5.5 Getting structured output

To use AI output in code you need data, not prose. There are two ways to get it.

The simple way: ask for JSON, then check it

import json

def classify_review_basic(text):
    prompt = f"""Classify this customer review.
Return JSON only, with keys: "sentiment" (positive/neutral/negative),
"topic" (product/delivery/price/other) and "summary" (max 10 words).

Review: {text}"""
    raw = ask(prompt, system="You return only valid JSON.")
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return {"sentiment": None, "topic": None, "summary": None, "error": raw[:80]}

print(classify_review_basic("Lovely board but it took two weeks to arrive."))
print(classify_review_basic("Fine. Does the job."))

The second review comes back with an error: the model added a friendly sentence before the JSON, so json.loads failed. Real models do this now and then, which is why the try/except from Module 3 is there.

The reliable way: give the model a schema

Current APIs offer structured outputs: you describe the shape you want, and the API guarantees the reply matches it. In Python you describe the shape as a small class, using the pydantic library.

from typing import Literal
from pydantic import BaseModel

class Review(BaseModel):
    sentiment: Literal["positive", "neutral", "negative"]
    topic: Literal["product", "delivery", "price", "other"]
    summary: str

def classify_review(text):
    r = client.messages.parse(
        model="YOUR-MODEL-NAME",
        max_tokens=200,
        messages=[{"role": "user", "content": f"Classify this customer review.\n\nReview: {text}"}],
        output_format=Review,               # the reply must match the Review class
    )
    return r.parsed_output.model_dump()     # a plain dictionary

print(classify_review("Lovely board but it took two weeks to arrive."))
print(classify_review("Fine. Does the job."))

No parsing, no try/except, and the labels can only be the ones you listed. This example uses Anthropic's SDK; OpenAI and Google offer the same idea under the same name. A valid shape is not the same as a correct answer, though: you still need to check the labels (Module 6).

5.6 Giving the model tools

On its own, a model can only produce text. To let it look something up or take an action, you give it tools: Python functions it is allowed to ask for. The model never runs your code. It replies "please call this function with these inputs", your code runs the function and sends the result back, and the model writes its final answer. A model that works through several tool calls in a loop to finish a task is what people mean by an AI agent.

Python · the tool-use steps, without a modelstock = {"bamboo board": 12, "utensil set": 0}

def check_stock(product):
    # A tool is an ordinary Python function.
    return {"product": product, "in_stock": stock.get(product, 0)}

# 1. You describe the tool to the model (this goes in the tools=[...] setting of the API call)
tool_description = {
    "name": "check_stock",
    "description": "Look up how many units of a product are in stock.",
    "input_schema": {"type": "object",
                     "properties": {"product": {"type": "string"}},
                     "required": ["product"]},
}

# 2. A customer asks "Do you have the bamboo board?" and the model replies with a request like this
tool_request = {"type": "tool_use", "name": "check_stock", "input": {"product": "bamboo board"}}

# 3. Your code runs the function the model asked for
tools = {"check_stock": check_stock}
result = tools[tool_request["name"]](**tool_request["input"])
print(result)

# 4. You send the result back, and the model writes the answer for the customer

MCP (Model Context Protocol) is an open standard for packaging tools so that any AI app can plug into them — a bit like USB for AI. Instead of writing a tool separately for each app, a team publishes one MCP server (for its calendar, database or help desk), and assistants and agents connect to it. The AI Agents course builds on this.

5.7 Handling errors and limits

import time

def ask_with_retry(prompt, attempts=3):
    for i in range(attempts):
        try:
            return ask(prompt)
        except anthropic.RateLimitError:
            time.sleep(2 ** i)            # wait 1s, 2s, 4s
        except anthropic.APIError as e:
            print("API error:", e)
            break
    return None

print(ask_with_retry("Suggest three names for a bamboo utensil set."))
Mind the cost

You pay per token, for input and output. Test on a handful of rows before running thousands, set max_tokens, and check response.usage.

5.8 Keeping track of cost

Every response tells you how many tokens it used. Add them up as you go and you always know what a job is costing — before the invoice arrives.

PRICE_IN, PRICE_OUT = 1.00, 5.00        # EXAMPLE prices in £ per million tokens — check your provider's price list
used = {"calls": 0, "input": 0, "output": 0}

def ask_tracked(prompt, max_tokens=300):
    r = client.messages.create(model="YOUR-MODEL-NAME", max_tokens=max_tokens,
                               messages=[{"role": "user", "content": prompt}])
    used["calls"] += 1
    used["input"] += r.usage.input_tokens
    used["output"] += r.usage.output_tokens
    return r.content[0].text

for question in ["Suggest three names for a bamboo utensil set.", "Explain a Python dictionary in two sentences."]:
    ask_tracked(question)

cost = (used["input"] * PRICE_IN + used["output"] * PRICE_OUT) / 1_000_000
print(used)
print(f"Cost so far: £{cost:.6f}")
print(f"The same two questions asked 100,000 times: about £{cost * 100_000:,.2f}")

Output tokens usually cost several times more than input tokens, which is one more reason to set max_tokens and to ask for short answers when short answers will do.

5.9 Don't pay twice: caching

While you're developing, you'll run the same cell again and again. Without care, every run calls the API again for answers you already have. A cache — here just a dictionary — remembers them.

cache = {}

def ask_cached(prompt):
    if prompt not in cache:
        cache[prompt] = ask_tracked(prompt)        # only call the model for something new
    return cache[prompt]

before = used["calls"]
for review in ["Lovely board", "Arrived late", "Lovely board", "Arrived late", "Lovely board"]:
    ask_cached(f"Summarise this review in three words: {review}")
print("Reviews processed: 5   API calls made:", used["calls"] - before)

Five reviews, two calls: the repeats cost nothing. Run the cell a second time and it makes no calls at all. For real projects, save the cache to a file (JSON Lines from Module 3 works well) so it survives restarting the notebook. A cache is only right when the same prompt should always give the same answer; clear it when you change the model or the instructions.

5.10 A longer conversation

The model has no memory between calls. A chat only feels continuous because your code sends the whole conversation every time, as a growing messages list in which the roles alternate:

conversation = [
    {"role": "user", "content": "Suggest three names for a bamboo utensil set."},
]
first = client.messages.create(model="YOUR-MODEL-NAME", max_tokens=200, messages=conversation)
conversation.append({"role": "assistant", "content": first.content[0].text})      # keep the model's reply
conversation.append({"role": "user", "content": "Explain a Python dictionary in two sentences."})

second = client.messages.create(model="YOUR-MODEL-NAME", max_tokens=200, messages=conversation)
for turn in conversation:
    print(f"{turn['role']:>9}: {turn['content'][:60]}")
print(f"assistant: {second.content[0].text[:60]}")
print("Input tokens, first call:", first.usage.input_tokens, "  second call:", second.usage.input_tokens)

The second call's input is larger than the first, because it carries the whole conversation so far. Long chats therefore get slower and more expensive with every turn, and eventually reach the model's limit; real applications trim or summarise older turns. (The practice model on this page only reads the latest question. A real model reads everything you send, which is what lets it answer "make the second one shorter".)

Exercise: flag the urgent reviews

Write a function triage(text) that uses client.messages.parse with a schema containing sentiment, topic and a true/false field urgent. Run it on the three reviews in the starter code and print only the urgent ones.

Your turnimport anthropic
from typing import Literal
from pydantic import BaseModel

client = anthropic.Anthropic()
inbox = ["Perfect gift, beautifully packaged!",
         "Courier left it in the rain, box soaked.",
         "The handle on the spatula snapped after a week."]

# Define a Triage schema and triage(text), then press Run
Show a solution
import anthropic
from typing import Literal
from pydantic import BaseModel

client = anthropic.Anthropic()
inbox = ["Perfect gift, beautifully packaged!",
         "Courier left it in the rain, box soaked.",
         "The handle on the spatula snapped after a week."]

class Triage(BaseModel):
    sentiment: Literal["positive", "neutral", "negative"]
    topic: Literal["product", "delivery", "price", "other"]
    urgent: bool

def triage(text):
    r = client.messages.parse(
        model="YOUR-MODEL-NAME", max_tokens=200, output_format=Triage,
        messages=[{"role": "user", "content": f"Classify this customer review.\n\nReview: {text}"}])
    return r.parsed_output.model_dump()

for review in inbox:
    result = triage(review)
    if result["urgent"]:
        print("URGENT:", review, result)
Exercise: estimate before you run

You have 20,000 reviews averaging 240 characters, and a 600-character instruction sent with each. Using the rule of thumb of 4 characters per token, a 30-token reply, and the example prices in the starter code, estimate the cost of classifying them all. Then work out the saving if the instruction is cut to 200 characters.

Your turnPRICE_IN, PRICE_OUT = 1.00, 5.00        # EXAMPLE prices in £ per million tokens

# Write job_cost(n, review_chars, instruction_chars, reply_tokens=30), then press Run
Show a solution
PRICE_IN, PRICE_OUT = 1.00, 5.00        # EXAMPLE prices in £ per million tokens

def job_cost(n, review_chars, instruction_chars, reply_tokens=30):
    tokens_in = n * (review_chars + instruction_chars) / 4
    tokens_out = n * reply_tokens
    return (tokens_in * PRICE_IN + tokens_out * PRICE_OUT) / 1_000_000

full = job_cost(20_000, 240, 600)
short = job_cost(20_000, 240, 200)
print(f"With a 600-character instruction: £{full:.2f}")
print(f"With a 200-character instruction: £{short:.2f}")
print(f"Saving: £{full - short:.2f} ({(full - short) / full:.0%})")
# The instruction is repeated 20,000 times, so trimming it matters more than anything else.

Key takeaways

  • Your code sends a prompt and key; the API returns output and token usage.
  • Keep keys in environment variables or Colab Secrets — never in code.
  • Wrap calls in a helper function.
  • For data your code can rely on, use structured outputs with a schema; if you only ask for JSON, validate it.
  • Tools let a model ask your code to run functions; MCP is the open standard for sharing tools between AI apps.
  • Retry rate-limit errors with back-off; test small to control cost.
  • Add up response.usage as you go; cache answers so reruns cost nothing.
  • The model has no memory: your code resends the whole conversation each turn.