Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/agentevals/builtin_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,10 @@ def get_evaluator(eval_metric: EvalMetric) -> Evaluator:
"agentevals.judges",
"FinalResponseMatchV2WithReasoning",
),
"rubric_based_final_response_quality_v1": (
"agentevals.judges",
"RubricBasedFinalResponseQualityV1WithHistory",
),
}

if name in _DIRECT_EVALUATORS:
Expand Down
167 changes: 166 additions & 1 deletion src/agentevals/judges.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@

import json
import re
from typing import Optional

from google.adk.evaluation.eval_case import ConversationScenario, Invocation, InvocationEvents
from google.adk.evaluation.eval_rubrics import RubricScore
from google.adk.evaluation.evaluator import EvaluationResult
from google.adk.evaluation.final_response_match_v2 import FinalResponseMatchV2Evaluator
from google.adk.evaluation.llm_as_judge import AutoRaterScore
from google.adk.evaluation.llm_as_judge_utils import get_text_from_content
from google.adk.evaluation.llm_as_judge_utils import (
get_grounding_metadata_as_json_str,
get_text_from_content,
get_tool_calls_and_responses_as_json_str,
get_tool_declarations_as_json_str,
)
from google.adk.evaluation.rubric_based_final_response_quality_v1 import RubricBasedFinalResponseQualityV1Evaluator
from google.adk.models.llm_response import LlmResponse

FINAL_RESPONSE_MATCH_RUBRIC_ID = "final_response_match"
Expand Down Expand Up @@ -64,3 +73,159 @@ def convert_auto_rater_response_to_score(self, llm_response: LlmResponse) -> Aut
)
],
)

def format_preceding_dialogue(invocations: list[Invocation]) -> str:
"""Formats turns 0..i-1 into readable history."""
if not invocations:
return "None (this is the first turn)."
lines = []
for idx, inv in enumerate(invocations, start=1):
user_text = get_text_from_content(inv.user_content) or ""
agent_text = get_text_from_content(inv.final_response) or ""

turn_str = f"Turn {idx}:\nUser: {user_text}"
# Include tool calls if the agent called tools in that turn
if inv.intermediate_data:
tool_json = get_tool_calls_and_responses_as_json_str(inv.intermediate_data)
if tool_json and tool_json != "[]":
turn_str += f"\nTools: {tool_json}"
turn_str += f"\nAssistant: {agent_text}"
lines.append(turn_str)
return "\n\n".join(lines)

# Prompt template that includes <preceding_conversation>
_RUBRIC_FINAL_RESPONSE_WITH_HISTORY_PROMPT = """
SPECIAL INSTRUCTION: think silently. Silent thinking token budget: 10240 tokens.
# Mission
Your mission is to evaluate the final answer quality of responses generated by an AI agent. You will be presented with preceding conversation turns (<preceding_conversation>), the current user prompt (<user_prompt>), the agent's response (<response>) to that user prompt, and a set of properties (<property>) that you must use to objectively assess the validity of the agent's response.
Only respond to the properties provided. Do not make up new properties.
# Rubric
"yes": The model's response fulfilled the property, OR the property's condition was not applicable to the response.
"no": The model's response met the conditions for the property to be applicable, but failed to fulfill it, or the property applies to a claim in the model's response that cannot be unambiguously verified using trusted evidence.
# Key Evaluation Principles
Your evaluation must follow a two-part process: first, collect trusted evidence from the agent's work, and second, judge the final answer against it.
1. **Establish Trusted Evidence from Context, Tool Calls and Grounding**:
* Your sources of truth are:
1. The <preceding_conversation> (facts, preferences, or corrections established in earlier turns).
2. The current <user_prompt>.
3. The direct output ('tool_response') from PROCEDURALLY SOUND tool calls found in the <response_steps>.
4. Model-supplied grounding metadata found in <grounding_metadata>.
* The following kinds of information ABSOLUTELY CANNOT BE USED to derive trusted evidence:
* The agent's final answer.
* The agent's reasoning, summaries, or any interpretations of the tool responses by the agent.
* Any tool call that is flawed.
2. **Judge Consistency with the Evidence**: Once you have collected trusted evidence, determine whether the agent's <final_answer> is consistent with it. A claim in the final answer is only considered correct if it can be verified using this evidence.
# Output Format (repeat this format for every property, starting with a new line):
ID: [Copy the id shown in the "[id: ...]" tag for this property, verbatim. Omit this line only if no tag is shown.]
Property: [Repeat the property text that follows the "[id: ...]" tag, word for word.]
Evidence: [List trusted evidence from preceding conversation, tool calls, or current user prompt.]
Rationale: [Explain your reasoning.]
Verdict: [yes|no]
Respond in pure text, not json.
# Your Turn
## Input
<preceding_conversation>
{preceding_conversation}
</preceding_conversation>
<user_prompt>
<developer_instructions>
{developer_instructions}
</developer_instructions>
<available_tools>
{tool_declarations}
</available_tools>
<main_prompt>
{user_input}
</main_prompt>
</user_prompt>
<response>
<response_steps>
{response_steps}
</response_steps>
<grounding_metadata>
{grounding_metadata}
</grounding_metadata>
<final_answer>
{final_response}
</final_answer>
</response>
<properties>
{rubrics}
</properties>
## Output
"""

class RubricBasedFinalResponseQualityV1WithHistory(RubricBasedFinalResponseQualityV1Evaluator):
"""Evaluates rubric properties for turn i with context from turns 0..i-1."""
def __init__(self, eval_metric):
super().__init__(eval_metric)
self._auto_rater_prompt_template = _RUBRIC_FINAL_RESPONSE_WITH_HISTORY_PROMPT
self._preceding_by_invocation: dict[int, list[Invocation]] = {}
async def evaluate_invocations(
self,
actual_invocations: list[Invocation],
expected_invocations: Optional[list[Invocation]] = None,
conversation_scenario: Optional[ConversationScenario] = None,
) -> EvaluationResult:
# Pre-map preceding turns for each invocation
self._preceding_by_invocation = {
id(actual): actual_invocations[:idx]
for idx, actual in enumerate(actual_invocations)
}
try:
return await super().evaluate_invocations(
actual_invocations=actual_invocations,
expected_invocations=expected_invocations,
conversation_scenario=conversation_scenario,
)
finally:
self._preceding_by_invocation.clear()
def format_auto_rater_prompt(
self,
actual_invocation: Invocation,
expected_invocation: Optional[Invocation],
) -> str:
# 1. Effective rubrics
self.create_effective_rubrics_list(actual_invocation.rubrics)
user_input = get_text_from_content(actual_invocation.user_content)
include_intermediate = self._criterion.include_intermediate_responses_in_final
final_response = (
get_text_from_content(
actual_invocation,
include_intermediate_responses_in_final=include_intermediate,
)
or ""
)
rubrics_text = "\n".join(
[f"* [id: {r.rubric_id}] {r.rubric_content.text_property}" for r in self.get_effective_rubrics_list()]
)
developer_instructions = ""
tool_declarations = "Agent has no tools."
response_steps = get_tool_calls_and_responses_as_json_str(actual_invocation.intermediate_data)
grounding_metadata = get_grounding_metadata_as_json_str(actual_invocation.intermediate_data)
app_details = actual_invocation.app_details
if app_details:
agent_name = None
if (
isinstance(actual_invocation.intermediate_data, InvocationEvents)
and actual_invocation.intermediate_data.invocation_events
):
agent_name = actual_invocation.intermediate_data.invocation_events[0].author
elif app_details.agent_details:
agent_name = next(iter(app_details.agent_details))
if agent_name:
developer_instructions = app_details.get_developer_instructions(agent_name=agent_name)
tool_declarations = get_tool_declarations_as_json_str(app_details)
# 2. Preceding conversation
preceding = self._preceding_by_invocation.get(id(actual_invocation), [])
preceding_text = format_preceding_dialogue(preceding)
return self._auto_rater_prompt_template.format(
preceding_conversation=preceding_text,
developer_instructions=developer_instructions,
tool_declarations=tool_declarations,
user_input=user_input,
response_steps=response_steps,
grounding_metadata=grounding_metadata,
final_response=final_response,
rubrics=rubrics_text,
)
80 changes: 80 additions & 0 deletions tests/test_rubrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@
build_eval_metric,
evaluate_builtin_metric,
extract_rubric_details,
get_evaluator,
to_rubric_objects,
)
from agentevals.config import BuiltinMetricDef, RubricDef, apply_builtin_overrides
from agentevals.custom_evaluators import evaluate_custom_evaluator
from agentevals.eval_config_loader import load_eval_config
from agentevals.genai.extract import extract_conversation
from agentevals.judges import RubricBasedFinalResponseQualityV1WithHistory, format_preceding_dialogue
from agentevals.runner import EvalRunConfig, run_evaluation
from otel.builders import request, span
from test_runner import _make_eval_set_json, _make_tool_trace
Expand Down Expand Up @@ -439,3 +441,81 @@ def test_per_rubric_scores_are_reported_per_invocation_and_overall(self):
}
]
assert [r["rubric_id"] for r in details["overall_rubric_scores"]] == ["grounded", "corrected"]


class TestPrecedingConversationContext:
def test_preceding_turns_are_provided_and_future_turns_excluded(self, monkeypatch):
captured_prompts: list[tuple[str, str]] = []
metric = build_eval_metric(METRIC, "gemini-2.5-flash", 0.5, rubrics=["Honors latest preference."])
evaluator = get_evaluator(metric)
assert isinstance(evaluator, RubricBasedFinalResponseQualityV1WithHistory)

orig_format = evaluator.format_auto_rater_prompt

def spy_format(actual, expected):
prompt = orig_format(actual, expected)
captured_prompts.append((actual.invocation_id, prompt))
return prompt

monkeypatch.setattr(evaluator, "format_auto_rater_prompt", spy_format)

async def fake_evaluate_sample(llm_request, actual, expected):
return PerInvocationResult(
actual_invocation=actual,
expected_invocation=expected,
score=1.0,
eval_status=EvalStatus.PASSED,
rubric_scores=[RubricScore(rubric_id="rubric_0", score=1.0, rationale="evidence found")],
)

monkeypatch.setattr(evaluator, "_evaluate_single_sample", fake_evaluate_sample)

t1 = _invocation("Turn 1 user request")
t1 = t1.model_copy(
update={
"final_response": genai_types.Content(
role="model", parts=[genai_types.Part(text="Turn 1 assistant reply")]
)
}
)
t2 = _invocation("Turn 2 correction request")
t2 = t2.model_copy(
update={
"final_response": genai_types.Content(
role="model", parts=[genai_types.Part(text="Turn 2 assistant completed reply")]
)
}
)

eval_result = asyncio.run(evaluator.evaluate_invocations([t1, t2]))
assert eval_result.overall_score == 1.0
assert len(captured_prompts) == 2

# Turn 1: No previous history, and must NOT leak Turn 2
id_1, prompt_1 = captured_prompts[0]
assert id_1 == t1.invocation_id
assert "None (this is the first turn)." in prompt_1
assert "Turn 2" not in prompt_1
assert "Turn 2 correction request" not in prompt_1

# Turn 2: Preceding history includes Turn 1
id_2, prompt_2 = captured_prompts[1]
assert id_2 == t2.invocation_id
assert "Turn 1:" in prompt_2
assert "User: Turn 1 user request" in prompt_2
assert "Assistant: Turn 1 assistant reply" in prompt_2
assert "Turn 2 correction request" in prompt_2

def test_format_preceding_dialogue_handles_empty_and_tools(self):
assert format_preceding_dialogue([]) == "None (this is the first turn)."
inv = _invocation("Hello")
inv = inv.model_copy(
update={
"final_response": genai_types.Content(role="model", parts=[genai_types.Part(text="Hi there")]),
}
)
formatted = format_preceding_dialogue([inv])
assert "Turn 1:" in formatted
assert "User: Hello" in formatted
assert "Assistant: Hi there" in formatted