azure-ai-evaluation 0.0.0b0__py3-none-any.whl → 1.0.0__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.
Files changed (122) hide show
  1. azure/ai/evaluation/__init__.py +82 -0
  2. azure/ai/evaluation/_common/__init__.py +16 -0
  3. azure/ai/evaluation/_common/_experimental.py +172 -0
  4. azure/ai/evaluation/_common/constants.py +72 -0
  5. azure/ai/evaluation/_common/math.py +89 -0
  6. azure/ai/evaluation/_common/rai_service.py +632 -0
  7. azure/ai/evaluation/_common/utils.py +445 -0
  8. azure/ai/evaluation/_constants.py +72 -0
  9. azure/ai/evaluation/_evaluate/__init__.py +3 -0
  10. azure/ai/evaluation/_evaluate/_batch_run/__init__.py +9 -0
  11. azure/ai/evaluation/_evaluate/_batch_run/code_client.py +188 -0
  12. azure/ai/evaluation/_evaluate/_batch_run/eval_run_context.py +89 -0
  13. azure/ai/evaluation/_evaluate/_batch_run/proxy_client.py +99 -0
  14. azure/ai/evaluation/_evaluate/_batch_run/target_run_context.py +46 -0
  15. azure/ai/evaluation/_evaluate/_eval_run.py +571 -0
  16. azure/ai/evaluation/_evaluate/_evaluate.py +850 -0
  17. azure/ai/evaluation/_evaluate/_telemetry/__init__.py +179 -0
  18. azure/ai/evaluation/_evaluate/_utils.py +298 -0
  19. azure/ai/evaluation/_evaluators/__init__.py +3 -0
  20. azure/ai/evaluation/_evaluators/_bleu/__init__.py +9 -0
  21. azure/ai/evaluation/_evaluators/_bleu/_bleu.py +72 -0
  22. azure/ai/evaluation/_evaluators/_coherence/__init__.py +7 -0
  23. azure/ai/evaluation/_evaluators/_coherence/_coherence.py +107 -0
  24. azure/ai/evaluation/_evaluators/_coherence/coherence.prompty +99 -0
  25. azure/ai/evaluation/_evaluators/_common/__init__.py +13 -0
  26. azure/ai/evaluation/_evaluators/_common/_base_eval.py +344 -0
  27. azure/ai/evaluation/_evaluators/_common/_base_prompty_eval.py +88 -0
  28. azure/ai/evaluation/_evaluators/_common/_base_rai_svc_eval.py +133 -0
  29. azure/ai/evaluation/_evaluators/_content_safety/__init__.py +17 -0
  30. azure/ai/evaluation/_evaluators/_content_safety/_content_safety.py +144 -0
  31. azure/ai/evaluation/_evaluators/_content_safety/_hate_unfairness.py +129 -0
  32. azure/ai/evaluation/_evaluators/_content_safety/_self_harm.py +123 -0
  33. azure/ai/evaluation/_evaluators/_content_safety/_sexual.py +125 -0
  34. azure/ai/evaluation/_evaluators/_content_safety/_violence.py +126 -0
  35. azure/ai/evaluation/_evaluators/_eci/__init__.py +0 -0
  36. azure/ai/evaluation/_evaluators/_eci/_eci.py +89 -0
  37. azure/ai/evaluation/_evaluators/_f1_score/__init__.py +9 -0
  38. azure/ai/evaluation/_evaluators/_f1_score/_f1_score.py +157 -0
  39. azure/ai/evaluation/_evaluators/_fluency/__init__.py +9 -0
  40. azure/ai/evaluation/_evaluators/_fluency/_fluency.py +104 -0
  41. azure/ai/evaluation/_evaluators/_fluency/fluency.prompty +86 -0
  42. azure/ai/evaluation/_evaluators/_gleu/__init__.py +9 -0
  43. azure/ai/evaluation/_evaluators/_gleu/_gleu.py +69 -0
  44. azure/ai/evaluation/_evaluators/_groundedness/__init__.py +9 -0
  45. azure/ai/evaluation/_evaluators/_groundedness/_groundedness.py +144 -0
  46. azure/ai/evaluation/_evaluators/_groundedness/groundedness_with_query.prompty +113 -0
  47. azure/ai/evaluation/_evaluators/_groundedness/groundedness_without_query.prompty +99 -0
  48. azure/ai/evaluation/_evaluators/_meteor/__init__.py +9 -0
  49. azure/ai/evaluation/_evaluators/_meteor/_meteor.py +90 -0
  50. azure/ai/evaluation/_evaluators/_multimodal/__init__.py +20 -0
  51. azure/ai/evaluation/_evaluators/_multimodal/_content_safety_multimodal.py +132 -0
  52. azure/ai/evaluation/_evaluators/_multimodal/_content_safety_multimodal_base.py +55 -0
  53. azure/ai/evaluation/_evaluators/_multimodal/_hate_unfairness.py +100 -0
  54. azure/ai/evaluation/_evaluators/_multimodal/_protected_material.py +124 -0
  55. azure/ai/evaluation/_evaluators/_multimodal/_self_harm.py +100 -0
  56. azure/ai/evaluation/_evaluators/_multimodal/_sexual.py +100 -0
  57. azure/ai/evaluation/_evaluators/_multimodal/_violence.py +100 -0
  58. azure/ai/evaluation/_evaluators/_protected_material/__init__.py +5 -0
  59. azure/ai/evaluation/_evaluators/_protected_material/_protected_material.py +113 -0
  60. azure/ai/evaluation/_evaluators/_qa/__init__.py +9 -0
  61. azure/ai/evaluation/_evaluators/_qa/_qa.py +93 -0
  62. azure/ai/evaluation/_evaluators/_relevance/__init__.py +9 -0
  63. azure/ai/evaluation/_evaluators/_relevance/_relevance.py +114 -0
  64. azure/ai/evaluation/_evaluators/_relevance/relevance.prompty +100 -0
  65. azure/ai/evaluation/_evaluators/_retrieval/__init__.py +9 -0
  66. azure/ai/evaluation/_evaluators/_retrieval/_retrieval.py +112 -0
  67. azure/ai/evaluation/_evaluators/_retrieval/retrieval.prompty +93 -0
  68. azure/ai/evaluation/_evaluators/_rouge/__init__.py +10 -0
  69. azure/ai/evaluation/_evaluators/_rouge/_rouge.py +98 -0
  70. azure/ai/evaluation/_evaluators/_service_groundedness/__init__.py +9 -0
  71. azure/ai/evaluation/_evaluators/_service_groundedness/_service_groundedness.py +148 -0
  72. azure/ai/evaluation/_evaluators/_similarity/__init__.py +9 -0
  73. azure/ai/evaluation/_evaluators/_similarity/_similarity.py +140 -0
  74. azure/ai/evaluation/_evaluators/_similarity/similarity.prompty +66 -0
  75. azure/ai/evaluation/_evaluators/_xpia/__init__.py +5 -0
  76. azure/ai/evaluation/_evaluators/_xpia/xpia.py +125 -0
  77. azure/ai/evaluation/_exceptions.py +128 -0
  78. azure/ai/evaluation/_http_utils.py +466 -0
  79. azure/ai/evaluation/_model_configurations.py +123 -0
  80. azure/ai/evaluation/_user_agent.py +6 -0
  81. azure/ai/evaluation/_vendor/__init__.py +3 -0
  82. azure/ai/evaluation/_vendor/rouge_score/__init__.py +14 -0
  83. azure/ai/evaluation/_vendor/rouge_score/rouge_scorer.py +328 -0
  84. azure/ai/evaluation/_vendor/rouge_score/scoring.py +63 -0
  85. azure/ai/evaluation/_vendor/rouge_score/tokenize.py +63 -0
  86. azure/ai/evaluation/_vendor/rouge_score/tokenizers.py +53 -0
  87. azure/ai/evaluation/_version.py +5 -0
  88. azure/ai/evaluation/py.typed +0 -0
  89. azure/ai/evaluation/simulator/__init__.py +16 -0
  90. azure/ai/evaluation/simulator/_adversarial_scenario.py +46 -0
  91. azure/ai/evaluation/simulator/_adversarial_simulator.py +471 -0
  92. azure/ai/evaluation/simulator/_constants.py +27 -0
  93. azure/ai/evaluation/simulator/_conversation/__init__.py +316 -0
  94. azure/ai/evaluation/simulator/_conversation/_conversation.py +178 -0
  95. azure/ai/evaluation/simulator/_conversation/constants.py +30 -0
  96. azure/ai/evaluation/simulator/_data_sources/__init__.py +3 -0
  97. azure/ai/evaluation/simulator/_data_sources/grounding.json +1150 -0
  98. azure/ai/evaluation/simulator/_direct_attack_simulator.py +218 -0
  99. azure/ai/evaluation/simulator/_helpers/__init__.py +4 -0
  100. azure/ai/evaluation/simulator/_helpers/_language_suffix_mapping.py +17 -0
  101. azure/ai/evaluation/simulator/_helpers/_simulator_data_classes.py +96 -0
  102. azure/ai/evaluation/simulator/_indirect_attack_simulator.py +220 -0
  103. azure/ai/evaluation/simulator/_model_tools/__init__.py +23 -0
  104. azure/ai/evaluation/simulator/_model_tools/_identity_manager.py +195 -0
  105. azure/ai/evaluation/simulator/_model_tools/_proxy_completion_model.py +244 -0
  106. azure/ai/evaluation/simulator/_model_tools/_rai_client.py +168 -0
  107. azure/ai/evaluation/simulator/_model_tools/_template_handler.py +201 -0
  108. azure/ai/evaluation/simulator/_model_tools/models.py +614 -0
  109. azure/ai/evaluation/simulator/_prompty/__init__.py +0 -0
  110. azure/ai/evaluation/simulator/_prompty/task_query_response.prompty +65 -0
  111. azure/ai/evaluation/simulator/_prompty/task_simulate.prompty +37 -0
  112. azure/ai/evaluation/simulator/_simulator.py +716 -0
  113. azure/ai/evaluation/simulator/_tracing.py +89 -0
  114. azure/ai/evaluation/simulator/_utils.py +132 -0
  115. azure_ai_evaluation-1.0.0.dist-info/METADATA +595 -0
  116. azure_ai_evaluation-1.0.0.dist-info/NOTICE.txt +70 -0
  117. azure_ai_evaluation-1.0.0.dist-info/RECORD +119 -0
  118. {azure_ai_evaluation-0.0.0b0.dist-info → azure_ai_evaluation-1.0.0.dist-info}/WHEEL +1 -1
  119. azure_ai_evaluation-1.0.0.dist-info/top_level.txt +1 -0
  120. azure_ai_evaluation-0.0.0b0.dist-info/METADATA +0 -7
  121. azure_ai_evaluation-0.0.0b0.dist-info/RECORD +0 -4
  122. azure_ai_evaluation-0.0.0b0.dist-info/top_level.txt +0 -1
@@ -0,0 +1,144 @@
1
+ # ---------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # ---------------------------------------------------------
4
+ import os
5
+ from typing import Dict, List, Optional, Union
6
+
7
+ from typing_extensions import overload, override
8
+ from promptflow.core import AsyncPrompty
9
+
10
+ from azure.ai.evaluation._evaluators._common import PromptyEvaluatorBase
11
+ from azure.ai.evaluation._model_configurations import Conversation
12
+ from ..._common.utils import construct_prompty_model_config, validate_model_config
13
+
14
+ try:
15
+ from ..._user_agent import USER_AGENT
16
+ except ImportError:
17
+ USER_AGENT = "None"
18
+
19
+
20
+ class GroundednessEvaluator(PromptyEvaluatorBase[Union[str, float]]):
21
+ """
22
+ Evaluates groundedness score for a given query (optional), response, and context or a multi-turn conversation,
23
+ including reasoning.
24
+
25
+ The groundedness measure assesses the correspondence between claims in an AI-generated answer and the source
26
+ context, making sure that these claims are substantiated by the context. Even if the responses from LLM are
27
+ factually correct, they'll be considered ungrounded if they can't be verified against the provided sources
28
+ (such as your input source or your database). Use the groundedness metric when you need to verify that
29
+ AI-generated responses align with and are validated by the provided context.
30
+
31
+ Groundedness scores range from 1 to 5, with 1 being the least grounded and 5 being the most grounded.
32
+
33
+ :param model_config: Configuration for the Azure OpenAI model.
34
+ :type model_config: Union[~azure.ai.evaluation.AzureOpenAIModelConfiguration,
35
+ ~azure.ai.evaluation.OpenAIModelConfiguration]
36
+
37
+ .. admonition:: Example:
38
+
39
+ .. literalinclude:: ../samples/evaluation_samples_evaluate.py
40
+ :start-after: [START groundedness_evaluator]
41
+ :end-before: [END groundedness_evaluator]
42
+ :language: python
43
+ :dedent: 8
44
+ :caption: Initialize and call a GroundednessEvaluator.
45
+
46
+ .. note::
47
+
48
+ To align with our support of a diverse set of models, an output key without the `gpt_` prefix has been added.
49
+ To maintain backwards compatibility, the old key with the `gpt_` prefix is still be present in the output;
50
+ however, it is recommended to use the new key moving forward as the old key will be deprecated in the future.
51
+ """
52
+
53
+ _PROMPTY_FILE_NO_QUERY = "groundedness_without_query.prompty"
54
+ _PROMPTY_FILE_WITH_QUERY = "groundedness_with_query.prompty"
55
+ _RESULT_KEY = "groundedness"
56
+ _OPTIONAL_PARAMS = ["query"]
57
+
58
+ id = "azureml://registries/azureml/models/Groundedness-Evaluator/versions/4"
59
+ """Evaluator identifier, experimental and to be used only with evaluation in cloud."""
60
+
61
+ @override
62
+ def __init__(self, model_config):
63
+ current_dir = os.path.dirname(__file__)
64
+ prompty_path = os.path.join(current_dir, self._PROMPTY_FILE_NO_QUERY) # Default to no query
65
+
66
+ super().__init__(model_config=model_config, prompty_file=prompty_path, result_key=self._RESULT_KEY)
67
+ self._model_config = model_config
68
+ # Needs to be set because it's used in call method to re-validate prompt if `query` is provided
69
+
70
+ @overload
71
+ def __call__(
72
+ self,
73
+ *,
74
+ response: str,
75
+ context: str,
76
+ query: Optional[str] = None,
77
+ ) -> Dict[str, Union[str, float]]:
78
+ """Evaluate groundedness for given input of response, context
79
+
80
+ :keyword response: The response to be evaluated.
81
+ :paramtype response: str
82
+ :keyword context: The context to be evaluated.
83
+ :paramtype context: str
84
+ :keyword query: The query to be evaluated. Optional parameter for use with the `response`
85
+ and `context` parameters. If provided, a different prompt template will be used for evaluation.
86
+ :paramtype query: Optional[str]
87
+ :return: The groundedness score.
88
+ :rtype: Dict[str, float]
89
+ """
90
+
91
+ @overload
92
+ def __call__(
93
+ self,
94
+ *,
95
+ conversation: Conversation,
96
+ ) -> Dict[str, Union[float, Dict[str, List[Union[str, float]]]]]:
97
+ """Evaluate groundedness for a conversation
98
+
99
+ :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
100
+ key "messages", and potentially a global context under the key "context". Conversation turns are expected
101
+ to be dictionaries with keys "content", "role", and possibly "context".
102
+ :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
103
+ :return: The groundedness score.
104
+ :rtype: Dict[str, Union[float, Dict[str, List[float]]]]
105
+ """
106
+
107
+ @override
108
+ def __call__( # pylint: disable=docstring-missing-param
109
+ self,
110
+ *args,
111
+ **kwargs,
112
+ ):
113
+ """Evaluate groundedness. Accepts either a query, response, and context for a single evaluation,
114
+ or a conversation for a multi-turn evaluation. If the conversation has more than one turn,
115
+ the evaluator will aggregate the results of each turn.
116
+
117
+ :keyword query: The query to be evaluated. Mutually exclusive with `conversation`. Optional parameter for use
118
+ with the `response` and `context` parameters. If provided, a different prompt template will be used for
119
+ evaluation.
120
+ :paramtype query: Optional[str]
121
+ :keyword response: The response to be evaluated. Mutually exclusive with the `conversation` parameter.
122
+ :paramtype response: Optional[str]
123
+ :keyword context: The context to be evaluated. Mutually exclusive with the `conversation` parameter.
124
+ :paramtype context: Optional[str]
125
+ :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
126
+ key "messages", and potentially a global context under the key "context". Conversation turns are expected
127
+ to be dictionaries with keys "content", "role", and possibly "context".
128
+ :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
129
+ :return: The relevance score.
130
+ :rtype: Union[Dict[str, Union[str, float]], Dict[str, Union[float, Dict[str, List[Union[str, float]]]]]]
131
+ """
132
+
133
+ if kwargs.get("query", None):
134
+ current_dir = os.path.dirname(__file__)
135
+ prompty_path = os.path.join(current_dir, self._PROMPTY_FILE_WITH_QUERY)
136
+ self._prompty_file = prompty_path
137
+ prompty_model_config = construct_prompty_model_config(
138
+ validate_model_config(self._model_config),
139
+ self._DEFAULT_OPEN_API_VERSION,
140
+ USER_AGENT,
141
+ )
142
+ self._flow = AsyncPrompty.load(source=self._prompty_file, model=prompty_model_config)
143
+
144
+ return super().__call__(*args, **kwargs)
@@ -0,0 +1,113 @@
1
+ ---
2
+ name: Groundedness
3
+ description: Evaluates groundedness score for RAG scenario
4
+ model:
5
+ api: chat
6
+ parameters:
7
+ temperature: 0.0
8
+ max_tokens: 800
9
+ top_p: 1.0
10
+ presence_penalty: 0
11
+ frequency_penalty: 0
12
+ response_format:
13
+ type: text
14
+
15
+ inputs:
16
+ query:
17
+ type: string
18
+ response:
19
+ type: string
20
+ context:
21
+ type: string
22
+
23
+
24
+ ---
25
+ system:
26
+ # Instruction
27
+ ## Goal
28
+ ### 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.
29
+ - **Definition**: You are given a definition of the communication trait that is being evaluated to help guide your Score.
30
+ - **Data**: Your input data include CONTEXT, QUERY, and RESPONSE.
31
+ - **Tasks**: To complete your evaluation you will be asked to evaluate the Data in different ways.
32
+
33
+ user:
34
+ # Definition
35
+ **Groundedness** refers to how well an answer is anchored in the provided context, evaluating its relevance, accuracy, and completeness based exclusively on that context. It assesses the extent to which the answer directly and fully addresses the question without introducing unrelated or incorrect information. The scale ranges from 1 to 5, with higher numbers indicating greater groundedness.
36
+
37
+ # Ratings
38
+ ## [Groundedness: 1] (Completely Unrelated Response)
39
+ **Definition:** An answer that does not relate to the question or the context in any way. It fails to address the topic, provides irrelevant information, or introduces completely unrelated subjects.
40
+
41
+ **Examples:**
42
+ **Context:** The company's annual meeting will be held next Thursday.
43
+ **Query:** When is the company's annual meeting?
44
+ **Response:** I enjoy hiking in the mountains during summer.
45
+
46
+ **Context:** The new policy aims to reduce carbon emissions by 20% over the next five years.
47
+ **Query:** What is the goal of the new policy?
48
+ **Response:** My favorite color is blue.
49
+
50
+ ## [Groundedness: 2] (Related Topic but Does Not Respond to the Query)
51
+ **Definition:** An answer that relates to the general topic of the context but does not answer the specific question asked. It may mention concepts from the context but fails to provide a direct or relevant response.
52
+
53
+ **Examples:**
54
+ **Context:** The museum will exhibit modern art pieces from various local artists.
55
+ **Query:** What kind of art will be exhibited at the museum?
56
+ **Response:** Museums are important cultural institutions.
57
+
58
+ **Context:** The new software update improves battery life and performance.
59
+ **Query:** What does the new software update improve?
60
+ **Response:** Software updates can sometimes fix bugs.
61
+
62
+ ## [Groundedness: 3] (Attempts to Respond but Contains Incorrect Information)
63
+ **Definition:** An answer that attempts to respond to the question but includes incorrect information not supported by the context. It may misstate facts, misinterpret the context, or provide erroneous details.
64
+
65
+ **Examples:**
66
+ **Context:** The festival starts on June 5th and features international musicians.
67
+ **Query:** When does the festival start?
68
+ **Response:** The festival starts on July 5th and features local artists.
69
+
70
+ **Context:** The recipe requires two eggs and one cup of milk.
71
+ **Query:** How many eggs are needed for the recipe?
72
+ **Response:** You need three eggs for the recipe.
73
+
74
+ ## [Groundedness: 4] (Partially Correct Response)
75
+ **Definition:** An answer that provides a correct response to the question but is incomplete or lacks specific details mentioned in the context. It captures some of the necessary information but omits key elements needed for a full understanding.
76
+
77
+ **Examples:**
78
+ **Context:** The bookstore offers a 15% discount to students and a 10% discount to senior citizens.
79
+ **Query:** What discount does the bookstore offer to students?
80
+ **Response:** Students get a discount at the bookstore.
81
+
82
+ **Context:** The company's headquarters are located in Berlin, Germany.
83
+ **Query:** Where are the company's headquarters?
84
+ **Response:** The company's headquarters are in Germany.
85
+
86
+ ## [Groundedness: 5] (Fully Correct and Complete Response)
87
+ **Definition:** An answer that thoroughly and accurately responds to the question, including all relevant details from the context. It directly addresses the question with precise information, demonstrating complete understanding without adding extraneous information.
88
+
89
+ **Examples:**
90
+ **Context:** The author released her latest novel, 'The Silent Echo', on September 1st.
91
+ **Query:** When was 'The Silent Echo' released?
92
+ **Response:** 'The Silent Echo' was released on September 1st.
93
+
94
+ **Context:** Participants must register by May 31st to be eligible for early bird pricing.
95
+ **Query:** By what date must participants register to receive early bird pricing?
96
+ **Response:** Participants must register by May 31st to receive early bird pricing.
97
+
98
+
99
+ # Data
100
+ CONTEXT: {{context}}
101
+ QUERY: {{query}}
102
+ RESPONSE: {{response}}
103
+
104
+
105
+ # Tasks
106
+ ## Please provide your assessment Score for the previous RESPONSE in relation to the CONTEXT and QUERY based on the Definitions above. Your output should include the following information:
107
+ - **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:".
108
+ - **Explanation**: a very short explanation of why you think the input Data should get that Score.
109
+ - **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.
110
+
111
+
112
+ ## Please provide your answers between the tags: <S0>your chain of thoughts</S0>, <S1>your explanation</S1>, <S2>your Score</S2>.
113
+ # Output
@@ -0,0 +1,99 @@
1
+ ---
2
+ name: Groundedness
3
+ description: Evaluates groundedness score for RAG scenario
4
+ model:
5
+ api: chat
6
+ parameters:
7
+ temperature: 0.0
8
+ max_tokens: 800
9
+ top_p: 1.0
10
+ presence_penalty: 0
11
+ frequency_penalty: 0
12
+ response_format:
13
+ type: text
14
+
15
+ inputs:
16
+ response:
17
+ type: string
18
+ context:
19
+ type: string
20
+
21
+ ---
22
+ system:
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 CONTEXT and RESPONSE.
28
+ - **Tasks**: To complete your evaluation you will be asked to evaluate the Data in different ways.
29
+
30
+ user:
31
+ # Definition
32
+ **Groundedness** refers to how faithfully a response adheres to the information provided in the CONTEXT, ensuring that all content is directly supported by the context without introducing unsupported information or omitting critical details. It evaluates the fidelity and precision of the response in relation to the source material.
33
+
34
+ # Ratings
35
+ ## [Groundedness: 1] (Completely Ungrounded Response)
36
+ **Definition:** The response is entirely unrelated to the CONTEXT, introducing topics or information that have no connection to the provided material.
37
+
38
+ **Examples:**
39
+ **Context:** The company's profits increased by 20% in the last quarter.
40
+ **Response:** I enjoy playing soccer on weekends with my friends.
41
+
42
+ **Context:** The new smartphone model features a larger display and improved battery life.
43
+ **Response:** The history of ancient Egypt is fascinating and full of mysteries.
44
+
45
+ ## [Groundedness: 2] (Contradictory Response)
46
+ **Definition:** The response directly contradicts or misrepresents the information provided in the CONTEXT.
47
+
48
+ **Examples:**
49
+ **Context:** The company's profits increased by 20% in the last quarter.
50
+ **Response:** The company's profits decreased by 20% in the last quarter.
51
+
52
+ **Context:** The new smartphone model features a larger display and improved battery life.
53
+ **Response:** The new smartphone model has a smaller display and shorter battery life.
54
+
55
+ ## [Groundedness: 3] (Accurate Response with Unsupported Additions)
56
+ **Definition:** The response accurately includes information from the CONTEXT but adds details, opinions, or explanations that are not supported by the provided material.
57
+
58
+ **Examples:**
59
+ **Context:** The company's profits increased by 20% in the last quarter.
60
+ **Response:** The company's profits increased by 20% in the last quarter due to their aggressive marketing strategy.
61
+
62
+ **Context:** The new smartphone model features a larger display and improved battery life.
63
+ **Response:** The new smartphone model features a larger display, improved battery life, and comes with a free case.
64
+
65
+ ## [Groundedness: 4] (Incomplete Response Missing Critical Details)
66
+ **Definition:** The response contains information from the CONTEXT but omits essential details that are necessary for a comprehensive understanding of the main point.
67
+
68
+ **Examples:**
69
+ **Context:** The company's profits increased by 20% in the last quarter, marking the highest growth rate in its history.
70
+ **Response:** The company's profits increased by 20% in the last quarter.
71
+
72
+ **Context:** The new smartphone model features a larger display, improved battery life, and an upgraded camera system.
73
+ **Response:** The new smartphone model features a larger display and improved battery life.
74
+
75
+ ## [Groundedness: 5] (Fully Grounded and Complete Response)
76
+ **Definition:** The response is entirely based on the CONTEXT, accurately and thoroughly conveying all essential information without introducing unsupported details or omitting critical points.
77
+
78
+ **Examples:**
79
+ **Context:** The company's profits increased by 20% in the last quarter, marking the highest growth rate in its history.
80
+ **Response:** The company's profits increased by 20% in the last quarter, marking the highest growth rate in its history.
81
+
82
+ **Context:** The new smartphone model features a larger display, improved battery life, and an upgraded camera system.
83
+ **Response:** The new smartphone model features a larger display, improved battery life, and an upgraded camera system.
84
+
85
+
86
+ # Data
87
+ CONTEXT: {{context}}
88
+ RESPONSE: {{response}}
89
+
90
+
91
+ # Tasks
92
+ ## Please provide your assessment Score for the previous RESPONSE in relation to the CONTEXT based on the Definitions above. Your output should include the following information:
93
+ - **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:".
94
+ - **Explanation**: a very short explanation of why you think the input Data should get that Score.
95
+ - **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.
96
+
97
+
98
+ ## Please provide your answers between the tags: <S0>your chain of thoughts</S0>, <S1>your explanation</S1>, <S2>your Score</S2>.
99
+ # Output
@@ -0,0 +1,9 @@
1
+ # ---------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # ---------------------------------------------------------
4
+
5
+ from ._meteor import MeteorScoreEvaluator
6
+
7
+ __all__ = [
8
+ "MeteorScoreEvaluator",
9
+ ]
@@ -0,0 +1,90 @@
1
+ # ---------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # ---------------------------------------------------------
4
+ from nltk.translate.meteor_score import meteor_score
5
+ from promptflow._utils.async_utils import async_run_allowing_running_loop
6
+
7
+ from azure.ai.evaluation._common.utils import nltk_tokenize, ensure_nltk_data_downloaded
8
+
9
+
10
+ class _AsyncMeteorScoreEvaluator:
11
+ def __init__(self, alpha: float = 0.9, beta: float = 3.0, gamma: float = 0.5):
12
+ self._alpha = alpha
13
+ self._beta = beta
14
+ self._gamma = gamma
15
+
16
+ ensure_nltk_data_downloaded()
17
+
18
+ async def __call__(self, *, ground_truth: str, response: str, **kwargs):
19
+ reference_tokens = nltk_tokenize(ground_truth)
20
+ hypothesis_tokens = nltk_tokenize(response)
21
+
22
+ score = meteor_score(
23
+ [reference_tokens],
24
+ hypothesis_tokens,
25
+ alpha=self._alpha,
26
+ beta=self._beta,
27
+ gamma=self._gamma,
28
+ )
29
+
30
+ return {
31
+ "meteor_score": score,
32
+ }
33
+
34
+
35
+ class MeteorScoreEvaluator:
36
+ """
37
+ Calculates the METEOR score for a given response and ground truth.
38
+
39
+ The METEOR (Metric for Evaluation of Translation with Explicit Ordering) score grader evaluates generated text by
40
+ comparing it to reference texts, focusing on precision, recall, and content alignment. It addresses limitations of
41
+ other metrics like BLEU by considering synonyms, stemming, and paraphrasing. METEOR score considers synonyms and
42
+ word stems to more accurately capture meaning and language variations. In addition to machine translation and
43
+ text summarization, paraphrase detection is an optimal use case for the METEOR score.
44
+
45
+ Use the METEOR score when you want a more linguistically informed evaluation metric that captures not only
46
+ n-gram overlap but also accounts for synonyms, stemming, and word order. This is particularly useful for evaluating
47
+ tasks like machine translation, text summarization, and text generation.
48
+
49
+ The METEOR score ranges from 0 to 1, with 1 indicating a perfect match.
50
+
51
+ :param alpha: The METEOR score alpha parameter. Default is 0.9.
52
+ :type alpha: float
53
+ :param beta: The METEOR score beta parameter. Default is 3.0.
54
+ :type beta: float
55
+ :param gamma: The METEOR score gamma parameter. Default is 0.5.
56
+ :type gamma: float
57
+
58
+ .. admonition:: Example:
59
+
60
+ .. literalinclude:: ../samples/evaluation_samples_evaluate.py
61
+ :start-after: [START meteor_score_evaluator]
62
+ :end-before: [END meteor_score_evaluator]
63
+ :language: python
64
+ :dedent: 8
65
+ :caption: Initialize and call a MeteorScoreEvaluator with alpha of 0.8.
66
+ """
67
+
68
+ id = "azureml://registries/azureml/models/Meteor-Score-Evaluator/versions/3"
69
+ """Evaluator identifier, experimental and to be used only with evaluation in cloud."""
70
+
71
+ def __init__(self, alpha: float = 0.9, beta: float = 3.0, gamma: float = 0.5):
72
+ self._async_evaluator = _AsyncMeteorScoreEvaluator(alpha=alpha, beta=beta, gamma=gamma)
73
+
74
+ def __call__(self, *, ground_truth: str, response: str, **kwargs):
75
+ """
76
+ Evaluate the METEOR score between the response and the ground truth.
77
+
78
+ :keyword response: The response to be evaluated.
79
+ :paramtype response: str
80
+ :keyword ground_truth: The ground truth to be compared against.
81
+ :paramtype ground_truth: str
82
+ :return: The METEOR score.
83
+ :rtype: Dict[str, float]
84
+ """
85
+ return async_run_allowing_running_loop(
86
+ self._async_evaluator, ground_truth=ground_truth, response=response, **kwargs
87
+ )
88
+
89
+ def _to_async(self):
90
+ return self._async_evaluator
@@ -0,0 +1,20 @@
1
+ # ---------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # ---------------------------------------------------------
4
+ from ._content_safety_multimodal import ContentSafetyMultimodalEvaluator
5
+ from ._content_safety_multimodal_base import ContentSafetyMultimodalEvaluatorBase
6
+ from ._hate_unfairness import HateUnfairnessMultimodalEvaluator
7
+ from ._self_harm import SelfHarmMultimodalEvaluator
8
+ from ._sexual import SexualMultimodalEvaluator
9
+ from ._violence import ViolenceMultimodalEvaluator
10
+ from ._protected_material import ProtectedMaterialMultimodalEvaluator
11
+
12
+ __all__ = [
13
+ "ContentSafetyMultimodalEvaluator",
14
+ "ContentSafetyMultimodalEvaluatorBase",
15
+ "ViolenceMultimodalEvaluator",
16
+ "SexualMultimodalEvaluator",
17
+ "SelfHarmMultimodalEvaluator",
18
+ "HateUnfairnessMultimodalEvaluator",
19
+ "ProtectedMaterialMultimodalEvaluator",
20
+ ]
@@ -0,0 +1,132 @@
1
+ # ---------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # ---------------------------------------------------------
4
+ import logging
5
+ from concurrent.futures import as_completed
6
+ from typing import Callable, Dict, List, Union
7
+
8
+ from promptflow.tracing import ThreadPoolExecutorWithContext as ThreadPoolExecutor
9
+ from azure.ai.evaluation._common._experimental import experimental
10
+ from azure.ai.evaluation._common.utils import validate_conversation
11
+ from ._hate_unfairness import HateUnfairnessMultimodalEvaluator
12
+ from ._self_harm import SelfHarmMultimodalEvaluator
13
+ from ._sexual import SexualMultimodalEvaluator
14
+ from ._violence import ViolenceMultimodalEvaluator
15
+
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ @experimental
21
+ class ContentSafetyMultimodalEvaluator:
22
+ """
23
+ Initialize a content safety multimodal evaluator configured to evaluate content safety metrics
24
+ in a multimodal scenario.
25
+
26
+ :param credential: The credential required for connecting to the Azure AI project.
27
+ :type credential: ~azure.core.credentials.TokenCredential
28
+ :param azure_ai_project: The scope of the Azure AI project, containing the subscription ID,
29
+ resource group, and project name.
30
+ :type azure_ai_project: ~azure.ai.evaluation.AzureAIProject
31
+ :param kwargs: Additional arguments to pass to the evaluator.
32
+ :type kwargs: Any
33
+
34
+ :return: A function that evaluates multimodal chat messages and generates content safety metrics.
35
+
36
+ **Usage Example**
37
+
38
+ .. code-block:: python
39
+
40
+ azure_ai_project = {
41
+ "subscription_id": "<subscription_id>",
42
+ "resource_group_name": "<resource_group_name>",
43
+ "project_name": "<project_name>",
44
+ }
45
+ eval_fn = ContentSafetyMultimodalEvaluator(azure_ai_project)
46
+ result = eval_fn(conversation=
47
+ {
48
+ "messages": [
49
+ {
50
+ "role": "user",
51
+ "content": [
52
+ {
53
+ "type": "text",
54
+ "text": "What's in this image?"
55
+ },
56
+ {
57
+ "type": "image_url",
58
+ "image_url": {
59
+ "url": "<image url or base64 encoded image>"
60
+ }
61
+ }
62
+ ]
63
+ },
64
+ {
65
+ "role": "assistant",
66
+ "content": "This picture shows an astronaut standing in the desert."
67
+ }
68
+ ]
69
+ }
70
+ )
71
+
72
+ **Output Format**
73
+
74
+ .. code-block:: json
75
+
76
+ {
77
+ "violence": "Medium",
78
+ "violence_score": 5.0,
79
+ "violence_reason": "Some reason",
80
+ "sexual": "Medium",
81
+ "sexual_score": 5.0,
82
+ "sexual_reason": "Some reason",
83
+ "self_harm": "Medium",
84
+ "self_harm_score": 5.0,
85
+ "self_harm_reason": "Some reason",
86
+ "hate_unfairness": "Medium",
87
+ "hate_unfairness_score": 5.0,
88
+ "hate_unfairness_reason": "Some reason"
89
+ }
90
+
91
+ """
92
+
93
+ id = "content_safety_multimodal"
94
+ """Evaluator identifier, experimental and to be used only with evaluation in cloud."""
95
+
96
+ def __init__(self, credential, azure_ai_project, **kwargs):
97
+ self._parallel = kwargs.pop("_parallel", False)
98
+ self._evaluators: List[Callable[..., Dict[str, Union[str, float]]]] = [
99
+ ViolenceMultimodalEvaluator(credential=credential, azure_ai_project=azure_ai_project),
100
+ SexualMultimodalEvaluator(credential=credential, azure_ai_project=azure_ai_project),
101
+ SelfHarmMultimodalEvaluator(credential=credential, azure_ai_project=azure_ai_project),
102
+ HateUnfairnessMultimodalEvaluator(credential=credential, azure_ai_project=azure_ai_project),
103
+ ]
104
+
105
+ def __call__(self, *, conversation, **kwargs):
106
+ """
107
+ Evaluates content-safety metrics for list of messages.
108
+
109
+ :keyword conversation: The conversation contains list of messages to be evaluated.
110
+ Each message should have "role" and "content" keys. It supports single turn only.
111
+ :paramtype conversation: ~azure.ai.evaluation.Conversation
112
+ :return: The evaluation score based on the Content Safety Metrics.
113
+ :rtype: Dict[str, Union[float, str]]
114
+ """
115
+ # validate inputs
116
+ validate_conversation(conversation)
117
+ results: Dict[str, Union[str, float]] = {}
118
+ if self._parallel:
119
+ with ThreadPoolExecutor() as executor:
120
+ futures = {
121
+ executor.submit(evaluator, conversation=conversation, **kwargs): evaluator
122
+ for evaluator in self._evaluators
123
+ }
124
+
125
+ for future in as_completed(futures):
126
+ results.update(future.result())
127
+ else:
128
+ for evaluator in self._evaluators:
129
+ result = evaluator(conversation=conversation, **kwargs)
130
+ results.update(result)
131
+
132
+ return results
@@ -0,0 +1,55 @@
1
+ # ---------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # ---------------------------------------------------------
4
+ from abc import ABC
5
+ from typing import Union
6
+ from azure.ai.evaluation._common.rai_service import evaluate_with_rai_service_multimodal
7
+ from azure.ai.evaluation._common.constants import EvaluationMetrics, _InternalEvaluationMetrics
8
+ from azure.ai.evaluation._common.utils import validate_conversation
9
+ from azure.core.credentials import TokenCredential
10
+
11
+
12
+ class ContentSafetyMultimodalEvaluatorBase(ABC):
13
+ """
14
+ Initialize a evaluator for a specified Evaluation Metric. Base class that is not
15
+ meant to be instantiated by users.
16
+
17
+ :param metric: The metric to be evaluated.
18
+ :type metric: ~azure.ai.evaluation._evaluators._content_safety.flow.constants.EvaluationMetrics
19
+ :param credential: The credential for connecting to Azure AI project. Required
20
+ :type credential: ~azure.core.credentials.TokenCredential
21
+ :param azure_ai_project: The scope of the Azure AI project.
22
+ It contains subscription id, resource group, and project name.
23
+ :type azure_ai_project: ~azure.ai.evaluation.AzureAIProject
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ metric: Union[EvaluationMetrics, _InternalEvaluationMetrics],
29
+ credential: TokenCredential,
30
+ azure_ai_project,
31
+ ):
32
+ self._metric = metric
33
+ self._azure_ai_project = azure_ai_project
34
+ self._credential = credential
35
+
36
+ async def __call__(self, *, conversation, **kwargs):
37
+ """
38
+ Evaluates content according to this evaluator's metric.
39
+ :keyword conversation: The conversation contains list of messages to be evaluated.
40
+ Each message should have "role" and "content" keys.
41
+ :paramtype conversation: ~azure.ai.evaluation.Conversation
42
+ :return: The evaluation score computation based on the Content Safety metric (self.metric).
43
+ :rtype: Dict[str, Union[float, str]]
44
+ """
45
+ # validate inputs
46
+ validate_conversation(conversation)
47
+ messages = conversation["messages"]
48
+ # Run score computation based on supplied metric.
49
+ result = await evaluate_with_rai_service_multimodal(
50
+ messages=messages,
51
+ metric_name=self._metric,
52
+ project_scope=self._azure_ai_project,
53
+ credential=self._credential,
54
+ )
55
+ return result