Skip to content

Lesson 3 of 6

Create Your First Claude-Powered Assistant

30 minUpdated 13 Nov 2026Part of Build Your First Claude AI Agent
On this page
  1. What you will learn
  2. What the SDK does for you
  3. Check what is installed
  4. Write the first version of agent.py
  5. Run it and read the result
  6. What each request costs you
  7. Expected output
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. References

In this lesson your project starts to talk. You will write a short Python program that sends one question to Claude and prints the answer. It is not an agent yet, because it has no tool and no job, but every later lesson builds on exactly this skeleton, so it is worth understanding each line.

The program does four things: it loads your key from .env, creates a client object, sends a request containing a model ID and a message, and reads the text out of the reply. You will also learn two details that surprise beginners: a reply is a list of blocks rather than a single string, and the model ID is a value that changes over time and so deserves a single, clearly labelled place in your code.

What you will learn

  • Install and check the official Anthropic Python SDK.
  • Make a first request and display Claude's response.
  • Explain each section of the starter program in plain language.
  • Recognise and fix the most common first-request errors.

Before you start

  • Completed Get Ready: Accounts, API Access and Safety: the claude-order-helper folder, an active virtual environment and a working .env file.
  • Your account must be able to make API requests, which may require billing to be set up.
  • Python 3.10 or later.

What the SDK does for you

Claude is reached over the internet. Your program sends a request describing what you want, and the service sends back a reply. You could write that network code yourself, but Anthropic publishes an official SDK (software development kit) for Python: a package that handles the networking, the authentication header and the format of requests and replies. Using the official SDK means fewer mistakes and code that matches the documentation.

The SDK reads your key from the ANTHROPIC_API_KEY environment variable, which is why lesson 2 used exactly that name. Your program never has to mention the key.

Check what is installed

Lesson 2 installed the SDK. SDK versions change, so record the version you have in case you need to ask for help or reproduce your set-up later. Run these with your virtual environment active.

  1. Step 1: Show the installed SDK version

    Bash
    pip show anthropic

    What you should see: A block of text including 'Name: anthropic' and a 'Version:' line.

  2. Step 2: Save the versions of everything you installed

    A requirements.txt file lists the exact packages so anyone can recreate your environment. It contains no secrets.

    Bash
    pip freeze > requirements.txt

    What you should see: A requirements.txt file appears that lists anthropic, python-dotenv and their dependencies.

Write the first version of agent.py

Create a file called agent.py in claude-order-helper and paste in the code below. The comments explain intent. Read them before you run it.

Pythonagent.py
import os
import sys

import anthropic
from dotenv import load_dotenv

# The model ID is the name of the Claude model to use. Model names change as
# new models are released and old ones are retired. Check Anthropic's models
# page (reachable from the documentation home linked in this lesson's
# references) and change this one constant if you need to. Everything else in the program reads it from here.
MODEL = "claude-opus-5-5"

# Upper limit on how long Claude's reply may be, measured in tokens (small
# pieces of text). Too low and a reply is cut off; too high wastes nothing
# unless the model actually uses it, but it is still a limit you control.
MAX_TOKENS = 2000


def text_of(response):
    # A reply is a list of content blocks. Most blocks are text, but a reply
    # can also contain other kinds, so we collect only the text ones.
    parts = []
    for block in response.content:
        if block.type == "text":
            parts.append(block.text)
    return "".join(parts)


def main():
    # Load ANTHROPIC_API_KEY from the .env file into the environment.
    load_dotenv()
    if not os.environ.get("ANTHROPIC_API_KEY"):
        sys.exit("ANTHROPIC_API_KEY is not set. Check your .env file.")

    # The client sends requests for us and finds the key on its own.
    client = anthropic.Anthropic()

    # The conversation is a list of messages. Each has a role and some text.
    messages = [
        {"role": "user", "content": "In two sentences, what does a shop's order-status page do?"}
    ]

    response = client.messages.create(
        model=MODEL,
        max_tokens=MAX_TOKENS,
        messages=messages,
    )

    print(text_of(response))
    # stop_reason tells us why Claude stopped: "end_turn" means it finished.
    print("Stopped because:", response.stop_reason)


if __name__ == "__main__":
    main()

Version 1: a single question and a single answer.

The code in plain language

import lines
Bring in tools from other packages. os and sys are part of Python. anthropic is the SDK and dotenv reads your .env file.
MODEL and MAX_TOKENS
Named settings at the top of the file. Putting them here means you change them in one place, not hunt through the code.
text_of
A small helper that pulls the written text out of a reply. It exists because a reply is a list of blocks, not one string.
load_dotenv and the check
Reads .env, then stops the program with a clear message if the key is missing, rather than failing later with a confusing error.
anthropic.Anthropic()
Creates the client, the object that sends requests. It picks up the key from the environment.
messages
The conversation so far. For now it holds one user message. In later lessons you will add replies and tool results to this list.
client.messages.create
Sends the request. You must give it a model, a maximum length and the messages. It returns once Claude has finished replying.

Run it and read the result

  1. Step 1: Check the virtual environment is active

    Your terminal prompt should begin with (.venv). If it does not, activate it again using the command from lesson 2.

    What you should see: The (.venv) prefix is visible.

  2. Step 2: Run the program

    Bash
    python agent.py

    What you should see: After a short pause you see a two-sentence answer and a line beginning 'Stopped because:'.

  3. Step 3: Change the question and run it again

    Edit the text inside the user message. Try asking for a list of three things a customer might ask about an order. Run again.

    What you should see: The reply changes. The structure of the program does not.

Illustrative outputIllustrative — your output will differ
An order-status page lets a customer see where their order is, such as whether it has been packed, shipped or delivered. It saves them contacting the shop and gives them an up-to-date answer at any time.
Stopped because: end_turn

Your own wording will differ. The model is not guaranteed to produce identical text each time. What should match is the shape: some text, then 'Stopped because: end_turn'.

What each request costs you

Each request uses tokens: small pieces of text counted on the way in (your messages) and on the way out (Claude's reply). Your usage is measured in tokens and billed according to the pricing on Anthropic's pages, which can change, so this course quotes no prices. The reply object includes a usage record, and lesson 6 shows you how to print it. For now, remember that short questions and short replies use few tokens.

If the first request fails, do not retry in a tight loop. Read the error message first. The table in the next section covers the usual causes, and the LLM API errors troubleshooting guide goes further.

Expected output and limitations

A short piece of text answering the question, followed by a line showing why generation stopped. The text varies from run to run.

Sample responseIllustrative — your output will differ
A shop's order-status page shows customers how far along their order is. It reduces enquiries by answering 'where is my parcel?' directly.
Stopped because: end_turn

Limitations to keep in mind

  • The sample is illustrative. The wording you receive will be different.
  • If the stop reason is max_tokens, the reply was cut off by your limit: raise MAX_TOKENS and run again.

Common errors and how to fix them

AuthenticationError, or an error mentioning an invalid API key.

Why it happens: The key in .env is wrong, has extra characters or spaces, or was revoked.

Fix: Check .env contains one line, ANTHROPIC_API_KEY=your-key, with no quotes or trailing space. If in doubt, create a new key in the developer platform and replace it.

NotFoundError mentioning the model.

Why it happens: The model ID in MODEL is misspelt or is no longer available to your account.

Fix: Open Anthropic's models page, copy a current model ID exactly, and update the MODEL constant.

An error about billing, credits or a permission problem.

Why it happens: Your developer account may need billing set up before API requests are allowed.

Fix: Check the billing section of the developer platform. A chat subscription does not cover API use.

ModuleNotFoundError: No module named 'anthropic'.

Why it happens: The virtual environment is not active, or the SDK was installed elsewhere.

Fix: Activate .venv, then run pip install anthropic again.

The reply is empty or cut off mid-sentence.

Why it happens: The token limit was reached before the reply finished.

Fix: Raise MAX_TOKENS and check that the stop reason line reads end_turn.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Make the question a command-line argument

Change agent.py so the question comes from the terminal, for example python agent.py "What is a tracking number?", instead of being fixed in the code. If no argument is given, use the original question as a default.

You will need

  • Your working agent.py from this lesson.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • sys.argv is a list of the words typed after python. The first item is the script name.
  • ' '.join(sys.argv[1:]) joins everything after the script name into one string.
Show a model answer

Inside main(), build the question with something like question = ' '.join(sys.argv[1:]) or 'In two sentences, what does a shop's order-status page do?', then use it as the content of the user message. The 'or' expression picks the default when the argument list is empty. Nothing else changes, which shows how small the surface of a first request really is.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why does agent.py collect text blocks instead of reading response.content[0].text?
    Show the answer and explanation

    Answer: B. A reply holds a list of blocks, and some replies start with a block that is not text. Looping and taking text blocks works in every case. The first option is wrong because content[0] is often text, which is exactly why the shortcut seems fine until it breaks.

  2. 2.Where should the model ID live in your code?
    Show the answer and explanation

    Answer: C. Model names change, so a single labelled constant means one edit when they do. The .env file is tempting because it is configuration, but it is for secrets and per-machine settings, and a model ID is neither.

  3. 3.What does a stop reason of end_turn tell you?
    Show the answer and explanation

    Answer: A. end_turn means the model completed its answer. Hitting your length limit gives a different reason, max_tokens, which is the one to look out for when replies seem cut off.

Written by
PromptFable Editorial
Last updated 13 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.