Lesson 18 of 39 · The Agent Harness
Harness Agents: Todos, Modes and File Memory
Build long-running agents with create_harness_agent: todo lists, plan and execute modes, looping until done, file memory and shared file access.
- 11 min read
- Intermediate
- Reviewed
- Explain what a harness agent adds to a plain Agent
- Create one with create_harness_agent and follow its todo list and mode
- Switch modes from your app with set_agent_mode, and loop until every todo is done
- Give an agent memory files per customer with FileMemoryProvider
- Share files with an agent through FileAccessProvider and an AgentFileStore
An agent that works like a person with a notebook
A plain agent answers one message at a time. Longer jobs, such as planning a two-day bike trip or researching a report, go better when the agent works the way people do: it writes a todo list, agrees the plan before acting, keeps notes, and doesn't stop until the list is done. Agent Framework packs these habits into a harness agent.
The core idea in plain Python:
# The harness idea in plain Python: a todo list and a mode that live in the session.
session = {"mode": "plan", "todos": []}
def todos_add(*titles):
for title in titles:
session["todos"].append({"id": len(session["todos"]) + 1, "title": title, "done": False})
def todos_complete(todo_id):
session["todos"][todo_id - 1]["done"] = True
def show():
print("mode:", session["mode"])
for todo in session["todos"]:
print(f" [{'x' if todo['done'] else ' '}] {todo['id']}. {todo['title']}")
todos_add("Pick a route", "Book two City E bikes", "Find a guesthouse") # while planning
show()
session["mode"] = "execute" # the customer says go
todos_complete(1)
show()
print("open:", sum(not todo["done"] for todo in session["todos"]))Your first harness agent
create_harness_agent(client, ...) returns a normal Agent. Your own instructions go in agent_instructions; they are added after the harness's general working rules (DEFAULT_HARNESS_INSTRUCTIONS, which you can replace with harness_instructions). Every feature can be switched off with a disable_... argument.
import asyncio
from agent_framework import TodoProvider, create_harness_agent, get_agent_mode, set_agent_mode
from agent_framework.openai import OpenAIChatClient
async def main():
agent = create_harness_agent(
OpenAIChatClient(model="MODEL_NAME"),
name="trip_planner",
agent_instructions="You plan bike trips for Velo's customers in Porto.",
disable_file_memory=True, # file memory comes later in this lesson
default_options={"store": False}, # the harness keeps the history itself
)
print("providers:", [provider.source_id for provider in agent.context_providers])
session = agent.create_session()
print("mode:", get_agent_mode(session))
print((await agent.run("Plan a two-day bike trip in the Douro valley for two people.", session=session)).text)
set_agent_mode(session, "execute") # your app switches the mode, e.g. after a Start button
print("mode:", get_agent_mode(session))
print((await agent.run("Go ahead.", session=session)).text)
todos = next(p for p in agent.context_providers if isinstance(p, TodoProvider))
for item in await todos.store.load_items(session, source_id=todos.source_id):
print(f" [{'x' if item.is_complete else ' '}] {item.id}. {item.title}")
asyncio.run(main())providers: ['in_memory', 'todo', 'agent_mode'] mode: plan Here is the plan: pick a route, book two City E bikes and find a guesthouse. Shall I start? mode: execute Route chosen: the 45 km Douro valley loop. Next I'll book the bikes. [x] 1. Pick a route [ ] 2. Book two City E bikes [ ] 3. Find a guesthouse
Here is what happened:
TodoProvidergave the model the toolstodos_add,todos_complete,todos_remove,todos_get_remainingandtodos_get_all. Inplanmode the model wrote three todos and asked before starting. Each todo is aTodoItemwith anid, atitle, an optionaldescriptionandis_complete.AgentModeProviderkept the mode in the session and gave the modelmode_getandmode_set. Your app read it withget_agent_mode(session)and changed it withset_agent_mode(session, "execute"); on the next run the provider told the model about the switch, and it started working.- Todos live in the session by default (
TodoSessionStore). Passtodo_provider=TodoProvider(store=TodoFileStore("todos"))to keep them in files instead, or subclassTodoStorefor a database.
The harness also adds compaction when you pass max_context_window_tokens and max_output_tokens, a web search tool when the client supports one (turn it off with disable_web_search=True), tool approvals with "don't ask again" rules, and, if you ask for them, skills (skills_paths) and background agents (background_agents).
Looping until every todo is done
A model often stops after one step. Give the harness a loop rule and it runs the agent again until the rule says stop. todos_remaining() keeps going while todos are open, and todos_remaining_message writes the next message, listing what is left:
import asyncio
from agent_framework import TodoItem, TodoProvider, create_harness_agent, set_agent_mode, todos_remaining, todos_remaining_message
from agent_framework.openai import OpenAIChatClient
async def main():
agent = create_harness_agent(
OpenAIChatClient(model="MODEL_NAME"),
agent_instructions="You plan bike trips for Velo's customers in Porto.",
disable_file_memory=True,
loop_should_continue=todos_remaining(looping_modes=["execute"]), # run again while todos are open
loop_next_message=todos_remaining_message, # remind the model what is left
loop_max_iterations=5, # safety cap
loop_return_final_only=True, # return only the last run
default_options={"store": False},
)
session = agent.create_session()
todos = next(p for p in agent.context_providers if isinstance(p, TodoProvider))
await todos.store.save_state(
session,
[TodoItem(1, "Pick a route"), TodoItem(2, "Book two City E bikes"), TodoItem(3, "Find a guesthouse")],
next_id=4,
source_id=todos.source_id,
)
set_agent_mode(session, "execute")
response = await agent.run("Finish the trip plan.", session=session)
print(response.text)
for item in await todos.store.load_items(session, source_id=todos.source_id):
print(f" [{'x' if item.is_complete else ' '}] {item.id}. {item.title}")
asyncio.run(main())Finished todo 3. [x] 1. Pick a route [x] 2. Book two City E bikes [x] 3. Find a guesthouse
The agent ran three times, finishing one todo each time. looping_modes=["execute"] keeps the loop out of planning, where the list is still being written, and loop_max_iterations is a safety cap on cost. Looping is still experimental, so it prints an ExperimentalWarning.
Memory files: FileMemoryProvider
FileMemoryProvider gives the agent a folder of notes with the tools file_memory_write, file_memory_read, file_memory_ls, file_memory_grep, file_memory_replace, file_memory_replace_lines and file_memory_delete. The harness adds one by default, kept per session in ./agent-file-memory. Pass your own provider with a scope, such as a customer id, to keep memories across all of that customer's sessions:
import asyncio
from pathlib import Path
from agent_framework import FileMemoryProvider, FileSystemAgentFileStore, create_harness_agent
from agent_framework.openai import OpenAIChatClient
def make_agent(customer_id: str):
memory = FileMemoryProvider(
FileSystemAgentFileStore("agent-memory"), # files under ./agent-memory
scope=customer_id, # one folder per customer, shared by all their sessions
)
return create_harness_agent(
OpenAIChatClient(model="MODEL_NAME"),
agent_instructions="You plan bike trips for Velo's customers in Porto.",
disable_file_memory=True, # replaced by our own provider below
context_providers=[memory],
default_options={"store": False},
)
async def main():
agent = make_agent("customer-asha")
print((await agent.run("Remember that I always ride a City E and want routes under 50 km a day.",
session=agent.create_session())).text)
# A week later: a new session, the same customer.
agent = make_agent("customer-asha")
print((await agent.run("Suggest a ride for Saturday.", session=agent.create_session())).text)
for path in sorted(Path("agent-memory").rglob("*.md")):
print(path.relative_to("agent-memory"), "->", path.read_text().splitlines())
asyncio.run(main())Saved. I'll remember that. Try the 45 km Douro valley loop on a City E: it stays under your 50 km a day. customer-asha/memories.md -> ['# Memory Index', '', "- **preferences.md**: Asha's riding preferences"] customer-asha/preferences.md -> ['- Rides a City E', '- Wants routes under 50 km a day'] customer-asha/preferences_description.md -> ["Asha's riding preferences"]
The provider keeps an index, memories.md, so the agent can see which notes exist, and stores each note's description next to it. FileMemoryProvider replaces the older MemoryContextProvider, which is deprecated.
Shared files: FileAccessProvider and file stores
FileAccessProvider is different: it opens a shared set of files (input data, documents, reports) that every session and agent can use. Its tools are file_access_read, file_access_read_lines, file_access_ls, file_access_grep, and the write tools file_access_write, file_access_replace, file_access_replace_lines and file_access_delete. Pass file_access_store to the harness to turn it on:
import asyncio
from agent_framework import InMemoryAgentFileStore, create_harness_agent
from agent_framework.openai import OpenAIChatClient
async def main():
files = InMemoryAgentFileStore() # use FileSystemAgentFileStore("shared") for real folders
await files.write("routes/douro.md", "Douro valley loop: 45 km, one long climb, river views.")
agent = create_harness_agent(
OpenAIChatClient(model="MODEL_NAME"),
agent_instructions="You plan bike trips for Velo's customers in Porto.",
file_access_store=files, # adds the file_access_* tools
file_access_disable_write_tools=True, # read, read_lines, ls and grep only
file_access_disable_readonly_tool_approval=True,
default_options={"store": False},
)
reply = await agent.run("What's the Douro route like?", session=agent.create_session())
print(reply.text)
print([entry.name for entry in await files.list_children("routes")])
asyncio.run(main())The Douro loop is 45 km with one long climb, and the views are worth it. ['douro.md']
Every file tool requires your approval by default. Here the read-only tools are approved in advance and the write tools are hidden, which suits an agent that only reads.
Both providers store files through an AgentFileStore:
FileSystemAgentFileStore(root_directory)keeps real files under one folder and refuses paths that try to leave it, such as../secrets.txtor/etc/passwd.InMemoryAgentFileStore()keeps files in memory, which is ideal for tests.- For cloud storage, subclass
AgentFileStoreand implement its abstract methods:write,read,delete,list_children(which returnsFileStoreEntryobjects),file_existsandcreate_directory.
Common mistakes
Write the loop rule that todos_remaining() uses: keep going only in a looping mode, and only while a todo is still open.
session = {"mode": "execute", "todos": [
{"id": 1, "title": "Pick a route", "done": True},
{"id": 2, "title": "Book two City E bikes", "done": False},
{"id": 3, "title": "Find a guesthouse", "done": False},
]}
def agent_step(session):
# A pretend agent run: it finishes the first open todo.
for todo in session["todos"]:
if not todo["done"]:
todo["done"] = True
return f"done: {todo['title']}"
return "nothing to do"
def should_continue(session, looping_modes=("execute",)):
# Return True only while the mode is one of looping_modes
# and at least one todo is still open.
return False
iterations = 0
print(agent_step(session))
while should_continue(session) and iterations < 10:
iterations += 1
print(agent_step(session))
print("open todos:", [todo["title"] for todo in session["todos"] if not todo["done"]])
session["mode"] = "plan"
session["todos"].append({"id": 4, "title": "Pack a rain jacket", "done": False})
print("loop in plan mode?", should_continue(session))
What is the difference between FileMemoryProvider and FileAccessProvider?
Summary
create_harness_agentbuilds anAgentwith todos, modes, file memory, compaction, approvals and more; switch parts off withdisable_...arguments.TodoProviderkeeps a list of **TodoItem**s;AgentModeProviderkeepsplanorexecute, read and set withget_agent_modeandset_agent_mode.loop_should_continue=todos_remaining(...)makes the agent keep working until every todo is done.FileMemoryProviderkeeps notes per session or scope;FileAccessProvideropens shared files with approvals; both use anAgentFileStoresuch asFileSystemAgentFileStoreorInMemoryAgentFileStore.
Next: Background Agents and Long-Running Responses.
Finished reading? Tick it off to track your progress.