How a session works
In an SDK-driven session, HiddenLayer generates the attacks and judges the results. Your code only connects the attacker to your target.You start a session
start_session with a name, a label for your target, and settings such as the execution strategy. HiddenLayer creates a workflow and returns a session object with a workflow_id.HiddenLayer generates attack prompts
Your handler calls the target
HiddenLayer judges and reports
Before you begin
- Install the SDK and configure credentials. See Installation and Authentication and configuration.
- Set
HIDDENLAYER_CLIENT_IDandHIDDENLAYER_CLIENT_SECRETin your environment, or setHIDDENLAYER_TOKENto a bearer token. Every example on this page reads credentials from the environment. - Your tenant needs access to AI Attack Simulation.
- You need a way to call your target from Python. The examples use a placeholder function so they run without extra packages. Install whatever your real target needs, such as
openaiorhttpx.
Run a session with the async client
The recommended approach usesAsyncHiddenLayer and run_with_callback_parallel, which processes several attack prompts at the same time. The SDK example notebooks use this pattern.
The handler receives four arguments:
Variant: target an OpenAI model
Variant: target an OpenAI model
pip install openai and an OPENAI_API_KEY environment variable. It follows the SDK’s red_team_openai.ipynb notebook.handler in place of the placeholder in the main example, and pass target_model=TARGET_MODEL and target_system_prompt=TARGET_SYSTEM_PROMPT to start_session.Control parallelism
run_with_callback_parallel(handler, max_parallel=None, poll_batch_interval=0.5) runs up to max_parallel handler calls at once. If you leave max_parallel as None, it uses the session’s max_parallel_techniques. Set it lower if your target has rate limits.
If any handler call raises an exception, the SDK cancels the remaining in-flight calls and re-raises the exception. Handle expected target errors inside your handler if you want the session to continue.
start_session parameters
client.evaluation_sessions.red_team.start_session(...) accepts these keyword arguments. Defaults are the SDK defaults. Where the SDK sends nothing, the HiddenLayer service applies its own default.
Read the results
After the session completes, callclient.evaluations.red_team.retrieve_evaluation_results(workflow_id). The response has workflow_id, run_id, status, and a result object with these fields:
result.report as a plain dict, so its keys are not guaranteed. The keys used below come from the SDK example notebooks: report["summary"] with total_sessions, success_rate_pct, success_total, attempts_total, and error_total, and report["by_objective"], which maps each objective ID to a dict with success and attempts. Use .get() and check types so your code keeps working if the structure changes.python print_results.py <workflow_id>. An objective is marked FAIL if at least one attack against it succeeded.
Run a session with the sync client
If your code is not asynchronous, useHiddenLayer and run_with_callback. The handler is a regular function. The sync session processes one attack prompt at a time, so it is slower than the parallel async approach.
iterate_actions() yields each ready attack action, and get_next_action(block=True) returns the next one. The async session also provides get_available_actions(max_actions=10). If you use these, you must submit each target reply yourself with client.evaluations.red_team.submit_target_response(workflow_id=..., session_id=..., target_response=...). run_with_callback and run_with_callback_parallel do this for you.
Execution strategies
Setexecution_strategy_type to choose how HiddenLayer builds attacks:
single and random is not documented in the SDK. The descriptions above follow the existing usage examples and need confirmation.static_prompt_set, pass a prompt set ID. The SDK example notebook mentions these built-in sets: do-anything-now-ape, financial-assistant-basic, and financial-assistant-advanced. You can also copy the ID of a prompt set you uploaded from the Console.
Monitor a session
Callclient.evaluations.red_team.retrieve_status(workflow_id) to check progress, for example from a separate process or dashboard. Useful fields include:
Resume a session
If your script stops while a session is running, the workflow continues to exist on the HiddenLayer side. Reconnect to it withresume_session(workflow_id, *, poll_interval=2.0, poll_max_wait=None, max_parallel_techniques=None), then drive it again with your handler. If you do not pass max_parallel_techniques, the resumed session uses 1.
Terminate a session
To stop a running session, callterminate_session(workflow_id).
await client.evaluation_sessions.red_team.terminate_session(workflow_id).
Timeouts
Red team sessions can run for a long time. Two separate limits apply:poll_max_wait(onstart_sessionandresume_session, defaultNone): an overall time limit, in seconds, measured from when the session object is created. The SDK checks it while it polls for attack prompts. When exceeded, it raises a plainExceptionwith a message likePolling timed out after ..., notPollTimeoutError. With the defaultNone, there is no limit.wait_for_completion: after all attack prompts are handled,run_with_callbackandrun_with_callback_parallelcallwait_for_completion()with its defaults (poll_interval=3.0,max_wait=300.0). If the workflow does not reach a terminal status within 300 seconds, it raisesPollTimeoutError. If the workflow status isFAILED, it raisesRedTeamSessionErrorwith the messageWorkflow failed: ....
retrieve_status, fetch results later, or resume the session. You can also call session.wait_for_completion(max_wait=...) yourself with a longer limit, or max_wait=None for no limit.
Error handling
Import the session helper exceptions fromhiddenlayer.lib.red_team_exceptions:
run_with_callback_parallel and cancels other in-flight handler calls.
See Error handling for the full SDK exception hierarchy.
Common errors and fixes
ValueError: execution_strategy_type must be 'single', 'random', or 'static_prompt_set'.
ValueError: execution_strategy_type must be 'single', 'random', or 'static_prompt_set'.
The static_prompt_set session fails or runs no prompts
The static_prompt_set session fails or runs no prompts
prompt_set_id. The SDK does not validate that it is present. Confirm the ID in the Console.UnprocessableEntityError (422) when starting a session
UnprocessableEntityError (422) when starting a session
attacker_guidance that contains code, JSON, XML, markdown, or other characters outside plain sentence punctuation. Another is a severity_mapping key that is not a known objective ID. Print e.body for details.PollTimeoutError: Workflow did not complete within 300.0s
PollTimeoutError: Workflow did not complete within 300.0s
session.wait_for_completion(max_wait=...) with a longer limit, or check retrieve_status later and then fetch the results.Exception: Polling timed out after ...
Exception: Polling timed out after ...
poll_max_wait limit you set was exceeded. Increase it, or leave it as None. Resume the session with resume_session to continue.RedTeamSessionError: Workflow failed: ...
RedTeamSessionError: Workflow failed: ...
FAILED. The message includes the error from the workflow status. Check that your handler returns meaningful strings and that your target is reachable, then start a new session.NotFoundError (404) for a workflow ID
NotFoundError (404) for a workflow ID
AuthenticationError (401) or PermissionDeniedError (403)
AuthenticationError (401) or PermissionDeniedError (403)

