deepagents 0.2.7__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,516 @@
1
+ Metadata-Version: 2.4
2
+ Name: deepagents
3
+ Version: 0.2.7
4
+ Summary: General purpose 'deep agent' with sub-agent spawning, todo list capabilities, and mock file system. Built on LangGraph.
5
+ License: MIT
6
+ Project-URL: Homepage, https://docs.langchain.com/oss/python/deepagents/overview
7
+ Project-URL: Documentation, https://reference.langchain.com/python/deepagents/
8
+ Project-URL: Source, https://github.com/langchain-ai/deepagents
9
+ Project-URL: Twitter, https://x.com/LangChainAI
10
+ Project-URL: Slack, https://www.langchain.com/join-community
11
+ Project-URL: Reddit, https://www.reddit.com/r/LangChain/
12
+ Requires-Python: <4.0,>=3.11
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: langchain-anthropic<2.0.0,>=1.0.0
15
+ Requires-Dist: langchain<2.0.0,>=1.0.2
16
+ Requires-Dist: langchain-core<2.0.0,>=1.0.0
17
+ Requires-Dist: wcmatch
18
+ Requires-Dist: daytona>=0.113.0
19
+ Requires-Dist: runloop-api-client>=0.66.1
20
+ Requires-Dist: tavily>=1.1.0
21
+
22
+ # 🧠🤖Deep Agents
23
+
24
+ Using an LLM to call tools in a loop is the simplest form of an agent.
25
+ This architecture, however, can yield agents that are “shallow” and fail to plan and act over longer, more complex tasks.
26
+
27
+ Applications like “Deep Research”, "Manus", and “Claude Code” have gotten around this limitation by implementing a combination of four things:
28
+ a **planning tool**, **sub agents**, access to a **file system**, and a **detailed prompt**.
29
+
30
+ <img src="deep_agents.png" alt="deep agent" width="600"/>
31
+
32
+ `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. For a full overview and quickstart of `deepagents`, the best resource is our [docs](https://docs.langchain.com/oss/python/deepagents/overview).
33
+
34
+ **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.**
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ # pip
40
+ pip install deepagents
41
+
42
+ # uv
43
+ uv add deepagents
44
+
45
+ # poetry
46
+ poetry add deepagents
47
+ ```
48
+
49
+ ## Usage
50
+
51
+ (To run the example below, you will need to `pip install tavily-python`).
52
+
53
+ Make sure to set `TAVILY_API_KEY` in your environment. You can generate one [here](https://www.tavily.com/).
54
+
55
+ ```python
56
+ import os
57
+ from typing import Literal
58
+ from tavily import TavilyClient
59
+ from deepagents import create_deep_agent
60
+
61
+ tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
62
+
63
+ # Web search tool
64
+ def internet_search(
65
+ query: str,
66
+ max_results: int = 5,
67
+ topic: Literal["general", "news", "finance"] = "general",
68
+ include_raw_content: bool = False,
69
+ ):
70
+ """Run a web search"""
71
+ return tavily_client.search(
72
+ query,
73
+ max_results=max_results,
74
+ include_raw_content=include_raw_content,
75
+ topic=topic,
76
+ )
77
+
78
+
79
+ # System prompt to steer the agent to be an expert researcher
80
+ research_instructions = """You are an expert researcher. Your job is to conduct thorough research, and then write a polished report.
81
+
82
+ You have access to an internet search tool as your primary means of gathering information.
83
+
84
+ ## `internet_search`
85
+
86
+ 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.
87
+ """
88
+
89
+ # Create the deep agent
90
+ agent = create_deep_agent(
91
+ tools=[internet_search],
92
+ system_prompt=research_instructions,
93
+ )
94
+
95
+ # Invoke the agent
96
+ result = agent.invoke({"messages": [{"role": "user", "content": "What is langgraph?"}]})
97
+ ```
98
+
99
+ See [examples/research/research_agent.py](examples/research/research_agent.py) for a more complex example.
100
+
101
+ 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)
102
+ in the same way you would any LangGraph agent.
103
+
104
+ ## Core Capabilities
105
+ **Planning & Task Decomposition**
106
+
107
+ 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.
108
+
109
+ **Context Management**
110
+
111
+ File system tools (`ls`, `read_file`, `write_file`, `edit_file`, `glob`, `grep`) allow agents to offload large context to memory, preventing context window overflow and enabling work with variable-length tool results.
112
+
113
+ **Subagent Spawning**
114
+
115
+ 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.
116
+
117
+ **Long-term Memory**
118
+
119
+ Extend agents with persistent memory across threads using LangGraph’s Store. Agents can save and retrieve information from previous conversations.
120
+
121
+ ## Customizing Deep Agents
122
+
123
+ There are several parameters you can pass to `create_deep_agent` to create your own custom deep agent.
124
+
125
+ ### `model`
126
+
127
+ 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/).
128
+
129
+ ```python
130
+ from langchain.chat_models import init_chat_model
131
+ from deepagents import create_deep_agent
132
+
133
+ model = init_chat_model("openai:gpt-4o")
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
+ ### `interrupt_on`
319
+ 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.
320
+
321
+ 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.
322
+
323
+ ```python
324
+ from langchain_core.tools import tool
325
+ from deepagents import create_deep_agent
326
+
327
+ @tool
328
+ def get_weather(city: str) -> str:
329
+ """Get the weather in a city."""
330
+ return f"The weather in {city} is sunny."
331
+
332
+ agent = create_deep_agent(
333
+ model="anthropic:claude-sonnet-4-20250514",
334
+ tools=[get_weather],
335
+ interrupt_on={
336
+ "get_weather": {
337
+ "allowed_decisions": ["approve", "edit", "reject"]
338
+ },
339
+ }
340
+ )
341
+
342
+ ```
343
+
344
+ ## Deep Agents Middleware
345
+
346
+ Deep Agents are built with a modular middleware architecture. As a reminder, Deep Agents have access to:
347
+ - A planning tool
348
+ - A filesystem for storing context and long-term memories
349
+ - The ability to spawn subagents
350
+
351
+ Each of these features is implemented as separate middleware. When you create a deep agent with `create_deep_agent`, we automatically attach **TodoListMiddleware**, **FilesystemMiddleware** and **SubAgentMiddleware** to your agent.
352
+
353
+ 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!
354
+
355
+ ### TodoListMiddleware
356
+
357
+ 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.
358
+
359
+ **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.
360
+
361
+ ```python
362
+ from langchain.agents import create_agent
363
+ from langchain.agents.middleware import TodoListMiddleware
364
+
365
+ # TodoListMiddleware is included by default in create_deep_agent
366
+ # You can customize it if building a custom agent
367
+ agent = create_agent(
368
+ model="anthropic:claude-sonnet-4-20250514",
369
+ # Custom planning instructions can be added via middleware
370
+ middleware=[
371
+ TodoListMiddleware(
372
+ system_prompt="Use the write_todos tool to..." # Optional: Custom addition to the system prompt
373
+ ),
374
+ ],
375
+ )
376
+ ```
377
+
378
+ ### FilesystemMiddleware
379
+
380
+ 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.
381
+ **FilesystemMiddleware** provides four tools to your agent to interact with both short-term and long-term memory.
382
+ - **ls**: List the files in your filesystem
383
+ - **read_file**: Read an entire file, or a certain number of lines from a file
384
+ - **write_file**: Write a new file to your filesystem
385
+ - **edit_file**: Edit an existing file in your filesystem
386
+
387
+ ```python
388
+ from langchain.agents import create_agent
389
+ from deepagents.middleware.filesystem import FilesystemMiddleware
390
+
391
+
392
+ # FilesystemMiddleware is included by default in create_deep_agent
393
+ # You can customize it if building a custom agent
394
+ agent = create_agent(
395
+ model="anthropic:claude-sonnet-4-20250514",
396
+ middleware=[
397
+ FilesystemMiddleware(
398
+ backend=..., # Optional: customize storage backend
399
+ system_prompt="Write to the filesystem when...", # Optional custom system prompt override
400
+ custom_tool_descriptions={
401
+ "ls": "Use the ls tool when...",
402
+ "read_file": "Use the read_file tool to..."
403
+ } # Optional: Custom descriptions for filesystem tools
404
+ ),
405
+ ],
406
+ )
407
+ ```
408
+
409
+ ### SubAgentMiddleware
410
+
411
+ 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.
412
+
413
+ 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.
414
+
415
+ ```python
416
+ from langchain_core.tools import tool
417
+ from langchain.agents import create_agent
418
+ from deepagents.middleware.subagents import SubAgentMiddleware
419
+
420
+
421
+ @tool
422
+ def get_weather(city: str) -> str:
423
+ """Get the weather in a city."""
424
+ return f"The weather in {city} is sunny."
425
+
426
+ agent = create_agent(
427
+ model="claude-sonnet-4-20250514",
428
+ middleware=[
429
+ SubAgentMiddleware(
430
+ default_model="claude-sonnet-4-20250514",
431
+ default_tools=[],
432
+ subagents=[
433
+ {
434
+ "name": "weather",
435
+ "description": "This subagent can get weather in cities.",
436
+ "system_prompt": "Use the get_weather tool to get the weather in a city.",
437
+ "tools": [get_weather],
438
+ "model": "gpt-4.1",
439
+ "middleware": [],
440
+ }
441
+ ],
442
+ )
443
+ ],
444
+ )
445
+ ```
446
+
447
+ For more complex use cases, you can also provide your own pre-built LangGraph graph as a subagent.
448
+
449
+ ```python
450
+ # Create a custom LangGraph graph
451
+ def create_weather_graph():
452
+ workflow = StateGraph(...)
453
+ # Build your custom graph
454
+ return workflow.compile()
455
+
456
+ weather_graph = create_weather_graph()
457
+
458
+ # Wrap it in a CompiledSubAgent
459
+ weather_subagent = CompiledSubAgent(
460
+ name="weather",
461
+ description="This subagent can get weather in cities.",
462
+ runnable=weather_graph
463
+ )
464
+
465
+ agent = create_agent(
466
+ model="anthropic:claude-sonnet-4-20250514",
467
+ middleware=[
468
+ SubAgentMiddleware(
469
+ default_model="claude-sonnet-4-20250514",
470
+ default_tools=[],
471
+ subagents=[weather_subagent],
472
+ )
473
+ ],
474
+ )
475
+ ```
476
+
477
+ ## Sync vs Async
478
+
479
+ Prior versions of deepagents separated sync and async agent factories.
480
+
481
+ `async_create_deep_agent` has been folded in to `create_deep_agent`.
482
+
483
+ **You should use `create_deep_agent` as the factory for both sync and async agents**
484
+
485
+
486
+ ## MCP
487
+
488
+ 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).
489
+
490
+ **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
491
+
492
+ (To run the example below, will need to `pip install langchain-mcp-adapters`)
493
+
494
+ ```python
495
+ import asyncio
496
+ from langchain_mcp_adapters.client import MultiServerMCPClient
497
+ from deepagents import create_deep_agent
498
+
499
+ async def main():
500
+ # Collect MCP tools
501
+ mcp_client = MultiServerMCPClient(...)
502
+ mcp_tools = await mcp_client.get_tools()
503
+
504
+ # Create agent
505
+ agent = create_deep_agent(tools=mcp_tools, ....)
506
+
507
+ # Stream the agent
508
+ async for chunk in agent.astream(
509
+ {"messages": [{"role": "user", "content": "what is langgraph?"}]},
510
+ stream_mode="values"
511
+ ):
512
+ if "messages" in chunk:
513
+ chunk["messages"][-1].pretty_print()
514
+
515
+ asyncio.run(main())
516
+ ```