Build Your First Deep Agent in Python and See Inside It

7 min read

The problem

Most "first agent" tutorials stop at one call to invoke. You get an answer back, but you cannot see what the agent was given, what the model saw, or where its files went. With Deep Agents this is a bigger gap than usual, because the defaults have changed between versions. Older posts say a deep agent ships with a long built-in system prompt, a planning tool, and a default Claude model. At version 0.7.42, none of those three is true by default.

So this part does two things. It builds a working deep agent in a few lines. Then it opens the agent up and reads, from real runs, exactly what create_deep_agent handed to the model.

Install with pinned versions

Every code block in this series ran at these versions:

text
deepagents==0.7.42
langchain==1.5.2
langchain-anthropic==1.7.13
langchain-core==1.8.5
langchain-openai==1.8.5
langgraph==1.2.24
langsmith==0.16.2
Python 3.12.3
bash
python -m venv .venv && . .venv/bin/activate
pip install "deepagents==0.7.42" "langchain==1.5.2" "langgraph==1.2.24" \
  "langchain-anthropic==1.7.13" "langchain-openai==1.8.5"
export ANTHROPIC_API_KEY=...   # or OPENAI_API_KEY, for the provider you use

Your first deep agent

python
# first_agent.py
from deepagents import create_deep_agent


def build_agent(model="anthropic:claude-sonnet-4-6"):
    return create_deep_agent(
        model=model,
        system_prompt="You are a concise research assistant. Save your notes to files.",
    )


def show(result):
    for m in result["messages"]:
        calls = [c["name"] for c in getattr(m, "tool_calls", [])]
        print(f"{type(m).__name__:12} calls={calls} {str(m.content)[:70]!r}")
    for path, f in result["files"].items():
        print(f"\n--- {path} ---\n{f['content']}")


if __name__ == "__main__":
    agent = build_agent()
    show(agent.invoke({"messages": [{"role": "user", "content": "Write /notes.md with three facts about LangGraph."}]}))

Pass the model as a provider:model string. The models page of the docs uses anthropic:claude-sonnet-4-6 and openai:gpt-5.4 as examples. Always pass one. In 0.7.42, leaving model out is deprecated since 0.5.3 and prints a warning, and it falls back to claude-sonnet-4-6.

To show the wiring without an API key, we ran the same build_agent with a scripted fake chat model in place of Claude. The fake asks for write_file, then read_file, then answers. The tools really ran. The file content is scripted, so it says so:

python
# run_fake.py
from recorder import RecordingFake, ai, call
from first_agent import build_agent, show

notes = "# LangGraph notes\n- (scripted fake content)\n"
model = RecordingFake(responses=[
    ai("", call("write_file", {"file_path": "/notes.md", "content": notes}, id="w")),
    ai("", call("read_file", {"file_path": "/notes.md"}, id="r")),
    ai("Saved /notes.md."),
])
agent = build_agent(model)
print(type(agent).__name__)
show(agent.invoke({"messages": [{"role": "user", "content": "Write /notes.md with three facts about LangGraph."}]}))
text
CompiledStateGraph
HumanMessage calls=[] 'Write /notes.md with three facts about LangGraph.'
AIMessage    calls=['write_file'] ''
ToolMessage  calls=[] 'Updated file /notes.md'
AIMessage    calls=['read_file'] ''
ToolMessage  calls=[] '@@ lines 1-2 of 2 @@\n# LangGraph notes\n- (scripted fake content)'
AIMessage    calls=[] 'Saved /notes.md.'

--- /notes.md ---
# LangGraph notes
- (scripted fake content)

The return value of create_deep_agent is a LangGraph CompiledStateGraph. That is why invoke, stream, checkpoints and interrupts all work on it: it is a normal LangGraph graph.

sequenceDiagram
  participant U as Your code
  participant A as Deep agent
  participant M as Model
  participant F as State files
  U->>A: invoke messages
  A->>M: system prompt, messages, 8 tools
  M-->>A: call write_file /notes.md
  A->>F: store file in state
  A->>M: Updated file /notes.md
  M-->>A: call read_file /notes.md
  F-->>A: numbered lines
  A->>M: file content
  M-->>A: final answer, no tool calls
  A-->>U: messages and files

Inspecting the result

The result is the agent's final state, a plain dictionary. To see what the model received, we used a fake model that also records every request. It is a short subclass of LangChain's FakeMessagesListChatModel:

python
# recorder.py (trimmed)
from fake import FakeToolModel, ai, call  # FakeMessagesListChatModel plus a bind_tools that returns self


class RecordingFake(FakeToolModel):
    seen_tools: list = []
    seen_requests: list = []
    ...

    def bind_tools(self, tools, **kwargs):
        names = []
        for t in tools:
            names.append(getattr(t, "name", None) or (t.get("name") if isinstance(t, dict) else str(t)))
        self.seen_tools.append(names)
        ...
        return self

    def _generate(self, messages, stop=None, run_manager=None, **kwargs):
        self.seen_requests.append(list(messages))
        return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)

Then we built an agent with a one-line system prompt and printed what it saw:

python
# inspect_agent.py
from recorder import RecordingFake, ai, call
from deepagents import create_deep_agent

model = RecordingFake(responses=[
    ai("", call("write_file", {"file_path": "/hello.md", "content": "# Hello\nWritten by a deep agent.\n"})),
    ai("Done. I wrote /hello.md."),
])

agent = create_deep_agent(model=model, system_prompt="You are a careful assistant.")
result = agent.invoke({"messages": [{"role": "user", "content": "Write a hello file."}]})

print("Tools the model was offered:")
print(model.seen_tools[0])

system = model.seen_requests[0][0]
text = system.content if isinstance(system.content, str) else "".join(
    b.get("text", "") for b in system.content if isinstance(b, dict))
print("\nSystem prompt type:", type(system).__name__, "| chars:", len(text))
print("System prompt text:")
print(text)

print("\nState keys:", sorted(result.keys()))
print("Messages:")
for m in result["messages"]:
    print(f"  {type(m).__name__:12} {str(m.content)[:60]!r} tool_calls={[c['name'] for c in getattr(m, 'tool_calls', [])]}")
print("\nFiles:", list(result["files"].keys()))
print(result["files"]["/hello.md"])
text
Tools the model was offered:
['ls', 'read_file', 'write_file', 'edit_file', 'delete', 'glob', 'grep', 'task']

System prompt type: SystemMessage | chars: 28
System prompt text:
You are a careful assistant.

State keys: ['files', 'messages']
Messages:
  HumanMessage 'Write a hello file.' tool_calls=[]
  AIMessage    '' tool_calls=['write_file']
  ToolMessage  'Updated file /hello.md' tool_calls=[]
  AIMessage    'Done. I wrote /hello.md.' tool_calls=[]

Files: ['/hello.md']
{'content': '# Hello\nWritten by a deep agent.\n', 'encoding': 'utf-8', 'created_at': '2026-11-28T13:31:55.255131+00:00', 'modified_at': '2026-11-28T13:31:55.255131+00:00'}

Three facts come out of this run.

  1. State has two keys by default: messages and files. There is no todos key, because planning is off.
  2. Files live in state, in memory. The default backend is StateBackend. Each file is a small dict with its content, encoding and two timestamps. Nothing touched the real disk. Part 5 covers the other backends.
  3. The system prompt was exactly ours, all 28 characters of it. In the 0.7.42 source, the old BASE_AGENT_PROMPT is deprecated since 0.7.0, with the note that Deep Agents "no longer provides an authored base prompt."

The built-in tools

The model was offered 8 tools. ls, read_file, write_file, edit_file, delete, glob and grep work on the virtual filesystem. task starts a subagent. Two tools are missing on purpose. execute is dropped because StateBackend cannot run commands. write_todos only appears when you pass TodoListMiddleware.

If the system prompt is so short, where did the detailed guidance go? Into the tool descriptions. We measured them:

text
default: 8 tools, 5136 description chars
  ls              206 chars
  read_file      1124 chars
  write_file      321 chars
  edit_file       338 chars
  delete          362 chars
  glob            809 chars
  grep            557 chars
  task           1419 chars
with TodoListMiddleware: 9 tools, 9009 description chars
  ...
  write_todos    3873 chars
Built-in tool description length, deepagents 0.7.42
task1419 chread_file1124 chglob809 chgrep557 chdelete362 chedit_file338 chwrite_file321 chls206 ch
Data from the sources listed below.

The task and read_file descriptions are the longest. They teach the model when to delegate, and how to read a long file in pages. This text is sent with every model call, so it is part of the fixed cost of a deep agent, as Part 2 measured.

What create_deep_agent builds

Hand-drawn diagram of the deepagents 0.7.42 middleware stack in order: Filesystem tools, SubAgents with the task tool and general-purpose helper, Summarization and PatchToolCalls, then your own middleware such as TodoListMiddleware, then prompt caching plus skills, memory and approvals if set, then UnsupportedContent and ModelRefusal; the stack is passed to LangChain create_agent, which compiles to a LangGraph graph

Drag to rotate. The Deep Agents stack, from the LangGraph runtime up to your model and tools.

Reading graph.py in 0.7.42, the main agent's middleware goes in this order: filesystem, subagents, summarization, and a patch step for dangling tool calls. Your middleware= list goes next. Then come any extras from the model's profile, skills if set, prompt caching, memory if set, approvals if set, and two safety layers at the end. The whole stack goes to LangChain's create_agent. The source also sets a recursion limit of 9,999 steps on the compiled graph, so long runs are not cut off early.

Models and providers

create_deep_agent takes a provider:model string, or any LangChain chat model object. Strings go through init_chat_model. To check what each form turns into, we built four agents. No model was called, so placeholder keys were enough:

python
import os
os.environ.setdefault("ANTHROPIC_API_KEY", "placeholder")
os.environ.setdefault("OPENAI_API_KEY", "placeholder")

from deepagents import create_deep_agent
from deepagents._models import resolve_model  # what create_deep_agent uses for strings
from langchain.chat_models import init_chat_model
from langchain_anthropic import ChatAnthropic

choices = {
    "string, Anthropic": "anthropic:claude-sonnet-4-6",
    "string, OpenAI": "openai:gpt-5.4",
    "init_chat_model": init_chat_model("anthropic:claude-sonnet-4-6", temperature=0, max_tokens=4000),
    "provider class": ChatAnthropic(model_name="claude-sonnet-4-6"),
}
for label, model in choices.items():
    agent = create_deep_agent(model=model)
    m = resolve_model(model)
    name = getattr(m, "model", None) or getattr(m, "model_name", None)
    extra = f" responses_api={m.use_responses_api}" if hasattr(m, "use_responses_api") else ""
    print(f"{label:18} -> {type(m).__name__}({name}){extra}  agent={type(agent).__name__}")
text
string, Anthropic  -> ChatAnthropic(claude-sonnet-4-6)  agent=CompiledStateGraph
string, OpenAI     -> ChatOpenAI(gpt-5.4) responses_api=True  agent=CompiledStateGraph
init_chat_model    -> ChatAnthropic(claude-sonnet-4-6)  agent=CompiledStateGraph
provider class     -> ChatAnthropic(claude-sonnet-4-6)  agent=CompiledStateGraph

Note the OpenAI line. An openai: string turns on the Responses API, which matches the docs. If you need Chat Completions, pass a ChatOpenAI object with use_responses_api=False. resolve_model lives in a private module. We import it here only to look inside, and your own code does not need it.

flowchart TB
  A[Pick a model] --> B{Need custom settings?}
  B -->|No| C[provider:model string]
  B -->|Yes| D[init_chat_model or provider class]
  C --> E[create_deep_agent]
  D --> E
  E --> F{Profile for this model?}
  F -->|Yes| G[Prompt suffix or extra middleware]
  F -->|No| H[Your prompt only]

Open models. The README says any model with tool calling works, including open-weight models on hosts such as Baseten or Fireworks, and self-hosted models through Ollama, vLLM or llama.cpp. The docs list Baseten, Fireworks, OpenRouter and Ollama as routes to open-weight models, using strings like baseten:zai-org/GLM-5.2. The real-model run in Part 2 used Llama 4 Scout, an open model, hosted on Cloudflare Workers AI.

Model profiles change the prompt

Some model strings carry a built-in harness profile that adds to your prompt. We listed the registered profiles. This reads a private registry, so the names may change in later versions:

python
from deepagents.profiles.harness import harness_profiles as hp
from deepagents.profiles._builtin_profiles import _ensure_builtin_profiles_loaded

_ensure_builtin_profiles_loaded()
for key, prof in sorted(hp._HARNESS_PROFILES.items()):
    suffix = len(prof.system_prompt_suffix or "")
    base = len(prof.base_system_prompt or "")
    extra = "yes" if prof.extra_middleware else "no"
    print(f"{key:40} base={base:5} suffix={suffix:5} extra_middleware={extra}")
text
anthropic:claude-haiku-4-5               base=    0 suffix= 1455 extra_middleware=no
anthropic:claude-opus-4-7                base=    0 suffix= 2148 extra_middleware=no
anthropic:claude-sonnet-4-6              base=    0 suffix= 1455 extra_middleware=no
...
openai:gpt-5.2-codex                     base=    0 suffix= 1166 extra_middleware=yes
openai:gpt-5.3-codex                     base=    0 suffix= 1166 extra_middleware=yes
...

So with anthropic:claude-sonnet-4-6, your prompt gets a 1,455-character suffix. The profile's docstring says it adds Anthropic's general Claude guidance: parallel tool calls, grounded answers, and reflecting after tool results. The Codex profiles go further: their extra middleware is TodoListMiddleware, so those models get write_todos even though planning is opt-in for everyone else. This is why the same code can behave a little differently on two models.

Five surprises on a first run

These come straight from the runs above and the 0.7.42 source. Each one trips people who learned from older posts.

  1. No model, no luck. Leaving out model still works, but it is deprecated and prints a warning. The parameter is marked to become required in 1.0.0. Pass a model every time.
  2. Your files are not on disk. A file the agent "wrote" lives in result["files"]. If you look in your folder, it is not there. That is the safe default. To write real files, pick a different backend, covered in Part 5.
  3. No to-do list. If your agent never plans, that is expected. Planning is opt-in since 0.7. Add TodoListMiddleware to get it.
  4. No shell. The execute tool only appears with a sandbox backend. On the default backend the model never sees it. Part 10 shows how to run commands safely.
  5. Your prompt is the prompt. With a model that has no profile, the system prompt is exactly the text you pass. If you pass nothing, the authored part is empty, and the model only gets the tool descriptions. Write a real system prompt for real work.

How this code was tested

Versions are listed at the top. 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 deepagents tools running, or from building agents without invoking them. The first_agent.py code is exactly what we ran, with the fake model passed in place of the default model string. The real-model runs in this series used Llama 4 Scout on Cloudflare Workers AI, through the same create_deep_agent code.

Try this

bash
python run_fake.py       # first_agent.py on a scripted model, no key needed
python inspect_agent.py  # tools offered, system prompt, state keys, files
python tool_sizes.py     # description length per built-in tool
python first_agent.py    # the real thing, needs ANTHROPIC_API_KEY

tool_sizes.py also builds an agent with TodoListMiddleware, and you can see the ninth tool appear in its output. Part 4 is about that tool.

Sources