File size: 72,576 Bytes
1856027 | 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 | # -*- coding: utf-8 -*-
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re
import threading
import time
from unittest import mock
from google import auth
from google.auth import credentials as auth_credentials
from google.cloud import aiplatform
import vertexai
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform.metadata import metadata
from google.cloud.aiplatform_v1.services import (
evaluation_service as gapic_evaluation_services,
)
from google.cloud.aiplatform_v1.types import (
evaluation_service as gapic_evaluation_service_types,
)
from google.cloud.aiplatform_v1beta1.services import (
evaluation_service as gapic_evaluation_services_preview,
)
from google.cloud.aiplatform_v1beta1.types import (
evaluation_service as gapic_evaluation_service_types_preview,
)
from vertexai import evaluation
from vertexai import generative_models
from vertexai.evaluation import _base as eval_base
from vertexai.evaluation import _evaluation
from vertexai.evaluation import eval_task
from vertexai.evaluation import utils
from vertexai.evaluation.metrics import _rouge
from vertexai.evaluation.metrics import metric_prompt_template
from vertexai.evaluation.metrics import (
metric_prompt_template_examples,
)
from vertexai.evaluation.metrics import pairwise_metric
from vertexai.evaluation.metrics import pointwise_metric
from vertexai.preview import evaluation as evaluation_preview
from vertexai.preview import reasoning_engines
import numpy as np
import pandas as pd
import pytest
EvalTask = eval_task.EvalTask
EvalTaskPreview = evaluation_preview.eval_task.EvalTask
Pointwise = metric_prompt_template_examples.MetricPromptTemplateExamples.Pointwise
PointwisePreview = (
evaluation_preview.metrics.metric_prompt_template_examples.MetricPromptTemplateExamples.Pointwise
)
Pairwise = metric_prompt_template_examples.MetricPromptTemplateExamples.Pairwise
_TEST_PROJECT = "test-project"
_TEST_LOCATION = "us-central1"
_TEST_BUCKET = "gs://test-bucket"
_TEST_FILE_NAME = "test-file-name.csv"
_AUTORATER_INSTRUCTION = """
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by AI models.
"""
_METRIC_DEFINITION = "You will be assessing Text Quality"
_CRITERIA = {
"Coherence": ("The response presents ideas in a logical and organized manner."),
"Fluency": "The text flows smoothly and naturally",
}
_POINTWISE_RATING_RUBRIC = {
"3": "(Good). Well-written.",
"2": "(Ok). Adequate writing with decent coherence and fluency.",
"1": "(Bad). Poorly written.",
}
_PAIRWISE_RATING_RUBRIC = {
"A": "Response A answers better than response B.",
"SAME": "Response A and B answers equally well.",
"B": "Response B answers better than response A.",
}
_EVALUATION_STEPS = {
"STEP 1": "Assess grammar correctness",
"STEP 2": "Assess word choice and flow",
}
_TEST_POINTWISE_METRIC = pointwise_metric.PointwiseMetric(
metric="test_pointwise_metric",
metric_prompt_template=metric_prompt_template.PointwiseMetricPromptTemplate(
metric_definition=_METRIC_DEFINITION,
criteria=_CRITERIA,
rating_rubric=_POINTWISE_RATING_RUBRIC,
evaluation_steps=_EVALUATION_STEPS,
),
)
_TEST_POINTWISE_METRIC_FREE_STRING = pointwise_metric.PointwiseMetric(
metric="test_pointwise_metric_str", metric_prompt_template="abc: {abc}"
)
_TEST_PAIRWISE_METRIC = pairwise_metric.PairwiseMetric(
metric="test_pairwise_metric",
metric_prompt_template=metric_prompt_template.PairwiseMetricPromptTemplate(
metric_definition=_METRIC_DEFINITION,
criteria=_CRITERIA,
rating_rubric=_PAIRWISE_RATING_RUBRIC,
evaluation_steps=_EVALUATION_STEPS,
),
)
_TEST_COMET = pointwise_metric.Comet(
version="COMET_22_SRC_REF",
source_language="en",
target_language="zh",
)
_TEST_METRICX = pointwise_metric.MetricX(
version="METRICX_24_SRC",
source_language="en",
target_language="zh",
)
_TEST_METRICS = (
"exact_match",
"bleu",
"rouge_1",
"rouge_2",
"rouge_l",
"rouge_l_sum",
Pointwise.COHERENCE,
Pointwise.FLUENCY,
Pointwise.SAFETY,
Pointwise.GROUNDEDNESS,
Pointwise.SUMMARIZATION_QUALITY,
Pointwise.VERBOSITY,
Pointwise.QUESTION_ANSWERING_QUALITY,
_TEST_POINTWISE_METRIC,
_TEST_PAIRWISE_METRIC,
)
_TEST_EVAL_DATASET_WITHOUT_PROMPT = pd.DataFrame(
{
"response": ["test", "text"],
"reference": ["test", "ref"],
"context": ["test", "context"],
"instruction": ["test", "instruction"],
}
)
_TEST_EVAL_DATASET_WITHOUT_RESPONSE = pd.DataFrame(
{
"prompt": ["test", "prompt"],
"reference": ["test", "ref"],
"context": ["test", "context"],
"instruction": ["test", "instruction"],
}
)
_TEST_AGENT_EVAL_DATASET_WITHOUT_RESPONSE = pd.DataFrame(
{
"prompt": ["test_input1", "test_input2"],
"reference_trajectory": [
[{"tool_name": "test_tool1"}, {"tool_name": "test_tool2"}],
[{"tool_name": "test_tool3"}, {"tool_name": "test_tool4"}],
],
},
)
_TEST_EVAL_DATASET_ALL_INCLUDED = pd.DataFrame(
{
"prompt": ["test_prompt", "text_prompt"],
"response": ["test", "text"],
"reference": ["test", "ref"],
"context": ["test", "context"],
"instruction": ["test", "instruction"],
"source": ["test", "source"],
}
)
_TEST_EVAL_DATASET_SINGLE = pd.DataFrame({"prompt": ["test_prompt", "text_prompt"]})
_TEST_JSONL_FILE_CONTENT = """{"prompt": "prompt", "reference": "reference"}\n
{"prompt":"test", "reference": "test"}\n
"""
_TEST_CSV_FILE_CONTENT = """reference,context,instruction\ntest,test,test\n
text,text,text\n
"""
_TEST_EXPERIMENT = "test-experiment"
_TEST_CSV = pd.DataFrame(
columns={
"response": ["text"],
"reference": ["ref"],
}
)
_EXPECTED_POINTWISE_PROMPT_TEMPLATE = """
# Instruction
hello
# Evaluation
## Metric Definition
this is eval metric
## Criteria
metric1: summarization
## Rating Rubric
0: bad
1: good
## Evaluation Steps
step1: start
step2: finish
## Evaluation Examples
Q: hi A: hello
# User Inputs and AI-generated Response
## User Inputs
### country
{country}
## AI-generated Response
{response}
"""
_EXPECTED_POINTWISE_PROMPT_TEMPLATE_WITH_DEFAULT_VALUES = """
# Instruction
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by AI models. We will provide you with the user prompt and an AI-generated responses.
You should first read the user input carefully for analyzing the task, and then evaluate the quality of the responses based on the Criteria provided in the Evaluation section below.
You will assign the response a rating following the Rating Rubric and Evaluation Steps. Give step by step explanations for your rating, and only choose ratings from the Rating Rubric.
# Evaluation
## Criteria
Coherence: The response presents ideas in a logical and organized manner.
Fluency: The text flows smoothly and naturally
## Rating Rubric
1: (Bad). Poorly written.
2: (Ok). Adequate writing with decent coherence and fluency.
3: (Good). Well-written.
## Evaluation Steps
Step 1: Assess the response in aspects of all criteria provided. Provide assessment according to each criterion.
Step 2: Score based on the rating rubric. Give a brief rationale to explain your evaluation considering each individual criterion.
# User Inputs and AI-generated Response
## User Inputs
## AI-generated Response
{response}
"""
_EXPECTED_PAIRWISE_PROMPT_TEMPLATE = """
# Instruction
hello
# Evaluation
## Metric Definition
this is eval metric
## Criteria
metric1: summarization
## Rating Rubric
A: good
B: good
## Evaluation Steps
step1: start
step2: finish
## Evaluation Examples
Q: hi A: hello
# User Inputs and AI-generated Responses
## User Inputs
### country
{country}
## AI-generated Responses
### Response A
{baseline_model_response}
### Response B
{response}
"""
_EXPECTED_PAIRWISE_PROMPT_TEMPLATE_WITH_DEFAULT_VALUES = """
# Instruction
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by two AI models. We will provide you with the user input and a pair of AI-generated responses (Response A and Response B).
You should first read the user input carefully for analyzing the task, and then evaluate the quality of the responses based on based on the Criteria provided in the Evaluation section below.
You will first judge responses individually, following the Rating Rubric and Evaluation Steps. Then you will give step by step explanations for your judgement, compare results to declare the winner based on the Rating Rubric and Evaluation Steps.
# Evaluation
## Criteria
Coherence: The response presents ideas in a logical and organized manner.
Fluency: The text flows smoothly and naturally
## Rating Rubric
A: Response A answers better than response B.
B: Response B answers better than response A.
SAME: Response A and B answers equally well.
## Evaluation Steps
Step 1: Analyze Response A based on all the Criteria.
Step 2: Analyze Response B based on all the Criteria.
Step 3: Compare the overall performance of Response A and Response B based on your analyses and assessment.
Step 4: Output your preference of "A", "SAME" or "B" to the pairwise_choice field according to the Rating Rubrics.
Step 5: Output your assessment reasoning in the explanation field
# User Inputs and AI-generated Responses
## User Inputs
## AI-generated Responses
### Response A
{baseline_model_response}
### Response B
{response}
"""
_MOCK_RUNNABLE_INFERENCE_RESPONSE = [
{
"input": "test_input",
"output": "test_output",
"intermediate_steps": [
[{"kwargs": {"tool": "test_tool1"}, "tool_output": "test_tool_output"}],
[{"kwargs": {"tool": "test_tool2"}, "tool_output": "test_tool_output"}],
],
},
{
"input": "test_input",
"output": "test_output",
"intermediate_steps": [
[{"kwargs": {"tool": "test_tool2"}, "tool_output": "test_tool_output"}],
[{"kwargs": {"tool": "test_tool3"}, "tool_output": "test_tool_output"}],
],
},
]
_MOCK_EXACT_MATCH_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
exact_match_results=gapic_evaluation_service_types.ExactMatchResults(
exact_match_metric_values=[
gapic_evaluation_service_types.ExactMatchMetricValue(score=1.0),
]
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
exact_match_results=gapic_evaluation_service_types.ExactMatchResults(
exact_match_metric_values=[
gapic_evaluation_service_types.ExactMatchMetricValue(score=0.0),
]
)
),
)
_MOCK_TRAJECTORY_EXACT_MATCH_RESULT = (
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
trajectory_exact_match_results=gapic_evaluation_service_types_preview.TrajectoryExactMatchResults(
trajectory_exact_match_metric_values=[
gapic_evaluation_service_types_preview.TrajectoryExactMatchMetricValue(
score=1.0
),
]
)
),
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
trajectory_exact_match_results=gapic_evaluation_service_types_preview.TrajectoryExactMatchResults(
trajectory_exact_match_metric_values=[
gapic_evaluation_service_types_preview.TrajectoryExactMatchMetricValue(
score=0.0
),
]
)
),
)
_MOCK_POINTWISE_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=5, explanation="explanation"
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=4, explanation="explanation"
)
),
)
_MOCK_PAIRWISE_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.BASELINE,
explanation="explanation",
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.BASELINE,
explanation="explanation",
)
),
)
_MOCK_SUMMARIZATION_QUALITY_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=5, explanation="explanation"
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=4, explanation="explanation"
)
),
)
_MOCK_COHERENCE_RESULT = (
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types_preview.PointwiseMetricResult(
score=5, explanation="explanation"
)
),
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types_preview.PointwiseMetricResult(
score=4, explanation="explanation"
)
),
)
_MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.BASELINE,
explanation="explanation",
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.CANDIDATE,
explanation="explanation",
)
),
)
_MOCK_MODEL_INFERENCE_RESPONSE = generative_models.GenerationResponse.from_dict(
{
"candidates": [
{
"content": {"parts": [{"text": "test_response"}]},
}
]
}
)
MOCK_EVAL_RESULT = eval_base.EvalResult(
summary_metrics={
"row_count": 1,
"mock_metric/mean": 1.0,
"mock_metric/std": np.nan,
},
metrics_table=pd.DataFrame(
{
"response": ["test"],
"mock_metric": [1.0],
}
),
)
_EXPECTED_ROUGE_REQUESTS = (
gapic_evaluation_service_types.EvaluateInstancesRequest(
location=f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}",
rouge_input=gapic_evaluation_service_types.RougeInput(
metric_spec=gapic_evaluation_service_types.RougeSpec(
rouge_type="rougeLsum", use_stemmer=True, split_summaries=True
),
instances=[
gapic_evaluation_service_types.RougeInstance(
prediction="test_response", reference="test"
),
],
),
),
gapic_evaluation_service_types.EvaluateInstancesRequest(
location=f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}",
rouge_input=gapic_evaluation_service_types.RougeInput(
metric_spec=gapic_evaluation_service_types.RougeSpec(
rouge_type="rougeLsum", use_stemmer=True, split_summaries=True
),
instances=[
gapic_evaluation_service_types.RougeInstance(
prediction="test_response", reference="ref"
),
],
),
),
)
_MOCK_ROUGE_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
rouge_results=gapic_evaluation_service_types.RougeResults(
rouge_metric_values=[
gapic_evaluation_service_types.RougeMetricValue(score=1.0)
]
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
rouge_results=gapic_evaluation_service_types.RougeResults(
rouge_metric_values=[
gapic_evaluation_service_types.RougeMetricValue(score=0.5)
]
)
),
)
_EXPECTED_COLUMN_MAPPING = {
"context": "context",
"reference": "reference",
"response": "response",
"instruction": "instruction",
"prompt": "prompt",
"source": "source",
}
_MOCK_MODEL_BASED_TRANSLATION_RESULT = (
# The order of the responses is important.
gapic_evaluation_service_types.EvaluateInstancesResponse(
comet_result=gapic_evaluation_service_types.CometResult(score=0.1)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
metricx_result=gapic_evaluation_service_types.MetricxResult(score=5)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
comet_result=gapic_evaluation_service_types.CometResult(score=0.9)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
metricx_result=gapic_evaluation_service_types.MetricxResult(score=20)
),
)
@pytest.fixture(scope="module")
def google_auth_mock():
with mock.patch.object(auth, "default") as google_auth_mock:
google_auth_mock.return_value = (
auth_credentials.AnonymousCredentials(),
_TEST_PROJECT,
)
yield google_auth_mock
@pytest.fixture
def mock_experiment_tracker():
with mock.patch.object(
metadata, "_experiment_tracker", autospec=True
) as mock_experiment_tracker:
yield mock_experiment_tracker
@pytest.fixture
def mock_storage_blob_upload_from_filename():
with mock.patch(
"google.cloud.storage.Blob.upload_from_filename"
) as mock_blob_upload_from_filename, mock.patch(
"google.cloud.storage.Bucket.exists", return_value=True
):
yield mock_blob_upload_from_filename
@pytest.mark.usefixtures("google_auth_mock")
class TestEvaluation:
def setup_method(self):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
def test_create_eval_task(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=_TEST_METRICS,
experiment=_TEST_EXPERIMENT,
)
assert test_eval_task.dataset.equals(_TEST_EVAL_DATASET_ALL_INCLUDED)
assert test_eval_task.metrics == _TEST_METRICS
assert test_eval_task.experiment == _TEST_EXPERIMENT
assert test_eval_task._metric_column_mapping == _EXPECTED_COLUMN_MAPPING
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_exact_match_metric(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
eval_dataset = pd.DataFrame(
{
"response": ["test", "text"],
"reference": ["test", "ref"],
}
)
test_metrics = ["exact_match"]
test_eval_task = EvalTask(dataset=eval_dataset, metrics=test_metrics)
mock_metric_results = _MOCK_EXACT_MATCH_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["exact_match/mean"] == 0.5
assert test_result.summary_metrics["exact_match/std"] == pytest.approx(0.7, 0.1)
assert list(test_result.metrics_table.columns.values) == [
"response",
"reference",
"exact_match/score",
]
assert test_result.metrics_table[["response", "reference"]].equals(eval_dataset)
assert list(test_result.metrics_table["exact_match/score"].values) == [
1.0,
0.0,
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pointwise_metrics(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
test_metrics = [_TEST_POINTWISE_METRIC]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
mock_metric_results = _MOCK_POINTWISE_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["test_pointwise_metric/mean"] == 4.5
assert test_result.summary_metrics[
"test_pointwise_metric/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"context",
"instruction",
"reference",
"test_pointwise_metric/score",
"test_pointwise_metric/explanation",
"source",
]
)
assert test_result.metrics_table["response"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["response"]
)
assert test_result.metrics_table["prompt"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["prompt"]
)
assert list(
test_result.metrics_table["test_pointwise_metric/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["test_pointwise_metric/explanation"].values
) == [
"explanation",
"explanation",
]
def test_compute_pointwise_metrics_free_string(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=[_TEST_POINTWISE_METRIC_FREE_STRING],
metric_column_mapping={"abc": "prompt"},
)
mock_metric_results = _MOCK_POINTWISE_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["test_pointwise_metric_str/mean"] == 4.5
assert test_result.summary_metrics[
"test_pointwise_metric_str/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"context",
"instruction",
"reference",
"test_pointwise_metric_str/score",
"test_pointwise_metric_str/explanation",
"source",
]
)
assert test_result.metrics_table["response"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["response"]
)
assert test_result.metrics_table["prompt"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["prompt"]
)
assert list(
test_result.metrics_table["test_pointwise_metric_str/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["test_pointwise_metric_str/explanation"].values
) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pointwise_metrics_metric_prompt_template_example(
self, api_transport
):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_model.generate_content.return_value = _MOCK_MODEL_INFERENCE_RESPONSE
mock_model._model_name = "publishers/google/model/gemini-1.0-pro"
test_metrics = [Pointwise.SUMMARIZATION_QUALITY]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = _MOCK_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_model,
prompt_template="{instruction} test prompt template {context}",
)
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["summarization_quality/mean"] == 4.5
assert test_result.summary_metrics[
"summarization_quality/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"reference",
"prompt",
"response",
"summarization_quality/score",
"summarization_quality/explanation",
]
)
assert list(
test_result.metrics_table["summarization_quality/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["summarization_quality/explanation"].values
) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pointwise_metrics_without_model_inference(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
test_metrics = [Pointwise.SUMMARIZATION_QUALITY]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
mock_metric_results = _MOCK_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["summarization_quality/mean"] == 4.5
assert test_result.summary_metrics[
"summarization_quality/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"reference",
"prompt",
"response",
"summarization_quality/score",
"summarization_quality/explanation",
"source",
]
)
assert list(
test_result.metrics_table["summarization_quality/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["summarization_quality/explanation"].values
) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_model_based_translation_metrics_without_model_inference(
self, api_transport
):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
test_metrics = [_TEST_COMET, _TEST_METRICX]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
mock_metric_results = _MOCK_MODEL_BASED_TRANSLATION_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["comet/mean"] == 0.5
assert test_result.summary_metrics["metricx/mean"] == 12.5
assert test_result.summary_metrics["comet/std"] == pytest.approx(0.5, 0.6)
assert test_result.summary_metrics["metricx/std"] == pytest.approx(10, 11)
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"reference",
"prompt",
"response",
"source",
"comet/score",
"metricx/score",
]
)
assert list(test_result.metrics_table["comet/score"].values) == [0.1, 0.9]
assert list(test_result.metrics_table["metricx/score"].values) == [5, 20]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_automatic_metrics_with_custom_metric_spec(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_model.generate_content.return_value = _MOCK_MODEL_INFERENCE_RESPONSE
mock_model._model_name = "publishers/google/model/gemini-1.0-pro"
test_metrics = [
_rouge.Rouge(
rouge_type="rougeLsum",
use_stemmer=True,
split_summaries=True,
)
]
test_eval_task = evaluation.EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=_MOCK_ROUGE_RESULT,
) as mock_evaluate_instances:
test_result = test_eval_task.evaluate(
model=mock_model,
)
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["rouge/mean"] == 0.75
assert test_result.summary_metrics["rouge/std"] == pytest.approx(0.35, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"reference",
"response",
"context",
"instruction",
"rouge/score",
]
)
assert list(test_result.metrics_table["rouge/score"].values) == [1, 0.5]
api_requests = [
call.kwargs["request"] for call in mock_evaluate_instances.call_args_list
]
assert api_requests == list(_EXPECTED_ROUGE_REQUESTS)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pairwise_metrics(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_baseline_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_baseline_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_baseline_model._model_name = "publishers/google/model/gemini-pro"
mock_candidate_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_candidate_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_candidate_model._model_name = "publishers/google/model/gemini-pro"
_TEST_PAIRWISE_METRIC._baseline_model = mock_baseline_model
test_metrics = [_TEST_PAIRWISE_METRIC]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = _MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_candidate_model,
prompt_template="{instruction} test prompt template {context}",
)
_TEST_PAIRWISE_METRIC._baseline_model = None
assert test_result.summary_metrics["row_count"] == 2
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"prompt",
"response",
"reference",
"baseline_model_response",
"test_pairwise_metric/pairwise_choice",
"test_pairwise_metric/explanation",
]
)
assert list(
test_result.metrics_table["test_pairwise_metric/pairwise_choice"].values
) == ["BASELINE", "CANDIDATE"]
assert list(
test_result.metrics_table["test_pairwise_metric/explanation"].values
) == [
"explanation",
"explanation",
]
assert set(test_result.summary_metrics.keys()) == set(
[
"row_count",
"test_pairwise_metric/candidate_model_win_rate",
"test_pairwise_metric/baseline_model_win_rate",
]
)
assert (
test_result.summary_metrics["test_pairwise_metric/candidate_model_win_rate"]
== 0.5
)
assert (
test_result.summary_metrics["test_pairwise_metric/baseline_model_win_rate"]
== 0.5
)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pairwise_metrics_metric_prompt_template_example(
self, api_transport
):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
eval_dataset = _TEST_EVAL_DATASET_WITHOUT_RESPONSE.copy(deep=True)
eval_dataset.insert(1, "baseline_model_response", ["baseline", "response"])
mock_candidate_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_candidate_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_candidate_model._model_name = "publishers/google/model/gemini-pro"
test_metrics = [Pairwise.SUMMARIZATION_QUALITY]
test_eval_task = EvalTask(dataset=eval_dataset, metrics=test_metrics)
mock_metric_results = _MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_candidate_model,
prompt_template="{instruction} test prompt template {context}",
)
assert test_result.summary_metrics["row_count"] == 2
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"prompt",
"response",
"reference",
"baseline_model_response",
"pairwise_summarization_quality/pairwise_choice",
"pairwise_summarization_quality/explanation",
]
)
assert list(
test_result.metrics_table[
"pairwise_summarization_quality/pairwise_choice"
].values
) == ["BASELINE", "CANDIDATE"]
assert list(
test_result.metrics_table[
"pairwise_summarization_quality/explanation"
].values
) == [
"explanation",
"explanation",
]
assert set(test_result.summary_metrics.keys()) == set(
[
"row_count",
"pairwise_summarization_quality/candidate_model_win_rate",
"pairwise_summarization_quality/baseline_model_win_rate",
]
)
assert (
test_result.summary_metrics[
"pairwise_summarization_quality/candidate_model_win_rate"
]
== 0.5
)
assert (
test_result.summary_metrics[
"pairwise_summarization_quality/baseline_model_win_rate"
]
== 0.5
)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pairwise_metrics_without_model_inference(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
eval_dataset = _TEST_EVAL_DATASET_ALL_INCLUDED.copy(deep=True)
eval_dataset.insert(1, "baseline_model_response", ["baseline", "response"])
test_metrics = [Pairwise.SUMMARIZATION_QUALITY]
test_eval_task = EvalTask(dataset=eval_dataset, metrics=test_metrics)
mock_metric_results = _MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"baseline_model_response",
"reference",
"context",
"instruction",
"pairwise_summarization_quality/pairwise_choice",
"pairwise_summarization_quality/explanation",
"source",
]
)
assert list(
test_result.metrics_table[
"pairwise_summarization_quality/pairwise_choice"
].values
) == ["BASELINE", "CANDIDATE"]
assert list(
test_result.metrics_table[
"pairwise_summarization_quality/explanation"
].values
) == [
"explanation",
"explanation",
]
assert set(test_result.summary_metrics.keys()) == set(
[
"row_count",
"pairwise_summarization_quality/candidate_model_win_rate",
"pairwise_summarization_quality/baseline_model_win_rate",
]
)
assert (
test_result.summary_metrics[
"pairwise_summarization_quality/candidate_model_win_rate"
]
== 0.5
)
assert (
test_result.summary_metrics[
"pairwise_summarization_quality/baseline_model_win_rate"
]
== 0.5
)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_multiple_metrics(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_baseline_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_baseline_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_baseline_model._model_name = "publishers/google/model/gemini-pro"
_TEST_PAIRWISE_METRIC._baseline_model = mock_baseline_model
mock_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_model.generate_content.return_value = _MOCK_MODEL_INFERENCE_RESPONSE
mock_model._model_name = "publishers/google/model/gemini-pro"
test_metrics = [
"exact_match",
Pointwise.SUMMARIZATION_QUALITY,
_TEST_PAIRWISE_METRIC,
]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = (
_MOCK_EXACT_MATCH_RESULT[0],
_MOCK_SUMMARIZATION_QUALITY_RESULT[0],
_MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT[0],
_MOCK_EXACT_MATCH_RESULT[1],
_MOCK_SUMMARIZATION_QUALITY_RESULT[1],
_MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT[1],
)
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_model,
prompt_template="{instruction} test prompt template {context}",
)
_TEST_PAIRWISE_METRIC._baseline_model = None
assert test_result.summary_metrics["row_count"] == 2
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"baseline_model_response",
"reference",
"context",
"instruction",
"exact_match/score",
"summarization_quality/score",
"summarization_quality/explanation",
"test_pairwise_metric/pairwise_choice",
"test_pairwise_metric/explanation",
]
)
assert list(test_result.metrics_table["exact_match/score"].values) == [
1.0,
0.0,
]
assert list(
test_result.metrics_table["test_pairwise_metric/pairwise_choice"].values
) == ["BASELINE", "CANDIDATE"]
assert list(
test_result.metrics_table["test_pairwise_metric/explanation"].values
) == [
"explanation",
"explanation",
]
assert (
test_result.summary_metrics["test_pairwise_metric/candidate_model_win_rate"]
== 0.5
)
assert (
test_result.summary_metrics["test_pairwise_metric/baseline_model_win_rate"]
== 0.5
)
assert list(
test_result.metrics_table["summarization_quality/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["summarization_quality/explanation"].values
) == [
"explanation",
"explanation",
]
def test_eval_result_experiment_run_logging(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=[Pointwise.FLUENCY],
experiment=_TEST_EXPERIMENT,
)
with mock.patch.multiple(
metadata._experiment_tracker,
_experiment=mock.MagicMock(name=_TEST_EXPERIMENT),
_experiment_run=None,
set_experiment=mock.DEFAULT,
reset=mock.DEFAULT,
):
with mock.patch.multiple(
vertexai.preview,
start_run=mock.MagicMock(),
log_params=mock.DEFAULT,
log_metrics=mock.DEFAULT,
) as mock_metadata:
with mock.patch.object(
target=_evaluation,
attribute="evaluate",
side_effect=[MOCK_EVAL_RESULT],
):
_ = test_eval_task.evaluate()
mock_metadata["log_metrics"].assert_called_once_with(
{"row_count": 1, "mock_metric/mean": 1.0, "mock_metric/std": "NaN"}
)
@pytest.mark.usefixtures("google_auth_mock")
class TestAgentEvaluation:
def setup_method(self):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_runnable_response_eval_with_runnable_inference(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_runnable = mock.create_autospec(reasoning_engines.Queryable, instance=True)
mock_runnable.query.return_value = _MOCK_RUNNABLE_INFERENCE_RESPONSE
test_metrics = [PointwisePreview.COHERENCE]
test_eval_task = EvalTaskPreview(
dataset=_TEST_AGENT_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = _MOCK_COHERENCE_RESULT
with mock.patch.object(
target=gapic_evaluation_services_preview.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
runnable=mock_runnable,
prompt_template="test prompt template",
)
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["coherence/mean"] == 4.5
assert test_result.summary_metrics["coherence/std"] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"reference_trajectory",
"response",
"latency_in_seconds",
"failure",
"predicted_trajectory",
"coherence/score",
"coherence/explanation",
]
)
assert list(test_result.metrics_table["coherence/score"].values) == [5, 4]
assert list(test_result.metrics_table["coherence/explanation"].values) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_runnable_trajectory_eval_with_runnable_inference(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_runnable = mock.create_autospec(reasoning_engines.Queryable, instance=True)
mock_runnable.query.return_value = _MOCK_RUNNABLE_INFERENCE_RESPONSE
test_metrics = ["trajectory_exact_match"]
test_eval_task = EvalTaskPreview(
dataset=_TEST_AGENT_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = _MOCK_TRAJECTORY_EXACT_MATCH_RESULT
with mock.patch.object(
target=gapic_evaluation_services_preview.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(runnable=mock_runnable)
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["trajectory_exact_match/mean"] == 0.5
assert test_result.summary_metrics[
"trajectory_exact_match/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"latency_in_seconds",
"failure",
"predicted_trajectory",
"reference_trajectory",
"trajectory_exact_match/score",
]
)
assert list(
test_result.metrics_table["trajectory_exact_match/score"].values
) == [1.0, 0.0]
@pytest.mark.usefixtures("google_auth_mock")
class TestEvaluationErrors:
def setup_method(self):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
def test_evaluate_empty_metrics(self):
test_eval_task = EvalTask(dataset=_TEST_EVAL_DATASET_WITHOUT_PROMPT, metrics=[])
with pytest.raises(ValueError, match="Metrics cannot be empty."):
test_eval_task.evaluate()
def test_evaluate_invalid_metrics(self):
metric_name = "invalid_metric"
with pytest.raises(
ValueError,
match=f"Metric name: {metric_name} is not supported.",
):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_PROMPT, metrics=[metric_name]
)
test_eval_task.evaluate()
def test_evaluate_duplicate_string_metric(self):
metrics = [
"exact_match",
"exact_match",
]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_PROMPT, metrics=metrics
)
with pytest.raises(
ValueError,
match="Duplicate string metric name found: 'exact_match'",
):
test_eval_task.evaluate()
def test_evaluate_duplicate_metric_instances(self):
metrics = [
Pointwise.SUMMARIZATION_QUALITY,
Pointwise.SUMMARIZATION_QUALITY,
]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=metrics
)
with pytest.raises(
ValueError,
match=(
"Duplicate Metric instances of the same metric name found:"
" 'summarization_quality'"
),
):
test_eval_task.evaluate()
def test_evaluate_invalid_experiment_run_name(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_PROMPT, metrics=_TEST_METRICS
)
with pytest.raises(ValueError, match="Experiment is not set"):
test_eval_task.evaluate(experiment_run_name="invalid_experiment_run_name")
with pytest.raises(ValueError, match="Experiment is not set"):
test_eval_task.display_runs()
def test_evaluate_experiment_name_already_exists(self, mock_experiment_tracker):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_PROMPT,
metrics=_TEST_METRICS,
experiment="test_eval_experiment_name",
)
mock_experiment_tracker.experiment_run.return_value = "experiment_run_1"
with pytest.raises(ValueError, match="Experiment run already exists"):
test_eval_task.evaluate(experiment_run_name="experiment_run_2")
def test_evaluate_response_column_and_model_provided(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=[_TEST_POINTWISE_METRIC],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"The `model` parameter or `baseline_model` in pairwise metric is"
" specified, but the evaluation `dataset` contains model response"
" column or baseline model response column `response`"
" to perform bring-your-own-response(BYOR) evaluation. If you would"
" like to perform evaluation using the dataset with the"
" existing model response column or or baseline model response column"
" `response`, please remove `model` parameter in `EvalTask.evaluate()`"
" function or `baseline_model` in `PairwiseMetric`."
)
),
):
test_eval_task.evaluate(model=mock.MagicMock())
def test_evaluate_baseline_response_column_and_baseline_model_provided(self):
_TEST_PAIRWISE_METRIC._baseline_model = mock.MagicMock()
eval_dataset = _TEST_EVAL_DATASET_WITHOUT_RESPONSE.copy(deep=True)
eval_dataset.insert(1, "baseline_model_response", ["baseline", "response"])
test_eval_task = EvalTask(
dataset=eval_dataset,
metrics=[_TEST_PAIRWISE_METRIC],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"The `model` parameter or `baseline_model` in pairwise metric is"
" specified, but the evaluation `dataset` contains model response"
" column or baseline model response column `baseline_model_response`"
" to perform bring-your-own-response(BYOR) evaluation. If you would"
" like to perform evaluation using the dataset with the"
" existing model response column or or baseline model response column"
" `baseline_model_response`, please remove `model` parameter in"
" `EvalTask.evaluate()` function or `baseline_model` in"
" `PairwiseMetric`."
)
),
):
test_eval_task.evaluate(model=mock.MagicMock())
_TEST_PAIRWISE_METRIC._baseline_model = None
def test_evaluate_baseline_model_provided_but_no_baseline_response_column(self):
mock_baseline_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_baseline_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_baseline_model._model_name = "publishers/google/model/gemini-pro"
_TEST_PAIRWISE_METRIC._baseline_model = mock_baseline_model
mock_candidate_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_candidate_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_candidate_model._model_name = "publishers/google/model/gemini-1.0-pro"
mock_metric_results = _MOCK_PAIRWISE_RESULT
eval_dataset = _TEST_EVAL_DATASET_WITHOUT_RESPONSE.copy(deep=True)
test_eval_task = EvalTask(
dataset=eval_dataset,
metrics=[_TEST_PAIRWISE_METRIC],
)
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_candidate_model,
)
_TEST_PAIRWISE_METRIC._baseline_model = None
assert test_result.summary_metrics["row_count"] == 2
def test_evaluate_response_column_and_model_not_provided(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_SINGLE,
metrics=[_TEST_POINTWISE_METRIC],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"Cannot find the `response` column in the evaluation dataset"
" to fill the metric prompt template for"
" `test_pointwise_metric` metric."
)
),
):
test_eval_task.evaluate()
def test_evaluate_baseline_model_response_column_not_provided(
self,
):
test_eval_dataset = _TEST_EVAL_DATASET_SINGLE.copy(deep=True)
test_eval_dataset.insert(1, "response", ["test", "response"])
test_eval_task = EvalTask(
dataset=test_eval_dataset,
metrics=[_TEST_PAIRWISE_METRIC],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"Cannot find the `baseline_model_response` column in the"
" evaluation dataset to fill the metric prompt template for"
" `test_pairwise_metric` metric."
)
),
):
test_eval_task.evaluate()
@pytest.mark.parametrize("eval_task_version", [EvalTask, EvalTaskPreview])
def test_evaluate_response_column_not_provided(self, eval_task_version):
test_eval_dataset = _TEST_EVAL_DATASET_SINGLE
test_eval_task = eval_task_version(
dataset=test_eval_dataset,
metrics=["exact_match"],
)
with pytest.raises(
KeyError,
match=re.escape(
(
"Required column `response` not found in the evaluation "
"dataset. The columns in the evaluation dataset are ['prompt']"
)
),
):
test_eval_task.evaluate()
@pytest.mark.parametrize("eval_task_version", [EvalTask, EvalTaskPreview])
def test_evaluate_reference_column_not_provided(self, eval_task_version):
test_eval_dataset = pd.DataFrame({"response": ["test", "text"]})
test_eval_task = eval_task_version(
dataset=test_eval_dataset,
metrics=["exact_match"],
)
with pytest.raises(
KeyError,
match=re.escape(
(
"Required column `reference` not found in the evaluation "
"dataset. The columns in the evaluation dataset are ['response']"
)
),
):
test_eval_task.evaluate()
def test_evaluate_reference_or_source_column_not_provided(
self,
):
test_eval_dataset = pd.DataFrame({"response": ["test", "text"]})
test_eval_task = EvalTask(
dataset=test_eval_dataset,
metrics=[_TEST_COMET, _TEST_METRICX],
)
with pytest.raises(
KeyError,
match=re.escape(
(
"Required column `source` not found in the evaluation "
"dataset. The columns in the evaluation dataset are ['response']"
)
),
):
test_eval_task.evaluate()
def test_evaluate_invalid_prompt_template_variables(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_SINGLE,
metrics=[Pointwise.FLUENCY],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"Failed to assemble prompt template: The following column(s) are"
" missing: invalid_variable. Please verify prompt_template"
" variables {'invalid_variable'} and evaluation dataset"
" column names {'prompt'}."
)
),
):
test_eval_task.evaluate(
prompt_template="test_prompt_template {invalid_variable}",
)
def test_evaluate_pairwise_metrics_with_multiple_baseline_models(self):
mock_baseline_model_1 = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_baseline_model_1._model_name = "publishers/google/model/gemini-1.0-pro"
mock_baseline_model_2 = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_baseline_model_2._model_name = "publishers/google/model/gemini-1.5-pro"
test_metrics = [
pairwise_metric.PairwiseMetric(
metric="pairwise_metric_1",
metric_prompt_template="test_prompt_template",
baseline_model=mock_baseline_model_1,
),
pairwise_metric.PairwiseMetric(
metric="pairwise_metric_2",
metric_prompt_template="test_prompt_template",
baseline_model=mock_baseline_model_2,
),
]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
with pytest.raises(
ValueError,
match="Not all `PairwiseMetric` instances have the same `baseline_model`",
):
test_eval_task.evaluate()
def test_evaluate_invalid_model_and_dataset_input(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_PROMPT,
metrics=[_TEST_POINTWISE_METRIC],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"The `model` parameter or `baseline_model` in pairwise metric is"
" specified, but the evaluation `dataset` contains model response"
" column or baseline model response column `response`"
" to perform bring-your-own-response(BYOR) evaluation. If you would"
" like to perform evaluation using the dataset with the"
" existing model response column or or baseline model response column"
" `response`, please remove `model` parameter in `EvalTask.evaluate()`"
" function or `baseline_model` in `PairwiseMetric`."
)
),
):
test_eval_task.evaluate(
model=generative_models.GenerativeModel(model_name="invalid_model_name")
)
def test_unmatched_metric_column_mapping(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=[_TEST_POINTWISE_METRIC_FREE_STRING],
)
with pytest.raises(
ValueError,
match=re.escape(
(
"The `model` parameter or `baseline_model` in pairwise metric is"
" specified, but the evaluation `dataset` contains model response"
" column or baseline model response column `response`"
" to perform bring-your-own-response(BYOR) evaluation. If you would"
" like to perform evaluation using the dataset with the"
" existing model response column or or baseline model response column"
" `response`, please remove `model` parameter in `EvalTask.evaluate()`"
" function or `baseline_model` in `PairwiseMetric`."
)
),
):
test_eval_task.evaluate(
model=generative_models.GenerativeModel(model_name="invalid_model_name")
)
@pytest.mark.usefixtures("google_auth_mock")
class TestEvaluationUtils:
def setup_method(self):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
def test_create_evaluation_service_client(self):
client = utils.create_evaluation_service_client()
assert isinstance(client, utils._EvaluationServiceClientWithOverride)
def test_load_dataset_from_dataframe(self):
data = {"col1": [1, 2], "col2": ["a", "b"]}
df = pd.DataFrame(data)
loaded_df = utils.load_dataset(df)
assert loaded_df.equals(df)
def test_load_dataset_from_dict(self):
data = {"col1": [1, 2], "col2": ["a", "b"]}
loaded_df = utils.load_dataset(data)
assert isinstance(loaded_df, pd.DataFrame)
assert loaded_df.to_dict("list") == data
def test_load_dataset_from_gcs_jsonl(self):
source = "gs://test_bucket/test_file.jsonl"
with mock.patch.object(
utils,
"_read_gcs_file_contents",
return_value=_TEST_JSONL_FILE_CONTENT,
):
loaded_df = utils.load_dataset(source)
assert isinstance(loaded_df, pd.DataFrame)
assert loaded_df.to_dict("list") == {
"prompt": ["prompt", "test"],
"reference": ["reference", "test"],
}
def test_load_dataset_from_gcs_csv(self):
source = "gs://test_bucket/test_file.csv"
with mock.patch.object(
utils, "_read_gcs_file_contents", return_value=_TEST_CSV_FILE_CONTENT
):
loaded_df = utils.load_dataset(source)
assert isinstance(loaded_df, pd.DataFrame)
assert loaded_df.to_dict("list") == {
"reference": ["test", "text"],
"context": ["test", "text"],
"instruction": ["test", "text"],
}
def test_load_dataset_from_bigquery(self):
source = "bq://project-id.dataset.table_name"
with mock.patch.object(
utils, "_load_bigquery", return_value=_TEST_EVAL_DATASET_WITHOUT_PROMPT
):
loaded_df = utils.load_dataset(source)
assert isinstance(loaded_df, pd.DataFrame)
assert loaded_df.equals(_TEST_EVAL_DATASET_WITHOUT_PROMPT)
def test_initialization(self):
limiter = utils.RateLimiter(rate=2)
assert limiter.seconds_per_event == 0.5
with pytest.raises(ValueError, match="Rate must be a positive number"):
utils.RateLimiter(-1)
with pytest.raises(ValueError, match="Rate must be a positive number"):
utils.RateLimiter(0)
def test_admit(self):
rate_limiter = utils.RateLimiter(rate=2)
assert rate_limiter._admit() == 0
time.sleep(0.1)
delay = rate_limiter._admit()
assert delay == pytest.approx(0.4, 0.01)
time.sleep(0.5)
delay = rate_limiter._admit()
assert delay == 0
def test_sleep_and_advance(self):
rate_limiter = utils.RateLimiter(rate=2)
start_time = time.time()
rate_limiter.sleep_and_advance()
assert (time.time() - start_time) < 0.1
start_time = time.time()
rate_limiter.sleep_and_advance()
assert (time.time() - start_time) >= 0.5
def test_thread_safety(self):
rate_limiter = utils.RateLimiter(rate=2)
start_time = time.time()
def target():
rate_limiter.sleep_and_advance()
threads = [threading.Thread(target=target) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
# Verify that the total minimum time should be 4.5 seconds
# (9 intervals of 0.5 seconds each).
total_time = time.time() - start_time
assert total_time >= 4.5
# TODO(b/361123127) Add test_to_metrics_spec back
def test_initialize_metric_column_mapping(self):
metric_column_mapping = {
"prompt": "prompt2",
"response": "response1",
"reference": "reference",
}
converted_metric_column_mapping = utils.initialize_metric_column_mapping(
metric_column_mapping=metric_column_mapping,
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
)
assert converted_metric_column_mapping == _EXPECTED_COLUMN_MAPPING
class TestPromptTemplate:
def test_init(self):
template_str = "Hello, {name}!"
prompt_template = evaluation.PromptTemplate(template_str)
assert prompt_template.template == template_str
def test_get_variables(self):
template_str = "Hello, {name}! Today is {day}."
prompt_template = evaluation.PromptTemplate(template_str)
assert prompt_template.variables == {"name", "day"}
def test_format(self):
template_str = "Hello, {name}! Today is {day}."
prompt_template = evaluation.PromptTemplate(template_str)
assembled_prompt = prompt_template.assemble(name="John", day="Monday")
assert str(assembled_prompt) == "Hello, John! Today is Monday."
def test_format_missing_variable(self):
template_str = "Hello, {name}!"
prompt_template = evaluation.PromptTemplate(template_str)
assembled_prompt = prompt_template.assemble()
assert str(assembled_prompt) == "Hello, {name}!"
assert prompt_template.variables == {"name"}
def test_partial_format(self):
template_str = "Hello, {name}! Today is {day}."
prompt_template = evaluation.PromptTemplate(template_str)
partially_assembled_prompt = prompt_template.assemble(name="John")
assert isinstance(partially_assembled_prompt, evaluation.PromptTemplate)
assert str(partially_assembled_prompt) == "Hello, John! Today is {day}."
assert partially_assembled_prompt.variables == {"day"}
assembled_prompt = partially_assembled_prompt.assemble(day="Monday")
assert str(assembled_prompt) == "Hello, John! Today is Monday."
def test_str(self):
template_str = "Hello, world!"
prompt_template = evaluation.PromptTemplate(template_str)
assert str(prompt_template) == template_str
def test_repr(self):
template_str = "Hello, {name}!"
prompt_template = evaluation.PromptTemplate(template_str)
assert repr(prompt_template) == f"PromptTemplate('{template_str}')"
def test_pointwise_metric_prompt_template(self):
pointwise_metric_prompt_template = evaluation.PointwiseMetricPromptTemplate(
criteria={"metric1": "summarization"},
rating_rubric={"1": "good", "0": "bad"},
input_variables=["country"],
instruction="hello",
metric_definition="this is eval metric",
evaluation_steps={"step1": "start", "step2": "finish"},
few_shot_examples=["Q: hi A: hello"],
)
assert (
str(pointwise_metric_prompt_template)
== _EXPECTED_POINTWISE_PROMPT_TEMPLATE.strip()
)
def test_pointwise_metric_prompt_template_with_default_values(self):
pointwise_metric_prompt_template = evaluation.PointwiseMetricPromptTemplate(
criteria=_CRITERIA,
rating_rubric=_POINTWISE_RATING_RUBRIC,
)
assert (
str(pointwise_metric_prompt_template)
== _EXPECTED_POINTWISE_PROMPT_TEMPLATE_WITH_DEFAULT_VALUES.strip()
)
def test_pairtwise_metric_prompt_template(self):
pairwise_metric_prompt_template = evaluation.PairwiseMetricPromptTemplate(
criteria={"metric1": "summarization"},
rating_rubric={"A": "good", "B": "good"},
input_variables=["country"],
instruction="hello",
metric_definition="this is eval metric",
evaluation_steps={"step1": "start", "step2": "finish"},
few_shot_examples=["Q: hi A: hello"],
)
assert (
str(pairwise_metric_prompt_template)
== _EXPECTED_PAIRWISE_PROMPT_TEMPLATE.strip()
)
def test_pairtwise_metric_prompt_template_with_default_values(self):
pairwise_metric_prompt_template = evaluation.PairwiseMetricPromptTemplate(
criteria=_CRITERIA,
rating_rubric=_PAIRWISE_RATING_RUBRIC,
)
assert (
str(pairwise_metric_prompt_template)
== _EXPECTED_PAIRWISE_PROMPT_TEMPLATE_WITH_DEFAULT_VALUES.strip()
)
def test_upload_results(self, mock_storage_blob_upload_from_filename):
evaluation.utils.upload_evaluation_results(
_TEST_CSV, _TEST_BUCKET, _TEST_FILE_NAME
)
assert mock_storage_blob_upload_from_filename.called_once_with(_TEST_CSV)
|