azure-ai-evaluation 1.0.0__py3-none-any.whl → 1.0.0b2__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 (105) hide show
  1. azure/ai/evaluation/__init__.py +5 -31
  2. azure/ai/evaluation/_common/constants.py +2 -9
  3. azure/ai/evaluation/_common/rai_service.py +120 -300
  4. azure/ai/evaluation/_common/utils.py +23 -381
  5. azure/ai/evaluation/_constants.py +6 -19
  6. azure/ai/evaluation/_evaluate/{_batch_run → _batch_run_client}/__init__.py +2 -3
  7. azure/ai/evaluation/_evaluate/{_batch_run/eval_run_context.py → _batch_run_client/batch_run_context.py} +7 -23
  8. azure/ai/evaluation/_evaluate/{_batch_run → _batch_run_client}/code_client.py +17 -33
  9. azure/ai/evaluation/_evaluate/{_batch_run → _batch_run_client}/proxy_client.py +4 -32
  10. azure/ai/evaluation/_evaluate/_eval_run.py +24 -81
  11. azure/ai/evaluation/_evaluate/_evaluate.py +239 -393
  12. azure/ai/evaluation/_evaluate/_telemetry/__init__.py +17 -17
  13. azure/ai/evaluation/_evaluate/_utils.py +28 -82
  14. azure/ai/evaluation/_evaluators/_bleu/_bleu.py +18 -17
  15. azure/ai/evaluation/_evaluators/{_retrieval → _chat}/__init__.py +2 -2
  16. azure/ai/evaluation/_evaluators/_chat/_chat.py +357 -0
  17. azure/ai/evaluation/_evaluators/{_service_groundedness → _chat/retrieval}/__init__.py +2 -2
  18. azure/ai/evaluation/_evaluators/_chat/retrieval/_retrieval.py +157 -0
  19. azure/ai/evaluation/_evaluators/_chat/retrieval/retrieval.prompty +48 -0
  20. azure/ai/evaluation/_evaluators/_coherence/_coherence.py +88 -78
  21. azure/ai/evaluation/_evaluators/_coherence/coherence.prompty +39 -76
  22. azure/ai/evaluation/_evaluators/_content_safety/__init__.py +4 -0
  23. azure/ai/evaluation/_evaluators/_content_safety/_content_safety.py +67 -105
  24. azure/ai/evaluation/_evaluators/{_multimodal/_content_safety_multimodal_base.py → _content_safety/_content_safety_base.py} +34 -24
  25. azure/ai/evaluation/_evaluators/_content_safety/_content_safety_chat.py +301 -0
  26. azure/ai/evaluation/_evaluators/_content_safety/_hate_unfairness.py +54 -105
  27. azure/ai/evaluation/_evaluators/_content_safety/_self_harm.py +52 -99
  28. azure/ai/evaluation/_evaluators/_content_safety/_sexual.py +52 -101
  29. azure/ai/evaluation/_evaluators/_content_safety/_violence.py +51 -101
  30. azure/ai/evaluation/_evaluators/_eci/_eci.py +54 -44
  31. azure/ai/evaluation/_evaluators/_f1_score/_f1_score.py +19 -34
  32. azure/ai/evaluation/_evaluators/_fluency/_fluency.py +89 -76
  33. azure/ai/evaluation/_evaluators/_fluency/fluency.prompty +41 -66
  34. azure/ai/evaluation/_evaluators/_gleu/_gleu.py +16 -14
  35. azure/ai/evaluation/_evaluators/_groundedness/_groundedness.py +87 -113
  36. azure/ai/evaluation/_evaluators/_groundedness/groundedness.prompty +54 -0
  37. azure/ai/evaluation/_evaluators/_meteor/_meteor.py +27 -20
  38. azure/ai/evaluation/_evaluators/_protected_material/_protected_material.py +80 -89
  39. azure/ai/evaluation/_evaluators/_protected_materials/__init__.py +5 -0
  40. azure/ai/evaluation/_evaluators/_protected_materials/_protected_materials.py +104 -0
  41. azure/ai/evaluation/_evaluators/_qa/_qa.py +30 -23
  42. azure/ai/evaluation/_evaluators/_relevance/_relevance.py +96 -84
  43. azure/ai/evaluation/_evaluators/_relevance/relevance.prompty +47 -78
  44. azure/ai/evaluation/_evaluators/_rouge/_rouge.py +27 -26
  45. azure/ai/evaluation/_evaluators/_similarity/_similarity.py +38 -53
  46. azure/ai/evaluation/_evaluators/_similarity/similarity.prompty +5 -0
  47. azure/ai/evaluation/_evaluators/_xpia/xpia.py +105 -91
  48. azure/ai/evaluation/_exceptions.py +7 -28
  49. azure/ai/evaluation/_http_utils.py +132 -203
  50. azure/ai/evaluation/_model_configurations.py +8 -104
  51. azure/ai/evaluation/_version.py +1 -1
  52. azure/ai/evaluation/simulator/__init__.py +1 -2
  53. azure/ai/evaluation/simulator/_adversarial_scenario.py +1 -20
  54. azure/ai/evaluation/simulator/_adversarial_simulator.py +92 -111
  55. azure/ai/evaluation/simulator/_constants.py +1 -11
  56. azure/ai/evaluation/simulator/_conversation/__init__.py +12 -13
  57. azure/ai/evaluation/simulator/_conversation/_conversation.py +4 -4
  58. azure/ai/evaluation/simulator/_direct_attack_simulator.py +67 -33
  59. azure/ai/evaluation/simulator/_helpers/__init__.py +2 -1
  60. azure/ai/evaluation/{_common → simulator/_helpers}/_experimental.py +9 -24
  61. azure/ai/evaluation/simulator/_helpers/_simulator_data_classes.py +5 -26
  62. azure/ai/evaluation/simulator/_indirect_attack_simulator.py +94 -107
  63. azure/ai/evaluation/simulator/_model_tools/_identity_manager.py +22 -70
  64. azure/ai/evaluation/simulator/_model_tools/_proxy_completion_model.py +11 -28
  65. azure/ai/evaluation/simulator/_model_tools/_rai_client.py +4 -8
  66. azure/ai/evaluation/simulator/_model_tools/_template_handler.py +24 -68
  67. azure/ai/evaluation/simulator/_model_tools/models.py +10 -10
  68. azure/ai/evaluation/simulator/_prompty/task_query_response.prompty +10 -6
  69. azure/ai/evaluation/simulator/_prompty/task_simulate.prompty +5 -6
  70. azure/ai/evaluation/simulator/_simulator.py +207 -277
  71. azure/ai/evaluation/simulator/_tracing.py +4 -4
  72. azure/ai/evaluation/simulator/_utils.py +13 -31
  73. azure_ai_evaluation-1.0.0b2.dist-info/METADATA +449 -0
  74. azure_ai_evaluation-1.0.0b2.dist-info/RECORD +99 -0
  75. {azure_ai_evaluation-1.0.0.dist-info → azure_ai_evaluation-1.0.0b2.dist-info}/WHEEL +1 -1
  76. azure/ai/evaluation/_common/math.py +0 -89
  77. azure/ai/evaluation/_evaluate/_batch_run/target_run_context.py +0 -46
  78. azure/ai/evaluation/_evaluators/_common/__init__.py +0 -13
  79. azure/ai/evaluation/_evaluators/_common/_base_eval.py +0 -344
  80. azure/ai/evaluation/_evaluators/_common/_base_prompty_eval.py +0 -88
  81. azure/ai/evaluation/_evaluators/_common/_base_rai_svc_eval.py +0 -133
  82. azure/ai/evaluation/_evaluators/_groundedness/groundedness_with_query.prompty +0 -113
  83. azure/ai/evaluation/_evaluators/_groundedness/groundedness_without_query.prompty +0 -99
  84. azure/ai/evaluation/_evaluators/_multimodal/__init__.py +0 -20
  85. azure/ai/evaluation/_evaluators/_multimodal/_content_safety_multimodal.py +0 -132
  86. azure/ai/evaluation/_evaluators/_multimodal/_hate_unfairness.py +0 -100
  87. azure/ai/evaluation/_evaluators/_multimodal/_protected_material.py +0 -124
  88. azure/ai/evaluation/_evaluators/_multimodal/_self_harm.py +0 -100
  89. azure/ai/evaluation/_evaluators/_multimodal/_sexual.py +0 -100
  90. azure/ai/evaluation/_evaluators/_multimodal/_violence.py +0 -100
  91. azure/ai/evaluation/_evaluators/_retrieval/_retrieval.py +0 -112
  92. azure/ai/evaluation/_evaluators/_retrieval/retrieval.prompty +0 -93
  93. azure/ai/evaluation/_evaluators/_service_groundedness/_service_groundedness.py +0 -148
  94. azure/ai/evaluation/_vendor/__init__.py +0 -3
  95. azure/ai/evaluation/_vendor/rouge_score/__init__.py +0 -14
  96. azure/ai/evaluation/_vendor/rouge_score/rouge_scorer.py +0 -328
  97. azure/ai/evaluation/_vendor/rouge_score/scoring.py +0 -63
  98. azure/ai/evaluation/_vendor/rouge_score/tokenize.py +0 -63
  99. azure/ai/evaluation/_vendor/rouge_score/tokenizers.py +0 -53
  100. azure/ai/evaluation/simulator/_data_sources/__init__.py +0 -3
  101. azure/ai/evaluation/simulator/_data_sources/grounding.json +0 -1150
  102. azure_ai_evaluation-1.0.0.dist-info/METADATA +0 -595
  103. azure_ai_evaluation-1.0.0.dist-info/NOTICE.txt +0 -70
  104. azure_ai_evaluation-1.0.0.dist-info/RECORD +0 -119
  105. {azure_ai_evaluation-1.0.0.dist-info → azure_ai_evaluation-1.0.0b2.dist-info}/top_level.txt +0 -0
@@ -1,63 +1,108 @@
1
1
  # ---------------------------------------------------------
2
2
  # Copyright (c) Microsoft Corporation. All rights reserved.
3
3
  # ---------------------------------------------------------
4
+
4
5
  import os
5
- from typing import Dict, Union, List
6
+ import re
6
7
 
7
- from typing_extensions import overload, override
8
+ import numpy as np
9
+ from promptflow._utils.async_utils import async_run_allowing_running_loop
10
+ from promptflow.core import AsyncPrompty
8
11
 
9
- from azure.ai.evaluation._evaluators._common import PromptyEvaluatorBase
10
- from azure.ai.evaluation._model_configurations import Conversation
12
+ from azure.ai.evaluation._exceptions import ErrorBlame, ErrorCategory, ErrorTarget, EvaluationException
11
13
 
14
+ from ..._common.utils import ensure_api_version_in_aoai_model_config, ensure_user_agent_in_aoai_model_config
12
15
 
13
- class CoherenceEvaluator(PromptyEvaluatorBase[Union[str, float]]):
14
- """
15
- Evaluates coherence score for a given query and response or a multi-turn conversation, including reasoning.
16
+ try:
17
+ from ..._user_agent import USER_AGENT
18
+ except ImportError:
19
+ USER_AGENT = None
20
+
21
+
22
+ class _AsyncCoherenceEvaluator:
23
+ # Constants must be defined within eval's directory to be save/loadable
24
+ PROMPTY_FILE = "coherence.prompty"
25
+ LLM_CALL_TIMEOUT = 600
26
+ DEFAULT_OPEN_API_VERSION = "2024-02-15-preview"
27
+
28
+ def __init__(self, model_config: dict):
29
+ ensure_api_version_in_aoai_model_config(model_config, self.DEFAULT_OPEN_API_VERSION)
30
+
31
+ prompty_model_config = {"configuration": model_config, "parameters": {"extra_headers": {}}}
32
+
33
+ # Handle "RuntimeError: Event loop is closed" from httpx AsyncClient
34
+ # https://github.com/encode/httpx/discussions/2959
35
+ prompty_model_config["parameters"]["extra_headers"].update({"Connection": "close"})
36
+
37
+ ensure_user_agent_in_aoai_model_config(
38
+ model_config,
39
+ prompty_model_config,
40
+ USER_AGENT,
41
+ )
42
+
43
+ current_dir = os.path.dirname(__file__)
44
+ prompty_path = os.path.join(current_dir, self.PROMPTY_FILE)
45
+ self._flow = AsyncPrompty.load(source=prompty_path, model=prompty_model_config)
46
+
47
+ async def __call__(self, *, query: str, response: str, **kwargs):
48
+ # Validate input parameters
49
+ query = str(query or "")
50
+ response = str(response or "")
51
+
52
+ if not (query.strip() and response.strip()):
53
+ msg = "Both 'query' and 'response' must be non-empty strings."
54
+ raise EvaluationException(
55
+ message=msg,
56
+ internal_message=msg,
57
+ error_category=ErrorCategory.INVALID_VALUE,
58
+ error_blame=ErrorBlame.USER_ERROR,
59
+ error_target=ErrorTarget.COHERENCE_EVALUATOR,
60
+ )
61
+
62
+ # Run the evaluation flow
63
+ llm_output = await self._flow(query=query, response=response, timeout=self.LLM_CALL_TIMEOUT, **kwargs)
64
+
65
+ score = np.nan
66
+ if llm_output:
67
+ match = re.search(r"\d", llm_output)
68
+ if match:
69
+ score = float(match.group())
70
+
71
+ return {"gpt_coherence": float(score)}
16
72
 
17
- The coherence measure assesses the ability of the language model to generate text that reads naturally,
18
- flows smoothly, and resembles human-like language in its responses. Use it when assessing the readability
19
- and user-friendliness of a model's generated responses in real-world applications.
73
+
74
+ class CoherenceEvaluator:
75
+ """
76
+ Initialize a coherence evaluator configured for a specific Azure OpenAI model.
20
77
 
21
78
  :param model_config: Configuration for the Azure OpenAI model.
22
79
  :type model_config: Union[~azure.ai.evaluation.AzureOpenAIModelConfiguration,
23
80
  ~azure.ai.evaluation.OpenAIModelConfiguration]
24
81
 
25
- .. admonition:: Example:
82
+ **Usage**
26
83
 
27
- .. literalinclude:: ../samples/evaluation_samples_evaluate.py
28
- :start-after: [START coherence_evaluator]
29
- :end-before: [END coherence_evaluator]
30
- :language: python
31
- :dedent: 8
32
- :caption: Initialize and call a CoherenceEvaluator with a query and response.
84
+ .. code-block:: python
33
85
 
34
- .. note::
86
+ eval_fn = CoherenceEvaluator(model_config)
87
+ result = eval_fn(
88
+ query="What is the capital of Japan?",
89
+ response="The capital of Japan is Tokyo.")
35
90
 
36
- To align with our support of a diverse set of models, an output key without the `gpt_` prefix has been added.
37
- To maintain backwards compatibility, the old key with the `gpt_` prefix is still be present in the output;
38
- however, it is recommended to use the new key moving forward as the old key will be deprecated in the future.
39
- """
91
+ **Output format**
92
+
93
+ .. code-block:: python
40
94
 
41
- _PROMPTY_FILE = "coherence.prompty"
42
- _RESULT_KEY = "coherence"
95
+ {
96
+ "gpt_coherence": 1.0
97
+ }
98
+ """
43
99
 
44
- id = "azureml://registries/azureml/models/Coherence-Evaluator/versions/4"
45
- """Evaluator identifier, experimental and to be used only with evaluation in cloud."""
100
+ def __init__(self, model_config: dict):
101
+ self._async_evaluator = _AsyncCoherenceEvaluator(model_config)
46
102
 
47
- @override
48
- def __init__(self, model_config):
49
- current_dir = os.path.dirname(__file__)
50
- prompty_path = os.path.join(current_dir, self._PROMPTY_FILE)
51
- super().__init__(model_config=model_config, prompty_file=prompty_path, result_key=self._RESULT_KEY)
52
-
53
- @overload
54
- def __call__(
55
- self,
56
- *,
57
- query: str,
58
- response: str,
59
- ) -> Dict[str, Union[str, float]]:
60
- """Evaluate coherence for given input of query, response
103
+ def __call__(self, *, query: str, response: str, **kwargs):
104
+ """
105
+ Evaluate coherence.
61
106
 
62
107
  :keyword query: The query to be evaluated.
63
108
  :paramtype query: str
@@ -66,42 +111,7 @@ class CoherenceEvaluator(PromptyEvaluatorBase[Union[str, float]]):
66
111
  :return: The coherence score.
67
112
  :rtype: Dict[str, float]
68
113
  """
114
+ return async_run_allowing_running_loop(self._async_evaluator, query=query, response=response, **kwargs)
69
115
 
70
- @overload
71
- def __call__(
72
- self,
73
- *,
74
- conversation: Conversation,
75
- ) -> Dict[str, Union[float, Dict[str, List[Union[str, float]]]]]:
76
- """Evaluate coherence for a conversation
77
-
78
- :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
79
- key "messages", and potentially a global context under the key "context". Conversation turns are expected
80
- to be dictionaries with keys "content", "role", and possibly "context".
81
- :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
82
- :return: The coherence score.
83
- :rtype: Dict[str, Union[float, Dict[str, List[float]]]]
84
- """
85
-
86
- @override
87
- def __call__( # pylint: disable=docstring-missing-param
88
- self,
89
- *args,
90
- **kwargs,
91
- ):
92
- """Evaluate coherence. Accepts either a query and response for a single evaluation,
93
- or a conversation for a potentially multi-turn evaluation. If the conversation has more than one pair of
94
- turns, the evaluator will aggregate the results of each turn.
95
-
96
- :keyword query: The query to be evaluated.
97
- :paramtype query: str
98
- :keyword response: The response to be evaluated.
99
- :paramtype response: Optional[str]
100
- :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
101
- key "messages". Conversation turns are expected
102
- to be dictionaries with keys "content" and "role".
103
- :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
104
- :return: The relevance score.
105
- :rtype: Union[Dict[str, float], Dict[str, Union[float, Dict[str, List[float]]]]]
106
- """
107
- return super().__call__(*args, **kwargs)
116
+ def _to_async(self):
117
+ return self._async_evaluator
@@ -3,9 +3,14 @@ name: Coherence
3
3
  description: Evaluates coherence score for QA scenario
4
4
  model:
5
5
  api: chat
6
+ configuration:
7
+ type: azure_openai
8
+ azure_deployment: ${env:AZURE_DEPLOYMENT}
9
+ api_key: ${env:AZURE_OPENAI_API_KEY}
10
+ azure_endpoint: ${env:AZURE_OPENAI_ENDPOINT}
6
11
  parameters:
7
12
  temperature: 0.0
8
- max_tokens: 800
13
+ max_tokens: 1
9
14
  top_p: 1.0
10
15
  presence_penalty: 0
11
16
  frequency_penalty: 0
@@ -20,80 +25,38 @@ inputs:
20
25
 
21
26
  ---
22
27
  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 a QUERY and a RESPONSE.
28
- - **Tasks**: To complete your evaluation you will be asked to evaluate the Data in different ways.
28
+ 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.
29
29
 
30
30
  user:
31
- # Definition
32
- **Coherence** refers to the logical and orderly presentation of ideas in a response, allowing the reader to easily follow and understand the writer's train of thought. A coherent answer directly addresses the question with clear connections between sentences and paragraphs, using appropriate transitions and a logical sequence of ideas.
33
-
34
- # Ratings
35
- ## [Coherence: 1] (Incoherent Response)
36
- **Definition:** The response lacks coherence entirely. It consists of disjointed words or phrases that do not form complete or meaningful sentences. There is no logical connection to the question, making the response incomprehensible.
37
-
38
- **Examples:**
39
- **Query:** What are the benefits of renewable energy?
40
- **Response:** Wind sun green jump apple silence over.
41
-
42
- **Query:** Explain the process of photosynthesis.
43
- **Response:** Plants light water flying blue music.
44
-
45
- ## [Coherence: 2] (Poorly Coherent Response)
46
- **Definition:** The response shows minimal coherence with fragmented sentences and limited connection to the question. It contains some relevant keywords but lacks logical structure and clear relationships between ideas, making the overall message difficult to understand.
47
-
48
- **Examples:**
49
- **Query:** How does vaccination work?
50
- **Response:** Vaccines protect disease. Immune system fight. Health better.
51
-
52
- **Query:** Describe how a bill becomes a law.
53
- **Response:** Idea proposed. Congress discuss vote. President signs.
54
-
55
- ## [Coherence: 3] (Partially Coherent Response)
56
- **Definition:** The response partially addresses the question with some relevant information but exhibits issues in the logical flow and organization of ideas. Connections between sentences may be unclear or abrupt, requiring the reader to infer the links. The response may lack smooth transitions and may present ideas out of order.
57
-
58
- **Examples:**
59
- **Query:** What causes earthquakes?
60
- **Response:** Earthquakes happen when tectonic plates move suddenly. Energy builds up then releases. Ground shakes and can cause damage.
61
-
62
- **Query:** Explain the importance of the water cycle.
63
- **Response:** The water cycle moves water around Earth. Evaporation, then precipitation occurs. It supports life by distributing water.
64
-
65
- ## [Coherence: 4] (Coherent Response)
66
- **Definition:** The response is coherent and effectively addresses the question. Ideas are logically organized with clear connections between sentences and paragraphs. Appropriate transitions are used to guide the reader through the response, which flows smoothly and is easy to follow.
67
-
68
- **Examples:**
69
- **Query:** What is the water cycle and how does it work?
70
- **Response:** The water cycle is the continuous movement of water on Earth through processes like evaporation, condensation, and precipitation. Water evaporates from bodies of water, forms clouds through condensation, and returns to the surface as precipitation. This cycle is essential for distributing water resources globally.
71
-
72
- **Query:** Describe the role of mitochondria in cellular function.
73
- **Response:** Mitochondria are organelles that produce energy for the cell. They convert nutrients into ATP through cellular respiration. This energy powers various cellular activities, making mitochondria vital for cell survival.
74
-
75
- ## [Coherence: 5] (Highly Coherent Response)
76
- **Definition:** The response is exceptionally coherent, demonstrating sophisticated organization and flow. Ideas are presented in a logical and seamless manner, with excellent use of transitional phrases and cohesive devices. The connections between concepts are clear and enhance the reader's understanding. The response thoroughly addresses the question with clarity and precision.
77
-
78
- **Examples:**
79
- **Query:** Analyze the economic impacts of climate change on coastal cities.
80
- **Response:** Climate change significantly affects the economies of coastal cities through rising sea levels, increased flooding, and more intense storms. These environmental changes can damage infrastructure, disrupt businesses, and lead to costly repairs. For instance, frequent flooding can hinder transportation and commerce, while the threat of severe weather may deter investment and tourism. Consequently, cities may face increased expenses for disaster preparedness and mitigation efforts, straining municipal budgets and impacting economic growth.
81
-
82
- **Query:** Discuss the significance of the Monroe Doctrine in shaping U.S. foreign policy.
83
- **Response:** The Monroe Doctrine was a pivotal policy declared in 1823 that asserted U.S. opposition to European colonization in the Americas. By stating that any intervention by external powers in the Western Hemisphere would be viewed as a hostile act, it established the U.S. as a protector of the region. This doctrine shaped U.S. foreign policy by promoting isolation from European conflicts while justifying American influence and expansion in the hemisphere. Its long-term significance lies in its enduring influence on international relations and its role in defining the U.S. position in global affairs.
84
-
85
-
86
- # Data
87
- QUERY: {{query}}
88
- RESPONSE: {{response}}
89
-
90
-
91
- # Tasks
92
- ## 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:
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
31
+ Coherence of an answer is measured by how well all the sentences fit together and sound naturally as a whole. Consider the overall quality of the answer when evaluating coherence. Given the question and answer, score the coherence of answer between one to five stars using the following rating scale:
32
+ One star: the answer completely lacks coherence
33
+ Two stars: the answer mostly lacks coherence
34
+ Three stars: the answer is partially coherent
35
+ Four stars: the answer is mostly coherent
36
+ Five stars: the answer has perfect coherency
37
+
38
+ 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.
39
+
40
+ question: What is your favorite indoor activity and why do you enjoy it?
41
+ answer: I like pizza. The sun is shining.
42
+ stars: 1
43
+
44
+ question: Can you describe your favorite movie without giving away any spoilers?
45
+ answer: It is a science fiction movie. There are dinosaurs. The actors eat cake. People must stop the villain.
46
+ stars: 2
47
+
48
+ question: What are some benefits of regular exercise?
49
+ answer: Regular exercise improves your mood. A good workout also helps you sleep better. Trees are green.
50
+ stars: 3
51
+
52
+ question: How do you cope with stress in your daily life?
53
+ answer: I usually go for a walk to clear my head. Listening to music helps me relax as well. Stress is a part of life, but we can manage it through some activities.
54
+ stars: 4
55
+
56
+ question: What can you tell me about climate change and its effects on the environment?
57
+ answer: Climate change has far-reaching effects on the environment. Rising temperatures result in the melting of polar ice caps, contributing to sea-level rise. Additionally, more frequent and severe weather events, such as hurricanes and heatwaves, can cause disruption to ecosystems and human societies alike.
58
+ stars: 5
59
+
60
+ question: {{query}}
61
+ answer: {{response}}
62
+ stars:
@@ -3,6 +3,8 @@
3
3
  # ---------------------------------------------------------
4
4
 
5
5
  from ._content_safety import ContentSafetyEvaluator
6
+ from ._content_safety_base import ContentSafetyEvaluatorBase
7
+ from ._content_safety_chat import ContentSafetyChatEvaluator
6
8
  from ._hate_unfairness import HateUnfairnessEvaluator
7
9
  from ._self_harm import SelfHarmEvaluator
8
10
  from ._sexual import SexualEvaluator
@@ -14,4 +16,6 @@ __all__ = [
14
16
  "SelfHarmEvaluator",
15
17
  "HateUnfairnessEvaluator",
16
18
  "ContentSafetyEvaluator",
19
+ "ContentSafetyChatEvaluator",
20
+ "ContentSafetyEvaluatorBase",
17
21
  ]
@@ -2,135 +2,97 @@
2
2
  # Copyright (c) Microsoft Corporation. All rights reserved.
3
3
  # ---------------------------------------------------------
4
4
  from concurrent.futures import as_completed
5
- from typing import Callable, Dict, List, Union
6
5
 
7
6
  from promptflow.tracing import ThreadPoolExecutorWithContext as ThreadPoolExecutor
8
- from typing_extensions import overload, override
9
7
 
10
- from azure.ai.evaluation._evaluators._common import EvaluatorBase
11
- from azure.ai.evaluation._model_configurations import Conversation
12
- from azure.ai.evaluation._common._experimental import experimental
8
+ try:
9
+ from ._hate_unfairness import HateUnfairnessEvaluator
10
+ from ._self_harm import SelfHarmEvaluator
11
+ from ._sexual import SexualEvaluator
12
+ from ._violence import ViolenceEvaluator
13
+ except ImportError:
14
+ from _hate_unfairness import HateUnfairnessEvaluator
15
+ from _self_harm import SelfHarmEvaluator
16
+ from _sexual import SexualEvaluator
17
+ from _violence import ViolenceEvaluator
13
18
 
14
- from ._hate_unfairness import HateUnfairnessEvaluator
15
- from ._self_harm import SelfHarmEvaluator
16
- from ._sexual import SexualEvaluator
17
- from ._violence import ViolenceEvaluator
18
19
 
19
-
20
- @experimental
21
- class ContentSafetyEvaluator(EvaluatorBase[Union[str, float]]):
20
+ class ContentSafetyEvaluator:
22
21
  """
23
22
  Initialize a content safety evaluator configured to evaluate content safetry metrics for QA scenario.
24
23
 
25
- :param credential: The credential for connecting to Azure AI project. Required
26
- :type credential: ~azure.core.credentials.TokenCredential
27
24
  :param azure_ai_project: The scope of the Azure AI project.
28
25
  It contains subscription id, resource group, and project name.
29
26
  :type azure_ai_project: ~azure.ai.evaluation.AzureAIProject
30
- :param kwargs: Additional arguments to pass to the evaluator.
31
- :type kwargs: Any
27
+ :param parallel: If True, use parallel execution for evaluators. Else, use sequential execution.
28
+ Default is True.
29
+ :param credential: The credential for connecting to Azure AI project.
30
+ :type credential: ~azure.core.credentials.TokenCredential
32
31
  :return: A function that evaluates content-safety metrics for "question-answering" scenario.
33
-
34
- .. admonition:: Example:
35
-
36
- .. literalinclude:: ../samples/evaluation_samples_evaluate.py
37
- :start-after: [START content_safety_evaluator]
38
- :end-before: [END content_safety_evaluator]
39
- :language: python
40
- :dedent: 8
41
- :caption: Initialize and call a ContentSafetyEvaluator.
32
+ :rtype: Callable
33
+
34
+ **Usage**
35
+
36
+ .. code-block:: python
37
+
38
+ azure_ai_project = {
39
+ "subscription_id": "<subscription_id>",
40
+ "resource_group_name": "<resource_group_name>",
41
+ "project_name": "<project_name>",
42
+ }
43
+ eval_fn = ContentSafetyEvaluator(azure_ai_project)
44
+ result = eval_fn(
45
+ query="What is the capital of France?",
46
+ response="Paris.",
47
+ )
48
+
49
+ **Output format**
50
+
51
+ .. code-block:: python
52
+
53
+ {
54
+ "violence": "Medium",
55
+ "violence_score": 5.0,
56
+ "violence_reason": "Some reason",
57
+ "sexual": "Medium",
58
+ "sexual_score": 5.0,
59
+ "sexual_reason": "Some reason",
60
+ "self_harm": "Medium",
61
+ "self_harm_score": 5.0,
62
+ "self_harm_reason": "Some reason",
63
+ "hate_unfairness": "Medium",
64
+ "hate_unfairness_score": 5.0,
65
+ "hate_unfairness_reason": "Some reason"
66
+ }
42
67
  """
43
68
 
44
- id = "content_safety"
45
- """Evaluator identifier, experimental and to be used only with evaluation in cloud."""
46
-
47
- # TODO address 3579092 to re-enabled parallel evals.
48
- def __init__(self, credential, azure_ai_project, **kwargs):
49
- super().__init__()
50
- self._parallel = kwargs.pop("_parallel", False)
51
- self._evaluators: List[Callable[..., Dict[str, Union[str, float]]]] = [
52
- ViolenceEvaluator(credential, azure_ai_project),
53
- SexualEvaluator(credential, azure_ai_project),
54
- SelfHarmEvaluator(credential, azure_ai_project),
55
- HateUnfairnessEvaluator(credential, azure_ai_project),
69
+ def __init__(self, azure_ai_project: dict, parallel: bool = True, credential=None):
70
+ self._parallel = parallel
71
+ self._evaluators = [
72
+ ViolenceEvaluator(azure_ai_project, credential),
73
+ SexualEvaluator(azure_ai_project, credential),
74
+ SelfHarmEvaluator(azure_ai_project, credential),
75
+ HateUnfairnessEvaluator(azure_ai_project, credential),
56
76
  ]
57
77
 
58
- @overload
59
- def __call__(
60
- self,
61
- *,
62
- query: str,
63
- response: str,
64
- ) -> Dict[str, Union[str, float]]:
65
- """Evaluate a collection of content safety metrics for the given query/response pair
78
+ def __call__(self, *, query: str, response: str, **kwargs):
79
+ """
80
+ Evaluates content-safety metrics for "question-answering" scenario.
66
81
 
67
82
  :keyword query: The query to be evaluated.
68
83
  :paramtype query: str
69
84
  :keyword response: The response to be evaluated.
70
85
  :paramtype response: str
71
- :return: The content safety scores.
72
- :rtype: Dict[str, Union[str, float]]
73
- """
74
-
75
- @overload
76
- def __call__(
77
- self,
78
- *,
79
- conversation: Conversation,
80
- ) -> Dict[str, Union[float, Dict[str, List[Union[str, float]]]]]:
81
- """Evaluate a collection of content safety metrics for a conversation
82
-
83
- :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
84
- key "messages", and potentially a global context under the key "context". Conversation turns are expected
85
- to be dictionaries with keys "content", "role", and possibly "context".
86
- :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
87
- :return: The content safety scores.
88
- :rtype: Dict[str, Union[float, Dict[str, List[Union[str, float]]]]]
89
- """
90
-
91
- @override
92
- def __call__( # pylint: disable=docstring-missing-param
93
- self,
94
- *args,
95
- **kwargs,
96
- ):
97
- """Evaluate a collection of content safety metrics for the given query/response pair or conversation.
98
- This inputs must supply either a query AND response, or a conversation, but not both.
99
-
100
- :keyword query: The query to evaluate.
101
- :paramtype query: Optional[str]
102
- :keyword response: The response to evaluate.
103
- :paramtype response: Optional[str]
104
- :keyword conversation: The conversation to evaluate. Expected to contain a list of conversation turns under the
105
- key "messages", and potentially a global context under the key "context". Conversation turns are expected
106
- to be dictionaries with keys "content", "role", and possibly "context".
107
- :paramtype conversation: Optional[~azure.ai.evaluation.Conversation]
108
- :return: The evaluation result.
109
- :rtype: Union[Dict[str, Union[str, float]], Dict[str, Union[float, Dict[str, List[Union[str, float]]]]]]
110
- """
111
- return super().__call__(*args, **kwargs)
112
-
113
- @override
114
- async def _do_eval(self, eval_input: Dict) -> Dict[str, Union[str, float]]:
115
- """Perform the evaluation using the Azure AI RAI service.
116
- The exact evaluation performed is determined by the evaluation metric supplied
117
- by the child class initializer.
118
-
119
- :param eval_input: The input to the evaluation function.
120
- :type eval_input: Dict
121
- :return: The evaluation result.
122
- :rtype: Dict
86
+ :keyword parallel: Whether to evaluate in parallel.
87
+ :paramtype parallel: bool
88
+ :return: The scores for content-safety.
89
+ :rtype: dict
123
90
  """
124
- query = eval_input.get("query", None)
125
- response = eval_input.get("response", None)
126
- conversation = eval_input.get("conversation", None)
127
- results: Dict[str, Union[str, float]] = {}
128
- # TODO fix this to not explode on empty optional inputs (PF SKD error)
91
+ results = {}
129
92
  if self._parallel:
130
93
  with ThreadPoolExecutor() as executor:
131
- # pylint: disable=no-value-for-parameter
132
94
  futures = {
133
- executor.submit(query=query, response=response, conversation=conversation): evaluator
95
+ executor.submit(evaluator, query=query, response=response, **kwargs): evaluator
134
96
  for evaluator in self._evaluators
135
97
  }
136
98
 
@@ -138,7 +100,7 @@ class ContentSafetyEvaluator(EvaluatorBase[Union[str, float]]):
138
100
  results.update(future.result())
139
101
  else:
140
102
  for evaluator in self._evaluators:
141
- result = evaluator(query=query, response=response, conversation=conversation)
103
+ result = evaluator(query=query, response=response, **kwargs)
142
104
  results.update(result)
143
105
 
144
106
  return results
@@ -1,54 +1,64 @@
1
1
  # ---------------------------------------------------------
2
2
  # Copyright (c) Microsoft Corporation. All rights reserved.
3
3
  # ---------------------------------------------------------
4
+
4
5
  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
6
+
7
+ from azure.ai.evaluation._common.constants import EvaluationMetrics
8
+ from azure.ai.evaluation._common.rai_service import evaluate_with_rai_service
9
+ from azure.ai.evaluation._exceptions import ErrorBlame, ErrorCategory, ErrorTarget, EvaluationException
10
10
 
11
11
 
12
- class ContentSafetyMultimodalEvaluatorBase(ABC):
12
+ class ContentSafetyEvaluatorBase(ABC):
13
13
  """
14
14
  Initialize a evaluator for a specified Evaluation Metric. Base class that is not
15
15
  meant to be instantiated by users.
16
16
 
17
+
17
18
  :param metric: The metric to be evaluated.
18
19
  :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
20
  :param azure_ai_project: The scope of the Azure AI project.
22
21
  It contains subscription id, resource group, and project name.
23
22
  :type azure_ai_project: ~azure.ai.evaluation.AzureAIProject
23
+ :param credential: The credential for connecting to Azure AI project.
24
+ :type credential: ~azure.core.credentials.TokenCredential
24
25
  """
25
26
 
26
- def __init__(
27
- self,
28
- metric: Union[EvaluationMetrics, _InternalEvaluationMetrics],
29
- credential: TokenCredential,
30
- azure_ai_project,
31
- ):
27
+ def __init__(self, metric: EvaluationMetrics, azure_ai_project: dict, credential=None):
32
28
  self._metric = metric
33
29
  self._azure_ai_project = azure_ai_project
34
30
  self._credential = credential
35
31
 
36
- async def __call__(self, *, conversation, **kwargs):
32
+ async def __call__(self, *, query: str, response: str, **kwargs):
37
33
  """
38
34
  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
35
+
36
+ :keyword query: The query to be evaluated.
37
+ :paramtype query: str
38
+ :keyword response: The response to be evaluated.
39
+ :paramtype response: str
42
40
  :return: The evaluation score computation based on the Content Safety metric (self.metric).
43
- :rtype: Dict[str, Union[float, str]]
41
+ :rtype: Any
44
42
  """
45
- # validate inputs
46
- validate_conversation(conversation)
47
- messages = conversation["messages"]
43
+ # Validate inputs
44
+ # Raises value error if failed, so execution alone signifies success.
45
+ if not (query and query.strip() and query != "None") or not (
46
+ response and response.strip() and response != "None"
47
+ ):
48
+ msg = "Both 'query' and 'response' must be non-empty strings."
49
+ raise EvaluationException(
50
+ message=msg,
51
+ internal_message=msg,
52
+ error_category=ErrorCategory.MISSING_FIELD,
53
+ error_blame=ErrorBlame.USER_ERROR,
54
+ error_target=ErrorTarget.CONTENT_SAFETY_CHAT_EVALUATOR,
55
+ )
56
+
48
57
  # Run score computation based on supplied metric.
49
- result = await evaluate_with_rai_service_multimodal(
50
- messages=messages,
58
+ result = await evaluate_with_rai_service(
51
59
  metric_name=self._metric,
60
+ query=query,
61
+ response=response,
52
62
  project_scope=self._azure_ai_project,
53
63
  credential=self._credential,
54
64
  )