deepagents 0.0.12rc2__tar.gz → 0.1.0__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.
@@ -0,0 +1,531 @@
1
+ Metadata-Version: 2.4
2
+ Name: deepagents
3
+ Version: 0.1.0
4
+ Summary: General purpose 'deep agent' with sub-agent spawning, todo list capabilities, and mock file system. Built on LangGraph.
5
+ License: MIT
6
+ Requires-Python: <4.0,>=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: langchain-anthropic==1.0.0
10
+ Requires-Dist: langchain==1.0.0
11
+ Requires-Dist: langchain-core==1.0.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest; extra == "dev"
14
+ Requires-Dist: pytest-cov; extra == "dev"
15
+ Requires-Dist: build; extra == "dev"
16
+ Requires-Dist: twine; extra == "dev"
17
+ Requires-Dist: langchain-openai; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ # 🧠🤖Deep Agents
21
+
22
+ Using an LLM to call tools in a loop is the simplest form of an agent.
23
+ This architecture, however, can yield agents that are “shallow” and fail to plan and act over longer, more complex tasks.
24
+
25
+ Applications like “Deep Research”, "Manus", and “Claude Code” have gotten around this limitation by implementing a combination of four things:
26
+ a **planning tool**, **sub agents**, access to a **file system**, and a **detailed prompt**.
27
+
28
+ <img src="deep_agents.png" alt="deep agent" width="600"/>
29
+
30
+ `deepagents` is a Python package that implements these in a general purpose way so that you can easily create a Deep Agent for your application.
31
+
32
+ **Acknowledgements: This project was primarily inspired by Claude Code, and initially was largely an attempt to see what made Claude Code general purpose, and make it even more so.**
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ # pip
38
+ pip install deepagents
39
+
40
+ # uv
41
+ uv add deepagents
42
+
43
+ # poetry
44
+ poetry add deepagents
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ (To run the example below, you will need to `pip install tavily-python`).
50
+
51
+ Make sure to set `TAVILY_API_KEY` in your environment. You can generate one [here](https://www.tavily.com/).
52
+
53
+ ```python
54
+ import os
55
+ from typing import Literal
56
+ from tavily import TavilyClient
57
+ from deepagents import create_deep_agent
58
+
59
+ tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
60
+
61
+ # Web search tool
62
+ def internet_search(
63
+ query: str,
64
+ max_results: int = 5,
65
+ topic: Literal["general", "news", "finance"] = "general",
66
+ include_raw_content: bool = False,
67
+ ):
68
+ """Run a web search"""
69
+ return tavily_client.search(
70
+ query,
71
+ max_results=max_results,
72
+ include_raw_content=include_raw_content,
73
+ topic=topic,
74
+ )
75
+
76
+
77
+ # System prompt to steer the agent to be an expert researcher
78
+ research_instructions = """You are an expert researcher. Your job is to conduct thorough research, and then write a polished report.
79
+
80
+ You have access to an internet search tool as your primary means of gathering information.
81
+
82
+ ## `internet_search`
83
+
84
+ Use this to run an internet search for a given query. You can specify the max number of results to return, the topic, and whether raw content should be included.
85
+ """
86
+
87
+ # Create the deep agent
88
+ agent = create_deep_agent(
89
+ tools=[internet_search],
90
+ system_prompt=research_instructions,
91
+ )
92
+
93
+ # Invoke the agent
94
+ result = agent.invoke({"messages": [{"role": "user", "content": "What is langgraph?"}]})
95
+ ```
96
+
97
+ See [examples/research/research_agent.py](examples/research/research_agent.py) for a more complex example.
98
+
99
+ The agent created with `create_deep_agent` is just a LangGraph graph - so you can interact with it (streaming, human-in-the-loop, memory, studio)
100
+ in the same way you would any LangGraph agent.
101
+
102
+ ## Core Capabilities
103
+ **Planning & Task Decomposition**
104
+
105
+ Deep Agents include a built-in `write_todos` tool that enables agents to break down complex tasks into discrete steps, track progress, and adapt plans as new information emerges.
106
+
107
+ **Context Management**
108
+
109
+ File system tools (`ls`, `read_file`, `write_file`, `edit_file`) allow agents to offload large context to memory, preventing context window overflow and enabling work with variable-length tool results.
110
+
111
+ **Subagent Spawning**
112
+
113
+ A built-in `task` tool enables agents to spawn specialized subagents for context isolation. This keeps the main agent’s context clean while still going deep on specific subtasks.
114
+
115
+ **Long-term Memory**
116
+
117
+ Extend agents with persistent memory across threads using LangGraph’s Store. Agents can save and retrieve information from previous conversations.
118
+
119
+ ## Customizing Deep Agents
120
+
121
+ There are several parameters you can pass to `create_deep_agent` to create your own custom deep agent.
122
+
123
+ ### `model`
124
+
125
+ By default, `deepagents` uses `"claude-sonnet-4-5-20250929"`. You can customize this by passing any [LangChain model object](https://python.langchain.com/docs/integrations/chat/).
126
+
127
+ ```python
128
+ from langchain.chat_models import init_chat_model
129
+ from deepagents import create_deep_agent
130
+
131
+ model = init_chat_model(
132
+ model="openai:gpt-5",
133
+ )
134
+ agent = create_deep_agent(
135
+ model=model,
136
+ )
137
+ ```
138
+
139
+ ### `system_prompt`
140
+ Deep Agents come with a built-in system prompt. This is relatively detailed prompt that is heavily based on and inspired by [attempts](https://github.com/kn1026/cc/blob/main/claudecode.md) to [replicate](https://github.com/asgeirtj/system_prompts_leaks/blob/main/Anthropic/claude-code.md)
141
+ Claude Code's system prompt. It was made more general purpose than Claude Code's system prompt. The default prompt contains detailed instructions for how to use the built-in planning tool, file system tools, and sub agents.
142
+
143
+ Each deep agent tailored to a use case should include a custom system prompt specific to that use case as well. The importance of prompting for creating a successful deep agent cannot be overstated.
144
+
145
+ ```python
146
+ from deepagents import create_deep_agent
147
+
148
+ research_instructions = """You are an expert researcher. Your job is to conduct thorough research, and then write a polished report.
149
+ """
150
+
151
+ agent = create_deep_agent(
152
+ system_prompt=research_instructions,
153
+ )
154
+ ```
155
+
156
+ ### `tools`
157
+
158
+ Just like with tool-calling agents, you can provide a deep agent with a set of tools that it has access to.
159
+
160
+ ```python
161
+ import os
162
+ from typing import Literal
163
+ from tavily import TavilyClient
164
+ from deepagents import create_deep_agent
165
+
166
+ tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
167
+
168
+ def internet_search(
169
+ query: str,
170
+ max_results: int = 5,
171
+ topic: Literal["general", "news", "finance"] = "general",
172
+ include_raw_content: bool = False,
173
+ ):
174
+ """Run a web search"""
175
+ return tavily_client.search(
176
+ query,
177
+ max_results=max_results,
178
+ include_raw_content=include_raw_content,
179
+ topic=topic,
180
+ )
181
+
182
+ agent = create_deep_agent(
183
+ tools=[internet_search]
184
+ )
185
+ ```
186
+
187
+ ### `middleware`
188
+ `create_deep_agent` is implemented with middleware that can be customized. You can provide additional middleware to extend functionality, add tools, or implement custom hooks.
189
+
190
+ ```python
191
+ from langchain_core.tools import tool
192
+ from deepagents import create_deep_agent
193
+ from langchain.agents.middleware import AgentMiddleware
194
+
195
+ @tool
196
+ def get_weather(city: str) -> str:
197
+ """Get the weather in a city."""
198
+ return f"The weather in {city} is sunny."
199
+
200
+ @tool
201
+ def get_temperature(city: str) -> str:
202
+ """Get the temperature in a city."""
203
+ return f"The temperature in {city} is 70 degrees Fahrenheit."
204
+
205
+ class WeatherMiddleware(AgentMiddleware):
206
+ tools = [get_weather, get_temperature]
207
+
208
+ agent = create_deep_agent(
209
+ model="anthropic:claude-sonnet-4-20250514",
210
+ middleware=[WeatherMiddleware()]
211
+ )
212
+ ```
213
+
214
+ ### `subagents`
215
+
216
+ A main feature of Deep Agents is their ability to spawn subagents. You can specify custom subagents that your agent can hand off work to in the subagents parameter. Sub agents are useful for context quarantine (to help not pollute the overall context of the main agent) as well as custom instructions.
217
+
218
+ `subagents` should be a list of dictionaries, where each dictionary follow this schema:
219
+
220
+ ```python
221
+ class SubAgent(TypedDict):
222
+ name: str
223
+ description: str
224
+ prompt: str
225
+ tools: Sequence[BaseTool | Callable | dict[str, Any]]
226
+ model: NotRequired[str | BaseChatModel]
227
+ middleware: NotRequired[list[AgentMiddleware]]
228
+ interrupt_on: NotRequired[dict[str, bool | InterruptOnConfig]]
229
+
230
+ class CompiledSubAgent(TypedDict):
231
+ name: str
232
+ description: str
233
+ runnable: Runnable
234
+ ```
235
+
236
+ **SubAgent fields:**
237
+ - **name**: This is the name of the subagent, and how the main agent will call the subagent
238
+ - **description**: This is the description of the subagent that is shown to the main agent
239
+ - **prompt**: This is the prompt used for the subagent
240
+ - **tools**: This is the list of tools that the subagent has access to.
241
+ - **model**: Optional model name or model instance.
242
+ - **middleware** Additional middleware to attach to the subagent. See [here](https://docs.langchain.com/oss/python/langchain/middleware) for an introduction into middleware and how it works with create_agent.
243
+ - **interrupt_on** A custom interrupt config that specifies human-in-the-loop interactions for your tools.
244
+
245
+ **CompiledSubAgent fields:**
246
+ - **name**: This is the name of the subagent, and how the main agent will call the subagent
247
+ - **description**: This is the description of the subagent that is shown to the main agent
248
+ - **runnable**: A pre-built LangGraph graph/agent that will be used as the subagent
249
+
250
+ #### Using SubAgent
251
+
252
+ ```python
253
+ import os
254
+ from typing import Literal
255
+ from tavily import TavilyClient
256
+ from deepagents import create_deep_agent
257
+
258
+ tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
259
+
260
+ def internet_search(
261
+ query: str,
262
+ max_results: int = 5,
263
+ topic: Literal["general", "news", "finance"] = "general",
264
+ include_raw_content: bool = False,
265
+ ):
266
+ """Run a web search"""
267
+ return tavily_client.search(
268
+ query,
269
+ max_results=max_results,
270
+ include_raw_content=include_raw_content,
271
+ topic=topic,
272
+ )
273
+
274
+ research_subagent = {
275
+ "name": "research-agent",
276
+ "description": "Used to research more in depth questions",
277
+ "system_prompt": "You are a great researcher",
278
+ "tools": [internet_search],
279
+ "model": "openai:gpt-4o", # Optional override, defaults to main agent model
280
+ }
281
+ subagents = [research_subagent]
282
+
283
+ agent = create_deep_agent(
284
+ model="anthropic:claude-sonnet-4-20250514",
285
+ subagents=subagents
286
+ )
287
+ ```
288
+
289
+ #### Using CustomSubAgent
290
+
291
+ For more complex use cases, you can provide your own pre-built LangGraph graph as a subagent:
292
+
293
+ ```python
294
+ # Create a custom agent graph
295
+ custom_graph = create_agent(
296
+ model=your_model,
297
+ tools=specialized_tools,
298
+ prompt="You are a specialized agent for data analysis..."
299
+ )
300
+
301
+ # Use it as a custom subagent
302
+ custom_subagent = CompiledSubAgent(
303
+ name="data-analyzer",
304
+ description="Specialized agent for complex data analysis tasks",
305
+ runnable=custom_graph
306
+ )
307
+
308
+ subagents = [custom_subagent]
309
+
310
+ agent = create_deep_agent(
311
+ model="anthropic:claude-sonnet-4-20250514",
312
+ tools=[internet_search],
313
+ system_prompt=research_instructions,
314
+ subagents=subagents
315
+ )
316
+ ```
317
+
318
+ ### `use_longterm_memory`
319
+ Deep agents come with a local filesystem to offload memory to. This filesystem is stored in state, and is therefore transient to a single thread.
320
+
321
+ You can extend deep agents with long-term memory by providing a Store and setting use_longterm_memory=True.
322
+
323
+ ```python
324
+ from deepagents import create_deep_agent
325
+ from langgraph.store.memory import InMemoryStore
326
+
327
+ store = InMemoryStore() # Or any other Store object
328
+ agent = create_deep_agent(
329
+ store=store,
330
+ use_longterm_memory=True
331
+ )
332
+ ```
333
+
334
+ ### `interrupt_on`
335
+ A common reality for agents is that some tool operations may be sensitive and require human approval before execution. Deep Agents supports human-in-the-loop workflows through LangGraph’s interrupt capabilities. You can configure which tools require approval using a checkpointer.
336
+
337
+ These tool configs are passed to our prebuilt [HITL middleware](https://docs.langchain.com/oss/python/langchain/middleware#human-in-the-loop) so that the agent pauses execution and waits for feedback from the user before executing configured tools.
338
+
339
+ ```python
340
+ from langchain_core.tools import tool
341
+ from deepagents import create_deep_agent
342
+
343
+ @tool
344
+ def get_weather(city: str) -> str:
345
+ """Get the weather in a city."""
346
+ return f"The weather in {city} is sunny."
347
+
348
+ agent = create_deep_agent(
349
+ model="anthropic:claude-sonnet-4-20250514",
350
+ tools=[get_weather],
351
+ interrupt_on={
352
+ "get_weather": {
353
+ "allowed_decisions": ["approve", "edit", "reject"]
354
+ },
355
+ }
356
+ )
357
+
358
+ ```
359
+
360
+ ## Deep Agents Middleware
361
+
362
+ Deep Agents are built with a modular middleware architecture. As a reminder, Deep Agents have access to:
363
+ - A planning tool
364
+ - A filesystem for storing context and long-term memories
365
+ - The ability to spawn subagents
366
+
367
+ Each of these features is implemented as separate middleware. When you create a deep agent with `create_deep_agent`, we automatically attach **PlanningMiddleware**, **FilesystemMiddleware** and **SubAgentMiddleware** to your agent.
368
+
369
+ Middleware is a composable concept, and you can choose to add as many or as few middleware to an agent depending on your use case. That means that you can also use any of the aforementioned middleware independently!
370
+
371
+ ### TodoListMiddleware
372
+
373
+ Planning is integral to solving complex problems. If you’ve used claude code recently, you’ll notice how it writes out a To-Do list before tackling complex, multi-part tasks. You’ll also notice how it can adapt and update this To-Do list on the fly as more information comes in.
374
+
375
+ **TodoListMiddleware** provides your agent with a tool specifically for updating this To-Do list. Before, and while it executes a multi-part task, the agent is prompted to use the write_todos tool to keep track of what its doing, and what still needs to be done.
376
+
377
+ ```python
378
+ from langchain.agents import create_agent
379
+ from langchain.agents.middleware import TodoListMiddleware
380
+
381
+ # TodoListMiddleware is included by default in create_deep_agent
382
+ # You can customize it if building a custom agent
383
+ agent = create_agent(
384
+ model="anthropic:claude-sonnet-4-20250514",
385
+ # Custom planning instructions can be added via middleware
386
+ middleware=[
387
+ TodoListMiddleware(
388
+ system_prompt="Use the write_todos tool to..." # Optional: Custom addition to the system prompt
389
+ ),
390
+ ],
391
+ )
392
+ ```
393
+
394
+ ### FilesystemMiddleware
395
+
396
+ Context engineering is one of the main challenges in building effective agents. This can be particularly hard when using tools that can return variable length results (ex. web_search, rag), as long ToolResults can quickly fill up your context window.
397
+ **FilesystemMiddleware** provides four tools to your agent to interact with both short-term and long-term memory.
398
+ - **ls**: List the files in your filesystem
399
+ - **read_file**: Read an entire file, or a certain number of lines from a file
400
+ - **write_file**: Write a new file to your filesystem
401
+ - **edit_file**: Edit an existing file in your filesystem
402
+
403
+ ```python
404
+ from langchain.agents import create_agent
405
+ from deepagents.middleware.filesystem import FilesystemMiddleware
406
+
407
+ # FilesystemMiddleware is included by default in create_deep_agent
408
+ # You can customize it if building a custom agent
409
+ agent = create_agent(
410
+ model="anthropic:claude-sonnet-4-20250514",
411
+ middleware=[
412
+ FilesystemMiddleware(
413
+ long_term_memory=False, # Enables access to long-term memory, defaults to False. You must attach a store to use long-term memory.
414
+ system_prompt="Write to the filesystem when...", # Optional custom addition to the system prompt
415
+ custom_tool_descriptions={
416
+ "ls": "Use the ls tool when...",
417
+ "read_file": "Use the read_file tool to..."
418
+ } # Optional: Custom descriptions for filesystem tools
419
+ ),
420
+ ],
421
+ )
422
+ ```
423
+
424
+ ### SubAgentMiddleware
425
+
426
+ Handing off tasks to subagents is a great way to isolate context, keeping the context window of the main (supervisor) agent clean while still going deep on a task. The subagents middleware allows you supply subagents through a task tool.
427
+
428
+ A subagent is defined with a name, description, system prompt, and tools. You can also provide a subagent with a custom model, or with additional middleware. This can be particularly useful when you want to give the subagent an additional state key to share with the main agent.
429
+
430
+ ```python
431
+ from langchain_core.tools import tool
432
+ from langchain.agents import create_agent
433
+ from deepagents.middleware.subagents import SubAgentMiddleware
434
+
435
+
436
+ @tool
437
+ def get_weather(city: str) -> str:
438
+ """Get the weather in a city."""
439
+ return f"The weather in {city} is sunny."
440
+
441
+ agent = create_agent(
442
+ model="claude-sonnet-4-20250514",
443
+ middleware=[
444
+ SubAgentMiddleware(
445
+ default_model="claude-sonnet-4-20250514",
446
+ default_tools=[],
447
+ subagents=[
448
+ {
449
+ "name": "weather",
450
+ "description": "This subagent can get weather in cities.",
451
+ "system_prompt": "Use the get_weather tool to get the weather in a city.",
452
+ "tools": [get_weather],
453
+ "model": "gpt-4.1",
454
+ "middleware": [],
455
+ }
456
+ ],
457
+ )
458
+ ],
459
+ )
460
+ ```
461
+
462
+ For more complex use cases, you can also provide your own pre-built LangGraph graph as a subagent.
463
+
464
+ ```python
465
+ # Create a custom LangGraph graph
466
+ def create_weather_graph():
467
+ workflow = StateGraph(...)
468
+ # Build your custom graph
469
+ return workflow.compile()
470
+
471
+ weather_graph = create_weather_graph()
472
+
473
+ # Wrap it in a CompiledSubAgent
474
+ weather_subagent = CompiledSubAgent(
475
+ name="weather",
476
+ description="This subagent can get weather in cities.",
477
+ runnable=weather_graph
478
+ )
479
+
480
+ agent = create_agent(
481
+ model="anthropic:claude-sonnet-4-20250514",
482
+ middleware=[
483
+ SubAgentMiddleware(
484
+ default_model="claude-sonnet-4-20250514",
485
+ default_tools=[],
486
+ subagents=[weather_subagent],
487
+ )
488
+ ],
489
+ )
490
+ ```
491
+
492
+ ## Sync vs Async
493
+
494
+ Prior versions of deepagents separated sync and async agent factories.
495
+
496
+ `async_create_deep_agent` has been folded in to `create_deep_agent`.
497
+
498
+ **You should use `create_deep_agent` as the factory for both sync and async agents**
499
+
500
+
501
+ ## MCP
502
+
503
+ The `deepagents` library can be ran with MCP tools. This can be achieved by using the [Langchain MCP Adapter library](https://github.com/langchain-ai/langchain-mcp-adapters).
504
+
505
+ **NOTE:** You will want to use `from deepagents import async_create_deep_agent` to use the async version of `deepagents`, since MCP tools are async
506
+
507
+ (To run the example below, will need to `pip install langchain-mcp-adapters`)
508
+
509
+ ```python
510
+ import asyncio
511
+ from langchain_mcp_adapters.client import MultiServerMCPClient
512
+ from deepagents import create_deep_agent
513
+
514
+ async def main():
515
+ # Collect MCP tools
516
+ mcp_client = MultiServerMCPClient(...)
517
+ mcp_tools = await mcp_client.get_tools()
518
+
519
+ # Create agent
520
+ agent = create_deep_agent(tools=mcp_tools, ....)
521
+
522
+ # Stream the agent
523
+ async for chunk in agent.astream(
524
+ {"messages": [{"role": "user", "content": "what is langgraph?"}]},
525
+ stream_mode="values"
526
+ ):
527
+ if "messages" in chunk:
528
+ chunk["messages"][-1].pretty_print()
529
+
530
+ asyncio.run(main())
531
+ ```