← Build an AI Agent Lesson 5 of 8

Planning

Make a plan first

A cake and snacks for 10 people, under ₹5,000. I'll just start… or should I?

Same goal, two ways. Switch between them.

With a big goal, it's easy to stop after the first thing works. So the LLM first writes a plan: every step, before it acts.
plan = the steps, written down first
Cake, snacks, add up: nothing gets forgotten.

A plan is written. How does the agent follow it?

Tick off the steps

Step through. Watch the plan get ticked off.

    The plan stays in the text, so every round the LLM sees what's done and what's next. Writing the plan is one more write:
    times the LLM writes = plans + rounds + 1
    1 plan + 3 rounds + 1 answer = 5 writes.

    Try it on new numbers.

    ✏️ Practice 5.1

    New numbers, same ideas.
    Remember: one round = think, act, look. Each round uses one tool.
    times the LLM writes = plans + rounds + 1

    Work each one out. Type the answer, press Check.
    A plan has 4 steps, each needing one tool. Nothing fails. How many rounds?
    Same task. How many times does the LLM write?
    A 3-step plan, one tool per step, nothing fails. Each write takes 2 s, each tool 1 s. How many seconds in total?

    Plans assume every step works. What if one doesn't?

    When a step fails, plan again

    Step through. Step 1 is going to fail.

      The shop is closed, so the old plan can't work. The LLM reads the error and writes a new PLAN:. The program starts counting from step 1 again.
      a failed step → a new plan
      2 plans + 4 rounds + 1 = 7 writes.

      Some plans fail because a step was too big. What size is right?

      Steps the right size

      Sort each step. Then press Check.

      A good step needs about one tool use. “Sort out the food” is too big: split it into “find a cake”, “find snacks”, and so on.
      one step ≈ one tool use

      Try it on new numbers.

      ✏️ Practice 5.2

      New numbers, same ideas.
      Remember: times the LLM writes = plans + rounds + 1
      A failed tool use still takes a round, and leads to a new plan.
      one step ≈ one tool use

      Work each one out. Type the answer, press Check.
      A 3-step plan. Step 2 fails once, a new plan fixes it, then everything works. How many rounds?
      Same task. How many times does the LLM write?
      A step says “Book the hall, order the food and book the music.” Each booking or order is one tool use. Split it the right size: how many steps?

      Here's planning in Python.

      The code

      The program reads the plan's numbered lines and counts the steps done. Guess what each print shows. Then press ▶ Run.

      import re
      
      # Tools: a pretend shop, and the calculator
      def shop(item):
          prices = {"cake for 10 at cake house": "₹1800", "snacks for 10": "₹1500"}
          if "sweet spot" in item.lower():
              return "Error: Sweet Spot is closed today"
          return prices.get(item.lower(), f"Error: no price found for {item}")
      
      def calculator(math):
          for ch in math:
              if ch not in "0123456789+-*/(). ":
                  return "Error: the calculator only takes numbers and + - * / ( )"
          if "**" in math:   # ** is power: 9 ** 999999 would never finish
              return "Error: the calculator only takes numbers and + - * / ( )"
          try:
              return str(eval(math))
          except Exception:
              return "Error: that math doesn't work out"
      
      TOOLS = {"shop": shop, "calculator": calculator}
      
      INSTRUCTIONS = """You are an agent. TOOLS you can use:
      shop(item) - the price of an item at a shop. Give it the item and the shop.
      calculator(math) - works out math exactly.
      First write PLAN: and your steps, one per line, numbered.
      Then do one step at a time: ACT: tool(input)
      If a step fails, write a new PLAN:.
      When you're done, write: ANSWER: your answer"""
      
      # Read the numbered steps out of a plan
      def read_plan(reply):
          steps = []
          for line in reply.split("\n"):
              if line != "" and line[0] in "0123456789":   # not empty, starts with a number
                  steps.append(line)
          return steps
      
      # A fake LLM with a plan, a failed step and a new plan
      fake_replies = [
          "PLAN:\n1. Find a cake for 10 at Sweet Spot\n2. Find snacks for 10\n3. Add up the cost",
          "ACT: shop(cake for 10 at Sweet Spot)",
          "THINK: Step 1 failed. A new plan.\nPLAN:\n1. Find a cake for 10 at Cake House\n2. Find snacks for 10\n3. Add up the cost",
          "ACT: shop(cake for 10 at Cake House)",
          "ACT: shop(snacks for 10)",
          "ACT: calculator(1800 + 1500)",
          "ANSWER: A Cake House cake and snacks: ₹3300 in all, under ₹5000.",
      ]
      def fake_llm(text):
          return fake_replies.pop(0)
      
      # The loop, now keeping track of the plan
      def run_agent(question, llm, step_limit=8):
          text = INSTRUCTIONS + "\n\nQuestion: " + question + "\n"
          plan = []
          done = 0
          for step in range(step_limit):
              reply = llm(text)
              print(reply)
              text += reply + "\n"
              if "PLAN:" in reply:
                  plan = read_plan(reply)
                  done = 0
                  print(f"(a plan with {len(plan)} steps)")
              if "ANSWER:" in reply:
                  return reply.split("ANSWER:")[1].strip()
              act = re.search(r"ACT: (\w+)\((.*)\)", reply)
              if act is None:
                  continue
              elif act.group(1) not in TOOLS:
                  look = f"Error: no tool called {act.group(1)}"
              else:
                  look = TOOLS[act.group(1)](act.group(2).strip('"'))
              if not look.startswith("Error"):
                  done += 1
              print("LOOK:", look, f"(done {done} of {len(plan)})")
              text += "LOOK: " + look + "\n"
          return "Stopped: the step limit was reached."
      
      print(run_agent("Order a cake and snacks for 10 people, under ₹5000.", fake_llm))

      The notebook has all of this, then the same with the real LLM from Lesson 3. Its first run downloads the model (about 3 GB).

      Quick check: did it all make sense?

      Lesson 5 test

      5 questions, one for each idea in this lesson. Answer them all right to pass. A wrong answer tells you why, and which page to look at again.

      1. WhyWhy does the LLM write a plan before acting on a big goal?
      2. CountA 2-step plan, one tool per step, nothing fails. How many times does the LLM write?
      3. PredictStep 1 says “buy a cake at Sweet Spot”. The LOOK: line says the shop is closed. What does the LLM write next?
      4. ApplyWhich step is the right size?
      5. CodeWhat does read_plan find in the LLM's reply?

      What your agent still does all alone.

      All by itself

      Your agent plans, acts, remembers. But it does every job itself: finding facts, writing, checking its own work.

      I'm doing everything. Could I get some help?

      This leaves a question
      One agent does everything. Could a team do better?
      Lesson 6 answers it.