DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge dev and preserve narrow Partner authoring intent
Bingxi Zhao (Frank)8fafd3ef3053
diff --cc deeptutor/capabilities/partner_authoring/binding.pyindex 7b8b92371,9f8c8d34c..a347d67a1--- a/deeptutor/capabilities/partner_authoring/binding.py+++ b/deeptutor/capabilities/partner_authoring/binding.py@@@ -8,43 -8,65 +8,93 @@@ from deeptutor.core.context import UnifPARTNER_AUTHORING_CAPABILITY_NAME = "partner_authoring"- _ACTION = re.compile(- r"(创建|新建|生成|设计|定制|做一个|来一个|来个|想要|需要|帮我做|帮我建|加一个)"- r"|(\bcreate\b|\bmake\b|\bbuild\b|\bdesign\b|\bgenerate\b|\bwant\b|\bneed\b|\badd\b)",+ # The action has to lead into the Partner object within one clause. Matching the two words+ # anywhere in the message fired on turns that only mention a Partner ("I want to file an issue+ # about the Partner bug"), and finish_instruction then forces a draft the user never asked for.+ _ZH_ACTION = (+ r"(?:创建|新建|生成|设计|定制|帮我做|帮我建|做一个|来一个|来个|加一个"+ r"|(?:想要|需要)(?:一个|一位|个|位))"+ )+ _ZH_OBJECT = r"(?:partner|伙伴|学习搭子|陪伴者|陪练|助教|导师|教练|学伴|智能体|角色)"+ # Stops at clause punctuation and at words that make the object a topic rather than the target.+ _ZH_GAP = r"(?:(?!关于|有关|提到|讨论)[^。!?!?;;,,、\n]){0,16}?"+ _EN_ACTION = (+ r"(?:\b(?:create|make|build|design|generate|add|set\s+up)\b(?:\s+(?:me|us))?"+ r"|\b(?:want|need)\b)"+ )+ _EN_DETERMINER = r"\s+(?:a|an|another|one|my\s+own|our\s+own|a\s+new|new)\b"+ _EN_GAP = r"(?:\s+(?!(?:about|with|for|of|from|in|on|to|that|which)\b)[\w'-]+){0,3}?"-_EN_OBJECT = r"\s+(?:partners?|companions?|tutors?|mentors?|coach(?:es)?|study\s+budd(?:y|ies))\b"++_EN_OBJECT = (++ r"\s+(?:partners?|companions?|tutors?|mentors?|coach(?:es)?|study\s+budd(?:y|ies))(?![\w-])"++)++ _AUTHORING_REQUEST = re.compile(+ rf"{_ZH_ACTION}{_ZH_GAP}{_ZH_OBJECT}|{_EN_ACTION}{_EN_DETERMINER}{_EN_GAP}{_EN_OBJECT}",+ re.IGNORECASE,+ )+ _QUOTED_OR_CODE = re.compile(+ r"```[\s\S]*?```|~~~[\s\S]*?~~~"+ r"|(?m:^>[^\n]*)|`[^`\n]*`"+ r'|"[^"\n]*"|“[^”\n]*”|「[^」\n]*」|『[^』\n]*』'+ r"|(?<!\w)'[^'\n]+'(?!\w)"+ )+ _CLAUSE_END = re.compile(r"[。!?!?;;,,\n]")+ _NEGATED_ACTION = re.compile(+ r"(?:\b(?:don't|do\s+not|never|not|can't|cannot)\s*(?:want|need)?(?:\s+(?:you\s+)?to)?\s*"+ r"|(?:不|别|不要|不用|无需|不必|不想(?:让你)?|不需要)\s*)$",+ re.IGNORECASE,+ )++_MENTION_QUESTION = re.compile(++ r"^\s*(?:(?:explain\s+)?(?:why|how|what)\b|(?:请)?(?:解释)?(?:为什么|为何|怎么|如何))",+ re.IGNORECASE,+)- _OBJECT = re.compile(- r"(partner|伙伴|学习搭子|陪伴者|陪练|助教|导师|教练|学伴|智能体|角色)"- r"|(\bcompanion\b|\btutor\b|\bmentor\b|\bcoach\b|\bstudy buddy\b)",++_NON_PARTNER_TARGET = re.compile(++ r"^\s+(?:issue|bug|report|checklist|style|tone|feature|setting|ticket)\b"++ r"|^(?:功能|问题|报告|文档|风格|语气|清单|按钮|页面)",+ re.IGNORECASE,+)-def is_partner_authoring_turn(context: UnifiedContext) -> bool:+def partner_authoring_trigger(context: UnifiedContext) -> str | None:+ """Why this turn is in the authoring flow, or ``None`` when it is not.++ ``explicit`` means the user selected the capability; ``heuristic`` means only+ the keyword gate matched, which is a guess about the words they typed.+ """# Home/product Chat owns the review card and confirmation flow. A Partner# (including one running inside a Group) must not create drafts inside its# synthetic workspace merely because someone talks about another Partner.if context.metadata.get("source") == "partner":- return False+ return Noneif context.active_capability == PARTNER_AUTHORING_CAPABILITY_NAME:- return True+ return "explicit"text = str(context.user_message or "")- if _ACTION.search(text) and _OBJECT.search(text):+ quoted = [match.span() for match in _QUOTED_OR_CODE.finditer(text)]+ for match in _AUTHORING_REQUEST.finditer(text):+ # Mentioning a request inside a quotation or code sample is not an+ # instruction. The action may still be outside quotes around a name.+ if any(start <= match.start() and match.end() <= end for start, end in quoted):+ continue+ clause_start = max(+ (boundary.end() for boundary in _CLAUSE_END.finditer(text, 0, match.start())),+ default=0,+ )+ if _NEGATED_ACTION.search(text[clause_start : match.start()]):+ continue- return True- return False++ if _MENTION_QUESTION.search(text[clause_start : match.start()]):++ continue++ if _NON_PARTNER_TARGET.match(text[match.end() :]):++ continue+ return "heuristic"+ return None+++def is_partner_authoring_turn(context: UnifiedContext) -> bool:+ return partner_authoring_trigger(context) is not None-__all__ = ["PARTNER_AUTHORING_CAPABILITY_NAME", "is_partner_authoring_turn"]+__all__ = [+ "PARTNER_AUTHORING_CAPABILITY_NAME",+ "is_partner_authoring_turn",+ "partner_authoring_trigger",+]diff --cc deeptutor/capabilities/partner_authoring/capability.pyindex 7af6d5216,1370f18f6..ba206256a--- a/deeptutor/capabilities/partner_authoring/capability.py+++ b/deeptutor/capabilities/partner_authoring/capability.py@@@ -29,9 -28,9 +29,13 @@@ class PartnerAuthoringCapabilitylanguage: str,prompts: dict[str, Any],) -> PromptBlock | None:-- _ = (context, prompts)++ _ = prompts++ trigger = partner_authoring_trigger(context)++ if trigger is None:++ return Nonelang = "zh" if str(language or "").lower().startswith("zh") else "en"-- prompt = resources.files(__package__).joinpath("prompts", lang, "system.md")++ filename = "system.md" if trigger == "explicit" else "heuristic.md"++ prompt = resources.files(__package__).joinpath("prompts", lang, filename)return PromptBlock(self.name, prompt.read_text(encoding="utf-8").strip())def augment_kwargs(diff --cc deeptutor/capabilities/partner_authoring/prompts/en/heuristic.mdindex 000000000,000000000..2e0278638new file mode 100644--- /dev/null+++ b/deeptutor/capabilities/partner_authoring/prompts/en/heuristic.md@@@ -1,0 -1,0 +1,1 @@@++The user's words may ask for a new DeepTutor Partner profile. First decide from the full request whether they actually want a new Partner. If they do, call `propose_partner` once to create an editable draft, then invite review and confirmation. If they are asking about an existing Partner, a bug, wording, or another task, answer that request normally and do not call `propose_partner`. Never claim a draft exists before the tool succeeds.diff --cc deeptutor/capabilities/partner_authoring/prompts/zh/heuristic.mdindex 000000000,000000000..dc74a361dnew file mode 100644--- /dev/null+++ b/deeptutor/capabilities/partner_authoring/prompts/zh/heuristic.md@@@ -1,0 -1,0 +1,1 @@@++用户的话可能是在请求新的 DeepTutor Partner 档案。先根据完整请求判断用户是否确实要创建新 Partner。若是,调用一次 `propose_partner` 生成可编辑草稿,再邀请用户检查并确认。若用户是在询问现有 Partner、报告问题、修改措辞或处理其他任务,正常回答,不要调用 `propose_partner`。工具成功前不得声称草稿已创建。diff --cc tests/agents/chat/test_agent_loop.pyindex ec65c3785,ec65c3785..99449c146--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@@ -1814,6 -1814,6 +1814,28 @@@ async def test_inline_think_is_never_anassert _answer_text(events) == "结论是 A。"++async def test_partner_wording_request_keeps_its_answer(++ monkeypatch: pytest.MonkeyPatch,++) -> None:++ """A Partner keyword in another task cannot redirect or discard a turn."""++ client = _ScriptedChatClient([[_llm_chunk(content="Use a warmer tone.")]])++ pipeline = AgenticChatPipeline(language="en")++ pipeline.registry = _Registry()++ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])++ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++++ events = await _run(++ pipeline,++ UnifiedContext(++ session_id="s1",++ user_message="Please add a companion-style tone to my summary",++ ),++ )++++ assert _answer_text(events) == "Use a warmer tone."++++@pytest.mark.asyncioasync def test_mastery_teaching_prose_streams_chunk_by_chunk(monkeypatch: pytest.MonkeyPatch,diff --cc tests/capabilities/test_partner_authoring_capability.pyindex aa570f881,fc7c74fa4..0a649228b--- a/tests/capabilities/test_partner_authoring_capability.py+++ b/tests/capabilities/test_partner_authoring_capability.py@@@ -5,8 -5,8 +5,12 @@@ from pathlib import Patimport pytestfrom deeptutor.capabilities.partner_authoring import PartnerAuthoringCapability--from deeptutor.capabilities.partner_authoring.binding import is_partner_authoring_turn++from deeptutor.capabilities.partner_authoring.binding import (++ is_partner_authoring_turn,++ partner_authoring_trigger,++)from deeptutor.capabilities.partner_authoring.tools import ProposePartnerTool++from deeptutor.capabilities.registry import active_loop_capabilitiesfrom deeptutor.core.context import UnifiedContextfrom deeptutor.multi_user.models import CurrentUser, UserScopefrom deeptutor.multi_user.paths import user_context@@@ -26,38 -26,67 +30,100 @@@ def test_partner_authoring_activation_rassert not is_partner_authoring_turn(partner_context)- def _selected_context(message: str) -> UnifiedContext:+ @pytest.mark.parametrize(+ "message",+ [+ "Create a partner that quizzes me on French verbs",+ "I want a patient math tutor",+ "Can you make me a strict coach?",+ "Set up a new study buddy for physics",+ "我想要一个数学导师",+ "来个学习搭子",+ 'Create a tutor named "Ada"',+ "I don't want a coach; create a tutor instead",+ "请不要创建一个伙伴,请帮我创建一个数学导师",+ ],+ )+ def test_partner_authoring_activates_on_a_creation_request(message: str) -> None:+ assert is_partner_authoring_turn(_context(message))+++ @pytest.mark.parametrize(+ "message",+ [+ "I want to file an issue about the Partner bug",+ "I want to report that Partner creation keeps triggering",+ "I need help understanding my tutor's feedback",+ "Make sure my tutor sees this",+ "Why can a flash-tier model answer well? The release notes mention Partner channels.",+ "我想提交一个关于伙伴功能的 bug",+ "生成的回答里提到了伙伴",+ "我需要解释一下,为什么会触发伙伴创建",+ "I don't want a tutor",+ "I do not need a partner",+ "Please don't create a partner",+ "I don't want you to create a tutor",+ "我不想要一个伙伴",+ "请不要创建一个伙伴",+ "我不想让你创建一个伙伴",+ 'Why does "create a Partner" trigger here?',+ "The issue title is 'create a Partner'",+ "请解释“创建一个伙伴”为什么会误触发",+ "```text\ncreate a Partner\n```",+ "> create a Partner\nWhy did this trigger?",++ "Please add a companion-style tone to my summary",++ "Why does create a Partner trigger here?",++ "Create a Partner issue for me",++ "Can you make a partner checklist?",++ "请解释为什么创建一个伙伴会触发",++ "帮我创建一个伙伴功能的说明",+ ],+ )+ def test_partner_authoring_ignores_turns_that_only_mention_a_partner(message: str) -> None:- assert not is_partner_authoring_turn(_context(message))+ context = _context(message)++ assert not is_partner_authoring_turn(context)++ assert "partner_authoring" not in {++ capability.name for capability in active_loop_capabilities(context)++ }+++ def test_explicit_partner_authoring_selection_still_routes_the_turn() -> None:+ context = _context("I don't want a tutor")context.active_capability = "partner_authoring"- return context+ assert is_partner_authoring_turn(context)- def test_explicit_selection_forces_a_draft_before_finishing() -> None:+ def test_capability_forces_a_draft_before_finishing() -> None:capability = PartnerAuthoringCapability()- context = _selected_context("创建一个伙伴")+ context = _context("创建一个伙伴")++ context.active_capability = "partner_authoring"assert "propose_partner" in capability.finish_instruction(context, "好的")context.extension("partner_authoring")["draft_created"] = "draft"assert capability.finish_instruction(context, "完成") == ""- @pytest.mark.parametrize(- "message",- [- # Filing a report about the false trigger supplies one word from each- # list, so the bug report about the bug triggers the bug.- 'I want to file an issue about this: Spurious "Create Partner" triggers hijack',- "Please add a companion-style tone to my summary",- ],- )- def test_a_keyword_match_never_discards_the_answer(message: str) -> None:- # A finish instruction makes the loop throw away the reply written this- # round, so it has to cost something the user actually asked for (#1587).++def test_heuristic_match_never_discards_a_written_answer() -> None:+ capability = PartnerAuthoringCapability()- context = _context(message)- assert is_partner_authoring_turn(context)- assert capability.finish_instruction(context, "A careful answer.") == ""++ context = _context("Create a partner that quizzes me on French verbs")++ assert partner_authoring_trigger(context) == "heuristic"++ assert capability.finish_instruction(context, "A complete answer") == ""++ prompt = capability.system_block(context, language="en", prompts={})++ assert prompt is not None++ assert "First decide from the full request" in prompt.content++ assert "If they are asking about an existing Partner" in prompt.content++++++def test_explicit_selection_keeps_the_authoring_instruction() -> None:++ capability = PartnerAuthoringCapability()++ context = _context("Create a partner")++ context.active_capability = "partner_authoring"++ assert partner_authoring_trigger(context) == "explicit"++ prompt = capability.system_block(context, language="en", prompts={})++ assert prompt is not None++ assert "call `propose_partner` exactly once" in prompt.content++ assert "propose_partner" in capability.finish_instruction(context, "A description only")++@pytest.mark.asyncioasync def test_propose_partner_persists_user_scoped_reviewable_draft(tmp_path: Path) -> None:user = CurrentUser(