Deep Agents Getting Started Tutorial

Deep Agents is a batteries-included agent development framework officially launched by LangChain, designed specifically for complex tasks, long-running processes, multi-step planning, and multi-agent collaboration scenarios.

Compared to traditional Agents that require developers to manually assemble components such as Prompt, Tool, Memory, and Workflow, Deep Agents has already built in core capabilities such as task planning, filesystem, sub-Agent orchestration, context compression, and memory management, allowing developers to focus more on business logic rather than underlying architecture setup.

This tutorial is designed for developers with zero prior experience. It guides you from installation and configuration through the core working mechanisms of Deep Agents step by step, and uses the DeepSeek API to build a real, runnable AI Agent project.


What are Deep Agents?

Deep Agents can be understood as an advanced Agent framework (Agent Harness) built for production environments.

It is officially defined as: an Agent runtime framework with complete infrastructure, not 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 task execution (Long Running Tasks)
  • Human approval (Human-in-the-Loop)
  • Persistent memory (Memory)
  • Streaming output (Streaming)

Deep Agents' design goals

Traditional Agents typically use the ReAct pattern: user input → LLM reasoning → call tool → LLM reasoning → call tool → output result.

When the task scale is small, this pattern works well. But as task complexity increases (for example, automatically generating market research reports, analyzing financial statements of multiple companies, or writing a complete project codebase), the following problems gradually emerge:

  • The context window quickly expands and exceeds model limits
  • ] Overly long reasoning chains cause performance degradation
  • The Agent easily forgets work completed earlier
  • Lack of isolation between multiple tasks, causing mutual interference
  • Tool calling logic becomes increasingly complex and hard to maintain

The core goal of Deep Agents is to solve these engineering problems in complex task scenarios.

Relationship with LangChain and LangGraph

] Many beginners easily confuse the positioning of these three projects; they actually sit at different abstraction levels.

FrameworkLevel positioningCore responsibilitiesApplicable scenarios
LangChainBase component layer.Provides AI basic components such as Model, Prompt, Tool, Retriever, and Output ParserFoundational capability for building individual Agents or AI applications
LangGraphRuntime layerProvides state management, workflow orchestration, nodes and edges, and Checkpoint persistence capabilitiesFor complex scenarios that require custom graph structures and execution flows
Deep AgentsApplication framework layer.Encapsulates production-grade capabilities on top of LangGraph, such as planning, file system, sub-Agents, memory, and context compressionQuickly build complex multi-step Agents without designing the architecture from scratch

The three are not mutually exclusive but can be used together: LangChain provides building blocks, LangGraph is the engineering framework that organizes the blocks, and Deep Agents is an out-of-the-box high-level application layer on top. Any LangGraphCompiledStateGraphcan be passed into Deep Agents as a subagent, and the three layers can be flexibly mixed.

Core Competencies Overview

Deep Agents comes with the following middleware built in, ready to use with no extra configuration:

CapabilityDescriptionCore Components
Task PlanningUse built-inwrite_todostools to break complex tasks into ordered stepsTodoListMiddleware
Virtual File SystemRead and write files, offload large tool outputs to disk, saving context windowFilesystemMiddleware
Sub-AgentDelegate subtasks to dedicated sub-Agents with independent context windowsSubAgentMiddleware
Context CompressionAutomatically summarize historical messages to avoid exceeding the model context limitSummarizationMiddleware
Human-in-the-loopPause before critical tool calls to wait for human approvalHumanInTheLoopMiddleware
Long-term MemoryCross-session persistent memory based on LangGraph StoreMemoryMiddleware
SkillsLoad reusable domain knowledge and instruction sets on demandSkillsMiddleware

Install

Deep Agents is published on PyPI with the package namedeepagents。

Recommended to useuvinstallation, which is faster; you can also use the traditionalpip。

Install with 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 the OpenAI interface, so you also need to installlangchain-openai。

pip install deepagents langchain-openai

The only requirement Deep Agents has for the model is that the model supportstool calling. DeepSeek V3 and DeepSeek R1 series both support it, so you can use it with confidence.


Configuration Instructions

create_deep_agentIt is the core function for creating an Agent, supporting the following parameter configuration.

ParametersTypeRequiredDescriptionDefault Value
modelstr or model instancenoModel string, in the formatprovider:model-name, or directly pass an initialized model objectanthropic:claude-sonnet-4-6
toolslistnoList of custom tool functions or LangChain Tool objectsNone
system_promptstr or SystemMessagenoCustom system prompt, used to define the Agent's role and behaviorNone
backendBackendProtocolnoVirtual file system backend, determines file storage locationStateBackend
subagentslistnoList of sub-Agent definitions, used for task delegationNone
memorylistnoList of AGENTS.md file paths loaded at startupNone
skillslistnoList of Skills directory paths loaded on demandNone
permissionslistnoAccess permission control rules at the file system path levelNone
interrupt_ondictnoSpecifies which tool calls require manual approval, must be used with checkpointerNone
checkpointerCheckpointernoState persistence checkpointer, must be set for multi-turn conversations or HITLNone
storeBaseStorenoCross-session long-term storage backendNone
response_formatResponseFormatnoSchema definition for structured outputNone
middlewarelistnoCustom middleware appended to the end of the default middleware stack()
debugboolnoEnable debug mode, output detailed logsFalse

File system backend comparison

Deep Agents provides multiple backends to control how the Agent reads and writes files.

BackendStorage LocationCross-session PersistenceApplicable Scenario
StateBackendWithin LangGraph graph stateNo (valid within the same thread)Default, for local development and simple scenarios
FilesystemBackendLocal diskYesRequires real read/write of local files, use with caution
StoreBackendLangGraph StoreYesMulti-turn conversation persistence, cross-Thread sharing
LocalShellBackendLocal disk + ShellYesRequires executing Shell commands, only in trusted environments
CompositeBackendRoutes to multiple backendsDepends on the child backendFine-grained control of storage policies for different directories

For beginners, simply use the defaultStateBackendis sufficient.FilesystemBackendandLocalShellBackendWill let the Agent directly operate on your local file system; strictly configure permissions before use.


Quick Start

This section demonstrates how to create a runnable Deep Agent with minimal code.

Configure DeepSeek API Key

DeepSeek is compatible with OpenAI's API format, and both the API Key and Base URL need 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"

DeepSeek's API Key can beplatform.deepseek.comapplied for. Set the environment variableOPENAI_BASE_URLto point to DeepSeek's address, and LangChain will automatically forward requests there.

TAVILY_API_KEY needs to be applied for on the Tavily official websitehttps://www.tavily.com/ to generate a 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.

example

# File path: hello_agent.py

import os
from deepagents import create_deep_agent
from langchain_openai import ChatOpenAI

# Use ChatOpenAI and set base_url to DeepSeek; this is the most direct way to connect
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; the function's docstring serves as the tool description
def get_weather(city: str) -> str:
    """Query the weather for a specified city."""
    # In a real project, you would call a real weather API here
    return f"{city} is sunny today, 25°C, suitable for going out."

# Create an Agent, passing in the model instance and tool list
agent = create_deep_agent(
    model=model,
    tools=[get_weather],
    system_prompt="You are a friendly assistant who can query weather information.",
)

# Call the Agent; messages accepts OpenAI-style message format
result = agent.invoke({
    "messages": [{"role": "user", "content": "What's the weather like in Beijing today?"}]
})

# Print the Agent's final reply
print(result["messages"][-1].content)
# 运行脚本
python hello_agent.py
Output:

Beijing is **sunny** today, with a temperature of **25°C**, very suitable for going out. ☀️

Note: The Agent returns a full list of messages (messages), and the final reply is at the end of the list, i.e.,result["messages"][-1].content。


Detailed usage

This section uses several real-world scenarios to gradually demonstrate the core capabilities of Deep Agents.

Use 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: 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",
)

# Math Calculation Tool Example
def calculate(expression: str) -> str:
    """Safely evaluate a mathematical expression and return the calculation result."""
    try:
        # Note: A safer expression evaluation library should be used in production environments.
        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 a mathematical analysis expert, 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."}]
})

print(result["messages"][-1].content)

Execution output:

再换一种方法做交叉验证:

- 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 \)

两种方法结果一致。

---

**结论**:1 到 100 的所有奇数之和为 **2500**。

**推导回顾**:
- 奇数序列首项 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_promptThe parameters define the Agent's role, task objectives, and behavioral norms.

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: Define the Agent's identity, responsibilities, and behavioral guidelines.
code_review_instructions = """You are a senior Python engineer, focusing on code review.

Your responsibilities:
- Check code readability, performance, and security
- Point out potential bugs and improvement suggestions
- Provide specific modification examples

Response format:
1. Overall rating (1-10)
2. List of main issues
3. 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:\n```python{code_to_review}```"}]
})

print(result["messages"][-1].content)

Streaming output

For scenarios that require real-time progress display, you can usestreamThe method receives Agent output chunk by chunk.

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 understandable 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:
                print(msg.content, end="", flush=True)

print()  # Final newline

Multi-turn dialogue (with checkpoints)

Together withMemorySavercheckpoints, you can achieve stateful dialogue across turns.

example

# 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  # In-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, which is lost after the process ends.
# It is recommended to use SqliteSaver or PostgresSaver in production
checkpointer = MemorySaver()

agent = create_deep_agent(
    model=model,
    system_prompt="You are a helpful programming assistant.",
    checkpointer=checkpointer,  # Must be passed, otherwise multi-turn conversations cannot remember context
)

# thread_id is the unique identifier of a conversation thread; the same thread_id shares the same context
config = {"configurable": {"thread_id": "example-session-001"}}

# First round
result1 = agent.invoke(
    {"messages": [{"role": "user", "content": "My name is EXAMPLE, and I am learning Python."}]},
    config=config,
)
print("First round reply:", result1["messages"][-1].content)

# Second round: The Agent can remember the previous round's information
result2 = agent.invoke(
    {"messages": [{"role": "user", "content": "What is my name? What am I learning?"}]},
    config=config,
)
print("Second round reply:", result2["messages"][-1].content)
First reply:你好,EXAMPLE!很高兴认识你,Python 是一门非常适合初学者的语言...
Second reply:你叫 EXAMPLE,你正在学习 Python!...

The role of thread_id:The samethread_idAll calls under it share the same conversation history. Differentthread_idare isolated from each other and do not interfere. You can think of it 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.

Scene description

We will build an Agent that receives the user's research topic, automatically breaks down tasks, calls search tools to collect information, and finally outputs a structured report.

Example

# File path: research_agent_demo.py
# Demo: 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 the 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 tools)
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 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 summarized 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:
    """Organize the research content into a Markdown format report.

    Args:
title: Report title
sections: Content of each section, represented as a JSON string, format: {"Chapter 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 fFormatting error: {str(e)}


# ──────────────────────────────────────────
# 3. Define a dedicated sub-agent (information integration expert)
# Sub-agent has an independent context window, avoiding main agent context bloat
# ──────────────────────────────────────────
report_writer_subagent = {
    "name": "report-writer",                        # Required: unique name of sub-agent
    "description": A professional report writing assistant, responsible for integrating research materials into clearly structured reports.,  # Required: The main Agent uses this description to decide when to delegate tasks
    "system_prompt": You are a professional report writing expert. After receiving the research materials, please organize them into a report consisting of three parts: summary, main content, and conclusion, with clear and concise language.,
    "tools": [format_report],                       # Optional: sub-agent-specific tools
    # If no model is specified, inherit 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:
1. Use the web_search tool to search for relevant information (search at least 2-3 times, covering different angles).
2. Organize and summarize the collected data
3. Delegate report-writer sub-agent to write the final report
4. Output the complete report to the user.

Note: Use different keywords for each search to get 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
# ──────────────────────────────────────────
print("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": "example-research-001"}}
)

print("=" * 60)
print("Research Report")
print("=" * 60)
print(result["messages"][-1].content)
正在研究中,请稍候...

============================================================
研究报告
============================================================
# LangGraph 研究报告

## 摘要
LangGraph 是 LangChain 团队推出的一个用于构建有状态、多角色 LLM 应用的框架...

## 主要内容
### 核心概念
LangGraph 将 Agent 的执行流程建模为一张有向图...

### 主要应用场景
1. 多步骤推理任务
2. 人机协作(Human-in-the-loop)工作流
3. 多 Agent 协作系统
...

## 结论
LangGraph 是构建生产级 Agent 应用的重要工具...

Human-in-the-loop example

For sensitive operations (e.g., deleting files, sending emails), the Agent can be configured to pause and wait for manual confirmation before execution.

Example

# File path: hitl_agent.py
# Human-in-the-loop: Let the Agent request human approval before executing 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:
    """Delete the file at the specified path."""
    # In actual projects, os.remove(path) is called here.
    return f"File {path} has been deleted."

@tool
def read_file(path: str) -> str:
    """Read the content of the file at the specified path."""
    return fContent of file {path}: (sample content)

# interrupt_on configures which tools require manual approval
# True means allow: approval, editing parameters, rejection, sending custom replies
# False means no approval required
# dict allows fine-grained control over the allowed operation types
checkpointer = MemorySaver()  # HITL must be used with a checkpointer

agent = create_deep_agent(
    model=model,
    tools=[delete_file, read_file],
    interrupt_on={
        "delete_file": True,   # Delete operation: requires full approval process
        "read_file": False,    # Read operation: no approval required
    },
    checkpointer=checkpointer,
)

config = {"configurable": {"thread_id": "example-hitl-001"}}

# First invocation: Agent pauses when executing delete_file
print("Starting Agent...")
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Please delete the file /tmp/test.txt."}]},
    config=config,
)

# Check if there is a pending approval interrupt
for msg in result.get("messages", []):
    print(fAgent message: {msg.content if hasattr(msg, 'content') else msg})

# Resume execution: pass in the approval decision
# "approve" means approve the execution of the tool
# "reject" means reject; the Agent will not execute the tool
print("\n"User approval: approve the delete operation")
final_result = agent.invoke(
    Command(resume={"decision": "approve"}),
    config=config,
)
print("Final result:", final_result["messages"][-1].content)

How interrupt_on works:When the Agent is about to call a marked tool, LangGraph triggers ainterrupt, the Agent's execution pauses. You canCommand(resume=...)pass in the approval result to resume execution.


Frequently Asked Questions

The following are common questions and considerations when using Deep Agents.

How to decide between using Deep Agents or directly using LangChain/LangGraph?

ScenarioRecommended choiceReason
Need planning, file read/write, sub-agents, context compressionDeep AgentsThese capabilities are out-of-the-box, no need to assemble them yourself
Need lightweight wrapping, just the tool call loopLangChain create_agentLighter than Deep Agents, no built-in middleware
Need a custom graph structure, the loop is not a standard tool call loopLangGraphFully customize the logic of graph nodes and edges
LangGraph CompiledStateGraph as a sub-agentMixed useYou can pass a custom graph as a subagent to Deep Agents

DeepSeek model selection recommendations

Modelmodel stringFeaturesApplicable scenarios
deepseek-v4-flashdeepseek-v4-flashStrong comprehensive capabilities, fast speed, low priceGeneral tasks, daily conversation, writing
deepseek-v4-prodeepseek-v4-proStrong reasoning ability, built-in chain of thoughtMathematics, code, complex logical reasoning

What should be done if the Agent calls a tool and no result is returned?

The return value of a tool function must be a string or a type that can be serialized into a string.

If a tool returns a complex object (such as a dict or list), it is recommended to usejson.dumps(result, ensure_ascii=False)to convert it before returning.

How can the Agent only access specific files at a time?

Usepermissionsparameters to configure file system access permissions, which can precisely control the Agent to only read and write 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 reading and writing the working directory
        FilesystemPermission(path="/secrets/", read=False, write=False),    # Forbid access to sensitive directories
    ],
)

How are the Agent's default system prompt and my prompt merged?

Deep Agents' prompt is assembled from four parts in a fixed order:

USER(your system_prompt) →BASE(SDK default prompt) →SUFFIX(model vendor-specific adjustments)

Your prompt is always at the very front and will not be overwritten. The SDK's default prompt tells the model how to use planning and file tools, so in most cases you do not need to rewrite it yourself.

Mistakes that beginners tend to make.

Common mistake 1:Forgetting to pass incheckpointer. When using Human-in-the-loop (interrupt_on) or multi-turn conversations, youmustpass in a checkpointer, otherwise the state cannot be saved and the Agent will report an error.

Common mistake 2:Tool functions do not have docstrings. Deep Agents uses the function's docstring as the tool description to let the model know when to call the tool. For a tool without a docstring, the model may not know when to call it or may even refuse to use it.

Common mistake 3:Directly modifyingselfattributes in middleware. The Agent's sub-agents and concurrent operations may run simultaneously, and direct modification of middleware instance attributes can lead to race conditions. When state needs to be saved, it should be passed through the graph's state rather than middleware instance variables.


More information

For more content, 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 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 Services) https://platform.deepseek.com
DeepSeek API Documentation https://api-docs.deepseek.com
Other extensions