From de1e89bba0205653bdb52679bc16a02e9ffe89b2 Mon Sep 17 00:00:00 2001 From: LamXwah <137157815+zh769394@users.noreply.github.com> Date: Wed, 19 Aug 2026 23:37:22 +0800 Subject: [PATCH] fix(chat): inject current date into runtime context (#910) Without the real date the model resolved 'today' from its training cutoff when composing web_search queries. Inject a day-granularity runtime_context block so the system prompt stays byte-stable within a day and keeps prompt-cache hits. --- deeptutor/agents/chat/prompt_blocks.py | 38 ++++++++ .../agents/chat/prompts/en/agentic_chat.yaml | 7 ++ .../agents/chat/prompts/zh/agentic_chat.yaml | 6 ++ tests/agents/chat/test_language_prompts.py | 2 +- tests/agents/chat/test_runtime_context.py | 92 +++++++++++++++++++ 5 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 tests/agents/chat/test_runtime_context.py diff --git a/deeptutor/agents/chat/prompt_blocks.py b/deeptutor/agents/chat/prompt_blocks.py index 332ae1d79..558e62400 100644 --- a/deeptutor/agents/chat/prompt_blocks.py +++ b/deeptutor/agents/chat/prompt_blocks.py @@ -2,6 +2,7 @@ from __future__ import annotations +from datetime import datetime from typing import Any from deeptutor.capabilities.protocol import PromptBlock @@ -68,6 +69,7 @@ class ChatPromptAssembler: ) -> list[PromptBlock]: blocks: list[PromptBlock] = [ 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")), ] @@ -130,6 +132,42 @@ class ChatPromptAssembler: 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 system prompt is + built once per turn and reused across every loop round, so omitting the + time keeps it byte-stable within a day and preserves prompt-cache hits. + Resolving relative dates does not need sub-day precision. + """ + now = datetime.now().astimezone() + if self.language == "zh": + dt_str = f"{now.year}年{now.month}月{now.day}日" + default = ( + "当前时间:{datetime}。以此为准解析「今天 / 本周 / 本月 / 今年 / 现在」等相对时间词," + "并在构造 web_search、paper_search 等查询时把它们换算成这个真实日期," + "不要使用训练数据里的旧日期。" + ) + else: + dt_str = now.date().isoformat() + default = ( + "Current date: {datetime}. Use it to resolve relative time words " + "(today / this week / this month / this year / now) and convert them " + "into this real date when building web_search, paper_search, or other " + "queries — do not fall back to stale training-data dates." + ) + template = self._t("runtime_context", default=default) + try: + return template.format(datetime=dt_str) + except (KeyError, IndexError, ValueError): + return f"{template} {dt_str}".strip() + def _partner_turn_policy(self, context: UnifiedContext) -> str: identity = context.metadata.get("agent_identity") if not isinstance(identity, dict): diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml index 49b28b329..d763ddf9a 100644 --- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml +++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml @@ -12,6 +12,13 @@ general: |- Never describe internal stages, prompt blocks, or implementation details unless the user explicitly asks about the system design. +# Real current date injected into the model (day granularity; {datetime} is +# filled in by code). Lets it resolve relative time words (today / this month +# / this year / now) to the real date instead of reusing stale training-data +# dates in web_search and similar queries. +runtime_context: |- + Current date: {datetime}. Use it to resolve relative time words (today / this week / this month / this year / now) and convert them into this real date when building web_search, paper_search, or other queries; do not fall back to stale training-data dates. + # Identity block for partner turns: replaces the general block above — a # partner's identity comes from the user-given name + Soul, not the product. general_partner: |- diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml index d6044952a..29adb43ff 100644 --- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml +++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml @@ -11,6 +11,12 @@ general: |- 你是 DeepTutor,一名互动式学习教练和学习伙伴。 除非用户明确询问系统设计,否则不要描述内部阶段、提示词块或实现细节。 +# 注入给模型的真实当前日期(day 粒度,由代码填入 {datetime})。 +# 用于把「今天 / 本月 / 今年 / 现在」等相对时间词换算成真实日期, +# 避免 web_search 等查询沿用训练数据里的旧日期。 +runtime_context: |- + 当前时间:{datetime}。以此为准解析「今天 / 本周 / 本月 / 今年 / 现在」等相对时间词,并在构造 web_search、paper_search 等查询时把它们换算成这个真实日期;不要使用训练数据里的旧日期。 + # Partner(伙伴)回合的身份块:替换掉上面的 general —— partner 的身份来自 # 用户起的名字 + Soul,而不是产品名。 general_partner: |- diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.py index 113458bd9..c87ef39c0 100644 --- a/tests/agents/chat/test_language_prompts.py +++ b/tests/agents/chat/test_language_prompts.py @@ -115,7 +115,7 @@ def test_prompt_blocks_include_localized_optional_context() -> None: blocks = assembler.blocks(context=ctx, tool_manifest="", workspace_note="工作区可用") names = [block.name for block in blocks] - assert names[:3] == ["general", "runtime_policy", "loop"] + assert names[:4] == ["general", "runtime_context", "runtime_policy", "loop"] assert "persona_style" in names assert "memory" in names assert "workspace" in names diff --git a/tests/agents/chat/test_runtime_context.py b/tests/agents/chat/test_runtime_context.py new file mode 100644 index 000000000..a9be57551 --- /dev/null +++ b/tests/agents/chat/test_runtime_context.py @@ -0,0 +1,92 @@ +"""The ``runtime_context`` block injects the real current date so the model +resolves relative time words (today / 本月 / 现在) instead of falling back to +stale training-data dates when composing web_search queries. + +Regression guard for the bug where "今天上海天气怎样?" produced a web_search +query of "上海天气 2025年6月" — a year stale relative to the real clock. +See ``deeptutor/agents/chat/prompt_blocks.py:_runtime_context_block``. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +import yaml + +from deeptutor.agents.chat import prompt_blocks as prompt_blocks_module +from deeptutor.agents.chat.prompt_blocks import ChatPromptAssembler +from deeptutor.core.context import UnifiedContext + +# Deliberately omits ``runtime_context``: exercises the code-default fallback, +# so the date is injected even when a prompt map lacks the entry. +PROMPTS_NO_RUNTIME = { + "general": "You are DeepTutor.", + "runtime_policy": "policy", + "loop": {"system": "loop"}, +} + +FIXED_NOW = datetime(2026, 8, 17, 12, tzinfo=timezone(timedelta(hours=8))) + + +class FrozenDateTime(datetime): + @classmethod + def now(cls, tz=None): + if tz is None: + return FIXED_NOW + return FIXED_NOW.astimezone(tz) + + +@pytest.fixture(autouse=True) +def _freeze_runtime_date(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(prompt_blocks_module, "datetime", FrozenDateTime) + + +def _runtime_block(assembler: ChatPromptAssembler) -> str: + blocks = assembler.blocks( + context=UnifiedContext(user_message="今天上海天气怎样?"), + tool_manifest="- none", + ) + return next(b.content for b in blocks if b.name == "runtime_context") + + +def test_block_is_registered(): + assembler = ChatPromptAssembler(prompts=PROMPTS_NO_RUNTIME, language="en") + names = [ + b.name + for b in assembler.blocks(context=UnifiedContext(user_message="hi"), tool_manifest="- none") + ] + assert "runtime_context" in names + + +def test_default_injects_real_current_date_en(): + content = _runtime_block(ChatPromptAssembler(prompts=PROMPTS_NO_RUNTIME, language="en")) + assert "{datetime}" not in content + assert "2026-08-17" in content + + +def test_default_injects_real_current_date_zh(): + content = _runtime_block(ChatPromptAssembler(prompts=PROMPTS_NO_RUNTIME, language="zh")) + assert "{datetime}" not in content + assert "2026年8月17日" in content + + +def test_yaml_template_substitutes_placeholder(): + """The shipped yaml template carries ``{datetime}``; the assembler must + swap it for the real date rather than leaking the raw placeholder.""" + root = Path(__file__).resolve().parents[3] / "deeptutor/agents/chat/prompts" + prompts = yaml.safe_load((root / "en" / "agentic_chat.yaml").read_text(encoding="utf-8")) + content = _runtime_block(ChatPromptAssembler(prompts=prompts, language="en")) + assert "{datetime}" not in content + assert "2026-08-17" in content + + +def test_shipped_yaml_carries_runtime_context_template(): + root = Path(__file__).resolve().parents[3] / "deeptutor/agents/chat/prompts" + for lang in ("en", "zh"): + data = yaml.safe_load((root / lang / "agentic_chat.yaml").read_text(encoding="utf-8")) + assert "runtime_context" in data, f"{lang} missing runtime_context" + assert "{datetime}" in data["runtime_context"], ( + f"{lang} runtime_context must keep the {{datetime}} placeholder" + )