client.evaluation_sessions.red_team, that runs the whole exchange for you. The TypeScript and Java SDKs don’t have a session helper. They expose the same red team endpoints, and you drive the session with a short loop, as shown on this page.
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
workflow_id.HiddenLayer generates attack prompts
Your code 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 your code. The main examples use a placeholder function so they run without extra packages. Install whatever your real target needs.
Run a session
- Python
- TypeScript
- Java
AsyncHiddenLayer 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
OPENAI_API_KEY environment variable. The Python handler uses the openai package (pip install openai) and follows the SDK’s red_team_openai.ipynb notebook. The TypeScript function calls the Chat Completions REST API with fetch, and the Java method uses OkHttp and Jackson, which the Java SDK already depends on.handler in place of the placeholder and pass target_model=TARGET_MODEL to start_session. In TypeScript, use this function in place of the placeholder callTarget: it reads the TARGET_SYSTEM_PROMPT constant that the program already declares. In Java, move the callTarget method and the OPENAI_MODEL, HTTP, and JSON fields into the program in place of the placeholder.Control parallelism
- Python
- TypeScript
- Java
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 as soon as it happens. Handle expected target errors inside your handler if you want the session to continue.Session parameters
Python passes these settings toclient.evaluation_sessions.red_team.start_session(...) as keyword arguments. TypeScript passes them in the client.evaluations.redTeam.create({...}) request object, using the API’s field names, and Java sets them on the ClientRedTeamBody builder.
The Python helper sends its own defaults, listed below. TypeScript and Java send only the fields you set. For anything you don’t send, the HiddenLayer service applies its own default.
Read the results
After the session completes, retrieve the results withclient.evaluations.red_team.retrieve_evaluation_results(workflow_id) in Python, client.evaluations.redTeam.retrieveEvaluationResults({ workflow_id }) in TypeScript, or client.evaluations().redTeam().retrieveEvaluationResults(workflowId) in Java. The response has workflow_id, run_id, status, and a result object with these fields:
Workflow not found or not completed.
Every field of result is optional, so check that a field is present before you read it. The following program prints a pass or fail line for each objective:
FAIL if at least one attack against it succeeded.
Run a session with the Python sync client
If your Python 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. (TypeScript is always asynchronous, and the Java runSession loop above is already synchronous.)
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
Set the execution strategy to choose how HiddenLayer builds attacks. Python takes the lowercase names below; TypeScript and Java take the uppercase API values (RANDOM, SINGLE, STATIC_PROMPT_SET).
single and random. The descriptions above follow the existing usage examples.client.evaluations.prompt_sets.list() in Python, client.evaluations.promptSets.list() in TypeScript, or client.evaluations().promptSets().list() in Java. The prompt set endpoints are in beta.
Monitor a session
Check a session’s progress with the status endpoint, for example from a separate process or dashboard:client.evaluations.red_team.retrieve_status(workflow_id) in Python, client.evaluations.redTeam.retrieveStatus({ workflow_id }) in TypeScript, or client.evaluations().redTeam().retrieveStatus(workflowId) in Java. Useful fields include:
Resume a session
If your program stops while a session is running, the workflow continues to exist on the HiddenLayer side. Reconnect to it with the saved workflow ID and drive it again with the same target call.- Python
- TypeScript
- Java
resume_session(workflow_id, *, poll_interval=2.0, poll_max_wait=None, max_parallel_techniques=None), then run the returned session with your handler. If you do not pass max_parallel_techniques, the resumed session uses 1.Terminate a session
To stop a running session, terminate its workflow:terminate_session(workflow_id) on client.evaluation_sessions.red_team in Python (the async client has the same method), client.evaluations.redTeam.terminate({ workflow_id }) in TypeScript, or client.evaluations().redTeam().terminate(workflowId) in Java.
Timeouts
Red team sessions can run for a long time. A client-side timeout does not stop the workflow on the HiddenLayer side. After a timeout, check the status, fetch results later, or resume the session.- Python
- TypeScript
- Java
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 raisesPollTimeoutErrorwith a message likePolling timed out after .... 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). It polls through 408, 429, and 5xx responses. If the workflow does not reach a terminal status within 300 seconds, it raisesPollTimeoutErrorwith the messageWorkflow did not complete within 300.0s. If the workflow status isFAILED, it raisesRedTeamSessionErrorwith the messageWorkflow failed: ....
session.wait_for_completion(max_wait=...) yourself with a longer limit, or max_wait=None for no limit.Error handling
- Python
- TypeScript
- Java
hiddenlayer.lib.red_team_exceptions:hiddenlayer.core.ApiError or one of its subclasses, as the examples on this page catch.run_with_callback_parallel and cancels other in-flight handler calls. In TypeScript and Java, an unhandled error in your target call ends your loop, but the workflow keeps running on the HiddenLayer side until you resume or terminate it.
See Error handling for the full error types of each SDK.
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'.
SINGLE, RANDOM, and STATIC_PROMPT_SET.The static prompt set session fails or runs no prompts
The static prompt set session fails or runs no prompts
financial-assistant-basic is rejected with a 400 (invalid UUID length). Look the ID up by name, as shown in Execution strategies.422 Unprocessable Entity when starting a session
422 Unprocessable Entity when starting a session
target_system_prompt is required: thesingleandrandomstrategies need a non-empty target system prompt unless aconfig_idsupplies one.- Attacker guidance that contains code, JSON, XML, markdown, or other characters outside plain sentence punctuation.
- A severity mapping key that is not a known objective ID.
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 the status later and then fetch the results.PollTimeoutError: Polling timed out after ...
PollTimeoutError: 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.Workflow failed: ...
Workflow failed: ...
FAILED. Python raises RedTeamSessionError with this message, and the TypeScript and Java examples throw an error with it. The message includes the error from the workflow status. Check that your target call returns meaningful strings and that your target is reachable, then start a new session.404 Not Found for a workflow ID
404 Not Found for a workflow ID
WorkflowNotFoundError. When you retrieve evaluation results, a 404 with the detail Workflow not found or not completed can also mean the workflow hasn’t completed, or was terminated: results exist only for completed workflows.
