Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 11 additions & 21 deletions libs/code/deepagents_code/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Mapping, Sequence

from deepagents import SystemPromptConfig
from deepagents.backends.protocol import BackendProtocol
from deepagents.backends.sandbox import SandboxBackendProtocol
from deepagents.middleware.async_subagents import AsyncSubAgent
Expand Down Expand Up @@ -1855,9 +1854,8 @@ def create_cli_agent(
Passing a value here replaces that auto-generated prompt
entirely — none of the dynamic context above is added, and
`sandbox_type` and `interactive` no longer influence the
prompt. The value is forwarded to the deepagents SDK as-is;
the SDK still layers its built-in base prompt beneath your
text.
prompt. Only pass an explicit prompt when you intend to take
full ownership of the system prompt's content.
interactive: When `False`, the auto-generated system prompt is
tailored for headless non-interactive execution, and every stack
gains terminal-stall recovery middleware (a runtime no-op unless the
Expand Down Expand Up @@ -2357,23 +2355,15 @@ def _subagent_cli_middleware(
if restrictive_shell_allow_list is not None:
agent_middleware.append(ShellAllowListMiddleware(restrictive_shell_allow_list))

# For the auto-generated prompt, overwrite the SDK's built-in base prompt
# (via the `base` key) so its content isn't duplicated on top of ours. A
# caller-supplied prompt is forwarded as-is: the SDK treats a bare string
# as a `prefix`, layering it above its built-in base (see `system_prompt`).
resolved_system_prompt: str | SystemPromptConfig
# Get or use custom system prompt
if system_prompt is None:
resolved_system_prompt = {
"base": get_system_prompt(
assistant_id=assistant_id,
sandbox_type=sandbox_type,
interactive=interactive,
cwd=effective_cwd,
fs_tools=fs_tools,
)
}
else:
resolved_system_prompt = system_prompt
system_prompt = get_system_prompt(
assistant_id=assistant_id,
sandbox_type=sandbox_type,
interactive=interactive,
cwd=effective_cwd,
fs_tools=fs_tools,
)

interrupt_on: dict[str, bool | InterruptOnConfig] | None
if resolved_interrupt_on is None:
Expand Down Expand Up @@ -2540,7 +2530,7 @@ def _subagent_cli_middleware(
_ensure_glm_5p2_profile_registered()
agent = create_deep_agent(
model=model,
system_prompt=resolved_system_prompt,
system_prompt=system_prompt,
tools=tools,
backend=composite_backend,
middleware=agent_middleware,
Expand Down
15 changes: 2 additions & 13 deletions libs/code/tests/unit_tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1819,14 +1819,10 @@ def create_agent(**_kwargs: Any) -> Mock:
mock_create_deep_agent.call_args.kwargs["context_schema"]
is CLIContextSchema
)
# The auto-generated prompt overwrites the SDK base prompt.
assert mock_create_deep_agent.call_args.kwargs["system_prompt"] == {
"base": "mocked prompt"
}
assert call_order == ["register_profile", "create_agent"]

def test_explicit_system_prompt_ignores_interactive(self, tmp_path: Path) -> None:
"""Explicit system_prompt is forwarded verbatim, ignoring interactive."""
"""Explicit system_prompt should be used verbatim, ignoring interactive."""
agent_dir = tmp_path / "agent"
agent_dir.mkdir()
skills_dir = tmp_path / "skills"
Expand Down Expand Up @@ -1857,9 +1853,7 @@ def test_explicit_system_prompt_ignores_interactive(self, tmp_path: Path) -> Non
patch("deepagents_code.agent.settings", mock_settings),
patch("deepagents_code.agent.PluginSkillsMiddleware"),
patch("deepagents_code.agent.MemoryMiddleware"),
patch(
"deepagents_code.agent.create_deep_agent", return_value=mock_agent
) as mock_create_deep_agent,
patch("deepagents_code.agent.create_deep_agent", return_value=mock_agent),
patch(
"deepagents._models.init_chat_model",
return_value=fake_model,
Expand All @@ -1879,11 +1873,6 @@ def test_explicit_system_prompt_ignores_interactive(self, tmp_path: Path) -> Non

# get_system_prompt should NOT be called when system_prompt is provided
mock_get_prompt.assert_not_called()
# A caller-supplied prompt is forwarded verbatim (SDK treats it as a
# prefix), unlike the auto-generated prompt which overwrites the base.
assert (
mock_create_deep_agent.call_args.kwargs["system_prompt"] == "custom prompt"
)


class TestDefaultAgentName:
Expand Down
2 changes: 0 additions & 2 deletions libs/deepagents/deepagents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from deepagents.graph import (
BASE_AGENT_PROMPT,
DeepAgentState,
SystemPromptConfig,
create_deep_agent,
)
from deepagents.middleware.async_subagents import AsyncSubAgent, AsyncSubAgentMiddleware
Expand Down Expand Up @@ -44,7 +43,6 @@
"RubricMiddleware",
"SubAgent",
"SubAgentMiddleware",
"SystemPromptConfig",
"__version__",
"create_deep_agent",
"register_harness_profile",
Expand Down
160 changes: 60 additions & 100 deletions libs/deepagents/deepagents/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import logging
from collections.abc import Callable, Sequence
from typing import Annotated, Any, Required, TypedDict, cast
from typing import Annotated, Any, Required, cast

from langchain.agents import AgentState, create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware, InterruptOnConfig, TodoListMiddleware
Expand Down Expand Up @@ -116,69 +116,37 @@ class DeepAgentState(AgentState):
## Progress Updates

For longer tasks, provide brief progress updates at reasonable intervals — a concise sentence recapping what you've done and what's next.""" # noqa: E501


class SystemPromptConfig(TypedDict, total=False):
"""Structured `system_prompt` for `create_deep_agent`.

All keys are optional. Each accepts a `str` or a `SystemMessage` (to
carry explicit `cache_control` markers).
"""

prefix: str | SystemMessage | None
"""Text placed before the base prompt."""

base: str | SystemMessage | None
"""Replacement for the active profile base prompt.

Omit the key to keep the active `HarnessProfile.base_system_prompt`, if
any. Set it to `None` to drop the base entirely, leaving only `prefix`,
`suffix`, and middleware-contributed content.
"""

suffix: str | SystemMessage | None
"""Text placed after the base prompt."""


_PROMPT_SEPARATOR = "\n\n"


def _assemble_prompt_parts(parts: list[str | SystemMessage]) -> str | SystemMessage:
r"""Join prompt parts into a single `str` or `SystemMessage`.

All-`str` parts join with blank lines. If any part is a `SystemMessage`,
the result is a `SystemMessage` whose `content_blocks` concatenate each
part's blocks with `\\n\\n` separators, preserving `cache_control` markers.
"""
if not parts:
return ""
if all(isinstance(part, str) for part in parts):
return _PROMPT_SEPARATOR.join(cast("list[str]", parts))
blocks: list[Any] = []
for i, part in enumerate(parts):
if i:
blocks.append({"type": "text", "text": _PROMPT_SEPARATOR})
if isinstance(part, SystemMessage):
blocks.extend(part.content_blocks)
else:
blocks.append({"type": "text", "text": part})
return SystemMessage(content_blocks=blocks)


def _normalize_system_prompt(
system_prompt: str | SystemMessage | SystemPromptConfig | None,
) -> SystemPromptConfig:
"""Coerce the `system_prompt` argument into a `SystemPromptConfig`.

`None` becomes an empty config; a bare `str`/`SystemMessage` becomes a
`prefix` (matching the pre-config behavior of placing caller text before
the base); a config dict is returned unchanged.
"""
if system_prompt is None:
return {}
if isinstance(system_prompt, (str, SystemMessage)):
return {"prefix": system_prompt}
return system_prompt
"""Default base system prompt for every deep agent (`BASE`).

The final system prompt sent to the model is composed from up to four
named parts:

- `USER` — the `system_prompt=` argument to `create_deep_agent` (`str` or
`SystemMessage`); when unset, no `USER` segment is included.
- `BASE` — this constant.
Comment thread
ccurme marked this conversation as resolved.
Resolved
- `CUSTOM` — `HarnessProfile.base_system_prompt`. When set on a matching
profile, replaces `BASE` outright; when unset, `BASE` is used.
- `SUFFIX` — `HarnessProfile.system_prompt_suffix`. When set on a
matching profile, appended last; when unset, no `SUFFIX` segment is
included.

The order is always `USER` -> (`BASE` or `CUSTOM`) -> `SUFFIX`, joined by
blank lines (`\\n\\n`). Two invariants follow:

1. `USER` is always at the front, so caller instructions take precedence
over SDK and profile content regardless of which model is selected.
2. `SUFFIX` is always at the end, so model-tuning guidance sits closest
to the conversation history (where the model attends most).

When `USER` is a `SystemMessage`, the right-hand assembly is appended as
an additional text content block onto the message's existing
`content_blocks` list, preserving any `cache_control` markers the caller
set.

See `create_deep_agent`'s `system_prompt` parameter or
[Prompt assembly](https://docs.langchain.com/oss/deepagents/customization#prompt-assembly)
for the full assembly order.
"""
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved


def _build_default_model() -> ChatAnthropic:
Expand Down Expand Up @@ -313,7 +281,7 @@ def create_deep_agent( # noqa: C901, PLR0912, PLR0915 # Complex graph assembly
model: str | BaseChatModel | None = None,
tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
*,
system_prompt: str | SystemMessage | SystemPromptConfig | None = None,
system_prompt: str | SystemMessage | None = None,
middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),
subagents: Sequence[SubAgent | CompiledSubAgent | AsyncSubAgent] | None = None,
skills: list[str] | None = None,
Expand Down Expand Up @@ -382,24 +350,23 @@ def create_deep_agent( # noqa: C901, PLR0912, PLR0915 # Complex graph assembly
To drop a built-in tool, register a
[`HarnessProfile`][deepagents.HarnessProfile] with
`excluded_tools`.
system_prompt: Custom system instructions.

A `str` or `SystemMessage` is placed at the front of the system
prompt, before any base or model-tuning suffix from a registered
`HarnessProfile`.

For more control, pass a
[`SystemPromptConfig`][deepagents.SystemPromptConfig] with any of:

- `prefix`: text before the base (same as passing a bare string).
- `base`: replace the profile base prompt; omit the key to keep
it, or set it to `None` to drop the base entirely.
- `suffix`: text after the base (before any profile suffix).

The assembly order is `prefix` -> `base` -> `suffix` ->
profile suffix, joined by blank lines. Any part may be a
`SystemMessage` to preserve `cache_control` markers; the result is
then a `SystemMessage` whose content blocks are concatenated.
system_prompt: Custom system instructions placed at the front of
the system prompt sent to the model.

Whatever you pass here always sits before the SDK's default
deep-agent prompt and any model-tuning suffix from a
registered `HarnessProfile`. With `system_prompt=None`, the
SDK default is used on its own (plus the profile suffix
when one applies). Sections are joined by a blank line.

Passing a `SystemMessage` instead of a string preserves any
`cache_control` markers on the message's content blocks —
useful for placing explicit Anthropic prompt-cache
breakpoints. The same ordering applies (caller's blocks
first, SDK content appended as an additional text block).

See [Prompt assembly](https://docs.langchain.com/oss/deepagents/customization#prompt-assembly)
for the full case-by-case breakdown.
middleware: Additional middleware to apply after the base stack
but before the tail middleware. The full ordering is:

Expand Down Expand Up @@ -955,23 +922,16 @@ class MyState(DeepAgentState):
required_names=_REQUIRED_MIDDLEWARE_NAMES,
)

# Assemble the main-agent prompt: prefix -> base -> suffix -> profile suffix.
# The config's `base` (when the key is present) overrides the profile base.
cfg = _normalize_system_prompt(system_prompt)
prompt_parts: list[str | SystemMessage] = []
prefix = cfg.get("prefix")
if prefix is not None:
prompt_parts.append(prefix)
profile_base = _profile.base_system_prompt
base = cfg.get("base", profile_base)
if base is not None:
prompt_parts.append(base)
suffix = cfg.get("suffix")
if suffix is not None:
prompt_parts.append(suffix)
if _profile.system_prompt_suffix is not None:
prompt_parts.append(_profile.system_prompt_suffix)
final_system_prompt: str | SystemMessage = _assemble_prompt_parts(prompt_parts)
base_prompt = _apply_profile_prompt(_profile, "")
if system_prompt is None:
final_system_prompt: str | SystemMessage = base_prompt
elif isinstance(system_prompt, SystemMessage):
if base_prompt:
final_system_prompt = SystemMessage(content_blocks=[*system_prompt.content_blocks, {"type": "text", "text": f"\n\n{base_prompt}"}])
else:
final_system_prompt = system_prompt
else:
final_system_prompt = system_prompt + (f"\n\n{base_prompt}" if base_prompt else "")

return create_agent(
model,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -798,7 +798,7 @@ def _apply_profile_prompt(profile: HarnessProfile, base_prompt: str) -> str:
"""
prompt = profile.base_system_prompt if profile.base_system_prompt is not None else base_prompt
if profile.system_prompt_suffix is not None:
prompt = prompt + "\n\n" + profile.system_prompt_suffix
prompt = prompt + "\n\n" + profile.system_prompt_suffix if prompt else profile.system_prompt_suffix
return prompt


Expand Down
Loading