Braj Kishore
JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
Say hi

Hiring · Building · Investing

Have a system — or a team —that needs to scale?

info@avyxon.ai

Usually replies within a day · track record here

JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
LinkedInXYouTubeSubstackInstagramThreadsFacebookDiscordGitHubTopmate
© 2026 Braj Kishore · Bengaluru, INThink Big · Start Small · Scale Fast
Agentic engineering
Lesson 04Foundations

The loop, from scratch

Every framework in this space is wrapping about forty lines of code. Write those lines once and no framework is mysterious again. Better still, you stop being surprised by what one of them is doing on your behalf.

An agent is a model that decides which tools to call, in what order, until it decides it is done. That is the whole definition, and it is the one that has held up.

Anthropic’s framing draws the line precisely. A workflow runs models and tools through code paths you wrote in advance. An agent lets the model direct its own process. Everything expensive about agents follows from that single handover: the cost, the latency, the debugging.

The code itself is genuinely small. Thorsten Ball built a working code-editing agent in under four hundred lines, most of it boilerplate, and described the substance as “an LLM, a loop, and enough tokens”. Hugging Face’s smolagents keeps its core agent logic inside about a thousand lines.

So the shape is small on purpose. What is not small is everything you add around it once real users arrive, and that is most of this lesson.

Building Effective AI AgentsAnthropicReAct: Synergizing Reasoning and Acting in Language ModelsarXiv 2210.03629Toolformer: Language Models Can Teach Themselves to Use ToolsarXiv 2302.04761
Interactive · all four guards at once

What separates a demo from a system, priced

Read the cost lane left to right — three of the four are lines of code, and only the fourth is real work. Select a guard for the detail.

The failure it prevents
A bad prompt spending your entire month's API budget overnight
The same tool called again with the same arguments — the most frequently observed failure mode in the published literature
An action that contradicts a rule the model read two turns earlier
A failure at step 18 costing the whole trajectory rather than one step
What it costs you
Three lines
Six lines
A deterministic check on the write paths
Persisting messages[] — a JSON blob keyed by run id is enough
At a four-person seed team
Non-negotiable
Do it
Cheap version
Skip it

Four guards. Three are cheap enough that skipping them is never defensible; the fourth is a genuine waste of a seed team’s only scarce resource.

The five boxes

Before any code, the architecture: five components and a cycle. The second box is the one that surprises people. The agent has no memory at all. The entire state of the run is an array you rebuild and resend on every single iteration.

Sit with that for a moment, because two things later in this lesson fall straight out of it. One is the cost curve. The other is why a chatty tool result is a state problem rather than an untidy one.

Interactive · component diagram

The five boxes every framework is wrapping

Select any box, or any guard, for what it does and why it is placed there.

resendtool_useappend tool_resultend_turnYour applicationowns the loopmessages[]the entire stateModeldecides, never actsstop_reasonthe exit conditionExecute toolyour code, your rulesReturn to callerthe run is over
The four guards
Component
messages[]

An agent has no memory. The complete state of the run is this array, which you rebuild and resend on every single iteration. That is why context is a budget rather than a container — and why a 40,000-token tool result is not a formatting problem, it is a state-management problem that will be paid for on every subsequent turn.

The model decides but never acts. It cannot touch your database. It can only emit a structured request that your code may honour or refuse. Every safety property you will ever want lives in that gap: approval gates, spend caps, audit trails. So the question to ask of any framework is whether it keeps the gap real or quietly closes it.

The loop itself

Here it is, with the guards already in place. A version without them is a version you rewrite in its first week of traffic. Two details carry most of the real bugs, and both are marked in the comments.

agent.py
import json
import anthropic

client = anthropic.Anthropic()
MAX_TURNS = 12


def run(user_message, tools, handlers):
    messages = [{"role": "user", "content": user_message}]
    seen = set()

    for turn in range(MAX_TURNS):          # guard: hard iteration cap
        response = client.messages.create(
            model="claude-opus-5",
            max_tokens=2048,
            tools=tools,
            messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        # Branch on stop_reason, NOT on "is there a tool_use block".
        # A reply truncated at max_tokens has no tool_use block either, and
        # code that tests for absence reads that truncation as a finished
        # answer. This is the single most expensive bug in the pattern.
        if response.stop_reason == "max_tokens":
            raise RuntimeError("truncated: raise max_tokens or shrink context")
        if response.stop_reason != "tool_use":
            return response

        results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            key = (block.name, json.dumps(block.input, sort_keys=True))
            if key in seen:                # guard: repeated identical call
                out = "Already called with these arguments. Use the earlier result."
            else:
                seen.add(key)
                out = execute(block, handlers)
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": out,            # a STRING, never a dict
                "is_error": out.startswith("ERROR"),
            })

        # Results go back on a USER message. This trips up almost everyone.
        messages.append({"role": "user", "content": results})

    raise RuntimeError(f"no answer in {MAX_TURNS} turns")


def execute(block, handlers):
    # Errors are returned to the model, not raised. An agent told that a
    # query failed can correct itself; an agent whose process died cannot.
    try:
        return json.dumps(handlers[block.name](**block.input))
    except Exception as exc:
        return f"ERROR: {type(exc).__name__}: {exc}"
The whole thing. Two of the four guards are already in it — the iteration cap on the for-loop and the repeat detector on the seen set — because the tutorial version without them does not survive its first week of traffic.

That is the entire mechanism. A framework adds retries, tracing, streaming and a graph abstraction on top. All of that is genuinely useful, and none of it changes the shape.

Which is the payoff for writing it yourself. If you cannot draw this on a whiteboard, you cannot debug what a framework is doing at two in the morning.

The other half of the work is the tool definition. It carries more of the quality burden than the prompt does — provided you know which of your constraints are real.

Set strict and the sampler is constrained to the schema. An invalid enum value or an unexpected key stops being unlikely and becomes structurally impossible. Numeric and string-length constraints are a different matter. They are documented as unsupported, so a schema that declares them reads as safer than it is. Anything you need bounded, you bound yourself, in the handler.

tools.py
import re

TOOLS = [{
    "name": "issue_refund",
    "description": (
        "Issue a refund against a delivered order. Amounts above the market's "
        "auto-approval ceiling are held for human approval and return "
        "status=blocked. Call get_refund_policy first to read the ceiling."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "order_id": {"type": "string"},
            "amount_inr": {"type": "integer"},
            "reason": {"type": "string", "enum": [
                "late_delivery_quality", "missing_item", "wrong_order",
            ]},
        },
        "required": ["order_id", "amount_inr", "reason"],
        "additionalProperties": False,
    },
    # Constrains sampling to the schema: the enum, the required keys and
    # additionalProperties are guaranteed. Numeric and length constraints
    # (minimum, maximum, minLength, maxLength) are NOT enforced — the docs
    # list them as unsupported, so anything you need bounded, you bound.
    "strict": True,
}]


def validate(order_id, amount_inr, reason):
    if not re.fullmatch(r"[0-9]{7}", order_id):
        return f"ERROR: order_id must be 7 digits, got {order_id!r}"
    if not 1 <= amount_inr <= 20_000:
        return f"ERROR: amount_inr out of range: {amount_inr}"
    return None
The enum and additionalProperties are enforced by strict mode; the numeric bounds are not, which is exactly why validate() exists. Constraints the sampler enforces make bad calls impossible — constraints it does not enforce are your job, and confusing the two is a common and confident mistake.

Watching one run

Reading a loop is not the same as watching one execute. Below is a real-shaped trajectory — the whole sequence of steps in one run. Ten turns, four tools, a refund on a late food-delivery order in Bengaluru. Watch the counters. They are the part almost nobody works out from the code alone.

Interactive · one real trajectory

A late-delivery refund, turn by turn

Ten turns of a four-tool agent handling a ₹684 refund in Bengaluru. Step through it and watch the right-hand counters — they are the part that surprises people.

1 / 10
usertextCustomer

My order came 50 minutes late and the food was stone cold. Order 8842137.

Context now
1,240
tokens resent on the next call
Model calls
0
each one resends everything
Input billed
0
cumulative, across the run

The 1,240 tokens before a word of conversation are the system prompt and the JSON schemas of four tools. Tool definitions are context, and you pay for them on every turn of the run.

Two things in that run are worth carrying into an interview. The first is the cost shape. Every turn resends the whole array, so a run’s billed input grows with roughly the square of its length. Cut one tool call from a ten-turn agent and you save far more than one turn’s worth.

The second is turn eight. The model proposed an action that contradicted a rule it had read two turns earlier. No prompt would have made that reliable. A comparison against a number did. That is the case for a deterministic check — plain code, no model — made in one turn of one run.

12-Factor Agentshumanlayer

Which of these you should actually build

The four guards are not a checklist to complete. Three are cheap enough that skipping them is never defensible, at any stage. The fourth is a genuine waste of a seed team’s only scarce resource.

Interactive · calibrate to your stage

What to actually do about this, at your size

Nearly all guidance on this topic is written for one company size and then read by everyone. Pick yours — the list re-sorts, and what you should deliberately not build drops to the bottom.

  • Iteration capNon-negotiable

    A hard maximum on loop turns, with the run recorded as capped rather than as a success.

    At this stage · Same three lines, now with an alert when the cap trips more than rarely — a rising cap rate is the earliest signal that a tool has quietly broken.

  • Repeat detectorDo it

    A set of (tool, arguments) pairs; on a repeat, return an error result telling the model it already has this.

    At this stage · Worth logging repeats as a metric now — a climbing repeat rate usually means a tool description has drifted out of date.

  • Result validatorDo it

    A deterministic check between the model's proposed action and the side effect actually firing.

    At this stage · Now on every write path. This is usually the stage where the first expensive incident makes the case for you, and it is better to have it before that.

  • CheckpointingCheap version

    Persist messages[] after each turn so a failure at step 18 costs one step rather than the whole trajectory.

    At this stage · A JSON blob in Postgres keyed by run id is enough. You do not need a durable-execution framework to survive a redeploy mid-run.

Nothing is optional at this stage. That is itself the finding — the cost of the control set is part of the cost of operating here.

Two systems that make the point

Both of these sit outside the usual Silicon Valley case list. Both turn on the same boundary: what the model is allowed to do, versus what it is only allowed to propose.

🇰🇪 Kenya

Jacaranda Health TRIM-AI — the model routes, the human answers

0.774
weighted F1, real-world data
Jun 2022
in the field since
EN + SW
code-mixed SMS

TRIM-AI reads SMS messages sent by pregnant women to the PROMPTS helpdesk and classifies how clinically urgent each one is. The messages are code-mixed: English and Swahili inside the same text. A weighted F1 of 0.774 sounds far too low to ship. Then you notice what the model is actually for. It does not answer the mother. It orders a queue that human helpdesk agents then work through.

That is the “decides but never acts” boundary, drawn around a whole product. A person is the actuator — the thing that finally acts — so a misranking costs a delayed call rather than wrong clinical advice. At that price, 0.774 is a perfectly shippable number. Now move the same model one box to the right and let it reply directly. The identical F1 becomes indefensible. The metric did not change. The position of the human did.

🇨🇦 Canada

Moffatt v. Air Canada — what an ungrounded answer costs

CAD 650.88
damages awarded
2024
BCCRT 149
2
contradictory sources of truth

Air Canada’s website chatbot told a bereaved passenger he could apply for a bereavement fare retroactively. Another page on the same website said the opposite. The airline argued that the chatbot was a separate entity, responsible for its own actions. The tribunal rejected that, found negligent misrepresentation, and awarded CAD 650.88.

The damages are trivial. The engineering lesson is not. This was not a hallucination problem in any interesting sense. It was two sources of truth on one domain, with nothing watching for them to diverge. So the fix is architectural rather than a better prompt. Generate from the same canonical policy document the web page renders from, cite it in the answer, and alarm on drift. And note where the ruling leaves you: “the bot is a separate system” is now a defence that has been tested in front of a tribunal and lost.

What to remember

  1. 1
    An agent is a loop you own

    Whoever owns the for-loop owns retries, budgets, timeouts, logging, and the ability to stop. That is the whole reason to write it once before adopting anything that hides it.

  2. 2
    messages[] is the entire state

    There is no memory. You rebuild and resend everything each turn. That is why cost grows with the square of the trajectory, and why a verbose tool result is a state problem rather than a formatting one.

  3. 3
    Branch on stop_reason

    Not on the absence of a tool call. Truncation and completion look identical to code that tests for absence.

  4. 4
    The model proposes; your code disposes

    Keep the gap between decision and side effect real, and put a deterministic check in it. Every approval gate, spend cap and audit trail you will ever need lives in that gap.

Sources

Every source in this lesson

Primary sources wherever one exists. Where a claim is contested or vendor-reported, the lesson says so at the point it is made.

Paper
  • ReAct: Synergizing Reasoning and Acting in Language ModelsarXiv 2210.03629

    Yao et al., ICLR 2023. Interleaving a reasoning trace with actions — the shape almost every agent loop still has, three years on.

  • Toolformer: Language Models Can Teach Themselves to Use ToolsarXiv 2302.04761

    Schick et al., 2023. The other root of the idea: a model deciding for itself when an external tool beats its own weights.

Read
  • Building Effective AI AgentsAnthropic

    December 2024. The distinction the whole field now uses: workflows orchestrate LLMs through predefined code paths; agents let the model direct its own process and tool use. Also the origin of the five workflow patterns.

  • How to Build an AgentThorsten Ball

    April 2025. A working code-editing agent in under 400 lines, most of it boilerplate — "an LLM, a loop, and enough tokens". The best antidote to framework mystique.

  • TRIM-AI: tele-triaging pregnant women in KenyaJacaranda Health

    TRIage for Mothers using AI. Classifies the emergency level of inbound SMS written in code-mixed English and Swahili, weighted F1 0.774 on real-world data, in the field since June 2022. The model prioritises; the human helpdesk answers.

Code
  • smolagentsHugging Face

    A barebones agent library whose core logic fits in about a thousand lines. Worth reading precisely because there is so little of it to read.

  • 12-Factor Agentshumanlayer

    Factor 8, own your control flow, and Factor 3, own your context window, are the two that decide whether you can debug the thing at 2am.

Docs
  • Tool use with ClaudeAnthropic docs

    The round trip in full: stop_reason "tool_use", a tool_use block, your execution, a tool_result block sent back on a user-role message. Also strict:true for schema conformance and disable_parallel_tool_use.

  • Moffatt v. Air Canada, 2024 BCCRT 149CanLII

    British Columbia Civil Resolution Tribunal. The airline argued its chatbot was a separate entity responsible for its own actions; the tribunal rejected that, found negligent misrepresentation, and awarded CAD 650.88.

Lesson 03
What an agent actually is
Lesson 05
Design patterns