Deep Agents Getting Started Tutorial
Deep Agents Getting Started Tutorial
Deep Agents is an out-of-the-box (Batteries Included) Agent development framework officially released by LangChain, designed specifically for complex tasks, long-running processes, multi-step planning, and multi-Agent collaboration scenarios.
Compared to traditional Agents, which require developers to manually combine components like Prompts, Tools, Memory, and Workflows, Deep Agents has built-in core capabilities such as task planning, file system access, sub-Agent scheduling, context compression, and memory management, allowing developers to focus more on business logic rather than underlying architecture construction.
This tutorial is aimed at developers with no prior experience, guiding you from installation and configuration to gradually understanding the core working mechanisms of Deep Agents and building a truly runnable AI Agent project using the DeepSeek API.
What are Deep Agents
Deep Agents can be understood as an advanced Agent framework (Agent Harness) oriented towards production environments.
The official definition is: an Agent execution framework with complete infrastructure, rather than just a simple LLM + Tool calling loop.
After installation, you can directly obtain the following capabilities without additional development:
- Automatic Task Planning (Planning)
- Filesystem Read/Write (Filesystem)
- Sub Agent Collaboration (Sub Agents)
- Context Compression and Management (Context Management)
- Long Running Tasks (Long Running Tasks)
- Human Approval (Human-in-the-Loop)
- Persistent Memory (Memory)
- Streaming Output
Design Goals of Deep Agents
Traditional Agents usually adopt the ReAct pattern: User Input -> LLM Inference -> Tool Call -> LLM Inference -> Tool Call -> Output Result.
This pattern works well for small tasks. However, as task complexity increases (e.g., automatically generating market research reports, analyzing multiple company financial reports, writing complete project code), the following problems gradually emerge:
- Context window rapidly expands, exceeding model limits
- Inference chain becomes too long, leading to performance degradation
- Agents are prone to forgetting previously completed work
- Lack of isolation between multiple tasks, leading to mutual interference
- Tool calling logic is becoming increasingly complex and difficult to maintain
The core goal of Deep Agents is to solve engineering problems in these complex task scenarios.
Relationship with LangChain and LangGraph
Many beginners easily confuse the positioning of these three projects; they are actually at different levels of abstraction.
| Framework | Positional hierarchy | Core responsibilities | Applicable scenarios |
|---|---|---|---|
| LangChain | Base Component Layer | Provides AI foundational components such as Model, Prompt, Tool, Retriever, and Output Parser | Provides the basic capabilities to build a single Agent or AI application |
| LangGraph | Runtime Layer | Provides state management, workflow orchestration, node and edge, and Checkpoint persistence capabilities | Complex scenarios requiring custom graph structures and execution flows |
| Deep Agents | Application Framework Layer | Encapsulates production-grade capabilities such as planning, file system, sub-Agents, memory, and context compression on top of LangGraph | Quickly build complex multi-step Agents without designing the architecture from scratch |

The three are not mutually exclusive but can be used synergistically: LangChain provides the building blocks, LangGraph is the engineering framework for organizing the blocks, and Deep Agents is the ready-to-use advanced application layer built on top of it. Any LangGraph
CompiledStateGraphcan be passed as a subagent to Deep Agents, allowing flexible mixing of the three layers.
Overview of Core Capabilities
Deep Agents has the following built-in middleware that can be used without extra configuration:
| Capabilities | Description | Core Components |
|---|---|---|
| Task Planning | Using built-inwrite_todosDecomposes complex tasks into ordered steps |
TodoListMiddleware |
| Virtual File System | Read and write files, offload large tool outputs to disk to save context window | FilesystemMiddleware |
| SubAgent | Delegate subtasks to dedicated sub-Agents with independent context windows | SubAgentMiddleware |
| Context compression | Automatically summarize historical messages to avoid exceeding model context limits | SummarizationMiddleware |
| Human-in-the-loop | Pause before critical tool calls to await manual approval | HumanInTheLoopMiddleware |
| Long-term memory | Cross-session persistent memory, based on LangGraph Store | MemoryMiddleware |
| Skills | On-demand loading of reusable domain knowledge and instruction sets | SkillsMiddleware |
Installation
Deep Agents is published on PyPI with the package name deepagents.
It is recommended to use uv for installation as it is faster; traditional pip can also be used.
Install using uv (recommended)
uv init
uv add deepagents tavily-python
uv sync
Install using pip
pip install deepagents tavily-python
Install with DeepSeek API
DeepSeek is compatible with OpenAI interfaces, so langchain-openai needs to be installed simultaneously.
pip install deepagents langchain-openai
Deep Agents' only requirement for a model is that the model supportstool callingDeepSeek V3 and DeepSeek R1 series both support it, so you can use it with confidence.
Configuration Description
create_deep_agentis the core function for creating Agents and supports the following parameter configurations.
| Parameter | Type | Required | Description | Default value |
|---|---|---|---|---|
model |
str or model instance | No | Model string, in the format ofprovider:model-name, or directly pass an initialized model object |
anthropic:claude-sonnet-4-6 |
tools |
List | No | List of custom tool functions or LangChain Tool objects | None |
system_prompt |
str or SystemMessage | False | Custom system prompt to define Agent role and behavior | None |
backend |
BackendProtocol | False | Virtual file system backend, determines file storage location | StateBackend |
subagents |
List | False | List of child Agents for task delegation | None |
memory |
List | False | List of AGENTS.md file paths loaded at startup | None |
skills |
List | No | List of Skills directory paths loaded on demand | None |
permissions |
List | No | Filesystem path level access control rules | None |
interrupt_on |
dict | No | Specifies which tool calls require manual approval, requires cooperation with checkpointer | None |
checkpointer |
Checkpointer | No | State persistence checkpoint, must be set for multi-turn conversations or HITL | None |
store |
BaseStore | No | Long-term storage backend across sessions | None |
response_format |
ResponseFormat | No | Schema definition for structured output | None |
middleware |
List | False | Custom middleware added to the end of the default middleware stack | () |
debug |
bool | False | Enable debug mode to output detailed logs | False |
Filesystem backend comparison
Deep Agents provides multiple backends to control how Agents read and write files.
| Backend | Storage location | Cross-session persistence | Applicable scenarios |
|---|---|---|---|
| StateBackend | In LangGraph graph state | No (valid within the same thread) | Default, for local development and simple scenarios |
| FilesystemBackend | Local disk | Yes | Requires actual read/write of local files, use with caution |
| StoreBackend | LangGraph Store | Is | Multi-turn conversation persistence, cross-Thread sharing |
| LocalShellBackend | Local disk + Shell | Is | Requires executing Shell commands, limited to trusted environments |
| CompositeBackend | Route to multiple backends | Depending on the sub-backend | Fine-grained control over storage strategies for different directories |
Beginners can use the defaultStateBackenddirectly.FilesystemBackendandLocalShellBackendallows the Agent to directly operate your local file system, and requires strict permission configuration before use.
Quick Start
This section demonstrates how to create a runnable Deep Agent with minimal code.
Configure DeepSeek API Key
DeepSeek uses an interface format compatible with OpenAI, requiring both an API Key and a Base URL to be set.
export OPENAI_API_KEY="sk-your-deepseek-api-key"
export OPENAI_BASE_URL="https://api.deepseek.com"
export TAVILY_API_KEY="your-tavily-api-key"
The DeepSeek API Key can be found atplatform.deepseek.comApply. Point the environment variable
OPENAI_BASE_URLto the DeepSeek address, and LangChain will automatically forward the request.TAVILY_API_KEY needs to be applied for on the official Tavily websitehttps://www.tavily.com/ and the generated key in the tvly-xxxxxxxx format.
Simplest example: Hello World Agent
Create an Agent with a custom tool and send the first message to DeepSeek.
Instance
File path: hello_agent.py
import
os
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
Use ChatOpenAI and point base_url to DeepSeek; this is the most direct way to integrate.
model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
Required: Model name
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
Required: DeepSeek API Key
base_url
=
"https://api.deepseek.com"
,
Required: DeepSeek's OpenAI compatible endpoint
)
Define a simple custom tool, where the function's docstring is the tool description
def
get_weather
(
city:
str
)
str
:
"""Query the weather for a specified city."""
In a real project, this would call a real weather API
return
f
"{city} is sunny today, with a temperature of 25°C, suitable for going out."
Create an Agent by passing the model instance and the list of tools.
agent
=
create_deep_agent
(
model
=
model
,
tools
=
[
get_weather
]
,
system_prompt
=
"You are a friendly assistant that can query weather information."
,
)
Call the Agent, messages accepts OpenAI style message format
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is the weather like in Beijing today?"
}
]
}
)
Print the Agent's final response
(
result
[
"messages"
]
[
1
]
.
content
)
Original prompt (Chinese, left untranslated)
# Run script
python hello_agent.py
Output content:
Beijing todayis sunny**, temperature25°C, very suitable for traveling. ☀️**
Note: Agent returns the complete list of messages (
messages), the final reply is at the end of the list, that isresult["messages"][-1].content.
Detailed Usage
This section demonstrates the core capabilities of Deep Agents through several real-world scenarios.
Using DeepSeek R1 for Reasoning Tasks
DeepSeek R1 is a reasoning-enhanced model suitable for tasks requiring complex analysis.
Example
File Path: reasoning_agent.py
import
os
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
DeepSeek R1: A model designed for complex reasoning
model
=
ChatOpenAI
(
model
=
"deepseek-v4-pro"
,
DeepSeek thinking model
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
)
Mathematical calculation tool example
def
calculate
(
expression:
str
)
str
:
"""Safely evaluates a mathematical expression and returns the result."""
try
:
Note: In production environments, a more secure expression evaluation library should be used
result
=
eval
(
expression
,
{
"builtins"
:
{
}
}
,
{
}
)
return
f
"Calculation result: {expression} = {result}"
except
Exception
as
e:
return
f
Calculation error: {str(e)}
agent
=
create_deep_agent
(
model
=
model
,
tools
=
[
calculate
]
,
system_prompt
=
You are an expert in mathematical analysis, skilled at breaking down complex problems and solving them step by step.
,
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Calculate the sum of all odd numbers from 1 to 100 and verify the result."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
Execution output:
Original prompt (Chinese, left untranslated)
再换一种方法做交叉验证:
- 1 到 100 所有整数之和:\( \frac{100 \times 101}{2} = 5050 \)
- 1 到 100 的偶数之和:\( 2 + 4 + \cdots + 100 = 2 \times \frac{50 \times 51}{2} = 2550 \)
- 奇数之和:\( 5050 - 2550 = 2500 \)
两种方法结果一致。
---
Conclusion: The sum of all odd numbers from 1 to 100 is 2500.
Derivation Review
- 奇数序列首项 1,末项 99,项数 \( \frac{99-1}{2}+1 = 50 \)
- 等差数列求和:\( S = \frac{n(a_1 + a_n)}{2} = \frac{50 \times (1+99)}{2} = 2500 \)
Custom system prompt
Throughsystem_promptparameters, define the Agent's role, task goals, and behavioral specifications.
Example
File path: custom_prompt_agent.py
import
os
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
)
Custom system prompt: Clearly define the Agent's identity, responsibilities, and behavioral guidelines
code_review_instructions
=
"""You are a senior Python engineer specializing in code review.
Your responsibilities:
- Check code readability, performance, and security
- Point out potential bugs and suggestions for improvement
- Provide specific modification examples
Response format:
- Overall score (1-10)
- List of main issues
- Specific improvement suggestions (with modified code snippets)
"""
agent
=
create_deep_agent
(
model
=
model
,
system_prompt
=
code_review_instructions
,
)
Submit a piece of code for review
code_to_review
=
"""
def find_user(users, name):
for i in range(len(users)):
if users[i]['name'] == name:
return users[i]
return None
"""
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: f
"Please review the following code:\npython{code_to_review}"
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
Streaming output
For scenarios that require real-time progress display, you can usestreamthe method to receive Agent output in chunks.
Example
File path: streaming_agent.py
import
os
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
)
agent
=
create_deep_agent
(
model
=
model
,
system_prompt
=
"You are a technical writing expert skilled at writing clear and easy-to-understand technical documentation."
,
)
The stream method returns a generator, yielding one event chunk at a time
for
chunk
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
Write a brief introduction to Python decorators.
}
]
}
)
:
chunk is a dictionary containing incremental messages
if
"messages"
in
chunk
:
for
msg
in
chunk
[
"messages"
]
:
if
hasattr
(
msg
,
"content"
)
and
msg.
content
:
(
msg.
content
,
end
=
""
,
flush
=
True
)
(
)
Final newline
Multi-turn conversation (with checkpoint)
Cooperate withMemorySaverCheckpoint, which can achieve stateful conversation across turns.
Instance
File path: multi_turn_agent.py
import
os
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
from
langgraph.
checkpoint
.
memory
import
MemorySaver
Memory checkpoint, data will be lost after restart
model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
)
MemorySaver saves the conversation state in memory and it is lost after the process ends
In production environments, SqliteSaver or PostgresSaver is recommended
checkpointer
=
MemorySaver
(
)
agent
=
create_deep_agent
(
model
=
model
,
system_prompt
=
"You are a helpful programming assistant."
,
checkpointer
=
checkpointer
,
Must be provided, otherwise multi-turn conversations cannot remember context
)
thread_id is the unique identifier for a conversation thread; the same thread_id shares the same context
config
=
{
"configurable"
:
{
"thread_id"
:
"runoob-session-001"
}
}
First round
result1
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"My name is RUNOOB, and I am learning Python."
}
]
}
,
config
=
config
,
)
(
"First round response:"
,
result1
[
"messages"
]
[
1
]
.
content
)
Second round: Agent can remember information from the previous round
result2
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is my name? What am I learning?"
}
]
}
,
config
=
config
,
)
(
"Second round response:"
,
result2
[
"messages"
]
[
1
]
.
content
)
Original prompt (Chinese, left untranslated)
第一轮回复:你好,RUNOOB!很高兴认识你,Python 是一门非常适合初学者的语言...
第二轮回复:你叫 RUNOOB,你正在学习 Python!...
The role of thread_id:All calls under the same
thread_idshare the same conversation history. Differentthread_idare isolated from each other and do not interfere with each other. This can be understood as a "conversation room number".
Comprehensive Demo: Research Report Agent
This section demonstrates a complete Research Report Agent, using DeepSeek V3 as the main model, integrating custom search tools, and demonstrating the use of sub-Agents.
Scenario Description
We will build an Agent that receives the user's research topic, automatically decomposes the tasks, calls search tools to collect materials, and finally outputs a structured report.
Example
File Path: research_agent_demo.py
Demonstration: Building a Research Report Agent using DeepSeek API + Deep Agents
Dependency installation: pip install deepagents langchain-openai requests
import
os
import
json
from
tavily
import
TavilyClient
from
typing
import
Literal
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
from
langgraph.
checkpoint
.
memory
import
MemorySaver
──────────────────────────────────────────
1. Initialize DeepSeek model
──────────────────────────────────────────
main_model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
Strong comprehensive capabilities, suitable for planning and writing
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
temperature
=
0.3
,
Optional: reduce randomness to make the report more rigorous
)
Initialize the Tavily client (for search tool)
tavily_client
=
TavilyClient
(
api_key
=
os
.
environ
[
"TAVILY_API_KEY"
]
)
──────────────────────────────────────────
2. Define the Tavily search tool
──────────────────────────────────────────
def
web_search
(
query:
str
,
max_results:
int
=
5
,
)
str
:
"""Use Tavily to search for internet information"""
try
:
response
=
tavily_client.
search
(
query
=
query
,
max_results
=
max_results
,
search_depth
=
"advanced"
,
include_answer
=
True
,
include_raw_content
=
False
,
)
lines
=
[
]
AI summary answer
if
response.
get
(
"answer"
)
:
lines.
append
(
f
"Summary: {response['answer']}\n"
)
Search results
for
idx
,
item
in
enumerate
(
response.
get
(
"results"
,
[
]
)
,
start
=
1
)
:
lines.
append
(
f
"""
[{idx}] {item.get('title', '')}
URL: {item.get('url', '')}
Content: {item.get('content', '')}
"""
.
strip
(
)
)
return
"\n\n"
.
join
(
lines
)
def
format_report
(
title:
str
,
sections:
str
)
str
:
"""Organizes research content into a Markdown formatted report.
Args:
title: Report title
sections: Content of each section, represented as a JSON string, format: {"Section Name": "Content"}
"""
try
:
data
=
json.
loads
(
sections
)
lines
=
[
f
"# {title}\n"
]
for
section_name
,
content
in
data.
items
(
)
:
lines.
append
(
f
"## {section_name}\n"
)
lines.
append
(
f
"{content}\n"
)
return
"\n"
.
join
(
lines
)
except
Exception
as
e:
return
f
"Formatting error: {str(e)}"
──────────────────────────────────────────
3. Define a dedicated sub-Agent (Information Integration Expert)
The sub-Agent has an independent context window, preventing the main Agent's context from bloating
──────────────────────────────────────────
report_writer_subagent
=
{
"name"
:
"report-writer"
,
Required: Unique name of the sub-Agent
"description"
:
"A professional report writing assistant responsible for integrating research materials into a clearly structured report."
,
Required: The main Agent uses this description to decide when to delegate tasks
"system_prompt"
:
"You are a professional report writing expert. After receiving research materials, please organize them into a report consisting of three parts: abstract, main content, and conclusion, using concise and clear language."
,
"tools"
:
[
format_report
]
,
Optional: Dedicated tools for sub-Agents
If model is not specified, it inherits the main Agent's model
}
──────────────────────────────────────────
4. Configure and create Deep Agent
──────────────────────────────────────────
checkpointer
=
MemorySaver
(
)
research_instructions
=
"""You are a professional research assistant skilled in in-depth research and report writing.
When the user provides a research topic, you should:
- Use the web_search tool to search for relevant information (search at least 2-3 times, covering different angles)
- Organize and summarize the collected materials
- Delegate the report-writer sub-Agent to write the final report
- Output the complete report to the user
Note: Use different keywords for each search to obtain more comprehensive information.
"""
agent
=
create_deep_agent
(
model
=
main_model
,
tools
=
[
web_search
]
,
Tools available to the main Agent
system_prompt
=
research_instructions
,
subagents
=
[
report_writer_subagent
]
,
Register sub Agent
checkpointer
=
checkpointer
,
)
──────────────────────────────────────────
5. Run Agent
──────────────────────────────────────────
(
"Researching, please wait...\n"
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please help me research what LangGraph is and its main application scenarios."
}
]
}
,
config
=
{
"configurable"
:
{
"thread_id"
:
"runoob-research-001"
}
}
)
(
"="
60
)
(
"Research Report"
)
(
"="
60
)
(
result
[
"messages"
]
[
1
]
.
content
)
Original prompt (Chinese, left untranslated)
正在研究中,请稍候...
============================================================
研究报告
============================================================
# LangGraph research report
## 摘要
LangGraph 是 LangChain 团队推出的一个用于构建有状态、多角色 LLM 应用的框架...
## Main Content
### 核心概念
LangGraph 将 Agent 的执行流程建模为一张有向图...
### Key Use Cases
1. 多步骤推理任务
2. 人机协作(Human-in-the-loop)工作流
3. 多 Agent 协作系统
...
## 结论
LangGraph 是构建生产级 Agent 应用的重要工具...
Human-in-the-loop example
For sensitive operations (e.g., deleting files, sending emails), you can configure the Agent to pause and wait for human confirmation before execution.
Instance
File path: hitl_agent.py
Human-in-the-loop: Requesting human approval before the Agent performs dangerous operations
import
os
from
langchain.
tools
import
tool
from
deepagents
import
create_deep_agent
from
langchain_openai
import
ChatOpenAI
from
langgraph.
checkpoint
.
memory
import
MemorySaver
from
langgraph.
types
import
Command
model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
)
Use the @tool decorator to define tools (requires the langchain package)
@
tool
def
delete_file
(
path:
str
)
str
:
"""Deletes the file at the specified path."""
In a real project, os.remove(path) would be called here
return
f
"File {path} has been deleted."
@
tool
def
read_file
(
path:
str
)
str
:
"""Reads the content of a file at the specified path."""
return
f
Content of file {path}: (Example content)
interrupt_on configures which tools require manual approval
True means allow: approval, parameter editing, rejection, sending custom replies
False means no approval is needed
dict can finely control the allowed operation types
checkpointer
=
MemorySaver
(
)
HITL must be used with checkpointer
agent
=
create_deep_agent
(
model
=
model
,
tools
=
[
delete_file
,
read_file
]
,
interrupt_on
=
{
"delete_file"
:
True
,
Delete operation: requires a complete approval process
"read_file"
:
False
,
Read operation: no approval required
}
,
checkpointer
=
checkpointer
,
)
config
=
{
"configurable"
:
{
"thread_id"
:
"runoob-hitl-001"
}
}
First call: Agent pauses when executing delete_file
(
"Starting Agent..."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please delete the /tmp/test.txt file."
}
]
}
,
config
=
config
,
)
Check for pending interruptions
for
msg
in
result.
get
(
"messages"
,
[
]
)
:
(
f
"Agent message: {msg.content if hasattr(msg, 'content') else msg}"
)
Resume execution: pass the approval decision
"approve" means to approve the execution of this tool
"reject" means to reject, and the Agent will not execute this tool
(
User approval: Approve delete operation
)
final_result
=
agent.
invoke
(
Command
(
resume
=
{
"decision"
:
"approve"
}
)
,
config
=
config
,
)
(
"Final result:"
,
final_result
[
"messages"
]
[
1
]
.
content
)
How interrupt_on works:When the Agent is about to call the marked tool, LangGraph triggers an
interrupt, and the Agent's execution is paused. You can do this byCommand(resume=...)Pass the approval result to resume execution.
FAQ
Here are common questions and notes when using Deep Agents.
How to decide whether to use Deep Agents or directly use LangChain/LangGraph?
| Scenario | Recommended choice | Reason |
|---|---|---|
| Requires planning, file read/write, sub-Agents, context compression | Deep Agents | These capabilities are ready to use without self-assembly |
| Requires lightweight encapsulation, only a tool-calling loop | LangChain create_agent | Lighter than Deep Agents, no built-in middleware |
| Requires custom graph structure, the loop is not a standard tool-calling loop | LangGraph | Fully customizable graph node and edge logic |
| LangGraph CompiledStateGraph as a sub Agent | Mixed use | Custom graphs can be passed as subagents to Deep Agents |
DeepSeek model selection recommendations
| Model | model string | Features | Applicable scenarios |
|---|---|---|---|
| deepseek-v4-flash | deepseek-v4-flash |
Strong comprehensive capabilities, fast speed, low price | General tasks, daily conversations, writing |
| deepseek-v4-pro | deepseek-v4-pro |
Strong reasoning ability, built-in chain-of-thought | Mathematics, code, complex logical reasoning |
What if the Agent does not return a result after calling a tool?
The return value of a tool function must be a string or a type that can be serialized to a string.
If the tool returns a complex object (such as a dictionary or a list), it is recommended tojson.dumps(result, ensure_ascii=False)convert it before returning.
How can I make the Agent access only specific files at a time?
Usepermissionsthe parameter configuration file system access permissions to precisely control that the Agent can only read and write to specified paths.
Example
from
deepagents
import
create_deep_agent
from
deepagents.
permissions
import
FilesystemPermission
from
langchain_openai
import
ChatOpenAI
import
os
model
=
ChatOpenAI
(
model
=
"deepseek-v4-flash"
,
api_key
=
os
.
environ
[
"OPENAI_API_KEY"
]
,
base_url
=
"https://api.deepseek.com"
,
)
agent
=
create_deep_agent
(
model
=
model
,
permissions
=
[
FilesystemPermission
(
path
=
"/workspace/"
,
read
=
True
,
write
=
True
)
,
Allow read and write to the working directory
FilesystemPermission
(
path
=
"/secrets/"
,
read
=
False
,
write
=
False
)
,
Prohibit access to sensitive directories
]
,
)
How are the Agent's default system prompt and my prompt merged?
The prompts for Deep Agents are concatenated in a fixed order of four parts:
USER (your system_prompt) $\rightarrow$ BASE (SDK default prompt) $\rightarrow$ SUFFIX (model vendor specific adjustments)
Your prompt is always at the very beginning and will not be overwritten. The SDK's default prompt tells the model how to use planning and file tools, so you usually do not need to rewrite it yourself.
Common mistakes for beginners
Common mistake 1:Forgetting to pass
checkpointerWhen using Human-in-the-loop (interrupt_on) or multi-turn conversations,you mustpass the checkpointer, otherwise the state cannot be saved, and the Agent will report an error.
Common mistake 2:Tool functions are missing docstrings. Deep Agents use function docstrings as tool descriptions to let the model know when to call the tool. Tools without docstrings might be unknown to the model or the model might refuse to use them.
Common Error 3:Directly modifying
selfproperties in the middleware. The Agent's sub-Agents and concurrent operations may run simultaneously, and direct modification of middleware instance properties can lead to a race condition. When saving state, it should be passed through the graph's state, not middleware instance variables.
More information
For more content, please refer to the following documentation:
| Name | Address |
|---|---|
| Deep Agents Official Documentation (Homepage) | https://docs.langchain.com/deepagents |
| Deep Agents GitHub Repository (Source Code) | https://github.com/langchain-ai/deepagents |
| Deep Agents Python Documentation (Python Development Guide) | https://docs.langchain.com/oss/python/deepagents/overview |
| Deep Agents JavaScript Documentation (JS/TS Development Guide) | https://docs.langchain.com/oss/javascript/deepagents/overview |
| Deep Agents Python API Reference Manual | https://reference.langchain.com/python/deepagents/deepagents |
| Deep Agents JavaScript API Reference Manual | https://reference.langchain.com/javascript/modules/deepagents.html |
| LangChain Official Documentation (Basic Component Library) | https://docs.langchain.com/langchain |
| LangGraph Official Documentation (Agent Runtime) | https://docs.langchain.com/langgraph |
| LangGraph GitHub repository (source code) | https://github.com/langchain-ai/langgraph |
| LangChain GitHub repository (source code) | https://github.com/langchain-ai/langchain |
| LangSmith official website (Agent debugging and monitoring) | https://www.langchain.com/langsmith |
| LangSmith official documentation | https://docs.smith.langchain.com |
| Tavily official website (search tool) | https://tavily.com |
| Tavily API documentation | https://docs.tavily.com |
| DeepSeek open platform (model service) | https://platform.deepseek.com |
| DeepSeek API documentation | https://api-docs.deepseek.com |