ProjekinAja. Agentic AI Stage 4 · Building Agents Lesson 4.4
● Stage 4 · Lesson 4.4

Crossing to Code — The Simplest Agent Loop

No-code shows you what; code shows you how — and gives you total control. Here's the smallest possible agent loop in real Python, explained line by line.

⏱ ~15 min read 🐍 First real code 🔁 The loop, for real

🎯 By the end you'll understand

Why writing the loop yourself in code unlocks total control, what the three pieces of setup are (a key, the SDK, a model call), and how to build the simplest working chat loop in Python — a messages list, a while loop, and one model call — then exactly how that skeleton becomes a real agent once you add tools.

KEY INSIGHTThe one idea to take away

An agent isn't a magic library. It's a list, a loop, and one function call — and you can write all three yourself in about fifteen lines of Python.

In Lesson 4.3 you wired tools together with no code. That showed you the shape of an agent. Now we drop one level down and build the engine ourselves — and it turns out to be smaller and less mysterious than the no-code canvas made it look.

We'll start with the very smallest version: a chat loop. It can't act yet — it only talks. But it's the exact skeleton the agent loop (2.1) hangs on. Next lesson we give it tools and it grows into a true agent. Build the bones first; add the muscles after.

🔑 Hold onto this

The whole agent loop is just three things you already met in Stage 2: a messages list (the conversation history — the context, 2.3), a model call (the brain, 1.3), and a loop (the heartbeat, 2.1). Code just makes those three explicit.

CORE CONCEPTWhy cross to code at all

No-code platforms (4.1) are wonderful for getting something running in an afternoon. But the moment you want something they didn't anticipate, you hit a wall. Code has no wall. Here's what you actually gain by writing the loop yourself:

No-code 🧩Code 🐍
Controlwhatever the platform exposestotal — every line is yours to change
Limitsthe vendor's feature set & pricingnone beyond the API itself
Understandingthe loop is hidden inside the toolyou see and own the loop (2.1)
Where it runstheir serversanywhere — your laptop, your server
Cost to startlow — drag and dropa little setup & reading

The honest trade: you pay a small upfront tax in setup and patience, and in return you get a system with no ceiling. For anything you intend to grow, that's the right bargain. And critically — once you've written the loop once, the mystery is gone forever. You'll look at every agent product differently.

💡 You don't have to abandon no-code

This isn't "code is better." It's "code is uncapped." Many great builders prototype in no-code, then rewrite the parts that matter in code once they know exactly what they need. Use whichever fits the job.

PRACTICALThe minimal setup — three pieces

Before any code runs, you need exactly three things. Conceptually they're tiny:

🔑

An API key

A secret password that tells the model provider "this request is from me, bill my account." You get it once from the provider's dashboard. We'll keep it in an environment variable, never in the code itself (more on why below).

📦

The SDK

A small library that wraps the model's web API so you call a Python function instead of hand-building HTTP requests. For Anthropic's models it's the anthropic package: pip install anthropic.

🧠

A model call

One function — client.messages.create(...) — that sends your conversation to the model and gets back its reply. That single call is the brain (1.3). Everything else is plumbing around it.

📖 SDK (Software Development Kit)

A ready-made library that turns a messy remote API into clean function calls in your language. Instead of constructing a web request by hand, you write client.messages.create(...) and the SDK handles the rest. Different providers ship different SDKs; the pattern below is the same everywhere.

⚠️ Model names and SDK syntax change over time

The exact model id (here claude-sonnet-5) and the precise function names get updated as providers ship new versions. Don't memorize the strings — learn the pattern: build a messages list, call the model, read the reply, append it, repeat. That shape has stayed stable across every version and every provider.

CORE CONCEPTBuild the loop, line by line

Let's grow it in three steps. Read each block as English first, then look at the code — they say the same thing.

Step 1 — One single message. Forget the loop for a second. The most basic thing you can do is send one message and print the reply. This is a chatbot with a memory of exactly nothing:

hello.pypython
import anthropic                          # the SDK we installed

client = anthropic.Anthropic()           # reads your API key from the environment

response = client.messages.create(
    model="claude-sonnet-5",           # which brain to use (id may change)
    max_tokens=1024,                     # a cap on how long the reply can be
    messages=[
        {"role": "user", "content": "Say hello in one sentence."},
    ],
)

print(response.content[0].text)            # the model's reply text

Three things to notice. anthropic.Anthropic() creates a client — it quietly grabs your key from the environment, so the key never appears in the file. messages is a list of turns, each a dict with a role ("user" or "assistant") and content. And the reply comes back inside response.content, a list of blocks — the text is in the first block.

Step 2 — Keep the history. A real conversation remembers what was said. The trick is dead simple: keep one growing list and append every turn to it — yours and the model's. That list is the context (2.3):

remember.pypython
messages = []                                  # the conversation history — starts empty

messages.append({"role": "user", "content": "My name is Ada."})

response = client.messages.create(
    model="claude-sonnet-5", max_tokens=1024, messages=messages,
)
reply = response.content[0].text

messages.append({"role": "assistant", "content": reply})   # save the model's turn too

Because we appended the model's reply back into messages, the next time we call the model the whole history goes along for the ride. Ask "what's my name?" after this and it answers "Ada" — not because it has a database, but because the answer is sitting right there in the list we keep re-sending. The model is stateless; the list is the memory.

Step 3 — Wrap it in a loop. Now the heartbeat (2.1). Put Step 2 inside a while loop that keeps asking the user for input. That's the complete chat loop:

chat.pypython
import anthropic

client = anthropic.Anthropic()
messages = []                                  # history lives outside the loop

while True:                                  # the loop = the heartbeat
    user = input("You: ")                     # 1. get the human's message
    if user.lower() in ("quit", "exit"):     # a STOP condition — vital!
        break

    messages.append({"role": "user", "content": user})

    response = client.messages.create(    # 2. call the model (the brain)
        model="claude-sonnet-5", max_tokens=1024, messages=messages,
    )
    reply = response.content[0].text

    print("Bot:", reply)                       # 3. show the reply
    messages.append({"role": "assistant", "content": reply})  # 4. remember it
    # 5. loop back to the top

That's it. A complete, working, multi-turn chat program in about fifteen lines. Read the five numbered steps in the loop: get input → call the model → print → remember → repeat. Hold that rhythm in your head — it's the spine of everything that follows.

▸ The shape to memorize

list + loop + one model call. Initialize a messages list. Loop: read input, append it, call the model, print and append the reply, go again — until a stop condition fires. Every chat program and every agent is a variation on these lines.

SEE ITTrace the loop

Here's the chat loop again. Press ▶ Step to walk through one real exchange — the user says "My name is Ada," then "What's my name?" Watch the highlighted line on the left and the messages list growing on the right. This is exactly what happens, beat by beat, when the program runs.

🔁 Interactive · Execute the chat loop one beat at a time

Each step highlights the line that runs and shows the resulting state.

chat.pyrunning…
messages = []while True:    user = input("You: ")    messages.append(user_turn)    response = client.messages.create(...)    reply = response.content[0].text    print("Bot:", reply)    messages.append(assistant_turn)
Step 0 · Ready

Press ▶ Step to begin. We'll trace two user turns.

messages list
(empty)
Beat 0 of 8

Notice what the highlight reveals: line 4 — the model call — runs once per turn, and the messages list only ever grows. Re-sending that whole list each time is how a stateless model "remembers." There's no hidden state. What you see is what runs.

FRAMEWORKFrom chat loop to real agent

The program above can talk, but it can't do anything. Ask it to check your calendar and it'll cheerfully say "I don't have access to your calendar." That's the gap between a chatbot and an agent (1.1) — and it's smaller than it looks.

To cross it, you add one capability: tools. You tell the model "here are some functions you can call," and now when it needs to act, instead of replying with text it replies with a request to run a tool. Your loop notices that request, runs the function, feeds the result back into the messages list, and calls the model again. The loop keeps spinning — act → observe → decide — until the goal is met. That's the agent loop (2.1) in full.

Chat loop (this lesson) input → model → reply it talks + tools → next lesson (4.5) Agent loop model → act → observe → decide → repeat it acts

So the chat loop you just built isn't a detour — it's the foundation. Lesson 4.5 takes this exact code and adds tools, and you'll watch it turn into something that genuinely gets work done. You already wrote the hard part.

💡 The mental upgrade

Chat loop: the model's reply is always text. Agent loop: the model's reply can also be "please run this tool" — and your loop handles that, then asks again. One new branch in the same loop. That's the whole leap.

KEY INSIGHTBrain, context, heartbeat — in plain code

Everything abstract from Stage 2 now has a concrete line of Python attached to it. This is the payoff of "show both": the concept and the code, side by side.

ConceptIn the codeWhat it does
The brain (1.3)client.messages.create(...)the one call that reasons and decides
The context (2.3)messages listthe history we re-send every turn — the model's only memory
The heartbeat (2.1)while True:keeps the cycle going turn after turn
Tools / hands (4.5)(added next lesson)turns "talk" into "act"

When you read someone else's 2,000-line agent framework later, find these four things and you'll understand its core in minutes. Everything else is convenience, safety rails, and polish wrapped around this same skeleton.

PRACTICALKeep your keys secret

One habit matters more than any line of agent logic: never put your API key in your code. A key is a billable password. If it's hardcoded and you push that file to GitHub, or share it, or paste it in a screenshot — someone can run up your bill or worse.

Instead, store it in an environment variable — a value that lives in your operating system's environment, outside any file you commit. The SDK reads it automatically:

terminalshell
# set it once in your terminal (it stays out of your code)
export ANTHROPIC_API_KEY="sk-...your-key..."

# now anthropic.Anthropic() finds it automatically — nothing in the .py file
python chat.py

Notice that in every code block above, anthropic.Anthropic() took no key argument. That's deliberate: the key flows in from the environment, never from the source. We go deeper on secrets, .env files, and safe deployment in Lesson 4.10.

⚠️ The one-line rule

If you ever find yourself typing api_key="sk-..." directly into a .py file — stop. Move it to an environment variable. This single habit prevents the most common and most expensive beginner mistake.

WEAKNESSCommon mistakes to avoid

✗ Hardcoding your API key

Pasting api_key="sk-..." into the source is the classic disaster. Keys leak through commits, screenshots, and shared files, and a leaked key spends real money. Always use an environment variable (Lesson 4.10).

✗ A loop with no stop condition

while True: with no break and no exit check runs forever — and in an agent loop, "forever" means burning tokens and money on every spin. Always give the loop a way out: a quit command, a max number of turns, or a goal-reached check.

✗ Copying code without understanding the loop

You can paste this script and it'll run — but if you don't grasp why the messages list grows and why the model call sits inside the loop, the first thing that breaks will stop you cold. Trace it (use the widget above) until the rhythm is obvious. Understanding the loop is the actual skill; the syntax is just notation.

KEY INSIGHTWhere this connects in your course

  • The loop (2.1) — the abstract "act → observe → repeat" heartbeat is now a literal while loop you can read.
  • Context & memory (2.3) — the messages list is the context window, in your hands.
  • The LLM brain (1.3) — client.messages.create(...) is the brain, called explicitly.
  • No-code building (4.1) — you saw the shape there; here you own the engine.
  • Giving your agent tools (4.5) — next: add tools so this loop can act, not just talk.
  • Keys & deployment (4.10) — the full story on secrets, .env files, and running safely.

You've crossed the line from using agents to building them in real code. Everything from here is adding capability to a loop you now genuinely understand.

GLOSSARYKey terms introduced

API
Application Programming Interface — the web service you send a request to (your conversation) and get a response from (the model's reply).
SDK
Software Development Kit — a library that wraps an API in clean function calls so you don't hand-build web requests (here, the anthropic package).
Messages list
The growing list of conversation turns (each with a role and content) that you re-send every turn — the model's only memory (the context, 2.3).
Model call
The single function (client.messages.create(...)) that sends the messages to the model and returns its reply — the brain (1.3).
Loop
The while cycle that repeats input → model → reply → remember, turn after turn — the heartbeat (2.1).
Environment variable
A value stored in the operating system's environment, outside your code, used to keep secrets like API keys out of source files.
API key
A secret password that authenticates your requests to a model provider and bills your account — keep it secret, never hardcode it (4.10).

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1What are the three pieces the simplest chat loop is built from?›

A messages list (the conversation history / context), a loop (the while that repeats), and one model call (client.messages.create(...), the brain). List + loop + one call.

2The model is stateless, so how does the chat program "remember" earlier turns?›

It keeps one growing messages list and appends every turn — both the user's and the model's reply — then re-sends the whole list on each call. The memory lives in the list we re-send, not inside the model.

3What single addition turns this chat loop into a real agent?›

Tools. Once the model can reply with "run this function" instead of only text, the loop can run that function, feed the result back into the messages list, and call again — act → observe → decide → repeat. That's the agent loop (covered in 4.5).

4Why should you never write api_key="sk-..." in your code?›

An API key is a billable secret. Hardcoding it means it can leak through commits, screenshots, or shared files — letting someone spend your money. Store it in an environment variable so the SDK reads it without it ever appearing in the source (more in 4.10).

You wrote the loop. Next: give it hands →