Skip to content

Commit 1b8367b

Browse files
riyosharomanlutz
andauthored
MAINT: Fixed doscstrings for pyrit/analytics+auth (microsoft#1192)
Co-authored-by: Roman Lutz <romanlutz13@gmail.com>
1 parent db22da2 commit 1b8367b

8 files changed

Lines changed: 64 additions & 19 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ extend-select = [
251251
# Temporary ignores for pyrit/ subdirectories until issue #1176
252252
# https://github.com/Azure/PyRIT/issues/1176 is fully resolved
253253
# TODO: Remove these ignores once the issues are fixed
254-
"pyrit/{analytics,auth,auxiliary_attacks,chat_message_normalizer,cli,embedding,exceptions,executor,memory,models,prompt_converter,prompt_normalizer,prompt_target,scenarios,score,setup,ui}/**/*.py" = ["D101", "D102", "D103", "D104", "D105", "D106", "D107", "D401", "D404", "D417", "D418", "DOC102", "DOC201", "DOC202", "DOC402", "DOC501"]
254+
"pyrit/{auxiliary_attacks,chat_message_normalizer,cli,embedding,exceptions,executor,memory,models,prompt_converter,prompt_normalizer,prompt_target,scenarios,score,setup,ui}/**/*.py" = ["D101", "D102", "D103", "D104", "D105", "D106", "D107", "D401", "D404", "D417", "D418", "DOC102", "DOC201", "DOC202", "DOC402", "DOC501"]
255255
"pyrit/__init__.py" = ["D104"]
256256

257257
[tool.ruff.lint.pydocstyle]

pyrit/analytics/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT license.
33

4+
"""Analytics module for PyRIT conversation and result analysis."""
5+
6+
47
from pyrit.analytics.conversation_analytics import ConversationAnalytics
58
from pyrit.analytics.result_analysis import analyze_results, AttackStats
69
from pyrit.analytics.text_matching import (

pyrit/analytics/conversation_analytics.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class ConversationAnalytics:
1818

1919
def __init__(self, *, memory_interface: MemoryInterface):
2020
"""
21-
Initializes the ConversationAnalytics with a memory interface for data access.
21+
Initialize the ConversationAnalytics with a memory interface for data access.
2222
2323
Args:
2424
memory_interface (MemoryInterface): An instance of MemoryInterface for accessing conversation data.
@@ -29,7 +29,7 @@ def get_prompt_entries_with_same_converted_content(
2929
self, *, chat_message_content: str
3030
) -> list[ConversationMessageWithSimilarity]:
3131
"""
32-
Retrieves chat messages that have the same converted content.
32+
Retrieve chat messages that have the same converted content.
3333
3434
Args:
3535
chat_message_content (str): The content of the chat message to find similar messages for.
@@ -58,7 +58,7 @@ def get_similar_chat_messages_by_embedding(
5858
self, *, chat_message_embedding: list[float], threshold: float = 0.8
5959
) -> list[EmbeddingMessageWithSimilarity]:
6060
"""
61-
Retrieves chat messages that are similar to the given embedding based on cosine similarity.
61+
Retrieve chat messages that are similar to the given embedding based on cosine similarity.
6262
6363
Args:
6464
chat_message_embedding (List[float]): The embedding of the chat message to find similar messages for.

pyrit/analytics/result_analysis.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
@dataclass
1212
class AttackStats:
13+
"""Statistics for attack analysis results."""
14+
1315
success_rate: Optional[float]
1416
total_decided: int
1517
successes: int

pyrit/auth/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# Licensed under the MIT license.
33

44
"""
5-
This module contains authentication functionality for a variety of services.
5+
Authentication functionality for a variety of services.
66
"""
77

88
from pyrit.auth.authenticator import Authenticator

pyrit/auth/authenticator.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,20 @@ class Authenticator(abc.ABC):
1414

1515
@abstractmethod
1616
def refresh_token(self) -> str:
17+
"""
18+
Refresh the authentication token.
19+
20+
Returns:
21+
str: The refreshed authentication token.
22+
"""
1723
raise NotImplementedError("refresh_token method not implemented")
1824

1925
@abstractmethod
2026
def get_token(self) -> str:
27+
"""
28+
Get the current authentication token.
29+
30+
Returns:
31+
str: The current authentication token.
32+
"""
2133
raise NotImplementedError("get_token method not implemented")

pyrit/auth/azure_auth.py

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,21 @@ class AzureAuth(Authenticator):
3131
_token_scope: str
3232

3333
def __init__(self, token_scope: str, tenant_id: str = ""):
34+
"""
35+
Initialize Azure authentication.
36+
37+
Args:
38+
token_scope (str): The token scope for authentication.
39+
tenant_id (str, optional): The tenant ID. Defaults to "".
40+
"""
3441
self._tenant_id = tenant_id
3542
self._token_scope = token_scope
3643
self._set_default_token()
3744

3845
def _set_default_token(self) -> None:
46+
"""
47+
Set up default Azure credentials and retrieve access token.
48+
"""
3949
self.azure_creds = DefaultAzureCredential()
4050
self.access_token = self.azure_creds.get_token(self._token_scope)
4151
self.token = self.access_token.token
@@ -45,8 +55,7 @@ def refresh_token(self) -> str:
4555
Refresh the access token if it is expired.
4656
4757
Returns:
48-
A token
49-
58+
str: A token
5059
"""
5160
curr_epoch_time_in_ms = int(time.time()) * 1_000
5261
access_token_epoch_expiration_time_in_ms = int(self.access_token.expires_on) * 1_000
@@ -63,13 +72,23 @@ def get_token(self) -> str:
6372
"""
6473
Get the current token.
6574
66-
Returns: The current token
67-
75+
Returns:
76+
str: current token
6877
"""
6978
return self.token
7079

7180

7281
def get_access_token_from_azure_cli(*, scope: str, tenant_id: str = ""):
82+
"""
83+
Get access token from Azure CLI.
84+
85+
Args:
86+
scope (str): The scope to request.
87+
tenant_id (str, optional): The tenant ID. Defaults to "".
88+
89+
Returns:
90+
str: The access token.
91+
"""
7392
try:
7493
credential = AzureCliCredential(tenant_id=tenant_id)
7594
token = credential.get_token(scope)
@@ -90,7 +109,7 @@ def get_access_token_from_azure_msi(*, client_id: str, scope: str):
90109
scope (str): The scope to request
91110
92111
Returns:
93-
Authentication token
112+
str: Authentication token
94113
"""
95114
try:
96115
credential = ManagedIdentityCredential(client_id=client_id)
@@ -103,15 +122,15 @@ def get_access_token_from_azure_msi(*, client_id: str, scope: str):
103122

104123
def get_access_token_from_msa_public_client(*, client_id: str, scope: str):
105124
"""
106-
Uses MSA account to connect to an AOAI endpoint via interactive login. A browser window
125+
Use MSA account to connect to an AOAI endpoint via interactive login. A browser window
107126
will open and ask for login credentials.
108127
109128
Args:
110129
client_id (str): The client ID of the service
111130
scope (str): The scope to request
112131
113132
Returns:
114-
Authentication token
133+
str: Authentication token
115134
"""
116135
try:
117136
app = msal.PublicClientApplication(client_id)
@@ -124,11 +143,14 @@ def get_access_token_from_msa_public_client(*, client_id: str, scope: str):
124143

125144
def get_access_token_from_interactive_login(scope: str) -> str:
126145
"""
127-
Connects to an OpenAI endpoint with an interactive login from Azure. A browser window will
146+
Connect to an OpenAI endpoint with an interactive login from Azure. A browser window will
128147
open and ask for login credentials. The token will be scoped for Azure Cognitive services.
129148
149+
Args:
150+
scope (str): The scope to request
151+
130152
Returns:
131-
Authentication token
153+
str: Authentication token
132154
"""
133155
try:
134156
token_provider = get_bearer_token_provider(InteractiveBrowserCredential(), scope)
@@ -143,7 +165,7 @@ def get_token_provider_from_default_azure_credential(scope: str) -> Callable[[],
143165
Connect to an AOAI endpoint via default Azure credential.
144166
145167
Returns:
146-
Authentication token provider
168+
Callable[[], str]: Authentication token provider
147169
"""
148170
try:
149171
token_provider = get_bearer_token_provider(DefaultAzureCredential(), scope)
@@ -161,7 +183,7 @@ def get_default_scope(endpoint: str) -> str:
161183
endpoint (str): The endpoint to get the scope for.
162184
163185
Returns:
164-
The default scope for the given endpoint.
186+
str: The default scope for the given endpoint.
165187
"""
166188
try:
167189
parsed_uri = urlparse(endpoint)
@@ -184,7 +206,7 @@ def get_speech_config(resource_id: Union[str, None], key: Union[str, None], regi
184206
region (str): The region to get the token for.
185207
186208
Returns:
187-
The speech config based on passed in args
209+
speechsdk.SpeechConfig: The speech config based on passed in args
188210
189211
Raises:
190212
ModuleNotFoundError: If azure.cognitiveservices.speech is not installed.
@@ -223,6 +245,9 @@ def get_speech_config_from_default_azure_credential(resource_id: str, region: st
223245
224246
Returns:
225247
The speech config for the given resource ID and region.
248+
249+
Raises:
250+
ModuleNotFoundError: If azure.cognitiveservices.speech is not installed.
226251
"""
227252
try:
228253
import azure.cognitiveservices.speech as speechsdk # noqa: F811

pyrit/auth/azure_storage_auth.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class AzureStorageAuth:
2222
@staticmethod
2323
async def get_user_delegation_key(blob_service_client: BlobServiceClient) -> UserDelegationKey:
2424
"""
25-
Retrieves a user delegation key valid for one day.
25+
Retrieve a user delegation key valid for one day.
2626
2727
Args:
2828
blob_service_client (BlobServiceClient): An instance of BlobServiceClient to interact
@@ -43,13 +43,16 @@ async def get_user_delegation_key(blob_service_client: BlobServiceClient) -> Use
4343
@staticmethod
4444
async def get_sas_token(container_url: str) -> str:
4545
"""
46-
Generates a SAS token for the specified blob using a user delegation key.
46+
Generate a SAS token for the specified blob using a user delegation key.
4747
4848
Args:
4949
container_url (str): The URL of the Azure Blob Storage container.
5050
5151
Returns:
5252
str: The generated SAS token.
53+
54+
Raises:
55+
ValueError: If container_url is empty or invalid.
5356
"""
5457
if not container_url:
5558
raise ValueError(

0 commit comments

Comments
 (0)