DeepTeam is a framework to red team LLMs and AI agents.
.
penguine8c654229b79c
diff --git a/deepteam/__init__.py b/deepteam/__init__.pyindex 5c7d9cb6..19281b7b 100644--- a/deepteam/__init__.py+++ b/deepteam/__init__.py@@ -2,6 +2,8 @@ import osimport warningsimport re+from ._version import __version__+# Optionally add telemetryfrom deepteam.red_team import red_teamdiff --git a/deepteam/attacks/multi_turn/__init__.py b/deepteam/attacks/multi_turn/__init__.pyindex 95163e5f..d1d46a64 100644--- a/deepteam/attacks/multi_turn/__init__.py+++ b/deepteam/attacks/multi_turn/__init__.py@@ -11,3 +11,16 @@ __all__ = ["SequentialJailbreak","BadLikertJudge",]++MULTI_TURN_ATTACK_MAP = {+ v.__name__: v+ for v in [+ CrescendoJailbreaking,+ LinearJailbreaking,+ TreeJailbreaking,+ SequentialJailbreak,+ BadLikertJudge,+ ]+}++MULTI_TURN_ATTACK_NAMES = sorted(list(MULTI_TURN_ATTACK_MAP.keys()))diff --git a/deepteam/attacks/single_turn/__init__.py b/deepteam/attacks/single_turn/__init__.pyindex 7268cb06..a5b5e80e 100644--- a/deepteam/attacks/single_turn/__init__.py+++ b/deepteam/attacks/single_turn/__init__.py@@ -35,3 +35,26 @@ __all__ = ["ContextPoisoning","GoalRedirection",]++SINGLE_TURN_ATTACK_MAP = {+ v.__name__: v+ for v in [+ Base64,+ GrayBox,+ Leetspeak,+ MathProblem,+ Multilingual,+ PromptInjection,+ PromptProbing,+ Roleplay,+ ROT13,+ SystemOverride,+ PermissionEscalation,+ LinguisticConfusion,+ InputBypass,+ ContextPoisoning,+ GoalRedirection,+ ]+}++SINGLE_TURN_ATTACK_NAMES = sorted(list(SINGLE_TURN_ATTACK_MAP.keys()))diff --git a/deepteam/confident/__init__.py b/deepteam/confident/__init__.pynew file mode 100644index 00000000..8b137891--- /dev/null+++ b/deepteam/confident/__init__.py@@ -0,0 +1 @@+diff --git a/deepteam/confident/api.py b/deepteam/confident/api.pynew file mode 100644index 00000000..18709d92--- /dev/null+++ b/deepteam/confident/api.py@@ -0,0 +1,177 @@+import logging+from typing import Optional, Any, Union, Tuple+import aiohttp+import requests+from enum import Enum+from tenacity import (+ retry,+ wait_exponential_jitter,+ retry_if_exception_type,+)+++import deepteam+from deepeval.confident.types import ApiResponse, ConfidentApiError+from deepeval.confident.api import (+ get_confident_api_key,+ CONFIDENT_API_KEY_ENV_VAR,+ get_base_api_url,+ retryable_exceptions,+ log_retry_error,+ HttpMethods,+)+++class Endpoints(Enum):+ RISK_ASSESSMENT_ENDPOINT = "/v1/risk-assessments"+++class Api:+ def __init__(self, api_key: Optional[str] = None):+ if api_key is None:+ api_key = get_confident_api_key()++ if not api_key:+ raise ValueError(+ f"No Confident API key found. Please run `deepteam login` or set the {CONFIDENT_API_KEY_ENV_VAR} environment variable in the CLI."+ )++ self.api_key = api_key+ self._headers = {+ "Content-Type": "application/json",+ "CONFIDENT_API_KEY": api_key,+ "X-DeepTeam-Version": deepteam.__version__,+ }+ self.base_api_url = get_base_api_url()++ @staticmethod+ @retry(+ wait=wait_exponential_jitter(initial=1, exp_base=2, jitter=2, max=10),+ retry=retry_if_exception_type(retryable_exceptions),+ after=log_retry_error,+ )+ def _http_request(+ method: str, url: str, headers=None, json=None, params=None+ ):+ session = requests.Session()+ return session.request(+ method=method,+ url=url,+ headers=headers,+ json=json,+ params=params,+ verify=True, # SSL verification is always enabled+ )++ def _handle_response(+ self, response_data: Union[dict, Any]+ ) -> Tuple[Any, Optional[str]]:+ if not isinstance(response_data, dict):+ return response_data, None++ try:+ api_response = ApiResponse(**response_data)+ except Exception:+ return response_data, None++ if api_response.deprecated:+ deprecation_msg = "You are using a deprecated API endpoint. Please update your deepteam version."+ if api_response.link:+ deprecation_msg += f" See: {api_response.link}"+ logging.warning(deprecation_msg)++ if not api_response.success:+ error_message = api_response.error or "Request failed"+ raise ConfidentApiError(error_message, api_response.link)++ return api_response.data, api_response.link++ def send_request(+ self,+ method: HttpMethods,+ endpoint: Endpoints,+ body=None,+ params=None,+ url_params=None,+ ) -> Tuple[Any, Optional[str]]:+ url = f"{self.base_api_url}{endpoint.value}"++ # Replace URL parameters if provided+ if url_params:+ for key, value in url_params.items():+ placeholder = f":{key}"+ if placeholder in url:+ url = url.replace(placeholder, str(value))++ res = self._http_request(+ method=method.value,+ url=url,+ headers=self._headers,+ json=body,+ params=params,+ )++ if res.status_code == 200:+ try:+ response_data = res.json()+ return self._handle_response(response_data)+ except ValueError:+ return res.text, None+ else:+ try:+ error_data = res.json()+ return self._handle_response(error_data)+ except (ValueError, ConfidentApiError) as e:+ if isinstance(e, ConfidentApiError):+ raise e+ error_message = (+ error_data.get("error", res.text)+ if "error_data" in locals()+ else res.text+ )+ raise Exception(error_message)++ async def a_send_request(+ self,+ method: HttpMethods,+ endpoint: Endpoints,+ body=None,+ params=None,+ url_params=None,+ ) -> Tuple[Any, Optional[str]]:+ url = f"{self.base_api_url}{endpoint.value}"++ if url_params:+ for key, value in url_params.items():+ placeholder = f":{key}"+ if placeholder in url:+ url = url.replace(placeholder, str(value))++ async with aiohttp.ClientSession() as session:+ async with session.request(+ method=method.value,+ url=url,+ headers=self._headers,+ json=body,+ params=params,+ ssl=True, # SSL verification enabled+ ) as res:+ if res.status == 200:+ try:+ response_data = await res.json()+ return self._handle_response(response_data)+ except aiohttp.ContentTypeError:+ return await res.text(), None+ else:+ try:+ error_data = await res.json()+ return self._handle_response(error_data)+ except (aiohttp.ContentTypeError, ConfidentApiError) as e:+ if isinstance(e, ConfidentApiError):+ raise e+ error_message = (+ error_data.get("error", await res.text())+ if "error_data" in locals()+ else await res.text()+ )+ raise Exception(error_message)diff --git a/deepteam/red_teamer/api.py b/deepteam/red_teamer/api.pynew file mode 100644index 00000000..4df12421--- /dev/null+++ b/deepteam/red_teamer/api.py@@ -0,0 +1,186 @@+from typing import List, Optional+from pydantic import BaseModel, Field++from deepeval.test_run.api import TurnApi+from deepteam.red_teamer.risk_assessment import (+ RiskAssessment,+ VulnerabilityTypeResult,+ AttackMethodResult,+)+from deepteam.test_case import RTTestCase, RTTurn+++class VulnerabilityTypeResult(BaseModel):+ vulnerability: str+ vulnerability_type: str = Field(alias="vulnerabilityType")+ pass_rate: float = Field(alias="passRate")+ passing: int+ failing: int+ errored: int+++class AttackMethodResult(BaseModel):+ attack_method: str = Field(alias="attackMethod")+ pass_rate: float = Field(alias="passRate")+ passing: int+ failing: int+ errored: int+++class APIRTTurn(TurnApi):+ turn_level_attack: Optional[str] = Field(+ alias="turnLevelAttack"+ )+++class APIRTTestCase(BaseModel):+ input: str+ actual_output: str = Field(alias="actualOutput")+ retrieval_context: Optional[List[str]] = Field(+ None, alias="retrievalContext"+ )+ tools_called: Optional[List[str]] = Field(+ None, alias="toolsCalled"+ )+ turns: Optional[List[APIRTTurn]] = Field(None)++ success: Optional[bool] = Field(None)+ score: Optional[float] = Field(None)+ reason: Optional[str] = Field(None)+ error: Optional[str] = Field(None)++ vulnerability: str = Field(alias="vulnerability")+ vulnerability_type: str = Field(alias="vulnerabilityType")+ attack_method: str = Field(alias="attackMethod")+ risk_category: str = Field(alias="riskCategory")++ order: int+++class APIRiskAssessment(BaseModel):+ vulnerability_results: List[VulnerabilityTypeResult] = Field(+ alias="vulnerabilityResults"+ )+ attack_results: List[AttackMethodResult] = Field(+ alias="attackResults"+ )+ run_duration: float = Field(alias="runDuration")+ identifier: Optional[str] = Field(alias="identifier")+ assessment_cost: Optional[float] = Field(+ alias="assessmentCost"+ )+ test_cases: List[APIRTTestCase] = Field(alias="testCases")+++def map_turn_to_api(turn: RTTurn, order: int) -> APIRTTurn:+ """Map RTTurn to APIRTTurn."""+ return APIRTTurn(+ role=turn.role,+ content=turn.content,+ order=order,+ user_id=turn.user_id,+ retrieval_context=turn.retrieval_context,+ tools_called=turn.tools_called,+ turn_level_attack=turn.turn_level_attack,+ )+++def map_test_case_to_api(test_case: RTTestCase, index: int) -> APIRTTestCase:+ """Map RTTestCase to APIRTTestCase."""+ turns = None+ if test_case.turns:+ turns = [+ map_turn_to_api(turn, idx)+ for idx, turn in enumerate(test_case.turns)+ ]+++ if test_case.score is not None:+ success = test_case.score > 0+ else:+ success = None++ return APIRTTestCase(+ input=test_case.input,+ actualOutput=test_case.actual_output,+ retrievalContext=test_case.retrieval_context,+ toolsCalled=test_case.tools_called,+ turns=turns,+ success=success,+ score=test_case.score,+ reason=test_case.reason,+ error=test_case.error,+ vulnerability=test_case.vulnerability,+ vulnerabilityType=test_case.vulnerability_type.value,+ attackMethod=test_case.attack_method,+ riskCategory=test_case.risk_category,+ order=index,+ )+++def map_vulnerability_type_result_to_api(+ result: VulnerabilityTypeResult,+) -> VulnerabilityTypeResult:+ """Map VulnerabilityTypeResult to API VulnerabilityTypeResult."""+ return VulnerabilityTypeResult(+ vulnerability=result.vulnerability,+ vulnerabilityType=result.vulnerability_type.value,+ passRate=result.pass_rate,+ passing=result.passing,+ failing=result.failing,+ errored=result.errored,+ )+++def map_attack_method_result_to_api(+ result: AttackMethodResult,+) -> AttackMethodResult:+ """Map AttackMethodResult to API AttackMethodResult."""+ return AttackMethodResult(+ attackMethod=result.attack_method or "",+ passRate=result.pass_rate,+ passing=result.passing,+ failing=result.failing,+ errored=result.errored,+ )+++def map_risk_assessment_to_api(+ risk_assessment: RiskAssessment,+ assessment_cost: Optional[float] = None,+ identifier: Optional[str] = None,+) -> APIRiskAssessment:+ """+ Map RiskAssessment to APIRiskAssessment.++ Args:+ risk_assessment: The internal RiskAssessment object+ identifier: Optional[str] = None,+ assessment_cost: Optional[float] = None,++ Returns:+ APIRiskAssessment: The API-compatible risk assessment object+ """+ vulnerability_type_results = [+ map_vulnerability_type_result_to_api(result)+ for result in risk_assessment.overview.vulnerability_type_results+ ]++ attack_results = [+ map_attack_method_result_to_api(result)+ for result in risk_assessment.overview.attack_method_results+ ]++ test_cases = [+ map_test_case_to_api(test_case, index)+ for index, test_case in enumerate(risk_assessment.test_cases)+ ]++ return APIRiskAssessment(+ vulnerabilityResults=vulnerability_type_results,+ attackResults=attack_results,+ runDuration=risk_assessment.overview.run_duration,+ identifier=identifier,+ assessmentCost=assessment_cost,+ testCases=test_cases,+ )diff --git a/deepteam/red_teamer/red_teamer.py b/deepteam/red_teamer/red_teamer.pyindex 0b588be3..b9d6deb8 100644--- a/deepteam/red_teamer/red_teamer.py+++ b/deepteam/red_teamer/red_teamer.py@@ -1,4 +1,6 @@import asyncio+import time+from deepeval.confident.api import is_confidentfrom tqdm import tqdmfrom typing import Dict, List, Optional, Unionfrom rich.console import Console@@ -6,11 +8,13 @@ from rich.table import Tableimport inspectfrom rich import boxfrom enum import Enum+from rich.console import Consolefrom deepeval.models import DeepEvalBaseLLMfrom deepeval.metrics.utils import initialize_modelfrom deepeval.dataset.golden import Golden+from deepteam.red_teamer.api import map_risk_assessment_to_apifrom deepteam.test_case import RTTestCasefrom deepeval.utils import get_or_create_event_loop@@ -28,6 +32,9 @@ from deepteam.red_teamer.risk_assessment import (RiskAssessment,)from deepteam.risks import getRiskCategory+from deepteam.confident.api import Api, HttpMethods, Endpoints++console = Console()class RedTeamer:@@ -102,6 +109,7 @@ class RedTeamer:model_callback), "`model_callback` needs to be sync. `async_mode` has been set to False."+ start_time = time.time()if evaluation_model is not None:self.evaluation_model = evaluation_modelif simulator_model is not None:@@ -185,14 +193,17 @@ class RedTeamer:pbar.close()+ run_duration = time.time() - start_timeself.risk_assessment = RiskAssessment(overview=construct_risk_assessment_overview(- red_teaming_test_cases=red_teaming_test_cases+ red_teaming_test_cases=red_teaming_test_cases,+ run_duration=run_duration,),test_cases=red_teaming_test_cases,)self.test_cases = red_teaming_test_casesself._print_risk_assessment()+ self._post_risk_assessment()return self.risk_assessment@@ -209,6 +220,7 @@ class RedTeamer:reuse_simulated_test_cases: bool = False,metadata: Optional[dict] = None,):+ start_time = time.time()if framework:vulnerabilities = framework.vulnerabilitiesattacks = framework.attacks@@ -310,21 +322,23 @@ class RedTeamer:await asyncio.gather(*tasks)pbar.close()+ run_duration = time.time() - start_timeself.risk_assessment = RiskAssessment(overview=construct_risk_assessment_overview(- red_teaming_test_cases=red_teaming_test_cases+ red_teaming_test_cases=red_teaming_test_cases,+ run_duration=run_duration,),test_cases=red_teaming_test_cases,)self.test_cases = red_teaming_test_casesself._print_risk_assessment()+ self._post_risk_assessment()return self.risk_assessmentdef _attack(self,model_callback: CallbackType,simulated_test_case: RTTestCase,- vulnerability: str,vulnerability_type: VulnerabilityType,vulnerabilities: List[BaseVulnerability],ignore_errors: bool,@@ -399,7 +413,6 @@ class RedTeamer:self,model_callback: CallbackType,simulated_test_case: RTTestCase,- vulnerability: str,vulnerability_type: VulnerabilityType,vulnerabilities: List[BaseVulnerability],ignore_errors: bool,@@ -488,7 +501,6 @@ class RedTeamer:model_callback=model_callback,simulated_test_case=simulated_test_case,vulnerabilities=vulnerabilities,- vulnerability=simulated_test_case.vulnerability,vulnerability_type=vulnerability_type,ignore_errors=ignore_errors,)@@ -510,7 +522,6 @@ class RedTeamer:model_callback=model_callback,simulated_test_case=simulated_test_case,vulnerabilities=vulnerabilities,- vulnerability=simulated_test_case.vulnerability,vulnerability_type=vulnerability_type,ignore_errors=ignore_errors,)@@ -657,3 +668,43 @@ class RedTeamer:console.print("\n" + "=" * 80)console.print("[bold magenta]LLM red teaming complete.[/bold magenta]")console.print("=" * 80 + "\n")++ def _post_risk_assessment(self):+ if not is_confident():+ passing = 0+ failing = 0+ for tc in self.risk_assessment.test_cases:+ if tc and tc.score is not None:+ if tc.score > 0:+ passing += 1+ else:+ failing += 1+ pass_rate = round((passing / (passing + failing)) * 100, 2)++ console.print(+ f"\n\n[rgb(5,245,141)]✓[/rgb(5,245,141)] Risk Assessment completed 🎉! (time taken: {round(self.risk_assessment.overview.run_duration, 2)}s)\n"+ f"» Test Results ({len(self.risk_assessment.test_cases)} total tests):\n",+ f" » Pass Rate: {pass_rate}% | Passed: [bold green]{passing}[/bold green] | Failed: [bold red]{failing}[/bold red]\n\n",+ "=" * 80,+ "\n\n» Want to share risk assessments with your team, or a place for your test cases to live? ❤️ 🏡\n"+ " » Run [bold]'deepteam login'[/bold] to analyze and save testing results on [rgb(106,0,255)]Confident AI[/rgb(106,0,255)].\n\n",+ )+ return++ api = Api()+ api_risk_assessment = map_risk_assessment_to_api(self.risk_assessment)+ try:+ body = api_risk_assessment.model_dump(+ by_alias=True, exclude_none=True+ )+ except AttributeError:+ # Pydantic version below 2.0+ body = api_risk_assessment.dict(by_alias=True, exclude_none=True)+++ data, link = api.send_request(+ method=HttpMethods.POST,+ endpoint=Endpoints.RISK_ASSESSMENT_ENDPOINT,+ body=body,+ )+ print(data, link, "@@@")diff --git a/deepteam/red_teamer/risk_assessment.py b/deepteam/red_teamer/risk_assessment.pyindex 05b97948..791243e3 100644--- a/deepteam/red_teamer/risk_assessment.py+++ b/deepteam/red_teamer/risk_assessment.py@@ -5,7 +5,6 @@ import osimport jsonfrom enum import Enum-from deepeval.test_case import Turnfrom deepteam.vulnerabilities.types import VulnerabilityTypefrom deepteam.test_case import RTTestCase@@ -97,6 +96,7 @@ class RedTeamingOverview(BaseModel):vulnerability_type_results: List[VulnerabilityTypeResult]attack_method_results: List[AttackMethodResult]errored: int+ run_duration: floatdef to_df(self):import pandas as pd@@ -176,7 +176,7 @@ class RiskAssessment(BaseModel):def construct_risk_assessment_overview(- red_teaming_test_cases: List[RTTestCase],+ red_teaming_test_cases: List[RTTestCase], run_duration: float) -> RedTeamingOverview:# Group test cases by vulnerability typevulnerability_type_to_cases: Dict[@@ -251,4 +251,5 @@ def construct_risk_assessment_overview(vulnerability_type_results=vulnerability_type_results,attack_method_results=attack_method_results,errored=errored,+ run_duration=run_duration,)diff --git a/deepteam/test_case/test_case.py b/deepteam/test_case/test_case.pyindex cdbf42ee..50954b1e 100644--- a/deepteam/test_case/test_case.py+++ b/deepteam/test_case/test_case.py@@ -1,6 +1,6 @@from typing import List, Optionalfrom enum import Enum-from pydantic import model_validator+from deepeval.test_case import LLMTestCase, Turndiff --git a/deepteam/vulnerabilities/__init__.py b/deepteam/vulnerabilities/__init__.pyindex a95a2dfc..5fe88254 100644--- a/deepteam/vulnerabilities/__init__.py+++ b/deepteam/vulnerabilities/__init__.py@@ -50,3 +50,33 @@ __all__ = ["Robustness","ExcessiveAgency",]++VULNERABILITY_MAP = {+ v.__name__: v+ for v in [+ Bias,+ Toxicity,+ Misinformation,+ IllegalActivity,+ PromptLeakage,+ PIILeakage,+ BFLA,+ BOLA,+ RBAC,+ DebugAccess,+ ShellInjection,+ SQLInjection,+ SSRF,+ IntellectualProperty,+ Competition,+ GraphicContent,+ PersonalSafety,+ CustomVulnerability,+ GoalTheft,+ RecursiveHijacking,+ Robustness,+ ExcessiveAgency,+ ]+}++VULNERABILITY_NAMES = sorted(list(VULNERABILITY_MAP.keys()))diff --git a/kk.py b/kk.pynew file mode 100644index 00000000..a3c41c32--- /dev/null+++ b/kk.py@@ -0,0 +1,17 @@+from deepteam import red_team+from deepteam.vulnerabilities import Bias+from deepteam.attacks.single_turn import Roleplay+import os+++async def your_callback(input: str) -> str:+ return "I'm sorry but I can't answer this: " + input+++print(os.environ.get("CONFIDENT_API_KEY"))++risk_assessment = red_team(+ attacks=[Roleplay()],+ vulnerabilities=[Bias()],+ model_callback=your_callback,+)