-
Notifications
You must be signed in to change notification settings - Fork 24
feat: Add FaithfulnessEvaluator #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jjbuck
merged 1 commit into
strands-agents:main
from
jjbuck:feature/faithfulness_evaluator
Nov 6, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| from opentelemetry.sdk.trace.export import BatchSpanProcessor | ||
| from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter | ||
| from strands import Agent | ||
|
|
||
| from strands_evals import Case, Dataset | ||
| from strands_evals.evaluators import FaithfulnessEvaluator | ||
| from strands_evals.mappers import StrandsInMemorySessionMapper | ||
| from strands_evals.telemetry import StrandsEvalsTelemetry | ||
|
|
||
| # ====================================== | ||
| # SETUP TELEMETRY | ||
| # ====================================== | ||
| telemetry = StrandsEvalsTelemetry() | ||
| memory_exporter = InMemorySpanExporter() | ||
| span_processor = BatchSpanProcessor(memory_exporter) | ||
| telemetry.tracer_provider.add_span_processor(span_processor) | ||
|
|
||
|
|
||
| # ====================================== | ||
| # SETUP AND RUN STRANDS EVAL | ||
| # ====================================== | ||
|
|
||
|
|
||
| def user_task_function(query: str) -> str: | ||
| agent = Agent(callback_handler=None) | ||
| agent_response = agent(query) | ||
| finished_spans = memory_exporter.get_finished_spans() | ||
| mapper = StrandsInMemorySessionMapper() | ||
| session = mapper.map_to_session(finished_spans, session_id="test-session") | ||
|
|
||
| return {"output": str(agent_response), "trajectory": session} | ||
|
|
||
|
|
||
| test_cases = [ | ||
| Case[str, str](name="knowledge-1", input="What is the capital of France?", metadata={"category": "knowledge"}), | ||
| Case[str, str](name="knowledge-2", input="What color is the ocean?", metadata={"category": "knowledge"}), | ||
| ] | ||
|
|
||
| evaluator = FaithfulnessEvaluator() | ||
|
|
||
| dataset = Dataset[str, str](cases=test_cases, evaluator=evaluator) | ||
|
|
||
| report = dataset.run_evaluations(user_task_function) | ||
| report.run_display() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| from enum import Enum | ||
|
|
||
| from pydantic import BaseModel, Field | ||
| from strands import Agent | ||
| from typing_extensions import TypeVar | ||
|
|
||
| from ..types.evaluation import EvaluationData, EvaluationOutput | ||
| from ..types.trace import EvaluationLevel, TraceLevelInput | ||
| from .evaluator import Evaluator | ||
| from .prompt_templates.faithfulness import get_template | ||
|
|
||
| InputT = TypeVar("InputT") | ||
| OutputT = TypeVar("OutputT") | ||
|
|
||
|
|
||
| class FaithfulnessScore(str, Enum): | ||
| """Categorical faithfulness ratings.""" | ||
|
|
||
| NOT_AT_ALL = "Not At All" | ||
| NOT_GENERALLY = "Not Generally" | ||
| NEUTRAL = "Neutral/Mixed" | ||
| GENERALLY_YES = "Generally Yes" | ||
| COMPLETELY_YES = "Completely Yes" | ||
|
|
||
|
|
||
| class FaithfulnessRating(BaseModel): | ||
| """Structured output for faithfulness evaluation.""" | ||
|
|
||
| reasoning: str = Field(description="Step by step reasoning to derive the final score") | ||
| score: FaithfulnessScore = Field(description="Categorical faithfulness rating") | ||
|
|
||
|
|
||
| class FaithfulnessEvaluator(Evaluator[InputT, OutputT]): | ||
| """Evaluates faithfulness of agent responses against conversation history.""" | ||
|
|
||
| evaluation_level = EvaluationLevel.TRACE_LEVEL | ||
|
|
||
| _score_mapping = { | ||
| FaithfulnessScore.NOT_AT_ALL: 0.0, | ||
| FaithfulnessScore.NOT_GENERALLY: 0.25, | ||
| FaithfulnessScore.NEUTRAL: 0.5, | ||
| FaithfulnessScore.GENERALLY_YES: 0.75, | ||
| FaithfulnessScore.COMPLETELY_YES: 1.0, | ||
| } | ||
|
|
||
| def __init__( | ||
| self, | ||
| version: str = "v0", | ||
| model: str | None = None, | ||
| system_prompt: str | None = None, | ||
| ): | ||
| super().__init__() | ||
| self.system_prompt = system_prompt if system_prompt is not None else get_template(version).SYSTEM_PROMPT | ||
| self.version = version | ||
| self.model = model | ||
|
|
||
| def evaluate(self, evaluation_case: EvaluationData[InputT, OutputT]) -> list[EvaluationOutput]: | ||
| parsed_input = self._get_last_turn(evaluation_case) | ||
| prompt = self._format_prompt(parsed_input) | ||
| evaluator_agent = Agent(model=self.model, system_prompt=self.system_prompt, callback_handler=None) | ||
| rating = evaluator_agent.structured_output(FaithfulnessRating, prompt) | ||
| normalized_score = self._score_mapping[rating.score] | ||
| result = EvaluationOutput(score=normalized_score, test_pass=normalized_score >= 0.5, reason=rating.reasoning) | ||
| return [result] | ||
|
|
||
| async def evaluate_async(self, evaluation_case: EvaluationData[InputT, OutputT]) -> list[EvaluationOutput]: | ||
| parsed_input = self._get_last_turn(evaluation_case) | ||
| prompt = self._format_prompt(parsed_input) | ||
| evaluator_agent = Agent(model=self.model, system_prompt=self.system_prompt, callback_handler=None) | ||
| rating = await evaluator_agent.structured_output_async(FaithfulnessRating, prompt) | ||
| normalized_score = self._score_mapping[rating.score] | ||
| result = EvaluationOutput(score=normalized_score, test_pass=normalized_score >= 0.5, reason=rating.reasoning) | ||
| return [result] | ||
|
|
||
| def _get_last_turn(self, evaluation_case: EvaluationData[InputT, OutputT]) -> TraceLevelInput: | ||
| """Extract the most recent turn from the conversation for evaluation.""" | ||
| parsed_inputs = self._parse_trajectory(evaluation_case) | ||
| if not parsed_inputs: | ||
| raise ValueError( | ||
| "No turn-level inputs could be parsed from the trajectory. " | ||
| "Ensure actual_trajectory is a Session with at least one AgentInvocationSpan." | ||
| ) | ||
| return parsed_inputs[-1] | ||
|
|
||
| def _format_prompt(self, parsed_input: TraceLevelInput) -> str: | ||
| """Format evaluation prompt from parsed turn data.""" | ||
| parts = [] | ||
|
|
||
| if parsed_input.session_history: | ||
poshinchen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| history_lines = [] | ||
| for msg in parsed_input.session_history: | ||
| if isinstance(msg, list): | ||
| # Handle tool execution lists | ||
| for tool_exec in msg: | ||
| history_lines.append(f"Action: {tool_exec.tool_call.name}({tool_exec.tool_call.arguments})") | ||
| history_lines.append(f"Tool: {tool_exec.tool_result.content}") | ||
| else: | ||
| text = msg.content[0].text if msg.content and hasattr(msg.content[0], "text") else "" | ||
| history_lines.append(f"{msg.role.value.capitalize()}: {text}") | ||
| history_str = "\n".join(history_lines) | ||
| parts.append(f"# Conversation History:\n{history_str}") | ||
|
|
||
| parts.append(f"# Assistant's Response:\n{parsed_input.agent_response.text}") | ||
|
|
||
| return "\n\n".join(parts) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
11 changes: 11 additions & 0 deletions
11
src/strands_evals/evaluators/prompt_templates/faithfulness/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| from . import faithfulness_v0 | ||
|
|
||
| VERSIONS = { | ||
| "v0": faithfulness_v0, | ||
| } | ||
|
|
||
| DEFAULT_VERSION = "v0" | ||
|
|
||
|
|
||
| def get_template(version: str = DEFAULT_VERSION): | ||
| return VERSIONS[version] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.