deepagents 0.0.5rc4__tar.gz → 0.0.6rc2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deepagents
3
- Version: 0.0.5rc4
3
+ Version: 0.0.6rc2
4
4
  Summary: General purpose 'deep agent' with sub-agent spawning, todo list capabilities, and mock file system. Built on LangGraph.
5
5
  License: MIT
6
6
  Requires-Python: <4.0,>=3.11
@@ -115,15 +115,26 @@ class SubAgent(TypedDict):
115
115
  prompt: str
116
116
  tools: NotRequired[list[str]]
117
117
  model_settings: NotRequired[dict[str, Any]]
118
+
119
+ class CustomSubAgent(TypedDict):
120
+ name: str
121
+ description: str
122
+ graph: Runnable
118
123
  ```
119
124
 
125
+ **SubAgent fields:**
120
126
  - **name**: This is the name of the subagent, and how the main agent will call the subagent
121
127
  - **description**: This is the description of the subagent that is shown to the main agent
122
128
  - **prompt**: This is the prompt used for the subagent
123
129
  - **tools**: This is the list of tools that the subagent has access to. By default will have access to all tools passed in, as well as all built-in tools.
124
130
  - **model_settings**: Optional dictionary for per-subagent model configuration (inherits the main model when omitted).
125
131
 
126
- To use it looks like:
132
+ **CustomSubAgent fields:**
133
+ - **name**: This is the name of the subagent, and how the main agent will call the subagent
134
+ - **description**: This is the description of the subagent that is shown to the main agent
135
+ - **graph**: A pre-built LangGraph graph/agent that will be used as the subagent
136
+
137
+ #### Using SubAgent
127
138
 
128
139
  ```python
129
140
  research_subagent = {
@@ -139,6 +150,35 @@ agent = create_deep_agent(
139
150
  )
140
151
  ```
141
152
 
153
+ #### Using CustomSubAgent
154
+
155
+ For more complex use cases, you can provide your own pre-built LangGraph graph as a subagent:
156
+
157
+ ```python
158
+ from langgraph.prebuilt import create_react_agent
159
+
160
+ # Create a custom agent graph
161
+ custom_graph = create_react_agent(
162
+ model=your_model,
163
+ tools=specialized_tools,
164
+ prompt="You are a specialized agent for data analysis..."
165
+ )
166
+
167
+ # Use it as a custom subagent
168
+ custom_subagent = {
169
+ "name": "data-analyzer",
170
+ "description": "Specialized agent for complex data analysis tasks",
171
+ "graph": custom_graph
172
+ }
173
+
174
+ subagents = [custom_subagent]
175
+ agent = create_deep_agent(
176
+ tools,
177
+ prompt,
178
+ subagents=subagents
179
+ )
180
+ ```
181
+
142
182
  ### `model` (Optional)
143
183
 
144
184
  By default, `deepagents` uses `"claude-sonnet-4-20250514"`. You can customize this by passing any [LangChain model object](https://python.langchain.com/docs/integrations/chat/).
@@ -102,15 +102,26 @@ class SubAgent(TypedDict):
102
102
  prompt: str
103
103
  tools: NotRequired[list[str]]
104
104
  model_settings: NotRequired[dict[str, Any]]
105
+
106
+ class CustomSubAgent(TypedDict):
107
+ name: str
108
+ description: str
109
+ graph: Runnable
105
110
  ```
106
111
 
112
+ **SubAgent fields:**
107
113
  - **name**: This is the name of the subagent, and how the main agent will call the subagent
108
114
  - **description**: This is the description of the subagent that is shown to the main agent
109
115
  - **prompt**: This is the prompt used for the subagent
110
116
  - **tools**: This is the list of tools that the subagent has access to. By default will have access to all tools passed in, as well as all built-in tools.
111
117
  - **model_settings**: Optional dictionary for per-subagent model configuration (inherits the main model when omitted).
112
118
 
113
- To use it looks like:
119
+ **CustomSubAgent fields:**
120
+ - **name**: This is the name of the subagent, and how the main agent will call the subagent
121
+ - **description**: This is the description of the subagent that is shown to the main agent
122
+ - **graph**: A pre-built LangGraph graph/agent that will be used as the subagent
123
+
124
+ #### Using SubAgent
114
125
 
115
126
  ```python
116
127
  research_subagent = {
@@ -126,6 +137,35 @@ agent = create_deep_agent(
126
137
  )
127
138
  ```
128
139
 
140
+ #### Using CustomSubAgent
141
+
142
+ For more complex use cases, you can provide your own pre-built LangGraph graph as a subagent:
143
+
144
+ ```python
145
+ from langgraph.prebuilt import create_react_agent
146
+
147
+ # Create a custom agent graph
148
+ custom_graph = create_react_agent(
149
+ model=your_model,
150
+ tools=specialized_tools,
151
+ prompt="You are a specialized agent for data analysis..."
152
+ )
153
+
154
+ # Use it as a custom subagent
155
+ custom_subagent = {
156
+ "name": "data-analyzer",
157
+ "description": "Specialized agent for complex data analysis tasks",
158
+ "graph": custom_graph
159
+ }
160
+
161
+ subagents = [custom_subagent]
162
+ agent = create_deep_agent(
163
+ tools,
164
+ prompt,
165
+ subagents=subagents
166
+ )
167
+ ```
168
+
129
169
  ### `model` (Optional)
130
170
 
131
171
  By default, `deepagents` uses `"claude-sonnet-4-20250514"`. You can customize this by passing any [LangChain model object](https://python.langchain.com/docs/integrations/chat/).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deepagents
3
- Version: 0.0.5rc4
3
+ Version: 0.0.6rc2
4
4
  Summary: General purpose 'deep agent' with sub-agent spawning, todo list capabilities, and mock file system. Built on LangGraph.
5
5
  License: MIT
6
6
  Requires-Python: <4.0,>=3.11
@@ -115,15 +115,26 @@ class SubAgent(TypedDict):
115
115
  prompt: str
116
116
  tools: NotRequired[list[str]]
117
117
  model_settings: NotRequired[dict[str, Any]]
118
+
119
+ class CustomSubAgent(TypedDict):
120
+ name: str
121
+ description: str
122
+ graph: Runnable
118
123
  ```
119
124
 
125
+ **SubAgent fields:**
120
126
  - **name**: This is the name of the subagent, and how the main agent will call the subagent
121
127
  - **description**: This is the description of the subagent that is shown to the main agent
122
128
  - **prompt**: This is the prompt used for the subagent
123
129
  - **tools**: This is the list of tools that the subagent has access to. By default will have access to all tools passed in, as well as all built-in tools.
124
130
  - **model_settings**: Optional dictionary for per-subagent model configuration (inherits the main model when omitted).
125
131
 
126
- To use it looks like:
132
+ **CustomSubAgent fields:**
133
+ - **name**: This is the name of the subagent, and how the main agent will call the subagent
134
+ - **description**: This is the description of the subagent that is shown to the main agent
135
+ - **graph**: A pre-built LangGraph graph/agent that will be used as the subagent
136
+
137
+ #### Using SubAgent
127
138
 
128
139
  ```python
129
140
  research_subagent = {
@@ -139,6 +150,35 @@ agent = create_deep_agent(
139
150
  )
140
151
  ```
141
152
 
153
+ #### Using CustomSubAgent
154
+
155
+ For more complex use cases, you can provide your own pre-built LangGraph graph as a subagent:
156
+
157
+ ```python
158
+ from langgraph.prebuilt import create_react_agent
159
+
160
+ # Create a custom agent graph
161
+ custom_graph = create_react_agent(
162
+ model=your_model,
163
+ tools=specialized_tools,
164
+ prompt="You are a specialized agent for data analysis..."
165
+ )
166
+
167
+ # Use it as a custom subagent
168
+ custom_subagent = {
169
+ "name": "data-analyzer",
170
+ "description": "Specialized agent for complex data analysis tasks",
171
+ "graph": custom_graph
172
+ }
173
+
174
+ subagents = [custom_subagent]
175
+ agent = create_deep_agent(
176
+ tools,
177
+ prompt,
178
+ subagents=subagents
179
+ )
180
+ ```
181
+
142
182
  ### `model` (Optional)
143
183
 
144
184
  By default, `deepagents` uses `"claude-sonnet-4-20250514"`. You can customize this by passing any [LangChain model object](https://python.langchain.com/docs/integrations/chat/).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "deepagents"
3
- version = "0.0.5rc4"
3
+ version = "0.0.6rc2"
4
4
  description = "General purpose 'deep agent' with sub-agent spawning, todo list capabilities, and mock file system. Built on LangGraph."
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
@@ -1,4 +1,9 @@
1
- from deepagents.sub_agent import _create_task_tool, _create_sync_task_tool, SubAgent
1
+ from deepagents.sub_agent import (
2
+ _create_task_tool,
3
+ _create_sync_task_tool,
4
+ SubAgent,
5
+ CustomSubAgent,
6
+ )
2
7
  from deepagents.model import get_default_model
3
8
  from deepagents.tools import write_todos, write_file, read_file, ls, edit_file
4
9
  from deepagents.state import DeepAgentState
@@ -8,37 +13,27 @@ from langchain_core.language_models import LanguageModelLike
8
13
  from deepagents.interrupt import create_interrupt_hook, ToolInterruptConfig
9
14
  from langgraph.types import Checkpointer
10
15
  from langgraph.prebuilt import create_react_agent
16
+ from deepagents.prompts import BASE_AGENT_PROMPT
11
17
 
12
18
  StateSchema = TypeVar("StateSchema", bound=DeepAgentState)
13
19
  StateSchemaType = Type[StateSchema]
14
20
 
15
- base_prompt = """You have access to a number of standard tools
16
-
17
- ## `write_todos`
18
-
19
- You have access to the `write_todos` tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
20
- These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
21
-
22
- It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
23
- ## `task`
24
-
25
- - When doing web search, prefer to use the `task` tool in order to reduce context usage."""
26
-
27
21
 
28
22
  def _agent_builder(
29
23
  tools: Sequence[Union[BaseTool, Callable, dict[str, Any]]],
30
24
  instructions: str,
31
25
  model: Optional[Union[str, LanguageModelLike]] = None,
32
- subagents: list[SubAgent] = None,
26
+ subagents: list[SubAgent | CustomSubAgent] = None,
33
27
  state_schema: Optional[StateSchemaType] = None,
34
28
  builtin_tools: Optional[list[str]] = None,
35
29
  interrupt_config: Optional[ToolInterruptConfig] = None,
36
30
  config_schema: Optional[Type[Any]] = None,
37
31
  checkpointer: Optional[Checkpointer] = None,
38
32
  post_model_hook: Optional[Callable] = None,
33
+ main_agent_tools: Optional[list[str]] = None,
39
34
  is_async: bool = False,
40
35
  ):
41
- prompt = instructions + base_prompt
36
+ prompt = instructions + BASE_AGENT_PROMPT
42
37
 
43
38
  all_builtin_tools = [write_todos, write_file, read_file, ls, edit_file]
44
39
 
@@ -56,7 +51,7 @@ def _agent_builder(
56
51
  if model is None:
57
52
  model = get_default_model()
58
53
  state_schema = state_schema or DeepAgentState
59
-
54
+
60
55
  # Should never be the case that both are specified
61
56
  if post_model_hook and interrupt_config:
62
57
  raise ValueError(
@@ -69,7 +64,7 @@ def _agent_builder(
69
64
  selected_post_model_hook = create_interrupt_hook(interrupt_config)
70
65
  else:
71
66
  selected_post_model_hook = None
72
-
67
+
73
68
  if not is_async:
74
69
  task_tool = _create_sync_task_tool(
75
70
  list(tools) + built_in_tools,
@@ -88,7 +83,16 @@ def _agent_builder(
88
83
  state_schema,
89
84
  selected_post_model_hook,
90
85
  )
91
- all_tools = built_in_tools + list(tools) + [task_tool]
86
+ if main_agent_tools is not None:
87
+ passed_in_tools = []
88
+ for tool_ in tools:
89
+ if not isinstance(tool_, BaseTool):
90
+ tool_ = tool(tool_)
91
+ if tool_.name in main_agent_tools:
92
+ passed_in_tools.append(tool_)
93
+ else:
94
+ passed_in_tools = list(tools)
95
+ all_tools = built_in_tools + passed_in_tools + [task_tool]
92
96
 
93
97
  return create_react_agent(
94
98
  model,
@@ -105,13 +109,14 @@ def create_deep_agent(
105
109
  tools: Sequence[Union[BaseTool, Callable, dict[str, Any]]],
106
110
  instructions: str,
107
111
  model: Optional[Union[str, LanguageModelLike]] = None,
108
- subagents: list[SubAgent] = None,
112
+ subagents: list[SubAgent | CustomSubAgent] = None,
109
113
  state_schema: Optional[StateSchemaType] = None,
110
114
  builtin_tools: Optional[list[str]] = None,
111
115
  interrupt_config: Optional[ToolInterruptConfig] = None,
112
116
  config_schema: Optional[Type[Any]] = None,
113
117
  checkpointer: Optional[Checkpointer] = None,
114
118
  post_model_hook: Optional[Callable] = None,
119
+ main_agent_tools: Optional[list[str]] = None,
115
120
  ):
116
121
  """Create a deep agent.
117
122
 
@@ -137,6 +142,9 @@ def create_deep_agent(
137
142
  config_schema: The schema of the deep agent.
138
143
  post_model_hook: Custom post model hook
139
144
  checkpointer: Optional checkpointer for persisting agent state between runs.
145
+ main_agent_tools: Optional list of tool names that the main agent should have. If not provided,
146
+ will have access to all tools. Note that built-in tools (for filesystem and todo and subagents) are
147
+ always included - this filtering only applies to passed in tools.
140
148
  """
141
149
  return _agent_builder(
142
150
  tools=tools,
@@ -149,6 +157,7 @@ def create_deep_agent(
149
157
  config_schema=config_schema,
150
158
  checkpointer=checkpointer,
151
159
  post_model_hook=post_model_hook,
160
+ main_agent_tools=main_agent_tools,
152
161
  is_async=False,
153
162
  )
154
163
 
@@ -157,13 +166,14 @@ def async_create_deep_agent(
157
166
  tools: Sequence[Union[BaseTool, Callable, dict[str, Any]]],
158
167
  instructions: str,
159
168
  model: Optional[Union[str, LanguageModelLike]] = None,
160
- subagents: list[SubAgent] = None,
169
+ subagents: list[SubAgent | CustomSubAgent] = None,
161
170
  state_schema: Optional[StateSchemaType] = None,
162
171
  builtin_tools: Optional[list[str]] = None,
163
172
  interrupt_config: Optional[ToolInterruptConfig] = None,
164
173
  config_schema: Optional[Type[Any]] = None,
165
174
  checkpointer: Optional[Checkpointer] = None,
166
175
  post_model_hook: Optional[Callable] = None,
176
+ main_agent_tools: Optional[list[str]] = None,
167
177
  ):
168
178
  """Create a deep agent.
169
179
 
@@ -189,6 +199,9 @@ def async_create_deep_agent(
189
199
  config_schema: The schema of the deep agent.
190
200
  post_model_hook: Custom post model hook
191
201
  checkpointer: Optional checkpointer for persisting agent state between runs.
202
+ main_agent_tools: Optional list of tool names that the main agent should have. If not provided,
203
+ will have access to all tools. Note that built-in tools (for filesystem and todo and subagents) are
204
+ always included - this filtering only applies to passed in tools.
192
205
  """
193
206
  return _agent_builder(
194
207
  tools=tools,
@@ -201,5 +214,6 @@ def async_create_deep_agent(
201
214
  config_schema=config_schema,
202
215
  checkpointer=checkpointer,
203
216
  post_model_hook=post_model_hook,
217
+ main_agent_tools=main_agent_tools,
204
218
  is_async=True,
205
219
  )
@@ -19,7 +19,8 @@ def create_interrupt_hook(
19
19
  """Create a post model hook that handles interrupts using native LangGraph schemas.
20
20
 
21
21
  Args:
22
- tool_configs: Dict mapping tool names to HumanInterruptConfig objects
22
+ tool_configs: Dict mapping tool names to HumanInterruptConfig objects or boolean values.
23
+ If True, uses default HumanInterruptConfig. If False, no interrupt.
23
24
  message_prefix: Optional message prefix for interrupt descriptions
24
25
  """
25
26
  # Right now we don't properly handle `ignore`
@@ -47,7 +48,7 @@ def create_interrupt_hook(
47
48
 
48
49
  for tool_call in last_message.tool_calls:
49
50
  tool_name = tool_call["name"]
50
- if tool_name in tool_configs:
51
+ if tool_name in tool_configs and tool_configs[tool_name]:
51
52
  interrupt_tool_calls.append(tool_call)
52
53
  else:
53
54
  auto_approved_tool_calls.append(tool_call)
@@ -1,27 +1,29 @@
1
- WRITE_TODOS_DESCRIPTION = """Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
1
+ WRITE_TODOS_TOOL_DESCRIPTION = """Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
2
2
  It also helps the user understand the progress of the task and overall progress of their requests.
3
+ Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
3
4
 
4
5
  ## When to Use This Tool
5
- Use this tool proactively in these scenarios:
6
+ Use this tool in these scenarios:
6
7
 
7
8
  1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
8
9
  2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
9
10
  3. User explicitly requests todo list - When the user directly asks you to use the todo list
10
11
  4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
11
- 5. After receiving new instructions - Immediately capture user requirements as todos
12
- 6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
13
- 7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
12
+ 5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.
14
13
 
15
- ## When NOT to Use This Tool
14
+ ## How to Use This Tool
15
+ 1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
16
+ 2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
17
+ 3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.
18
+ 4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.
16
19
 
17
- Skip using this tool when:
20
+ ## When NOT to Use This Tool
21
+ It is important to skip using this tool when:
18
22
  1. There is only a single, straightforward task
19
- 2. The task is trivial and tracking it provides no organizational benefit
23
+ 2. The task is trivial and tracking it provides no benefit
20
24
  3. The task can be completed in less than 3 trivial steps
21
25
  4. The task is purely conversational or informational
22
26
 
23
- NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
24
-
25
27
  ## Examples of When to Use the Todo List
26
28
 
27
29
  <example>
@@ -37,9 +39,9 @@ Assistant: I'll help add a dark mode toggle to your application settings. Let me
37
39
 
38
40
  <reasoning>
39
41
  The assistant used the todo list because:
40
- 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
41
- 2. The user explicitly requested tests and build be run afterward
42
- 3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
42
+ 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
43
+ 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
44
+ 3. Both of the user's requests are complex and require multiple steps to complete.
43
45
  </reasoning>
44
46
  </example>
45
47
 
@@ -61,7 +63,6 @@ The assistant used the todo list because:
61
63
  1. Marketing campaign planning involves multiple distinct channels and activities
62
64
  2. Each component requires careful coordination and planning
63
65
  3. The systematic approach ensures all aspects of the launch are covered
64
- 4. Progress tracking helps maintain timeline and deliverables
65
66
  </reasoning>
66
67
  </example>
67
68
 
@@ -74,10 +75,10 @@ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me
74
75
 
75
76
  <reasoning>
76
77
  The assistant used the todo list because:
77
- 1. First, the assistant searched to understand the scope of the task
78
- 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
78
+ 1. The assistant searched to understand the scope of the task
79
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
79
80
  3. The todo list helps ensure every instance is tracked and updated systematically
80
- 4. This approach prevents missing any occurrences and maintains consistency
81
+ 4. This approach prevents missing any occurrences and maintains consistency.
81
82
  </reasoning>
82
83
  </example>
83
84
 
@@ -151,19 +152,45 @@ The assistant did not use the todo list because this is a single information loo
151
152
  </reasoning>
152
153
  </example>
153
154
 
155
+ <example>
156
+ User: I need to write a function that checks if a number is prime and then test it out.
157
+ Assistant: I'll help you write a function that checks if a number is prime and then test it out.
158
+ *Writes function that checks if a number is prime*
159
+ *Tests the function*
160
+
161
+ <reasoning>
162
+ Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.
163
+ </reasoning>
164
+ </example>
165
+
166
+ <example>
167
+ User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
168
+ Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
169
+ *Orders a pizza from Dominos*
170
+ *Orders a burger from McDonald's*
171
+ *Orders a salad from Subway*
172
+
173
+ <reasoning>
174
+ Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls.
175
+ Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
176
+ </reasoning>
177
+ </example>
178
+
179
+
154
180
  ## Task States and Management
155
181
 
156
182
  1. **Task States**: Use these states to track progress:
157
183
  - pending: Task not yet started
158
- - in_progress: Currently working on (limit to ONE task at a time)
184
+ - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)
159
185
  - completed: Task finished successfully
160
186
 
161
187
  2. **Task Management**:
162
188
  - Update task status in real-time as you work
163
189
  - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
164
- - Only have ONE task in_progress at any time
165
190
  - Complete current tasks before starting new ones
166
191
  - Remove tasks that are no longer relevant from the list entirely
192
+ - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
193
+ - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.
167
194
 
168
195
  3. **Task Completion Requirements**:
169
196
  - ONLY mark a task as completed when you have FULLY accomplished it
@@ -181,36 +208,76 @@ The assistant did not use the todo list because this is a single information loo
181
208
  - Break complex tasks into smaller, manageable steps
182
209
  - Use clear, descriptive task names
183
210
 
184
- When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully."""
211
+ Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
212
+ Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.
213
+ """
185
214
 
186
- TASK_DESCRIPTION_PREFIX = """Launch a new agent to handle complex, multi-step tasks autonomously.
215
+ TASK_TOOL_DESCRIPTION = """Launch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.
187
216
 
188
217
  Available agent types and the tools they have access to:
189
- - general-purpose: General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)
218
+ - general-purpose: General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.
190
219
  {other_agents}
191
- """
192
-
193
- TASK_DESCRIPTION_SUFFIX = """When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
194
-
195
- When to use the Agent tool:
196
- - When you are instructed to execute custom slash commands. Use the Agent tool with the slash command invocation as the entire prompt. The slash command can take arguments. For example: Task(description="Check the file", prompt="/check-file path/to/file.py")
197
220
 
198
- When NOT to use the Agent tool:
199
- - If you want to read a specific file path, use the Read or Glob tool instead of the Agent tool, to find the match more quickly
200
- - If you are searching for a specific term or definition within a known location, use the Glob tool instead, to find the match more quickly
201
- - If you are searching for content within a specific file or set of 2-3 files, use the Read tool instead of the Agent tool, to find the match more quickly
202
- - Other tasks that are not related to the agent descriptions above
221
+ When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
203
222
 
204
-
205
- Usage notes:
223
+ ## Usage notes:
206
224
  1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
207
225
  2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
208
226
  3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
209
227
  4. The agent's outputs should generally be trusted
210
228
  5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
211
229
  6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
230
+ 7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.
212
231
 
213
- Example usage:
232
+ ### Example usage of the general-purpose agent:
233
+
234
+ <example_agent_descriptions>
235
+ "general-purpose": use this agent for general purpose tasks, it has access to all tools as the main agent.
236
+ </example_agent_descriptions>
237
+
238
+ <example>
239
+ User: "I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them."
240
+ Assistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*
241
+ Assistant: *Synthesizes the results of the three isolated research tasks and responds to the User*
242
+ <commentary>
243
+ Research is a complex, multi-step task in it of itself.
244
+ The research of each individual player is not dependent on the research of the other players.
245
+ The assistant uses the task tool to break down the complex objective into three isolated tasks.
246
+ Each research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.
247
+ This means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.
248
+ </commentary>
249
+ </example>
250
+
251
+ <example>
252
+ User: "Analyze a single large code repository for security vulnerabilities and generate a report."
253
+ Assistant: *Launches a single `task` subagent for the repository analysis*
254
+ Assistant: *Receives report and integrates results into final summary*
255
+ <commentary>
256
+ Subagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.
257
+ If the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.
258
+ </commentary>
259
+ </example>
260
+
261
+ <example>
262
+ User: "Schedule two meetings for me and prepare agendas for each."
263
+ Assistant: *Calls the task tool in parallel to launch two `task` subagents (one per meeting) to prepare agendas*
264
+ Assistant: *Returns final schedules and agendas*
265
+ <commentary>
266
+ Tasks are simple individually, but subagents help silo agenda preparation.
267
+ Each subagent only needs to worry about the agenda for one meeting.
268
+ </commentary>
269
+ </example>
270
+
271
+ <example>
272
+ User: "I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway."
273
+ Assistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*
274
+ <commentary>
275
+ The assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.
276
+ It is better to just complete the task directly and NOT use the `task`tool.
277
+ </commentary>
278
+ </example>
279
+
280
+ ### Example usage with custom agents:
214
281
 
215
282
  <example_agent_descriptions>
216
283
  "content-reviewer": use this agent after you are done creating significant content or documents
@@ -224,13 +291,13 @@ assistant: Sure let me write a function that checks if a number is prime
224
291
  assistant: First let me use the Write tool to write a function that checks if a number is prime
225
292
  assistant: I'm going to use the Write tool to write the following code:
226
293
  <code>
227
- function isPrime(n) {
294
+ function isPrime(n) {{
228
295
  if (n <= 1) return false
229
- for (let i = 2; i * i <= n; i++) {
296
+ for (let i = 2; i * i <= n; i++) {{
230
297
  if (n % i === 0) return false
231
- }
298
+ }}
232
299
  return true
233
- }
300
+ }}
234
301
  </code>
235
302
  <commentary>
236
303
  Since significant content was created and the task was completed, now use the content-reviewer agent to review the work
@@ -255,16 +322,15 @@ Since the user is greeting, use the greeting-responder agent to respond with a f
255
322
  </commentary>
256
323
  assistant: "I'm going to use the Task tool to launch with the greeting-responder agent"
257
324
  </example>"""
258
- EDIT_DESCRIPTION = """Performs exact string replacements in files.
325
+
326
+ LIST_FILES_TOOL_DESCRIPTION = """Lists all files in the local filesystem.
259
327
 
260
328
  Usage:
261
- - You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
262
- - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
263
- - ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.
264
- - Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
265
- - The edit will FAIL if `old_string` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use `replace_all` to change every instance of `old_string`.
266
- - Use `replace_all` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance."""
267
- TOOL_DESCRIPTION = """Reads a file from the local filesystem. You can access any file directly by using this tool.
329
+ - The list_files tool will return a list of all files in the local filesystem.
330
+ - This is very useful for exploring the file system and finding the right file to read or edit.
331
+ - You should almost ALWAYS use this tool before using the Read or Edit tools."""
332
+
333
+ READ_FILE_TOOL_DESCRIPTION = """Reads a file from the local filesystem. You can access any file directly by using this tool.
268
334
  Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
269
335
 
270
336
  Usage:
@@ -274,4 +340,76 @@ Usage:
274
340
  - Any lines longer than 2000 characters will be truncated
275
341
  - Results are returned using cat -n format, with line numbers starting at 1
276
342
  - You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
277
- - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents."""
343
+ - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.
344
+ - You should ALWAYS make sure a file has been read before editing it."""
345
+
346
+ EDIT_FILE_TOOL_DESCRIPTION = """Performs exact string replacements in files.
347
+
348
+ Usage:
349
+ - You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
350
+ - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
351
+ - ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.
352
+ - Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
353
+ - The edit will FAIL if `old_string` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use `replace_all` to change every instance of `old_string`.
354
+ - Use `replace_all` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance."""
355
+
356
+ WRITE_FILE_TOOL_DESCRIPTION = """Writes to a file in the local filesystem.
357
+
358
+ Usage:
359
+ - The file_path parameter must be an absolute path, not a relative path
360
+ - The content parameter must be a string
361
+ - The write_file tool will create the a new file.
362
+ - Prefer to edit existing files over creating new ones when possible."""
363
+
364
+
365
+ BASE_AGENT_PROMPT = """In order to complete the objective that the user asks ofyou, you have access to a number of standard tools.
366
+
367
+ ## `write_todos`
368
+
369
+ You have access to the `write_todos` tool to help you manage and plan complex objectives.
370
+ Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
371
+ This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
372
+
373
+ It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.
374
+ For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
375
+ Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.
376
+
377
+ IMPORTANT: The `write_todos` tool should never be called multiple times in parallel.
378
+
379
+ ## `task` (subagent spawner)
380
+
381
+ You have access to a `task` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.
382
+
383
+ When to use the task tool:
384
+ - When a task is complex and multi-step, and can be fully delegated in isolation
385
+ - When a task is independent of other tasks and can run in parallel
386
+ - When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread
387
+ - When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)
388
+ - When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)
389
+
390
+ Subagent lifecycle:
391
+ 1. **Spawn** → Provide clear role, instructions, and expected output
392
+ 2. **Run** → The subagent completes the task autonomously
393
+ 3. **Return** → The subagent provides a single structured result
394
+ 4. **Reconcile** → Incorporate or synthesize the result into the main thread
395
+
396
+ When NOT to use the task tool:
397
+ - If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)
398
+ - If the task is trivial (a few tool calls or simple lookup)
399
+ - If delegating does not reduce token usage, complexity, or context switching
400
+ - If splitting would add latency without benefit
401
+
402
+ ## Filesystem Tools `ls`, `read_file`, `write_file`, `edit_file`
403
+
404
+ You have access to a local, private filesystem which you can interact with using these tools.
405
+ - ls: list all files in the local filesystem
406
+ - read_file: read a file from the local filesystem
407
+ - write_file: write to a file in the local filesystem
408
+ - edit_file: edit a file in the local filesystem
409
+
410
+ # Important Usage Notes to Remember
411
+ - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.
412
+ - Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.
413
+ - Remember to use the `task` tool to silo independent tasks within a multi-part objective.
414
+ - You should use the `task` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.
415
+ """
@@ -1,4 +1,4 @@
1
- from deepagents.prompts import TASK_DESCRIPTION_PREFIX, TASK_DESCRIPTION_SUFFIX
1
+ from deepagents.prompts import TASK_TOOL_DESCRIPTION
2
2
  from deepagents.state import DeepAgentState
3
3
  from langgraph.prebuilt import create_react_agent
4
4
  from langchain_core.tools import BaseTool
@@ -9,6 +9,7 @@ from langchain_core.language_models import LanguageModelLike
9
9
  from langchain.chat_models import init_chat_model
10
10
  from typing import Annotated, NotRequired, Any, Union, Optional, Callable
11
11
  from langgraph.types import Command
12
+ from langchain_core.runnables import Runnable
12
13
 
13
14
  from langgraph.prebuilt import InjectedState
14
15
 
@@ -22,10 +23,28 @@ class SubAgent(TypedDict):
22
23
  model: NotRequired[Union[LanguageModelLike, dict[str, Any]]]
23
24
 
24
25
 
25
- def _get_agents(tools, instructions, subagents: list[SubAgent], model, state_schema, post_model_hook: Optional[Callable] = None):
26
+ class CustomSubAgent(TypedDict):
27
+ name: str
28
+ description: str
29
+ graph: Runnable
30
+
31
+
32
+ def _get_agents(
33
+ tools,
34
+ instructions,
35
+ subagents: list[SubAgent | CustomSubAgent],
36
+ model,
37
+ state_schema,
38
+ post_model_hook: Optional[Callable] = None,
39
+ ):
26
40
  agents = {
27
41
  "general-purpose": create_react_agent(
28
- model, prompt=instructions, tools=tools, checkpointer=False, post_model_hook=post_model_hook
42
+ model,
43
+ prompt=instructions,
44
+ tools=tools,
45
+ checkpointer=False,
46
+ post_model_hook=post_model_hook,
47
+ state_schema=state_schema,
29
48
  )
30
49
  }
31
50
  tools_by_name = {}
@@ -34,6 +53,9 @@ def _get_agents(tools, instructions, subagents: list[SubAgent], model, state_sch
34
53
  tool_ = tool(tool_)
35
54
  tools_by_name[tool_.name] = tool_
36
55
  for _agent in subagents:
56
+ if "graph" in _agent:
57
+ agents[_agent["name"]] = _agent["graph"]
58
+ continue
37
59
  if "tools" in _agent:
38
60
  _tools = [tools_by_name[t] for t in _agent["tools"]]
39
61
  else:
@@ -61,19 +83,25 @@ def _get_agents(tools, instructions, subagents: list[SubAgent], model, state_sch
61
83
  return agents
62
84
 
63
85
 
64
- def _get_subagent_description(subagents):
86
+ def _get_subagent_description(subagents: list[SubAgent | CustomSubAgent]):
65
87
  return [f"- {_agent['name']}: {_agent['description']}" for _agent in subagents]
66
88
 
67
89
 
68
90
  def _create_task_tool(
69
- tools, instructions, subagents: list[SubAgent], model, state_schema, post_model_hook: Optional[Callable] = None
91
+ tools,
92
+ instructions,
93
+ subagents: list[SubAgent | CustomSubAgent],
94
+ model,
95
+ state_schema,
96
+ post_model_hook: Optional[Callable] = None,
70
97
  ):
71
- agents = _get_agents(tools, instructions, subagents, model, state_schema, post_model_hook)
98
+ agents = _get_agents(
99
+ tools, instructions, subagents, model, state_schema, post_model_hook
100
+ )
72
101
  other_agents_string = _get_subagent_description(subagents)
73
102
 
74
103
  @tool(
75
- description=TASK_DESCRIPTION_PREFIX.format(other_agents=other_agents_string)
76
- + TASK_DESCRIPTION_SUFFIX
104
+ description=TASK_TOOL_DESCRIPTION.format(other_agents=other_agents_string)
77
105
  )
78
106
  async def task(
79
107
  description: str,
@@ -101,14 +129,20 @@ def _create_task_tool(
101
129
 
102
130
 
103
131
  def _create_sync_task_tool(
104
- tools, instructions, subagents: list[SubAgent], model, state_schema, post_model_hook: Optional[Callable] = None
132
+ tools,
133
+ instructions,
134
+ subagents: list[SubAgent | CustomSubAgent],
135
+ model,
136
+ state_schema,
137
+ post_model_hook: Optional[Callable] = None,
105
138
  ):
106
- agents = _get_agents(tools, instructions, subagents, model, state_schema, post_model_hook)
139
+ agents = _get_agents(
140
+ tools, instructions, subagents, model, state_schema, post_model_hook
141
+ )
107
142
  other_agents_string = _get_subagent_description(subagents)
108
143
 
109
144
  @tool(
110
- description=TASK_DESCRIPTION_PREFIX.format(other_agents=other_agents_string)
111
- + TASK_DESCRIPTION_SUFFIX
145
+ description=TASK_TOOL_DESCRIPTION.format(other_agents=other_agents_string)
112
146
  )
113
147
  def task(
114
148
  description: str,
@@ -5,14 +5,16 @@ from typing import Annotated, Union
5
5
  from langgraph.prebuilt import InjectedState
6
6
 
7
7
  from deepagents.prompts import (
8
- WRITE_TODOS_DESCRIPTION,
9
- EDIT_DESCRIPTION,
10
- TOOL_DESCRIPTION,
8
+ WRITE_TODOS_TOOL_DESCRIPTION,
9
+ LIST_FILES_TOOL_DESCRIPTION,
10
+ READ_FILE_TOOL_DESCRIPTION,
11
+ WRITE_FILE_TOOL_DESCRIPTION,
12
+ EDIT_FILE_TOOL_DESCRIPTION,
11
13
  )
12
14
  from deepagents.state import Todo, DeepAgentState
13
15
 
14
16
 
15
- @tool(description=WRITE_TODOS_DESCRIPTION)
17
+ @tool(description=WRITE_TODOS_TOOL_DESCRIPTION)
16
18
  def write_todos(
17
19
  todos: list[Todo], tool_call_id: Annotated[str, InjectedToolCallId]
18
20
  ) -> Command:
@@ -26,19 +28,19 @@ def write_todos(
26
28
  )
27
29
 
28
30
 
31
+ @tool(description=LIST_FILES_TOOL_DESCRIPTION)
29
32
  def ls(state: Annotated[DeepAgentState, InjectedState]) -> list[str]:
30
33
  """List all files"""
31
34
  return list(state.get("files", {}).keys())
32
35
 
33
36
 
34
- @tool(description=TOOL_DESCRIPTION)
37
+ @tool(description=READ_FILE_TOOL_DESCRIPTION)
35
38
  def read_file(
36
39
  file_path: str,
37
40
  state: Annotated[DeepAgentState, InjectedState],
38
41
  offset: int = 0,
39
42
  limit: int = 2000,
40
43
  ) -> str:
41
- """Read file."""
42
44
  mock_filesystem = state.get("files", {})
43
45
  if file_path not in mock_filesystem:
44
46
  return f"Error: File '{file_path}' not found"
@@ -77,13 +79,13 @@ def read_file(
77
79
  return "\n".join(result_lines)
78
80
 
79
81
 
82
+ @tool(description=WRITE_FILE_TOOL_DESCRIPTION)
80
83
  def write_file(
81
84
  file_path: str,
82
85
  content: str,
83
86
  state: Annotated[DeepAgentState, InjectedState],
84
87
  tool_call_id: Annotated[str, InjectedToolCallId],
85
88
  ) -> Command:
86
- """Write to a file."""
87
89
  files = state.get("files", {})
88
90
  files[file_path] = content
89
91
  return Command(
@@ -96,7 +98,7 @@ def write_file(
96
98
  )
97
99
 
98
100
 
99
- @tool(description=EDIT_DESCRIPTION)
101
+ @tool(description=EDIT_FILE_TOOL_DESCRIPTION)
100
102
  def edit_file(
101
103
  file_path: str,
102
104
  old_string: str,
File without changes
File without changes