diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_conversation_context.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_conversation_context.py index 511c43585..56187e251 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_conversation_context.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_conversation_context.py @@ -91,9 +91,11 @@ # "Filter Usage" is a chart) or an open "anything else" ("I'll replace Order Breakdown in the same # position"). "With it" names the chart, so "replace the date filter with it" still places one. _CHART_NOUNS = r"charts?|visualizations?|insights?" +# "Confirm and I'll propose placing it at the end" places the chart as much as "place it" does. +_PLACING = rf"{_PLACEMENT_VERBS}|replacing|placing|putting|swapping|adding|inserting|moving" _PLACED_CHART_RE = re.compile( - rf"\b(?:{_PLACEMENT_VERBS})\s+(?:\S+\s+)?(?:it|them)\b" - rf"|\b(?:{_PLACEMENT_VERBS})\s+(?:\S+\s+){{0,5}}?(?:{_CHART_NOUNS})\b" + rf"\b(?:{_PLACING})\s+(?:\S+\s+)?(?:it|them)\b" + rf"|\b(?:{_PLACING})\s+(?:\S+\s+){{0,5}}?(?:{_CHART_NOUNS})\b" rf"|\b(?:{_PLACEMENT_VERBS})\b[^,;]*?\bwith\s+(?:it|them|(?:this|that|the)\s+(?:new\s+)?(?:{_CHART_NOUNS}))\b", re.IGNORECASE, ) @@ -107,12 +109,75 @@ rf"(?:{_SHOULD_I}|{_WANT_ME_TO}|{_IF_YOU_WANT_ME_TO})(?:{_PLACEMENT_VERBS})\b", re.IGNORECASE, ) +# A word to say before a placement ('Say "place it" and I'll add it', "Type “yes” and I will put it +# below"): a go-ahead or placement word, at most a pronoun or "ahead" after it, between a matching pair of +# straight or curly quotes. Read on the raw reply and turned into _SAY_TOKEN before the quoted literals are +# masked, so both quote styles read alike; a literal that asks for more ("yes, but smaller", "Section A", +# "ok it's fine") stays a literal and is masked. +_SAY_TOKEN = "saygoaheadword" +_SAY_WORDS = rf"yes|ok(?:ay)?|{_PLACEMENT_VERBS}|{_APPROVAL_VERBS}" +_SAY_TAIL = r"(?:\s+(?:it|them|this|that|ahead|now))?\s*[.!]?\s*" +_SAY_LITERAL = "|".join( + rf"{opening}\s*({_SAY_WORDS}){_SAY_TAIL}{closing}" for opening, closing in ('""', "“”", "‘’", "''") +) +_SAY_WORD_RE = re.compile(rf"\b(say|type)\s+(?:{_SAY_LITERAL})(?!\w)", re.IGNORECASE) +# Each word to say that the reply ties to what it will then do ('say "add" and I'll add it as a new row', +# also ', or "add" and I'll …') is one option. Two options are a choice unless every word only goes ahead: +# 'Say "yes" and I'll replace Order breakdown with it, or say "add" and I'll add it as a new row' asks +# which, 'Say "yes" and I'll place it. Or just say "place it" and I'll add it there' does not. A word with +# no "and I'll" after it ('To move it later, just type "move"') offers nothing now. +_SAY_OFFER_RE = re.compile( + rf"(?:\b(?:say|type)\s+|\bor\s+)(?:{_SAY_LITERAL})(?!\w),?\s+and\s+i(?:['’]ll|\s+will)\b", re.IGNORECASE +) +_SAY_GO_AHEAD_WORDS = frozenset({"yes", "ok", "okay", "place", "proceed", "apply", "go ahead"}) +# A reply that says before a "where" that it already placed the chart ("I replaced Order Breakdown with +# it") asks for no place to go on with. The claim must place the chart itself: "I added a comparison line +# to it" changed the chart, and "I've added it to the preview below" shows it. +_CLAIMS_PLACED_RE = re.compile( + r"\bi(?:['’]ve|\s+have)?\s+(?:already\s+)?(?:placed|added|put|moved|inserted)\s+" + rf"(?:it|them|(?:the|this|that)\s+(?:\S+\s+){{0,2}}?(?:{_CHART_NOUNS}))\b" + r"(?!\s+(?:in|into|to|on)\s+(?:the|a)\s+preview)" + r"|\bi(?:['’]ve|\s+have)?\s+(?:already\s+)?(?:replaced|swapped)\s+[^.;]{1,40}?\s+with\s+(?:it|them)\b", + re.IGNORECASE, +) +# An ask for a place on a condition about the spot ("if that spot is not right", "if you'd rather have it +# elsewhere") asks nothing yet; "if it helps" or "if you like" is a courtesy. +_IF_ELSEWHERE_RE = re.compile( + r"\bif\s+(?:that|this|the)\s+(?:spot|place|position|location)\b|\bif\s+you(?:['’]d|\s+would)\s+rather\b" + r"|\bif\s+you\s+prefer\b", + re.IGNORECASE, +) # These name no placement of their own ("Once you confirm the new title, I'll rename it"), so they # count only in a sentence that places a chart (_PLACED_CHART_RE). _GO_AHEAD_RE = re.compile( r"\b(?:once|when|after|if)\s+you\s+confirm\b" r"|\bconfirm,?\s+and\s+i(?:['’]ll|\s+will)\b" - rf"|\b(?:tell|ask)\s+me\s+to\s+(?:{_PLACEMENT_VERBS}|{_APPROVAL_VERBS})\b", + rf"|\b(?:tell|ask)\s+me\s+to\s+(?:{_PLACEMENT_VERBS}|{_APPROVAL_VERBS})\b" + rf"|\b(?:say|type)\s+{_SAY_TOKEN}\s+and\s+i(?:['’]ll|\s+will)\b", + re.IGNORECASE, +) +# Beside a shown chart, placing it named as the next step ("I've previewed it for placement at the end; +# applying it and switching the dashboard to last quarter will be the next step") is the same stop, told +# rather than asked. The placing verb and the chart come right next to the step: "placing it … will be the +# next step", "the next step is to place it", "next, I'll add it". "Next, I'll explain how to add it" and +# "adding a filter will be the next step" place nothing. +_PLACING_ING = r"replacing|placing|putting|swapping|adding|inserting|moving|applying" +_NEXT_STEP_RE = re.compile( + rf"\b(?:{_PLACING_ING})\s+(?:it|them)\b[^.;]*?\b(?:will\s+be|is)\s+(?:the|my)\s+next\s+step\b" + rf"|\bthe\s+next\s+step\s+(?:is|will\s+be)\s+(?:to\s+)?(?:{_PLACEMENT_VERBS}|apply|{_PLACING_ING})\s+(?:it|them)\b" + rf"|\bnext,?\s+i(?:['’]ll|\s+will)\s+(?:{_PLACEMENT_VERBS}|apply)\s+(?:it|them)\b", + re.IGNORECASE, +) +# A step left to the user ("once you pick a section", "for you in the UI", "which you can do from the menu", +# "place it yourself") or one the agent still lacks something for ("but I still need your section") is no +# go-ahead stop. A refusal or a claim around it is no guard: a "yes" then gets no patch, and the run fails +# on that. +_NEXT_STEP_HANDED_BACK_RE = re.compile( + r"\b(?:once|when|after|if)\s+you\s+(?:pick|choose|select|specify|tell|decide|provide|name)\b" + r"|\bfor\s+you\s+(?:in|to\s+do|from)\b|\bfor\s+your\s+(?:\w+\s+)?admin\b" + r"|\byou\s+can\s+do\b|\byou\s+can\s+(?:place|add|apply|put)\s+(?:it|them)\s+(?:yourself|from|via)\b" + r"|\byourself\b|\bhow\s+to\b|\byou(?:['’]ll|\s+will)\s+need\b" + r"|\bi\s+(?:still\s+)?need\s+(?:the|a|an|your|you\s+to|to\s+know|more)\b", re.IGNORECASE, ) # Beside a chart the same reply shows, an offer to place it ("I can replace Order breakdown with it", @@ -147,6 +212,17 @@ r"|how\s+(?:wide|tall|big|large|many)\b)", re.IGNORECASE, ) +# A reply that places nothing yet asks where the chart should go ("tell me where to place it", "let me +# know where you want it", "which section it should go in"). The place must be for the chart: +# "let me know where else I can help" or "which other charts you need" ask for nothing to place. +_THE_CHART = rf"it|them|(?:the|this|that)\s+(?:\S+\s+){{0,3}}?(?:{_CHART_NOUNS})" +_PLACE_ASK_IN_WORDS_RE = re.compile( + rf"\b(?:let\s+me\s+know|tell\s+me|please\s+(?:{_REQUEST_VERBS}))\s+" + r"(?:where(?!\s+else)|which\s+(?:section|tab|row|column|position|spot|place))\b[^.?!]*?" + rf"\b(?:(?:{_PLACEMENT_VERBS})\s+(?:\S+\s+)?(?:{_THE_CHART})" + rf"|you(?:['’]d|\s+would)?\s+(?:want|like)\s+(?:{_THE_CHART})|(?:{_THE_CHART}|they)\s+should\s+go)\b", + re.IGNORECASE, +) _EDIT_REQUEST_RE = re.compile( rf"\bplease\s+(?:{_REQUEST_VERBS})\b|\breply\s+with\b|^\s*(?:select|choose|pick)\s+(?:one|a|an|the)\b", re.IGNORECASE, @@ -283,13 +359,15 @@ def classify_edit_reply(chat_result: ChatResult, rendered_text: str, *, shown_ea I'll place it", "ask me to place it when you're ready") is a confirmation, so it is told yes. So is an offer to place it ("I can replace Order breakdown with it") once a chart has been shown: in this reply, or anywhere in the conversation so far (``shown_earlier``), as when the editor asks again in a - turn after its preview. + turn after its preview, and so is placing that chart named as the next step ("applying it will be + the next step"). Either kind of confirmation turns into a question when the reply also asks for something a yes does not supply: another question ("Which size should it have? Once you confirm, I'll place it."), a choice in the placement itself ("Should I put it before or after Orders over time?", "in Sales or Finance"), a numbered list with two placement items, something to confirm other than going ahead ("once you confirm which section"), a request for a place ("Please specify the size") or, from the - ask on, any other request. + ask on, any other request. A reply that places nothing but asks for a place in words ("tell me + where to place it") is a question too. """ if has_structured_question(chat_result): return "question" @@ -297,20 +375,45 @@ def classify_edit_reply(chat_result: ChatResult, rendered_text: str, *, shown_ea kind = classify_reply(chat_result, text) if chat_result.alert_proposals: return kind - plain = _EMPHASIS_RE.sub("", _FORMULA_SPAN_RE.sub(" ", text)) + said = _SAY_WORD_RE.sub(rf"\1 {_SAY_TOKEN}", text) + plain = _EMPHASIS_RE.sub("", _FORMULA_SPAN_RE.sub(" ", said)) sentences = [s for s in _SENTENCE_END_RE.split(plain) if s.strip()] # ADHOC_VIZ_ID stands for a chart the reply did not show, so it makes no offer. created = chat_result.created_visualizations shown = [viz for viz in (created.objects if created else []) if viz.id != ADHOC_VIZ_ID] offers = bool(shown) or shown_earlier placing = [ - bool(_PLACEMENT_ASK_RE.search(s) or _GO_AHEAD_RE.search(s) or (offers and _PLACEMENT_OFFER_RE.search(s))) - and bool(_PLACED_CHART_RE.search(s) or (offers and _PLACED_ANYTHING_RE.search(s))) + ( + ( + bool( + _PLACEMENT_ASK_RE.search(s) or _GO_AHEAD_RE.search(s) or (offers and _PLACEMENT_OFFER_RE.search(s)) + ) + and bool(_PLACED_CHART_RE.search(s) or (offers and _PLACED_ANYTHING_RE.search(s))) + ) + or ( + offers + and bool(_NEXT_STEP_RE.search(s)) + and not _NEXT_STEP_HANDED_BACK_RE.search(s) + and not _REQUEST_RE.search(s) + ) + ) and not _WH_ASK_RE.search(s) for s in sentences ] if not any(placing): - return "question" if kind == "confirmation" and asks_in_text(chat_result, text) else kind + if kind == "confirmation": + return "question" if asks_in_text(chat_result, text) else kind + # "Review it, then tell me where to place it" asks for a place without a question mark. A reply that + # said before the ask that the chart is already placed asks nothing to go on with ("I replaced Order + # Breakdown with it. Let me know where you want it moved"), nor does an ask on a condition about the spot. + if kind == "no_action" and any( + _PLACE_ASK_IN_WORDS_RE.search(s) + and not _IF_ELSEWHERE_RE.search(s) + and not any(_CLAIMS_PLACED_RE.search(t) for t in sentences[:i]) + for i, s in enumerate(sentences) + ): + return "question" + return kind # A shown chart's title is a name, so an "or" inside one ("Orders or Returns") is no choice. Only a # title of three words or more with an "or" in it is masked, and only as whole words: a title like # "a" or "or" would otherwise eat into the sentence around it. @@ -323,6 +426,11 @@ def classify_edit_reply(chat_result: ChatResult, rendered_text: str, *, shown_ea first = placing.index(True) # The second option can come as a sentence of its own after the ask: "Should I replace it? Alternatively, ...". masked = [title_re.sub(" ", s) if title_re else s for s in sentences] + offered = { + " ".join(next(word for word in m.groups() if word).lower().split()) for m in _SAY_OFFER_RE.finditer(text) + } + if len(offered) >= 2 and not offered <= _SAY_GO_AHEAD_WORDS: + return "question" if any( _PLACEMENT_CHOICE_RE.search(s) or (is_placing and _DESTINATION_CHOICE_RE.search(s)) for i, (s, is_placing) in enumerate(zip(masked, placing, strict=True)) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/dashboard_skill.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/dashboard_skill.py index 54c01752c..a79be5802 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/dashboard_skill.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/dashboard_skill.py @@ -7,6 +7,7 @@ import re import time from collections import Counter +from collections.abc import Sequence from dataclasses import dataclass, field from typing import Any @@ -352,7 +353,13 @@ def _check_forbidden(widgets: list[dict], forbidden: list[dict]) -> list[str]: return failures -def _check_answer(answer: str, must_include: list[str], must_not_match: list[str]) -> list[str]: +def _check_answer( + answer: str, + must_include: Sequence[str], + must_not_match: Sequence[str], + must_not_match_any_turn: Sequence[str] = (), + earlier_answers: Sequence[str] = (), +) -> list[str]: """Score the text the user actually reads. Nothing else in this evaluator looks at the answer: every other check reads the drafted @@ -365,17 +372,35 @@ def _check_answer(answer: str, must_include: list[str], must_not_match: list[str point was made rather than that a sentence was phrased a particular way. ``must_not_match`` is a regular expression, because what it rules out is usually a shape -- a token, an id, a claim pattern -- and not a fixed string. + + ``must_include`` and ``must_not_match`` read ``answer``, the last turn that said anything, + which states the outcome. ``must_not_match_any_turn`` also reads ``earlier_answers``, the prose + of the turns that spoke before it: a plan proposed in the first turn is replaced by the text of + the turn that drafts it, and the user read both. It is a key of its own because an earlier turn + may honestly say what the outcome must not ("I couldn't find a churn chart. Should I use + Retention instead?") before the agent recovers. """ normalized = _norm(answer) failures: list[str] = [ f"the answer does not mention {phrase!r}" for phrase in must_include if _norm(str(phrase)) not in normalized ] - for pattern in must_not_match: - # Compiled at validation time too, so a bad pattern fails the fixture rather than the - # run; compiling again here keeps this function usable on its own. + # Compiled at validation time too, so a bad pattern fails the fixture rather than the run; + # compiling again here keeps this function usable on its own. + for pattern in [*must_not_match, *must_not_match_any_turn]: found = re.search(str(pattern), answer, re.IGNORECASE) if found: failures.append(f"the answer matches {pattern!r}, which it must not (matched {found.group(0)!r})") + for pattern in must_not_match_any_turn: + if re.search(str(pattern), answer, re.IGNORECASE): + continue + for turn, earlier in enumerate(earlier_answers, start=1): + found = re.search(str(pattern), earlier, re.IGNORECASE) + if found: + failures.append( + f"earlier reply {turn} of {len(earlier_answers)} with prose matches {pattern!r}, which it " + f"must not (matched {found.group(0)!r})" + ) + break return failures @@ -1650,16 +1675,17 @@ def _forbidden_visualizations(expected_output: dict) -> list[dict]: return expected_output.get("must_not_contain") or [] -def _answer_assertions(expected_output: dict) -> tuple[list[str], list[str]]: - """The answer-text assertions, as ``(must_include, must_not_match)``.""" +def _answer_assertions(expected_output: dict) -> tuple[list[str], list[str], list[str]]: + """The answer-text assertions, as ``(must_include, must_not_match, must_not_match_any_turn)``.""" return ( list(expected_output.get("answer_must_include") or []), list(expected_output.get("answer_must_not_match") or []), + list(expected_output.get("answer_must_not_match_any_turn") or []), ) -def _compile_pattern(pattern: object) -> re.Pattern[str]: - """Compile one ``answer_must_not_match`` entry, naming the fixture key on failure. +def _compile_pattern(pattern: object, key: str = "answer_must_not_match") -> re.Pattern[str]: + """Compile one ``answer_must_not_match`` or ``answer_must_not_match_any_turn`` entry, naming the key on failure. Raises: ValueError: the pattern does not compile. @@ -1667,7 +1693,7 @@ def _compile_pattern(pattern: object) -> re.Pattern[str]: try: return re.compile(str(pattern)) except re.error as exc: - raise ValueError(f"answer_must_not_match carries an invalid regular expression {pattern!r}: {exc}") from exc + raise ValueError(f"{key} carries an invalid regular expression {pattern!r}: {exc}") from exc def _expects_dashboard(expected_output: dict) -> bool: @@ -1730,6 +1756,7 @@ def _has_date_range(expected_output: dict) -> bool: "must_not_contain", "answer_must_include", "answer_must_not_match", + "answer_must_not_match_any_turn", "clarification_reply", } ) @@ -1752,7 +1779,7 @@ def _validate_expectation(expected_output: dict) -> None: raise ValueError( f"expected_output states {unknown}, which no check reads; known keys: {sorted(_EXPECTATION_KEYS)}" ) - for key in ("answer_must_include", "answer_must_not_match"): + for key in ("answer_must_include", "answer_must_not_match", "answer_must_not_match_any_turn"): value = expected_output.get(key) if value is None: continue @@ -1765,11 +1792,13 @@ def _validate_expectation(expected_output: dict) -> None: raise ValueError(f"{key} must be a list of strings, got {value!r}") if any(not entry.strip() for entry in value): raise ValueError(f"{key} carries an empty entry, which asserts nothing: {value!r}") - must_include, must_not_match = _answer_assertions(expected_output) + must_include, must_not_match, must_not_match_any_turn = _answer_assertions(expected_output) # Compiled here so an unparseable pattern fails the fixture before the first API call, # rather than raising mid-scoring with a run already spent. for pattern in must_not_match: _compile_pattern(pattern) + for pattern in must_not_match_any_turn: + _compile_pattern(pattern, "answer_must_not_match_any_turn") if "clarification_reply" in expected_output: reply = expected_output["clarification_reply"] @@ -1806,7 +1835,7 @@ def _validate_expectation(expected_output: dict) -> None: raise ValueError("expects_dashboard is false, so the case must not list visualizations to find") if _is_edit(expected_output): raise ValueError("expects_dashboard is false is a creation shape; an edit always produces a patch") - if not must_include and not must_not_match: + if not must_include and not must_not_match and not must_not_match_any_turn: raise ValueError( "expects_dashboard is false needs an answer assertion; without one the case scores nothing " "beyond the absence of a draft, which an agent that fell over satisfies too" @@ -2576,6 +2605,7 @@ def evaluate_dashboard_response( answer_text: str = "", producing_tool_called: bool = False, shown_visualization_ids: frozenset[str] = frozenset(), + earlier_answers: tuple[str, ...] = (), ) -> DashboardEvaluation: """Score one dashboard response against its expectation. @@ -2588,16 +2618,16 @@ def evaluate_dashboard_response( """ is_edit = _is_edit(expected_output) forbidden = _forbidden_visualizations(expected_output) - must_include, must_not_match = _answer_assertions(expected_output) + must_include, must_not_match, must_not_match_any_turn = _answer_assertions(expected_output) expects_dashboard = _expects_dashboard(expected_output) applies = _Applies.of( expected_output, forbidden=bool(forbidden), - answer=bool(must_include or must_not_match), + answer=bool(must_include or must_not_match or must_not_match_any_turn), refusal=not expects_dashboard, ) tool = _producing_tool(expected_output) - answer_failures = _check_answer(answer_text, must_include, must_not_match) + answer_failures = _check_answer(answer_text, must_include, must_not_match, must_not_match_any_turn, earlier_answers) if not expects_dashboard: # The whole of a refusal case: nothing was drafted, and the answer said the right @@ -2912,6 +2942,12 @@ def _execute_single_dashboard_run( is_edit = _is_edit(expected_output) expects_dashboard = _expects_dashboard(expected_output) answer_text = "" + # The prose of the turn behind answer_text. An earlier turn reaches answer_must_not_match_any_turn by + # its prose only: a clarifyingQuestions part carries chart refs as gen-ai's prompt asks, which the UI shows + # as chips, so a token in it is no raw token the user reads. The last turn that spoke is answer_text + # as rendered, structured parts included, since it states the outcome the answer checks are about. + answer_prose = "" + earlier_answers: list[str] = [] tool_result: dict | None = None dashboard_part: dict | None = None patch_part: dict | None = None @@ -2989,8 +3025,12 @@ def _execute_single_dashboard_run( # produces the draft carries the text describing it, and that text is exactly what the # answer assertions are about. Kept as the last turn that said anything, so a silent # turn after a spoken one does not erase what the user was shown. - response_text = (chat_result.text_response or "").strip() or render_answer_text(chat_result) - answer_text = response_text or answer_text + prose = (chat_result.text_response or "").strip() + response_text = prose or render_answer_text(chat_result) + if response_text and answer_prose: + earlier_answers.append(answer_prose) + if response_text: + answer_text, answer_prose = response_text, prose candidate = _extract_tool_result(chat_result.tool_call_events or [], tool) if candidate is not None: @@ -3086,6 +3126,7 @@ def _execute_single_dashboard_run( _skill_activated(all_tool_call_events, _required_skill(expected_output)), patch_part=patch_part, answer_text=answer_text, + earlier_answers=tuple(earlier_answers), shown_visualization_ids=frozenset(shown_visualization_ids), # Any call, not just a successful one -- see DashboardEvaluation. BOTH tools, # not the one this case selected: a refusal is a creation shape, so `tool` is diff --git a/packages/gooddata-eval/tests/test_agentic_dashboard_skill.py b/packages/gooddata-eval/tests/test_agentic_dashboard_skill.py index 2eb4dbe48..996b3e7a8 100644 --- a/packages/gooddata-eval/tests/test_agentic_dashboard_skill.py +++ b/packages/gooddata-eval/tests/test_agentic_dashboard_skill.py @@ -3331,6 +3331,183 @@ def test_the_check_is_published_only_when_the_case_carries_it(self): ev = evaluate_dashboard_response(_draft_result(), part, _DC05_EXPECTED, skill_activated=True) assert "answer_matched" not in ev.strict_checks + def test_a_forbidden_pattern_in_an_earlier_reply_fails(self) -> None: + """A plan proposed in the first turn is replaced by the text of the turn that drafts it, + and the user read both: a raw token in the plan must fail the case.""" + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + expected = {**_DC05_EXPECTED, "answer_must_not_match_any_turn": [r"\{visualization/[0-9a-f-]+\}"]} + ev = evaluate_dashboard_response( + _draft_result(), + part, + expected, + skill_activated=True, + answer_text="I drafted the dashboard with Total Customers and Active Customers.", + earlier_answers=(f"Plan: 1. {{visualization/{_SUBSTITUTE}}} 2. Active Customers. Should I build it?",), + ) + assert not ev.answer_matched + assert any(f.startswith("earlier reply 1 of 1 with prose matches") for f in ev.failures) + + def test_a_phrase_in_an_earlier_reply_does_not_satisfy_must_include(self) -> None: + """The last reply states the outcome; an earlier plan naming the point does not make it.""" + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + expected = {**_DC05_EXPECTED, "answer_must_include": ["could not be covered"]} + ev = evaluate_dashboard_response( + _draft_result(), + part, + expected, + skill_activated=True, + answer_text="Here is your dashboard.", + earlier_answers=("One chart could not be covered. Should I build the rest?",), + ) + assert not ev.answer_matched + + def test_every_earlier_turn_that_spoke_reaches_the_answer_check(self) -> None: + """End to end: the plan turn's text reaches the any-turn check although the draft turn spoke last.""" + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + client = MagicMock() + client.send_message.side_effect = [ + _chat_result( + tool_calls=[_tool_call("set_skills", {"skills_to_activate": ["dashboard_builder"]})], + text=f"Here is the plan: {{visualization/{_SUBSTITUTE}}} and Active Customers. Should I create it?", + ), + _chat_result( + tool_calls=[_tool_call("draft_dashboard", _draft_result())], + parts=[part], + text="I drafted the dashboard.", + ), + ] + summary = _run_with(client, {**_DC05_EXPECTED, "answer_must_not_match_any_turn": [r"\{visualization/"]}) + assert client.send_message.call_count == 2 + assert not summary.pass_at_k + assert any(f.startswith("earlier reply 1 of 1 with prose matches") for f in summary.best.evaluation.failures) + + @pytest.mark.parametrize( + ("first", "second", "where"), + [ + # Every earlier turn is read, not only the first. + ( + "Let me look at the customers charts.", + "Plan: {token} and Active Customers. Should I create it?", + "2 of 2", + ), + # A plan in prose stays read when a turn with only a structured question follows it. + ("Plan: {token} and Active Customers. Should I create it?", None, "1 of 1"), + ], + ) + def test_a_token_in_any_earlier_prose_turn_fails(self, first: str, second: str | None, where: str) -> None: + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + token = f"{{visualization/{_SUBSTITUTE}}}" + question = {"type": "clarifyingQuestions", "questions": [{"text": "Which one?", "control": {"options": []}}]} + skills = [_tool_call("set_skills", {"skills_to_activate": ["dashboard_builder"]})] + client = MagicMock() + client.send_message.side_effect = [ + _chat_result(tool_calls=skills, text=first.format(token=token)), + _chat_result(text=second.format(token=token)) if second else _chat_result(parts=[question]), + _chat_result( + tool_calls=[_tool_call("draft_dashboard", _draft_result())], parts=[part], text="I drafted it." + ), + ] + summary = _run_with(client, {**_DC05_EXPECTED, "answer_must_not_match_any_turn": [r"\{visualization/"]}) + assert client.send_message.call_count == 3 + assert any(f.startswith(f"earlier reply {where} with prose matches") for f in summary.best.evaluation.failures) + + def test_a_chart_ref_in_an_earlier_structured_question_is_no_raw_token(self) -> None: + """gen-ai writes clarifyingQuestions options as chart refs, which the UI shows as chips.""" + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + question = { + "type": "clarifyingQuestions", + "questions": [ + { + "text": "Which customers chart?", + "control": {"options": [f"{{visualization/{_SUBSTITUTE}}} (bar chart)"]}, + } + ], + } + client = MagicMock() + client.send_message.side_effect = [ + _chat_result( + tool_calls=[_tool_call("set_skills", {"skills_to_activate": ["dashboard_builder"]})], + parts=[question], + ), + _chat_result( + tool_calls=[_tool_call("draft_dashboard", _draft_result())], + parts=[part], + text="I drafted the dashboard.", + ), + ] + summary = _run_with(client, {**_DC05_EXPECTED, "answer_must_not_match_any_turn": [r"\{visualization/"]}) + assert client.send_message.call_count == 2 + assert summary.best.evaluation.answer_matched + + def test_answer_must_not_match_reads_the_last_reply_only(self) -> None: + """An earlier turn may honestly say what the outcome must not before the agent recovers.""" + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + ev = evaluate_dashboard_response( + _draft_result(), + part, + {**_DC05_EXPECTED, "answer_must_not_match": ["couldn'?t find"]}, + skill_activated=True, + answer_text="I drafted the dashboard with Total Customers and Active Customers.", + earlier_answers=("I couldn't find a churn chart. Should I use Active Customers instead?",), + ) + assert ev.answer_matched + + def test_answer_must_not_match_any_turn_also_reads_the_last_reply(self) -> None: + part = _dashboard_part( + [_widget("Total Customers", _TOTAL_CUSTOMERS), _widget("Active Customers", _ACTIVE_CUSTOMERS)], + date_filter=_THIS_YEAR_FILTER, + ) + ev = evaluate_dashboard_response( + _draft_result(), + part, + {**_DC05_EXPECTED, "answer_must_not_match_any_turn": [r"\{visualization/"]}, + skill_activated=True, + answer_text=f"I drafted it with {{visualization/{_SUBSTITUTE}}}.", + ) + assert not ev.answer_matched + assert any(f.startswith("the answer matches") for f in ev.failures) + + @pytest.mark.parametrize( + ("value", "message"), + [ + ("{visualization/", "answer_must_not_match_any_turn must be a list of strings"), + (["{visualization/["], "answer_must_not_match_any_turn carries an invalid regular expression"), + ([" "], "answer_must_not_match_any_turn carries an empty entry"), + ], + ) + def test_an_unusable_any_turn_pattern_is_rejected_up_front(self, value: object, message: str) -> None: + with pytest.raises(ValueError, match=re.escape(message)): + _run_with(MagicMock(), {**_DC05_EXPECTED, "answer_must_not_match_any_turn": value}) + + def test_an_any_turn_pattern_is_an_answer_assertion_for_a_refusal(self) -> None: + expected = { + "type": "dashboard", + "expects_dashboard": False, + "answer_must_not_match_any_turn": [r"\{visualization/"], + } + client = MagicMock() + client.send_message.return_value = _chat_result(text="I can't build a Revenue by Planet chart.") + summary = _run_with(client, expected) + assert summary.best.evaluation.answer_matched + def test_an_invalid_regular_expression_is_rejected_up_front(self): client = MagicMock() with pytest.raises(ValueError, match="invalid regular expression"): @@ -4415,6 +4592,249 @@ def test_a_request_to_go_ahead_with_a_placement_is_a_confirmation(self, text: st def test_a_placement_that_needs_more_than_a_yes_is_a_question(self, text: str) -> None: assert classify_edit_reply(_chat_result(text=text), text) == "question" + @pytest.mark.parametrize( + "text", + [ + # A live reply to placing an existing chart on an open dashboard, verbatim. + "Here’s the existing Net Sales chart, showing Net Sales alongside the previous period. " + "Say “place it” and I’ll add it at the end of the dashboard.", + 'Here is the chart. Say "place it" and I\'ll add it at the end of the dashboard.', + "Here is the chart. Type “yes” and I will put it below Orders over time.", + "Here is the chart. Say 'go ahead' and I'll add it at the end.", + # An apostrophe in a later literal does not close the word's quotes. + 'Here is the chart. Say "ok" and I\'ll add it. The "Net Sales" chart is ready, it\'s fine.', + ], + ) + def test_a_word_to_say_before_the_placement_is_a_confirmation(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "confirmation" + + # A live reply, verbatim: the preview, then placing it told as the next step. + _NEXT_STEP_REPLY = ( + "The Net Sales chart shows current net sales alongside the previous period. I’ve previewed it for " + "placement at the end of the dashboard; applying it and switching the dashboard to last quarter " + "will be the next step." + ) + + @pytest.mark.parametrize( + "text", + [ + _NEXT_STEP_REPLY, + "Here is the chart. The next step is to place it at the end of the dashboard.", + "Here is the chart. Next, I’ll add it below Orders over time.", + "Here is the chart. Adding it at the end of the dashboard is the next step.", + # Asides that refuse or claim something other than placing the chart, and go-ahead conditions. + "Here is the chart. I can't wait to place it; applying it will be the next step.", + "I can't show the previous year, but here is the chart. Applying it is the next step.", + "I've added a comparison line to the preview. Placing it at the end is the next step.", + "Here is the chart. Next, I'll place it at the end, and you can then review it.", + "Here is the chart. Applying it will be the next step if you agree.", + "Here is the chart. When you are ready, the next step is to place it at the end.", + "Here is the chart. Next, I'll place it at the end of the Admin dashboard.", + # A refusal two sentences back is about another spot. + "I can't place it in the Sales tab, which is locked. Here is the chart. Next, I'll place it at the end.", + # A change to the chart or to its preview is no claim of having placed it. + "I've added the previous period to the chart. Placing it at the end of the dashboard will be the next step.", + "Here is the chart. I've added a comparison line to this chart. Applying it is the next step.", + "I've added it to the preview below. Placing it at the end of the dashboard will be the next step.", + # Something left to the user about another matter, or a refusal of another spot. + "Here is the chart. Next, I'll place it at the end; you can put it elsewhere later.", + "I can't place it in the Sales tab, which is locked. Next, I'll place it at the end instead.", + ], + ) + def test_placing_the_shown_chart_told_as_the_next_step_is_a_confirmation(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "confirmation" + assert classify_edit_reply(_chat_result(text=text), text, shown_earlier=True) == "confirmation" + + def test_a_next_step_without_a_shown_chart_stays_no_action(self) -> None: + text = self._NEXT_STEP_REPLY + assert classify_edit_reply(_chat_result(text=text), text) == "no_action" + + @pytest.mark.parametrize( + "text", + [ + "Here is the chart. Next, I’ll explain the filters.", + "Here is the chart. Adding a filter will be the next step.", + "Here is the chart. It will be applied to the dashboard. That is the next step for the team.", + ], + ) + def test_a_next_step_that_places_no_chart_stays_no_action(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "no_action" + + @pytest.mark.parametrize( + "text", + [ + # Left to the user, or the agent still lacks something. + "Here is the chart. Applying it is the next step, which you can do from the dashboard menu.", + "Here is the chart. Placing it is the next step for your dashboard admin.", + "Here is the chart. I’ve placed it at the end; applying it is the next step for you in the UI.", + "Here is the chart. The next step is to place it, but I need the section name first.", + "Here is the chart. The next step is to place it yourself from the dashboard menu.", + "Here is the chart. Applying it is the next step, but I still need your preferred section first.", + # Explaining how to place it places nothing. + "Here is the chart. Next, I'll explain how to add it.", + "Here is the chart. Next, I'll review the colors before I add it.", + # A placement named only as a noun places nothing. + "Here is the chart. Next, I’ll explain the placement options.", + ], + ) + def test_a_next_step_the_agent_will_not_take_now_stays_no_action(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "no_action" + + @pytest.mark.parametrize( + "text", + [ + "Here is the Net Sales chart. Applying it will be the next step once you pick a section.", + "Here is the Net Sales chart. The next step is to place it, so pick a section for it.", + ], + ) + def test_a_next_step_that_waits_for_a_pick_is_a_question(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "question" + + @pytest.mark.parametrize( + "text", + [ + "I can't place it on this dashboard because it is locked. Adding it to a new dashboard will be the next step.", + "I added it at the end. Next, I’ll move it to the top.", + ], + ) + def test_a_refusal_or_a_claim_beside_a_next_step_still_goes_ahead(self, text: str) -> None: + """No guard reads them: the "yes" that follows gets no patch when the agent cannot place it, and the + dashboard it then patches is what the item scores.""" + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "confirmation" + + @pytest.mark.parametrize( + "text", + [ + # A live reply, verbatim. + "I previewed the Net Sales chart. It shows Net Sales alongside the previous period comparison. " + "Confirm and I’ll propose placing it at the end of the dashboard and switching the dashboard " + "to last quarter.", + "Here is the chart. Confirm and I’ll go on adding it below Orders over time.", + ], + ) + def test_a_placement_named_by_its_ing_form_is_a_confirmation(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "confirmation" + + @pytest.mark.parametrize( + "text", + [ + # A word to say that is no go-ahead, in either quote style. + 'Here is the chart. Say "thanks" and I\'ll add it at the end.', + "Here is the chart. Say “thanks” and I’ll add it at the end.", + # A literal that asks for more than a yes is masked like any other quote. + "Here is the chart. Say “yes, but smaller” and I’ll add it at the end.", + "Here is the chart. Say “don’t place it” and I’ll add it anyway.", + # No word to say at all. + "Here is the chart and I'll add it once it is ready.", + "Here is the chart. Just say and I'll add it at the end.", + "Here is the chart. Say “yes”, then I can tell you how to add it yourself.", + # A literal whose quotes do not pair is no word to say. + "Here is the chart. Say \"ok it's fine\" and I'll add it.", + ], + ) + def test_a_word_to_say_that_is_no_go_ahead_is_no_confirmation(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "no_action" + + def test_a_go_ahead_word_that_places_nothing_stays_no_action(self) -> None: + """The word to say counts only in a sentence that places the chart.""" + text = "Here is the chart. Say “yes” and I’ll explain the options." + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "no_action" + + @pytest.mark.parametrize( + "text", + [ + 'Here is the chart. Say "replace" and I\'ll replace Order breakdown with it, ' + 'or say "add" and I\'ll add it as a new row.', + "Here is the chart. Say “replace” and I’ll replace Order breakdown with it. " + "Or say “add” and I’ll add it as a new row.", + # Two options with no "or" between them. + 'Here is the chart. Say "replace" and I\'ll replace Order breakdown with it. ' + 'Say "add" and I\'ll add it as a new row.', + # The second word offered without "say". + "Here is the chart. Say “replace” and I’ll replace Order breakdown with it, " + "or “add” and I’ll add it as a new row.", + # A go-ahead word and a way of placing tied to different placements. + "Here is the chart. Say “yes” and I’ll replace Order breakdown with it, " + "or say “add” and I’ll add it as a new row.", + ], + ) + def test_two_words_to_say_are_a_choice(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "question" + + @pytest.mark.parametrize( + "text", + [ + "Here is the chart. Say “place it” and I’ll add it. You can also type “yes” to go ahead.", + "Here is the chart. Say “yes” and I’ll place it at the end. Or say “go ahead” and I’ll do the same.", + "Here is the chart. Say “yes” and I’ll place it at the end of the dashboard (type “ok” if you prefer).", + "Here is the chart. Say “yes” and I’ll place it at the end. Or just say “place it” and I’ll add it there.", + 'Here is the chart. Say "add" and I\'ll add it at the end. You can also type "insert".', + # An opt-out is no option, in either quote style. + "Here is the chart. Say “yes” and I’ll add it at the end, or “no” to keep the dashboard as is.", + 'Here is the chart. Say "yes" and I\'ll add it at the end, or "no" to keep the dashboard as is.', + # A word for later offers nothing now. + "Here is the chart. Say “add” and I’ll add it at the end. To move it later, just type “move”.", + ], + ) + def test_two_words_to_say_for_the_same_placement_are_a_confirmation(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "confirmation" + + @pytest.mark.parametrize( + "text", + [ + # A live reply, verbatim: the preview, then a request for a place with no question mark. + "I found the existing **Net Sales** chart. It shows Net Sales with a previous-period comparison. " + "Review it below, then tell me where to place it on the dashboard.", + "Review it below, then let me know where you want it on the dashboard.", + "Here is the chart. Let me know which section it should go in.", + "Here is the chart. Just tell me where it should go.", + "Here are the charts. Tell me which section they should go in.", + "Here is the chart. Tell me where to place the new chart.", + "Here is the chart. Tell me where you want the Net Sales chart.", + "Here is the chart. Tell me which section the chart should go in.", + # Courtesies and asides that are no condition about the spot and no claim of placing it. + "Here is the chart. If it helps, tell me where to place it.", + "Here is the chart. I added a title. Let me know where you want the chart.", + "Here is the chart. Tell me where you want it. I've placed it in the preview below.", + "Here is the chart. I added a comparison line to it. Tell me where to place it.", + "I've added it to the preview below. Tell me where to place it.", + ], + ) + def test_a_request_for_a_place_without_a_question_mark_is_a_question(self, text: str) -> None: + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "question" + assert classify_edit_reply(_chat_result(text=text), text) == "question" + + @pytest.mark.parametrize( + "text", + [ + "Done. Let me know where else I can help.", + "Done. Let me know which other charts you need.", + "I renamed the chart. Tell me which filter to change next.", + "I added Net Sales at the end. Let me know what size you prefer for it.", + "I updated the date filter. Let me know where else you want it applied.", + "Here is the chart. Tell me where to add the filter.", + # A reply that says the chart is placed, or asks only on a condition. + "Here's the Top 10 Buyers chart. I replaced Order Breakdown with it. " + "Let me know where you want it moved if that spot is not right.", + "I replaced Order Breakdown with it. Let me know where you want it moved.", + "Here is the chart. If you would rather have it elsewhere, let me know where you want it.", + ], + ) + def test_a_request_for_something_other_than_a_place_stays_no_action(self, text: str) -> None: + assert classify_edit_reply(_chat_result(text=text), text) == "no_action" + @pytest.mark.parametrize( "text", [ @@ -4482,11 +4902,17 @@ def test_an_or_inside_the_title_of_the_chart_shown_is_no_choice(self) -> None: "Should I replace Won or Lost Deals with it?", "Should I replace Won or Lost Deals with this chart now?", "Should I replace Order breakdown with it, keeping the same width or height?", + "Should I replace Won or “Lost Deals” with it?", ], ) def test_an_or_with_no_place_or_question_after_it_is_no_choice(self, text: str) -> None: assert classify_edit_reply(_chat_result(text=text), text) == "confirmation" + def test_an_or_before_a_quoted_widget_name_is_no_choice_beside_a_preview(self) -> None: + text = "Should I replace Won or “Lost Deals” to make room for it?" + shown = _editor_turn(text=text, shown=[_preview_part()]) + assert classify_edit_reply(shown, text) == "confirmation" + @pytest.mark.parametrize( "text", [