DeepTeam is a framework to red team LLMs and AI agents.
rename Attempt to Probe
A-Vamshi940a374d588c
diff --git a/deepteam/attacks/multi_turn/bad_likert_judge/bad_likert_judge.py b/deepteam/attacks/multi_turn/bad_likert_judge/bad_likert_judge.pyindex 17a7a724..f2be7287 100644--- a/deepteam/attacks/multi_turn/bad_likert_judge/bad_likert_judge.py+++ b/deepteam/attacks/multi_turn/bad_likert_judge/bad_likert_judge.py@@ -50,7 +50,7 @@ class BadLikertJudge(BaseMultiTurnAttack):"max_backtracks": AttackParameter(type="integer",default=3,- description="Consecutive failed attempts tolerated before stopping.",+ description="Consecutive failed probes tolerated before stopping.",),}@@ -87,7 +87,7 @@ class BadLikertJudge(BaseMultiTurnAttack):attack = progression.goalbacktracks = 0# A turn can fail to land -- the simulator errors, or balks at writing- # the attack -- so the attempt budget is larger than the turn budget.+ # the attack -- so the probe budget is larger than the turn budget.attempts_remaining = self.num_turns + self.max_backtracksprogress = create_progress()diff --git a/deepteam/attacks/multi_turn/crescendo_jailbreaking/crescendo_jailbreaking.py b/deepteam/attacks/multi_turn/crescendo_jailbreaking/crescendo_jailbreaking.pyindex 45096558..93488622 100644--- a/deepteam/attacks/multi_turn/crescendo_jailbreaking/crescendo_jailbreaking.py+++ b/deepteam/attacks/multi_turn/crescendo_jailbreaking/crescendo_jailbreaking.py@@ -125,17 +125,18 @@ class CrescendoJailbreaking(BaseMultiTurnAttack):refusal_note = Noneupdate_pbar(progress, rounds_pbar)- attempt = progression.probe(attack)- self._remember_target_exchange(attempt)- progression.commit(attempt)+ probe = progression.probe(attack)+ self._remember_target_exchange(probe)+ progression.commit(probe)update_pbar(progress, rounds_pbar)is_refusal, rationale = self._refusal_score(- progression, attempt.response.content+ progression, probe.output.content)update_pbar(progress, rounds_pbar)if is_refusal:+ progression.score_probe(probe, 0.0, rationale)backtracks += 1eval_flag = Falserefusal_note = REFUSAL_NOTE.format(rationale=rationale)@@ -154,8 +155,9 @@ class CrescendoJailbreaking(BaseMultiTurnAttack):breakeval_flag, _ = self._eval_score(- progression, attempt.response.content+ progression, probe.output.content)+ progression.score_probe(probe, 1.0 if eval_flag else 0.0)update_pbar(progress, rounds_pbar)update_pbar(progress, rounds_pbar, advance_to_end=True)@@ -193,17 +195,18 @@ class CrescendoJailbreaking(BaseMultiTurnAttack):# Probe first so the refused turns can be walked back without# having cost a metric call.- attempt = await progression.a_probe(attack)- self._remember_target_exchange(attempt)- await progression.a_commit(attempt)+ probe = await progression.a_probe(attack)+ self._remember_target_exchange(probe)+ await progression.a_commit(probe)update_pbar(progress, rounds_pbar)is_refusal, rationale = await self._a_refusal_score(- progression, attempt.response.content+ progression, probe.output.content)update_pbar(progress, rounds_pbar)if is_refusal:+ progression.score_probe(probe, 0.0, rationale)backtracks += 1eval_flag = Falserefusal_note = REFUSAL_NOTE.format(rationale=rationale)@@ -222,8 +225,9 @@ class CrescendoJailbreaking(BaseMultiTurnAttack):breakeval_flag, _ = await self._a_eval_score(- progression, attempt.response.content+ progression, probe.output.content)+ progression.score_probe(probe, 1.0 if eval_flag else 0.0)update_pbar(progress, rounds_pbar)update_pbar(progress, rounds_pbar, advance_to_end=True)@@ -249,14 +253,14 @@ class CrescendoJailbreaking(BaseMultiTurnAttack):},)- def _remember_target_exchange(self, attempt) -> None:+ def _remember_target_exchange(self, probe) -> None:self.memory.add_message(self.target_conversation_id,- {"role": "user", "content": attempt.attack},+ {"role": "user", "content": probe.input},)self.memory.add_message(self.target_conversation_id,- {"role": "assistant", "content": attempt.response.content},+ {"role": "assistant", "content": probe.output.content},)def _attack_prompt(diff --git a/deepteam/attacks/multi_turn/progression/__init__.py b/deepteam/attacks/multi_turn/progression/__init__.pyindex f378eba4..fdcdc1fe 100644--- a/deepteam/attacks/multi_turn/progression/__init__.py+++ b/deepteam/attacks/multi_turn/progression/__init__.py@@ -1,5 +1,5 @@from .progression import Progression, TURN_LEVEL_ATTACK_RATE-from .types import Attempt, ProgressionResult+from .types import Probe, ProgressionResultfrom .stopping import (StopReason,default_stop_detail,@@ -22,7 +22,7 @@ from .shift_detection import (__all__ = ["Progression","TURN_LEVEL_ATTACK_RATE",- "Attempt",+ "Probe","ProgressionResult","StopReason","default_stop_detail",diff --git a/deepteam/attacks/multi_turn/progression/progression.py b/deepteam/attacks/multi_turn/progression/progression.pyindex f11ed7ca..271370d3 100644--- a/deepteam/attacks/multi_turn/progression/progression.py+++ b/deepteam/attacks/multi_turn/progression/progression.py@@ -1,9 +1,14 @@import random+import timefrom typing import List, Optional, Unionfrom deepeval.metrics.utils import initialize_modelfrom deepeval.models import DeepEvalBaseLLM+from deepteam.attacks.attack_simulator.utils import (+ add_cost,+ current_simulation_cost,+)from deepteam.attacks.multi_turn.types import CallbackTypefrom deepteam.attacks.multi_turn.utils import (a_enhance_attack,@@ -21,7 +26,7 @@ from deepteam.attacks.multi_turn.progression.stopping import (mark_stop,)from deepteam.attacks.multi_turn.progression.types import (- Attempt,+ Probe,ProgressionResult,)from deepteam.attacks.single_turn import BaseSingleTurnAttack@@ -73,12 +78,15 @@ class Progression:)self.turns_spent = 0- self.attempts: List[Attempt] = []- # Attempt-tree bookkeeping. `_parent` is the attempt new probes+ self.probes: List[Probe] = []+ # Probe-tree bookkeeping. `_parent` is the probe new probes# descend from -- it follows commits and rolls back on a backtrack.- self._next_attempt_id = 0- self._parent: Optional[Attempt] = None- self._committed: List[Attempt] = []+ self._next_probe_id = 0+ self._parent: Optional[Probe] = None+ self._committed: List[Probe] = []+ # Running total of the active cost scope at the last probe, so each+ # probe gets the simulator spend accrued since the previous one.+ self._cost_snapshot = current_simulation_cost()self.stop_reason = StopReason.BUDGET_EXHAUSTEDself.stop_detail: Optional[str] = Noneself.shift_verdict: Optional[MetricVerdict] = None@@ -106,54 +114,56 @@ class Progression:stop_reason=self.stop_reason,stop_detail=stop_detail,turns_spent=self.turns_spent,- attempts=self.attempts,+ probes=self.probes,shift_verdict=self.shift_verdict,error=self.error,)- def probe(self, attack: str, *, enhance: bool = True) -> Attempt:+ def probe(self, attack: str, *, enhance: bool = True) -> Probe:"""Put an attack to the target without keeping it in the conversation.For attacks that try several things per step and keep one: tree searchbranches, retry-until-accepted loops, and knowledge-gathering questions- asked before the conversation proper begins. The Attempt is recorded+ asked before the conversation proper begins. The Probe is recordedeither way, so what was discarded survives in the result."""attack, turn_level_attack = self._apply_turn_level_attack(attack, enhance)- return self._record_attempt(- attack,- self.model_callback(attack, self.turns),- turn_level_attack,+ start = time.perf_counter()+ response = self.model_callback(attack, self.turns)+ latency = time.perf_counter() - start+ return self._record_probe(+ attack, response, turn_level_attack, latency)- async def a_probe(self, attack: str, *, enhance: bool = True) -> Attempt:+ async def a_probe(self, attack: str, *, enhance: bool = True) -> Probe:attack, turn_level_attack = await self._a_apply_turn_level_attack(attack, enhance)- return self._record_attempt(- attack,- await self.model_callback(attack, self.turns),- turn_level_attack,+ start = time.perf_counter()+ response = await self.model_callback(attack, self.turns)+ latency = time.perf_counter() - start+ return self._record_probe(+ attack, response, turn_level_attack, latency)- def commit(self, attack: Union[str, Attempt]) -> RTTurn:+ def commit(self, attack: Union[str, Probe]) -> RTTurn:"""Put an attack to the target and keep both turns.- Passing an Attempt from `probe` reuses the response already collected+ Passing a Probe from `probe` reuses the response already collectedrather than calling the target a second time."""- attempt = attack if isinstance(attack, Attempt) else self.probe(attack)- return self._commit_attempt(attempt)+ probe = attack if isinstance(attack, Probe) else self.probe(attack)+ return self._commit_probe(probe)- async def a_commit(self, attack: Union[str, Attempt]) -> RTTurn:- attempt = (+ async def a_commit(self, attack: Union[str, Probe]) -> RTTurn:+ probe = (attack- if isinstance(attack, Attempt)+ if isinstance(attack, Probe)else await self.a_probe(attack))- return self._commit_attempt(attempt)+ return self._commit_probe(probe)def shift_detected(self) -> bool:"""Has the target's behavior shifted? Records the stop reason when it@@ -170,8 +180,8 @@ class Progression:returndel self.turns[-2 * count :]self.turns_spent = max(0, self.turns_spent - count)- # Walked-back turns are simply un-committed; the attempts stay in- # `attempts` with committed=False so the backtrack is reconstructable.+ # Walked-back turns are simply un-committed; the probes stay in+ # `probes` with committed=False so the backtrack is reconstructable.for _ in range(min(count, len(self._committed))):self._committed.pop().committed = Falseself._parent = self._committed[-1] if self._committed else None@@ -203,33 +213,52 @@ class Progression:random.random() < self.turn_level_attack_rate)- def _record_attempt(+ def _record_probe(self,attack: str,response: RTTurn,turn_level_attack: Optional[str],- ) -> Attempt:- attempt = Attempt(- id=self._next_attempt_id,+ latency: Optional[float] = None,+ ) -> Probe:+ probe = Probe(+ id=self._next_probe_id,parent_id=self._parent.id if self._parent else None,depth=self._parent.depth + 1 if self._parent else 0,- attack=attack,- response=response,+ input=attack,+ output=response,turn_level_attack=turn_level_attack,+ latency=latency,+ simulation_cost=self._simulation_cost_since_last_probe(),)- self._next_attempt_id += 1- self.attempts.append(attempt)- return attempt-- def _commit_attempt(self, attempt: Attempt) -> RTTurn:- attempt.committed = True- attempt.response.turn_level_attack = attempt.turn_level_attack- self.turns.append(RTTurn(role="user", content=attempt.attack))- self.turns.append(attempt.response)+ self._next_probe_id += 1+ self.probes.append(probe)+ return probe++ def _simulation_cost_since_last_probe(self) -> Optional[float]:+ total = current_simulation_cost()+ if total is None:+ return None+ delta = add_cost(total, -(self._cost_snapshot or 0))+ self._cost_snapshot = total+ return delta++ def score_probe(+ self, probe: Probe, score: float, reason: Optional[str] = None+ ) -> None:+ """Record an attack's own judgement of a probe. The scale is the+ attack's own until callers normalise across algorithms."""+ probe.score = score+ probe.reason = reason++ def _commit_probe(self, probe: Probe) -> RTTurn:+ probe.committed = True+ probe.output.turn_level_attack = probe.turn_level_attack+ self.turns.append(RTTurn(role="user", content=probe.input))+ self.turns.append(probe.output)self.turns_spent += 1- self._committed.append(attempt)- self._parent = attempt- return attempt.response+ self._committed.append(probe)+ self._parent = probe+ return probe.outputdef _resolve_shift(self, verdict) -> bool:if verdict is None:diff --git a/deepteam/attacks/multi_turn/progression/types.py b/deepteam/attacks/multi_turn/progression/types.pyindex 7eb8d279..65e2470b 100644--- a/deepteam/attacks/multi_turn/progression/types.py+++ b/deepteam/attacks/multi_turn/progression/types.py@@ -9,14 +9,18 @@ from deepteam.attacks.multi_turn.progression.stopping import StopReasonfrom deepteam.test_case.test_case import RTTurn-class Attempt(BaseModel):+class Probe(BaseModel):id: intparent_id: Optional[int] = None- attack: str- response: RTTurn+ input: str+ output: RTTurnturn_level_attack: Optional[str] = Nonecommitted: bool = Falsedepth: int = 0+ latency: Optional[float] = None+ simulation_cost: Optional[float] = None+ score: Optional[float] = None+ reason: Optional[str] = Noneclass ProgressionResult(BaseModel):@@ -26,7 +30,7 @@ class ProgressionResult(BaseModel):stop_reason: StopReasonstop_detail: Optional[str] = Noneturns_spent: int = 0- attempts: List[Attempt] = []+ probes: List[Probe] = []shift_verdict: Optional[MetricVerdict] = Noneerror: Optional[Exception] = Nonediff --git a/deepteam/attacks/multi_turn/sequential_break/sequential_break.py b/deepteam/attacks/multi_turn/sequential_break/sequential_break.pyindex ca3d9077..00670f89 100644--- a/deepteam/attacks/multi_turn/sequential_break/sequential_break.py+++ b/deepteam/attacks/multi_turn/sequential_break/sequential_break.py@@ -310,7 +310,7 @@ class SequentialJailbreak(BaseMultiTurnAttack):previous_template: str,previous_response: Optional[str],) -> str:- feedback = "Previous attempt was not successful"+ feedback = "Previous probe was not successful"if previous_response:feedback += f"\nPrevious response: {previous_response[:500]}"diff --git a/deepteam/attacks/multi_turn/tree_jailbreaking/tree_jailbreaking.py b/deepteam/attacks/multi_turn/tree_jailbreaking/tree_jailbreaking.pyindex 4900c527..0458b9aa 100644--- a/deepteam/attacks/multi_turn/tree_jailbreaking/tree_jailbreaking.py+++ b/deepteam/attacks/multi_turn/tree_jailbreaking/tree_jailbreaking.py@@ -19,7 +19,7 @@ from deepteam.attacks.multi_turn.base_multi_turn_attack import (BaseMultiTurnAttack,)from deepteam.attacks.multi_turn.progression import (- Attempt,+ Probe,Progression,StopReason,)@@ -79,7 +79,7 @@ class TreeJailbreaking(BaseMultiTurnAttack):def _attack(self, progression: Progression) -> None:deadline = time.time() + self.max_runtimehistory = self._root_history(progression)- best: Optional[Attempt] = None+ best: Optional[Probe] = Noneprogress = create_progress()with progress:@@ -103,15 +103,14 @@ class TreeJailbreaking(BaseMultiTurnAttack):progression.stop(StopReason.SIMULATION_ERROR)break- # Scores stay local -- an Attempt records the search's shape,- # not this attack's private scoring.- attempts = [+ probes = [progression.probe(prompt) for prompt, _ in prompts]- scored = [- (attempt, self._score(progression, attempt))- for attempt in attempts- ]+ scored = []+ for probe in probes:+ score = self._score(progression, probe)+ progression.score_probe(probe, score)+ scored.append((probe, score))best, best_score = max(scored, key=lambda pair: pair[1])progression.commit(best)history = self._descend_history(@@ -127,7 +126,7 @@ class TreeJailbreaking(BaseMultiTurnAttack):async def _a_attack(self, progression: Progression) -> None:deadline = time.time() + self.max_runtimehistory = self._root_history(progression)- best: Optional[Attempt] = None+ best: Optional[Probe] = Noneprogress = create_progress()with progress:@@ -151,7 +150,7 @@ class TreeJailbreaking(BaseMultiTurnAttack):progression.stop(StopReason.SIMULATION_ERROR)break- attempts = list(+ probes = list(await asyncio.gather(*[progression.a_probe(prompt)@@ -159,16 +158,16 @@ class TreeJailbreaking(BaseMultiTurnAttack):]))- # Scores stay local -- an Attempt records the search's shape,- # not this attack's private scoring.scores = await asyncio.gather(*[- self._a_score(progression, attempt)- for attempt in attempts+ self._a_score(progression, probe)+ for probe in probes])+ for probe, score in zip(probes, scores):+ progression.score_probe(probe, score)best, best_score = max(- zip(attempts, scores), key=lambda pair: pair[1]+ zip(probes, scores), key=lambda pair: pair[1])await progression.a_commit(best)history = self._descend_history(@@ -196,14 +195,14 @@ class TreeJailbreaking(BaseMultiTurnAttack):def _branch_history(history: List[dict],goal: str,- best: Optional[Attempt],+ best: Optional[Probe],best_score: float,) -> List[dict]:return history + [{"role": "user","content": (- f"Current prompt: {best.attack if best else goal}\n\n"+ f"Current prompt: {best.input if best else goal}\n\n"f"OBJECTIVE: {goal}\n\n"f"SCORE: {best_score if best else 0}"),@@ -212,14 +211,14 @@ class TreeJailbreaking(BaseMultiTurnAttack):@staticmethoddef _descend_history(- history: List[dict], best: Attempt, best_score: float+ history: List[dict], best: Probe, best_score: float) -> List[dict]:return history + [- {"role": "assistant", "content": best.attack},+ {"role": "assistant", "content": best.input},{"role": "user","content": (- f"RESPONSE: {best.response.content}\n\nSCORE: {best_score}"+ f"RESPONSE: {best.output.content}\n\nSCORE: {best_score}"),},]@@ -297,12 +296,12 @@ class TreeJailbreaking(BaseMultiTurnAttack):return res.prompt, topic.on_topic- def _score(self, progression: Progression, attempt: Attempt) -> float:+ def _score(self, progression: Progression, probe: Probe) -> float:rating: Rating = generate(JailBreakingTemplate.linear_judge(progression.goal,- attempt.attack,- attempt.response,+ probe.input,+ probe.output,progression.vulnerability_data,),Rating,@@ -311,13 +310,13 @@ class TreeJailbreaking(BaseMultiTurnAttack):return rating.ratingasync def _a_score(- self, progression: Progression, attempt: Attempt+ self, progression: Progression, probe: Probe) -> float:rating: Rating = await a_generate(JailBreakingTemplate.linear_judge(progression.goal,- attempt.attack,- attempt.response,+ probe.input,+ probe.output,progression.vulnerability_data,),Rating,