From f3972ed163aeffc24036e0f7442037d9190a9f3a Mon Sep 17 00:00:00 2001 From: duongthimy Date: Tue, 24 Nov 2026 22:10:00 +0100 Subject: [PATCH] feat(gooddata-eval): add agentic_memory test kind - One question per run, graded twice; the run passes only when both pass - memory_injected (code): the memory items gen-ai injected into the turn's prompt, read from the applyMemory detail of the turn's items (/items), hold every memory_input.injected title and no memory_input.not_injected title; without the detail (feature flag enableGenAiInteractionIntelligence off) the check fails naming it - memory_answer_pass (judge): the answer against expected_output, with the general-question judge steps copied into the kind - MemoryInput model; Langfuse loader reads memory_input; CLI dispatch, single-turn and parallel-safe registries; README jira: QA-30177 risk: low --- packages/gooddata-eval/AGENTS.md | 2 +- packages/gooddata-eval/README.md | 43 +- .../src/gooddata_eval/cli/agentic_runner.py | 16 + .../gooddata_eval/core/agentic/__init__.py | 12 + .../src/gooddata_eval/core/agentic/memory.py | 596 ++++++++++++++++++ .../core/dataset/langfuse_source.py | 36 +- .../src/gooddata_eval/core/interaction.py | 1 + .../src/gooddata_eval/core/models.py | 38 +- .../tests/test_agentic_memory.py | 499 +++++++++++++++ .../tests/test_agentic_runner.py | 6 +- .../gooddata-eval/tests/test_trace_linker.py | 1 + 11 files changed, 1243 insertions(+), 7 deletions(-) create mode 100644 packages/gooddata-eval/src/gooddata_eval/core/agentic/memory.py create mode 100644 packages/gooddata-eval/tests/test_agentic_memory.py diff --git a/packages/gooddata-eval/AGENTS.md b/packages/gooddata-eval/AGENTS.md index 1ce6af55e..65deb9ef7 100644 --- a/packages/gooddata-eval/AGENTS.md +++ b/packages/gooddata-eval/AGENTS.md @@ -64,7 +64,7 @@ its own shape. `test_kind` on the item is what labels the result, not the evalua which is why `knowledge_question` can reuse `GeneralQuestionEvaluator` verbatim. `dashboard_summary` items additionally need `summary_input`, `document_takeaway` items `takeaway_input`, `catalog_metadata` items `catalog_input`, `agentic_agent_switcher` items -`agent_switcher_input`. `agentic_knowledge` items keep earlier user turns in +`agent_switcher_input`, `agentic_memory` items `memory_input`. `agentic_knowledge` items keep earlier user turns in `expected_output.setup_turns` (`question` is the graded turn); their evaluator lives in `core/evaluators/knowledge.py` but is agentic-only, so it is not in the single-shot registry. diff --git a/packages/gooddata-eval/README.md b/packages/gooddata-eval/README.md index cbb2047dd..d0a6e1ea3 100644 --- a/packages/gooddata-eval/README.md +++ b/packages/gooddata-eval/README.md @@ -320,7 +320,7 @@ linking ran. Pass `TAVERN_E2E_SKIP_TRACE_LINK=1` to opt out of linking altogethe their eval kind, and states latency for each: - **Single-shot** — kinds that send exactly one chat message per run: every non-agentic kind, plus - `agentic_general_question`, `agentic_guardrail` and `agentic_search`. + `agentic_general_question`, `agentic_guardrail`, `agentic_search` and `agentic_memory`. - **Multi-turn** — kinds that drive a simulated user or fixture turns: `agentic_visualization` (and `vis_agentic`), `agentic_metric_skill`, `agentic_alert_skill`, `agentic_dashboard_skill`, `agentic_document_skill`, `agentic_kda_skill`, `agentic_anomaly_detection`, `agentic_what_if`, @@ -983,6 +983,47 @@ first message when the new conversation is bound to another agent (`agent_bound` are reported as `turn_`, e.g. `turn2_skills_used`, `turn2_include_0`. The CI entry point is `evaluate_agentic_agent_switcher`, which takes the whole item; `--agent-id` does not apply. +### `agentic_memory` items + +Memory items check AI memory (organization- and workspace-level memory items). Each run sends +`question` in a new conversation and is graded twice; it passes only when both pass: + +- `memory_injected` (code) — the memory items gen-ai injected into the turn's prompt, read from the + `applyMemory` detail of the turn's conversation items (`/items`), hold every title in + `memory_input.injected` and none in `memory_input.not_injected`. A turn with other details and + no `applyMemory` injected nothing, so an item with only `not_injected` titles passes there. + gen-ai records the details only while the `enableGenAiInteractionIntelligence` feature flag is on + for the organization. A turn with no detail at all, or items that cannot be read, leave the + injected memory unknown: the run fails with the check `memory_read` (also the name of its + Langfuse score) and the exit `chat_error`. The message of a turn without details names the flag. +- `memory_answer_pass` (judge) — the answer against `expected_output`, with the + `agentic_general_question` judge steps. The judge reads text only, so a chart the turn created + is given to it as one line with the chart's title and type. + +Titles are compared exactly. Injected means "in the prompt", not "followed": gen-ai presents memory +as defaults, so whether the answer applies an item is the judge's part. In a Langfuse dataset the +block goes in the item's `metadata` or its `input` object; an item carrying it is an `agentic_memory` +item unless it declares another `test_kind` or its `expectedOutput` has a `visualization` key (that +infers `vis_agentic`), as for the other structured inputs; `metadata.test_kind: "agentic_memory"` +forces the memory kind. + +```json +{ + "id": "om-auto-returns", + "dataset_name": "org_memory", + "test_kind": "agentic_memory", + "question": "Which product categories had the most returned orders in 2024? Anything I should keep in mind?", + "expected_output": "The answer mentions that orders can be returned within 30 days of delivery.", + "memory_input": { + "injected": ["help-line", "returns-30-days"], + "not_injected": ["returns-14-days-disabled"] + } +} +``` + +At least one title is required, and a title cannot be in both lists. The CI entry point is +`evaluate_agentic_memory`, which takes the whole item. + ### `agentic_knowledge` items Knowledge items ask the AI chat questions it answers from knowledge documents (tools diff --git a/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py b/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py index a130f2d89..91986e21f 100644 --- a/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py +++ b/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py @@ -25,6 +25,7 @@ from gooddata_eval.core.agentic.guardrail import evaluate_agentic_guardrail from gooddata_eval.core.agentic.kda_skill import evaluate_agentic_kda_skill from gooddata_eval.core.agentic.knowledge import evaluate_agentic_knowledge +from gooddata_eval.core.agentic.memory import evaluate_agentic_memory from gooddata_eval.core.agentic.metric_skill import evaluate_agentic_metric_skill from gooddata_eval.core.agentic.search_tool import evaluate_agentic_search_tool from gooddata_eval.core.agentic.visualization import evaluate_agentic_visualization @@ -67,6 +68,7 @@ class _LfKw(TypedDict, total=False): "agentic_what_if", "agentic_agent_switcher", "agentic_knowledge", + "agentic_memory", } ) @@ -86,6 +88,7 @@ class _LfKw(TypedDict, total=False): # reads like a model regression. # # agentic_general_question, agentic_guardrail answer questions only, no tool writes +# agentic_memory same as agentic_general_question, plus a read of /items # agentic_search search_objects, read-only by definition; an item # with setup_turns runs serially (item_runs_in_parallel) # vis_agentic, agentic_visualization visualizations come back as AAC proposals @@ -95,6 +98,7 @@ class _LfKw(TypedDict, total=False): { "agentic_general_question", "agentic_guardrail", + "agentic_memory", "agentic_search", "vis_agentic", "agentic_visualization", @@ -400,6 +404,18 @@ def _dispatch_agentic( gate=gate, **lf_kw, ) + elif kind == "agentic_memory": + # The item carries its own memory_input and user_context. + return evaluate_agentic_memory( + host=host, + token=token, + workspace_id=workspace_id, + dataset_item=item, + k=k, + gate=gate, + agent_id=agent_id, + **lf_kw, + ) elif kind == "agentic_knowledge": return evaluate_agentic_knowledge( host=host, diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/__init__.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/__init__.py index a7475042f..a0b33b8e6 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/__init__.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/__init__.py @@ -61,6 +61,13 @@ evaluate_agentic_kda_skill, run_agentic_kda_skill, ) +from gooddata_eval.core.agentic.memory import ( + AgenticMemorySummary, + MemoryAssertionError, + MemoryRunResult, + evaluate_agentic_memory, + run_agentic_memory, +) from gooddata_eval.core.agentic.metric_skill import ( AgenticMetricSummary, MetricRunResult, @@ -92,6 +99,11 @@ run_agentic_report_skill = run_agentic_document_skill __all__ = [ + "run_agentic_memory", + "evaluate_agentic_memory", + "MemoryRunResult", + "MemoryAssertionError", + "AgenticMemorySummary", "AgentSwitcherAssertionError", "AgentSwitcherRunResult", "AgenticAgentSwitcherSummary", diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/memory.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/memory.py new file mode 100644 index 000000000..fac670eb2 --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/memory.py @@ -0,0 +1,596 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +"""Agentic AI memory evaluation runner (`agentic_memory`). + +One question per run, graded twice: +- code: the memory items gen-ai injected into the turn's prompt (`applyMemory` detail of the + turn's items, read from `/items`) hold every `memory_input.injected` title and no + `memory_input.not_injected` title; +- judge: the answer text against the item's expected output. + +gen-ai records the details of a turn only while the `enableGenAiInteractionIntelligence` feature +flag is on for the organization, and `applyMemory` only when the turn injected an item: +- a turn with other details and no `applyMemory` injected nothing; +- a turn with no detail at all cannot be checked: the run fails with a message naming the flag. +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field +from typing import Any + +import httpx + +from gooddata_eval.core.agentic._failed_runs import build_failed_runs +from gooddata_eval.core.agentic._failure_message import FailedCheck, failed_check_records +from gooddata_eval.core.agentic._gate import ( + DEFAULT_GATE, + EvalGate, + gate_passed, + log_gate_scores, + stamp_gate_metadata, +) +from gooddata_eval.core.agentic._outcome import ( + agentic_detail, + agentic_success, + attach_labels, + chat_failure_exit, + failure_message_head, + label_runs, + mark_unscored_run, + raise_agentic_failure, +) +from gooddata_eval.core.agentic._trace_linker import ( + RunIdentity, + RunTraceContext, + SubmitTraceLink, + conversations_to_link, + open_item_trace, + run_trace_link_inline, + submit_trace_scoring, + utc_now, +) +from gooddata_eval.core.chat.render import render_answer_text +from gooddata_eval.core.chat.sse_client import ADHOC_VIZ_ID, ChatClient, ChatError +from gooddata_eval.core.config import ReasoningEffort +from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError, LLMJudge, score_run +from gooddata_eval.core.langfuse.item_scope import item_scope +from gooddata_eval.core.models import ( + AgenticAssertionError, + AgenticEvalOutcome, + ChatResult, + DatasetItem, + LoopExit, + MemoryInput, + ReasoningStepEvent, + ToolCallEvent, + build_latency_breakdown, +) +from gooddata_eval.core.timing import PhaseTimings, log_timer, sum_timings + +_DEFAULT_K = 1 +_TEST_KIND = "agentic_memory" +_APPLY_MEMORY = "applyMemory" +_FLAG = "enableGenAiInteractionIntelligence" + +# Own copy of the general-question judge steps: a change there must not move this kind's verdicts. +_MEMORY_EVALUATION_STEPS: list[str] = [ + ( + "Read the EXPECTED OUTPUT carefully. It describes what a correct response to the INPUT should convey — " + "this may include specific facts, figures, key concepts, or analytical conclusions. " + "Use it as the ground truth for evaluation." + ), + ( + "Check that the ACTUAL OUTPUT genuinely attempts to answer the question. " + "Return FAIL (0) if the chatbot refuses, says it cannot answer, or deflects a legitimate analytical question." + ), + ( + "Check whether the key facts, figures, or concepts described in the EXPECTED OUTPUT " + "are present and correctly represented in the ACTUAL OUTPUT. " + "Exact wording is not required — focus on conceptual and factual alignment. " + "Return FAIL (0) if important information from the EXPECTED OUTPUT is missing or contradicted." + ), + ( + "Do not penalize the chatbot for providing additional relevant context, richer explanations, " + "or different but equivalent phrasing. " + "Focus only on whether the core answer aligns with the EXPECTED OUTPUT." + ), + ( + "If the ACTUAL OUTPUT is empty, null, or contains only an error message unrelated to the question, " + "return FAIL (0)." + ), + ( + "Return PASS (1) if the chatbot's response is factually and conceptually aligned with the EXPECTED OUTPUT. " + "Return FAIL (0) otherwise." + ), +] + + +@dataclass +class MemoryRunResult: + """One run: the answer, the judge's verdict and the memory gen-ai injected.""" + + conversation_id: str + actual_output: str + judge_passed: bool + reasoning: str + # Titles of the memory items injected into the turn's prompt; None when they could not be read. + applied_memory: list[str] | None + memory_error: str | None + reasoning_steps: list[str] = field(default_factory=list) + response_id: str | None = None + timings: PhaseTimings = field(default_factory=PhaseTimings) + # An unreadable judge response leaves the run ungraded, as in the general-question kind. + judge_error: str | None = None + tool_call_events: list[ToolCallEvent] = field(default_factory=list) + reasoning_step_events: list[ReasoningStepEvent] = field(default_factory=list) + run_latency_s: float = 0.0 + # Set when the chat turn itself failed (no final answer, timeout, chat error): the run is a + # failure with neither check run. + chat_error: str | None = None + exit_reason: LoopExit | None = None + + @property + def memory_passed(self) -> bool: + return self.memory_error is None and self.chat_error is None + + @property + def memory_check(self) -> str: + """The name the memory check is reported under: `memory_read` when the injected memory + is unknown, which is not a wrong injection.""" + return "memory_read" if self.applied_memory is None else "memory_injected" + + @property + def passed(self) -> bool: + return self.judge_passed and self.memory_passed + + @property + def ungraded(self) -> bool: + """No verdict: the judge could not grade and the memory check passed. A failed memory + check decides the run on its own, so that run is a failure whatever the judge did.""" + return self.judge_error is not None and self.memory_passed + + +@dataclass +class AgenticMemorySummary: + """Aggregated outcome of K runs of one memory item.""" + + run_results: list[MemoryRunResult] + pass_at_k: bool + pass_power_k: bool + best: MemoryRunResult + + @property + def scored_run_results(self) -> list[MemoryRunResult]: + return [r for r in self.run_results if not r.ungraded] + + @property + def judge_errors(self) -> list[str]: + return [r.judge_error for r in self.run_results if r.ungraded and r.judge_error is not None] + + +class MemoryAssertionError(AgenticAssertionError): + """Raised when a memory evaluation fails.""" + + +def _turn_details(items: list[dict[str, Any]], response_id: str | None) -> list[dict[str, Any]]: + return [ + item["detail"] + for item in items + if isinstance(item.get("detail"), dict) and (response_id is None or item.get("responseId") == response_id) + ] + + +def applied_memory_titles(items: list[dict[str, Any]], response_id: str | None) -> list[str] | None: + """Titles from the `applyMemory` detail of the turn `response_id`, in retrieval order. + + Empty when the turn has other details and no `applyMemory`: it injected no memory. + None when the turn has no detail at all: gen-ai did not record them (flag off). + """ + details = _turn_details(items, response_id) + if not details: + return None + titles: list[str] = [] + for detail in details: + if detail.get("category") != _APPLY_MEMORY: + continue + raw = detail.get("items") + entries = raw if isinstance(raw, list) else [] + titles += [e["title"] for e in entries if isinstance(e, dict) and isinstance(e.get("title"), str)] + return titles + + +_NOT_RECORDED = ( + f"the turn recorded no detail, so the injected memory is unknown: is the {_FLAG} feature flag on " + "for the organization?" +) + + +def memory_check_error(spec: MemoryInput, applied: list[str] | None) -> str | None: + """Why the injected memory does not match `spec`; None when it does.""" + if applied is None: + return _NOT_RECORDED + missing = [t for t in spec.injected if t not in applied] + unwanted = [t for t in spec.not_injected if t in applied] + problems = [] + if missing: + problems.append(f"not injected: {missing}") + if unwanted: + problems.append(f"injected but must not be: {unwanted}") + return "; ".join(problems) or None + + +def _render_turn(chat_result: ChatResult) -> str: + """The answer text, plus one line per chart the turn created. + + The judge reads text only. An answer that is a chart and a closing line would read as no + answer at all, and the judge would fail it whatever the item grades. + """ + objects = chat_result.created_visualizations.objects if chat_result.created_visualizations else [] + charts = [ + f'[The answer shows a chart: "{viz.title or "untitled"}" ({viz.type})]' + for viz in objects + if viz.id != ADHOC_VIZ_ID + ] + return "\n\n".join(chunk for chunk in (*charts, render_answer_text(chat_result)) if chunk) + + +def _run_single( + client: ChatClient, judge: LLMJudge, conversation_id: str, item: DatasetItem, spec: MemoryInput +) -> MemoryRunResult: + item_started = time.monotonic() + try: + chat_result = client.send_message(conversation_id, item.question) + except ChatError as exc: + # The agent's own failure: this run fails, the other runs of the item still count. + elapsed = time.monotonic() - item_started + partial = exc.partial_result + return MemoryRunResult( + conversation_id=conversation_id, + actual_output="", + judge_passed=False, + reasoning="", + applied_memory=None, + memory_error=None, + timings=PhaseTimings(agent_s=elapsed), + tool_call_events=list(partial.tool_call_events or []) if partial else [], + reasoning_step_events=list(partial.reasoning_step_events or []) if partial else [], + run_latency_s=elapsed, + chat_error=f"chat failed: {exc}", + exit_reason=chat_failure_exit(exc), + ) + actual_output = _render_turn(chat_result) + agent_elapsed = time.monotonic() - item_started + log_timer(f"[timer] memory {conversation_id} GoodData response complete after {agent_elapsed:.2f}s") + + # The memory check reads the stored items. Without them the injected memory is unknown: the + # run fails with the exit `chat_error`, as in the agent-switcher kind, not as a wrong injection. + exit_reason = None + try: + applied = applied_memory_titles(client.list_items(conversation_id), chat_result.response_id) + memory_error = memory_check_error(spec, applied) + except (httpx.HTTPError, ValueError) as e: + applied, memory_error = None, f"reading the conversation items failed: {type(e).__name__}: {e}" + if applied is None: + exit_reason = LoopExit.CHAT_ERROR + + judge_started = time.monotonic() + verdict = score_run( + judge, input=item.question, expected_output=str(item.expected_output), actual_output=actual_output + ) + judge_elapsed = time.monotonic() - judge_started + return MemoryRunResult( + conversation_id=conversation_id, + actual_output=actual_output, + judge_passed=verdict.passed, + reasoning=verdict.reasoning, + applied_memory=applied, + memory_error=memory_error, + reasoning_steps=list(chat_result.reasoning_steps or []), + response_id=chat_result.response_id, + timings=PhaseTimings(agent_s=agent_elapsed, judge_s=judge_elapsed), + judge_error=verdict.error, + tool_call_events=list(chat_result.tool_call_events or []), + reasoning_step_events=list(chat_result.reasoning_step_events or []), + run_latency_s=time.monotonic() - item_started, + exit_reason=exit_reason, + ) + + +def _memory_spec(item: DatasetItem) -> MemoryInput: + if item.memory_input is None: + raise ValueError(f"{_TEST_KIND} item {item.id!r} has no memory_input") + if not str(item.expected_output or "").strip(): + raise ValueError(f"{_TEST_KIND} item {item.id!r} has no expected_output for the judge") + return item.memory_input + + +def _dataset_item(dataset_item: DatasetItem | dict, dataset_name: str) -> DatasetItem: + """The item as a DatasetItem; a dict is the item as stored in a fixture file.""" + if isinstance(dataset_item, DatasetItem): + return dataset_item + return DatasetItem.model_validate( + {"id": "", "test_kind": _TEST_KIND, "expected_output": "", **dataset_item, "dataset_name": dataset_name} + ) + + +def run_agentic_memory( + host: str, + token: str, + workspace_id: str, + dataset_item: DatasetItem, + k: int = _DEFAULT_K, + reasoning_effort: ReasoningEffort | None = None, + agent_id: str | None = None, +) -> AgenticMemorySummary: + """Run one memory item K times, each in its own conversation. + + Raises: + ValueError: the item has no `memory_input`, or k is below 1. Raised before any chat request. + """ + if k < 1: + raise ValueError(f"k must be at least 1, got {k}") + spec = _memory_spec(dataset_item) + client = ChatClient( + host=host, + token=token, + workspace_id=workspace_id, + reasoning_effort=reasoning_effort, + agent_id=agent_id, + user_context=dataset_item.user_context, + ) + judge = LLMJudge(_MEMORY_EVALUATION_STEPS) + run_results: list[MemoryRunResult] = [] + try: + for _ in range(k): + conv_id = client.create_conversation() + try: + run_results.append(_run_single(client, judge, conv_id, dataset_item, spec)) + finally: + client.delete_conversation(conv_id) + finally: + client.close() + + # As in the general-question kind: pass@K ignores ungraded runs, pass^K counts them as unverified. + scored = [r for r in run_results if not r.ungraded] + pass_at_k = any(r.passed for r in scored) + pass_power_k = len(scored) == len(run_results) and bool(scored) and all(r.passed for r in scored) + best = max(scored or run_results, key=lambda r: (r.passed, r.memory_passed, r.judge_passed)) + return AgenticMemorySummary(run_results=run_results, pass_at_k=pass_at_k, pass_power_k=pass_power_k, best=best) + + +def _run_detail(run: MemoryRunResult) -> dict: + return { + "judge_passed": run.judge_passed, + "judge_reasoning": run.reasoning, + "memory_passed": run.memory_passed, + "applied_memory": run.applied_memory, + "actual_output": run.actual_output, + **({"chat_error": run.chat_error} if run.chat_error is not None else {}), + "latency_breakdown": build_latency_breakdown(run.tool_call_events, run.reasoning_step_events), + } + + +def _failed_checks(run: MemoryRunResult) -> list[dict]: + checks = [] + if run.chat_error is not None: + return failed_check_records([FailedCheck("chat_turn", actual=run.chat_error)]) + if run.memory_error is not None: + checks.append(FailedCheck(run.memory_check, actual=run.memory_error)) + if run.judge_error is None and not run.judge_passed: + checks.append(FailedCheck("memory_answer_pass", part="judge", actual=run.reasoning)) + return failed_check_records(checks) + + +def _attach_diagnostics( + error: JudgeResponseError, + best: MemoryRunResult, + detail: dict, + failed_runs: list[dict], + runs_passed: int, + runs_effective: int, + run_latencies_s: list[float], + best_run_latency_s: float | None, +) -> None: + """The report payload of an item no run of which the judge could grade.""" + error.reasoning_steps = best.reasoning_steps + error.conversation_id = best.conversation_id + error.response_id = best.response_id + error.detail = detail + error.runs_passed = runs_passed + error.runs_effective = runs_effective + error.failed_runs = failed_runs + error.run_latencies_s = run_latencies_s + error.best_run_latency_s = best_run_latency_s + + +def evaluate_agentic_memory( + host: str, + token: str, + workspace_id: str, + dataset_item: DatasetItem | dict, + k: int = _DEFAULT_K, + agent_id: str | None = None, + langfuse: object | None = None, + dataset_item_id: str | None = None, + dataset_name: str = "memory", + run_timestamp: str | None = None, + model_version_override: str | None = None, + run_metadata_extra: dict | None = None, + reasoning_effort: ReasoningEffort | None = None, + submit_trace_link: SubmitTraceLink = run_trace_link_inline, + gate: EvalGate = DEFAULT_GATE, +) -> AgenticEvalOutcome: + """Run a memory item K times, log to Langfuse, and raise MemoryAssertionError when the gate fails. + + Args: + host: GoodData host URL. + token: API token. + workspace_id: Workspace the conversations run in. + dataset_item: The item, or the item as stored, carrying `memory_input` and optionally `user_context`. + k: Runs per item; each creates its own conversation. + agent_id: Agent the conversations are created with; the default agent when None. + langfuse: Langfuse client; built from the LANGFUSE_* environment when None. + dataset_item_id: Langfuse item id; the item's own `id` when None. + dataset_name: Langfuse dataset name; prefixes the experiment run name. + run_timestamp: Shared run timestamp for the run name. + model_version_override: Model-version tag for the run. + run_metadata_extra: Extra experiment-run metadata. + reasoning_effort: Sent on every message. + submit_trace_link: How the Langfuse block is run; inline by default. + gate: `any` (pass@K) or `power` (pass^K). + + Raises: + MemoryAssertionError: the gate did not pass. + JudgeResponseError: the judge returned no readable verdict for any run. + ValueError: the item has no valid `memory_input`, raised before any request. + """ + item = _dataset_item(dataset_item, dataset_name) + _memory_spec(item) + item_id = item.id if dataset_item_id is None else dataset_item_id + identity = RunIdentity( + host, + token, + workspace_id, + dataset_name, + run_timestamp, + model_version_override, + run_metadata_extra, + reasoning_effort, + ) + langfuse, window_start, scope = open_item_trace(langfuse, identity, item_id, suffix_runs=k > 1) + with item_scope(scope): + summary = run_agentic_memory( + host=host, + token=token, + workspace_id=workspace_id, + dataset_item=item, + k=k, + reasoning_effort=reasoning_effort, + agent_id=agent_id, + ) + + run_labels = label_runs( + summary.run_results, + passed=lambda r: not r.ungraded and r.passed, + judge_error=lambda r: r.judge_error if r.ungraded else None, + ) + + if langfuse is not None and item_id: + window_end = utc_now() + + def _write_scores(ctx: RunTraceContext) -> None: + stamp_gate_metadata(ctx.run_metadata, k=len(summary.run_results), gate=gate) + for run_idx, run in enumerate(summary.run_results): + if run.ungraded: + mark_unscored_run(ctx, run_idx, run.conversation_id, run_labels.error_label(run_idx)) + continue + pt = ctx.trace(run.conversation_id) + with ctx.observe( + pt, run_idx, conversation_id=run.conversation_id, output={"memory_pass": run.passed} + ) as tid: + ctx.score(tid, name="memory_pass", value=float(run.passed), data_type="BOOLEAN") + if run.chat_error is not None: + # Neither check ran: only the run's verdict is recorded. + log_gate_scores( + ctx, tid, gate=gate, pass_at_k=summary.pass_at_k, pass_power_k=summary.pass_power_k + ) + continue + ctx.score(tid, name=run.memory_check, value=float(run.memory_passed), data_type="BOOLEAN") + if run.judge_error is None: + ctx.score(tid, name="memory_answer_pass", value=float(run.judge_passed), data_type="BOOLEAN") + log_gate_scores(ctx, tid, gate=gate, pass_at_k=summary.pass_at_k, pass_power_k=summary.pass_power_k) + ctx.quality( + tid, + strict_checks={ + run.memory_check: run.memory_passed, + **({"memory_answer_pass": run.judge_passed} if run.judge_error is None else {}), + }, + latency_sec=pt.latency if pt else None, + cost_usd=pt.total_cost if pt else None, + ) + + submit_trace_scoring( + submit_trace_link, + identity, + langfuse=langfuse, + dataset_item_id=item_id, + conversation_ids=conversations_to_link( + [r.conversation_id for r in summary.scored_run_results], + [r.conversation_id for r in summary.run_results if r.ungraded], + ), + window_start=window_start, + window_end=window_end, + suffix_runs=k > 1, + write_scores=_write_scores, + scope=scope, + item_input=item.question, + ) + + item_timings = sum_timings([r.timings for r in summary.run_results]) + unscored = summary.judge_errors + runs_passed = sum(1 for r in summary.scored_run_results if r.passed) + runs_effective = len(summary.run_results) + run_latencies_s = [r.run_latency_s for r in summary.run_results] + best = summary.best + detail = agentic_detail( + best.tool_call_events, + best.reasoning_step_events, + judge_passed=best.judge_passed, + judge_reasoning=best.reasoning, + memory_passed=best.memory_passed, + applied_memory=best.applied_memory, + actual_output=best.actual_output, + **({"unscored_runs": len(unscored), "judge_errors": unscored} if unscored else {}), + ) + failed_runs = build_failed_runs( + summary.run_results, labels=run_labels, detail=_run_detail, failed_checks=_failed_checks + ) + # The run's own wall time: it includes the /items read, which `timings` does not. + best_run_latency_s = best.run_latency_s + + if not summary.scored_run_results: + error = JudgeResponseError( + f"judge returned no readable verdict for any of the {len(summary.run_results)} run(s): " + + " | ".join(unscored) + ) + _attach_diagnostics( + error, best, detail, failed_runs, runs_passed, runs_effective, run_latencies_s, best_run_latency_s + ) + error.timings = item_timings + attach_labels(error, run_labels, gate) + raise error + + if not gate_passed(gate, pass_at_k=summary.pass_at_k, pass_power_k=summary.pass_power_k): + gate_note = failure_message_head(gate, run_labels, runs_passed, failed_runs, len(unscored)) + raise_agentic_failure( + MemoryAssertionError, + f"Memory assertion failed. {gate_note} {best.chat_error + '; ' if best.chat_error else ''}" + f"memory: {best.memory_error or 'ok'}; " + f"judge passed={best.judge_passed}. Reasoning: {best.reasoning}", + harness_error=run_labels.harness_error_record, + shadow=run_labels.shadow(gate), + reasoning_steps=best.reasoning_steps, + conversation_id=best.conversation_id, + response_id=best.response_id, + detail=detail, + timings=item_timings, + runs_passed=runs_passed, + runs_effective=runs_effective, + failed_runs=failed_runs, + run_latencies_s=run_latencies_s, + best_run_latency_s=best_run_latency_s, + ) + return agentic_success( + shadow=run_labels.shadow(gate), + reasoning_steps=best.reasoning_steps, + conversation_id=best.conversation_id, + response_id=best.response_id, + detail=detail, + timings=item_timings, + runs_passed=runs_passed, + runs_effective=runs_effective, + failed_runs=failed_runs, + run_latencies_s=run_latencies_s, + best_run_latency_s=best_run_latency_s, + ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py b/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py index f4ac0dd90..d2a5d2aa8 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py @@ -18,7 +18,14 @@ from pydantic import ValidationError from gooddata_eval.core.langfuse._env import make_http_client -from gooddata_eval.core.models import AgentSwitcherInput, CatalogInput, DatasetItem, SummaryInput, TakeawayInput +from gooddata_eval.core.models import ( + AgentSwitcherInput, + CatalogInput, + DatasetItem, + MemoryInput, + SummaryInput, + TakeawayInput, +) _PAGE_SIZE = 100 @@ -124,6 +131,27 @@ def _agent_switcher_input_from_raw(raw: dict, expected_output: Any) -> AgentSwit return None +def _memory_input_from_raw(raw: dict, expected_output: Any) -> MemoryInput | None: + """Locate an agentic_memory item's `memory_input`, the same way as `agent_switcher_input`. + + Raises: + ValueError: The value found is not a valid `memory_input` object. + """ + for source in (raw.get("input"), raw.get("metadata"), expected_output): + if not isinstance(source, dict) or source.get("memory_input") is None: + continue + found = source["memory_input"] + if not isinstance(found, dict): + raise ValueError( + f"Langfuse item {raw.get('id')!r}: memory_input must be a JSON object, got {type(found).__name__}" + ) + try: + return MemoryInput.model_validate(found) + except ValidationError as e: + raise ValueError(f"Langfuse item {raw.get('id')!r}: invalid memory_input: {e}") from e + return None + + def _user_context_from_raw(raw: dict) -> dict[str, Any] | None: """Locate an item's `user_context` -- relayed verbatim as the chat request's `userContext`. @@ -183,7 +211,8 @@ def _item_from_raw(raw: dict, *, dataset_name: str, test_kind: str) -> DatasetIt takeaway_input = _takeaway_input_from_raw(raw, expected_output) catalog_input = _catalog_input_from_raw(raw, expected_output) agent_switcher_input = _agent_switcher_input_from_raw(raw, expected_output) - # An item carrying `takeaway_input`, `catalog_input` or `agent_switcher_input` can only be of + memory_input = _memory_input_from_raw(raw, expected_output) + # An item carrying `takeaway_input`, `catalog_input`, `agent_switcher_input` or `memory_input` can only be of # that kind, so it stands in for the CLI default; an explicit test_kind or a structural match # still wins. default_kind = test_kind @@ -193,6 +222,8 @@ def _item_from_raw(raw: dict, *, dataset_name: str, test_kind: str) -> DatasetIt default_kind = "document_takeaway" if agent_switcher_input is not None: default_kind = "agentic_agent_switcher" + if memory_input is not None: + default_kind = "agentic_memory" resolved_kind = _infer_test_kind(expected_output, default_kind, raw.get("metadata")) return DatasetItem( id=str(raw["id"]), @@ -204,6 +235,7 @@ def _item_from_raw(raw: dict, *, dataset_name: str, test_kind: str) -> DatasetIt takeaway_input=takeaway_input, catalog_input=catalog_input, agent_switcher_input=agent_switcher_input, + memory_input=memory_input, user_context=_user_context_from_raw(raw), ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/interaction.py b/packages/gooddata-eval/src/gooddata_eval/core/interaction.py index 577f52ac6..49b748a09 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/interaction.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/interaction.py @@ -29,6 +29,7 @@ "agentic_guardrail", "agentic_search", "agentic_dashboard_summary", + "agentic_memory", } ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/models.py b/packages/gooddata-eval/src/gooddata_eval/core/models.py index 4737f8faf..62715dc32 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/models.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/models.py @@ -9,7 +9,15 @@ from enum import Enum from typing import Any, Literal -from pydantic import BaseModel, ConfigDict, Field, SerializerFunctionWrapHandler, field_validator, model_serializer +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SerializerFunctionWrapHandler, + field_validator, + model_serializer, + model_validator, +) from gooddata_eval.core.timing import PhaseTimings @@ -629,6 +637,32 @@ class AgentSwitcherInput(BaseModel): turns: list[AgentSwitcherTurn] = Field(min_length=1) +class MemoryInput(BaseModel): + """Structured input for the `agentic_memory` test kind: memory item titles, as gen-ai records them. + + `injected` must all be in the turn's injected memory, `not_injected` none of it. Unknown keys + are rejected so a typo in a dataset item fails loudly. + """ + + model_config = ConfigDict(extra="forbid") + + injected: list[str] = Field(default_factory=list) + not_injected: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def _check(self) -> "MemoryInput": + if not self.injected and not self.not_injected: + raise ValueError("memory_input needs at least one title in injected or not_injected") + # Titles are compared exactly: a blank or padded one never matches, so its check always passes. + padded = sorted(t for t in (*self.injected, *self.not_injected) if not t or t != t.strip()) + if padded: + raise ValueError(f"memory_input titles must not be empty or padded with spaces: {padded}") + both = sorted(set(self.injected) & set(self.not_injected)) + if both: + raise ValueError(f"memory_input lists {both} as both injected and not_injected") + return self + + class DatasetItem(BaseModel): """Common dataset envelope. `expected_output` stays raw; each evaluator parses its own shape.""" @@ -647,6 +681,8 @@ class DatasetItem(BaseModel): catalog_input: CatalogInput | None = None # Only used by the `agentic_agent_switcher` test kind; ignored by all others. agent_switcher_input: AgentSwitcherInput | None = None + # Only used by the `agentic_memory` test kind; ignored by all others. + memory_input: MemoryInput | None = None # Relayed verbatim as the chat request's `userContext`. Deliberately opaque: gen-ai owns # that schema (a discriminated union of view/widget descriptors), so re-modelling it here # would only create a second copy to keep in sync. diff --git a/packages/gooddata-eval/tests/test_agentic_memory.py b/packages/gooddata-eval/tests/test_agentic_memory.py new file mode 100644 index 000000000..d5f7e0923 --- /dev/null +++ b/packages/gooddata-eval/tests/test_agentic_memory.py @@ -0,0 +1,499 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +# SPDX-License-Identifier: LicenseRef-GoodData-Enterprise +import contextlib +from collections.abc import Iterator +from typing import Any +from unittest.mock import MagicMock, patch + +import httpx +import pytest +from gooddata_eval.core.agentic.memory import ( + MemoryAssertionError, + applied_memory_titles, + evaluate_agentic_memory, + memory_check_error, + run_agentic_memory, +) +from gooddata_eval.core.chat.sse_client import TurnIncompleteError +from gooddata_eval.core.dataset.langfuse_source import _item_from_raw +from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError +from gooddata_eval.core.models import ChatResult, DatasetItem, LoopExit, MemoryInput +from pydantic import ValidationError + + +def _apply_memory(response_id: str, *titles: str) -> dict[str, Any]: + return { + "role": "user", + "responseId": response_id, + "content": {"type": "text", "text": "q"}, + "detail": { + "category": "applyMemory", + "items": [{"title": t, "strategy": "ALWAYS", "score": None} for t in titles], + }, + } + + +def _answer(response_id: str) -> dict[str, Any]: + return {"role": "assistant", "responseId": response_id, "content": {"type": "text", "text": "a"}, "detail": None} + + +def _composed(response_id: str) -> dict[str, Any]: + """The answer item of a turn gen-ai recorded details for (flag on).""" + return {**_answer(response_id), "detail": {"category": "composeAnswer"}} + + +def _item(injected: tuple[str, ...] = ("help-line",), not_injected: tuple[str, ...] = ("off-item",)) -> DatasetItem: + return DatasetItem( + id="om-1", + dataset_name="org_memory", + test_kind="agentic_memory", + question="How many orders did we have in 2024?", + expected_output="Ends with the help line.", + memory_input=MemoryInput(injected=list(injected), not_injected=list(not_injected)), + ) + + +def _client(items: list[dict[str, Any]] | Exception, response_id: str = "resp-1") -> MagicMock: + client = MagicMock() + client.create_conversation.return_value = "conv-1" + client.send_message.return_value = ChatResult.model_validate( + {"textResponse": "8,963 orders. Questions? Ask the BI team.", "toolCallEvents": [], "responseId": response_id} + ) + if isinstance(items, Exception): + client.list_items.side_effect = items + else: + client.list_items.return_value = items + return client + + +def _judge(passed: bool = True) -> MagicMock: + judge = MagicMock() + judge.model = "gpt-4o" + judge.score.return_value = (passed, "judge reason") + return judge + + +@contextlib.contextmanager +def _patched(client: MagicMock, judge: MagicMock) -> Iterator[None]: + with ( + patch("gooddata_eval.core.agentic.memory.ChatClient", return_value=client), + patch("gooddata_eval.core.agentic.memory.LLMJudge", return_value=judge), + ): + yield + + +# --- reading the injected memory --------------------------------------------------------- + + +def test_titles_come_from_the_apply_memory_detail_of_the_turn_only() -> None: + items = [ + _apply_memory("old", "stale"), + _answer("old"), + _apply_memory("resp-1", "help-line", "returns"), + _answer("resp-1"), + ] + assert applied_memory_titles(items, "resp-1") == ["help-line", "returns"] + + +def test_a_turn_without_any_detail_reads_as_none_not_as_no_memory() -> None: + assert applied_memory_titles([_answer("resp-1")], "resp-1") is None + assert applied_memory_titles([_composed("old"), _answer("resp-1")], "resp-1") is None + assert applied_memory_titles([_apply_memory("resp-1")], "resp-1") == [] + + +def test_a_turn_with_other_details_and_no_apply_memory_injected_nothing() -> None: + assert applied_memory_titles([_composed("resp-1")], "resp-1") == [] + + +def test_other_detail_categories_are_ignored() -> None: + other = {**_answer("resp-1"), "detail": {"category": "skillRouting", "items": [{"title": "help-line"}]}} + assert applied_memory_titles([other], "resp-1") == [] + + +@pytest.mark.parametrize( + ("applied", "error"), + [ + (["help-line", "returns"], None), + (["returns"], "not injected: ['help-line']"), + (["help-line", "off-item"], "injected but must not be: ['off-item']"), + ([], "not injected: ['help-line']"), + ], + ids=["match", "missing", "unwanted", "empty"], +) +def test_memory_check(applied: list[str], error: str | None) -> None: + assert memory_check_error(MemoryInput(injected=["help-line"], not_injected=["off-item"]), applied) == error + + +def test_a_turn_without_the_detail_names_the_flag() -> None: + error = memory_check_error(MemoryInput(injected=["help-line"]), None) + assert error is not None and "enableGenAiInteractionIntelligence" in error + + +# --- memory_input ------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + "raw", + [ + {}, + {"injected": ["a"], "not_injected": ["a"]}, + {"injected": ["a"], "typo": ["b"]}, + {"not_injected": [" a"]}, + {"injected": [""]}, + ], + ids=["empty", "both-lists", "unknown-key", "padded-title", "blank-title"], +) +def test_invalid_memory_input_is_rejected(raw: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + MemoryInput.model_validate(raw) + + +def test_langfuse_item_with_memory_input_is_a_memory_item() -> None: + raw = { + "id": "x", + "input": "Net Sales FY24?", + "expectedOutput": "Uses April 2024 - March 2025.", + "metadata": {"memory_input": {"injected": ["fiscal-year"]}}, + } + item = _item_from_raw(raw, dataset_name="org_memory", test_kind="visualization") + assert item.test_kind == "agentic_memory" + assert item.memory_input == MemoryInput(injected=["fiscal-year"]) + + +def test_langfuse_item_with_a_broken_memory_input_fails_loudly() -> None: + raw = {"id": "x", "input": "q", "expectedOutput": "e", "metadata": {"memory_input": ["fiscal-year"]}} + with pytest.raises(ValueError, match="memory_input must be a JSON object"): + _item_from_raw(raw, dataset_name="org_memory", test_kind="visualization") + + +# --- one run ----------------------------------------------------------------------------- + + +def test_a_run_passes_when_the_memory_and_the_answer_pass() -> None: + client = _client([_apply_memory("resp-1", "help-line"), _answer("resp-1")]) + with _patched(client, _judge(True)): + summary = run_agentic_memory("https://h", "t", "ws", _item(), k=1) + run = summary.run_results[0] + assert (run.passed, run.applied_memory) == (True, ["help-line"]) + client.list_items.assert_called_once_with("conv-1") + client.delete_conversation.assert_called_once_with("conv-1") + + +def test_a_good_answer_does_not_hide_missing_memory() -> None: + client = _client([_apply_memory("resp-1", "returns"), _answer("resp-1")]) + with _patched(client, _judge(True)): + run = run_agentic_memory("https://h", "t", "ws", _item(), k=1).run_results[0] + assert run.judge_passed and not run.memory_passed and not run.passed + + +def test_injected_memory_does_not_hide_a_wrong_answer() -> None: + client = _client([_apply_memory("resp-1", "help-line"), _answer("resp-1")]) + with _patched(client, _judge(False)): + run = run_agentic_memory("https://h", "t", "ws", _item(), k=1).run_results[0] + assert run.memory_passed and not run.passed + + +def test_an_unreadable_items_list_is_an_error_and_the_answer_is_still_judged() -> None: + client = _client(httpx.ConnectError("down")) + judge = _judge(True) + with _patched(client, judge): + run = run_agentic_memory("https://h", "t", "ws", _item(), k=1).run_results[0] + assert run.memory_error is not None and "down" in run.memory_error + assert run.exit_reason == LoopExit.CHAT_ERROR + assert run.judge_error is None and judge.score.called and not run.passed + + +def test_a_turn_that_injected_nothing_passes_an_item_that_expects_nothing() -> None: + client = _client([_composed("resp-1")]) + with _patched(client, _judge(True)): + run = run_agentic_memory("https://h", "t", "ws", _item(injected=()), k=1).run_results[0] + assert (run.passed, run.applied_memory, run.exit_reason) == (True, [], None) + + +def test_a_turn_that_injected_nothing_fails_an_item_that_expects_an_item() -> None: + client = _client([_composed("resp-1")]) + with _patched(client, _judge(True)): + run = run_agentic_memory("https://h", "t", "ws", _item(), k=1).run_results[0] + assert (run.memory_error, run.exit_reason) == ("not injected: ['help-line']", None) + + +def test_a_turn_without_any_detail_fails_as_unread_memory_and_names_the_flag() -> None: + client = _client([_answer("resp-1")]) + with _patched(client, _judge(True)), pytest.raises(MemoryAssertionError) as exc: + evaluate_agentic_memory("https://h", "t", "ws", _item(injected=()), k=1) + assert "enableGenAiInteractionIntelligence" in str(exc.value) + (failed,) = exc.value.failed_runs + assert [c["name"] for c in failed["failed_checks"]] == ["memory_read"] + assert failed["exit_reason"] == "chat_error" + + +def test_a_chart_answer_reaches_the_judge_as_a_line_with_its_title() -> None: + client = _client([_apply_memory("resp-1", "help-line")]) + viz = {"id": "v1", "title": "Orders by month", "type": "column_chart", "query": {"fields": {}}} + client.send_message.return_value = ChatResult.model_validate( + { + "textResponse": "Questions? Ask the BI team.", + "createdVisualizations": {"objects": [viz], "reasoning": ""}, + "toolCallEvents": [], + "responseId": "resp-1", + } + ) + judge = _judge(True) + with _patched(client, judge): + run = run_agentic_memory("https://h", "t", "ws", _item(), k=1).run_results[0] + assert run.actual_output == ( + '[The answer shows a chart: "Orders by month" (column_chart)]\n\nQuestions? Ask the BI team.' + ) + + +def test_an_item_without_memory_input_fails_before_any_request() -> None: + item = _item().model_copy(update={"memory_input": None}) + client = _client([]) + with _patched(client, _judge(True)), pytest.raises(ValueError, match="no memory_input"): + run_agentic_memory("https://h", "t", "ws", item, k=1) + client.create_conversation.assert_not_called() + + +def test_k_runs_use_one_conversation_each() -> None: + client = _client([_apply_memory("resp-1", "help-line")]) + client.create_conversation.side_effect = ["conv-1", "conv-2", "conv-3"] + with _patched(client, _judge(True)): + summary = run_agentic_memory("https://h", "t", "ws", _item(), k=3) + assert [r.conversation_id for r in summary.run_results] == ["conv-1", "conv-2", "conv-3"] + assert summary.pass_at_k and summary.pass_power_k + + +# --- the gate ---------------------------------------------------------------------------- + + +def test_a_failing_item_raises_with_the_memory_check_named() -> None: + client = _client([_apply_memory("resp-1", "returns")]) + with _patched(client, _judge(True)), pytest.raises(MemoryAssertionError) as exc: + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1) + err = exc.value + assert "not injected: ['help-line']" in str(err) + assert [c["name"] for c in err.failed_runs[0]["failed_checks"]] == ["memory_injected"] + assert err.detail["applied_memory"] == ["returns"] + + +def test_a_passing_item_returns_the_injected_memory_in_its_detail() -> None: + client = _client([_apply_memory("resp-1", "help-line")]) + with _patched(client, _judge(True)): + outcome = evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1) + assert outcome.detail["memory_passed"] is True + assert outcome.detail["applied_memory"] == ["help-line"] + + +def test_the_item_user_context_reaches_the_chat_client() -> None: + item = _item().model_copy(update={"user_context": {"view": {"type": "dashboard", "id": "d1"}}}) + client = _client([_apply_memory("resp-1", "help-line")]) + with ( + patch("gooddata_eval.core.agentic.memory.ChatClient", return_value=client) as chat_client, + patch("gooddata_eval.core.agentic.memory.LLMJudge", return_value=_judge(True)), + ): + run_agentic_memory("https://h", "t", "ws", item, k=1) + assert chat_client.call_args.kwargs["user_context"] == {"view": {"type": "dashboard", "id": "d1"}} + + +def test_a_stored_item_dict_is_accepted() -> None: + stored = { + "id": "om-1", + "question": "How many orders did we have in 2024?", + "expected_output": "Ends with the help line.", + "memory_input": {"injected": ["help-line"]}, + } + client = _client([_apply_memory("resp-1", "help-line")]) + with _patched(client, _judge(True)): + outcome = evaluate_agentic_memory("https://h", "t", "ws", stored, dataset_name="org_memory", k=1) + assert outcome.detail["applied_memory"] == ["help-line"] + + +def test_a_stored_item_without_memory_input_fails_before_any_request() -> None: + client = _client([]) + with _patched(client, _judge(True)), pytest.raises(ValueError, match="no memory_input"): + evaluate_agentic_memory("https://h", "t", "ws", {"id": "om-1", "question": "q"}, k=1) + client.create_conversation.assert_not_called() + + +def test_an_item_without_expected_output_fails_before_any_request() -> None: + client = _client([]) + item = {"id": "om-1", "question": "q", "memory_input": {"injected": ["help-line"]}} + with _patched(client, _judge(True)), pytest.raises(ValueError, match="no expected_output"): + evaluate_agentic_memory("https://h", "t", "ws", item, k=1) + client.create_conversation.assert_not_called() + + +def test_a_run_with_unread_memory_is_scored_as_memory_read_not_as_a_wrong_injection() -> None: + captured: dict[str, Any] = {} + + def _capture(_submit: object, _identity: object, **kwargs: Any) -> None: + captured.update(kwargs) + + client = _client([_answer("resp-1")]) + with ( + _patched(client, _judge(True)), + patch("gooddata_eval.core.agentic.memory.submit_trace_scoring", _capture), + pytest.raises(MemoryAssertionError), + ): + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1, langfuse=MagicMock()) + ctx = _ScoreCtx() + captured["write_scores"](ctx) + scores = {name: value for _, name, value in ctx.scores} + assert (scores["memory_pass"], scores["memory_read"], scores["memory_answer_pass"]) == (0.0, 0.0, 1.0) + assert "memory_injected" not in scores + assert ctx.strict_checks == [{"memory_read": False, "memory_answer_pass": True}] + + +def test_k_below_one_is_refused() -> None: + with pytest.raises(ValueError, match="k must be at least 1"): + run_agentic_memory("https://h", "t", "ws", _item(), k=0) + + +def test_a_structured_expected_visualization_still_wins_over_memory_input() -> None: + raw = { + "id": "x", + "input": "q", + "expectedOutput": {"visualization": {"type": "bar"}}, + "metadata": {"memory_input": {"injected": ["a"]}}, + } + assert _item_from_raw(raw, dataset_name="d", test_kind="visualization").test_kind == "vis_agentic" + raw["metadata"]["test_kind"] = "agentic_memory" + assert _item_from_raw(raw, dataset_name="d", test_kind="visualization").test_kind == "agentic_memory" + + +def test_an_item_no_run_of_which_the_judge_could_grade_is_an_error_with_its_diagnostics() -> None: + client = _client([_apply_memory("resp-1", "help-line")]) + judge = _judge(True) + judge.score.side_effect = JudgeResponseError("not JSON") + with _patched(client, judge), pytest.raises(JudgeResponseError, match="no readable verdict") as exc: + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=2) + assert exc.value.runs_effective == 2 + assert exc.value.detail["applied_memory"] == ["help-line"] + + +class _ScoreCtx: + def __init__(self) -> None: + self.run_metadata: dict[str, Any] = {} + self.scores: list[tuple[int, str, Any]] = [] + self.unscored: list[int] = [] + self.strict_checks: list[Any] = [] + + def trace(self, _conversation_id: str) -> None: + return None + + @contextlib.contextmanager + def observe(self, _trace: object, run_idx: int, **_kwargs: Any) -> Iterator[int]: + yield run_idx + + def score(self, trace_id: int, *, name: str, value: Any, data_type: str, comment: str | None = None) -> None: + self.scores.append((trace_id, name, value)) + + def quality(self, trace_id: int, **kwargs: Any) -> None: + self.scores.append((trace_id, "quality_score", None)) + self.strict_checks.append(kwargs.get("strict_checks")) + + +def test_each_run_is_scored_with_the_memory_and_the_answer_checks() -> None: + captured: dict[str, Any] = {} + + def _capture(_submit: object, _identity: object, **kwargs: Any) -> None: + captured.update(kwargs) + + client = _client([_apply_memory("resp-1", "returns")]) + with ( + _patched(client, _judge(True)), + patch("gooddata_eval.core.agentic.memory.submit_trace_scoring", _capture), + pytest.raises(MemoryAssertionError), + ): + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1, langfuse=MagicMock()) + ctx = _ScoreCtx() + captured["write_scores"](ctx) + + assert captured["dataset_item_id"] == "om-1" + scores = {name: value for _, name, value in ctx.scores} + assert (scores["memory_pass"], scores["memory_injected"], scores["memory_answer_pass"]) == (0.0, 0.0, 1.0) + + +def test_the_best_run_latency_is_the_run_wall_time_with_the_items_read() -> None: + client = _client([_apply_memory("resp-1", "help-line")]) + # item start, agent stop, judge start, judge stop, run stop: the /items read takes 5s. + with _patched(client, _judge(True)), patch("time.monotonic", side_effect=[0.0, 2.0, 7.0, 8.0, 8.0]): + outcome = evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1) + assert outcome.best_run_latency_s == 8.0 + assert outcome.run_latencies_s == [8.0] + + +def test_a_failed_memory_check_stays_a_failure_when_the_judge_cannot_grade() -> None: + client = _client([_apply_memory("resp-1", "returns")]) + judge = _judge(True) + judge.score.side_effect = JudgeResponseError("not JSON") + with _patched(client, judge), pytest.raises(MemoryAssertionError) as exc: + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1) + assert "not injected: ['help-line']" in str(exc.value) + assert [c["name"] for c in exc.value.failed_runs[0]["failed_checks"]] == ["memory_injected"] + assert getattr(exc.value, "harness_error", None) is None + + +def test_a_run_the_memory_check_failed_is_scored_without_a_judge_verdict() -> None: + captured: dict[str, Any] = {} + + def _capture(_submit: object, _identity: object, **kwargs: Any) -> None: + captured.update(kwargs) + + client = _client([_apply_memory("resp-1", "returns")]) + judge = _judge(True) + judge.score.side_effect = JudgeResponseError("not JSON") + with ( + _patched(client, judge), + patch("gooddata_eval.core.agentic.memory.submit_trace_scoring", _capture), + pytest.raises(MemoryAssertionError), + ): + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=1, langfuse=MagicMock()) + ctx = _ScoreCtx() + captured["write_scores"](ctx) + scores = {name: value for _, name, value in ctx.scores} + assert (scores["memory_pass"], scores["memory_injected"]) == (0.0, 0.0) + assert "memory_answer_pass" not in scores + + +def _client_whose_second_turn_fails() -> MagicMock: + client = _client([_apply_memory("resp-1", "help-line")]) + client.create_conversation.side_effect = ["conv-1", "conv-2"] + client.send_message.side_effect = [client.send_message.return_value, TurnIncompleteError("no final answer")] + return client + + +def test_a_failed_turn_fails_its_run_and_keeps_the_other_runs() -> None: + client = _client_whose_second_turn_fails() + with _patched(client, _judge(True)): + outcome = evaluate_agentic_memory("https://h", "t", "ws", _item(), k=2, gate="any") + assert (outcome.runs_passed, outcome.runs_effective) == (1, 2) + (failed,) = outcome.failed_runs + assert [c["name"] for c in failed["failed_checks"]] == ["chat_turn"] + assert "no final answer" in failed["detail"]["chat_error"] + assert [c.args[0] for c in client.delete_conversation.call_args_list] == ["conv-1", "conv-2"] + + +def test_a_failed_turn_fails_the_power_gate_with_both_runs_recorded() -> None: + client = _client_whose_second_turn_fails() + with _patched(client, _judge(True)), pytest.raises(MemoryAssertionError) as exc: + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=2, gate="power") + assert (exc.value.runs_passed, exc.value.runs_effective) == (1, 2) + assert getattr(exc.value, "harness_error", None) is None + + +def test_a_failed_turn_is_scored_as_a_failed_run_without_check_scores() -> None: + captured: dict[str, Any] = {} + + def _capture(_submit: object, _identity: object, **kwargs: Any) -> None: + captured.update(kwargs) + + client = _client_whose_second_turn_fails() + with _patched(client, _judge(True)), patch("gooddata_eval.core.agentic.memory.submit_trace_scoring", _capture): + evaluate_agentic_memory("https://h", "t", "ws", _item(), k=2, gate="any", langfuse=MagicMock()) + ctx = _ScoreCtx() + captured["write_scores"](ctx) + by_run = {i: {n: v for t, n, v in ctx.scores if t == i} for i in (0, 1)} + assert by_run[0]["memory_injected"] == 1.0 + assert by_run[1]["memory_pass"] == 0.0 + assert not {"memory_injected", "memory_answer_pass", "quality_score"} & set(by_run[1]) diff --git a/packages/gooddata-eval/tests/test_agentic_runner.py b/packages/gooddata-eval/tests/test_agentic_runner.py index d1de254eb..9919e37f2 100644 --- a/packages/gooddata-eval/tests/test_agentic_runner.py +++ b/packages/gooddata-eval/tests/test_agentic_runner.py @@ -109,6 +109,7 @@ def test_dispatch_agentic_omits_agent_id_by_default(): ("agentic_what_if", {"metric_id": "spend"}, "evaluate_agentic_what_if"), ("agentic_agent_switcher", {}, "evaluate_agentic_agent_switcher"), ("agentic_knowledge", {"expected_documents": ["Discount Policy"]}, "evaluate_agentic_knowledge"), + ("agentic_memory", "Ends with the help line.", "evaluate_agentic_memory"), ] # Kinds whose item names its own agents, so the CLI's --agent-id does not reach them. @@ -905,6 +906,7 @@ def test_an_errored_item_without_timings_keeps_its_zero_defaults(): ("agentic_knowledge", "evaluate_agentic_knowledge", {}), ("agentic_conversation", "evaluate_agentic_conversation", {"id": "c1", "expected_skills": [], "turns": []}), ("agentic_agent_switcher", "evaluate_agentic_agent_switcher", {}), + ("agentic_memory", "evaluate_agentic_memory", "Ends with the help line."), ] @@ -948,8 +950,8 @@ def test_dispatch_agentic_passes_user_context_through_to_every_kind( # agentic_dashboard_summary builds its own context from the dashboard it summarises and # takes its scope from summary_input, so relaying the item's context would override the # thing under test rather than add to it. Excluded on purpose, not by omission. -# agentic_agent_switcher gets the whole item and reads user_context off it. -_KINDS_WITHOUT_USER_CONTEXT = {"agentic_dashboard_summary", "agentic_agent_switcher"} +# agentic_agent_switcher and agentic_memory get the whole item and read user_context off it. +_KINDS_WITHOUT_USER_CONTEXT = {"agentic_dashboard_summary", "agentic_agent_switcher", "agentic_memory"} class _Stop(Exception): diff --git a/packages/gooddata-eval/tests/test_trace_linker.py b/packages/gooddata-eval/tests/test_trace_linker.py index 6f80f00e9..724e0eea6 100644 --- a/packages/gooddata-eval/tests/test_trace_linker.py +++ b/packages/gooddata-eval/tests/test_trace_linker.py @@ -126,6 +126,7 @@ def test_run_trace_link_inline_runs_the_task_on_the_calling_thread(): ("anomaly_detection", "evaluate_agentic_anomaly_detection"), ("what_if", "evaluate_agentic_what_if"), ("agent_switcher", "evaluate_agentic_agent_switcher"), + ("memory", "evaluate_agentic_memory"), ]