create_agent(model, tools, system_prompt, middleware) compiles a graph with two nodes, model and tools, and an edge back from tools to model. Middleware hooks run around those nodes. The one this lesson uses, wrap_tool_call(request, handler), wraps every tool call: it can refuse, call the tool with handler(request), and change the result before the model reads it.
Trimming a long output (keep the head and the tail, spill the rest to a file) is taught in Applied LLM Systems 06. Here you plug it into the framework. ToolCallLimitMiddleware(run_limit=n, exit_behavior="end") adds the step budget: after n tool calls, the run stops. Its default, exit_behavior="continue", only blocks the extra calls with an error message and lets the run go on.
🎯 The graph is the loop; middleware is your policy on every turn of it.