Lesson 3 of 6 · 2 min
Let a model plan, then check the plan
# run locally: planner.py (uses app/llm.py from the production kit)
import json
from app.llm import chat
from pydantic import BaseModel, ValidationError
class Step(BaseModel):
id: str
tool: str
args: dict
needs: list[str] = []
def plan_for(goal, tools):
messages = [{"role": "user", "content": f"Goal: {goal}\nTools: {list(tools)}\nReply only with a JSON list of steps with id, tool, args, needs. An argument equal to a step id means that step's result."}]
for _ in range(3):
text, _ = chat(messages)
try:
steps = [Step(**s).model_dump() for s in json.loads(text[text.index("["):text.rindex("]") + 1])]
if all(s["tool"] in tools for s in steps):
return steps
problem = "unknown tool"
except (ValueError, ValidationError) as e:
problem = str(e)[:300]
messages += [{"role": "assistant", "content": text}, {"role": "user", "content": "Invalid: " + problem + ". Send the JSON list again."}]
raise RuntimeError("no valid plan")