Roadmaps / AI Engineering / Lab 2

Lab 2 of 8 · Your first call to a model

Ask Claude questions from Python

Get an API key, call Claude from a script, read the token usage, and hold a short conversation.

Time
45 minutes
Cost
Anthropic asks you to buy a small amount of credit before the API works. With the Haiku model used here, this whole roadmap costs well under $1 of it. Set a monthly spend limit in the console.

What you learn

A model API takes messages and returns text. Understanding system prompts, tokens and cost is the base of every AI feature you will build.

  • Messages, roles and the system prompt
  • Tokens: what you pay for, in and out
  • Choosing a model: quality, speed and price
  • Sending conversation history

In the AI era: Models change every few months. Keeping the model name in one setting, as this lab does, lets you upgrade without rewriting your app.

Before you start

  • Finish lab 1.

Step by step

  1. 1 Create an API key

    Sign in at console.anthropic.com, add credit under Billing, set a low monthly limit under Limits, then create a key under API Keys. Copy it once: you cannot see it again.

  2. 2 Put the key in .env

    Open .env and add this line with your real key. Never paste the key into code, chat messages or screenshots.

    File: .env (add a line)
    ANTHROPIC_API_KEY=paste-your-key-here
  3. 3 Create the shared Claude helper

    Every later lab imports from this file, so the model name is set in one place. Haiku is fast and cheap; change MODEL in .env to try others.

    File: llm.py
    """One place for the Claude client, so every script uses the same model and key."""
    import os
    from functools import lru_cache
    
    import anthropic
    from dotenv import load_dotenv
    
    load_dotenv()
    MODEL = os.getenv("MODEL", "claude-haiku-5-5")
    
    
    @lru_cache
    def client() -> anthropic.Anthropic:
        # Reads ANTHROPIC_API_KEY from the environment (your .env file).
        return anthropic.Anthropic()
    
    
    def text_of(message) -> str:
        """The text parts of a Claude reply, joined together."""
        return "".join(block.text for block in message.content if block.type == "text")
    
  4. 4 Ask a question

    The system prompt sets the assistant's role; the message is the question. Run python ask.py "What is an API?".

    File: ask.py
    import sys
    
    from llm import MODEL, client, text_of
    
    question = " ".join(sys.argv[1:]) or "Explain what an API is in two sentences."
    message = client().messages.create(
        model=MODEL,
        max_tokens=300,
        system="You are a patient teacher. Answer in plain English for a beginner.",
        messages=[{"role": "user", "content": question}],
    )
    print(text_of(message))
    print(f"\n(tokens in: {message.usage.input_tokens}, out: {message.usage.output_tokens})")
    
    You should see:

    A short answer, then a line with the token counts.

  5. 5 Hold a conversation

    Models remember nothing between calls. To continue a conversation you send the history every time, which is why long chats cost more. Type quit to stop.

    File: chat.py
    from llm import MODEL, client, text_of
    
    history = []
    while True:
        question = input("You: ").strip()
        if question.lower() in {"quit", "exit"}:
            break
        history.append({"role": "user", "content": question})
        message = client().messages.create(model=MODEL, max_tokens=300, messages=history)
        reply = text_of(message)
        history.append({"role": "assistant", "content": reply})
        print(f"Claude: {reply}\n")
    
    You should see:

    Ask "My name is Sam", then "What is my name?": it answers Sam, because you sent the history.

  6. 6 Commit and push

    Check once more that .env is not listed.

    Run this
    git status --short
    git add llm.py ask.py chat.py
    git commit -m "Call Claude from Python"
    git push

You are done when

  • python ask.py prints an answer and token counts.

  • The chat remembers your name within one session.

  • Your key is only in .env, which is not on GitHub.

Finished? Get your proof page

We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.