Chapter 05 · Section II · 30 min read
Your first API call to a language model
Twenty minutes of setup, ten lines of code, and your Python program is talking to a frontier language model. The smallest end-to-end AI application of the entire track.
This is the section the previous four chapters were preparing you for. By the end of it, you will have a Python program that sends a piece of text to Claude — or Gemini, or GPT; the shape is almost identical — and receives a written response back. Not a chat-window response. A response your code receives, which it can pass to another step, save to a file, post to Telegram, or display in an app. This is the moment “building AI” stops being a phrase and becomes a thing you have done.
Getting an API key
We will use Anthropic’s Claude as the example. You can do the same exercise with OpenAI, Google, or any other major API; the code is almost word-for-word the same.
- Go to
console.anthropic.comand sign up. You will need an email and a phone number. - Anthropic gives most new accounts a small amount of free credit — usually a few US dollars. That is enough for hundreds of small experiments in this track.
- Once logged in, find the API Keys page in the console. Click “Create Key”, give it a name like “building-ai-course”, and copy the key immediately. The console will only show the key once.
The key looks like sk-ant-api03-... followed by a long random string. Treat it as a password. Anyone with this key can spend money from your account.
Storing the key safely
In your project folder, create a file called .env:
ANTHROPIC_API_KEY=sk-ant-api03-...your-key...
Make sure .env is in your .gitignore. (It should already be there from Chapter 4.)
In Python, load it like this:
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ["ANTHROPIC_API_KEY"]
You need one extra install for this — the python-dotenv package:
pip install python-dotenv
The load_dotenv() call reads the .env file and adds its contents to os.environ. Then os.environ["ANTHROPIC_API_KEY"] retrieves the key. Your code never contains the key directly; only the file (which is never committed) does.
Installing the Anthropic SDK
Anthropic publishes a Python library that handles all the HTTP plumbing for you:
pip install anthropic
Then update your requirements.txt:
pip freeze > requirements.txt
Your first call
The smallest complete program:
import os
from dotenv import load_dotenv
import anthropic
load_dotenv()
client = anthropic.Anthropic() # picks up ANTHROPIC_API_KEY automatically
response = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=300,
messages=[
{"role": "user", "content": "Explain in two sentences what NEPSE is."},
],
)
print(response.content[0].text)
Run it. After a second or two of waiting, you will see something like:
NEPSE — the Nepal Stock Exchange — is the country's main equity market,
where shares in Nepali companies, banks, and hydropower projects are
listed and traded. It is regulated by the Securities Board of Nepal
(SEBON) and located in Singha Durbar, Kathmandu.
That is the entire shape of every language-model program you will ever write. Read it back slowly:
client.messages.create(...)is the call. It sends a request to Anthropic’s servers and waits for a reply.model="claude-haiku-4-5-20251001"chooses which model. Anthropic offers a range — Haiku is fast and cheap; Sonnet is balanced; Opus is the most capable. For most of this track, Haiku is plenty.max_tokens=300caps how long the reply can be. Tokens are roughly three quarters of a word; 300 tokens is about 220 words.messages=[...]is the conversation so far. Here it has one message — yours, marked with role"user". In Course 04, you will pass longer message lists to build conversations.response.content[0].textis how you read the model’s reply. The structure of the response is a list of content blocks; the first one’s.textfield is what you typed up to the model and the model wrote back.
A more interesting call
A program that takes a NEPSE summary line and asks the model to translate and explain it in Nepali:
import os
from dotenv import load_dotenv
import anthropic
load_dotenv()
client = anthropic.Anthropic()
market_note = (
"NEPSE closed at 2,134.7 — up 0.8 percent on the day. "
"Banking shares led the gains; hydropower was mixed."
)
prompt = (
f"You are explaining the Nepali stock market to a shopkeeper "
f"in Itahari who does not read English. Translate and gently "
f"explain the following market note in plain Nepali, in 3-4 sentences. "
f"Use Devanagari script.\n\n"
f"Market note: {market_note}"
)
response = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=400,
messages=[
{"role": "user", "content": prompt},
],
)
print(response.content[0].text)
The response will be a 3-4 sentence Nepali explanation in Devanagari. Notice three real builder moves in that prompt:
- A role. Telling the model “you are explaining to a shopkeeper in Itahari” steers it toward simple, grounded language.
- A length. “3-4 sentences” prevents the model from rambling.
- A format. “Use Devanagari script” tells it which script to write in.
In Course 04 we will spend a whole chapter on prompting in code. For now, notice that even these three small framings make the output dramatically better.
What it costs
Anthropic prices per million tokens of input and output, and prices change. As of late 2025, Haiku is roughly a quarter of a US dollar per million input tokens — meaning a typical small call like the one above costs a small fraction of a paisa. Your free credit will last you the whole track if you are not careless.
To check usage, the API console has a “Usage” page. Glance at it once a week while you are learning. If you ever see the daily number climb unexpectedly, you almost certainly have an infinite loop or a script you forgot to kill.
Error handling, briefly
Network calls fail. APIs return errors. Your code should be ready:
try:
response = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=300,
messages=[{"role": "user", "content": "Say hi"}],
)
print(response.content[0].text)
except anthropic.APIError as e:
print(f"API error: {e}")
For now a single try/except is enough. In Course 04 we will handle rate limits, retries, and timeouts properly.
Check your understanding
Quick check
—A junior developer commits the following file to a public GitHub repo: # config.py ANTHROPIC_API_KEY = 'sk-ant-api03-abc123...' What is the most accurate description of what they should do?
Quick check
—You write a prompt that says: 'Summarise this paragraph.' The model's reply is rambling, in formal English, and three times longer than you wanted. Based on this section, which change is most likely to help — without changing the input paragraph?
What comes next
You have spoken to a language model from your own code. In the next section you do something different: you load a model onto your own laptop and use it to read Nepali text out of an image. No internet, no API. Pure on-device AI — the other side of the coin from what you just did, and the foundation of every privacy-sensitive AI application you will ever build.