Planning: Breaking a Goal into Steps

Ask for a plan first, then run each step and record its result and status, like a to-do list the agent works through.

AI · intermediate · 6 min · 24 steps · free

What you'll learn

planning.py

RESULTS = {'find flights': '3 flights found', 'pick cheapest': 'AI-123, 4200 rupees', 'book it': 'booked AI-123'}

# Stands in for asking the model to break a goal into steps.
def plan(goal):
    return ['find flights', 'pick cheapest', 'book it']

# Stands in for calling the right tool for each step.
def execute(task):
    return RESULTS[task]

goal = 'book the cheapest flight to Goa'
tasks = [{'task': t, 'status': 'todo'} for t in plan(goal)]
for item in tasks:
    item['result'] = execute(item['task'])
    item['status'] = 'done'
print(tasks[-1]['result'])

Step by step

  1. RESULTS is created and points to a new dict: {find flights: '3 flights found', pick cheapest: 'AI-123, 4200 rupees', book it: 'booked AI-123'}.
  2. Python defines the function plan(). Its body does not run yet: it runs each time the function is called.
  3. Python defines the function execute(). Its body does not run yet: it runs each time the function is called.
  4. goal is created with the value 'book the cheapest flight to Goa'.
  5. The model is asked for a plan.
  6. The function returns ['find flights', 'pick cheapest', 'book it'].
  7. Three tasks, each marked "todo".
  8. item is created and points to a new dict: {task: 'find flights', status: 'todo'}.
  9. Python calls execute(), with task = 'find flights'. It gets its own names.
  10. The function returns RESULTS[task].
  11. Task 1 done: its result is stored next to it.
  12. status in the dict that item points to changes from 'todo' to 'done'.
  13. item now points to a different dict: {task: 'pick cheapest', status: 'todo'}.
  14. Python calls execute(), with task = 'pick cheapest'. It gets its own names.
  15. The function returns RESULTS[task].
  16. execute() has finished, so its names are gone. A new key result with the value 'AI-123, 4200 rupees' is added to the dict that item points to.
  17. status in the dict that item points to changes from 'todo' to 'done'.
  18. The last task.
  19. Python calls execute(), with task = 'book it'. It gets its own names.
  20. The function returns RESULTS[task].
  21. execute() has finished, so its names are gone. A new key result with the value 'booked AI-123' is added to the dict that item points to.
  22. status in the dict that item points to changes from 'todo' to 'done'.
  23. Python moves to the next item of the loop: for item in tasks.
  24. Every task is done; the last result is the outcome.

Common mistakes

Best practices

Key takeaways

Check yourself

Why plan before acting?

Answer: Long goals need ordered steps

A step fails. Good agents?

Answer: Re-plan

·

More in Agents