azure-ai-evaluation 1.0.0b3__py3-none-any.whl → 1.0.0b5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of azure-ai-evaluation might be problematic. Click here for more details.

Files changed (93) hide show
  1. azure/ai/evaluation/__init__.py +23 -1
  2. azure/ai/evaluation/{simulator/_helpers → _common}/_experimental.py +20 -9
  3. azure/ai/evaluation/_common/constants.py +9 -2
  4. azure/ai/evaluation/_common/math.py +29 -0
  5. azure/ai/evaluation/_common/rai_service.py +222 -93
  6. azure/ai/evaluation/_common/utils.py +328 -19
  7. azure/ai/evaluation/_constants.py +16 -8
  8. azure/ai/evaluation/_evaluate/{_batch_run_client → _batch_run}/__init__.py +3 -2
  9. azure/ai/evaluation/_evaluate/{_batch_run_client → _batch_run}/code_client.py +33 -17
  10. azure/ai/evaluation/_evaluate/{_batch_run_client/batch_run_context.py → _batch_run/eval_run_context.py} +14 -7
  11. azure/ai/evaluation/_evaluate/{_batch_run_client → _batch_run}/proxy_client.py +22 -4
  12. azure/ai/evaluation/_evaluate/_batch_run/target_run_context.py +35 -0
  13. azure/ai/evaluation/_evaluate/_eval_run.py +47 -14
  14. azure/ai/evaluation/_evaluate/_evaluate.py +370 -188
  15. azure/ai/evaluation/_evaluate/_telemetry/__init__.py +15 -16
  16. azure/ai/evaluation/_evaluate/_utils.py +77 -25
  17. azure/ai/evaluation/_evaluators/_bleu/_bleu.py +1 -1
  18. azure/ai/evaluation/_evaluators/_coherence/_coherence.py +16 -10
  19. azure/ai/evaluation/_evaluators/_coherence/coherence.prompty +76 -34
  20. azure/ai/evaluation/_evaluators/_common/_base_eval.py +76 -46
  21. azure/ai/evaluation/_evaluators/_common/_base_prompty_eval.py +26 -19
  22. azure/ai/evaluation/_evaluators/_common/_base_rai_svc_eval.py +62 -25
  23. azure/ai/evaluation/_evaluators/_content_safety/_content_safety.py +68 -36
  24. azure/ai/evaluation/_evaluators/_content_safety/_content_safety_chat.py +67 -46
  25. azure/ai/evaluation/_evaluators/_content_safety/_hate_unfairness.py +33 -4
  26. azure/ai/evaluation/_evaluators/_content_safety/_self_harm.py +33 -4
  27. azure/ai/evaluation/_evaluators/_content_safety/_sexual.py +33 -4
  28. azure/ai/evaluation/_evaluators/_content_safety/_violence.py +33 -4
  29. azure/ai/evaluation/_evaluators/_eci/_eci.py +7 -5
  30. azure/ai/evaluation/_evaluators/_f1_score/_f1_score.py +14 -6
  31. azure/ai/evaluation/_evaluators/_fluency/_fluency.py +22 -21
  32. azure/ai/evaluation/_evaluators/_fluency/fluency.prompty +66 -36
  33. azure/ai/evaluation/_evaluators/_gleu/_gleu.py +1 -1
  34. azure/ai/evaluation/_evaluators/_groundedness/_groundedness.py +51 -16
  35. azure/ai/evaluation/_evaluators/_groundedness/groundedness_with_query.prompty +113 -0
  36. azure/ai/evaluation/_evaluators/_groundedness/groundedness_without_query.prompty +99 -0
  37. azure/ai/evaluation/_evaluators/_meteor/_meteor.py +3 -7
  38. azure/ai/evaluation/_evaluators/_multimodal/__init__.py +20 -0
  39. azure/ai/evaluation/_evaluators/_multimodal/_content_safety_multimodal.py +130 -0
  40. azure/ai/evaluation/_evaluators/_multimodal/_content_safety_multimodal_base.py +57 -0
  41. azure/ai/evaluation/_evaluators/_multimodal/_hate_unfairness.py +96 -0
  42. azure/ai/evaluation/_evaluators/_multimodal/_protected_material.py +120 -0
  43. azure/ai/evaluation/_evaluators/_multimodal/_self_harm.py +96 -0
  44. azure/ai/evaluation/_evaluators/_multimodal/_sexual.py +96 -0
  45. azure/ai/evaluation/_evaluators/_multimodal/_violence.py +96 -0
  46. azure/ai/evaluation/_evaluators/_protected_material/_protected_material.py +46 -13
  47. azure/ai/evaluation/_evaluators/_qa/_qa.py +11 -6
  48. azure/ai/evaluation/_evaluators/_relevance/_relevance.py +23 -20
  49. azure/ai/evaluation/_evaluators/_relevance/relevance.prompty +78 -42
  50. azure/ai/evaluation/_evaluators/_retrieval/_retrieval.py +126 -80
  51. azure/ai/evaluation/_evaluators/_retrieval/retrieval.prompty +74 -24
  52. azure/ai/evaluation/_evaluators/_rouge/_rouge.py +2 -2
  53. azure/ai/evaluation/_evaluators/_service_groundedness/__init__.py +9 -0
  54. azure/ai/evaluation/_evaluators/_service_groundedness/_service_groundedness.py +150 -0
  55. azure/ai/evaluation/_evaluators/_similarity/_similarity.py +32 -15
  56. azure/ai/evaluation/_evaluators/_xpia/xpia.py +36 -10
  57. azure/ai/evaluation/_exceptions.py +26 -6
  58. azure/ai/evaluation/_http_utils.py +203 -132
  59. azure/ai/evaluation/_model_configurations.py +23 -6
  60. azure/ai/evaluation/_vendor/__init__.py +3 -0
  61. azure/ai/evaluation/_vendor/rouge_score/__init__.py +14 -0
  62. azure/ai/evaluation/_vendor/rouge_score/rouge_scorer.py +328 -0
  63. azure/ai/evaluation/_vendor/rouge_score/scoring.py +63 -0
  64. azure/ai/evaluation/_vendor/rouge_score/tokenize.py +63 -0
  65. azure/ai/evaluation/_vendor/rouge_score/tokenizers.py +53 -0
  66. azure/ai/evaluation/_version.py +1 -1
  67. azure/ai/evaluation/simulator/__init__.py +2 -1
  68. azure/ai/evaluation/simulator/_adversarial_scenario.py +5 -0
  69. azure/ai/evaluation/simulator/_adversarial_simulator.py +88 -60
  70. azure/ai/evaluation/simulator/_conversation/__init__.py +13 -12
  71. azure/ai/evaluation/simulator/_conversation/_conversation.py +4 -4
  72. azure/ai/evaluation/simulator/_data_sources/__init__.py +3 -0
  73. azure/ai/evaluation/simulator/_data_sources/grounding.json +1150 -0
  74. azure/ai/evaluation/simulator/_direct_attack_simulator.py +24 -66
  75. azure/ai/evaluation/simulator/_helpers/__init__.py +1 -2
  76. azure/ai/evaluation/simulator/_helpers/_simulator_data_classes.py +26 -5
  77. azure/ai/evaluation/simulator/_indirect_attack_simulator.py +98 -95
  78. azure/ai/evaluation/simulator/_model_tools/_identity_manager.py +67 -21
  79. azure/ai/evaluation/simulator/_model_tools/_proxy_completion_model.py +28 -11
  80. azure/ai/evaluation/simulator/_model_tools/_template_handler.py +68 -24
  81. azure/ai/evaluation/simulator/_model_tools/models.py +10 -10
  82. azure/ai/evaluation/simulator/_prompty/task_query_response.prompty +4 -9
  83. azure/ai/evaluation/simulator/_prompty/task_simulate.prompty +6 -5
  84. azure/ai/evaluation/simulator/_simulator.py +222 -169
  85. azure/ai/evaluation/simulator/_tracing.py +4 -4
  86. azure/ai/evaluation/simulator/_utils.py +6 -6
  87. {azure_ai_evaluation-1.0.0b3.dist-info → azure_ai_evaluation-1.0.0b5.dist-info}/METADATA +237 -52
  88. azure_ai_evaluation-1.0.0b5.dist-info/NOTICE.txt +70 -0
  89. azure_ai_evaluation-1.0.0b5.dist-info/RECORD +120 -0
  90. {azure_ai_evaluation-1.0.0b3.dist-info → azure_ai_evaluation-1.0.0b5.dist-info}/WHEEL +1 -1
  91. azure/ai/evaluation/_evaluators/_groundedness/groundedness.prompty +0 -49
  92. azure_ai_evaluation-1.0.0b3.dist-info/RECORD +0 -98
  93. {azure_ai_evaluation-1.0.0b3.dist-info → azure_ai_evaluation-1.0.0b5.dist-info}/top_level.txt +0 -0
@@ -3,6 +3,7 @@
3
3
  # ---------------------------------------------------------
4
4
 
5
5
  from concurrent.futures import as_completed
6
+ from typing import Callable, Dict, List
6
7
 
7
8
  from promptflow.tracing import ThreadPoolExecutorWithContext as ThreadPoolExecutor
8
9
 
@@ -21,8 +22,7 @@ class QAEvaluator:
21
22
  :param model_config: Configuration for the Azure OpenAI model.
22
23
  :type model_config: Union[~azure.ai.evaluation.AzureOpenAIModelConfiguration,
23
24
  ~azure.ai.evaluation.OpenAIModelConfiguration]
24
- :return: A function that evaluates and generates metrics for "question-answering" scenario.
25
- :rtype: Callable
25
+ :return: A callable class that evaluates and generates metrics for "question-answering" scenario.
26
26
 
27
27
  **Usage**
28
28
 
@@ -41,6 +41,11 @@ class QAEvaluator:
41
41
  .. code-block:: python
42
42
 
43
43
  {
44
+ "groundedness": 3.5,
45
+ "relevance": 4.0,
46
+ "coherence": 1.5,
47
+ "fluency": 4.0,
48
+ "similarity": 3.0,
44
49
  "gpt_groundedness": 3.5,
45
50
  "gpt_relevance": 4.0,
46
51
  "gpt_coherence": 1.5,
@@ -50,10 +55,10 @@ class QAEvaluator:
50
55
  }
51
56
  """
52
57
 
53
- def __init__(self, model_config: dict, parallel: bool = True):
58
+ def __init__(self, model_config, parallel: bool = True):
54
59
  self._parallel = parallel
55
60
 
56
- self._evaluators = [
61
+ self._evaluators: List[Callable[..., Dict[str, float]]] = [
57
62
  GroundednessEvaluator(model_config),
58
63
  RelevanceEvaluator(model_config),
59
64
  CoherenceEvaluator(model_config),
@@ -77,9 +82,9 @@ class QAEvaluator:
77
82
  :keyword parallel: Whether to evaluate in parallel. Defaults to True.
78
83
  :paramtype parallel: bool
79
84
  :return: The scores for QA scenario.
80
- :rtype: dict
85
+ :rtype: Dict[str, float]
81
86
  """
82
- results = {}
87
+ results: Dict[str, float] = {}
83
88
  if self._parallel:
84
89
  with ThreadPoolExecutor() as executor:
85
90
  futures = {
@@ -4,6 +4,7 @@
4
4
 
5
5
  import os
6
6
  from typing import Optional
7
+
7
8
  from typing_extensions import override
8
9
 
9
10
  from azure.ai.evaluation._evaluators._common import PromptyEvaluatorBase
@@ -24,28 +25,32 @@ class RelevanceEvaluator(PromptyEvaluatorBase):
24
25
  eval_fn = RelevanceEvaluator(model_config)
25
26
  result = eval_fn(
26
27
  query="What is the capital of Japan?",
27
- response="The capital of Japan is Tokyo.",
28
- context="Tokyo is Japan's capital, known for its blend of traditional culture \
29
- and technological advancements.")
28
+ response="The capital of Japan is Tokyo.")
30
29
 
31
30
  **Output format**
32
31
 
33
32
  .. code-block:: python
34
33
 
35
34
  {
36
- "gpt_relevance": 3.0
35
+ "relevance": 3.0,
36
+ "gpt_relevance": 3.0,
37
+ "relevance_reason": "The response is relevant to the query because it provides the correct answer.",
37
38
  }
39
+
40
+ Note: To align with our support of a diverse set of models, a key without the `gpt_` prefix has been added.
41
+ To maintain backwards compatibility, the old key with the `gpt_` prefix is still be present in the output;
42
+ however, it is recommended to use the new key moving forward as the old key will be deprecated in the future.
38
43
  """
39
44
 
40
45
  # Constants must be defined within eval's directory to be save/loadable
41
- PROMPTY_FILE = "relevance.prompty"
42
- RESULT_KEY = "gpt_relevance"
46
+ _PROMPTY_FILE = "relevance.prompty"
47
+ _RESULT_KEY = "relevance"
43
48
 
44
49
  @override
45
- def __init__(self, model_config: dict):
50
+ def __init__(self, model_config):
46
51
  current_dir = os.path.dirname(__file__)
47
- prompty_path = os.path.join(current_dir, self.PROMPTY_FILE)
48
- super().__init__(model_config=model_config, prompty_file=prompty_path, result_key=self.RESULT_KEY)
52
+ prompty_path = os.path.join(current_dir, self._PROMPTY_FILE)
53
+ super().__init__(model_config=model_config, prompty_file=prompty_path, result_key=self._RESULT_KEY)
49
54
 
50
55
  @override
51
56
  def __call__(
@@ -53,25 +58,23 @@ class RelevanceEvaluator(PromptyEvaluatorBase):
53
58
  *,
54
59
  query: Optional[str] = None,
55
60
  response: Optional[str] = None,
56
- context: Optional[str] = None,
57
- conversation: Optional[dict] = None,
58
- **kwargs
61
+ conversation=None,
62
+ **kwargs,
59
63
  ):
60
- """Evaluate relevance. Accepts either a response and context a single evaluation,
64
+ """Evaluate relevance. Accepts either a query and response for a single evaluation,
61
65
  or a conversation for a multi-turn evaluation. If the conversation has more than one turn,
62
66
  the evaluator will aggregate the results of each turn.
63
67
 
64
- :keyword query: The query to be evaluated.
68
+ :keyword query: The query to be evaluated. Mutually exclusive with the `conversation` parameter.
65
69
  :paramtype query: Optional[str]
66
- :keyword response: The response to be evaluated.
70
+ :keyword response: The response to be evaluated. Mutually exclusive with the `conversation` parameter.
67
71
  :paramtype response: Optional[str]
68
- :keyword context: The context to be evaluated.
69
- :paramtype context: Optional[str]
70
72
  :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
71
73
  key "messages", and potentially a global context under the key "context". Conversation turns are expected
72
74
  to be dictionaries with keys "content", "role", and possibly "context".
73
- :paramtype conversation: Optional[Dict]
75
+ :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
74
76
  :return: The relevance score.
75
- :rtype: dict
77
+ :rtype: Union[Dict[str, float], Dict[str, Union[float, Dict[str, List[float]]]]]
76
78
  """
77
- return super().__call__(query=query, response=response, context=context, conversation=conversation, **kwargs)
79
+
80
+ return super().__call__(query=query, response=response, conversation=conversation, **kwargs)
@@ -5,7 +5,7 @@ model:
5
5
  api: chat
6
6
  parameters:
7
7
  temperature: 0.0
8
- max_tokens: 1
8
+ max_tokens: 800
9
9
  top_p: 1.0
10
10
  presence_penalty: 0
11
11
  frequency_penalty: 0
@@ -17,48 +17,84 @@ inputs:
17
17
  type: string
18
18
  response:
19
19
  type: string
20
- context:
21
- type: string
22
20
 
23
21
  ---
24
22
  system:
25
- You are an AI assistant. You will be given the definition of an evaluation metric for assessing the quality of an answer in a question-answering task. Your job is to compute an accurate evaluation score using the provided evaluation metric. You should return a single integer value between 1 to 5 representing the evaluation metric. You will include no other text or information.
23
+ # Instruction
24
+ ## Goal
25
+ ### You are an expert in evaluating the quality of a RESPONSE from an intelligent system based on provided definition and data. Your goal will involve answering the questions below using the information provided.
26
+ - **Definition**: You are given a definition of the communication trait that is being evaluated to help guide your Score.
27
+ - **Data**: Your input data include QUERY and RESPONSE.
28
+ - **Tasks**: To complete your evaluation you will be asked to evaluate the Data in different ways.
29
+
26
30
  user:
27
- Relevance measures how well the answer addresses the main aspects of the question, based on the context. Consider whether all and only the important aspects are contained in the answer when evaluating relevance. Given the context and question, score the relevance of the answer between one to five stars using the following rating scale:
28
- One star: the answer completely lacks relevance
29
- Two stars: the answer mostly lacks relevance
30
- Three stars: the answer is partially relevant
31
- Four stars: the answer is mostly relevant
32
- Five stars: the answer has perfect relevance
33
-
34
- This rating value should always be an integer between 1 and 5. So the rating produced should be 1 or 2 or 3 or 4 or 5.
35
-
36
- context: Marie Curie was a Polish-born physicist and chemist who pioneered research on radioactivity and was the first woman to win a Nobel Prize.
37
- question: What field did Marie Curie excel in?
38
- answer: Marie Curie was a renowned painter who focused mainly on impressionist styles and techniques.
39
- stars: 1
40
-
41
- context: The Beatles were an English rock band formed in Liverpool in 1960, and they are widely regarded as the most influential music band in history.
42
- question: Where were The Beatles formed?
43
- answer: The band The Beatles began their journey in London, England, and they changed the history of music.
44
- stars: 2
45
-
46
- context: The recent Mars rover, Perseverance, was launched in 2020 with the main goal of searching for signs of ancient life on Mars. The rover also carries an experiment called MOXIE, which aims to generate oxygen from the Martian atmosphere.
47
- question: What are the main goals of Perseverance Mars rover mission?
48
- answer: The Perseverance Mars rover mission focuses on searching for signs of ancient life on Mars.
49
- stars: 3
50
-
51
- context: The Mediterranean diet is a commonly recommended dietary plan that emphasizes fruits, vegetables, whole grains, legumes, lean proteins, and healthy fats. Studies have shown that it offers numerous health benefits, including a reduced risk of heart disease and improved cognitive health.
52
- question: What are the main components of the Mediterranean diet?
53
- answer: The Mediterranean diet primarily consists of fruits, vegetables, whole grains, and legumes.
54
- stars: 4
55
-
56
- context: The Queen's Royal Castle is a well-known tourist attraction in the United Kingdom. It spans over 500 acres and contains extensive gardens and parks. The castle was built in the 15th century and has been home to generations of royalty.
57
- question: What are the main attractions of the Queen's Royal Castle?
58
- answer: The main attractions of the Queen's Royal Castle are its expansive 500-acre grounds, extensive gardens, parks, and the historical castle itself, which dates back to the 15th century and has housed generations of royalty.
59
- stars: 5
60
-
61
- context: {{context}}
62
- question: {{query}}
63
- answer: {{response}}
64
- stars:
31
+ # Definition
32
+ **Relevance** refers to how effectively a response addresses a question. It assesses the accuracy, completeness, and direct relevance of the response based solely on the given information.
33
+
34
+ # Ratings
35
+ ## [Relevance: 1] (Irrelevant Response)
36
+ **Definition:** The response is unrelated to the question. It provides information that is off-topic and does not attempt to address the question posed.
37
+
38
+ **Examples:**
39
+ **Query:** What is the team preparing for?
40
+ **Response:** I went grocery shopping yesterday evening.
41
+
42
+ **Query:** When will the company's new product line launch?
43
+ **Response:** International travel can be very rewarding and educational.
44
+
45
+ ## [Relevance: 2] (Incorrect Response)
46
+ **Definition:** The response attempts to address the question but includes incorrect information. It provides a response that is factually wrong based on the provided information.
47
+
48
+ **Examples:**
49
+ **Query:** When was the merger between the two firms finalized?
50
+ **Response:** The merger was finalized on April 10th.
51
+
52
+ **Query:** Where and when will the solar eclipse be visible?
53
+ **Response:** The solar eclipse will be visible in Asia on December 14th.
54
+
55
+ ## [Relevance: 3] (Incomplete Response)
56
+ **Definition:** The response addresses the question but omits key details necessary for a full understanding. It provides a partial response that lacks essential information.
57
+
58
+ **Examples:**
59
+ **Query:** What type of food does the new restaurant offer?
60
+ **Response:** The restaurant offers Italian food like pasta.
61
+
62
+ **Query:** What topics will the conference cover?
63
+ **Response:** The conference will cover renewable energy and climate change.
64
+
65
+ ## [Relevance: 4] (Complete Response)
66
+ **Definition:** The response fully addresses the question with accurate and complete information. It includes all essential details required for a comprehensive understanding, without adding any extraneous information.
67
+
68
+ **Examples:**
69
+ **Query:** What type of food does the new restaurant offer?
70
+ **Response:** The new restaurant offers Italian cuisine, featuring dishes like pasta, pizza, and risotto.
71
+
72
+ **Query:** What topics will the conference cover?
73
+ **Response:** The conference will cover renewable energy, climate change, and sustainability practices.
74
+
75
+ ## [Relevance: 5] (Comprehensive Response with Insights)
76
+ **Definition:** The response not only fully and accurately addresses the question but also includes additional relevant insights or elaboration. It may explain the significance, implications, or provide minor inferences that enhance understanding.
77
+
78
+ **Examples:**
79
+ **Query:** What type of food does the new restaurant offer?
80
+ **Response:** The new restaurant offers Italian cuisine, featuring dishes like pasta, pizza, and risotto, aiming to provide customers with an authentic Italian dining experience.
81
+
82
+ **Query:** What topics will the conference cover?
83
+ **Response:** The conference will cover renewable energy, climate change, and sustainability practices, bringing together global experts to discuss these critical issues.
84
+
85
+
86
+
87
+ # Data
88
+ QUERY: {{query}}
89
+ RESPONSE: {{response}}
90
+
91
+
92
+ # Tasks
93
+ ## Please provide your assessment Score for the previous RESPONSE in relation to the QUERY based on the Definitions above. Your output should include the following information:
94
+ - **ThoughtChain**: To improve the reasoning process, think step by step and include a step-by-step explanation of your thought process as you analyze the data based on the definitions. Keep it brief and start your ThoughtChain with "Let's think step by step:".
95
+ - **Explanation**: a very short explanation of why you think the input Data should get that Score.
96
+ - **Score**: based on your previous analysis, provide your Score. The Score you give MUST be a integer score (i.e., "1", "2"...) based on the levels of the definitions.
97
+
98
+
99
+ ## Please provide your answers between the tags: <S0>your chain of thoughts</S0>, <S1>your explanation</S1>, <S2>your Score</S2>.
100
+ # Output
@@ -4,93 +4,106 @@
4
4
 
5
5
  import json
6
6
  import logging
7
+ import math
7
8
  import os
8
- import re
9
+ from typing import Optional
9
10
 
10
- import numpy as np
11
11
  from promptflow._utils.async_utils import async_run_allowing_running_loop
12
12
  from promptflow.core import AsyncPrompty
13
13
 
14
-
15
- from ..._common.utils import construct_prompty_model_config
14
+ from azure.ai.evaluation._exceptions import EvaluationException, ErrorBlame, ErrorCategory, ErrorTarget
15
+ from ..._common.math import list_mean_nan_safe
16
+ from ..._common.utils import construct_prompty_model_config, validate_model_config, parse_quality_evaluator_reason_score
16
17
 
17
18
  logger = logging.getLogger(__name__)
18
19
 
19
20
  try:
20
21
  from .._user_agent import USER_AGENT
21
22
  except ImportError:
22
- USER_AGENT = None
23
+ USER_AGENT = "None"
23
24
 
24
25
 
25
26
  class _AsyncRetrievalScoreEvaluator:
26
27
  # Constants must be defined within eval's directory to be save/loadable
27
- PROMPTY_FILE = "retrieval.prompty"
28
- LLM_CALL_TIMEOUT = 600
29
- DEFAULT_OPEN_API_VERSION = "2024-02-15-preview"
28
+ _PROMPTY_FILE = "retrieval.prompty"
29
+ _LLM_CALL_TIMEOUT = 600
30
+ _DEFAULT_OPEN_API_VERSION = "2024-02-15-preview"
30
31
 
31
32
  def __init__(self, model_config: dict):
32
33
  prompty_model_config = construct_prompty_model_config(
33
- model_config,
34
- self.DEFAULT_OPEN_API_VERSION,
34
+ validate_model_config(model_config),
35
+ self._DEFAULT_OPEN_API_VERSION,
35
36
  USER_AGENT,
36
37
  )
37
38
 
38
39
  current_dir = os.path.dirname(__file__)
39
- prompty_path = os.path.join(current_dir, self.PROMPTY_FILE)
40
+ prompty_path = os.path.join(current_dir, self._PROMPTY_FILE)
40
41
  self._flow = AsyncPrompty.load(source=prompty_path, model=prompty_model_config)
41
42
 
42
- async def __call__(self, *, conversation, **kwargs):
43
- # Extract queries, responses and contexts from conversation
44
- queries = []
45
- responses = []
46
- contexts = []
47
-
48
- for each_turn in conversation:
49
- role = each_turn["role"]
50
- if role == "user":
51
- queries.append(each_turn["content"])
52
- elif role == "assistant":
53
- responses.append(each_turn["content"])
54
- if "context" in each_turn and "citations" in each_turn["context"]:
55
- citations = json.dumps(each_turn["context"]["citations"])
56
- contexts.append(citations)
57
-
58
- # Evaluate each turn
59
- per_turn_scores = []
60
- history = []
61
- for turn_num, query in enumerate(queries):
62
- try:
63
- query = query if turn_num < len(queries) else ""
64
- answer = responses[turn_num] if turn_num < len(responses) else ""
65
- context = contexts[turn_num] if turn_num < len(contexts) else ""
66
-
67
- history.append({"user": query, "assistant": answer})
68
-
69
- llm_output = await self._flow(
70
- query=query, history=history, documents=context, timeout=self.LLM_CALL_TIMEOUT, **kwargs
71
- )
72
- score = np.nan
73
- if llm_output:
74
- parsed_score_response = re.findall(r"\d+", llm_output.split("# Result")[-1].strip())
75
- if len(parsed_score_response) > 0:
76
- score = float(parsed_score_response[0].replace("'", "").strip())
77
-
78
- per_turn_scores.append(score)
79
-
80
- except Exception as e: # pylint: disable=broad-exception-caught
81
- logger.warning(
82
- "Evaluator %s failed for turn %s with exception: %s", self.__class__.__name__, turn_num + 1, e
83
- )
84
-
85
- per_turn_scores.append(np.nan)
43
+ async def __call__(self, *, query, context, conversation, **kwargs):
44
+ if conversation:
45
+ # Extract queries, responses and contexts from conversation
46
+ queries = []
47
+ responses = []
48
+ contexts = []
49
+
50
+ conversation = conversation.get("messages", None)
51
+
52
+ for each_turn in conversation:
53
+ role = each_turn["role"]
54
+ if role == "user":
55
+ queries.append(each_turn["content"])
56
+ elif role == "assistant":
57
+ responses.append(each_turn["content"])
58
+ if "context" in each_turn:
59
+ if "citations" in each_turn["context"]:
60
+ citations = json.dumps(each_turn["context"]["citations"])
61
+ contexts.append(citations)
62
+ elif isinstance(each_turn["context"], str):
63
+ contexts.append(each_turn["context"])
64
+
65
+ # Evaluate each turn
66
+ per_turn_scores = []
67
+ per_turn_reasons = []
68
+ for turn_num, turn_query in enumerate(queries):
69
+ try:
70
+ if turn_num >= len(queries):
71
+ turn_query = ""
72
+ context = contexts[turn_num] if turn_num < len(contexts) else ""
73
+
74
+ llm_output = await self._flow(
75
+ query=turn_query, context=context, timeout=self._LLM_CALL_TIMEOUT, **kwargs
76
+ )
77
+ score, reason = parse_quality_evaluator_reason_score(llm_output)
78
+ per_turn_scores.append(score)
79
+ per_turn_reasons.append(reason)
80
+
81
+ except Exception as e: # pylint: disable=broad-exception-caught
82
+ logger.warning(
83
+ "Evaluator %s failed for turn %s with exception: %s", self.__class__.__name__, turn_num + 1, e
84
+ )
85
+
86
+ per_turn_scores.append(math.nan)
87
+ per_turn_reasons.append("")
88
+
89
+ mean_per_turn_score = list_mean_nan_safe(per_turn_scores)
90
+
91
+ return {
92
+ "retrieval": mean_per_turn_score,
93
+ "gpt_retrieval": mean_per_turn_score,
94
+ "evaluation_per_turn": {
95
+ "gpt_retrieval": per_turn_scores,
96
+ "retrieval": per_turn_scores,
97
+ "retrieval_reason": per_turn_reasons,
98
+ },
99
+ }
100
+ llm_output = await self._flow(query=query, context=context, timeout=self._LLM_CALL_TIMEOUT, **kwargs)
101
+ score, reason = parse_quality_evaluator_reason_score(llm_output)
86
102
 
87
103
  return {
88
- "gpt_retrieval": np.nanmean(per_turn_scores),
89
- "evaluation_per_turn": {
90
- "gpt_retrieval": {
91
- "score": per_turn_scores,
92
- }
93
- },
104
+ "retrieval": score,
105
+ "retrieval_reason": reason,
106
+ "gpt_retrieval": score,
94
107
  }
95
108
 
96
109
 
@@ -108,16 +121,16 @@ class RetrievalEvaluator:
108
121
 
109
122
  .. code-block:: python
110
123
 
111
- chat_eval = RetrievalScoreEvaluator(model_config)
112
- conversation = [
113
- {"role": "user", "content": "What is the value of 2 + 2?"},
114
- {"role": "assistant", "content": "2 + 2 = 4", "context": {
115
- "citations": [
116
- {"id": "math_doc.md", "content": "Information about additions: 1 + 2 = 3, 2 + 2 = 4"}
117
- ]
124
+ chat_eval = RetrievalEvaluator(model_config)
125
+ conversation = {
126
+ "messages": [
127
+ {"role": "user", "content": "What is the value of 2 + 2?"},
128
+ {
129
+ "role": "assistant", "content": "2 + 2 = 4",
130
+ "context": "From 'math_doc.md': Information about additions: 1 + 2 = 3, 2 + 2 = 4"
118
131
  }
119
- }
120
- ]
132
+ ]
133
+ }
121
134
  result = chat_eval(conversation=conversation)
122
135
 
123
136
  **Output format**
@@ -125,27 +138,60 @@ class RetrievalEvaluator:
125
138
  .. code-block:: python
126
139
 
127
140
  {
128
- "gpt_retrieval": 3.0
141
+ "gpt_retrieval": 3.0,
142
+ "retrieval": 3.0,
129
143
  "evaluation_per_turn": {
130
- "gpt_retrieval": {
131
- "score": [1.0, 2.0, 3.0]
132
- }
144
+ "gpt_retrieval": [1.0, 2.0, 3.0],
145
+ "retrieval": [1.0, 2.0, 3.0],
146
+ "retrieval_reason": ["<reasoning for score 1>", "<reasoning for score 2>", "<reasoning for score 3>"]
133
147
  }
134
148
  }
149
+
150
+ Note: To align with our support of a diverse set of models, a key without the `gpt_` prefix has been added.
151
+ To maintain backwards compatibility, the old key with the `gpt_` prefix is still be present in the output;
152
+ however, it is recommended to use the new key moving forward as the old key will be deprecated in the future.
135
153
  """
136
154
 
137
- def __init__(self, model_config: dict):
155
+ def __init__(self, model_config):
138
156
  self._async_evaluator = _AsyncRetrievalScoreEvaluator(model_config)
139
157
 
140
- def __call__(self, *, conversation, **kwargs):
141
- """Evaluates retrieval score chat scenario.
158
+ def __call__(self, *, query: Optional[str] = None, context: Optional[str] = None, conversation=None, **kwargs):
159
+ """Evaluates retrieval score chat scenario. Accepts either a query and context for a single evaluation,
160
+ or a conversation for a multi-turn evaluation. If the conversation has more than one turn,
161
+ the evaluator will aggregate the results of each turn.
142
162
 
163
+ :keyword query: The query to be evaluated. Mutually exclusive with `conversation` parameter.
164
+ :paramtype query: Optional[str]
165
+ :keyword context: The context to be evaluated. Mutually exclusive with `conversation` parameter.
166
+ :paramtype context: Optional[str]
143
167
  :keyword conversation: The conversation to be evaluated.
144
- :paramtype conversation: List[Dict]
168
+ :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
145
169
  :return: The scores for Chat scenario.
146
- :rtype: dict
170
+ :rtype: :rtype: Dict[str, Union[float, Dict[str, List[float]]]]
147
171
  """
148
- return async_run_allowing_running_loop(self._async_evaluator, conversation=conversation, **kwargs)
172
+ if (query is None or context is None) and conversation is None:
173
+ msg = "Either a pair of 'query'/'context' or 'conversation' must be provided."
174
+ raise EvaluationException(
175
+ message=msg,
176
+ internal_message=msg,
177
+ blame=ErrorBlame.USER_ERROR,
178
+ category=ErrorCategory.MISSING_FIELD,
179
+ target=ErrorTarget.RETRIEVAL_EVALUATOR,
180
+ )
181
+
182
+ if (query or context) and conversation:
183
+ msg = "Either a pair of 'query'/'context' or 'conversation' must be provided, but not both."
184
+ raise EvaluationException(
185
+ message=msg,
186
+ internal_message=msg,
187
+ blame=ErrorBlame.USER_ERROR,
188
+ category=ErrorCategory.INVALID_VALUE,
189
+ target=ErrorTarget.RETRIEVAL_EVALUATOR,
190
+ )
191
+
192
+ return async_run_allowing_running_loop(
193
+ self._async_evaluator, query=query, context=context, conversation=conversation, **kwargs
194
+ )
149
195
 
150
196
  def _to_async(self):
151
197
  return self._async_evaluator