azure-ai-evaluation 1.3.0__py3-none-any.whl → 1.4.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.
Potentially problematic release.
This version of azure-ai-evaluation might be problematic. Click here for more details.
- azure/ai/evaluation/__init__.py +43 -1
- azure/ai/evaluation/_azure/_models.py +6 -6
- azure/ai/evaluation/_common/constants.py +6 -2
- azure/ai/evaluation/_common/rai_service.py +38 -4
- azure/ai/evaluation/_common/raiclient/__init__.py +34 -0
- azure/ai/evaluation/_common/raiclient/_client.py +128 -0
- azure/ai/evaluation/_common/raiclient/_configuration.py +87 -0
- azure/ai/evaluation/_common/raiclient/_model_base.py +1235 -0
- azure/ai/evaluation/_common/raiclient/_patch.py +20 -0
- azure/ai/evaluation/_common/raiclient/_serialization.py +2050 -0
- azure/ai/evaluation/_common/raiclient/_version.py +9 -0
- azure/ai/evaluation/_common/raiclient/aio/__init__.py +29 -0
- azure/ai/evaluation/_common/raiclient/aio/_client.py +130 -0
- azure/ai/evaluation/_common/raiclient/aio/_configuration.py +87 -0
- azure/ai/evaluation/_common/raiclient/aio/_patch.py +20 -0
- azure/ai/evaluation/_common/raiclient/aio/operations/__init__.py +25 -0
- azure/ai/evaluation/_common/raiclient/aio/operations/_operations.py +981 -0
- azure/ai/evaluation/_common/raiclient/aio/operations/_patch.py +20 -0
- azure/ai/evaluation/_common/raiclient/models/__init__.py +60 -0
- azure/ai/evaluation/_common/raiclient/models/_enums.py +18 -0
- azure/ai/evaluation/_common/raiclient/models/_models.py +651 -0
- azure/ai/evaluation/_common/raiclient/models/_patch.py +20 -0
- azure/ai/evaluation/_common/raiclient/operations/__init__.py +25 -0
- azure/ai/evaluation/_common/raiclient/operations/_operations.py +1225 -0
- azure/ai/evaluation/_common/raiclient/operations/_patch.py +20 -0
- azure/ai/evaluation/_common/raiclient/py.typed +1 -0
- azure/ai/evaluation/_common/utils.py +22 -2
- azure/ai/evaluation/_constants.py +7 -0
- azure/ai/evaluation/_converters/__init__.py +3 -0
- azure/ai/evaluation/_converters/_ai_services.py +804 -0
- azure/ai/evaluation/_converters/_models.py +302 -0
- azure/ai/evaluation/_evaluate/_batch_run/__init__.py +10 -3
- azure/ai/evaluation/_evaluate/_batch_run/_run_submitter_client.py +104 -0
- azure/ai/evaluation/_evaluate/_batch_run/batch_clients.py +82 -0
- azure/ai/evaluation/_evaluate/_eval_run.py +1 -1
- azure/ai/evaluation/_evaluate/_evaluate.py +31 -2
- azure/ai/evaluation/_evaluators/_bleu/_bleu.py +23 -3
- azure/ai/evaluation/_evaluators/_code_vulnerability/__init__.py +5 -0
- azure/ai/evaluation/_evaluators/_code_vulnerability/_code_vulnerability.py +120 -0
- azure/ai/evaluation/_evaluators/_coherence/_coherence.py +21 -2
- azure/ai/evaluation/_evaluators/_common/_base_eval.py +43 -3
- azure/ai/evaluation/_evaluators/_common/_base_multi_eval.py +3 -1
- azure/ai/evaluation/_evaluators/_common/_base_prompty_eval.py +43 -4
- azure/ai/evaluation/_evaluators/_common/_base_rai_svc_eval.py +16 -4
- azure/ai/evaluation/_evaluators/_content_safety/_content_safety.py +42 -5
- azure/ai/evaluation/_evaluators/_content_safety/_hate_unfairness.py +15 -0
- azure/ai/evaluation/_evaluators/_content_safety/_self_harm.py +15 -0
- azure/ai/evaluation/_evaluators/_content_safety/_sexual.py +15 -0
- azure/ai/evaluation/_evaluators/_content_safety/_violence.py +15 -0
- azure/ai/evaluation/_evaluators/_f1_score/_f1_score.py +28 -4
- azure/ai/evaluation/_evaluators/_fluency/_fluency.py +21 -2
- azure/ai/evaluation/_evaluators/_gleu/_gleu.py +26 -3
- azure/ai/evaluation/_evaluators/_groundedness/_groundedness.py +21 -3
- azure/ai/evaluation/_evaluators/_intent_resolution/__init__.py +7 -0
- azure/ai/evaluation/_evaluators/_intent_resolution/_intent_resolution.py +152 -0
- azure/ai/evaluation/_evaluators/_intent_resolution/intent_resolution.prompty +161 -0
- azure/ai/evaluation/_evaluators/_meteor/_meteor.py +26 -3
- azure/ai/evaluation/_evaluators/_qa/_qa.py +51 -7
- azure/ai/evaluation/_evaluators/_relevance/_relevance.py +26 -2
- azure/ai/evaluation/_evaluators/_response_completeness/__init__.py +7 -0
- azure/ai/evaluation/_evaluators/_response_completeness/_response_completeness.py +157 -0
- azure/ai/evaluation/_evaluators/_response_completeness/response_completeness.prompty +99 -0
- azure/ai/evaluation/_evaluators/_retrieval/_retrieval.py +21 -2
- azure/ai/evaluation/_evaluators/_rouge/_rouge.py +113 -4
- azure/ai/evaluation/_evaluators/_service_groundedness/_service_groundedness.py +23 -3
- azure/ai/evaluation/_evaluators/_similarity/_similarity.py +24 -5
- azure/ai/evaluation/_evaluators/_task_adherence/__init__.py +7 -0
- azure/ai/evaluation/_evaluators/_task_adherence/_task_adherence.py +148 -0
- azure/ai/evaluation/_evaluators/_task_adherence/task_adherence.prompty +117 -0
- azure/ai/evaluation/_evaluators/_tool_call_accuracy/__init__.py +9 -0
- azure/ai/evaluation/_evaluators/_tool_call_accuracy/_tool_call_accuracy.py +292 -0
- azure/ai/evaluation/_evaluators/_tool_call_accuracy/tool_call_accuracy.prompty +71 -0
- azure/ai/evaluation/_evaluators/_ungrounded_attributes/__init__.py +5 -0
- azure/ai/evaluation/_evaluators/_ungrounded_attributes/_ungrounded_attributes.py +103 -0
- azure/ai/evaluation/_evaluators/_xpia/xpia.py +2 -0
- azure/ai/evaluation/_exceptions.py +5 -0
- azure/ai/evaluation/_legacy/__init__.py +3 -0
- azure/ai/evaluation/_legacy/_batch_engine/__init__.py +9 -0
- azure/ai/evaluation/_legacy/_batch_engine/_config.py +45 -0
- azure/ai/evaluation/_legacy/_batch_engine/_engine.py +368 -0
- azure/ai/evaluation/_legacy/_batch_engine/_exceptions.py +88 -0
- azure/ai/evaluation/_legacy/_batch_engine/_logging.py +292 -0
- azure/ai/evaluation/_legacy/_batch_engine/_openai_injector.py +23 -0
- azure/ai/evaluation/_legacy/_batch_engine/_result.py +99 -0
- azure/ai/evaluation/_legacy/_batch_engine/_run.py +121 -0
- azure/ai/evaluation/_legacy/_batch_engine/_run_storage.py +128 -0
- azure/ai/evaluation/_legacy/_batch_engine/_run_submitter.py +217 -0
- azure/ai/evaluation/_legacy/_batch_engine/_status.py +25 -0
- azure/ai/evaluation/_legacy/_batch_engine/_trace.py +105 -0
- azure/ai/evaluation/_legacy/_batch_engine/_utils.py +82 -0
- azure/ai/evaluation/_legacy/_batch_engine/_utils_deprecated.py +131 -0
- azure/ai/evaluation/_legacy/prompty/__init__.py +36 -0
- azure/ai/evaluation/_legacy/prompty/_connection.py +182 -0
- azure/ai/evaluation/_legacy/prompty/_exceptions.py +59 -0
- azure/ai/evaluation/_legacy/prompty/_prompty.py +313 -0
- azure/ai/evaluation/_legacy/prompty/_utils.py +545 -0
- azure/ai/evaluation/_legacy/prompty/_yaml_utils.py +99 -0
- azure/ai/evaluation/_red_team/__init__.py +3 -0
- azure/ai/evaluation/_red_team/_attack_objective_generator.py +192 -0
- azure/ai/evaluation/_red_team/_attack_strategy.py +42 -0
- azure/ai/evaluation/_red_team/_callback_chat_target.py +74 -0
- azure/ai/evaluation/_red_team/_default_converter.py +21 -0
- azure/ai/evaluation/_red_team/_red_team.py +1858 -0
- azure/ai/evaluation/_red_team/_red_team_result.py +246 -0
- azure/ai/evaluation/_red_team/_utils/__init__.py +3 -0
- azure/ai/evaluation/_red_team/_utils/constants.py +64 -0
- azure/ai/evaluation/_red_team/_utils/formatting_utils.py +164 -0
- azure/ai/evaluation/_red_team/_utils/logging_utils.py +139 -0
- azure/ai/evaluation/_red_team/_utils/strategy_utils.py +188 -0
- azure/ai/evaluation/_safety_evaluation/__init__.py +1 -1
- azure/ai/evaluation/_safety_evaluation/_generated_rai_client.py +0 -0
- azure/ai/evaluation/_safety_evaluation/_safety_evaluation.py +251 -150
- azure/ai/evaluation/_version.py +1 -1
- azure/ai/evaluation/simulator/_adversarial_scenario.py +3 -1
- azure/ai/evaluation/simulator/_adversarial_simulator.py +54 -27
- azure/ai/evaluation/simulator/_model_tools/_generated_rai_client.py +145 -0
- azure/ai/evaluation/simulator/_model_tools/_rai_client.py +71 -1
- {azure_ai_evaluation-1.3.0.dist-info → azure_ai_evaluation-1.4.0.dist-info}/METADATA +69 -15
- azure_ai_evaluation-1.4.0.dist-info/RECORD +197 -0
- {azure_ai_evaluation-1.3.0.dist-info → azure_ai_evaluation-1.4.0.dist-info}/WHEEL +1 -1
- azure_ai_evaluation-1.3.0.dist-info/RECORD +0 -119
- {azure_ai_evaluation-1.3.0.dist-info → azure_ai_evaluation-1.4.0.dist-info}/NOTICE.txt +0 -0
- {azure_ai_evaluation-1.3.0.dist-info → azure_ai_evaluation-1.4.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# ---------------------------------------------------------
|
|
2
|
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3
|
+
# ---------------------------------------------------------
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import List, Optional, Dict, Any
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
class RiskCategory(str, Enum):
|
|
12
|
+
"""Risk categories for attack objectives."""
|
|
13
|
+
HateUnfairness = "hate_unfairness"
|
|
14
|
+
Violence = "violence"
|
|
15
|
+
Sexual = "sexual"
|
|
16
|
+
SelfHarm = "self_harm"
|
|
17
|
+
|
|
18
|
+
class _AttackObjectiveGenerator:
|
|
19
|
+
"""Generator for creating attack objectives.
|
|
20
|
+
|
|
21
|
+
:param risk_categories: List of risk categories to generate attack objectives for (optional if custom_attack_seed_prompts is provided)
|
|
22
|
+
:type risk_categories: Optional[List[RiskCategory]]
|
|
23
|
+
:param num_objectives: Number of objectives to generate per risk category
|
|
24
|
+
:type num_objectives: int
|
|
25
|
+
:param application_scenario: Description of the application scenario for context
|
|
26
|
+
:type application_scenario: Optional[str]
|
|
27
|
+
:param custom_attack_seed_prompts: Path to a JSON file containing custom attack seed prompts (can be absolute or relative path)
|
|
28
|
+
:type custom_attack_seed_prompts: Optional[str]
|
|
29
|
+
"""
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
risk_categories: Optional[List[RiskCategory]] = None,
|
|
33
|
+
num_objectives: int = 10,
|
|
34
|
+
application_scenario: Optional[str] = None,
|
|
35
|
+
custom_attack_seed_prompts: Optional[str] = None,
|
|
36
|
+
):
|
|
37
|
+
self.risk_categories = risk_categories or []
|
|
38
|
+
self.num_objectives = num_objectives
|
|
39
|
+
self.application_scenario = application_scenario
|
|
40
|
+
self.custom_attack_seed_prompts = custom_attack_seed_prompts
|
|
41
|
+
self.logger = logging.getLogger("_AttackObjectiveGenerator")
|
|
42
|
+
|
|
43
|
+
# If custom_attack_seed_prompts is provided, validate and load them
|
|
44
|
+
self.custom_prompts = None
|
|
45
|
+
self.validated_prompts = []
|
|
46
|
+
self.valid_prompts_by_category = {}
|
|
47
|
+
|
|
48
|
+
if custom_attack_seed_prompts:
|
|
49
|
+
self._load_and_validate_custom_prompts()
|
|
50
|
+
|
|
51
|
+
def _load_and_validate_custom_prompts(self) -> None:
|
|
52
|
+
"""Load and validate custom attack seed prompts from the provided file path."""
|
|
53
|
+
if not self.custom_attack_seed_prompts:
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
# Handle both absolute and relative paths
|
|
57
|
+
custom_prompts_path = Path(self.custom_attack_seed_prompts)
|
|
58
|
+
|
|
59
|
+
# Convert to absolute path if it's a relative path
|
|
60
|
+
if not custom_prompts_path.is_absolute():
|
|
61
|
+
self.logger.info(f"Converting relative path '{custom_prompts_path}' to absolute path")
|
|
62
|
+
custom_prompts_path = Path.cwd() / custom_prompts_path
|
|
63
|
+
|
|
64
|
+
self.logger.debug(f"Using absolute path: {custom_prompts_path}")
|
|
65
|
+
|
|
66
|
+
# Check if the file exists
|
|
67
|
+
if not custom_prompts_path.exists():
|
|
68
|
+
raise ValueError(f"Custom attack seed prompts file not found: {custom_prompts_path}")
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
# Load JSON file
|
|
72
|
+
with open(custom_prompts_path, 'r', encoding='utf-8') as f:
|
|
73
|
+
self.custom_prompts = json.load(f)
|
|
74
|
+
|
|
75
|
+
# Validate that it's a list
|
|
76
|
+
if not isinstance(self.custom_prompts, list):
|
|
77
|
+
raise ValueError(f"Custom attack seed prompts must be a JSON array, got {type(self.custom_prompts)}, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
78
|
+
|
|
79
|
+
self.logger.info(f"Loaded {len(self.custom_prompts)} prompts from {self.custom_attack_seed_prompts}")
|
|
80
|
+
|
|
81
|
+
# Initialize dictionary for categorized prompts
|
|
82
|
+
for risk_category in RiskCategory:
|
|
83
|
+
self.valid_prompts_by_category[risk_category.value] = []
|
|
84
|
+
|
|
85
|
+
# Process each prompt and validate format
|
|
86
|
+
valid_prompts_count = 0
|
|
87
|
+
invalid_prompts_count = 0
|
|
88
|
+
for i, prompt in enumerate(self.custom_prompts):
|
|
89
|
+
try:
|
|
90
|
+
# Check required fields
|
|
91
|
+
if not isinstance(prompt, dict):
|
|
92
|
+
self.logger.warning(f"Skipping prompt {i}: not a JSON object")
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
if "metadata" not in prompt:
|
|
96
|
+
self.logger.warning(f"Skipping prompt {i}: missing 'metadata' field")
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
if "messages" not in prompt or not prompt["messages"]:
|
|
100
|
+
self.logger.warning(f"Skipping prompt {i}: missing or empty 'messages' field")
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
# Check metadata structure
|
|
104
|
+
metadata = prompt["metadata"]
|
|
105
|
+
if not isinstance(metadata, dict):
|
|
106
|
+
self.logger.warning(f"Skipping prompt {i}: 'metadata' is not a JSON object, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
if "target_harms" not in metadata or not metadata["target_harms"]:
|
|
110
|
+
self.logger.warning(f"Skipping prompt {i}: missing or empty 'target_harms' in metadata, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
# Check target_harms structure
|
|
114
|
+
valid_risk_types = {cat.value for cat in RiskCategory}
|
|
115
|
+
valid_risk_found = False
|
|
116
|
+
prompt_categories = []
|
|
117
|
+
|
|
118
|
+
for harm in metadata["target_harms"]:
|
|
119
|
+
if not isinstance(harm, dict):
|
|
120
|
+
self.logger.warning(f"Skipping harm in prompt {i}: not a JSON object, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
121
|
+
continue
|
|
122
|
+
|
|
123
|
+
if "risk-type" not in harm:
|
|
124
|
+
self.logger.warning(f"Skipping harm in prompt {i}: missing 'risk-type' field, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
risk_type = harm.get("risk-type", "")
|
|
128
|
+
if risk_type not in valid_risk_types:
|
|
129
|
+
self.logger.warning(f"Skipping harm in prompt {i}: invalid risk-type '{risk_type}'. Valid types: {valid_risk_types}. see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
prompt_categories.append(risk_type)
|
|
133
|
+
valid_risk_found = True
|
|
134
|
+
|
|
135
|
+
if not valid_risk_found:
|
|
136
|
+
self.logger.warning(f"Skipping prompt {i}: no valid risk types found. See https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
137
|
+
continue
|
|
138
|
+
|
|
139
|
+
# Check messages structure
|
|
140
|
+
messages = prompt["messages"]
|
|
141
|
+
if not isinstance(messages, list) or not messages:
|
|
142
|
+
self.logger.warning(f"Skipping prompt {i}: 'messages' is not a list or is empty, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
143
|
+
continue
|
|
144
|
+
|
|
145
|
+
message = messages[0]
|
|
146
|
+
if not isinstance(message, dict):
|
|
147
|
+
self.logger.warning(f"Skipping prompt {i}: first message is not a JSON object, see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
148
|
+
continue
|
|
149
|
+
|
|
150
|
+
if "role" not in message or message["role"] != "user":
|
|
151
|
+
self.logger.warning(f"Skipping prompt {i}: first message must have role='user', see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
152
|
+
continue
|
|
153
|
+
|
|
154
|
+
if "content" not in message or not message["content"]:
|
|
155
|
+
self.logger.warning(f"Skipping prompt {i}: first message missing or empty 'content', see https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
# If we got here, the prompt is valid
|
|
159
|
+
self.validated_prompts.append(prompt)
|
|
160
|
+
valid_prompts_count += 1
|
|
161
|
+
|
|
162
|
+
# Add to the appropriate categories
|
|
163
|
+
for category in prompt_categories:
|
|
164
|
+
self.valid_prompts_by_category[category].append(prompt)
|
|
165
|
+
|
|
166
|
+
except Exception as e:
|
|
167
|
+
self.logger.warning(f"Error validating prompt {i}: {str(e)}")
|
|
168
|
+
invalid_prompts_count += 1
|
|
169
|
+
|
|
170
|
+
# Check if we have at least one valid prompt
|
|
171
|
+
if valid_prompts_count == 0:
|
|
172
|
+
raise ValueError("No valid prompts found in custom attack seed prompts file. See https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
173
|
+
|
|
174
|
+
self.logger.info(f"Loaded {valid_prompts_count} valid prompts from custom attack seed prompts file")
|
|
175
|
+
|
|
176
|
+
if invalid_prompts_count > 0:
|
|
177
|
+
self.logger.warning(f"Skipped {invalid_prompts_count} invalid prompts")
|
|
178
|
+
|
|
179
|
+
# Log the breakdown by risk category
|
|
180
|
+
category_counts = {cat: len(prompts) for cat, prompts in self.valid_prompts_by_category.items() if len(prompts) > 0}
|
|
181
|
+
self.logger.info(f"Prompt distribution by risk category: {category_counts}")
|
|
182
|
+
|
|
183
|
+
# Automatically extract risk categories from valid prompts if not provided
|
|
184
|
+
if not self.risk_categories:
|
|
185
|
+
categories_with_prompts = [cat for cat, prompts in self.valid_prompts_by_category.items() if prompts]
|
|
186
|
+
self.risk_categories = [RiskCategory(cat) for cat in categories_with_prompts]
|
|
187
|
+
self.logger.info(f"Automatically set risk categories based on valid prompts: {[cat.value for cat in self.risk_categories]}")
|
|
188
|
+
|
|
189
|
+
except json.JSONDecodeError as e:
|
|
190
|
+
raise ValueError(f"Failed to parse custom attack seed prompts file: {str(e)}. See https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
191
|
+
except Exception as e:
|
|
192
|
+
raise ValueError(f"Error loading custom attack seed prompts: {str(e)}. See https://aka.ms/airedteamingagent-howtodoc for more information")
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# ---------------------------------------------------------
|
|
2
|
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3
|
+
# ---------------------------------------------------------
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import List
|
|
6
|
+
|
|
7
|
+
class AttackStrategy(Enum):
|
|
8
|
+
"""Strategies for attacks."""
|
|
9
|
+
EASY = "easy"
|
|
10
|
+
MODERATE = "moderate"
|
|
11
|
+
DIFFICULT = "difficult"
|
|
12
|
+
AnsiAttack = "ansi_attack"
|
|
13
|
+
AsciiArt = "ascii_art"
|
|
14
|
+
AsciiSmuggler = "ascii_smuggler"
|
|
15
|
+
Atbash = "atbash"
|
|
16
|
+
Base64 = "base64"
|
|
17
|
+
Binary = "binary"
|
|
18
|
+
Caesar = "caesar"
|
|
19
|
+
CharacterSpace = "character_space"
|
|
20
|
+
CharSwap = "char_swap"
|
|
21
|
+
Diacritic = "diacritic"
|
|
22
|
+
Flip = "flip"
|
|
23
|
+
Leetspeak = "leetspeak"
|
|
24
|
+
Morse = "morse"
|
|
25
|
+
ROT13 = "rot13"
|
|
26
|
+
SuffixAppend = "suffix_append"
|
|
27
|
+
StringJoin = "string_join"
|
|
28
|
+
Tense = "tense"
|
|
29
|
+
UnicodeConfusable = "unicode_confusable"
|
|
30
|
+
UnicodeSubstitution = "unicode_substitution"
|
|
31
|
+
Url = "url"
|
|
32
|
+
Baseline = "baseline"
|
|
33
|
+
Jailbreak = "jailbreak"
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def Compose(cls, items: List["AttackStrategy"]) -> List["AttackStrategy"]:
|
|
37
|
+
for item in items:
|
|
38
|
+
if not isinstance(item, cls):
|
|
39
|
+
raise ValueError("All items must be instances of AttackStrategy")
|
|
40
|
+
if len(items) > 2:
|
|
41
|
+
raise ValueError("Composed strategies must have at most 2 items")
|
|
42
|
+
return items
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# ---------------------------------------------------------
|
|
2
|
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3
|
+
# ---------------------------------------------------------
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
from pyrit.models import (
|
|
8
|
+
PromptRequestResponse,
|
|
9
|
+
construct_response_from_request,
|
|
10
|
+
)
|
|
11
|
+
from pyrit.prompt_target import PromptChatTarget
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _CallbackChatTarget(PromptChatTarget):
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
*,
|
|
20
|
+
callback: Callable[[List[Dict], bool, Optional[str], Optional[Dict[str, Any]]], Dict],
|
|
21
|
+
stream: bool = False,
|
|
22
|
+
) -> None:
|
|
23
|
+
"""
|
|
24
|
+
Initializes an instance of the _CallbackChatTarget class.
|
|
25
|
+
|
|
26
|
+
It is intended to be used with PyRIT where users define a callback function
|
|
27
|
+
that handles sending a prompt to a target and receiving a response.
|
|
28
|
+
The _CallbackChatTarget class is a wrapper around the callback function that allows it to be used
|
|
29
|
+
as a target in the PyRIT framework.
|
|
30
|
+
For that reason, it merely handles additional functionality such as memory.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
callback (Callable): The callback function that sends a prompt to a target and receives a response.
|
|
34
|
+
stream (bool, optional): Indicates whether the target supports streaming. Defaults to False.
|
|
35
|
+
"""
|
|
36
|
+
PromptChatTarget.__init__(self)
|
|
37
|
+
self._callback = callback
|
|
38
|
+
self._stream = stream
|
|
39
|
+
|
|
40
|
+
async def send_prompt_async(self, *, prompt_request: PromptRequestResponse) -> PromptRequestResponse:
|
|
41
|
+
|
|
42
|
+
self._validate_request(prompt_request=prompt_request)
|
|
43
|
+
request = prompt_request.request_pieces[0]
|
|
44
|
+
|
|
45
|
+
messages = self._memory.get_chat_messages_with_conversation_id(conversation_id=request.conversation_id)
|
|
46
|
+
|
|
47
|
+
messages.append(request.to_chat_message())
|
|
48
|
+
|
|
49
|
+
logger.info(f"Sending the following prompt to the prompt target: {request}")
|
|
50
|
+
|
|
51
|
+
# response_context contains "messages", "stream", "session_state, "context"
|
|
52
|
+
response_context = await self._callback(messages=messages, stream=self._stream, session_state=None, context=None) # type: ignore
|
|
53
|
+
|
|
54
|
+
response_text = response_context["messages"][-1]["content"]
|
|
55
|
+
response_entry = construct_response_from_request(
|
|
56
|
+
request=request, response_text_pieces=[response_text]
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
logger.info(
|
|
60
|
+
"Received the following response from the prompt target"
|
|
61
|
+
+ f"{response_text}"
|
|
62
|
+
)
|
|
63
|
+
return response_entry
|
|
64
|
+
|
|
65
|
+
def _validate_request(self, *, prompt_request: PromptRequestResponse) -> None:
|
|
66
|
+
if len(prompt_request.request_pieces) != 1:
|
|
67
|
+
raise ValueError("This target only supports a single prompt request piece.")
|
|
68
|
+
|
|
69
|
+
if prompt_request.request_pieces[0].converted_value_data_type != "text":
|
|
70
|
+
raise ValueError("This target only supports text prompt input.")
|
|
71
|
+
|
|
72
|
+
def is_json_response_supported(self) -> bool:
|
|
73
|
+
"""Indicates that this target supports JSON response format."""
|
|
74
|
+
return False
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from pyrit.models import PromptDataType
|
|
2
|
+
from pyrit.prompt_converter import ConverterResult, PromptConverter
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class _DefaultConverter(PromptConverter):
|
|
6
|
+
|
|
7
|
+
async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult:
|
|
8
|
+
"""
|
|
9
|
+
Simple converter that does nothing to the prompt and returns it as is.
|
|
10
|
+
"""
|
|
11
|
+
if not self.input_supported(input_type):
|
|
12
|
+
raise ValueError("Input type not supported")
|
|
13
|
+
|
|
14
|
+
result = ConverterResult(output_text=prompt, output_type="text")
|
|
15
|
+
return result
|
|
16
|
+
|
|
17
|
+
def input_supported(self, input_type: PromptDataType) -> bool:
|
|
18
|
+
return input_type == "text"
|
|
19
|
+
|
|
20
|
+
def output_supported(self, output_type: PromptDataType) -> bool:
|
|
21
|
+
return output_type == "text"
|