Start learning free

LESSON 85 OF 129 · AI ENGINEERING: AGENTS

Plan the Steps in Python

Practice

Your agent decides one step at a time, so you only find out what it is up to while it is already doing it. A plan fixes that: before the loop, one extra call asks the model to write down the steps it means to take, without using a tool yet.

The plan is JSON text. The model replies with a string that holds a list. json.loads turns that text into a Python list your code can work with, and json.dumps turns a list back into text:

text = '["Find the product", "Check its stock"]'
steps = json.loads(text)      # a list of 2 strings
print(steps[1])               # Check its stock
back = json.dumps(steps)      # text again

Printing the plan before anything runs gives a person, or your code, a moment to read what the agent is about to do. But the plan call and the loop are separate conversations: the model in the loop only follows the plan if you send it along with the goal.

Your program must print the plan, then the trace, where every thought names its plan step:

Plan:
  1. Look up order 6
  2. List the products in the order
  3. Check the stock of each product
  4. Tell the customer why the order is late
Step 1
  Thought: Plan step 1: I look up order 6.
  Tool: lookup_order {'order_id': 6} -> {'id': 6, 'customer': 'Ben Ortiz', 'ordered': '2026-05-21', 'status': 'cancelled'}
Step 2
  Thought: Plan step 2. The order was cancelled, so it isn't late. I'll still see what was in it.
  Tool: order_items {'order_id': 6} -> {'items': [{'product_id': 7, 'name': 'Stapler', 'quantity': 1}]}
Step 3
  Thought: Plan step 3: one stapler in the order. I check its stock.
  Tool: check_stock {'product_id': 7} -> {'name': 'Stapler', 'stock': 15}
Step 4
  Answer: Hi Ben, your order 6 isn't late: it was cancelled, so nothing was sent. The stapler you wanted is in stock (15 left), so you can order it again whenever you like.

Your task: the text PLAN_PROMPT is ready. At the top of run_agent, ask the model for a plan, turn the reply into a Python list, print it with numbers, then add the plan to the goal so the model in the loop follows it.


Assignment
Follow the Coding Tutorial to ask for a plan, print it, and send it to the loop along with the goal.


Hint
The plan call is one call to ask_model before the loop, with a list of one user message. The text you add to the goal starts with a space, so it doesn't stick to the goal's last word.


STEP 1 OF 6
    Ctrl + Enter to check

    Ai Plan Steps in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free