How to Give a Deep Agent Memory With AGENTS.md and Skills

8 min read

Every new chat with an agent starts from zero. You told it last week that tests use pytest, that it must never touch migrations/, and that you want short answers. Today it has forgotten all of it.

The obvious fix is to paste everything into the system prompt. That breaks in two ways.

  1. Some knowledge is always needed, and it changes. Project rules and user preferences should be in front of the model on every call. They also grow, because the agent should learn from corrections. A hard-coded prompt string cannot learn.
  2. Some knowledge is only needed sometimes, and it is big. A full release-notes playbook, a SQL review checklist, a style guide. Put ten of those into every prompt and you pay for thousands of tokens on every call, for tasks that use none of them.

There is a third problem under both: where does learned knowledge live? If the agent writes "user prefers pytest" into a file in thread A, thread B should see it. A different user should not.

Deep agents split this into three features:

  • memory=: AGENTS.md files, loaded in full into the system prompt.
  • skills=: SKILL.md directories, where only the name and description sit in the prompt, and the body is read on demand.
  • StoreBackend behind a CompositeBackend: files under one path prefix that outlive the thread.

This part runs all three and measures what each one puts in the prompt. It builds on the backends from the virtual filesystem part.

How this code was tested

Python 3.12.3, deepagents==0.7.42, langchain==1.5.2, langchain-core==1.8.5, langgraph==1.2.24. All runs in this part used a scripted fake chat model that also records every prompt it receives, which is how we can print the exact system prompt the middleware built. The memory loading, skill discovery, store routing and namespaces are real. The model's tool calls are scripted. No real-model runs were made for this part: the series' Llama 4 Scout endpoint on Workers AI returned HTTP 429 earlier the same day, and the series rule is to stop real calls after a 429.

Hand-drawn diagram: on the left, what the model sees. The system prompt holds the full AGENTS.md text inside an agent_memory block, plus a skills list with only names and descriptions. A tool message holds a full SKILL.md body. On the right, files in the backend: /memories/AGENTS.md is loaded once per thread and updated with edit_file; /skills/release-notes/SKILL.md sends only its frontmatter at start and its body through read_file when needed.

Memory: AGENTS.md, always in the prompt

AGENTS.md is a plain markdown convention for agent instructions (agents.md). Deep agents load any list of such files with memory=:

python
from deepagents import create_deep_agent
from deepagents.backends.utils import create_file_data

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    memory=["/memory/user/AGENTS.md", "/memory/project/AGENTS.md"],
)
result = agent.invoke({
    "messages": [{"role": "user", "content": "Remember that I prefer pytest."}],
    # Default StateBackend: the files live in state, so seed them on invoke.
    "files": {
        "/memory/user/AGENTS.md": create_file_data("# User preferences\n- Answer in short bullet points.\n"),
        "/memory/project/AGENTS.md": create_file_data(open("project/AGENTS.md").read()),
    },
})

The paths are backend paths. With the default StateBackend they come from the files you pass in. With FilesystemBackend they are read from disk under its root_dir. A missing file is skipped without an error.

The project file in this test has a comment for authors:

markdown
# Project memory

<!-- authoring note: the model never sees HTML comments -->

## Conventions
- Python 3.12, type hints everywhere.
- Tests live in tests/ and run with `pytest -q`.
- Never edit files under migrations/ by hand.

Here is the block MemoryMiddleware added to the first system prompt, from logs/part09-memory-agents-md.txt:

text
<agent_memory>
/memory/user/AGENTS.md

# User preferences
- Answer in short bullet points.

/memory/project/AGENTS.md

# Project memory
...
## Conventions
- Python 3.12, type hints everywhere.
- Tests live in tests/ and run with `pytest -q`.
- Never edit files under migrations/ by hand.
...
</agent_memory>
--- HTML comment reached the model: False
--- memory guidelines block chars: 5072
--- total system prompt chars: 5424

What this shows:

  • Files appear in the order you list them, each under its path.
  • HTML comments are stripped before injection. Use them for notes to humans.
  • The memory content is small here. The fixed <memory_guidelines> text after it is 5,072 characters. Those guidelines tell the model to treat memory as file data rather than commands, to save learnings with edit_file, and never to store API keys or passwords. That fixed text is the cost of turning memory on, even with a one-line AGENTS.md.
Characters in the first system prompt (memory demo)
memory guidelines (fixed)5072charseverything else352chars
Data from the sources listed below.

The agent edits its own memory

The scripted model reacted to "Remember that I prefer pytest" with an edit_file on the user file, which is what the guidelines ask for. After the turn:

text
--- user AGENTS.md after the turn:
# User preferences
- Answer in short bullet points.
- Prefers pytest over unittest.

--- second model call sees the edit in its prompt: False

The file changed, but the very next model call in the same run still saw the old text. That is not a bug in our script. In 0.7.42, MemoryMiddleware.before_agent loads the files into a private memory_contents state key, and skips loading if that key is already present. So when does the edit show up?

When does an edit reach the prompt?

We ran three invocations with a checkpointer, two on thread t1 and one on thread t2, with memory in a StoreBackend so both threads share the file (code/part09/memory_reload.py):

text
t1 turn 1, call 1  prompt has 'Uses pytest': False
t1 turn 1, call 2  prompt has 'Uses pytest': False
t1 turn 2          prompt has 'Uses pytest': False
t2 turn 1          prompt has 'Uses pytest': True
store now holds: ['# Prefs', '- Short answers.', '- Uses pytest.']

With a checkpointer, memory_contents is saved with the thread, so the whole thread keeps the memory it loaded at its first turn. A new thread loads fresh and sees the edit. In practice: memory learned in one conversation shows up in the next conversation, not later in the same one. Within the same conversation, the model still has its own edit_file call in its history, so it knows what it saved.

Skills: names in the prompt, bodies on demand

A skill is a directory with a SKILL.md file. YAML frontmatter on top, instructions below:

markdown
---
name: release-notes
description: Write user-facing release notes from a list of merged pull requests. Use when the user asks for a changelog or release notes.
license: MIT
metadata:
  owner: docs-team
---

# Release notes

## Steps
1. Read the PR list the user gives you, or `/changes.txt` if it exists.
2. Group changes into: New, Improved, Fixed. Drop internal refactors.
3. Write one plain sentence per change. Lead with what the user can now do.
4. Save the result to `/release-notes.md`.
...

The format follows the Agent Skills specification (agentskills.io). The SkillMetadata type in 0.7.42 enforces its rules: name is 1 to 64 characters, lowercase letters, digits and single hyphens, and must match the directory name. description is capped at 1,024 characters. Optional fields are license, compatibility, metadata and allowed-tools.

We made three skills on disk: release-notes, sql-review (with allowed-tools: read_file grep), and a broken one named Bad Name in a BadName/ folder.

python
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend

backend = FilesystemBackend(root_dir="skills_root", virtual_mode=True)
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    backend=backend,
    skills=["/skills/"],
)

The run printed a warning first:

text
Skill 'Bad Name' in /skills/BadName/SKILL.md does not follow Agent Skills specification: name must be lowercase alphanumeric with single hyphens only. Consider renaming for spec compliance.

It warns but still lists the skill. Then the skills section of the system prompt (logs/part09-skills.txt):

text
## Skills System
...
**Skills Skills**: `/skills/` (higher priority)
...
**Available Skills:**

- **Bad Name**: A skill whose name breaks the naming rules.
  -> Read `/skills/BadName/SKILL.md` for full instructions
- **release-notes**: Write user-facing release notes from a list of merged pull requests. Use when the user asks for a changelog or release notes. (License: MIT)
  -> Read `/skills/release-notes/SKILL.md` for full instructions
- **sql-review**: Review SQL migrations for locking, missing indexes and unsafe defaults. Use when the user shares a .sql file or asks about a migration.
  -> Allowed tools: read_file, grep

Two small things. The label "Skills Skills" is the source label plus the word "Skills". The label comes from the path: a folder literally called skills normally takes its parent's name, so ~/.claude/skills becomes "Claude", but at the root there is no parent, so it stays "Skills". Use a path like /project/skills/ to get a readable label. SkillsMiddleware also accepts a (path, label) tuple, though create_deep_agent(skills=...) is typed as a list of strings. And in 0.7.42 allowed-tools is only printed in the listing. We found no code in the package that enforces it.

This is progressive disclosure. The model sees one line per skill and a path. When a task matches, it calls read_file on that path. The prompt text tells it to pass limit=1000, because the default read is 100 lines.

sequenceDiagram
    participant U as User
    participant A as Agent
    participant L as LLM
    participant B as Backend
    A->>B: list /skills/, parse frontmatter
    U->>A: write release notes for PR 88
    A->>L: prompt with skill names only
    L-->>A: read_file release-notes/SKILL.md
    A->>B: read SKILL.md
    B-->>A: full instructions
    A->>L: tool result with body
    L-->>A: write_file /release-notes.md
    A->>B: write file
    L-->>U: done

The measured sizes:

text
--- available-skills listing chars: 622
--- full SKILL.md chars: release-notes 778 | sql-review 479
--- whole skills section chars: 2448
--- skill body in first prompt: False
--- skill body arrives via read_file: True
Skills demo: characters in context
skills section (fixed text + list)2448charslist of 3 skills622chars3 skill bodies if inlined1257chars
Data from the sources listed below.

The bodies-inlined bar adds the two real skill files (778 + 479 = 1,257 characters, without the tiny broken one). With three short skills, disclosure barely saves anything: the fixed "how to use skills" text is bigger than the bodies. The saving appears when skills are long or many. The docs suggest keeping a SKILL.md body under 5,000 tokens and putting deep reference material in files the skill points to, so each layer stays small.

Skills are loaded once per thread and cached in state, like memory. The middleware docstring gives the reset: invoke with "skills_metadata": None to rescan. It also supports pinned_skills=[...] on invoke, which appends a named skill's full body as a message, for when the user names the skill directly.

Memory or skill?

flowchart TD
    Q["new piece of agent knowledge"] --> A{"needed on almost every task?"}
    A -- yes --> M["AGENTS.md via memory="]
    A -- no --> B{"a multi-step workflow or long reference?"}
    B -- yes --> S["SKILL.md via skills="]
    B -- no --> T{"does it change per user?"}
    T -- yes --> P["file under /memories/ in StoreBackend"]
    T -- no --> SP["system_prompt="]

Long-term memory across threads with StoreBackend

StateBackend files die with the thread. To keep some files, route a path prefix to a StoreBackend, which saves files in a LangGraph store. The namespace function decides who shares what. Here it reads a user ID from the runtime context:

python
from dataclasses import dataclass
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, StoreBackend

@dataclass
class Ctx:
    user_id: str

store = InMemoryStore()   # use a database-backed store in production
backend = CompositeBackend(
    default=StateBackend(),   # scratch files: per thread
    routes={"/memories/": StoreBackend(namespace=lambda rt: (rt.context.user_id, "memories"))},
)
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    backend=backend, store=store, checkpointer=InMemorySaver(), context_schema=Ctx,
)

agent.invoke({"messages": [...]}, {"configurable": {"thread_id": "A"}}, context=Ctx(user_id="alice"))

Thread A (alice) writes /memories/prefs.md and /scratch.md. Thread B (alice) lists /, reads both. Thread C (bob) reads /memories/prefs.md. From logs/part09-store-threads.txt:

text
=== thread A, user alice
tool write_file: Updated file /memories/prefs.md
tool write_file: Updated file /scratch.md
thread files in state: ['/scratch.md']

=== thread B, user alice
tool ls: ['/memories/']
tool read_file: @@ lines 1-1 of 1 @@
Prefers metric units.
tool read_file: Error: File '/scratch.md' not found

=== thread C, user bob
tool read_file: Error: File '/prefs.md' not found

store namespaces: [('alice', 'memories'), ('bob', 'memories')]
('alice', 'memories') /prefs.md -> Prefers metric units.

Everything we wanted:

  • /memories/prefs.md written in thread A is readable in thread B for the same user.
  • /scratch.md stayed in thread A's state and is gone in thread B.
  • Bob's namespace is separate, so his read fails.
  • The thread's files state only lists /scratch.md. Routed files are not in thread state at all.

Note bob's error message says /prefs.md, not /memories/prefs.md. The composite backend strips the route prefix before handing the path to the store backend, and the store key is /prefs.md. If you read the store directly from app code, use the key without the prefix.

sequenceDiagram
    participant A1 as Thread A alice
    participant CB as CompositeBackend
    participant ST as State of thread
    participant S as Store
    A1->>CB: write /memories/prefs.md
    CB->>S: put alice/memories /prefs.md
    A1->>CB: write /scratch.md
    CB->>ST: save in thread A
    Note over A1,S: new thread B, same user
    CB->>S: get alice/memories /prefs.md
    S-->>CB: Prefers metric units

Put this together with memory=["/memories/AGENTS.md"] and you get the pattern the docs describe for long-term memory: an AGENTS.md per user that the agent edits with edit_file, stored across threads, and loaded at the start of each new thread. That is exactly what memory_reload.py above ran.

One caution from the memory middleware's own prompt: memory is file data that "may be outdated, incorrect, or written by someone other than the current user". If users can write to a shared namespace, one user can plant instructions for another. Scope namespaces per user unless you mean to share, and keep shared skill libraries read-only. Permission rules for that are in the backends part.

Try this

bash
pip install deepagents==0.7.42
mkdir -p demo/skills/hello-world
cat > demo/skills/hello-world/SKILL.md <<'EOF'
---
name: hello-world
description: Greet the user in three languages. Use when the user says hello.
---
1. Say hello in English, French and Spanish.
EOF
python - <<'EOF'
from deepagents.backends import FilesystemBackend
from deepagents.middleware.skills import SkillsMiddleware, _list_skills
b = FilesystemBackend(root_dir="demo", virtual_mode=True)
print(_list_skills(b, "/skills/"))
EOF

_list_skills is a private helper, used here only to show the parsed frontmatter. Then pass skills=["/skills/"] and backend=b to create_deep_agent and print the system prompt your model receives.

Sources