Skip to main content
Red teaming is the practice of attacking your own system the way an adversary would, so you find weaknesses before someone else does. For an LLM application, that means sending prompts designed to jailbreak the model, leak its system prompt, extract sensitive data, or redirect it away from its task. HiddenLayer AI Attack Simulation automates this. With the SDK, you can run a red team session against any target your code can call: a hosted model, an internal API, a chatbot behind a web UI, or an agent. The Python SDK includes a session helper, 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.
1

You start a session

You create a red team workflow with a name, a label for your target, and settings such as the execution strategy. HiddenLayer returns a workflow_id.
2

HiddenLayer generates attack prompts

HiddenLayer produces attack prompts based on the objectives and techniques you select.
3

Your code calls the target

For each attack prompt, your code sends the prompt to your application or model and submits the reply back to HiddenLayer. In Python, you write a function called the handler and the session helper calls it for each prompt. In TypeScript and Java, your loop asks for the next action, calls the target, and submits the reply.
4

HiddenLayer judges and reports

HiddenLayer decides whether each attack succeeded and may continue a multi-turn conversation. When the session finishes, it produces an evaluation report that you can retrieve with the SDK or view in the Console.
Because your code calls the target, HiddenLayer never needs network access to your application or credentials for it.
All AI Attack Simulation endpoints are in beta. Beta APIs have no compatibility guarantees, and their parameters and responses can change between SDK versions. See the Beta API FAQ. The first call to each beta endpoint emits a warning:
  • Python: a hiddenlayer.BetaWarning, including for calls the session helper makes. To hide it, call warnings.filterwarnings("ignore", category=hiddenlayer.BetaWarning).
  • TypeScript: a console.warn, once per endpoint per process.
  • Java: a WARNING through the java.util.logging logger com.hiddenlayer.api.lib.BetaWarning, once per endpoint per JVM.

Before you begin

  • Install the SDK and configure credentials. See Installation and Authentication and configuration.
  • Set HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET in your environment, or set HIDDENLAYER_TOKEN to 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.
For your first run, use a small static prompt set (the static_prompt_set execution strategy) to confirm that your target call works before you start a larger adaptive evaluation. See Execution strategies.

Run a session

The recommended approach uses 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:It must return the target’s reply as a string.
Python
Expected result: the program prints the workflow ID right away, then runs until HiddenLayer finishes the session. This can take several minutes. It then prints the final status, the text evaluation report, and summary counts. The session and its report also appear in the Console.
Print or log the workflow ID as soon as the session starts. If your program stops, you need it to resume, check status, or terminate the session.
These target functions send each attack prompt, with the conversation so far, to an OpenAI chat model. They need an 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.
In Python, use this 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

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 to client.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 with client.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: Results are available once the workflow completes. Until then, and for a workflow that was terminated, the endpoint answers 404 with the detail 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:
Run it with the workflow ID as an argument. An objective is marked FAIL if at least one attack against it succeeded.

Run a session with the Python sync client

If your Python code is not asynchronous, use HiddenLayer 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.)
Python
Expected result: the same as the async example, but attack prompts are handled one at a time. Python sessions also expose lower-level methods if you need more control: 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).
The SDKs don’t document the exact behavioral difference between single and random. The descriptions above follow the existing usage examples.
For a static prompt set, pass the prompt set’s ID, a UUID. HiddenLayer provides built-in sets such as Financial Assistant Basic and Financial Assistant Advanced, and you can upload your own in the Console. To find an ID, list the prompt sets and pick one by name, as the examples below do: 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.
Call 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.
Python

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.
Terminating a session is irreversible. The workflow stops and cannot be restarted. Confirm the workflow ID before you run this.

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.
Two separate limits apply to the session helper:
  • poll_max_wait (on start_session and resume_session, default None): 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 PollTimeoutError with a message like Polling timed out after .... With the default None, there is no limit.
  • wait_for_completion: after all attack prompts are handled, run_with_callback and run_with_callback_parallel call wait_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 raises PollTimeoutError with the message Workflow did not complete within 300.0s. If the workflow status is FAILED, it raises RedTeamSessionError with the message Workflow failed: ....
You can also call session.wait_for_completion(max_wait=...) yourself with a longer limit, or max_wait=None for no limit.
Python

Error handling

Import the session helper exceptions from hiddenlayer.lib.red_team_exceptions:Other API errors raise hiddenlayer.core.ApiError or one of its subclasses, as the examples on this page catch.
Also handle errors from your own target. In Python, an unhandled exception in the handler stops 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

Python only. You passed an unsupported strategy name. Use one of the three lowercase values. TypeScript and Java take the uppercase values SINGLE, RANDOM, and STATIC_PROMPT_SET.
Check that you passed a prompt set ID. The SDKs do not validate that it is present. The ID is a UUID: a name or slug such as financial-assistant-basic is rejected with a 400 (invalid UUID length). Look the ID up by name, as shown in Execution strategies.
A parameter failed validation. The error body names the field. Common causes:
  • target_system_prompt is required: the single and random strategies need a non-empty target system prompt unless a config_id supplies 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.
Python only. Your handler finished, but the workflow took longer than five minutes to finalize. The workflow is still running. Call session.wait_for_completion(max_wait=...) with a longer limit, or check the status later and then fetch the results.
Python only. The poll_max_wait limit you set was exceeded. Increase it, or leave it as None. Resume the session with resume_session to continue.
HiddenLayer reported the workflow as 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.
The workflow ID is wrong, or you are connected to a different environment (region) than the one that created it. The Python session helper raises 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.
Check your credentials and environment, and confirm that your tenant has access to AI Attack Simulation. See Authentication and configuration.

More examples

The Python SDK repository includes example notebooks for different kinds of targets: an OpenAI model, a custom HTTP API, a web chat UI driven by Playwright, a static prompt set, a webhook-based target, a WebSocket target, and a generic template. The target-calling code in each notebook carries over to the TypeScript and Java loops. For more background and Console-based workflows, see: