Module 11: Deep Agents
Deep Agents CLI
Capsule overview
Deep Agents CLI lets you run autonomous agents from the terminal. It isn't a development wrapper or a testing environment — it's a productivity tool. You hand it a task; the agent plans, executes, writes files, and delivers the result. You come back when it's done.
In Module 6 you built a CLI for your agent by hand: argparse, an execution loop, error handling, formatted output. It worked, but every new agent meant rebuilding that layer. Deep Agents CLI gives you all of it out of the box with a single command.
The difference from the previous capsules: in 02-05 you learned the Deep Agents capabilities as Python APIs. In this capsule, you invoke those same capabilities from the terminal without writing code.
Installation and setup
Install the CLI
If you installed deep-agents back in capsule 01, the CLI is already available:
pip install deep-agents
Check that it works:
deep-agent --version
# Expected output:
# deep-agent 0.2.x
Configure API keys
The CLI reads environment variables. If you already have a .env, make sure it gets loaded in your shell:
export OPENAI_API_KEY=sk-...
Or use a .env file in your working directory:
# .env
OPENAI_API_KEY=sk-...
TAVILY_API_KEY=tvly-...
The CLI automatically loads the .env from the current directory.
Quick check
deep-agent "What is the capital of France?"
# Expected output:
# [Planning] Task is simple, executing directly...
# [Result] The capital of France is Paris.
If you see a coherent answer, the CLI is ready.
Basic usage: one task, one result
Direct command
deep-agent "Research current trends in RAG and write a summary to output/rag-trends.md"
What happens under the hood:
1. [Planning] write_todos: breaks "research RAG" into steps
2. [Executing] Step 1: Search for sources on RAG 2025
3. [Filesystem] Write findings to research/web_results.md
4. [Executing] Step 2: Analyze and synthesize
5. [Filesystem] Write analysis to analysis/synthesis.md
6. [Executing] Step 3: Generate final summary
7. [Filesystem] Write report to output/rag-trends.md
8. [Complete] 3/3 todos completed. File: output/rag-trends.md
The file output/rag-trends.md lands in your working directory. You open it, review it, use it.
An example with real output
deep-agent "Create a comparison of 3 AI agent frameworks (LangGraph, CrewAI, AutoGen). Include pros, cons, and use cases. Write the result to output/frameworks-comparison.md"
# Expected output (streaming):
# ─── Deep Agent: Research Assistant ───
# [Plan] Creating task breakdown...
# 1. [pending] Search for LangGraph features and use cases
# 2. [pending] Search for CrewAI features and use cases
# 3. [pending] Search for AutoGen features and use cases
# 4. [pending] Compare and analyze frameworks
# 5. [pending] Write comparison report
#
# [Step 1/5] Searching LangGraph...
# ✅ Found 8 relevant sources
# → Saved to research/langgraph.md
#
# [Step 2/5] Searching CrewAI...
# ✅ Found 6 relevant sources
# → Saved to research/crewai.md
#
# [Step 3/5] Searching AutoGen...
# ✅ Found 7 relevant sources
# → Saved to research/autogen.md
#
# [Step 4/5] Analyzing frameworks...
# → Saved to analysis/comparison.md
#
# [Step 5/5] Writing final report...
# → Saved to output/frameworks-comparison.md
#
# ─── Complete ───
# Files generated: 5
# Todos: 5/5 completed
# Total tokens: ~12,400
# Estimated cost: $0.03
Interactive mode: a conversation with the agent
Interactive mode lets you supervise and redirect the agent while it works.
Start interactive mode
deep-agent --interactive
# Expected output:
# ─── Deep Agent Interactive Mode ───
# Type your task, or 'quit' to exit.
#
# > Research the state of AI safety in 2025
#
# [Plan] Creating task breakdown...
# 1. [pending] Define scope of AI safety research
# 2. [pending] Search academic papers
# 3. [pending] Search industry reports
# 4. [pending] Synthesize findings
# 5. [pending] Write report
#
# [Step 1/5] Defining scope...
# → Focus: alignment, governance, technical safety
#
# > Focus more on governance and regulation, less on technical alignment
#
# [Replanning] Adjusting focus...
# 1. [completed] Define scope → UPDATED to governance focus
# 2. [pending] Search EU AI Act and regulations
# 3. [pending] Search US executive orders on AI
# 4. [pending] Search industry self-regulation
# 5. [pending] Synthesize governance landscape
# 6. [pending] Write report
#
# [Step 2/6] Searching EU AI Act...
The key point: you can redirect the research at any moment without restarting. The agent replans dynamically.
Interactive-mode commands
Commands available in interactive mode:
> [text] Send instructions to the agent
> /status Show the current progress of the todos
> /files List the generated files
> /read [path] Show the contents of a generated file
> /cost Show tokens used and estimated cost
> /pause Pause the current run
> /resume Resume the run
> /quit End the session
Example: check progress and read files
# Inside interactive mode:
> /status
# Expected output:
# Todos:
# 1. [completed] Define scope
# 2. [completed] Search EU AI Act
# 3. [in_progress] Search US executive orders
# 4. [pending] Search industry self-regulation
# 5. [pending] Synthesize governance landscape
# 6. [pending] Write report
# Progress: 2/6 (33%)
> /files
# Expected output:
# Files generated:
# research/eu_ai_act.md (2.4 KB)
# research/us_executive.md (1.8 KB)
> /read research/eu_ai_act.md
# Expected output:
# --- research/eu_ai_act.md ---
# # EU AI Act: Key Provisions
#
# ## Classification System
# The EU AI Act categorizes AI systems into risk levels...
# ...
> /cost
# Expected output:
# Tokens used: 8,420 (input: 6,100, output: 2,320)
# Estimated cost: $0.02
# Model: gpt-4.1-mini
Configuration options
Model selection
deep-agent --model openai:gpt-4.1 "Analyze this dataset and generate insights"
deep-agent --model openai:gpt-4.1-mini "Summarize this article"
Use gpt-4.1 for complex tasks that need deep reasoning. Use gpt-4.1-mini for simpler tasks where speed and cost matter more.
Tool permissions
deep-agent --tools web_search,file_write "Research X and write the report"
deep-agent --tools all "Research X, run code, and generate charts"
deep-agent --tools none "Just answer with what you know, no searching"
Memory backend
deep-agent --memory filesystem:./agent_memory "Remember my preferences"
deep-agent --memory postgres:postgresql://user:pass@localhost/db "Remember my preferences"
deep-agent --memory none "Don't remember anything from this session"
Iteration limit
deep-agent --max-iterations 10 "Research topic X exhaustively"
deep-agent --max-iterations 3 "Give me a quick summary of Y"
max-iterations controls how many planning-execution steps the agent can take. More iterations = deeper but more expensive.
Output directory
deep-agent --output-dir ./reports "Generate a report on AI agents"
The agent writes every file inside ./reports/ instead of the current directory.
Combining options
deep-agent \
--model openai:gpt-4.1 \
--tools web_search,file_write \
--memory filesystem:./memory \
--max-iterations 15 \
--output-dir ./research-output \
"Research the impact of LLMs on higher education. Look for academic papers, university reports, and statistical data. Generate a 3-section report with sources."
Shell commands: running system commands
Deep Agents CLI can run system commands as part of its workflow. That's what makes it powerful for development tasks.
Enabling it (with safety controls)
deep-agent --tools shell "List the Python files in src/ and analyze the project structure"
# Expected output:
# [Plan] Creating task breakdown...
# 1. [pending] List Python files in src/
# 2. [pending] Analyze project structure
# 3. [pending] Write analysis
#
# [Step 1/3] Running shell command...
# $ find src/ -name "*.py" -type f
# ✅ Found 23 files
#
# [Step 2/3] Analyzing structure...
# → Project follows domain-driven design
# → 4 main modules: api/, core/, models/, utils/
#
# [Step 3/3] Writing analysis...
# → Saved to output/project-analysis.md
Safety controls
The CLI ships with default restrictions to prevent destructive operations:
Allowed by default:
✅ Reading: ls, cat, head, find, grep, wc
✅ Analysis: python script.py (no destructive flags)
✅ System info: uname, whoami, pwd
Requires confirmation (--shell-confirm):
⚠️ Writing: mkdir, cp, mv
⚠️ Installing: pip install, npm install
⚠️ Git: git add, git commit
Always blocked:
❌ Destructive: rm -rf, drop database
❌ System: sudo, chmod 777
❌ Network: curl with POST, wget
deep-agent --tools shell --shell-confirm "Reorganize the files in src/ by domain"
With --shell-confirm, the agent asks for your approval before running any command that modifies the filesystem.
Practical use cases
1. Research automation
deep-agent \
--tools web_search,file_write \
--output-dir ./research \
"Research the current state of vector databases in 2025. Compare Pinecone, Weaviate, Qdrant, and Chroma. Include: features, pricing, performance benchmarks, and ideal use cases. Generate a detailed report with a comparison table."
Result: a 3-5 page report at ./research/output/report.md with a comparison table, cited sources, and conclusions.
2. Automated code review
deep-agent \
--tools shell,file_write \
--output-dir ./review \
"Review the code in src/api/ and src/models/. Analyze: naming conventions, error handling, type hints, docstrings, and possible bugs. Generate a report with improvement suggestions prioritized by severity."
The agent reads your code, analyzes it, and generates a detailed report without modifying anything.
3. Data analysis
deep-agent \
--tools shell,file_write \
--model openai:gpt-4.1 \
"Analyze the file data/sales_2025.csv. Identify trends, outliers, and correlations. Generate visualizations in output/charts/ and an executive summary in output/analysis.md"
4. Documentation generation
deep-agent \
--tools shell,file_write \
"Read the code in src/ and generate technical documentation. For each module, include: description, main functions, parameters, and usage examples. Write the documentation to docs/"
5. Interview prep
deep-agent \
--tools web_search,file_write \
--memory filesystem:./interview-prep \
"Prepare me for an AI Engineer interview. Research the most common questions in 2025, create 20 questions with model answers, and group them by category: LLMs, agents, RAG, MLOps, system design."
Per-project configuration
The .deep-agent.yaml config file
Instead of passing options on every command, create a config file at the root of the project:
# .deep-agent.yaml
model: openai:gpt-4.1-mini
tools:
- web_search
- file_write
- shell
memory:
backend: filesystem
path: ./.agent_memory
max_iterations: 10
output_dir: ./agent_output
shell:
confirm: true
blocked_commands:
- rm -rf
- drop
- sudo
instructions: |
You are a development assistant for the Atlas project.
The project uses Python 3.12, FastAPI, and PostgreSQL.
Always follow the project conventions in CONTRIBUTING.md.
With that configuration in place, you can run:
deep-agent "Add input validation to the POST /users endpoint"
And the agent already knows the project context, which tools it has, and what the conventions are.
Check the configuration
deep-agent --show-config
# Expected output:
# ─── Configuration ───
# Source: .deep-agent.yaml
# Model: openai:gpt-4.1-mini
# Tools: web_search, file_write, shell
# Memory: filesystem (./.agent_memory)
# Max iterations: 10
# Output dir: ./agent_output
# Shell confirm: true
# Custom instructions: Yes (3 lines)
Custom configuration with prompts
# .deep-agent.yaml for a research project
model: openai:gpt-4.1
tools:
- web_search
- file_write
memory:
backend: filesystem
path: ./.research_memory
max_iterations: 20
output_dir: ./research
instructions: |
You are an academic research assistant.
Prioritize papers from arxiv, ACL, NeurIPS, and ICML.
Always include citations in APA format.
Reports must include: Abstract, Methodology, Findings, Discussion, References.
Monitoring the run in real time
Streaming output
By default, the CLI shows progress in real time:
deep-agent "Research X" --verbose
# Output with --verbose:
# [10:30:01] Starting Deep Agent...
# [10:30:01] Model: gpt-4.1-mini
# [10:30:01] Tools: web_search, file_write
# [10:30:02] [Planning] Analyzing task...
# [10:30:03] [Planning] Created 5 todos
# [10:30:03] [Todo 1] "Define scope" → in_progress
# [10:30:05] [Todo 1] "Define scope" → completed
# [10:30:05] [Tool] web_search("RAG techniques 2025")
# [10:30:08] [Tool] web_search returned 5 results
# [10:30:08] [Filesystem] Writing research/web_results.md (2.1 KB)
# [10:30:08] [Todo 2] "Search academic papers" → completed
# ...
# [10:30:45] [Complete] 5/5 todos completed
# [10:30:45] Files: 4 generated
# [10:30:45] Tokens: 15,230 (cost: ~$0.04)
# [10:30:45] Duration: 43 seconds
Quiet output
deep-agent "Research X" --quiet
# Only shows the final result, with no intermediate progress
Log to a file
deep-agent "Research X" --log ./agent.log
The log captures everything: planning, tool calls, filesystem operations, tokens, and timing. Useful for post-run debugging.
Comparison: hand-built CLI (M6) vs Deep Agents CLI
In Module 6, if you wanted an agent that ran from the terminal, you built the interface yourself:
M6: a CLI built by hand
import argparse
from dotenv import load_dotenv
load_dotenv()
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
from typing import TypedDict, Annotated
import operator
class State(TypedDict):
messages: Annotated[list, operator.add]
query: str
def search_node(state):
query = state["query"]
return {"messages": [{"role": "assistant", "content": f"Results for: {query}"}]}
def report_node(state):
return {"messages": [{"role": "assistant", "content": "Report generated."}]}
builder = StateGraph(State)
builder.add_node("search", search_node)
builder.add_node("report", report_node)
builder.add_edge(START, "search")
builder.add_edge("search", "report")
builder.add_edge("report", END)
graph = builder.compile(checkpointer=MemorySaver())
parser = argparse.ArgumentParser(description="Research Agent CLI")
parser.add_argument("query", help="Research topic")
parser.add_argument("--model", default="gpt-4.1-mini")
parser.add_argument("--max-sources", type=int, default=5)
parser.add_argument("--output", default="output/report.md")
args = parser.parse_args()
result = graph.invoke(
{"messages": [], "query": args.query},
config={"configurable": {"thread_id": "cli-session"}}
)
print(f"Query: {args.query}")
print(f"Model: {args.model}")
print(f"Output: {args.output}")
# Expected output (when run with: python cli.py "AI agents"):
# Query: AI agents
# Model: gpt-4.1-mini
# Output: output/report.md
~40 lines just for the CLI interface, not counting the actual agent.
Deep Agents CLI: zero code
deep-agent --model openai:gpt-4.1-mini --output-dir ./output "AI agents"
One line. The CLI, the planning, the filesystem, the output — all included.
Comparison table
| Aspect | Hand-built CLI (M6) | Deep Agents CLI |
|---|---|---|
| Code for the CLI | ~40 lines (argparse, loop, output) | 0 lines (built-in) |
| Planning | You design it | Automatic (write_todos) |
| Filesystem | You handle the files | Automatic (virtual filesystem) |
| Interactive mode | You build it | --interactive |
| Monitoring | Print statements | --verbose, --log |
| Configuration | Argparse + code | .deep-agent.yaml |
| Customization | Total (it's your code) | Limited to the CLI's options |
| Debugging | You decide what to log | Standardized logging |
The trade-off is the same one as always: convenience vs control. The hand-built CLI gives you exactly the interface you want. Deep Agents CLI gives you a complete interface without writing code.
Troubleshooting
1. deep-agent: command not found
Cause: the package wasn't installed globally, or it isn't on your PATH.
Fix:
pip install deep-agents
# Or, if you use pipx:
pipx install deep-agents
# Check:
which deep-agent
# Expected output: /usr/local/bin/deep-agent or similar
2. The agent never finishes (it's stuck in a loop)
Cause: you didn't set max-iterations and the task is ambiguous.
Fix:
deep-agent --max-iterations 10 "Your task here"
If the agent hits the limit, it stops and hands you whatever it has so far.
3. It can't find the API key
Cause: the environment variable isn't set, or the .env isn't in the current directory.
Fix:
echo $OPENAI_API_KEY
# If it's empty:
export OPENAI_API_KEY=sk-...
# Or check the .env:
cat .env | head -1
# Should show: OPENAI_API_KEY=sk-...
4. Files don't land in the expected directory
Cause: you didn't specify --output-dir, so the agent uses an internal directory.
Fix:
deep-agent --output-dir ./my-directory "Your task"
# The files land in ./my-directory/
5. Interactive mode won't accept input
Cause: you're running in an environment with no TTY (a pipe, a script, CI).
Fix: interactive mode needs a real terminal. For scripts, use direct mode:
# In a script (non-interactive):
deep-agent "Direct task, no interaction"
# For interactive, run it in a real terminal:
deep-agent --interactive
Exercises
Exercise 1: Your first CLI run
Run a simple command with Deep Agents CLI: ask it to research a short topic and write the result to a file. Verify the file was created and holds relevant content.
See solution
deep-agent --output-dir ./ex1 "What are the 3 best practices for prompt engineering in 2025? Write the result to output/best-practices.md"
Check it:
ls ./ex1/output/
# Expected output:
# best-practices.md
cat ./ex1/output/best-practices.md | head -20
# Expected output:
# # Prompt Engineering Best Practices (2025)
#
# ## 1. Structured Prompts
# ...
Exercise 2: Interactive mode with a redirect
Start interactive mode. Ask for research on a topic. Halfway through, redirect the focus. Verify that the agent replanned.
See solution
deep-agent --interactive --output-dir ./ex2
> Research AI agent frameworks in 2025
# Wait for steps 1-2 to complete...
> Focus only on open-source frameworks, ignore enterprise solutions
# Check:
> /status
# It should show an updated plan that filters out enterprise solutions
> /files
# Verify the files reflect the new focus
> /quit
Exercise 3: Per-project configuration
Create a .deep-agent.yaml file for a fictional project. Configure: model, tools, memory, and instructions. Run a task and verify the configuration is applied.
See solution
Create .deep-agent.yaml:
model: openai:gpt-4.1-mini
tools:
- web_search
- file_write
memory:
backend: filesystem
path: ./.agent_memory
max_iterations: 5
output_dir: ./project_output
instructions: |
You are a development assistant for a Python project.
Always suggest code with type hints.
Reports must be concise (500 words max).
Check it and run it:
deep-agent --show-config
# It should show the configuration from the file
deep-agent "What are the best practices for FastAPI in 2025?"
# The report should be concise (<500 words) and mention type hints
Exercise 4: Research automation with structured output
Use the CLI to research 3 related topics, each in its own file. Verify the agent organizes the files correctly.
See solution
deep-agent \
--tools web_search,file_write \
--output-dir ./ex4 \
--max-iterations 15 \
"Research 3 topics: (1) RAG techniques, (2) AI agent architectures, (3) LLM evaluation methods. For each topic, write a summary in a separate file: output/rag.md, output/agents.md, output/evaluation.md. At the end, generate output/summary.md with an executive summary that connects the 3 topics."
Check it:
ls ./ex4/output/
# Expected output:
# rag.md agents.md evaluation.md summary.md
wc -l ./ex4/output/*.md
# Verify each file has substantial content
Exercise 5: Code review with shell
Use the CLI with the shell tool to analyze a code directory and generate a quality report.
See solution
deep-agent \
--tools shell,file_write \
--shell-confirm \
--output-dir ./ex5 \
"Analyze the Python files in the current directory. List every .py file, count the lines of code, identify unused imports if possible, and check whether the public functions have docstrings. Generate a report at output/code-review.md"
--shell-confirm asks for your approval before every shell command. Check it:
cat ./ex5/output/code-review.md
# It should contain: the file list, line counts, observations about quality
Exercise 6: Cost comparison, CLI vs API (Advanced)
Run the same task with the CLI and with the Python API. Compare: tokens used, files generated, and execution time.
See solution
CLI:
time deep-agent \
--model openai:gpt-4.1-mini \
--tools web_search,file_write \
--output-dir ./ex6_cli \
--verbose \
"Research AI agent trends in 2025 and generate a summary"
Python API:
import time
from dotenv import load_dotenv
load_dotenv()
from deep_agents import create_deep_agent
from langchain_community.tools import TavilySearchResults
start = time.time()
agent = create_deep_agent(
"openai:gpt-4.1-mini",
tools=[TavilySearchResults(max_results=3)],
name="assistant",
instructions="Research AI agent trends in 2025 and generate a summary.",
)
result = agent.run("Research AI agent trends in 2025 and generate a summary")
elapsed = time.time() - start
print(f"API - Time: {elapsed:.1f}s")
print(f"API - Files: {len(result.files)}")
print(f"API - Todos completed: {sum(1 for t in result.todos if t['status'] == 'completed')}")
# Expected output (compare with the CLI):
# API - Time: ~35-50s
# API - Files: 3-4
# API - Todos completed: 4-5
The comparison should show that the CLI and the API produce similar results, with the CLI adding minimal overhead for argument parsing and the terminal interface.
Summary
- Deep Agents CLI runs autonomous agents from the terminal — a productivity tool, not a development environment
- Basic usage:
deep-agent "your task"— the agent plans, executes, and hands you files with the results - Interactive mode (
--interactive) lets you supervise and redirect the agent in real time, with commands like/status,/files,/read, and/cost - Configuration options:
--model,--tools,--memory,--max-iterations,--output-dircontrol the behavior from the command line - Shell commands let the agent run system commands with safety controls (
--shell-confirmfor approval, destructive commands blocked) - Per-project configuration via
.deep-agent.yamlremoves the need to pass options on every command - Comparison with M6: building a CLI by hand takes ~40 lines just for the interface. Deep Agents CLI provides all of it with no code, with the trade-off of less customization
Next capsule: the decision tree — create_agent vs LangGraph vs Deep Agents. The most important capsule of the module: a definitive decision framework for picking the right level of abstraction.
Additional resources
- Deep Agents CLI — Documentation — Complete reference for the CLI's commands and options
- Deep Agents Configuration — The
.deep-agent.yamlformat and available options - Click (Python CLI Framework) — If you need to build a custom CLI beyond what Deep Agents provides
- Rich (Terminal Formatting) — Library for formatted terminal output, used internally by Deep Agents CLI
- Autonomous Agent Patterns — Autonomous agent patterns and how the CLI implements them
Module 11 — LangChain & LangGraph: From Chains to Agents