Spaces:
Sleeping
Sleeping
File size: 8,756 Bytes
c96b98a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | from uuid import uuid4
from pathlib import Path
from typing import Optional, Union, Callable, List
from pydantic import BaseModel, ConfigDict, field_validator, Field
from phi.agent import Agent, RunResponse
from phi.utils.log import logger, set_log_level_to_debug
from phi.utils.timer import Timer
class AccuracyResult(BaseModel):
score: int = Field(..., description="Accuracy Score between 1 and 10 assigned to the Agent's answer.")
reason: str = Field(..., description="Detailed reasoning for the accuracy score.")
class EvalResult(BaseModel):
accuracy_score: int = Field(..., description="Accuracy Score between 1 to 10.")
accuracy_reason: str = Field(..., description="Reasoning for the accuracy score.")
class Eval(BaseModel):
# Evaluation name
name: Optional[str] = None
# Evaluation UUID (autogenerated if not set)
eval_id: Optional[str] = Field(None, validate_default=True)
# Agent to evaluate
agent: Optional[Agent] = None
# Question to evaluate
question: str
answer: Optional[str] = None
# Expected Answer for the question
expected_answer: str
# Result of the evaluation
result: Optional[EvalResult] = None
accuracy_evaluator: Optional[Agent] = None
# Guidelines for the accuracy evaluator
accuracy_guidelines: Optional[List[str]] = None
# Additional context to the accuracy evaluator
accuracy_context: Optional[str] = None
accuracy_result: Optional[AccuracyResult] = None
# Save the result to a file
save_result_to_file: Optional[str] = None
# debug_mode=True enables debug logs
debug_mode: bool = False
model_config = ConfigDict(arbitrary_types_allowed=True)
@field_validator("eval_id", mode="before")
def set_eval_id(cls, v: Optional[str] = None) -> str:
return v or str(uuid4())
@field_validator("debug_mode", mode="before")
def set_log_level(cls, v: bool) -> bool:
if v:
set_log_level_to_debug()
logger.debug("Debug logs enabled")
return v
def get_accuracy_evaluator(self) -> Agent:
if self.accuracy_evaluator is not None:
return self.accuracy_evaluator
try:
from phi.model.openai import OpenAIChat
except ImportError as e:
logger.exception(e)
logger.error(
"phidata uses `openai` as the default model provider. Please run `pip install openai` to use the default evaluator."
)
exit(1)
accuracy_guidelines = ""
if self.accuracy_guidelines is not None and len(self.accuracy_guidelines) > 0:
accuracy_guidelines = "\n## Guidelines for the AI Agent's answer:\n"
accuracy_guidelines += "\n- ".join(self.accuracy_guidelines)
accuracy_guidelines += "\n"
accuracy_context = ""
if self.accuracy_context is not None and len(self.accuracy_context) > 0:
accuracy_context = "## Additional Context:\n"
accuracy_context += self.accuracy_context
accuracy_context += "\n"
return Agent(
model=OpenAIChat(id="gpt-4o-mini"),
description=f"""\
You are an expert evaluator tasked with assessing the accuracy of an AI Agent's answer compared to an expected answer for a given question.
Your task is to provide a detailed analysis and assign a score on a scale of 1 to 10, where 10 indicates a perfect match to the expected answer.
## Question:
{self.question}
## Expected Answer:
{self.expected_answer}
## Evaluation Criteria:
1. Accuracy of information
2. Completeness of the answer
3. Relevance to the question
4. Use of key concepts and ideas
5. Overall structure and clarity of presentation
{accuracy_guidelines}{accuracy_context}
## Instructions:
1. Carefully compare the AI Agent's answer to the expected answer.
2. Provide a detailed analysis, highlighting:
- Specific similarities and differences
- Key points included or missed
- Any inaccuracies or misconceptions
3. Explicitly reference the evaluation criteria and any provided guidelines in your reasoning.
4. Assign a score from 1 to 10 (use only whole numbers) based on the following scale:
1-2: Completely incorrect or irrelevant
3-4: Major inaccuracies or missing crucial information
5-6: Partially correct, but with significant omissions or errors
7-8: Mostly accurate and complete, with minor issues
9-10: Highly accurate and complete, matching the expected answer closely
Your evaluation should be objective, thorough, and well-reasoned. Provide specific examples from both answers to support your assessment.""",
response_model=AccuracyResult,
)
def run(self, answer: Optional[Union[str, Callable]] = None) -> Optional[EvalResult]:
logger.debug(f"*********** Evaluation Start: {self.eval_id} ***********")
answer_to_evaluate: Optional[RunResponse] = None
if answer is None:
if self.agent is not None:
logger.debug("Getting answer from agent")
answer_to_evaluate = self.agent.run(self.question)
if self.answer is not None:
answer_to_evaluate = RunResponse(content=self.answer)
else:
try:
if callable(answer):
logger.debug("Getting answer from callable")
answer_to_evaluate = RunResponse(content=answer())
else:
answer_to_evaluate = RunResponse(content=answer)
except Exception as e:
logger.error(f"Failed to get answer: {e}")
raise
if answer_to_evaluate is None:
raise ValueError("No Answer to evaluate.")
else:
self.answer = answer_to_evaluate.content
logger.debug("************************ Evaluating ************************")
logger.debug(f"Question: {self.question}")
logger.debug(f"Expected Answer: {self.expected_answer}")
logger.debug(f"Answer: {answer_to_evaluate}")
logger.debug("************************************************************")
logger.debug("Evaluating accuracy...")
accuracy_evaluator = self.get_accuracy_evaluator()
try:
self.accuracy_result: AccuracyResult = accuracy_evaluator.run(
answer_to_evaluate.content, stream=False
).content
except Exception as e:
logger.error(f"Failed to evaluate accuracy: {e}")
return None
if self.accuracy_result is not None:
self.result = EvalResult(
accuracy_score=self.accuracy_result.score,
accuracy_reason=self.accuracy_result.reason,
)
# -*- Save result to file if save_result_to_file is set
if self.save_result_to_file is not None and self.result is not None:
try:
fn_path = Path(self.save_result_to_file.format(name=self.name, eval_id=self.eval_id))
if not fn_path.parent.exists():
fn_path.parent.mkdir(parents=True, exist_ok=True)
fn_path.write_text(self.result.model_dump_json(indent=4))
except Exception as e:
logger.warning(f"Failed to save result to file: {e}")
logger.debug(f"*********** Evaluation End: {self.eval_id} ***********")
return self.result
def print_result(self, answer: Optional[Union[str, Callable]] = None) -> Optional[EvalResult]:
from phi.cli.console import console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.box import ROUNDED
response_timer = Timer()
response_timer.start()
with Progress(SpinnerColumn(spinner_name="dots"), TextColumn("{task.description}"), transient=True) as progress:
progress.add_task("Working...")
result: Optional[EvalResult] = self.run(answer=answer)
response_timer.stop()
if result is None:
return None
table = Table(
box=ROUNDED,
border_style="blue",
show_header=False,
title="[ Evaluation Result ]",
title_style="bold sky_blue1",
title_justify="center",
)
table.add_row("Question", self.question)
table.add_row("Answer", self.answer)
table.add_row("Expected Answer", self.expected_answer)
table.add_row("Accuracy Score", f"{str(result.accuracy_score)}/10")
table.add_row("Accuracy Reason", result.accuracy_reason)
table.add_row("Time Taken", f"{response_timer.elapsed:.1f}s")
console.print(table)
return result
|