hackagent 0.1.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.
Files changed (117) hide show
  1. hackagent/__init__.py +23 -0
  2. hackagent/agent.py +193 -0
  3. hackagent/api/__init__.py +1 -0
  4. hackagent/api/agent/__init__.py +1 -0
  5. hackagent/api/agent/agent_create.py +340 -0
  6. hackagent/api/agent/agent_destroy.py +136 -0
  7. hackagent/api/agent/agent_list.py +234 -0
  8. hackagent/api/agent/agent_partial_update.py +354 -0
  9. hackagent/api/agent/agent_retrieve.py +227 -0
  10. hackagent/api/agent/agent_update.py +354 -0
  11. hackagent/api/attack/__init__.py +1 -0
  12. hackagent/api/attack/attack_create.py +264 -0
  13. hackagent/api/attack/attack_destroy.py +140 -0
  14. hackagent/api/attack/attack_list.py +242 -0
  15. hackagent/api/attack/attack_partial_update.py +278 -0
  16. hackagent/api/attack/attack_retrieve.py +235 -0
  17. hackagent/api/attack/attack_update.py +278 -0
  18. hackagent/api/key/__init__.py +1 -0
  19. hackagent/api/key/key_create.py +168 -0
  20. hackagent/api/key/key_destroy.py +97 -0
  21. hackagent/api/key/key_list.py +158 -0
  22. hackagent/api/key/key_retrieve.py +150 -0
  23. hackagent/api/prompt/__init__.py +1 -0
  24. hackagent/api/prompt/prompt_create.py +160 -0
  25. hackagent/api/prompt/prompt_destroy.py +98 -0
  26. hackagent/api/prompt/prompt_list.py +173 -0
  27. hackagent/api/prompt/prompt_partial_update.py +174 -0
  28. hackagent/api/prompt/prompt_retrieve.py +151 -0
  29. hackagent/api/prompt/prompt_update.py +174 -0
  30. hackagent/api/result/__init__.py +1 -0
  31. hackagent/api/result/result_create.py +160 -0
  32. hackagent/api/result/result_destroy.py +98 -0
  33. hackagent/api/result/result_list.py +233 -0
  34. hackagent/api/result/result_partial_update.py +178 -0
  35. hackagent/api/result/result_retrieve.py +151 -0
  36. hackagent/api/result/result_trace_create.py +178 -0
  37. hackagent/api/result/result_update.py +174 -0
  38. hackagent/api/run/__init__.py +1 -0
  39. hackagent/api/run/run_create.py +172 -0
  40. hackagent/api/run/run_destroy.py +104 -0
  41. hackagent/api/run/run_list.py +260 -0
  42. hackagent/api/run/run_partial_update.py +186 -0
  43. hackagent/api/run/run_result_create.py +178 -0
  44. hackagent/api/run/run_retrieve.py +163 -0
  45. hackagent/api/run/run_run_tests_create.py +172 -0
  46. hackagent/api/run/run_update.py +186 -0
  47. hackagent/attacks/AdvPrefix/README.md +7 -0
  48. hackagent/attacks/AdvPrefix/__init__.py +0 -0
  49. hackagent/attacks/AdvPrefix/completer.py +438 -0
  50. hackagent/attacks/AdvPrefix/config.py +59 -0
  51. hackagent/attacks/AdvPrefix/preprocessing.py +521 -0
  52. hackagent/attacks/AdvPrefix/scorer.py +259 -0
  53. hackagent/attacks/AdvPrefix/scorer_parser.py +498 -0
  54. hackagent/attacks/AdvPrefix/selector.py +246 -0
  55. hackagent/attacks/AdvPrefix/step1_generate.py +324 -0
  56. hackagent/attacks/AdvPrefix/step4_compute_ce.py +293 -0
  57. hackagent/attacks/AdvPrefix/step6_get_completions.py +387 -0
  58. hackagent/attacks/AdvPrefix/step7_evaluate_responses.py +289 -0
  59. hackagent/attacks/AdvPrefix/step8_aggregate_evaluations.py +177 -0
  60. hackagent/attacks/AdvPrefix/step9_select_prefixes.py +59 -0
  61. hackagent/attacks/AdvPrefix/utils.py +192 -0
  62. hackagent/attacks/__init__.py +6 -0
  63. hackagent/attacks/advprefix.py +1136 -0
  64. hackagent/attacks/base.py +50 -0
  65. hackagent/attacks/strategies.py +539 -0
  66. hackagent/branding.py +143 -0
  67. hackagent/client.py +328 -0
  68. hackagent/errors.py +31 -0
  69. hackagent/logger.py +67 -0
  70. hackagent/models/__init__.py +71 -0
  71. hackagent/models/agent.py +240 -0
  72. hackagent/models/agent_request.py +169 -0
  73. hackagent/models/agent_type_enum.py +12 -0
  74. hackagent/models/attack.py +154 -0
  75. hackagent/models/attack_request.py +82 -0
  76. hackagent/models/evaluation_status_enum.py +14 -0
  77. hackagent/models/organization_minimal.py +68 -0
  78. hackagent/models/paginated_agent_list.py +123 -0
  79. hackagent/models/paginated_attack_list.py +123 -0
  80. hackagent/models/paginated_prompt_list.py +123 -0
  81. hackagent/models/paginated_result_list.py +123 -0
  82. hackagent/models/paginated_run_list.py +123 -0
  83. hackagent/models/paginated_user_api_key_list.py +123 -0
  84. hackagent/models/patched_agent_request.py +176 -0
  85. hackagent/models/patched_attack_request.py +92 -0
  86. hackagent/models/patched_prompt_request.py +162 -0
  87. hackagent/models/patched_result_request.py +237 -0
  88. hackagent/models/patched_run_request.py +138 -0
  89. hackagent/models/prompt.py +226 -0
  90. hackagent/models/prompt_request.py +155 -0
  91. hackagent/models/result.py +294 -0
  92. hackagent/models/result_list_evaluation_status.py +14 -0
  93. hackagent/models/result_request.py +232 -0
  94. hackagent/models/run.py +233 -0
  95. hackagent/models/run_list_status.py +12 -0
  96. hackagent/models/run_request.py +133 -0
  97. hackagent/models/status_enum.py +12 -0
  98. hackagent/models/step_type_enum.py +14 -0
  99. hackagent/models/trace.py +121 -0
  100. hackagent/models/trace_request.py +94 -0
  101. hackagent/models/user_api_key.py +201 -0
  102. hackagent/models/user_api_key_request.py +73 -0
  103. hackagent/models/user_profile_minimal.py +76 -0
  104. hackagent/py.typed +1 -0
  105. hackagent/router/__init__.py +11 -0
  106. hackagent/router/adapters/__init__.py +5 -0
  107. hackagent/router/adapters/google_adk.py +658 -0
  108. hackagent/router/adapters/litellm_adapter.py +290 -0
  109. hackagent/router/base.py +48 -0
  110. hackagent/router/router.py +753 -0
  111. hackagent/types.py +46 -0
  112. hackagent/utils.py +61 -0
  113. hackagent/vulnerabilities/__init__.py +0 -0
  114. hackagent-0.1.0.dist-info/LICENSE +202 -0
  115. hackagent-0.1.0.dist-info/METADATA +173 -0
  116. hackagent-0.1.0.dist-info/RECORD +117 -0
  117. hackagent-0.1.0.dist-info/WHEEL +4 -0
hackagent/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """A client library for accessing HackAgent API"""
2
+
3
+ from .client import AuthenticatedClient, Client
4
+ from .agent import HackAgent
5
+ from .errors import HackAgentError, ApiError, UnexpectedStatusError
6
+ from .models import Agent, Prompt, Result, Run
7
+ from .logger import setup_package_logging
8
+
9
+ setup_package_logging()
10
+
11
+
12
+ __all__ = (
13
+ "AuthenticatedClient",
14
+ "Client",
15
+ "HackAgent",
16
+ "HackAgentError",
17
+ "ApiError",
18
+ "UnexpectedStatusError",
19
+ "Agent",
20
+ "Prompt",
21
+ "Result",
22
+ "Run",
23
+ )
hackagent/agent.py ADDED
@@ -0,0 +1,193 @@
1
+ import logging
2
+ import os
3
+ from typing import Any, Optional, Dict, Tuple
4
+ from dotenv import load_dotenv, find_dotenv
5
+
6
+ from hackagent.client import AuthenticatedClient
7
+ from hackagent.models import AgentTypeEnum
8
+ from hackagent.errors import HackAgentError
9
+ from hackagent.router import AgentRouter
10
+
11
+ # Import strategies
12
+ from .attacks.strategies import (
13
+ AttackStrategy,
14
+ # DirectTestAttackStrategy,
15
+ # ManagedAttackStrategy,
16
+ AdvPrefix,
17
+ )
18
+
19
+ # Import for the splash screen
20
+ from .branding import display_hackagent_splash
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ DEFAULT_MAX_WAIT_TIME_SECONDS = 180
25
+ DEFAULT_POLL_INTERVAL_SECONDS = 5
26
+
27
+ # Default predefined prompts
28
+ # Format: category -> (default_prompt_name, prompt_text)
29
+ DEFAULT_PROMPTS: Dict[str, Tuple[str, str]] = {
30
+ "sql_injection": ("Default SQL Injection Test", "admin' OR '1'='1"),
31
+ "xss_basic": ("Basic XSS Test", "<script>alert('XSS')</script>"),
32
+ "command_injection_linux": ("Linux Command Injection Test", "; ls -la"),
33
+ # Users can extend this by passing their own dict to the constructor
34
+ }
35
+
36
+ # --- Strategy Pattern for Attacks ---
37
+
38
+
39
+ class HackAgent:
40
+ """
41
+ A client class to interact with the HackAgent testing platform,
42
+ automating agent and prompt setup, test execution, and result retrieval.
43
+ It now uses an AgentRouter to manage agent definitions with the backend.
44
+ """
45
+
46
+ # Logging setup (RichHandler) is now performed in hackagent/__init__.py
47
+ # when the package is imported. No class variable or static method needed here for that.
48
+
49
+ def __init__(
50
+ self,
51
+ endpoint: str,
52
+ name: str = None,
53
+ agent_type: AgentTypeEnum = AgentTypeEnum.UNKNOWN,
54
+ base_url: Optional[str] = None,
55
+ token: Optional[str] = None,
56
+ predefined_prompts: Optional[Dict[str, Tuple[str, str]]] = None,
57
+ raise_on_unexpected_status: bool = False,
58
+ timeout: Optional[float] = None,
59
+ env_file_path: Optional[str] = None,
60
+ ):
61
+ display_hackagent_splash() # Display the splash screen on init
62
+
63
+ self.client = AuthenticatedClient(
64
+ base_url=base_url,
65
+ token=self._resolve_api_token(token, env_file_path),
66
+ prefix="Api-Key",
67
+ raise_on_unexpected_status=raise_on_unexpected_status,
68
+ timeout=timeout,
69
+ )
70
+
71
+ self.prompts = DEFAULT_PROMPTS.copy()
72
+ if predefined_prompts:
73
+ self.prompts.update(predefined_prompts)
74
+
75
+ # Initialize the AgentRouter
76
+ self.router = AgentRouter(
77
+ client=self.client, name=name, agent_type=agent_type, endpoint=endpoint
78
+ )
79
+
80
+ # Initialize strategies by passing the HackAgent instance (self)
81
+ self.attack_strategies: Dict[str, AttackStrategy] = {
82
+ # "direct_test": DirectTestAttackStrategy(hack_agent=self),
83
+ # "managed_attack": ManagedAttackStrategy(hack_agent=self),
84
+ "advprefix": AdvPrefix(hack_agent=self),
85
+ }
86
+
87
+ def _resolve_api_token(
88
+ self, token: Optional[str], env_file_path: Optional[str]
89
+ ) -> str:
90
+ """Resolves the API token from direct input or environment variables."""
91
+ api_token_resolved = token
92
+ if api_token_resolved is None:
93
+ logger.debug(
94
+ "API token not provided directly, attempting to load from environment."
95
+ )
96
+ dotenv_to_load = env_file_path or find_dotenv(usecwd=True)
97
+
98
+ if dotenv_to_load:
99
+ logger.debug(f"Loading .env file from: {dotenv_to_load}")
100
+ load_dotenv(dotenv_to_load)
101
+ else:
102
+ logger.debug("No .env file found to load.")
103
+
104
+ api_token_resolved = os.getenv("HACKAGENT_API_TOKEN")
105
+
106
+ if not api_token_resolved:
107
+ error_message = (
108
+ "API token not provided and not found in HACKAGENT_API_TOKEN "
109
+ "environment variable (after attempting to load .env)."
110
+ )
111
+ raise ValueError(error_message)
112
+ return api_token_resolved
113
+
114
+ async def hack(
115
+ self,
116
+ attack_config: Dict[str, Any],
117
+ run_config_override: Optional[Dict[str, Any]] = None,
118
+ fail_on_run_error: bool = True,
119
+ ) -> Any:
120
+ """
121
+ Executes a specified attack type against a victim agent.
122
+
123
+ This method orchestrates the agent setup in the backend via the router,
124
+ and then delegates to the appropriate attack strategy.
125
+
126
+ Args:
127
+ attack_config: Parameters specific to the chosen attack type and prompt.
128
+ 'category', 'prompt_text', etc.
129
+ run_config_override: Optional dictionary to override default run configurations.
130
+ fail_on_run_error: If True, raises an exception if the run fails.
131
+
132
+ Returns:
133
+ The result from the attack strategy's execute method.
134
+
135
+ Raises:
136
+ ValueError: If type is unsupported or config is invalid.
137
+ HackAgentError: For issues during API interaction or run processing.
138
+ """
139
+ try:
140
+ attack_type = attack_config.get("attack_type")
141
+ if not attack_type:
142
+ raise ValueError("'attack_type' must be provided in attack_config.")
143
+
144
+ strategy = self.attack_strategies.get(attack_type)
145
+ if not strategy:
146
+ raise ValueError(
147
+ f"Unsupported attack_type: {attack_type}. Supported types: {list(self.attack_strategies.keys())}."
148
+ )
149
+
150
+ # The router's own agent is the victim
151
+ backend_agent = self.router.backend_agent
152
+
153
+ logger.info(
154
+ f"Preparing to attack agent '{backend_agent.name}' (ID: {backend_agent.id}, Type: {backend_agent.agent_type.value}) "
155
+ f"configured in this HackAgent instance, using strategy '{attack_type}'."
156
+ )
157
+
158
+ # Removed logic for setting up a separate victim agent, as self.router.backend_agent_model is the victim.
159
+ # The ensure_agent_in_backend call for the victim is no longer needed here,
160
+ # as the router ensures its own agent upon initialization.
161
+
162
+ logger.info(
163
+ f"Using Victim Backend Agent ID: {backend_agent.id} for '{backend_agent.name}'"
164
+ )
165
+
166
+ return await strategy.execute(
167
+ attack_config=attack_config,
168
+ run_config_override=run_config_override,
169
+ fail_on_run_error=fail_on_run_error,
170
+ )
171
+
172
+ except HackAgentError: # Re-raise HackAgentErrors directly
173
+ raise
174
+ except ValueError as ve: # Catch config errors (e.g. unsupported attack type)
175
+ logger.error(
176
+ f"Configuration error in HackAgent.attack: {ve}", exc_info=True
177
+ )
178
+ raise HackAgentError(f"Configuration error: {ve}") from ve
179
+ except (
180
+ RuntimeError
181
+ ) as re: # Catch general runtime issues from backend calls etc.
182
+ logger.error(f"Runtime error during HackAgent.attack: {re}", exc_info=True)
183
+ # Check if it's one of our specific RuntimeErrors from be_ops
184
+ if "Failed to create backend agent" in str(
185
+ re
186
+ ) or "Failed to update metadata" in str(re):
187
+ raise HackAgentError(f"Backend agent operation failed: {re}") from re
188
+ raise HackAgentError(f"An unexpected runtime error occurred: {re}") from re
189
+ except Exception as e: # Catch any other unexpected errors
190
+ logger.error(f"Unexpected error in HackAgent.attack: {e}", exc_info=True)
191
+ raise HackAgentError(
192
+ f"An unexpected error occurred during attack: {e}"
193
+ ) from e
@@ -0,0 +1 @@
1
+ """Contains methods for accessing the API"""
@@ -0,0 +1 @@
1
+ """Contains endpoint functions for accessing the API"""
@@ -0,0 +1,340 @@
1
+ from http import HTTPStatus
2
+ from typing import Any, Optional, Union
3
+
4
+ import httpx
5
+
6
+ from ... import errors
7
+ from ...client import AuthenticatedClient, Client
8
+ from ...models.agent import Agent
9
+ from ...models.agent_request import AgentRequest
10
+ from ...types import Response
11
+
12
+
13
+ def _get_kwargs(
14
+ *,
15
+ body: AgentRequest,
16
+ ) -> dict[str, Any]:
17
+ headers: dict[str, Any] = {}
18
+
19
+ _kwargs: dict[str, Any] = {
20
+ "method": "post",
21
+ "url": "/api/agent",
22
+ }
23
+
24
+ _body = body.to_dict()
25
+
26
+ _kwargs["json"] = _body
27
+ headers["Content-Type"] = "application/json"
28
+
29
+ _kwargs["headers"] = headers
30
+ return _kwargs
31
+
32
+
33
+ def _parse_response(
34
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
35
+ ) -> Optional[Agent]:
36
+ if response.status_code == 201:
37
+ response_201 = Agent.from_dict(response.json())
38
+
39
+ return response_201
40
+ if client.raise_on_unexpected_status:
41
+ raise errors.UnexpectedStatus(response.status_code, response.content)
42
+ else:
43
+ return None
44
+
45
+
46
+ def _build_response(
47
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
48
+ ) -> Response[Agent]:
49
+ return Response(
50
+ status_code=HTTPStatus(response.status_code),
51
+ content=response.content,
52
+ headers=response.headers,
53
+ parsed=_parse_response(client=client, response=response),
54
+ )
55
+
56
+
57
+ def sync_detailed(
58
+ *,
59
+ client: AuthenticatedClient,
60
+ body: AgentRequest,
61
+ ) -> Response[Agent]:
62
+ """Provides CRUD operations for Agent instances.
63
+
64
+ This ViewSet manages Agent records, ensuring that users can only interact
65
+ with agents based on their permissions and organizational context.
66
+ It filters agent listings for users and handles the logic for creating
67
+ agents, including associating them with the correct organization and owner.
68
+
69
+ Authentication uses UserAPIKeyAuthentication and PrivyAuthentication.
70
+ Permissions are based on IsAuthenticated, with queryset filtering providing
71
+ row-level access control.
72
+
73
+ Class Attributes:
74
+ queryset (QuerySet): The default queryset for listing agents, initially all agents.
75
+ This is further filtered by `get_queryset()`.
76
+ serializer_class (AgentSerializer): The serializer used for validating and
77
+ deserializing input, and for serializing output.
78
+ authentication_classes (list): List of authentication classes to use.
79
+ permission_classes (list): List of permission classes to use.
80
+ parser_classes (list): List of parser classes for handling request data.
81
+ lookup_field (str): The model field used for looking up individual instances (UUID 'id').
82
+
83
+ Args:
84
+ body (AgentRequest): Serializes Agent model instances to JSON and validates data for
85
+ creating
86
+ or updating Agent instances.
87
+
88
+ This serializer provides a comprehensive representation of an Agent,
89
+ including its type, endpoint, and nested details for related 'organization'
90
+ and 'owner' for read operations, while allowing 'organization' and 'owner' IDs
91
+ for write operations.
92
+
93
+ Attributes:
94
+ organization_detail (OrganizationMinimalSerializer): Read-only nested
95
+ serializer for the agent's organization. Displays minimal details.
96
+ owner_detail (UserProfileMinimalSerializer): Read-only nested serializer
97
+ for the agent's owner's user profile. Displays minimal details.
98
+ Can be null if the agent has no owner or the owner has no profile.
99
+ type (CharField): The type of the agent (e.g., GENERIC_ADK, OPENAI_SDK).
100
+ Uses the choices defined in the Agent model's AgentType enum.
101
+
102
+ Meta:
103
+ model (Agent): The model class that this serializer works with.
104
+ fields (tuple): The fields to include in the serialized output.
105
+ Includes standard Agent fields like 'endpoint', 'type',
106
+ and the read-only nested details.
107
+ read_only_fields (tuple): Fields that are read-only and cannot be
108
+ set during create/update operations through this serializer.
109
+ This includes 'id', 'created_at', 'updated_at', and the
110
+ nested detail fields.
111
+
112
+ Raises:
113
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
114
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
115
+
116
+ Returns:
117
+ Response[Agent]
118
+ """
119
+
120
+ kwargs = _get_kwargs(
121
+ body=body,
122
+ )
123
+
124
+ response = client.get_httpx_client().request(
125
+ **kwargs,
126
+ )
127
+
128
+ return _build_response(client=client, response=response)
129
+
130
+
131
+ def sync(
132
+ *,
133
+ client: AuthenticatedClient,
134
+ body: AgentRequest,
135
+ ) -> Optional[Agent]:
136
+ """Provides CRUD operations for Agent instances.
137
+
138
+ This ViewSet manages Agent records, ensuring that users can only interact
139
+ with agents based on their permissions and organizational context.
140
+ It filters agent listings for users and handles the logic for creating
141
+ agents, including associating them with the correct organization and owner.
142
+
143
+ Authentication uses UserAPIKeyAuthentication and PrivyAuthentication.
144
+ Permissions are based on IsAuthenticated, with queryset filtering providing
145
+ row-level access control.
146
+
147
+ Class Attributes:
148
+ queryset (QuerySet): The default queryset for listing agents, initially all agents.
149
+ This is further filtered by `get_queryset()`.
150
+ serializer_class (AgentSerializer): The serializer used for validating and
151
+ deserializing input, and for serializing output.
152
+ authentication_classes (list): List of authentication classes to use.
153
+ permission_classes (list): List of permission classes to use.
154
+ parser_classes (list): List of parser classes for handling request data.
155
+ lookup_field (str): The model field used for looking up individual instances (UUID 'id').
156
+
157
+ Args:
158
+ body (AgentRequest): Serializes Agent model instances to JSON and validates data for
159
+ creating
160
+ or updating Agent instances.
161
+
162
+ This serializer provides a comprehensive representation of an Agent,
163
+ including its type, endpoint, and nested details for related 'organization'
164
+ and 'owner' for read operations, while allowing 'organization' and 'owner' IDs
165
+ for write operations.
166
+
167
+ Attributes:
168
+ organization_detail (OrganizationMinimalSerializer): Read-only nested
169
+ serializer for the agent's organization. Displays minimal details.
170
+ owner_detail (UserProfileMinimalSerializer): Read-only nested serializer
171
+ for the agent's owner's user profile. Displays minimal details.
172
+ Can be null if the agent has no owner or the owner has no profile.
173
+ type (CharField): The type of the agent (e.g., GENERIC_ADK, OPENAI_SDK).
174
+ Uses the choices defined in the Agent model's AgentType enum.
175
+
176
+ Meta:
177
+ model (Agent): The model class that this serializer works with.
178
+ fields (tuple): The fields to include in the serialized output.
179
+ Includes standard Agent fields like 'endpoint', 'type',
180
+ and the read-only nested details.
181
+ read_only_fields (tuple): Fields that are read-only and cannot be
182
+ set during create/update operations through this serializer.
183
+ This includes 'id', 'created_at', 'updated_at', and the
184
+ nested detail fields.
185
+
186
+ Raises:
187
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
188
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
189
+
190
+ Returns:
191
+ Agent
192
+ """
193
+
194
+ return sync_detailed(
195
+ client=client,
196
+ body=body,
197
+ ).parsed
198
+
199
+
200
+ async def asyncio_detailed(
201
+ *,
202
+ client: AuthenticatedClient,
203
+ body: AgentRequest,
204
+ ) -> Response[Agent]:
205
+ """Provides CRUD operations for Agent instances.
206
+
207
+ This ViewSet manages Agent records, ensuring that users can only interact
208
+ with agents based on their permissions and organizational context.
209
+ It filters agent listings for users and handles the logic for creating
210
+ agents, including associating them with the correct organization and owner.
211
+
212
+ Authentication uses UserAPIKeyAuthentication and PrivyAuthentication.
213
+ Permissions are based on IsAuthenticated, with queryset filtering providing
214
+ row-level access control.
215
+
216
+ Class Attributes:
217
+ queryset (QuerySet): The default queryset for listing agents, initially all agents.
218
+ This is further filtered by `get_queryset()`.
219
+ serializer_class (AgentSerializer): The serializer used for validating and
220
+ deserializing input, and for serializing output.
221
+ authentication_classes (list): List of authentication classes to use.
222
+ permission_classes (list): List of permission classes to use.
223
+ parser_classes (list): List of parser classes for handling request data.
224
+ lookup_field (str): The model field used for looking up individual instances (UUID 'id').
225
+
226
+ Args:
227
+ body (AgentRequest): Serializes Agent model instances to JSON and validates data for
228
+ creating
229
+ or updating Agent instances.
230
+
231
+ This serializer provides a comprehensive representation of an Agent,
232
+ including its type, endpoint, and nested details for related 'organization'
233
+ and 'owner' for read operations, while allowing 'organization' and 'owner' IDs
234
+ for write operations.
235
+
236
+ Attributes:
237
+ organization_detail (OrganizationMinimalSerializer): Read-only nested
238
+ serializer for the agent's organization. Displays minimal details.
239
+ owner_detail (UserProfileMinimalSerializer): Read-only nested serializer
240
+ for the agent's owner's user profile. Displays minimal details.
241
+ Can be null if the agent has no owner or the owner has no profile.
242
+ type (CharField): The type of the agent (e.g., GENERIC_ADK, OPENAI_SDK).
243
+ Uses the choices defined in the Agent model's AgentType enum.
244
+
245
+ Meta:
246
+ model (Agent): The model class that this serializer works with.
247
+ fields (tuple): The fields to include in the serialized output.
248
+ Includes standard Agent fields like 'endpoint', 'type',
249
+ and the read-only nested details.
250
+ read_only_fields (tuple): Fields that are read-only and cannot be
251
+ set during create/update operations through this serializer.
252
+ This includes 'id', 'created_at', 'updated_at', and the
253
+ nested detail fields.
254
+
255
+ Raises:
256
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
257
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
258
+
259
+ Returns:
260
+ Response[Agent]
261
+ """
262
+
263
+ kwargs = _get_kwargs(
264
+ body=body,
265
+ )
266
+
267
+ response = await client.get_async_httpx_client().request(**kwargs)
268
+
269
+ return _build_response(client=client, response=response)
270
+
271
+
272
+ async def asyncio(
273
+ *,
274
+ client: AuthenticatedClient,
275
+ body: AgentRequest,
276
+ ) -> Optional[Agent]:
277
+ """Provides CRUD operations for Agent instances.
278
+
279
+ This ViewSet manages Agent records, ensuring that users can only interact
280
+ with agents based on their permissions and organizational context.
281
+ It filters agent listings for users and handles the logic for creating
282
+ agents, including associating them with the correct organization and owner.
283
+
284
+ Authentication uses UserAPIKeyAuthentication and PrivyAuthentication.
285
+ Permissions are based on IsAuthenticated, with queryset filtering providing
286
+ row-level access control.
287
+
288
+ Class Attributes:
289
+ queryset (QuerySet): The default queryset for listing agents, initially all agents.
290
+ This is further filtered by `get_queryset()`.
291
+ serializer_class (AgentSerializer): The serializer used for validating and
292
+ deserializing input, and for serializing output.
293
+ authentication_classes (list): List of authentication classes to use.
294
+ permission_classes (list): List of permission classes to use.
295
+ parser_classes (list): List of parser classes for handling request data.
296
+ lookup_field (str): The model field used for looking up individual instances (UUID 'id').
297
+
298
+ Args:
299
+ body (AgentRequest): Serializes Agent model instances to JSON and validates data for
300
+ creating
301
+ or updating Agent instances.
302
+
303
+ This serializer provides a comprehensive representation of an Agent,
304
+ including its type, endpoint, and nested details for related 'organization'
305
+ and 'owner' for read operations, while allowing 'organization' and 'owner' IDs
306
+ for write operations.
307
+
308
+ Attributes:
309
+ organization_detail (OrganizationMinimalSerializer): Read-only nested
310
+ serializer for the agent's organization. Displays minimal details.
311
+ owner_detail (UserProfileMinimalSerializer): Read-only nested serializer
312
+ for the agent's owner's user profile. Displays minimal details.
313
+ Can be null if the agent has no owner or the owner has no profile.
314
+ type (CharField): The type of the agent (e.g., GENERIC_ADK, OPENAI_SDK).
315
+ Uses the choices defined in the Agent model's AgentType enum.
316
+
317
+ Meta:
318
+ model (Agent): The model class that this serializer works with.
319
+ fields (tuple): The fields to include in the serialized output.
320
+ Includes standard Agent fields like 'endpoint', 'type',
321
+ and the read-only nested details.
322
+ read_only_fields (tuple): Fields that are read-only and cannot be
323
+ set during create/update operations through this serializer.
324
+ This includes 'id', 'created_at', 'updated_at', and the
325
+ nested detail fields.
326
+
327
+ Raises:
328
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
329
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
330
+
331
+ Returns:
332
+ Agent
333
+ """
334
+
335
+ return (
336
+ await asyncio_detailed(
337
+ client=client,
338
+ body=body,
339
+ )
340
+ ).parsed