deepagents-cli 0.0.2__py3-none-any.whl → 0.0.4__py3-none-any.whl
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.
Potentially problematic release.
This version of deepagents-cli might be problematic. Click here for more details.
- deepagents_cli/__init__.py +5 -0
- deepagents_cli/__main__.py +6 -0
- deepagents_cli/agent.py +267 -0
- deepagents_cli/cli.py +13 -0
- deepagents_cli/commands.py +86 -0
- deepagents_cli/config.py +138 -0
- deepagents_cli/execution.py +644 -0
- deepagents_cli/file_ops.py +347 -0
- deepagents_cli/input.py +249 -0
- deepagents_cli/main.py +217 -0
- deepagents_cli/py.typed +0 -0
- deepagents_cli/tools.py +140 -0
- deepagents_cli/ui.py +455 -0
- deepagents_cli-0.0.4.dist-info/METADATA +18 -0
- deepagents_cli-0.0.4.dist-info/RECORD +18 -0
- deepagents_cli-0.0.4.dist-info/entry_points.txt +3 -0
- deepagents_cli-0.0.4.dist-info/top_level.txt +1 -0
- deepagents/__init__.py +0 -18
- deepagents/cli.py +0 -588
- deepagents/default_agent_prompt.md +0 -94
- deepagents/graph.py +0 -168
- deepagents/middleware/__init__.py +0 -13
- deepagents/middleware/common.py +0 -16
- deepagents/middleware/filesystem.py +0 -1159
- deepagents/middleware/local_filesystem.py +0 -741
- deepagents/middleware/subagents.py +0 -480
- deepagents/prompts.py +0 -327
- deepagents/skills.py +0 -85
- deepagents_cli-0.0.2.dist-info/METADATA +0 -555
- deepagents_cli-0.0.2.dist-info/RECORD +0 -17
- deepagents_cli-0.0.2.dist-info/entry_points.txt +0 -2
- deepagents_cli-0.0.2.dist-info/licenses/LICENSE +0 -21
- deepagents_cli-0.0.2.dist-info/top_level.txt +0 -1
- {deepagents_cli-0.0.2.dist-info → deepagents_cli-0.0.4.dist-info}/WHEEL +0 -0
|
@@ -1,480 +0,0 @@
|
|
|
1
|
-
"""Middleware for providing subagents to an agent via a `task` tool."""
|
|
2
|
-
|
|
3
|
-
from collections.abc import Awaitable, Callable, Sequence
|
|
4
|
-
from typing import Any, TypedDict, cast
|
|
5
|
-
from typing_extensions import NotRequired
|
|
6
|
-
|
|
7
|
-
from langchain.agents import create_agent
|
|
8
|
-
from langchain.agents.middleware import HumanInTheLoopMiddleware, InterruptOnConfig
|
|
9
|
-
from langchain.agents.middleware.types import AgentMiddleware, ModelRequest, ModelResponse
|
|
10
|
-
from langchain.tools import BaseTool, ToolRuntime
|
|
11
|
-
from langchain_core.language_models import BaseChatModel
|
|
12
|
-
from langchain_core.messages import HumanMessage, ToolMessage
|
|
13
|
-
from langchain_core.runnables import Runnable
|
|
14
|
-
from langchain_core.tools import StructuredTool
|
|
15
|
-
from langgraph.types import Command
|
|
16
|
-
|
|
17
|
-
try:
|
|
18
|
-
from langchain_anthropic.middleware.prompt_caching import AnthropicPromptCachingMiddleware
|
|
19
|
-
except ImportError:
|
|
20
|
-
AnthropicPromptCachingMiddleware = None
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
class SubAgent(TypedDict):
|
|
24
|
-
"""Specification for an agent.
|
|
25
|
-
|
|
26
|
-
When specifying custom agents, the `default_middleware` from `SubAgentMiddleware`
|
|
27
|
-
will be applied first, followed by any `middleware` specified in this spec.
|
|
28
|
-
To use only custom middleware without the defaults, pass `default_middleware=[]`
|
|
29
|
-
to `SubAgentMiddleware`.
|
|
30
|
-
"""
|
|
31
|
-
|
|
32
|
-
name: str
|
|
33
|
-
"""The name of the agent."""
|
|
34
|
-
|
|
35
|
-
description: str
|
|
36
|
-
"""The description of the agent."""
|
|
37
|
-
|
|
38
|
-
system_prompt: str
|
|
39
|
-
"""The system prompt to use for the agent."""
|
|
40
|
-
|
|
41
|
-
tools: Sequence[BaseTool | Callable | dict[str, Any]]
|
|
42
|
-
"""The tools to use for the agent."""
|
|
43
|
-
|
|
44
|
-
model: NotRequired[str | BaseChatModel]
|
|
45
|
-
"""The model for the agent. Defaults to `default_model`."""
|
|
46
|
-
|
|
47
|
-
middleware: NotRequired[list[AgentMiddleware]]
|
|
48
|
-
"""Additional middleware to append after `default_middleware`."""
|
|
49
|
-
|
|
50
|
-
interrupt_on: NotRequired[dict[str, bool | InterruptOnConfig]]
|
|
51
|
-
"""The tool configs to use for the agent."""
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
class CompiledSubAgent(TypedDict):
|
|
55
|
-
"""A pre-compiled agent spec."""
|
|
56
|
-
|
|
57
|
-
name: str
|
|
58
|
-
"""The name of the agent."""
|
|
59
|
-
|
|
60
|
-
description: str
|
|
61
|
-
"""The description of the agent."""
|
|
62
|
-
|
|
63
|
-
runnable: Runnable
|
|
64
|
-
"""The Runnable to use for the agent."""
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools."
|
|
68
|
-
|
|
69
|
-
# State keys that should be excluded when passing state to subagents
|
|
70
|
-
_EXCLUDED_STATE_KEYS = ("messages", "todos")
|
|
71
|
-
|
|
72
|
-
TASK_TOOL_DESCRIPTION = """Launch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.
|
|
73
|
-
|
|
74
|
-
Available agent types and the tools they have access to:
|
|
75
|
-
{available_agents}
|
|
76
|
-
|
|
77
|
-
When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
78
|
-
|
|
79
|
-
## Usage notes:
|
|
80
|
-
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
|
|
81
|
-
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.
|
|
82
|
-
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.
|
|
83
|
-
4. The agent's outputs should generally be trusted
|
|
84
|
-
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
|
|
85
|
-
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.
|
|
86
|
-
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.
|
|
87
|
-
|
|
88
|
-
### Example usage of the general-purpose agent:
|
|
89
|
-
|
|
90
|
-
<example_agent_descriptions>
|
|
91
|
-
"general-purpose": use this agent for general purpose tasks, it has access to all tools as the main agent.
|
|
92
|
-
</example_agent_descriptions>
|
|
93
|
-
|
|
94
|
-
<example>
|
|
95
|
-
User: "I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them."
|
|
96
|
-
Assistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*
|
|
97
|
-
Assistant: *Synthesizes the results of the three isolated research tasks and responds to the User*
|
|
98
|
-
<commentary>
|
|
99
|
-
Research is a complex, multi-step task in it of itself.
|
|
100
|
-
The research of each individual player is not dependent on the research of the other players.
|
|
101
|
-
The assistant uses the task tool to break down the complex objective into three isolated tasks.
|
|
102
|
-
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.
|
|
103
|
-
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.
|
|
104
|
-
</commentary>
|
|
105
|
-
</example>
|
|
106
|
-
|
|
107
|
-
<example>
|
|
108
|
-
User: "Analyze a single large code repository for security vulnerabilities and generate a report."
|
|
109
|
-
Assistant: *Launches a single `task` subagent for the repository analysis*
|
|
110
|
-
Assistant: *Receives report and integrates results into final summary*
|
|
111
|
-
<commentary>
|
|
112
|
-
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.
|
|
113
|
-
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.
|
|
114
|
-
</commentary>
|
|
115
|
-
</example>
|
|
116
|
-
|
|
117
|
-
<example>
|
|
118
|
-
User: "Schedule two meetings for me and prepare agendas for each."
|
|
119
|
-
Assistant: *Calls the task tool in parallel to launch two `task` subagents (one per meeting) to prepare agendas*
|
|
120
|
-
Assistant: *Returns final schedules and agendas*
|
|
121
|
-
<commentary>
|
|
122
|
-
Tasks are simple individually, but subagents help silo agenda preparation.
|
|
123
|
-
Each subagent only needs to worry about the agenda for one meeting.
|
|
124
|
-
</commentary>
|
|
125
|
-
</example>
|
|
126
|
-
|
|
127
|
-
<example>
|
|
128
|
-
User: "I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway."
|
|
129
|
-
Assistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*
|
|
130
|
-
<commentary>
|
|
131
|
-
The assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.
|
|
132
|
-
It is better to just complete the task directly and NOT use the `task`tool.
|
|
133
|
-
</commentary>
|
|
134
|
-
</example>
|
|
135
|
-
|
|
136
|
-
### Example usage with custom agents:
|
|
137
|
-
|
|
138
|
-
<example_agent_descriptions>
|
|
139
|
-
"content-reviewer": use this agent after you are done creating significant content or documents
|
|
140
|
-
"greeting-responder": use this agent when to respond to user greetings with a friendly joke
|
|
141
|
-
"research-analyst": use this agent to conduct thorough research on complex topics
|
|
142
|
-
</example_agent_description>
|
|
143
|
-
|
|
144
|
-
<example>
|
|
145
|
-
user: "Please write a function that checks if a number is prime"
|
|
146
|
-
assistant: Sure let me write a function that checks if a number is prime
|
|
147
|
-
assistant: First let me use the Write tool to write a function that checks if a number is prime
|
|
148
|
-
assistant: I'm going to use the Write tool to write the following code:
|
|
149
|
-
<code>
|
|
150
|
-
function isPrime(n) {{
|
|
151
|
-
if (n <= 1) return false
|
|
152
|
-
for (let i = 2; i * i <= n; i++) {{
|
|
153
|
-
if (n % i === 0) return false
|
|
154
|
-
}}
|
|
155
|
-
return true
|
|
156
|
-
}}
|
|
157
|
-
</code>
|
|
158
|
-
<commentary>
|
|
159
|
-
Since significant content was created and the task was completed, now use the content-reviewer agent to review the work
|
|
160
|
-
</commentary>
|
|
161
|
-
assistant: Now let me use the content-reviewer agent to review the code
|
|
162
|
-
assistant: Uses the Task tool to launch with the content-reviewer agent
|
|
163
|
-
</example>
|
|
164
|
-
|
|
165
|
-
<example>
|
|
166
|
-
user: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?"
|
|
167
|
-
<commentary>
|
|
168
|
-
This is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis
|
|
169
|
-
</commentary>
|
|
170
|
-
assistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.
|
|
171
|
-
assistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take
|
|
172
|
-
</example>
|
|
173
|
-
|
|
174
|
-
<example>
|
|
175
|
-
user: "Hello"
|
|
176
|
-
<commentary>
|
|
177
|
-
Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
|
|
178
|
-
</commentary>
|
|
179
|
-
assistant: "I'm going to use the Task tool to launch with the greeting-responder agent"
|
|
180
|
-
</example>""" # noqa: E501
|
|
181
|
-
|
|
182
|
-
TASK_SYSTEM_PROMPT = """## `task` (subagent spawner)
|
|
183
|
-
|
|
184
|
-
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.
|
|
185
|
-
|
|
186
|
-
When to use the task tool:
|
|
187
|
-
- When a task is complex and multi-step, and can be fully delegated in isolation
|
|
188
|
-
- When a task is independent of other tasks and can run in parallel
|
|
189
|
-
- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread
|
|
190
|
-
- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)
|
|
191
|
-
- 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.)
|
|
192
|
-
|
|
193
|
-
Subagent lifecycle:
|
|
194
|
-
1. **Spawn** → Provide clear role, instructions, and expected output
|
|
195
|
-
2. **Run** → The subagent completes the task autonomously
|
|
196
|
-
3. **Return** → The subagent provides a single structured result
|
|
197
|
-
4. **Reconcile** → Incorporate or synthesize the result into the main thread
|
|
198
|
-
|
|
199
|
-
When NOT to use the task tool:
|
|
200
|
-
- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)
|
|
201
|
-
- If the task is trivial (a few tool calls or simple lookup)
|
|
202
|
-
- If delegating does not reduce token usage, complexity, or context switching
|
|
203
|
-
- If splitting would add latency without benefit
|
|
204
|
-
|
|
205
|
-
## Important Task Tool Usage Notes to Remember
|
|
206
|
-
- 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.
|
|
207
|
-
- Remember to use the `task` tool to silo independent tasks within a multi-part objective.
|
|
208
|
-
- 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.""" # noqa: E501
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "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." # noqa: E501
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
def _get_subagents(
|
|
215
|
-
*,
|
|
216
|
-
default_model: str | BaseChatModel,
|
|
217
|
-
default_tools: Sequence[BaseTool | Callable | dict[str, Any]],
|
|
218
|
-
default_middleware: list[AgentMiddleware] | None,
|
|
219
|
-
default_interrupt_on: dict[str, bool | InterruptOnConfig] | None,
|
|
220
|
-
subagents: list[SubAgent | CompiledSubAgent],
|
|
221
|
-
general_purpose_agent: bool,
|
|
222
|
-
) -> tuple[dict[str, Any], list[str]]:
|
|
223
|
-
"""Create subagent instances from specifications.
|
|
224
|
-
|
|
225
|
-
Args:
|
|
226
|
-
default_model: Default model for subagents that don't specify one.
|
|
227
|
-
default_tools: Default tools for subagents that don't specify tools.
|
|
228
|
-
default_middleware: Middleware to apply to all subagents. If `None`,
|
|
229
|
-
no default middleware is applied.
|
|
230
|
-
default_interrupt_on: The tool configs to use for the default general-purpose subagent. These
|
|
231
|
-
are also the fallback for any subagents that don't specify their own tool configs.
|
|
232
|
-
subagents: List of agent specifications or pre-compiled agents.
|
|
233
|
-
general_purpose_agent: Whether to include a general-purpose subagent.
|
|
234
|
-
|
|
235
|
-
Returns:
|
|
236
|
-
Tuple of (agent_dict, description_list) where agent_dict maps agent names
|
|
237
|
-
to runnable instances and description_list contains formatted descriptions.
|
|
238
|
-
"""
|
|
239
|
-
# Use empty list if None (no default middleware)
|
|
240
|
-
default_subagent_middleware = default_middleware or []
|
|
241
|
-
|
|
242
|
-
agents: dict[str, Any] = {}
|
|
243
|
-
subagent_descriptions = []
|
|
244
|
-
|
|
245
|
-
# Create general-purpose agent if enabled
|
|
246
|
-
if general_purpose_agent:
|
|
247
|
-
general_purpose_middleware = [*default_subagent_middleware]
|
|
248
|
-
if default_interrupt_on:
|
|
249
|
-
general_purpose_middleware.append(HumanInTheLoopMiddleware(interrupt_on=default_interrupt_on))
|
|
250
|
-
general_purpose_subagent = create_agent(
|
|
251
|
-
default_model,
|
|
252
|
-
system_prompt=DEFAULT_SUBAGENT_PROMPT,
|
|
253
|
-
tools=default_tools,
|
|
254
|
-
middleware=general_purpose_middleware,
|
|
255
|
-
)
|
|
256
|
-
agents["general-purpose"] = general_purpose_subagent
|
|
257
|
-
subagent_descriptions.append(f"- general-purpose: {DEFAULT_GENERAL_PURPOSE_DESCRIPTION}")
|
|
258
|
-
|
|
259
|
-
# Process custom subagents
|
|
260
|
-
for agent_ in subagents:
|
|
261
|
-
subagent_descriptions.append(f"- {agent_['name']}: {agent_['description']}")
|
|
262
|
-
if "runnable" in agent_:
|
|
263
|
-
custom_agent = cast("CompiledSubAgent", agent_)
|
|
264
|
-
agents[custom_agent["name"]] = custom_agent["runnable"]
|
|
265
|
-
continue
|
|
266
|
-
_tools = agent_.get("tools", list(default_tools))
|
|
267
|
-
|
|
268
|
-
subagent_model = agent_.get("model", default_model)
|
|
269
|
-
|
|
270
|
-
_middleware = [*default_subagent_middleware, *agent_["middleware"]] if "middleware" in agent_ else default_subagent_middleware
|
|
271
|
-
|
|
272
|
-
interrupt_on = agent_.get("interrupt_on", default_interrupt_on)
|
|
273
|
-
if interrupt_on:
|
|
274
|
-
_middleware.append(HumanInTheLoopMiddleware(interrupt_on=interrupt_on))
|
|
275
|
-
|
|
276
|
-
agents[agent_["name"]] = create_agent(
|
|
277
|
-
subagent_model,
|
|
278
|
-
system_prompt=agent_["system_prompt"],
|
|
279
|
-
tools=_tools,
|
|
280
|
-
middleware=_middleware,
|
|
281
|
-
checkpointer=False,
|
|
282
|
-
)
|
|
283
|
-
return agents, subagent_descriptions
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
def _create_task_tool(
|
|
287
|
-
*,
|
|
288
|
-
default_model: str | BaseChatModel,
|
|
289
|
-
default_tools: Sequence[BaseTool | Callable | dict[str, Any]],
|
|
290
|
-
default_middleware: list[AgentMiddleware] | None,
|
|
291
|
-
default_interrupt_on: dict[str, bool | InterruptOnConfig] | None,
|
|
292
|
-
subagents: list[SubAgent | CompiledSubAgent],
|
|
293
|
-
general_purpose_agent: bool,
|
|
294
|
-
task_description: str | None = None,
|
|
295
|
-
) -> BaseTool:
|
|
296
|
-
"""Create a task tool for invoking subagents.
|
|
297
|
-
|
|
298
|
-
Args:
|
|
299
|
-
default_model: Default model for subagents.
|
|
300
|
-
default_tools: Default tools for subagents.
|
|
301
|
-
default_middleware: Middleware to apply to all subagents.
|
|
302
|
-
default_interrupt_on: The tool configs to use for the default general-purpose subagent. These
|
|
303
|
-
are also the fallback for any subagents that don't specify their own tool configs.
|
|
304
|
-
subagents: List of subagent specifications.
|
|
305
|
-
general_purpose_agent: Whether to include general-purpose agent.
|
|
306
|
-
task_description: Custom description for the task tool. If `None`,
|
|
307
|
-
uses default template. Supports `{available_agents}` placeholder.
|
|
308
|
-
|
|
309
|
-
Returns:
|
|
310
|
-
A StructuredTool that can invoke subagents by type.
|
|
311
|
-
"""
|
|
312
|
-
subagent_graphs, subagent_descriptions = _get_subagents(
|
|
313
|
-
default_model=default_model,
|
|
314
|
-
default_tools=default_tools,
|
|
315
|
-
default_middleware=default_middleware,
|
|
316
|
-
default_interrupt_on=default_interrupt_on,
|
|
317
|
-
subagents=subagents,
|
|
318
|
-
general_purpose_agent=general_purpose_agent,
|
|
319
|
-
)
|
|
320
|
-
subagent_description_str = "\n".join(subagent_descriptions)
|
|
321
|
-
|
|
322
|
-
def _return_command_with_state_update(result: dict, tool_call_id: str) -> Command:
|
|
323
|
-
state_update = {k: v for k, v in result.items() if k not in _EXCLUDED_STATE_KEYS}
|
|
324
|
-
return Command(
|
|
325
|
-
update={
|
|
326
|
-
**state_update,
|
|
327
|
-
"messages": [ToolMessage(result["messages"][-1].content, tool_call_id=tool_call_id)],
|
|
328
|
-
}
|
|
329
|
-
)
|
|
330
|
-
|
|
331
|
-
def _validate_and_prepare_state(subagent_type: str, description: str, runtime: ToolRuntime) -> tuple[Runnable, dict]:
|
|
332
|
-
"""Validate subagent type and prepare state for invocation."""
|
|
333
|
-
if subagent_type not in subagent_graphs:
|
|
334
|
-
msg = f"Error: invoked agent of type {subagent_type}, the only allowed types are {[f'`{k}`' for k in subagent_graphs]}"
|
|
335
|
-
raise ValueError(msg)
|
|
336
|
-
subagent = subagent_graphs[subagent_type]
|
|
337
|
-
# Create a new state dict to avoid mutating the original
|
|
338
|
-
subagent_state = {k: v for k, v in runtime.state.items() if k not in _EXCLUDED_STATE_KEYS}
|
|
339
|
-
subagent_state["messages"] = [HumanMessage(content=description)]
|
|
340
|
-
return subagent, subagent_state
|
|
341
|
-
|
|
342
|
-
# Use custom description if provided, otherwise use default template
|
|
343
|
-
if task_description is None:
|
|
344
|
-
task_description = TASK_TOOL_DESCRIPTION.format(available_agents=subagent_description_str)
|
|
345
|
-
elif "{available_agents}" in task_description:
|
|
346
|
-
# If custom description has placeholder, format with agent descriptions
|
|
347
|
-
task_description = task_description.format(available_agents=subagent_description_str)
|
|
348
|
-
|
|
349
|
-
def task(
|
|
350
|
-
description: str,
|
|
351
|
-
subagent_type: str,
|
|
352
|
-
runtime: ToolRuntime,
|
|
353
|
-
) -> str | Command:
|
|
354
|
-
subagent, subagent_state = _validate_and_prepare_state(subagent_type, description, runtime)
|
|
355
|
-
result = subagent.invoke(subagent_state)
|
|
356
|
-
return _return_command_with_state_update(result, runtime.tool_call_id)
|
|
357
|
-
|
|
358
|
-
async def atask(
|
|
359
|
-
description: str,
|
|
360
|
-
subagent_type: str,
|
|
361
|
-
runtime: ToolRuntime,
|
|
362
|
-
) -> str | Command:
|
|
363
|
-
subagent, subagent_state = _validate_and_prepare_state(subagent_type, description, runtime)
|
|
364
|
-
result = await subagent.ainvoke(subagent_state)
|
|
365
|
-
return _return_command_with_state_update(result, runtime.tool_call_id)
|
|
366
|
-
|
|
367
|
-
return StructuredTool.from_function(
|
|
368
|
-
name="task",
|
|
369
|
-
func=task,
|
|
370
|
-
coroutine=atask,
|
|
371
|
-
description=task_description,
|
|
372
|
-
)
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
class SubAgentMiddleware(AgentMiddleware):
|
|
376
|
-
"""Middleware for providing subagents to an agent via a `task` tool.
|
|
377
|
-
|
|
378
|
-
This middleware adds a `task` tool to the agent that can be used to invoke subagents.
|
|
379
|
-
Subagents are useful for handling complex tasks that require multiple steps, or tasks
|
|
380
|
-
that require a lot of context to resolve.
|
|
381
|
-
|
|
382
|
-
A chief benefit of subagents is that they can handle multi-step tasks, and then return
|
|
383
|
-
a clean, concise response to the main agent.
|
|
384
|
-
|
|
385
|
-
Subagents are also great for different domains of expertise that require a narrower
|
|
386
|
-
subset of tools and focus.
|
|
387
|
-
|
|
388
|
-
This middleware comes with a default general-purpose subagent that can be used to
|
|
389
|
-
handle the same tasks as the main agent, but with isolated context.
|
|
390
|
-
|
|
391
|
-
Args:
|
|
392
|
-
default_model: The model to use for subagents.
|
|
393
|
-
Can be a LanguageModelLike or a dict for init_chat_model.
|
|
394
|
-
default_tools: The tools to use for the default general-purpose subagent.
|
|
395
|
-
default_middleware: Default middleware to apply to all subagents. If `None` (default),
|
|
396
|
-
no default middleware is applied. Pass a list to specify custom middleware.
|
|
397
|
-
default_interrupt_on: The tool configs to use for the default general-purpose subagent. These
|
|
398
|
-
are also the fallback for any subagents that don't specify their own tool configs.
|
|
399
|
-
subagents: A list of additional subagents to provide to the agent.
|
|
400
|
-
system_prompt: Full system prompt override. When provided, completely replaces
|
|
401
|
-
the agent's system prompt.
|
|
402
|
-
general_purpose_agent: Whether to include the general-purpose agent. Defaults to `True`.
|
|
403
|
-
task_description: Custom description for the task tool. If `None`, uses the
|
|
404
|
-
default description template.
|
|
405
|
-
|
|
406
|
-
Example:
|
|
407
|
-
```python
|
|
408
|
-
from langchain.agents.middleware.subagents import SubAgentMiddleware
|
|
409
|
-
from langchain.agents import create_agent
|
|
410
|
-
|
|
411
|
-
# Basic usage with defaults (no default middleware)
|
|
412
|
-
agent = create_agent(
|
|
413
|
-
"openai:gpt-4o",
|
|
414
|
-
middleware=[
|
|
415
|
-
SubAgentMiddleware(
|
|
416
|
-
default_model="openai:gpt-4o",
|
|
417
|
-
subagents=[],
|
|
418
|
-
)
|
|
419
|
-
],
|
|
420
|
-
)
|
|
421
|
-
|
|
422
|
-
# Add custom middleware to subagents
|
|
423
|
-
agent = create_agent(
|
|
424
|
-
"openai:gpt-4o",
|
|
425
|
-
middleware=[
|
|
426
|
-
SubAgentMiddleware(
|
|
427
|
-
default_model="openai:gpt-4o",
|
|
428
|
-
default_middleware=[TodoListMiddleware()],
|
|
429
|
-
subagents=[],
|
|
430
|
-
)
|
|
431
|
-
],
|
|
432
|
-
)
|
|
433
|
-
```
|
|
434
|
-
"""
|
|
435
|
-
|
|
436
|
-
def __init__(
|
|
437
|
-
self,
|
|
438
|
-
*,
|
|
439
|
-
default_model: str | BaseChatModel,
|
|
440
|
-
default_tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
|
|
441
|
-
default_middleware: list[AgentMiddleware] | None = None,
|
|
442
|
-
default_interrupt_on: dict[str, bool | InterruptOnConfig] | None = None,
|
|
443
|
-
subagents: list[SubAgent | CompiledSubAgent] | None = None,
|
|
444
|
-
system_prompt: str | None = TASK_SYSTEM_PROMPT,
|
|
445
|
-
general_purpose_agent: bool = True,
|
|
446
|
-
task_description: str | None = None,
|
|
447
|
-
) -> None:
|
|
448
|
-
"""Initialize the SubAgentMiddleware."""
|
|
449
|
-
super().__init__()
|
|
450
|
-
self.system_prompt = system_prompt
|
|
451
|
-
task_tool = _create_task_tool(
|
|
452
|
-
default_model=default_model,
|
|
453
|
-
default_tools=default_tools or [],
|
|
454
|
-
default_middleware=default_middleware,
|
|
455
|
-
default_interrupt_on=default_interrupt_on,
|
|
456
|
-
subagents=subagents or [],
|
|
457
|
-
general_purpose_agent=general_purpose_agent,
|
|
458
|
-
task_description=task_description,
|
|
459
|
-
)
|
|
460
|
-
self.tools = [task_tool]
|
|
461
|
-
|
|
462
|
-
def wrap_model_call(
|
|
463
|
-
self,
|
|
464
|
-
request: ModelRequest,
|
|
465
|
-
handler: Callable[[ModelRequest], ModelResponse],
|
|
466
|
-
) -> ModelResponse:
|
|
467
|
-
"""Update the system prompt to include instructions on using subagents."""
|
|
468
|
-
if self.system_prompt is not None:
|
|
469
|
-
request.system_prompt = request.system_prompt + "\n\n" + self.system_prompt if request.system_prompt else self.system_prompt
|
|
470
|
-
return handler(request)
|
|
471
|
-
|
|
472
|
-
async def awrap_model_call(
|
|
473
|
-
self,
|
|
474
|
-
request: ModelRequest,
|
|
475
|
-
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
476
|
-
) -> ModelResponse:
|
|
477
|
-
"""(async) Update the system prompt to include instructions on using subagents."""
|
|
478
|
-
if self.system_prompt is not None:
|
|
479
|
-
request.system_prompt = request.system_prompt + "\n\n" + self.system_prompt if request.system_prompt else self.system_prompt
|
|
480
|
-
return await handler(request)
|