hackagent 0.3.1__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.
- hackagent/__init__.py +12 -0
- hackagent/agent.py +214 -0
- hackagent/api/__init__.py +1 -0
- hackagent/api/agent/__init__.py +1 -0
- hackagent/api/agent/agent_create.py +347 -0
- hackagent/api/agent/agent_destroy.py +140 -0
- hackagent/api/agent/agent_list.py +242 -0
- hackagent/api/agent/agent_partial_update.py +361 -0
- hackagent/api/agent/agent_retrieve.py +235 -0
- hackagent/api/agent/agent_update.py +361 -0
- hackagent/api/apilogs/__init__.py +1 -0
- hackagent/api/apilogs/apilogs_list.py +170 -0
- hackagent/api/apilogs/apilogs_retrieve.py +162 -0
- hackagent/api/attack/__init__.py +1 -0
- hackagent/api/attack/attack_create.py +275 -0
- hackagent/api/attack/attack_destroy.py +146 -0
- hackagent/api/attack/attack_list.py +254 -0
- hackagent/api/attack/attack_partial_update.py +289 -0
- hackagent/api/attack/attack_retrieve.py +247 -0
- hackagent/api/attack/attack_update.py +289 -0
- hackagent/api/checkout/__init__.py +1 -0
- hackagent/api/checkout/checkout_create.py +225 -0
- hackagent/api/generate/__init__.py +1 -0
- hackagent/api/generate/generate_create.py +253 -0
- hackagent/api/judge/__init__.py +1 -0
- hackagent/api/judge/judge_create.py +253 -0
- hackagent/api/key/__init__.py +1 -0
- hackagent/api/key/key_create.py +179 -0
- hackagent/api/key/key_destroy.py +103 -0
- hackagent/api/key/key_list.py +170 -0
- hackagent/api/key/key_retrieve.py +162 -0
- hackagent/api/organization/__init__.py +1 -0
- hackagent/api/organization/organization_create.py +208 -0
- hackagent/api/organization/organization_destroy.py +104 -0
- hackagent/api/organization/organization_list.py +170 -0
- hackagent/api/organization/organization_me_retrieve.py +126 -0
- hackagent/api/organization/organization_partial_update.py +222 -0
- hackagent/api/organization/organization_retrieve.py +163 -0
- hackagent/api/organization/organization_update.py +222 -0
- hackagent/api/prompt/__init__.py +1 -0
- hackagent/api/prompt/prompt_create.py +171 -0
- hackagent/api/prompt/prompt_destroy.py +104 -0
- hackagent/api/prompt/prompt_list.py +185 -0
- hackagent/api/prompt/prompt_partial_update.py +185 -0
- hackagent/api/prompt/prompt_retrieve.py +163 -0
- hackagent/api/prompt/prompt_update.py +185 -0
- hackagent/api/result/__init__.py +1 -0
- hackagent/api/result/result_create.py +175 -0
- hackagent/api/result/result_destroy.py +106 -0
- hackagent/api/result/result_list.py +249 -0
- hackagent/api/result/result_partial_update.py +193 -0
- hackagent/api/result/result_retrieve.py +167 -0
- hackagent/api/result/result_trace_create.py +177 -0
- hackagent/api/result/result_update.py +189 -0
- hackagent/api/run/__init__.py +1 -0
- hackagent/api/run/run_create.py +187 -0
- hackagent/api/run/run_destroy.py +112 -0
- hackagent/api/run/run_list.py +291 -0
- hackagent/api/run/run_partial_update.py +201 -0
- hackagent/api/run/run_result_create.py +177 -0
- hackagent/api/run/run_retrieve.py +179 -0
- hackagent/api/run/run_run_tests_create.py +187 -0
- hackagent/api/run/run_update.py +201 -0
- hackagent/api/user/__init__.py +1 -0
- hackagent/api/user/user_create.py +212 -0
- hackagent/api/user/user_destroy.py +106 -0
- hackagent/api/user/user_list.py +174 -0
- hackagent/api/user/user_me_retrieve.py +126 -0
- hackagent/api/user/user_me_update.py +196 -0
- hackagent/api/user/user_partial_update.py +226 -0
- hackagent/api/user/user_retrieve.py +167 -0
- hackagent/api/user/user_update.py +226 -0
- hackagent/attacks/AdvPrefix/__init__.py +41 -0
- hackagent/attacks/AdvPrefix/completions.py +416 -0
- hackagent/attacks/AdvPrefix/config.py +259 -0
- hackagent/attacks/AdvPrefix/evaluation.py +745 -0
- hackagent/attacks/AdvPrefix/evaluators.py +564 -0
- hackagent/attacks/AdvPrefix/generate.py +711 -0
- hackagent/attacks/AdvPrefix/utils.py +307 -0
- hackagent/attacks/__init__.py +35 -0
- hackagent/attacks/advprefix.py +507 -0
- hackagent/attacks/base.py +106 -0
- hackagent/attacks/strategies.py +906 -0
- hackagent/cli/__init__.py +19 -0
- hackagent/cli/commands/__init__.py +20 -0
- hackagent/cli/commands/agent.py +100 -0
- hackagent/cli/commands/attack.py +417 -0
- hackagent/cli/commands/config.py +301 -0
- hackagent/cli/commands/results.py +327 -0
- hackagent/cli/config.py +249 -0
- hackagent/cli/main.py +515 -0
- hackagent/cli/tui/__init__.py +31 -0
- hackagent/cli/tui/actions_logger.py +200 -0
- hackagent/cli/tui/app.py +288 -0
- hackagent/cli/tui/base.py +137 -0
- hackagent/cli/tui/logger.py +318 -0
- hackagent/cli/tui/views/__init__.py +33 -0
- hackagent/cli/tui/views/agents.py +488 -0
- hackagent/cli/tui/views/attacks.py +624 -0
- hackagent/cli/tui/views/config.py +244 -0
- hackagent/cli/tui/views/dashboard.py +307 -0
- hackagent/cli/tui/views/results.py +1210 -0
- hackagent/cli/tui/widgets/__init__.py +24 -0
- hackagent/cli/tui/widgets/actions.py +346 -0
- hackagent/cli/tui/widgets/logs.py +435 -0
- hackagent/cli/utils.py +276 -0
- hackagent/client.py +286 -0
- hackagent/errors.py +37 -0
- hackagent/logger.py +83 -0
- hackagent/models/__init__.py +109 -0
- hackagent/models/agent.py +223 -0
- hackagent/models/agent_request.py +129 -0
- hackagent/models/api_token_log.py +184 -0
- hackagent/models/attack.py +154 -0
- hackagent/models/attack_request.py +82 -0
- hackagent/models/checkout_session_request_request.py +76 -0
- hackagent/models/checkout_session_response.py +59 -0
- hackagent/models/choice.py +81 -0
- hackagent/models/choice_message.py +67 -0
- hackagent/models/evaluation_status_enum.py +14 -0
- hackagent/models/generate_error_response.py +59 -0
- hackagent/models/generate_request_request.py +212 -0
- hackagent/models/generate_success_response.py +115 -0
- hackagent/models/generic_error_response.py +70 -0
- hackagent/models/message_request.py +67 -0
- hackagent/models/organization.py +102 -0
- hackagent/models/organization_minimal.py +68 -0
- hackagent/models/organization_request.py +71 -0
- hackagent/models/paginated_agent_list.py +123 -0
- hackagent/models/paginated_api_token_log_list.py +123 -0
- hackagent/models/paginated_attack_list.py +123 -0
- hackagent/models/paginated_organization_list.py +123 -0
- hackagent/models/paginated_prompt_list.py +123 -0
- hackagent/models/paginated_result_list.py +123 -0
- hackagent/models/paginated_run_list.py +123 -0
- hackagent/models/paginated_user_api_key_list.py +123 -0
- hackagent/models/paginated_user_profile_list.py +123 -0
- hackagent/models/patched_agent_request.py +128 -0
- hackagent/models/patched_attack_request.py +92 -0
- hackagent/models/patched_organization_request.py +71 -0
- hackagent/models/patched_prompt_request.py +125 -0
- hackagent/models/patched_result_request.py +237 -0
- hackagent/models/patched_run_request.py +138 -0
- hackagent/models/patched_user_profile_request.py +99 -0
- hackagent/models/prompt.py +220 -0
- hackagent/models/prompt_request.py +126 -0
- hackagent/models/result.py +294 -0
- hackagent/models/result_list_evaluation_status.py +14 -0
- hackagent/models/result_request.py +232 -0
- hackagent/models/run.py +233 -0
- hackagent/models/run_list_status.py +12 -0
- hackagent/models/run_request.py +133 -0
- hackagent/models/status_enum.py +12 -0
- hackagent/models/step_type_enum.py +14 -0
- hackagent/models/trace.py +121 -0
- hackagent/models/trace_request.py +94 -0
- hackagent/models/usage.py +75 -0
- hackagent/models/user_api_key.py +201 -0
- hackagent/models/user_api_key_request.py +73 -0
- hackagent/models/user_profile.py +135 -0
- hackagent/models/user_profile_minimal.py +76 -0
- hackagent/models/user_profile_request.py +99 -0
- hackagent/router/__init__.py +25 -0
- hackagent/router/adapters/__init__.py +20 -0
- hackagent/router/adapters/base.py +63 -0
- hackagent/router/adapters/google_adk.py +671 -0
- hackagent/router/adapters/litellm_adapter.py +524 -0
- hackagent/router/adapters/openai_adapter.py +426 -0
- hackagent/router/router.py +969 -0
- hackagent/router/types.py +54 -0
- hackagent/tracking/__init__.py +42 -0
- hackagent/tracking/context.py +163 -0
- hackagent/tracking/decorators.py +299 -0
- hackagent/tracking/tracker.py +441 -0
- hackagent/types.py +54 -0
- hackagent/utils.py +194 -0
- hackagent/vulnerabilities/__init__.py +13 -0
- hackagent/vulnerabilities/prompts.py +81 -0
- hackagent-0.3.1.dist-info/METADATA +122 -0
- hackagent-0.3.1.dist-info/RECORD +183 -0
- hackagent-0.3.1.dist-info/WHEEL +4 -0
- hackagent-0.3.1.dist-info/entry_points.txt +2 -0
- hackagent-0.3.1.dist-info/licenses/LICENSE +202 -0
hackagent/client.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import ssl
|
|
2
|
+
from typing import Any, Optional, Union
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
from attrs import define, evolve, field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@define
|
|
9
|
+
class Client:
|
|
10
|
+
"""A class for keeping track of data related to the API
|
|
11
|
+
|
|
12
|
+
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
|
|
13
|
+
|
|
14
|
+
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
|
|
15
|
+
|
|
16
|
+
``cookies``: A dictionary of cookies to be sent with every request
|
|
17
|
+
|
|
18
|
+
``headers``: A dictionary of headers to be sent with every request
|
|
19
|
+
|
|
20
|
+
``timeout``: The maximum amount of a time a request can take. API functions will raise
|
|
21
|
+
httpx.TimeoutException if this is exceeded.
|
|
22
|
+
|
|
23
|
+
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
|
|
24
|
+
but can be set to False for testing purposes.
|
|
25
|
+
|
|
26
|
+
``follow_redirects``: Whether or not to follow redirects. Default value is False.
|
|
27
|
+
|
|
28
|
+
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
Attributes:
|
|
32
|
+
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
|
|
33
|
+
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
|
|
34
|
+
argument to the constructor.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
|
|
38
|
+
_base_url: str = field(alias="base_url")
|
|
39
|
+
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
|
|
40
|
+
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
|
|
41
|
+
_timeout: Optional[httpx.Timeout] = field(
|
|
42
|
+
default=None, kw_only=True, alias="timeout"
|
|
43
|
+
)
|
|
44
|
+
_verify_ssl: Union[str, bool, ssl.SSLContext] = field(
|
|
45
|
+
default=True, kw_only=True, alias="verify_ssl"
|
|
46
|
+
)
|
|
47
|
+
_follow_redirects: bool = field(
|
|
48
|
+
default=False, kw_only=True, alias="follow_redirects"
|
|
49
|
+
)
|
|
50
|
+
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
|
|
51
|
+
_client: Optional[httpx.Client] = field(default=None, init=False)
|
|
52
|
+
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
|
|
53
|
+
|
|
54
|
+
def with_headers(self, headers: dict[str, str]) -> "Client":
|
|
55
|
+
"""Get a new client matching this one with additional headers"""
|
|
56
|
+
if self._client is not None:
|
|
57
|
+
self._client.headers.update(headers)
|
|
58
|
+
if self._async_client is not None:
|
|
59
|
+
self._async_client.headers.update(headers)
|
|
60
|
+
return evolve(self, headers={**self._headers, **headers})
|
|
61
|
+
|
|
62
|
+
def with_cookies(self, cookies: dict[str, str]) -> "Client":
|
|
63
|
+
"""Get a new client matching this one with additional cookies"""
|
|
64
|
+
if self._client is not None:
|
|
65
|
+
self._client.cookies.update(cookies)
|
|
66
|
+
if self._async_client is not None:
|
|
67
|
+
self._async_client.cookies.update(cookies)
|
|
68
|
+
return evolve(self, cookies={**self._cookies, **cookies})
|
|
69
|
+
|
|
70
|
+
def with_timeout(self, timeout: httpx.Timeout) -> "Client":
|
|
71
|
+
"""Get a new client matching this one with a new timeout (in seconds)"""
|
|
72
|
+
if self._client is not None:
|
|
73
|
+
self._client.timeout = timeout
|
|
74
|
+
if self._async_client is not None:
|
|
75
|
+
self._async_client.timeout = timeout
|
|
76
|
+
return evolve(self, timeout=timeout)
|
|
77
|
+
|
|
78
|
+
def set_httpx_client(self, client: httpx.Client) -> "Client":
|
|
79
|
+
"""Manually set the underlying httpx.Client
|
|
80
|
+
|
|
81
|
+
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
|
|
82
|
+
"""
|
|
83
|
+
self._client = client
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
def get_httpx_client(self) -> httpx.Client:
|
|
87
|
+
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
|
|
88
|
+
if self._client is None:
|
|
89
|
+
self._client = httpx.Client(
|
|
90
|
+
base_url=self._base_url,
|
|
91
|
+
cookies=self._cookies,
|
|
92
|
+
headers=self._headers,
|
|
93
|
+
timeout=self._timeout,
|
|
94
|
+
verify=self._verify_ssl,
|
|
95
|
+
follow_redirects=self._follow_redirects,
|
|
96
|
+
**self._httpx_args,
|
|
97
|
+
)
|
|
98
|
+
return self._client
|
|
99
|
+
|
|
100
|
+
def __enter__(self) -> "Client":
|
|
101
|
+
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
|
|
102
|
+
self.get_httpx_client().__enter__()
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def __exit__(self, *args: Any, **kwargs: Any) -> None:
|
|
106
|
+
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
|
|
107
|
+
self.get_httpx_client().__exit__(*args, **kwargs)
|
|
108
|
+
|
|
109
|
+
def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":
|
|
110
|
+
"""Manually the underlying httpx.AsyncClient
|
|
111
|
+
|
|
112
|
+
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
|
|
113
|
+
"""
|
|
114
|
+
self._async_client = async_client
|
|
115
|
+
return self
|
|
116
|
+
|
|
117
|
+
def get_async_httpx_client(self) -> httpx.AsyncClient:
|
|
118
|
+
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
|
|
119
|
+
if self._async_client is None:
|
|
120
|
+
self._async_client = httpx.AsyncClient(
|
|
121
|
+
base_url=self._base_url,
|
|
122
|
+
cookies=self._cookies,
|
|
123
|
+
headers=self._headers,
|
|
124
|
+
timeout=self._timeout,
|
|
125
|
+
verify=self._verify_ssl,
|
|
126
|
+
follow_redirects=self._follow_redirects,
|
|
127
|
+
**self._httpx_args,
|
|
128
|
+
)
|
|
129
|
+
return self._async_client
|
|
130
|
+
|
|
131
|
+
async def __aenter__(self) -> "Client":
|
|
132
|
+
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
|
|
133
|
+
await self.get_async_httpx_client().__aenter__()
|
|
134
|
+
return self
|
|
135
|
+
|
|
136
|
+
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
|
|
137
|
+
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
|
|
138
|
+
await self.get_async_httpx_client().__aexit__(*args, **kwargs)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@define
|
|
142
|
+
class AuthenticatedClient:
|
|
143
|
+
"""A Client which has been authenticated for use on secured endpoints
|
|
144
|
+
|
|
145
|
+
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
|
|
146
|
+
|
|
147
|
+
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
|
|
148
|
+
|
|
149
|
+
``cookies``: A dictionary of cookies to be sent with every request
|
|
150
|
+
|
|
151
|
+
``headers``: A dictionary of headers to be sent with every request
|
|
152
|
+
|
|
153
|
+
``timeout``: The maximum amount of a time a request can take. API functions will raise
|
|
154
|
+
httpx.TimeoutException if this is exceeded.
|
|
155
|
+
|
|
156
|
+
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
|
|
157
|
+
but can be set to False for testing purposes.
|
|
158
|
+
|
|
159
|
+
``follow_redirects``: Whether or not to follow redirects. Default value is False.
|
|
160
|
+
|
|
161
|
+
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
Attributes:
|
|
165
|
+
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
|
|
166
|
+
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
|
|
167
|
+
argument to the constructor.
|
|
168
|
+
token: The token to use for authentication
|
|
169
|
+
prefix: The prefix to use for the Authorization header
|
|
170
|
+
auth_header_name: The name of the Authorization header
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
|
|
174
|
+
_base_url: str = field(alias="base_url")
|
|
175
|
+
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
|
|
176
|
+
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
|
|
177
|
+
_timeout: Optional[httpx.Timeout] = field(
|
|
178
|
+
default=None, kw_only=True, alias="timeout"
|
|
179
|
+
)
|
|
180
|
+
_verify_ssl: Union[str, bool, ssl.SSLContext] = field(
|
|
181
|
+
default=True, kw_only=True, alias="verify_ssl"
|
|
182
|
+
)
|
|
183
|
+
_follow_redirects: bool = field(
|
|
184
|
+
default=False, kw_only=True, alias="follow_redirects"
|
|
185
|
+
)
|
|
186
|
+
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
|
|
187
|
+
_client: Optional[httpx.Client] = field(default=None, init=False)
|
|
188
|
+
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
|
|
189
|
+
|
|
190
|
+
token: str
|
|
191
|
+
prefix: str = "Bearer"
|
|
192
|
+
auth_header_name: str = "Authorization"
|
|
193
|
+
|
|
194
|
+
def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
|
|
195
|
+
"""Get a new client matching this one with additional headers"""
|
|
196
|
+
if self._client is not None:
|
|
197
|
+
self._client.headers.update(headers)
|
|
198
|
+
if self._async_client is not None:
|
|
199
|
+
self._async_client.headers.update(headers)
|
|
200
|
+
return evolve(self, headers={**self._headers, **headers})
|
|
201
|
+
|
|
202
|
+
def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
|
|
203
|
+
"""Get a new client matching this one with additional cookies"""
|
|
204
|
+
if self._client is not None:
|
|
205
|
+
self._client.cookies.update(cookies)
|
|
206
|
+
if self._async_client is not None:
|
|
207
|
+
self._async_client.cookies.update(cookies)
|
|
208
|
+
return evolve(self, cookies={**self._cookies, **cookies})
|
|
209
|
+
|
|
210
|
+
def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
|
|
211
|
+
"""Get a new client matching this one with a new timeout (in seconds)"""
|
|
212
|
+
if self._client is not None:
|
|
213
|
+
self._client.timeout = timeout
|
|
214
|
+
if self._async_client is not None:
|
|
215
|
+
self._async_client.timeout = timeout
|
|
216
|
+
return evolve(self, timeout=timeout)
|
|
217
|
+
|
|
218
|
+
def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":
|
|
219
|
+
"""Manually set the underlying httpx.Client
|
|
220
|
+
|
|
221
|
+
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
|
|
222
|
+
"""
|
|
223
|
+
self._client = client
|
|
224
|
+
return self
|
|
225
|
+
|
|
226
|
+
def get_httpx_client(self) -> httpx.Client:
|
|
227
|
+
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
|
|
228
|
+
if self._client is None:
|
|
229
|
+
self._headers[self.auth_header_name] = (
|
|
230
|
+
f"{self.prefix} {self.token}" if self.prefix else self.token
|
|
231
|
+
)
|
|
232
|
+
self._client = httpx.Client(
|
|
233
|
+
base_url=self._base_url,
|
|
234
|
+
cookies=self._cookies,
|
|
235
|
+
headers=self._headers,
|
|
236
|
+
timeout=self._timeout,
|
|
237
|
+
verify=self._verify_ssl,
|
|
238
|
+
follow_redirects=self._follow_redirects,
|
|
239
|
+
**self._httpx_args,
|
|
240
|
+
)
|
|
241
|
+
return self._client
|
|
242
|
+
|
|
243
|
+
def __enter__(self) -> "AuthenticatedClient":
|
|
244
|
+
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
|
|
245
|
+
self.get_httpx_client().__enter__()
|
|
246
|
+
return self
|
|
247
|
+
|
|
248
|
+
def __exit__(self, *args: Any, **kwargs: Any) -> None:
|
|
249
|
+
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
|
|
250
|
+
self.get_httpx_client().__exit__(*args, **kwargs)
|
|
251
|
+
|
|
252
|
+
def set_async_httpx_client(
|
|
253
|
+
self, async_client: httpx.AsyncClient
|
|
254
|
+
) -> "AuthenticatedClient":
|
|
255
|
+
"""Manually the underlying httpx.AsyncClient
|
|
256
|
+
|
|
257
|
+
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
|
|
258
|
+
"""
|
|
259
|
+
self._async_client = async_client
|
|
260
|
+
return self
|
|
261
|
+
|
|
262
|
+
def get_async_httpx_client(self) -> httpx.AsyncClient:
|
|
263
|
+
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
|
|
264
|
+
if self._async_client is None:
|
|
265
|
+
self._headers[self.auth_header_name] = (
|
|
266
|
+
f"{self.prefix} {self.token}" if self.prefix else self.token
|
|
267
|
+
)
|
|
268
|
+
self._async_client = httpx.AsyncClient(
|
|
269
|
+
base_url=self._base_url,
|
|
270
|
+
cookies=self._cookies,
|
|
271
|
+
headers=self._headers,
|
|
272
|
+
timeout=self._timeout,
|
|
273
|
+
verify=self._verify_ssl,
|
|
274
|
+
follow_redirects=self._follow_redirects,
|
|
275
|
+
**self._httpx_args,
|
|
276
|
+
)
|
|
277
|
+
return self._async_client
|
|
278
|
+
|
|
279
|
+
async def __aenter__(self) -> "AuthenticatedClient":
|
|
280
|
+
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
|
|
281
|
+
await self.get_async_httpx_client().__aenter__()
|
|
282
|
+
return self
|
|
283
|
+
|
|
284
|
+
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
|
|
285
|
+
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
|
|
286
|
+
await self.get_async_httpx_client().__aexit__(*args, **kwargs)
|
hackagent/errors.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Contains shared errors types that can be raised from API functions"""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class UnexpectedStatus(Exception):
|
|
5
|
+
"""Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""
|
|
6
|
+
|
|
7
|
+
def __init__(self, status_code: int, content: bytes):
|
|
8
|
+
self.status_code = status_code
|
|
9
|
+
self.content = content
|
|
10
|
+
|
|
11
|
+
super().__init__(
|
|
12
|
+
f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class HackAgentError(Exception):
|
|
17
|
+
"""Base exception class for HackAgent errors"""
|
|
18
|
+
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ApiError(HackAgentError):
|
|
23
|
+
"""Raised when an API call fails"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self, message: str, status_code: int | None = None, response: dict | None = None
|
|
27
|
+
):
|
|
28
|
+
self.message = message
|
|
29
|
+
self.status_code = status_code
|
|
30
|
+
self.response = response
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Alias for backward compatibility with tests
|
|
35
|
+
UnexpectedStatusError = UnexpectedStatus
|
|
36
|
+
|
|
37
|
+
__all__ = ["UnexpectedStatus", "UnexpectedStatusError", "HackAgentError", "ApiError"]
|
hackagent/logger.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Copyright 2025 - AI4I. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
from rich.logging import RichHandler
|
|
20
|
+
|
|
21
|
+
_rich_handler_configured_for_package = False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def setup_package_logging(
|
|
25
|
+
logger_name: str = "hackagent", default_level_str: str = "WARNING"
|
|
26
|
+
):
|
|
27
|
+
"""Configures RichHandler for the specified logger if not already set."""
|
|
28
|
+
global _rich_handler_configured_for_package
|
|
29
|
+
|
|
30
|
+
package_logger = logging.getLogger(logger_name)
|
|
31
|
+
|
|
32
|
+
if logger_name == "hackagent" and _rich_handler_configured_for_package:
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
has_console_handler = any(
|
|
36
|
+
isinstance(h, logging.StreamHandler) for h in package_logger.handlers
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
if not has_console_handler:
|
|
40
|
+
log_level_env = os.getenv(
|
|
41
|
+
f"{logger_name.upper()}_LOG_LEVEL", default_level_str
|
|
42
|
+
).upper()
|
|
43
|
+
level = getattr(logging, log_level_env, logging.WARNING)
|
|
44
|
+
package_logger.setLevel(level)
|
|
45
|
+
|
|
46
|
+
rich_handler = RichHandler(
|
|
47
|
+
show_time=True,
|
|
48
|
+
show_level=True,
|
|
49
|
+
show_path=False,
|
|
50
|
+
markup=True,
|
|
51
|
+
rich_tracebacks=True,
|
|
52
|
+
tracebacks_show_locals=False,
|
|
53
|
+
)
|
|
54
|
+
package_logger.addHandler(rich_handler)
|
|
55
|
+
package_logger.propagate = False # Avoid duplicate logs with root logger
|
|
56
|
+
|
|
57
|
+
if logger_name == "hackagent":
|
|
58
|
+
_rich_handler_configured_for_package = True
|
|
59
|
+
# Set default levels for common noisy libraries
|
|
60
|
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
61
|
+
logging.getLogger("litellm").setLevel(logging.WARNING)
|
|
62
|
+
# Add other libraries here if needed, e.g.:
|
|
63
|
+
# logging.getLogger("another_library").setLevel(logging.WARNING)
|
|
64
|
+
|
|
65
|
+
# package_logger.debug(f"RichHandler configured for '{logger_name}' logger at level {level}.")
|
|
66
|
+
|
|
67
|
+
elif any(isinstance(h, RichHandler) for h in package_logger.handlers):
|
|
68
|
+
if logger_name == "hackagent":
|
|
69
|
+
_rich_handler_configured_for_package = True
|
|
70
|
+
|
|
71
|
+
return package_logger
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_logger(name: str) -> logging.Logger:
|
|
75
|
+
"""
|
|
76
|
+
Retrieves a logger instance.
|
|
77
|
+
If the logger is 'hackagent' or starts with 'hackagent.',
|
|
78
|
+
it ensures the package logging is set up.
|
|
79
|
+
"""
|
|
80
|
+
if name == "hackagent" or name.startswith("hackagent."):
|
|
81
|
+
# Ensure base "hackagent" logger is configured first
|
|
82
|
+
setup_package_logging(logger_name="hackagent")
|
|
83
|
+
return logging.getLogger(name)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Contains all the data models used in inputs/outputs"""
|
|
2
|
+
|
|
3
|
+
from .agent import Agent
|
|
4
|
+
from .agent_request import AgentRequest
|
|
5
|
+
from .api_token_log import APITokenLog
|
|
6
|
+
from .attack import Attack
|
|
7
|
+
from .attack_request import AttackRequest
|
|
8
|
+
from .checkout_session_request_request import CheckoutSessionRequestRequest
|
|
9
|
+
from .checkout_session_response import CheckoutSessionResponse
|
|
10
|
+
from .choice import Choice
|
|
11
|
+
from .choice_message import ChoiceMessage
|
|
12
|
+
from .evaluation_status_enum import EvaluationStatusEnum
|
|
13
|
+
from .generate_error_response import GenerateErrorResponse
|
|
14
|
+
from .generate_request_request import GenerateRequestRequest
|
|
15
|
+
from .generate_success_response import GenerateSuccessResponse
|
|
16
|
+
from .generic_error_response import GenericErrorResponse
|
|
17
|
+
from .message_request import MessageRequest
|
|
18
|
+
from .organization import Organization
|
|
19
|
+
from .organization_minimal import OrganizationMinimal
|
|
20
|
+
from .organization_request import OrganizationRequest
|
|
21
|
+
from .paginated_agent_list import PaginatedAgentList
|
|
22
|
+
from .paginated_api_token_log_list import PaginatedAPITokenLogList
|
|
23
|
+
from .paginated_attack_list import PaginatedAttackList
|
|
24
|
+
from .paginated_organization_list import PaginatedOrganizationList
|
|
25
|
+
from .paginated_prompt_list import PaginatedPromptList
|
|
26
|
+
from .paginated_result_list import PaginatedResultList
|
|
27
|
+
from .paginated_run_list import PaginatedRunList
|
|
28
|
+
from .paginated_user_api_key_list import PaginatedUserAPIKeyList
|
|
29
|
+
from .paginated_user_profile_list import PaginatedUserProfileList
|
|
30
|
+
from .patched_agent_request import PatchedAgentRequest
|
|
31
|
+
from .patched_attack_request import PatchedAttackRequest
|
|
32
|
+
from .patched_organization_request import PatchedOrganizationRequest
|
|
33
|
+
from .patched_prompt_request import PatchedPromptRequest
|
|
34
|
+
from .patched_result_request import PatchedResultRequest
|
|
35
|
+
from .patched_run_request import PatchedRunRequest
|
|
36
|
+
from .patched_user_profile_request import PatchedUserProfileRequest
|
|
37
|
+
from .prompt import Prompt
|
|
38
|
+
from .prompt_request import PromptRequest
|
|
39
|
+
from .result import Result
|
|
40
|
+
from .result_list_evaluation_status import ResultListEvaluationStatus
|
|
41
|
+
from .result_request import ResultRequest
|
|
42
|
+
from .run import Run
|
|
43
|
+
from .run_list_status import RunListStatus
|
|
44
|
+
from .run_request import RunRequest
|
|
45
|
+
from .status_enum import StatusEnum
|
|
46
|
+
from .step_type_enum import StepTypeEnum
|
|
47
|
+
from .trace import Trace
|
|
48
|
+
from .trace_request import TraceRequest
|
|
49
|
+
from .usage import Usage
|
|
50
|
+
from .user_api_key import UserAPIKey
|
|
51
|
+
from .user_api_key_request import UserAPIKeyRequest
|
|
52
|
+
from .user_profile import UserProfile
|
|
53
|
+
from .user_profile_minimal import UserProfileMinimal
|
|
54
|
+
from .user_profile_request import UserProfileRequest
|
|
55
|
+
|
|
56
|
+
__all__ = (
|
|
57
|
+
"Agent",
|
|
58
|
+
"AgentRequest",
|
|
59
|
+
"APITokenLog",
|
|
60
|
+
"Attack",
|
|
61
|
+
"AttackRequest",
|
|
62
|
+
"CheckoutSessionRequestRequest",
|
|
63
|
+
"CheckoutSessionResponse",
|
|
64
|
+
"Choice",
|
|
65
|
+
"ChoiceMessage",
|
|
66
|
+
"EvaluationStatusEnum",
|
|
67
|
+
"GenerateErrorResponse",
|
|
68
|
+
"GenerateRequestRequest",
|
|
69
|
+
"GenerateSuccessResponse",
|
|
70
|
+
"GenericErrorResponse",
|
|
71
|
+
"MessageRequest",
|
|
72
|
+
"Organization",
|
|
73
|
+
"OrganizationMinimal",
|
|
74
|
+
"OrganizationRequest",
|
|
75
|
+
"PaginatedAgentList",
|
|
76
|
+
"PaginatedAPITokenLogList",
|
|
77
|
+
"PaginatedAttackList",
|
|
78
|
+
"PaginatedOrganizationList",
|
|
79
|
+
"PaginatedPromptList",
|
|
80
|
+
"PaginatedResultList",
|
|
81
|
+
"PaginatedRunList",
|
|
82
|
+
"PaginatedUserAPIKeyList",
|
|
83
|
+
"PaginatedUserProfileList",
|
|
84
|
+
"PatchedAgentRequest",
|
|
85
|
+
"PatchedAttackRequest",
|
|
86
|
+
"PatchedOrganizationRequest",
|
|
87
|
+
"PatchedPromptRequest",
|
|
88
|
+
"PatchedResultRequest",
|
|
89
|
+
"PatchedRunRequest",
|
|
90
|
+
"PatchedUserProfileRequest",
|
|
91
|
+
"Prompt",
|
|
92
|
+
"PromptRequest",
|
|
93
|
+
"Result",
|
|
94
|
+
"ResultListEvaluationStatus",
|
|
95
|
+
"ResultRequest",
|
|
96
|
+
"Run",
|
|
97
|
+
"RunListStatus",
|
|
98
|
+
"RunRequest",
|
|
99
|
+
"StatusEnum",
|
|
100
|
+
"StepTypeEnum",
|
|
101
|
+
"Trace",
|
|
102
|
+
"TraceRequest",
|
|
103
|
+
"Usage",
|
|
104
|
+
"UserAPIKey",
|
|
105
|
+
"UserAPIKeyRequest",
|
|
106
|
+
"UserProfile",
|
|
107
|
+
"UserProfileMinimal",
|
|
108
|
+
"UserProfileRequest",
|
|
109
|
+
)
|