Skip to content

Commit 052d9a9

Browse files
Merge pull request #1931 from gooddata/snapshot-master-06bf7727-to-rel/dev
[bot] Merge master/06bf7727 into rel/dev
2 parents c0c8869 + 06bf772 commit 052d9a9

2 files changed

Lines changed: 122 additions & 11 deletions

File tree

‎packages/gooddata-eval/src/gooddata_eval/core/agentic/document_skill.py‎

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import re
77
import time
88
from collections.abc import Iterator
9-
from dataclasses import dataclass, field
9+
from dataclasses import dataclass, field, replace
1010
from typing import Any
1111

1212
from gooddata_eval.core.agentic._conversation_context import classify_reply
@@ -65,7 +65,9 @@
6565
# The copilot's own rule: a document opens with a cover and has at least one content page.
6666
_COVER_PAGE = "cover"
6767
_CONTENT_PAGE = "content"
68-
_EXPECTATION_KEYS = frozenset({"period", "visualizations", "narrative", "expects_clarification"})
68+
_EXPECTATION_KEYS = frozenset(
69+
{"period", "visualizations", "narrative", "expects_clarification", "asked_first_required", "clarification_reply"}
70+
)
6971
# Template tokens the document renders at export time ({documentName}, {periodStart}, ...).
7072
_PLACEHOLDER_RE = re.compile(r"\{\w+\}")
7173
_SUMMARY_SLOT = "summary"
@@ -299,6 +301,10 @@ def _expects_clarification(expected_output: dict) -> bool:
299301
return "expects_clarification" in expected_output
300302

301303

304+
def _asked_first_required(expected_output: dict) -> bool:
305+
return expected_output.get("asked_first_required") is True
306+
307+
302308
def _validate_expectation(expected_output: Any) -> None:
303309
"""Reject a fixture the run could not score meaningfully, before the first API call.
304310
@@ -336,6 +342,19 @@ def _validate_expectation(expected_output: Any) -> None:
336342
raise ValueError(
337343
f"expects_clarification must be true or false, got {expected_output['expects_clarification']!r}"
338344
)
345+
if "asked_first_required" in expected_output:
346+
if not isinstance(expected_output["asked_first_required"], bool):
347+
raise ValueError(
348+
f"asked_first_required must be true or false, got {expected_output['asked_first_required']!r}"
349+
)
350+
if expected_output["asked_first_required"] and expected_output.get("expects_clarification") is not True:
351+
raise ValueError("asked_first_required needs expects_clarification: true")
352+
if "clarification_reply" in expected_output:
353+
reply = expected_output["clarification_reply"]
354+
if not isinstance(reply, str) or not reply.strip():
355+
raise ValueError(f"clarification_reply must be a non-empty reply, got {reply!r}")
356+
if expected_output.get("expects_clarification") is not True:
357+
raise ValueError("clarification_reply needs expects_clarification: true")
339358

340359

341360
def _validate_user_context(user_context: dict | None) -> None:
@@ -351,12 +370,16 @@ def _validate_user_context(user_context: dict | None) -> None:
351370
raise ValueError("user_context.view.report is the Report name; send view.document")
352371

353372

354-
def build_simulated_reply(expected_output: dict) -> str:
373+
def build_simulated_reply(expected_output: dict, *, asked: bool = True) -> str:
355374
"""The reply the simulated user sends when the copilot asks back instead of drafting.
356375
357376
Deterministic and LLM-free, built from what the fixture states, so a failure stays the
358377
copilot's rather than a simulated user that phrased things differently each run.
378+
A fixture's ``clarification_reply`` replaces it after a turn that ``asked``, for a question
379+
the charts and period do not answer. The run sends it once, to the first such turn.
359380
"""
381+
if asked and isinstance(reply := expected_output.get("clarification_reply"), str):
382+
return reply
360383
segments: list[str] = []
361384
visualizations = expected_output.get("visualizations") or []
362385
if visualizations:
@@ -380,6 +403,7 @@ class _Applies:
380403
period: bool
381404
charts: bool
382405
narrative: bool = False
406+
asked_first: bool = False
383407

384408

385409
@dataclass
@@ -398,6 +422,7 @@ class DocumentEvaluation:
398422
charts_matched: bool = False
399423
summaries_present: bool = False
400424
narrative_judged: bool = False
425+
asked_first: bool = False
401426
judge_reasoning: str = ""
402427
# Set when the judge returned something unreadable. The run then has no narrative verdict:
403428
# it is neither published as a 0 nor allowed to pass on the remaining checks.
@@ -438,6 +463,8 @@ def strict_checks(self) -> dict[str, bool]:
438463
checks["document_summaries_present"] = self.summaries_present
439464
if self.judge_error is None:
440465
checks["document_narrative_judged"] = self.narrative_judged
466+
if self.applies.asked_first:
467+
checks["document_asked_first"] = self.asked_first
441468
return checks
442469

443470

@@ -646,10 +673,12 @@ def diagnostics(self) -> dict[str, bool]:
646673
"""Observed but not scored.
647674
648675
Whether the copilot asked before drafting is recorded only when the fixture says it
649-
expects a question, and never gates: how much the copilot should ask is a product
650-
decision, not something a run can get wrong.
676+
expects a question. It gates only when the fixture sets ``asked_first_required``: how
677+
much the copilot should ask is a product decision, made per item.
651678
"""
652-
return {"document_asked_first": self.asked_first} if self.expects_clarification else {}
679+
if not self.expects_clarification or self.evaluation.applies.asked_first:
680+
return {}
681+
return {"document_asked_first": self.asked_first}
653682

654683
@property
655684
def judge_error(self) -> str | None:
@@ -711,7 +740,8 @@ def _execute_single_document_run(
711740
turn_offset = 0.0
712741
tool_index_offset = 0
713742
reasoning_index_offset = 0
714-
first_turn_asked = False
743+
asked_before_draft = False
744+
replied = False
715745

716746
run_started = time.monotonic()
717747
for iteration in range(max_iterations):
@@ -748,8 +778,8 @@ def _execute_single_document_run(
748778
break
749779

750780
response_text = (chat_result.text_response or "").strip() or render_answer_text(chat_result)
751-
if iteration == 0:
752-
first_turn_asked = classify_reply(chat_result, response_text) == "question"
781+
asked = classify_reply(chat_result, response_text) != "no_action"
782+
asked_before_draft = asked_before_draft or asked
753783
if not response_text and not chat_result.tool_call_events:
754784
break
755785
if iteration >= max_iterations - 1:
@@ -758,7 +788,8 @@ def _execute_single_document_run(
758788
f"[timer] document_skill {conversation_id} GoodData turn {turns} complete after "
759789
f"{agent_elapsed:.2f}s; answering with the expected charts and period"
760790
)
761-
current_question = build_simulated_reply(expected_output)
791+
current_question = build_simulated_reply(expected_output, asked=asked and not replied)
792+
replied = replied or asked
762793

763794
evaluation = evaluate_document_response(
764795
tool_result,
@@ -767,14 +798,19 @@ def _execute_single_document_run(
767798
skill_activated=_skill_activated(all_tool_call_events, _BUILDER_SKILL),
768799
legacy_names=legacy_wire_names(all_parts, all_tool_call_events),
769800
)
801+
if _asked_first_required(expected_output):
802+
evaluation.applies = replace(evaluation.applies, asked_first=True)
803+
evaluation.asked_first = asked_before_draft
804+
if tool_result is not None and not asked_before_draft:
805+
evaluation.failures.append("the copilot drafted without asking first")
770806
if judge is not None and _has_narrative(expected_output):
771807
timings.judge_s += _judge_narrative(evaluation, judge, document_part, question, expected_output["narrative"])
772808

773809
return DocumentRunResult(
774810
conversation_id=conversation_id,
775811
evaluation=evaluation,
776812
expects_clarification=_expects_clarification(expected_output),
777-
asked_first=first_turn_asked,
813+
asked_first=asked_before_draft,
778814
tool_result=tool_result,
779815
document_part=document_part,
780816
total_turns=turns,

‎packages/gooddata-eval/tests/test_agentic_document_skill.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -615,6 +615,10 @@ def test_the_document_format_is_recorded_in_the_run_metadata(
615615
({"visualizations": []}, "visualizations is empty"),
616616
({"visualizations": [{"title": "Revenue"}]}, "every visualization needs an 'id'"),
617617
({"expects_clarification": "yes"}, "expects_clarification must be true or false"),
618+
({"asked_first_required": "yes"}, "asked_first_required must be true or false"),
619+
({"asked_first_required": True}, "asked_first_required needs expects_clarification: true"),
620+
({"clarification_reply": " "}, "clarification_reply must be a non-empty reply"),
621+
({"clarification_reply": "Use 2026."}, "clarification_reply needs expects_clarification: true"),
618622
],
619623
)
620624
def test_an_unusable_fixture_is_rejected_before_any_request(expected: dict, message: str) -> None:
@@ -788,6 +792,77 @@ def test_a_structured_clarifying_question_counts_as_asking() -> None:
788792
assert run.diagnostics == {"document_asked_first": True}
789793

790794

795+
def test_a_run_that_must_ask_first_fails_when_it_drafts_straight_away() -> None:
796+
expected = {"expects_clarification": True, "asked_first_required": True}
797+
run = _execute_single_document_run(_ScriptedChatClient([_drafting_turn()]), "c", "q", expected, 4)
798+
assert run.evaluation.strict_checks["document_asked_first"] is False
799+
assert not run.evaluation.strict_pass
800+
assert run.diagnostics == {}
801+
802+
803+
def test_a_run_that_must_ask_first_passes_when_it_asks_then_drafts() -> None:
804+
question = _chat_result(text="The pages show no data for 2030. Drop them, change the period, or keep them?")
805+
expected = {"expects_clarification": True, "asked_first_required": True}
806+
run = _execute_single_document_run(_ScriptedChatClient([question, _drafting_turn()]), "c", "q", expected, 4)
807+
assert run.evaluation.strict_checks["document_asked_first"] is True
808+
assert run.evaluation.strict_pass
809+
810+
811+
def test_a_run_that_must_ask_first_passes_when_it_asks_for_confirmation() -> None:
812+
question = _chat_result(text="I could not find any data for 2030. Should I create the document anyway?")
813+
expected = {"expects_clarification": True, "asked_first_required": True}
814+
run = _execute_single_document_run(_ScriptedChatClient([question, _drafting_turn()]), "c", "q", expected, 4)
815+
assert run.evaluation.strict_checks["document_asked_first"] is True
816+
assert run.evaluation.strict_pass
817+
818+
819+
def test_a_run_that_must_ask_first_passes_when_it_asks_after_a_status_turn() -> None:
820+
status = _chat_result(text="Working on it.")
821+
question = _chat_result(text="Which period?")
822+
expected = {"expects_clarification": True, "asked_first_required": True}
823+
run = _execute_single_document_run(_ScriptedChatClient([status, question, _drafting_turn()]), "c", "q", expected, 4)
824+
assert run.evaluation.strict_checks["document_asked_first"] is True
825+
assert run.evaluation.strict_pass
826+
827+
828+
def test_a_run_that_must_ask_first_and_never_drafts_fails_only_for_the_missing_draft() -> None:
829+
expected = {"expects_clarification": True, "asked_first_required": True}
830+
run = _execute_single_document_run(_ScriptedChatClient([_chat_result()]), "c", "q", expected, 4)
831+
assert run.evaluation.failures == ["the agent never produced a successful draft_document call"]
832+
833+
834+
def test_the_fixture_reply_answers_the_copilots_question() -> None:
835+
client = _ScriptedChatClient([_chat_result(text="Which period?"), _drafting_turn()])
836+
expected = {"expects_clarification": True, "clarification_reply": "Use the first half of 2026 instead."}
837+
_execute_single_document_run(client, "c", "q", expected, 4)
838+
assert client.sent == ["q", "Use the first half of 2026 instead."]
839+
840+
841+
def test_the_fixture_reply_answers_only_the_first_question() -> None:
842+
client = _ScriptedChatClient(
843+
[_chat_result(text="Which period?"), _chat_result(text="Which charts?"), _drafting_turn()]
844+
)
845+
expected = {"expects_clarification": True, "clarification_reply": "Use the first half of 2026 instead."}
846+
_execute_single_document_run(client, "c", "q", expected, 4)
847+
assert client.sent == [
848+
"q",
849+
"Use the first half of 2026 instead.",
850+
"Anything else is up to you. Please create the document now.",
851+
]
852+
853+
854+
def test_the_fixture_reply_waits_for_a_question() -> None:
855+
expected = {"expects_clarification": True, "clarification_reply": "Use the first half of 2026 instead."}
856+
status = _chat_result(text="Working on it.")
857+
client = _ScriptedChatClient([status, _chat_result(text="Which period?"), _drafting_turn()])
858+
_execute_single_document_run(client, "c", "q", expected, 4)
859+
assert client.sent == [
860+
"q",
861+
"Anything else is up to you. Please create the document now.",
862+
"Use the first half of 2026 instead.",
863+
]
864+
865+
791866
# ── page kinds, fixture keys, asking, two drafts in one turn ───────────────
792867

793868

0 commit comments

Comments
 (0)