Python AI for Beginners: Call an LLM in 25 Lines

Python AI for beginners does not have to mean months of maths before you get to touch anything fun. You can call a real large language model, the same kind that powers the chat assistants you already use, in about 25 lines of Python. This post gets you from zero to a working AI script: get a key, install one library, send a prompt, and read the reply. Then we build a tiny study helper that explains any Python error you paste into it.

“Machines take me by surprise with great frequency.”

Alan Turing, Computing Machinery and Intelligence

Last Updated: July 2026 | Tested on: Python 3.14.6, anthropic SDK 0.111.0, tiktoken 0.13 | Difficulty: Beginner | Reading Time: 17 minutes

Here is the honest truth that most courses hide until chapter nine: talking to an AI model from your own code is easier than reading a file. There is no machine learning to understand first, no neural network to train, no Graphics Processing Unit (GPU) to buy. You write a question as a normal Python string, hand it to a library, and a sentence of text comes back. If you have finished the earlier posts on strings, functions, and errors, you already know everything you need.

The deeper theory, how the model actually predicts each word, what tokens and context windows are, temperature and embeddings, all gets its own proper treatment later in the series (Part 7). Python AI for beginners means making it work first.

What an LLM API Actually Is, in Five Sentences

Think of ordering a thali at a restaurant you cannot see into. You write your order on a slip (your prompt), hand it through a window (the API), the kitchen you never enter does the work (the model), and a plate comes back (the reply). You do not need to know how the kitchen runs to enjoy the meal, and you do not need to understand neural networks to use a model.

Here is the whole idea in five sentences. An LLM (large language model) is a program that has read a huge amount of text and learned to predict what words come next. An API (application programming interface) is just a doorway that lets your code send a request to that model over the internet and get a response back. You send a prompt, which is plain text, and you get back plain text. The model provider runs the heavy machine on their servers, so your laptop only sends a small message and waits for the answer. That round trip, question out and answer back, is the entire thing you are learning today.

you pay for input+ output tokensYour Python scriptbuilds a prompt string,the question you askSDK + API keysends the prompt overHTTPS to the providerProvider APIchecks your key, splits theprompt into tokens (wordchunks)The modelpredicts the reply,one token after anotherJSON replythe answer text plus a usagecount of tokens billedBack in your scriptmessage.content[0].textholdsthe answer, print() shows itOne LLM Call: The Prompt to Response Round Trip

The diagram traces one call from start to finish. Your script builds a prompt string and the SDK ships it, together with your API key, over an encrypted connection to the provider. Their API checks the key and splits your text into tokens, which are small chunks of words. The model reads those tokens and predicts the reply one token at a time, then everything is packed into a small JSON message: the answer text plus a usage count of how many tokens you used.

That message lands back in your script, where one line of Python pulls out the text and prints it. You pay for the tokens going in and the tokens coming out, which is why the whole call costs a fraction of a rupee.

Get a Key and Install One SDK

An API key is like the PIN on your metro card. It proves the request is yours so the provider knows whose account to bill, and it is a secret you never share or paste into your code. Two quick steps get you ready.

Step 1, get a key. Sign up on your provider’s developer console (this post uses Anthropic’s Claude as the main example), open the API keys page, and create a key. It looks like a long string starting with sk-. Copy it once, because the console will not show it again.

Step 2, install one library and set the key. The SDK (software development kit) is the small Python package that does the network work for you. Install it, then store your key in an environment variable so it stays out of your code.

📄 terminal: install the SDK and set your key

pip install anthropic

# macOS / Linux (this session only):
export ANTHROPIC_API_KEY="sk-paste-your-key-here"

# Windows PowerShell (this session only):
$env:ANTHROPIC_API_KEY = "sk-paste-your-key-here"

What happened here: pip install anthropic downloads the official Python library. The export (or $env: on Windows) line puts your key into an environment variable named ANTHROPIC_API_KEY, which the library reads automatically. Setting it this way keeps the secret out of your .py file, so you can share your code or push it to GitHub without leaking your key. At the time of writing the package name is anthropic; the other providers have their own, which we show near the end.

Python AI for Beginners: Your First LLM Call in 25 Lines

This is the moment. Save the file below as first_call.py and run it. It asks the model a small question and prints the reply. Read the comments, because every line earns its place.

📄 first_call.py: your first message to an LLM

import anthropic  # the library you just installed

# Pin the model in one place so future-you knows exactly what ran.
MODEL = "claude-opus-4-8"  # swap when models change

# The client reads your key from the ANTHROPIC_API_KEY environment
# variable. You never paste the key into the code itself.
client = anthropic.Anthropic()

# messages is a list of turns. Here we send one user turn: our question.
message = client.messages.create(
    model=MODEL,
    max_tokens=300,          # a ceiling on how long the reply can be
    messages=[
        {
            "role": "user",
            "content": "In one sentence, explain what an API key is to a beginner.",
        },
    ],
)

# The reply comes back as a list of content blocks. For a plain text
# answer, the words live in the first block.
reply = message.content[0].text
print(reply)

▶ Example output

An API key is a secret password that tells a service the request is coming from your account, so it can let you in and keep track of your usage.

What happened here: the output is labelled “Example output” because a live model call needs your own key and network, so your exact wording will differ slightly each run. Everything else is real and runs as shown. client.messages.create() is the one function that sends your prompt and waits for the reply. You passed it the model name, a max_tokens ceiling, and a messages list holding a single user turn. The answer arrives as message.content, a list of blocks, and for a plain text reply the text sits in message.content[0].text. That is the full round trip from the diagram, done in one function call.

Pin the Model in a Constant

Notice the MODEL = "claude-opus-4-8" line at the top. That small habit saves you real pain later. Model names change every few months as providers release newer, smarter versions and retire old ones. If you scatter the name across ten function calls, upgrading means hunting down all ten. Put it in one constant and a future upgrade is a single edit.

Think of it like the phone number saved as “Doctor” in your contacts. When the clinic changes its number, you update one entry, and every reminder that calls “Doctor” keeps working. The comment # swap when models change is a note to future-you: this is the one line to touch when a newer model lands. At the time of writing (mid-2026) claude-opus-4-8 is a current model, but treat any specific name as a value that will move, not a fact carved in stone.

Build a Study Helper for Python Errors

Now something you will actually use while learning. Every beginner hits confusing error messages (we covered the most common ones in the Python error messages post). Let us build a helper that takes any error you paste in and explains it in plain English. Say a learner named Aditi keeps getting an IndentationError and wants a friendlier explanation than the raw traceback.

Before wiring in the model, a good habit is to print your prompt first and read exactly what you are about to send. This costs nothing and catches half of all “why did the AI answer the wrong thing” moments. Here is just the prompt-building part, which runs on its own with no key needed:

📄 peek_prompt.py: see exactly what you send before you send it

# peek_prompt.py: see exactly what you send before you send it
error_text = "IndentationError: expected an indented block after 'if' statement on line 3"

prompt = f"""You are a patient Python tutor for a beginner.
Explain this error in plain English, give the most likely cause,
and show one corrected code snippet. Keep it under 120 words.

The error:
{error_text}"""

print(prompt)

▶ Output

You are a patient Python tutor for a beginner.
Explain this error in plain English, give the most likely cause,
and show one corrected code snippet. Keep it under 120 words.

The error:
IndentationError: expected an indented block after 'if' statement on line 3

What happened here: that output is real, printed straight from Python. An f-string glued your instructions and the pasted error into one clear message. This is called a prompt, and giving the model a role (“a patient Python tutor”) plus a shape (“plain English, the cause, one snippet, under 120 words”) is what turns a vague reply into a useful one. Now we swap the print for a real call and let the reader paste any error they like.

📄 error_helper.py: an AI tutor for Python errors

import anthropic

MODEL = "claude-opus-4-8"  # swap when models change
client = anthropic.Anthropic()

# Paste any Python error you got, and let the model explain it.
error_text = input("Paste your Python error: ")

prompt = f"""You are a patient Python tutor for a beginner.
Explain this error in plain English, give the most likely cause,
and show one corrected code snippet. Keep it under 120 words.

The error:
{error_text}"""

message = client.messages.create(
    model=MODEL,
    max_tokens=500,
    messages=[{"role": "user", "content": prompt}],
)

print(message.content[0].text)

▶ Example output

Paste your Python error: IndentationError: expected an indented block after 'if' statement on line 3

Plain English: Python expected some indented code right after your `if` line,
but the next line was empty or lined up with the `if` instead of sitting inside it.

Most likely cause: you wrote an `if` and forgot to indent the line under it.
Every block after a colon must be indented (4 spaces is standard).

Fixed:
    if score >= 50:
        print("Pass")   # this line is indented, so it belongs to the if

What happened here: input() waits for Aditi to paste an error, that text drops into the prompt, and the model returns a beginner-friendly explanation. You have built a genuinely useful tool in under 20 lines: an on-demand tutor that reads any traceback and tells you what to fix. Change the instructions in the prompt and you change the behaviour, for example ask it to explain code, write a docstring, or translate a comment. Same 20 lines, endless uses.

Count the Tokens Yourself

The cost section below charges you “per token,” so it is worth seeing exactly what a token is instead of taking it on faith. A token is the small chunk of text a model actually reads, usually a whole word, a piece of a word, or a punctuation mark. You can count them yourself with a tiny library called tiktoken (install it once with pip install tiktoken). This is the same counting the paid API does before it bills you, so it turns the price from a mystery into plain arithmetic.

📄 count_tokens.py: see and count the tokens in your text

import tiktoken

# o200k_base is the tokenizer for GPT-4o and other modern OpenAI models
enc = tiktoken.get_encoding("o200k_base")

# 1) See the tokens inside a sentence
text = "I am learning to call an AI."
ids = enc.encode(text)
print("text        :", repr(text))
print("token count :", len(ids))
print("the pieces  :", [enc.decode([i]) for i in ids])

# 2) Some words are one token, some split into several
print()
for word in ["cat", "learning", "strawberry"]:
    pieces = [enc.decode([i]) for i in enc.encode(word)]
    print(f"{word:12} -> {len(pieces)} token(s): {pieces}")

# 3) Count a whole request and estimate the bill
print()
prompt = "Explain a Python IndexError in one line."
reply = "An IndexError means you asked for a list position that does not exist."
tin, tout = len(enc.encode(prompt)), len(enc.encode(reply))
price_in, price_out = 0.15, 0.60   # dollars per 1,000,000 tokens; real prices vary by model
cost = tin / 1_000_000 * price_in + tout / 1_000_000 * price_out
print("prompt tokens:", tin, "| reply tokens:", tout, "| total:", tin + tout)
print(f"rough cost   : ${cost:.8f}")

▶ Output

text        : 'I am learning to call an AI.'
token count : 8
the pieces  : ['I', ' am', ' learning', ' to', ' call', ' an', ' AI', '.']

cat          -> 1 token(s): ['cat']
learning     -> 1 token(s): ['learning']
strawberry   -> 3 token(s): ['st', 'raw', 'berry']

prompt tokens: 9 | reply tokens: 15 | total: 24
rough cost   : $0.00001035

What happened here: The eight-word sentence became eight tokens, one per word plus the full stop, and each got a leading space so the model knows where words begin. The fun part is the second block: “cat” and “learning” are common enough to be a single token each, but “strawberry” splits into st, raw, and berry. Long or rare words break into these subword pieces, which is also why a model sometimes miscounts the letters in a word: it never saw the letters, only the chunks. Finally we counted a real request at 9 plus 15 tokens and priced it at a tiny fraction of a cent, so the cost section below is really just this token count times a price. One honest note: tiktoken is OpenAI’s tokenizer, and Claude or Gemini split text a little differently, but the idea is identical everywhere.

What Does This Actually Cost?

The first question beginners ask is “will this empty my bank account?” The honest answer: a demo like this costs less than a single chocolate. You are billed per token, roughly per chunk of a word, split into tokens going in (your prompt) and tokens coming out (the reply). Let us compute the real number instead of hand-waving.

📄 cost_estimate.py: the price of one small call

# Prices are per 1 million tokens, from the provider's pricing page
# (Claude Opus 4.8 at the time of writing: $5 in, $25 out per 1M tokens).
PRICE_IN_PER_M = 5.00
PRICE_OUT_PER_M = 25.00

# A tiny call: a short question in, a short answer out.
input_tokens = 14        # "In one sentence, what is an API key?"
output_tokens = 60       # a one-sentence reply

cost_in = input_tokens / 1_000_000 * PRICE_IN_PER_M
cost_out = output_tokens / 1_000_000 * PRICE_OUT_PER_M
total = cost_in + cost_out

print(f"Input:  {input_tokens} tokens  ->  ${cost_in:.6f}")
print(f"Output: {output_tokens} tokens  ->  ${cost_out:.6f}")
print(f"Total for this call:        ${total:.6f}")
print(f"Calls you could make for $1: {int(1 / total):,}")

▶ Output

Input:  14 tokens  ->  $0.000070
Output: 60 tokens  ->  $0.001500
Total for this call:        $0.001570
Calls you could make for $1: 636

What happened here: that math is real Python output. One call here costs about $0.0016, so a single dollar buys you more than 600 of them. The prices are from the provider’s public pricing page and change over time, so plug in the current numbers when you check. Two things keep costs tiny for learning: short prompts, and a sensible max_tokens so a runaway reply cannot balloon the bill.

You may not even need to spend anything to start. At the time of writing, common free options include:

  • Free trial credits: most providers hand new accounts a small credit balance, which is plenty for hundreds of practice calls.
  • Free developer tiers: Google’s AI Studio (for Gemini) offers a free tier with daily limits, good for learning without a card.
  • Local models: tools like Ollama let you run smaller open models on your own machine for zero per-call cost, handy for endless experimentation.

The Same Idea on OpenAI and Gemini

Here is the reassuring part. The concept you just learned is not tied to one company. Every provider follows the same shape: make a client, name a model, send your text, read the reply. Only the package name and a few words change. Think of it like buses from different companies: different paint, same doors and seats. Below is the same tiny call on two other popular providers, so you can see how little actually differs.

📄 openai_call.py: the same shape on OpenAI’s Responses API

from openai import OpenAI  # pip install openai

MODEL = "gpt-5.1"  # swap when models change; check their model list

client = OpenAI()  # reads the OPENAI_API_KEY environment variable

response = client.responses.create(
    model=MODEL,
    input="In one sentence, explain what an API key is to a beginner.",
)

print(response.output_text)

📄 gemini_call.py: the same shape on Google Gemini

from google import genai  # pip install google-genai

MODEL = "gemini-2.5-flash"  # swap when models change; check their model list

client = genai.Client()  # reads the GEMINI_API_KEY environment variable

response = client.models.generate_content(
    model=MODEL,
    contents="In one sentence, explain what an API key is to a beginner.",
)

print(response.text)

What happened here: squint and all three are the same program. You import a library, pin a model, create a client that reads a key from the environment, send your text, and print the reply. The method names differ (messages.create on Anthropic, responses.create on OpenAI, generate_content on Gemini) and so do the model names, which is exactly why we pin them in a MODEL constant. Because these method and model names shift over time, always glance at the provider’s current quickstart rather than trusting a snippet from a year ago. Note for OpenAI: use the modern Responses API shown here, not the older Assistants API, which is on its way out.

Common Mistakes

Mistake 1: Pasting your API key into the code

Writing client = anthropic.Anthropic(api_key="sk-...") straight in your script is the classic beginner slip. The moment you push that file to GitHub, bots find the key within minutes and run up a bill on your account. Keep the key in an environment variable and let the library read it, exactly as we did above. Your code should never contain the actual key.

Mistake 2: Forgetting max_tokens, or setting it too low

max_tokens is the ceiling on the reply length. Set it too low and the answer gets chopped off mid-sentence. Leave it huge for a chatty prompt and a runaway reply can cost more than you expected. For small learning scripts, a few hundred is a sensible, safe number.

Mistake 3: Reading the reply the wrong way

The reply is not a plain string, it is an object with a content list inside it. Beginners try print(message) and get a wall of metadata, then panic. The text you want lives at message.content[0].text. Remember that one path and the confusion disappears.

Best Practices

  • DO keep your key in an environment variable, never in the code.
  • DO pin the model in a MODEL constant so upgrades are a one-line edit.
  • DO print your prompt and read it before sending, especially when the reply looks off.
  • DO give the model a clear role and a shape for the answer, not just a bare question.
  • DON’T commit code with a key in it, even for five minutes.
  • DON’T hard-code a model name in ten places; use the one constant.
  • DON’T assume today’s model names and method names are permanent; check the current docs.

Conclusion

You just called a real AI model from Python, twice. You know what an LLM API is (a doorway to a text-predicting model), how to keep your key safe, how to send a prompt and read the reply, and how to pin the model so upgrades stay painless. You built a study helper that explains any Python error, and you saw the same pattern work across three providers, which means this skill is not locked to one company. That is Python AI for beginners done right: a small, real script first, theory later.

This was a taste on purpose. The deeper story, how tokens and context windows shape what you can ask, how to hold a real conversation across turns, how temperature changes the answers, and how to give the model tools to act, all comes later in the series (Part 7 goes properly into how these models work). For now, you have the one thing that matters: a working AI script you wrote yourself. Change the prompt in the study helper tonight and make it do something useful for your own learning.

Keep going: browse the full Python + AI/ML tutorial series home to see where this fits and what comes next.

Frequently Asked Questions

Do I need to know machine learning to call an LLM in Python?

No. Calling a large language model is just sending a text prompt to an API and reading the text reply. Python AI for beginners needs only basic Python (strings, functions, lists): no machine learning, no maths, and no GPU. The provider runs the model on their servers; your code only sends a small request and waits for the answer.

How much does it cost to call an LLM as a beginner?

Very little. You pay per token, split between your prompt (input) and the reply (output). A tiny demo call costs roughly $0.0016 with a current model, so one dollar covers hundreds of practice calls. Most providers also give free trial credits or a free developer tier, so you can start without spending anything.

Where do I put my API key so it stays safe?

Store it in an environment variable such as ANTHROPIC_API_KEY and let the SDK read it automatically. Never paste the key into your .py file, and never commit it to GitHub. Keeping the key in the environment means you can share or push your code without leaking the secret.

What is max_tokens and what value should I use?

max_tokens is the maximum length of the reply, measured in tokens (roughly word chunks). Too low and the answer gets cut off; too high and a long reply can cost more. For small learning scripts, a few hundred is a safe, sensible ceiling.

Can I use the same code with OpenAI or Gemini instead of Claude?

Yes, the pattern is the same across providers: make a client, name a model, send your text, print the reply. Only the package name and method change (messages.create on Anthropic, responses.create on OpenAI, generate_content on Gemini). Pin the model in a constant and check each provider’s current quickstart, since model and method names change over time.

Why is the reply an object instead of a plain string?

The model returns more than text: it also sends usage counts and structure, packed into a response object. The text you want sits in a content list, reached with message.content[0].text. Printing the whole object shows metadata, which confuses beginners, so read the text field directly.

Interview Questions on Calling an LLM

These come from real screens and onsites. Practice answering before you read each answer.

Q: In plain terms, what is the difference between an LLM and an LLM API?

The LLM is the model itself, a program trained on huge amounts of text that predicts what words come next. The API is the doorway that lets your code send a prompt to that model over the internet and receive a reply. You interact with the model only through the API: you never run the model on your own machine in this setup, you just send text and read text back.

Q: Why should an API key live in an environment variable instead of in the source code?

A key in the source code gets committed to version control, and public repositories are scanned by bots that grab exposed keys within minutes and run up charges on your account. An environment variable keeps the secret outside the file, so you can share or push the code safely. The SDK reads the variable automatically, so there is no downside to doing it the safe way.

Q: What does max_tokens control, and what breaks if you set it wrong?

max_tokens caps how long the model’s reply can be. Set it too low and the answer is truncated mid-sentence, which looks like a bug but is just the ceiling being hit. Set it very high on an open-ended prompt and a long reply can cost more than intended, since you pay per output token. For small scripts a few hundred tokens is a safe middle ground.

Q: Why do we pin the model name in a MODEL constant instead of writing it inline?

Model names change as providers release newer versions and retire old ones. If the name is written inline in every call, an upgrade means editing many places and risking a missed one. A single MODEL constant makes an upgrade a one-line change, and it documents at a glance exactly which model the code used.

Q: The provider returns a response object, not a string. How do you get the text, and why is it structured that way?

The text sits inside a content list, reached with message.content[0].text. It is structured because a response carries more than words: token usage for billing, the reason it stopped, and potentially multiple content blocks. Returning a rich object lets you inspect all of that, while the plain answer stays one attribute away.

Q: How would you move this code from Claude to another provider like OpenAI or Gemini?

The structure stays the same: import the provider’s library, pin a model, create a client that reads a key from the environment, send the text, and read the reply. You change the package, the method name (for example responses.create or generate_content), and the model name in the MODEL constant. Because these details shift over time, you confirm them against the provider’s current quickstart rather than assuming.

Want more? the official Python documentation documents everything this post could not fit.

Previous: Python: Debugging & Basic Testing with pdb, breakpoint(), assert

Next: Python: OOP Concepts, Classes, Objects, Why OOP

Series Home: Python + AI/ML Tutorial Series

RahulAuthor posts

Avatar for Rahul

Rahul is a passionate IT professional who loves to sharing his knowledge with others and inspiring them to expand their technical knowledge. Rahul's current objective is to write informative and easy-to-understand articles to help people avoid day-to-day technical issues altogether. Follow Rahul's blog to stay informed on the latest trends in IT and gain insights into how to tackle complex technical issues. Whether you're a beginner or an expert in the field, Rahul's articles are sure to leave you feeling inspired and informed.

No comment

Leave a Reply

Your email address will not be published. Required fields are marked *