Why Agents Lose Track of Long Tasks, and the To-Do Fix
The problem
Give an agent a ten-step job and watch the message list. After a few steps it is mostly raw tool output: file contents, search results, error logs. The plan the model had at the start is buried somewhere in an old reply. Nothing on the page says which steps are done, which one is active, and what is left. The model has to rebuild that picture from scratch on every call. A person watching the run has the same problem: there is nothing to show as progress except a spinner.
LangChain's post that introduced Deep Agents points at Claude Code's answer, a to-do list tool. The post notes that the tool basically does nothing: it is a no-op that exists only to keep the agent on track. That sounds odd until you see what it really does. It turns the plan into a short, structured object that sits in the agent's state and gets restated in the conversation every time it changes.
In deepagents 0.7.42 that tool is write_todos. This part covers how to turn it on, what it stores, what it costs, and how to stream it to a user.
It is off by default
The docs say it plainly: starting in v0.7, task planning is opt-in only. Earlier versions included the planning middleware by default. Part 3 showed the effect: a default agent is offered 8 tools, and write_todos is not one of them. You turn it on with one line:
pythonfrom deepagents import create_deep_agent from langchain.agents.middleware import TodoListMiddleware agent = create_deep_agent( model="anthropic:claude-sonnet-4-6", middleware=[TodoListMiddleware()], )
Note the import path. TodoListMiddleware lives in LangChain, in langchain.agents.middleware, not in deepagents. One exception: in 0.7.42 the built-in profiles for OpenAI's Codex models add TodoListMiddleware for you, because their prompt suffix refers to write_todos.
A full run, step by step
Here is a run on a scripted fake chat model. The fake plays the part of a model that follows the tool's own instructions: it marks the first task in_progress, moves through the list, writes a file, and marks everything done. The tools and the middleware are real.
python"""write_todos end to end on a scripted fake model (no API key).""" import _fakepath # noqa: F401 (adds code/common to sys.path) from fake import FakeToolModel, ai, call from deepagents import create_deep_agent from langchain.agents.middleware import TodoListMiddleware def todos(*statuses): names = ["Outline the post", "Draft the intro", "Write the summary file"] return {"todos": [{"content": n, "status": s} for n, s in zip(names, statuses)]} model = FakeToolModel(responses=[ ai("", call("write_todos", todos("in_progress", "pending", "pending"), id="t1")), ai("", call("write_todos", todos("completed", "in_progress", "pending"), id="t2")), ai("", call("write_todos", todos("completed", "completed", "in_progress"), id="t3")), ai("", call("write_file", {"file_path": "/summary.md", "content": "Intro and outline done.\n"}, id="w1")), ai("", call("write_todos", todos("completed", "completed", "completed"), id="t4")), ai("Summary saved to /summary.md. Outline: 3 sections. Intro: drafted."), ]) agent = create_deep_agent(model=model, middleware=[TodoListMiddleware()]) result = agent.invoke({"messages": [{"role": "user", "content": "Plan and write a short post summary."}]}) print("state keys:", sorted(result.keys())) print("final todos:") for t in result["todos"]: print(f" [{t['status']}] {t['content']}") print("\nwhat the model saw after the first write_todos:") first_tool_msg = [m for m in result["messages"] if type(m).__name__ == "ToolMessage"][0] print(" ", first_tool_msg.content) print("\nfinal answer:", result["messages"][-1].content)
textstate keys: ['files', 'messages', 'todos'] final todos: [completed] Outline the post [completed] Draft the intro [completed] Write the summary file what the model saw after the first write_todos: Updated todo list to [{'content': 'Outline the post', 'status': 'in_progress'}, {'content': 'Draft the intro', 'status': 'pending'}, {'content': 'Write the summary file', 'status': 'pending'}] final answer: Summary saved to /summary.md. Outline: 3 sections. Intro: drafted.
A third state key, todos, appears next to messages and files. And every call echoes the full list back into the conversation as a tool message. That echo is the whole trick: the latest plan is always one of the most recent messages the model reads.
sequenceDiagram participant M as Model participant MW as TodoListMiddleware participant T as write_todos participant S as Agent state MW->>M: system prompt plus write_todos guide M->>T: write_todos full list T->>S: todos = new list T-->>M: Updated todo list to ... M->>T: write_todos with one more done T->>S: todos replaced again T-->>M: Updated todo list to ... M-->>MW: final answer as text
Animation: each write_todos call rewrites the whole to-do list in agent state, and items move from pending to in_progress to completed.
The state shape
The source in LangChain 1.5.2 defines the whole data model in a few lines:
pythonclass Todo(TypedDict): content: str status: Literal["pending", "in_progress", "completed"] class PlanningState(AgentState[ResponseT]): todos: Annotated[NotRequired[list[Todo]], OmitFromInput]
Each item is just text and one of three statuses. There are no IDs, no due dates, and no "blocked" or "cancelled" states. The tool's description tells the model how to handle those cases instead: when blocked, keep the task in_progress and add a new task that describes the blocker. It also says more than one task can be in_progress at once, when they are unrelated and can run in parallel.
The tool does not edit one item. It replaces the whole list on every call. The tool's return value sets todos to whatever list the model sent.

Two calls in one turn are rejected
Because each call replaces the list, two calls in the same model turn would race. The middleware checks for this after every model call. If the model asks for more than one write_todos at once, all of them get an error message, and none of them runs. We tested it:
python"""Two write_todos calls in one turn are rejected (scripted fake model).""" # imports as in todo_basic.py one = {"todos": [{"content": "A", "status": "in_progress"}]} two = {"todos": [{"content": "B", "status": "in_progress"}]} model = FakeToolModel(responses=[ ai("", call("write_todos", one, id="x1"), call("write_todos", two, id="x2")), ai("", call("write_todos", one, id="x3")), ai("Done."), ]) agent = create_deep_agent(model=model, middleware=[TodoListMiddleware()]) result = agent.invoke({"messages": [{"role": "user", "content": "go"}]}) for m in result["messages"]: if type(m).__name__ == "ToolMessage": print(f"{m.tool_call_id}: status={m.status} | {m.content[:90]}") print("final todos:", result["todos"])
textx1: status=error | Error: The `write_todos` tool should never be called multiple times in parallel. Please ca x2: status=error | Error: The `write_todos` tool should never be called multiple times in parallel. Please ca x3: status=success | Updated todo list to [{'content': 'A', 'status': 'in_progress'}] final todos: [{'content': 'A', 'status': 'in_progress'}]
The first turn's two calls both failed with status=error. The model's retry in the next turn, with a single call, went through. This matters for models that like parallel tool calls. The model gets a clear error and a second chance, instead of a silently mixed-up plan.
What planning costs
write_todos is not free. The middleware appends a guide to the system prompt on every model call, and the tool description rides along with every call too. We counted both:
pythonfrom langchain.agents.middleware import TodoListMiddleware default = TodoListMiddleware() short = TodoListMiddleware( system_prompt="Use write_todos for tasks with 3+ steps. Keep one item in_progress. Mark items completed right away.", tool_description="Replace the whole todo list. Each item: content and status (pending, in_progress, completed).", ) for label, mw in [("default", default), ("short custom", short)]: p, d = len(mw.system_prompt), len(mw.tools[0].description) print(f"{label:13} system prompt {p:5} chars, tool description {d:5} chars, total ~{(p + d) // 4} tokens at 4 chars/token")
textdefault system prompt 1370 chars, tool description 3873 chars, total ~1310 tokens at 4 chars/token short custom system prompt 100 chars, tool description 93 chars, total ~48 tokens at 4 chars/token
Extra prompt text per model call from planning (chars)Data from the sources listed below.
The default adds about 5,200 characters, roughly 1,300 tokens at 4 characters per token, to every request. For comparison, Part 3 measured all 8 default deep agent tool descriptions together at 5,136 characters. Turning on planning nearly doubles the fixed text the model reads before your task even starts.
Both texts can be replaced through the two constructor arguments shown above. The docs list exactly those two options. A short version is cheaper, but the default text carries real guidance: when not to plan, when to mark items done, and to write the final answer after the last write_todos call. If you shorten it, test that your model still behaves.
The default guide also tells the model to skip planning for trivial jobs: "For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool." The docs suggest planning for long or complicated multi-step tasks, for less capable models that benefit from an explicit accountability tool, and for UIs that stream progress.
Streaming progress to a user
Because todos live in state, every write_todos call shows up as a state update. With stream_mode="updates" you can turn each one into a progress line:
python# agent: create_deep_agent(model=..., middleware=[TodoListMiddleware()]); the model here is # a scripted fake that moves three steps along (see todo_stream.py) for chunk in agent.stream({"messages": [{"role": "user", "content": "Research and report."}]}, stream_mode="updates"): for node, update in chunk.items(): if update and "todos" in update: done = sum(t["status"] == "completed" for t in update["todos"]) bar = " ".join({"completed": "[x]", "in_progress": "[>]", "pending": "[ ]"}[t["status"]] for t in update["todos"]) print(f"{node:6} {bar} {done}/{len(update['todos'])} done")
texttools [>] [ ] [ ] 0/3 done tools [x] [>] [ ] 1/3 done tools [x] [x] [>] 2/3 done tools [x] [x] [x] 3/3 done
The updates arrive from the tools node, the moment each write_todos call returns. A web UI can render the same data as a checklist. Part 11 covers the other stream modes.
flowchart LR A[Model turn] --> B{write_todos called?} B -->|No| A B -->|Once| C[Replace state todos] B -->|Twice or more| D[Error to every call] D --> A C --> E[Stream update to UI] C --> A
Todos survive across turns, but you cannot pass them in
With a checkpointer, the list stays with the thread. We ran two turns on one thread_id. The first turn wrote a plan. The second turn did not touch it:
pythonfrom langgraph.checkpoint.memory import InMemorySaver # model: a scripted fake that writes two todos, then answers twice (see todo_thread.py) agent = create_deep_agent(model=model, middleware=[TodoListMiddleware()], checkpointer=InMemorySaver()) cfg = {"configurable": {"thread_id": "demo-1"}} agent.invoke({"messages": [{"role": "user", "content": "Start the job."}]}, cfg) agent.invoke({"messages": [{"role": "user", "content": "Where are we?"}]}, cfg) state = agent.get_state(cfg).values print("turn 2 todos:", [(t["content"], t["status"]) for t in state["todos"]]) print("input schema has 'todos':", "todos" in agent.get_input_jsonschema().get("properties", {})) print("output schema has 'todos':", "todos" in agent.get_output_jsonschema().get("properties", {}))
textturn 2 todos: [('Collect data', 'completed'), ('Write chart', 'in_progress')] input schema has 'todos': False output schema has 'todos': True
The plan carried over to turn 2. But todos is not part of the agent's input schema. That is the OmitFromInput marker in PlanningState. You read the plan from the output or from get_state, and only the model writes it, through the tool.
It works without deepagents too
Since TodoListMiddleware is a LangChain middleware, a plain create_agent can use it:
pythonimport _fakepath # noqa: F401 from fake import FakeToolModel, ai, call from langchain.agents import create_agent from langchain.agents.middleware import TodoListMiddleware model = FakeToolModel(responses=[ ai("", call("write_todos", {"todos": [ {"content": "Check the logs", "status": "in_progress"}, {"content": "Write the fix", "status": "pending"}]}, id="p1")), ai("Logs checked. Next: the fix."), ]) agent = create_agent(model, tools=[], middleware=[TodoListMiddleware()]) result = agent.invoke({"messages": [{"role": "user", "content": "Fix the bug."}]}) print("state keys:", sorted(result.keys())) print("todos:", result["todos"])
textstate keys: ['messages', 'todos'] todos: [{'content': 'Check the logs', 'status': 'in_progress'}, {'content': 'Write the fix', 'status': 'pending'}]
So if planning is the only piece of the recipe you need, you can add it to a lighter loop and skip the rest.
What this does not prove
Every run in this part used a scripted model. The scripts show the wiring: the state key, the echo, the parallel guard, the stream, the checkpointer. They do not show whether a real model plans well, or whether planning makes a given model finish more tasks. That depends on the model and the task, and you should measure it on your own work.
How this code was tested
Versions: deepagents 0.7.42, langchain 1.5.2, langchain-core 1.8.5, langgraph 1.2.24, Python 3.12.3. No real model was called in this part. Every printed output came from a scripted fake model built on LangChain's FakeMessagesListChatModel, with the real TodoListMiddleware, write_todos tool and deepagents tools running. The cost numbers are character counts of the real prompt and tool description, converted at 4 characters per token. The first snippet with "anthropic:claude-sonnet-4-6" shows the reader's setup. Our runs passed the fake model in its place.
Try this
bashpython todo_basic.py # plan, progress, final todos python todo_parallel.py # two write_todos in one turn python todo_stream.py # progress bar from stream_mode="updates" python todo_thread.py # todos across two turns with a checkpointer python todo_cost.py # prompt cost, default vs short python todo_plain_agent.py # TodoListMiddleware on a plain create_agent
Then swap the fake model in todo_basic.py for a real one, give it a task with five or more steps, and print result["todos"] at the end. Check whether the model kept exactly one item in_progress at a time, as the guide asks.
Next: Part 5: The virtual filesystem and its backends.
