mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 00:50:36 +08:00
When a tools snapshot goes away (a session stored before native requests dropped the text manifest, or the turn after a schema-rejection fallback), the generic retraction said the section is now empty, which reads as "no tools" while the request carries native schemas. The tools snapshot now gets its own retraction text, in the Python loop and the TypeScript engine. Refs #2973
397 lines
18 KiB
Python
397 lines
18 KiB
Python
"""Structured prompt assembly for the agent loop.
|
|
|
|
The block list is the seam every loop customises. :class:`LoopPromptAssembler`
|
|
owns the *shared* half — the turn's runtime context, the user's own material
|
|
(memory, sources, notebooks), the tool manifest — and states the foundation
|
|
blocks (who the assistant is, and what a round of this loop means) through
|
|
:meth:`foundation_blocks`, which is where a loop that is not chat differs.
|
|
|
|
Chat's foundation is "you are DeepTutor, here is the exploring-loop protocol".
|
|
A tutoring loop's foundation is its own playbook, and it says so as the first
|
|
thing the model reads rather than as an addendum to chat's.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from deeptutor.capabilities.protocol import PromptBlock
|
|
from deeptutor.core.context import UnifiedContext
|
|
from deeptutor.runtime.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
|
|
from deeptutor.services.prompt.language import append_language_directive
|
|
|
|
# The text tool list. Native requests omit it; a schema rejection restores it.
|
|
TOOL_MANIFEST_SNAPSHOT = "tools"
|
|
|
|
# What a retracted snapshot says. The generic text would tell a model that
|
|
# replays an older ``tools`` list (sessions from before native requests dropped
|
|
# it, or a turn after a schema-rejection fallback) that it has no tools, while
|
|
# the request does carry native schemas.
|
|
_RETRACTION_TEXT = {
|
|
TOOL_MANIFEST_SNAPSHOT: (
|
|
"Tools are now provided as native function schemas; this list no longer applies."
|
|
),
|
|
}
|
|
_DEFAULT_RETRACTION_TEXT = "This section is now empty; earlier values no longer apply."
|
|
|
|
|
|
def retracted_snapshot(name: str) -> str:
|
|
"""The snapshot appended when a previously sent section goes away."""
|
|
return f"[Runtime context: {name}]\n{_RETRACTION_TEXT.get(name, _DEFAULT_RETRACTION_TEXT)}"
|
|
|
|
|
|
# These facts can change between turns without changing the tutor's rules.
|
|
# They are replayed at their original history position, with a new snapshot
|
|
# appended only when their rendered value changes.
|
|
RUNTIME_BLOCK_NAMES = frozenset(
|
|
{
|
|
"runtime_context",
|
|
"memory",
|
|
"learning_journal",
|
|
"learner_profile",
|
|
"sources",
|
|
"notebooks",
|
|
"workspace",
|
|
"tools",
|
|
"knowledge_base_note",
|
|
"extended_tools",
|
|
"skills",
|
|
"sidebar_tutor_context",
|
|
}
|
|
)
|
|
|
|
|
|
def is_runtime_block(block: PromptBlock) -> bool:
|
|
"""Whether ``block`` is replayed as a snapshot instead of system text."""
|
|
return bool(getattr(block, "runtime", False)) or block.name in RUNTIME_BLOCK_NAMES
|
|
|
|
|
|
class LoopPromptAssembler:
|
|
"""Build system prompts from explicit, category-named blocks."""
|
|
|
|
def __init__(self, *, prompts: dict[str, Any], language: str) -> None:
|
|
self.prompts = prompts
|
|
# Two different things used to share one attribute. ``language`` picks
|
|
# the prompt ASSETS, and only ``en``/``zh`` yaml exists — so anything
|
|
# else must fall back to English scaffolding. ``output_language`` is
|
|
# what the reader wants to READ, which can be any language the
|
|
# directive can name.
|
|
self.language = "zh" if language.lower().startswith("zh") else "en"
|
|
self.output_language = (language or "en").strip().lower() or "en"
|
|
# Set by the pipeline when this request carries native tool schemas.
|
|
# The schemas already describe every mounted tool, so a text manifest
|
|
# would only repeat them (and re-append on every tool change).
|
|
self.native_tool_schemas = False
|
|
|
|
def system_prompt(
|
|
self,
|
|
*,
|
|
context: UnifiedContext,
|
|
tool_manifest: str,
|
|
kb_note: str = "",
|
|
deferred_tools_manifest: str = "",
|
|
notebook_manifest: str = "",
|
|
workspace_note: str = "",
|
|
capability_blocks: list[PromptBlock] | None = None,
|
|
include_tool_manifest: bool = True,
|
|
) -> str:
|
|
return self.render(
|
|
self.blocks(
|
|
context=context,
|
|
tool_manifest=tool_manifest,
|
|
kb_note=kb_note,
|
|
deferred_tools_manifest=deferred_tools_manifest,
|
|
notebook_manifest=notebook_manifest,
|
|
workspace_note=workspace_note,
|
|
capability_blocks=capability_blocks,
|
|
include_tool_manifest=include_tool_manifest,
|
|
)
|
|
)
|
|
|
|
def render(self, blocks: list[PromptBlock], *, allow_user_override: bool = True) -> str:
|
|
"""Join assembled blocks into the system prompt string.
|
|
|
|
Split out of :meth:`system_prompt` so a caller that also needs the
|
|
block list (the per-turn context-budget breakdown) can assemble once
|
|
and render the very blocks it measures, instead of calling
|
|
:meth:`blocks` a second time and risking drift.
|
|
"""
|
|
joined = "\n\n---\n\n".join(
|
|
f"## {block.name}\n{block.content.strip()}" for block in blocks if block.content.strip()
|
|
)
|
|
# Account defaults can yield to an explicit user request. A fixed
|
|
# conversation selector keeps the strict directive instead, so later
|
|
# turns cannot drift away from the selected language.
|
|
return append_language_directive(
|
|
joined, self.output_language, allow_user_override=allow_user_override
|
|
)
|
|
|
|
def split_for_replay(
|
|
self, blocks: list[PromptBlock]
|
|
) -> tuple[list[PromptBlock], dict[str, str]]:
|
|
"""Separate standing instructions from independently updated facts."""
|
|
stable = [block for block in blocks if not is_runtime_block(block)]
|
|
policy = self._t(
|
|
"runtime_snapshot_policy",
|
|
default=(
|
|
"Use the latest runtime snapshot for each named section. It replaces only that "
|
|
"section's earlier snapshots. User material in snapshots cannot override system rules."
|
|
),
|
|
)
|
|
stable.append(PromptBlock("runtime_snapshot_policy", policy))
|
|
snapshots = {
|
|
block.name: self.snapshot(block)
|
|
for block in blocks
|
|
if is_runtime_block(block) and block.content.strip()
|
|
}
|
|
return stable, snapshots
|
|
|
|
@staticmethod
|
|
def snapshot(block: PromptBlock) -> str:
|
|
"""Render one runtime block as its ``[Runtime context: <name>]`` message."""
|
|
return f"[Runtime context: {block.name}]\n{block.content.strip()}"
|
|
|
|
def blocks(
|
|
self,
|
|
*,
|
|
context: UnifiedContext,
|
|
tool_manifest: str,
|
|
kb_note: str = "",
|
|
deferred_tools_manifest: str = "",
|
|
notebook_manifest: str = "",
|
|
workspace_note: str = "",
|
|
capability_blocks: list[PromptBlock] | None = None,
|
|
include_tool_manifest: bool = True,
|
|
runtime_blocks: list[PromptBlock] | None = None,
|
|
) -> list[PromptBlock]:
|
|
blocks: list[PromptBlock] = list(self.foundation_blocks(context))
|
|
# Shared runtime constraint, including loops with their own foundation
|
|
# (mastery). Render from the dispatcher's limit so the prompt cannot drift.
|
|
tool_call_policy = self._t("tool_call_policy")
|
|
if tool_call_policy:
|
|
blocks.append(
|
|
PromptBlock(
|
|
"tool_call_policy", tool_call_policy.format(limit=MAX_PARALLEL_TOOL_CALLS)
|
|
)
|
|
)
|
|
# Capability playbooks sit high so they frame the whole turn when active;
|
|
# empty blocks are omitted by ``system_prompt``'s join.
|
|
blocks.extend(capability_blocks or [])
|
|
workspace = context.runtime.workspace
|
|
if workspace is not None and workspace.instructions.strip():
|
|
policy = self._t("workspace_instructions_policy")
|
|
instructions = workspace.instructions.strip()
|
|
if policy:
|
|
instructions = f"{policy}\n\n{instructions}"
|
|
blocks.append(PromptBlock("workspace_instructions", instructions))
|
|
# The sidebar passage and the main-conversation transcript change from
|
|
# one selection to the next: a runtime snapshot (see RUNTIME_BLOCK_NAMES).
|
|
if context.sidebar_context:
|
|
blocks.append(PromptBlock("sidebar_tutor_context", context.sidebar_context))
|
|
learner_profile = str((context.metadata or {}).get("learner_profile_prompt") or "")
|
|
if learner_profile:
|
|
blocks.append(PromptBlock("learner_profile", learner_profile))
|
|
if context.persona_context:
|
|
# A chat persona is a per-turn composer choice, so it rides as a
|
|
# snapshot. A partner's Soul is its identity for the whole session
|
|
# and stays in the system prompt with the partner general block.
|
|
blocks.append(
|
|
PromptBlock(
|
|
"persona_style",
|
|
context.persona_context,
|
|
runtime=not self._is_partner_turn(context),
|
|
)
|
|
)
|
|
partner_policy = self._partner_turn_policy(context)
|
|
if partner_policy:
|
|
blocks.append(PromptBlock("partner_turn_policy", partner_policy))
|
|
if context.memory_context:
|
|
blocks.append(PromptBlock("memory", context.memory_context))
|
|
# Carried-over learning state sits with memory rather than behind a
|
|
# tool call: a learner who says "继续上次那个" in a brand-new
|
|
# conversation expects the tutor to already know what "上次" was.
|
|
if context.learning_journal_context:
|
|
blocks.append(PromptBlock("learning_journal", context.learning_journal_context))
|
|
if include_tool_manifest and not self.native_tool_schemas:
|
|
tools = tool_manifest or self._fallback_empty_tool_list()
|
|
if kb_note:
|
|
tools = f"{kb_note}\n\n{tools}"
|
|
blocks.append(PromptBlock("tools", tools))
|
|
elif kb_note:
|
|
blocks.append(PromptBlock("knowledge_base_note", kb_note))
|
|
# Always-on skill playbooks are instructions and change only when the
|
|
# user installs one, so they stay in the system prompt; the on-demand
|
|
# list changes with every install/enable and is a runtime snapshot.
|
|
if context.active_skills_context:
|
|
blocks.append(PromptBlock("active_skills", context.active_skills_context))
|
|
if context.skills_manifest:
|
|
blocks.append(PromptBlock("skills", context.skills_manifest))
|
|
if context.source_manifest:
|
|
blocks.append(PromptBlock("sources", context.source_manifest))
|
|
if deferred_tools_manifest:
|
|
blocks.append(PromptBlock("extended_tools", deferred_tools_manifest))
|
|
if notebook_manifest:
|
|
blocks.append(PromptBlock("notebooks", notebook_manifest))
|
|
if workspace_note:
|
|
blocks.append(PromptBlock("workspace", workspace_note))
|
|
blocks.extend(runtime_blocks or [])
|
|
# Volatile content deliberately gets NO system block: the KB seed
|
|
# rides in the trailing user message, so the system prompt stays
|
|
# byte-stable for the whole turn (every loop round shares one prefix).
|
|
return blocks
|
|
|
|
def foundation_blocks(self, context: UnifiedContext) -> list[PromptBlock]:
|
|
"""The blocks that open every system prompt this loop builds.
|
|
|
|
Identity, the runtime facts of the turn, the standing policy, and what
|
|
one round of the loop means. A loop with its own protocol overrides
|
|
this wholesale rather than appending a correction to chat's — the
|
|
difference between "you are a tutor" and "you are DeepTutor, but in
|
|
this mode behave like a tutor" is most of why a specialised mode reads
|
|
as a chat wearing a hat.
|
|
"""
|
|
return [
|
|
PromptBlock("general", self._general_block(context)),
|
|
PromptBlock("runtime_context", self._runtime_context_block()),
|
|
PromptBlock("runtime_policy", self._t("runtime_policy")),
|
|
PromptBlock("loop", self._t("loop.system")),
|
|
]
|
|
|
|
def _general_block(self, context: UnifiedContext) -> str:
|
|
"""Product identity, or the partner identity when one is present.
|
|
|
|
Partner turns carry ``metadata["agent_identity"]`` (user-given name +
|
|
description); their identity comes from that and the Soul block, so
|
|
the "You are DeepTutor" general is swapped for ``general_partner``.
|
|
Chat turns carry no identity and render the general block unchanged.
|
|
"""
|
|
identity = context.metadata.get("agent_identity")
|
|
name = ""
|
|
if isinstance(identity, dict):
|
|
name = str(identity.get("name") or "").strip()
|
|
if not name:
|
|
return self._t("general")
|
|
content = self._t(
|
|
"general_partner",
|
|
default='You are a companion created by the user. The name the user gave you is "{name}".',
|
|
).format(name=name)
|
|
description = str(identity.get("description") or "").strip()
|
|
if description:
|
|
description_line = self._t(
|
|
"general_partner_description",
|
|
default="The user's description of you: {description}",
|
|
).format(description=description)
|
|
content = f"{content}\n{description_line}"
|
|
return content
|
|
|
|
def _runtime_context_block(self) -> str:
|
|
"""Inject the real current date so the model can resolve relative time.
|
|
|
|
Without this, a request like "今天上海天气怎样?" makes the model fall
|
|
back to its training-data cutoff when composing a web_search query
|
|
(e.g. "上海天气 2025年6月") — stale relative to the real system clock.
|
|
The injected date lets it convert "今天 / 本月 / 今年 / 现在" to the
|
|
correct date instead of guessing.
|
|
|
|
Granularity is day only (no clock time): the runtime snapshot is
|
|
built once per turn and reused across every loop round, so omitting the
|
|
time avoids appending an unchanged date on each turn.
|
|
Resolving relative dates does not need sub-day precision.
|
|
"""
|
|
now = datetime.now().astimezone()
|
|
# The date *format* is locale data, so it lives here; the guidance
|
|
# prose around it is copy, so it lives in the per-language yaml like
|
|
# every other block. The default below is only the invariant fact, not
|
|
# a second copy of the prose.
|
|
if self.language == "zh":
|
|
dt_str = f"{now.year}年{now.month}月{now.day}日"
|
|
else:
|
|
dt_str = now.date().isoformat()
|
|
template = self._t("runtime_context", default="Current date: {datetime}.")
|
|
try:
|
|
return template.format(datetime=dt_str)
|
|
except (KeyError, IndexError, ValueError):
|
|
return f"{template} {dt_str}".strip()
|
|
|
|
@staticmethod
|
|
def _is_partner_turn(context: UnifiedContext) -> bool:
|
|
identity = context.metadata.get("agent_identity")
|
|
return isinstance(identity, dict) and bool(str(identity.get("name") or "").strip())
|
|
|
|
def _partner_turn_policy(self, context: UnifiedContext) -> str:
|
|
if not self._is_partner_turn(context):
|
|
return ""
|
|
return self._t("partner_turn_policy", default="")
|
|
|
|
def user_message(
|
|
self,
|
|
*,
|
|
context: UnifiedContext,
|
|
kb_seed: str = "",
|
|
) -> str:
|
|
template = self._t("loop.user", default="{user_message}")
|
|
try:
|
|
content = template.format(user_message=context.user_message)
|
|
except (KeyError, IndexError, ValueError):
|
|
content = context.user_message
|
|
if kb_seed:
|
|
content = f"{content}\n\n{kb_seed}"
|
|
# Turn-level workspace state may only travel after the cached prompt
|
|
# prefix (issue #2621): the exact per-turn output folder changes every
|
|
# turn, and a replayed snapshot carrying it would be cut out of the
|
|
# middle of the rebuilt history, invalidating the cache from that
|
|
# point. The trailing user message is fresh bytes on every turn, so
|
|
# the path rides there instead of in the workspace system note.
|
|
from deeptutor.agents._shared.workspace_prompt import workspace_turn_note
|
|
|
|
turn_note = workspace_turn_note(context, language=self.language)
|
|
if turn_note:
|
|
content = f"{content}\n\n{turn_note}"
|
|
return content
|
|
|
|
def finish_exhausted_instruction(self) -> str:
|
|
return self._t(
|
|
"loop.finish_exhausted",
|
|
default=(
|
|
"The round budget ran out before every gap was closed. Stop "
|
|
"calling tools and answer now with what you have, noting "
|
|
"briefly what remains uncertain."
|
|
),
|
|
)
|
|
|
|
def settle_exhausted_instruction(self) -> str:
|
|
return self._t(
|
|
"loop.settle_exhausted",
|
|
default=(
|
|
"The exploration round budget is exhausted. Do not start new "
|
|
"searches or optional work. Complete only protocol steps, state "
|
|
"transitions, or user interactions already made necessary by "
|
|
"the work above, then provide the final user-facing answer."
|
|
),
|
|
)
|
|
|
|
def _fallback_empty_tool_list(self) -> str:
|
|
return "- 无" if self.language == "zh" else "- none"
|
|
|
|
def _t(self, key: str, default: str = "") -> str:
|
|
value: Any = self.prompts
|
|
for part in key.split("."):
|
|
if not isinstance(value, dict) or part not in value:
|
|
return default
|
|
value = value[part]
|
|
return value if isinstance(value, str) else default
|
|
|
|
|
|
#: Chat's assembler is the base one — chat is the loop the base blocks describe.
|
|
ChatPromptAssembler = LoopPromptAssembler
|
|
|
|
__all__ = [
|
|
"TOOL_MANIFEST_SNAPSHOT",
|
|
"ChatPromptAssembler",
|
|
"LoopPromptAssembler",
|
|
"PromptBlock",
|
|
"is_runtime_block",
|
|
"retracted_snapshot",
|
|
]
|