> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiddenlayer.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Run AI Attack Simulation red team sessions

> Use the HiddenLayer SDKs to run AI Attack Simulation red team sessions against your own LLM application, monitor progress, and read the evaluation report.

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](https://docs.hiddenlayer.ai/docs/products/ai-attack-simulation/overview.md) 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.

> [!WARNING]
>
> 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](https://dev.hiddenlayer.ai/docs/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](https://docs.hiddenlayer.ai/docs/integrations/sdk/installation.md) and [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md).
* 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.

> [!TIP]
>
> 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](#execution-strategies).

## Run a session

> [tab] Python
>
> 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:
>
> | Argument | Description |
> | - | - |
> | `attack_prompt` | The attack prompt to send to your target. |
> | `history` | Earlier turns in this attack conversation, as a list of dicts with `role` and `content` keys. Use it if your target is stateless and needs the full conversation. |
> | `session_id` | The ID of this attack conversation. Useful if your target keeps its own conversation state. |
> | `target_system_prompt` | The workflow's target system prompt. It can be `None`, so keep your own copy of the prompt, as the OpenAI variant below does, instead of relying on this argument. |
>
> It must return the target's reply as a string.
>
> ```python Python theme={null}
> import asyncio
> import sys
> from typing import Any, Dict, List, Optional
>
> import httpx
> from hiddenlayer import AsyncHiddenLayer
> from hiddenlayer.core import ApiError
> from hiddenlayer.lib.red_team_exceptions import RedTeamSessionError
>
> TARGET_MODEL = "acme-support-bot"  # Free-form label for your target
> TARGET_SYSTEM_PROMPT = "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts."
>
>
> async def call_target(prompt: str, history: List[Dict[str, Any]], system_prompt: str) -> str:
>     """Placeholder target. Replace the body with a call to your application or model."""
>     await asyncio.sleep(0.1)
>     return "I'm sorry, I can only help with questions about your own accounts."
>
>
> async def handler(
>     attack_prompt: Optional[str],
>     history: Optional[List[Dict[str, Any]]],
>     session_id: Optional[str],
>     target_system_prompt: Optional[str],
> ) -> str:
>     reply = await call_target(attack_prompt or "", history or [], target_system_prompt or TARGET_SYSTEM_PROMPT)
>     # Return a non-empty string. The SDK examples return " " when the target replies with nothing.
>     return reply or " "
>
>
> async def main() -> int:
>     # Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET (or HIDDENLAYER_TOKEN).
>     client = AsyncHiddenLayer()
>     workflow_id = None
>     try:
>         session = await client.evaluation_sessions.red_team.start_session(
>             name="Acme support bot red team",
>             target_model=TARGET_MODEL,
>             target_system_prompt=TARGET_SYSTEM_PROMPT,
>             execution_strategy_type="random",
>             max_turns=3,
>             max_parallel_techniques=3,
>         )
>         workflow_id = session.workflow_id
>         print(f"Session started: {workflow_id}")
>
>         await session.run_with_callback_parallel(handler)
>         print("Session complete.")
>
>         results = await client.evaluations.red_team.retrieve_evaluation_results(workflow_id)
>     except RedTeamSessionError as e:
>         print(f"Red team session error: {e} (workflow: {workflow_id})", file=sys.stderr)
>         return 1
>     except ApiError as e:
>         print(f"HiddenLayer API error {e.status_code}: {e.body} (workflow: {workflow_id})", file=sys.stderr)
>         return 1
>     except httpx.TransportError as e:
>         print(f"Could not reach HiddenLayer: {e!r} (workflow: {workflow_id})", file=sys.stderr)
>         return 1
>
>     print(f"Status: {results.status}")
>     if results.result.evaluation_report:
>         print("\nEvaluation report:\n")
>         print(results.result.evaluation_report)
>
>     report = results.result.report
>     if report is not None and report.summary is not None:
>         summary = report.summary
>         print(f"\nTotal sessions: {summary.total_sessions}")
>         print(f"Success rate:   {summary.success_rate_pct or 0:.1f}%")
>         print(f"Successful:     {summary.success_total} / {summary.attempts_total}")
>         print(f"Errors:         {summary.error_total}")
>     return 0
>
>
> if __name__ == "__main__":
>     sys.exit(asyncio.run(main()))
> ```

> [tab] TypeScript
>
> Create the workflow with `client.evaluations.redTeam.create`, then loop over the next-action endpoint. Each action has these fields:
>
> | Field | Description |
> | - | - |
> | `is_ready` | `false` while HiddenLayer is still preparing the next action. Wait and ask again. |
> | `action_type` | `attack_task` (send `attack_prompt` to your target), `complete` (no more prompts), or `failed`. |
> | `attack_prompt` | The attack prompt to send to your target. |
> | `history` | Earlier turns in this attack conversation, as objects with `role` and `content`. |
> | `session_id` | The ID of this attack conversation. Submit it with the target's reply. |
> | `target_system_prompt` | The workflow's target system prompt. It can be `null`, so keep your own copy of the prompt instead of relying on this field. |
>
> For each `attack_task`, submit the target's reply with `submitTargetResponse`. After the last prompt, poll the workflow status until HiddenLayer finishes the report. The `runSession` function below does both, so you can reuse it to [resume a session](#resume-a-session).
>
> ```typescript TypeScript theme={null}
> import { HiddenLayer, HiddenLayerError } from "@hiddenlayerai/hiddenlayer-sdk";
> import { setTimeout as sleep } from "node:timers/promises";
>
> const TARGET_MODEL = "acme-support-bot"; // Free-form label for your target
> const TARGET_SYSTEM_PROMPT = "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts.";
> const TERMINAL_STATUSES = new Set(["COMPLETED", "FAILED", "CANCELLED", "TERMINATED", "TIMED_OUT"]);
>
> /** Placeholder target. Replace the body with a call to your application or model. */
> async function callTarget(prompt: string, history: Record<string, unknown>[], systemPrompt: string): Promise<string> {
>     return "I'm sorry, I can only help with questions about your own accounts.";
> }
>
> /** Answers every attack prompt of a workflow, then waits for HiddenLayer to finish the report. */
> async function runSession(client: HiddenLayer, workflowId: string): Promise<void> {
>     const redTeam = client.evaluations.redTeam;
>     while (true) {
>         const action = await redTeam.retrieveNextAction({ workflow_id: workflowId });
>         if (!action.is_ready) {
>             await sleep(2_000);
>             continue;
>         }
>         if (action.action_type === "complete") {
>             break;
>         }
>         if (action.action_type === "failed") {
>             throw new Error(action.message ?? "Workflow failed");
>         }
>         if (action.action_type !== "attack_task") {
>             continue;
>         }
>         const reply = await callTarget(
>             action.attack_prompt ?? "",
>             action.history ?? [],
>             action.target_system_prompt ?? TARGET_SYSTEM_PROMPT,
>         );
>         await redTeam.submitTargetResponse({
>             workflow_id: workflowId,
>             session_id: action.session_id ?? "",
>             // Send a non-empty string, as the Python helper does.
>             target_response: reply || " ",
>         });
>     }
>
>     const deadline = Date.now() + 5 * 60_000;
>     while (true) {
>         const status = await redTeam.retrieveStatus({ workflow_id: workflowId });
>         if (status.status === "COMPLETED") {
>             return;
>         }
>         if (status.status === "FAILED") {
>             throw new Error(`Workflow failed: ${status.error}`);
>         }
>         if (TERMINAL_STATUSES.has(status.status)) {
>             // A cancelled, terminated, or timed-out workflow has no results to read.
>             throw new Error(`Workflow ${workflowId} ended with status ${status.status}`);
>         }
>         if (Date.now() > deadline) {
>             throw new Error(`Workflow ${workflowId} did not complete within 5 minutes`);
>         }
>         await sleep(3_000);
>     }
> }
>
> // Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET (or HIDDENLAYER_TOKEN).
> const client = new HiddenLayer();
> let workflowId: string | undefined;
> try {
>     const started = await client.evaluations.redTeam.create({
>         name: "Acme support bot red team",
>         target_model: TARGET_MODEL,
>         target_system_prompt: TARGET_SYSTEM_PROMPT,
>         execution_strategy_type: "RANDOM",
>         max_turns: 3,
>         max_parallel_techniques: 3,
>     });
>     workflowId = started.workflow_id;
>     console.log(`Session started: ${workflowId}`);
>
>     await runSession(client, workflowId);
>     console.log("Session complete.");
>
>     const results = await client.evaluations.redTeam.retrieveEvaluationResults({ workflow_id: workflowId });
>     console.log(`Status: ${results.status}`);
>     if (results.result.evaluation_report) {
>         console.log(`\nEvaluation report:\n\n${results.result.evaluation_report}`);
>     }
>     const summary = results.result.report?.summary;
>     if (summary) {
>         console.log(`\nTotal sessions: ${summary.total_sessions}`);
>         console.log(`Success rate:   ${(summary.success_rate_pct ?? 0).toFixed(1)}%`);
>         console.log(`Successful:     ${summary.success_total} / ${summary.attempts_total}`);
>         console.log(`Errors:         ${summary.error_total}`);
>     }
> } catch (err) {
>     if (err instanceof HiddenLayerError) {
>         console.error(`HiddenLayer error ${err.statusCode ?? "(no response)"}: ${err.message} (workflow: ${workflowId})`);
>         process.exitCode = 1;
>     } else {
>         throw err;
>     }
> }
> ```

> [tab] Java
>
> Create the workflow with `client.evaluations().redTeam().create`, then loop over the next-action endpoint. Each `NextActionResponse` has these fields (optional ones return an `Optional`):
>
> | Getter | Description |
> | - | - |
> | `getIsReady()` | `false` while HiddenLayer is still preparing the next action. Wait and ask again. |
> | `getActionType()` | `attack_task` (send the attack prompt to your target), `complete` (no more prompts), or `failed`. |
> | `getAttackPrompt()` | The attack prompt to send to your target. |
> | `getHistory()` | Earlier turns in this attack conversation, as maps with `role` and `content`. |
> | `getSessionId()` | The ID of this attack conversation. Submit it with the target's reply. |
> | `getTargetSystemPrompt()` | The workflow's target system prompt. It can be empty, so keep your own copy of the prompt instead of relying on this getter. |
>
> For each `attack_task`, submit the target's reply with `submitTargetResponse`. After the last prompt, poll the workflow status until HiddenLayer finishes the report. The `runSession` method below does both, so you can reuse it to [resume a session](#resume-a-session).
>
> ```java Java theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.core.HiddenLayerApiException;
> import com.hiddenlayer.api.resources.evaluations.redteam.RedTeamClient;
> import com.hiddenlayer.api.resources.evaluations.redteam.requests.ClientRedTeamBody;
> import com.hiddenlayer.api.resources.evaluations.redteam.requests.SubmitTargetResponseBody;
> import com.hiddenlayer.api.resources.evaluations.redteam.types.ClientRedTeamBodyExecutionStrategyType;
> import com.hiddenlayer.api.types.NextActionResponse;
> import com.hiddenlayer.api.types.RedTeamReport;
> import com.hiddenlayer.api.types.RedTeamReportSummary;
> import com.hiddenlayer.api.types.WorkflowResultResponse;
> import com.hiddenlayer.api.types.WorkflowStatusResponse;
> import java.util.Arrays;
> import java.util.Collections;
> import java.util.HashSet;
> import java.util.List;
> import java.util.Map;
> import java.util.Set;
> import java.util.concurrent.TimeUnit;
>
> public class RedTeamRun {
>     static final String TARGET_MODEL = "acme-support-bot"; // Free-form label for your target
>     static final String TARGET_SYSTEM_PROMPT =
>             "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts.";
>     static final Set<String> TERMINAL_STATUSES =
>             new HashSet<>(Arrays.asList("COMPLETED", "FAILED", "CANCELLED", "TERMINATED", "TIMED_OUT"));
>
>     /** Placeholder target. Replace the body with a call to your application or model. */
>     static String callTarget(String prompt, List<Map<String, Object>> history, String systemPrompt) {
>         return "I'm sorry, I can only help with questions about your own accounts.";
>     }
>
>     /** Answers every attack prompt of a workflow, then waits for HiddenLayer to finish the report. */
>     static void runSession(HiddenLayerClient client, String workflowId) throws InterruptedException {
>         RedTeamClient redTeam = client.evaluations().redTeam();
>         while (true) {
>             NextActionResponse action = redTeam.retrieveNextAction(workflowId);
>             if (!action.getIsReady()) {
>                 Thread.sleep(2_000);
>                 continue;
>             }
>             String actionType = action.getActionType().orElse("");
>             if (actionType.equals("complete")) {
>                 break;
>             }
>             if (actionType.equals("failed")) {
>                 throw new IllegalStateException(action.getMessage().orElse("Workflow failed"));
>             }
>             if (!actionType.equals("attack_task")) {
>                 continue;
>             }
>             String reply = callTarget(
>                     action.getAttackPrompt().orElse(""),
>                     action.getHistory().orElse(Collections.emptyList()),
>                     action.getTargetSystemPrompt().orElse(TARGET_SYSTEM_PROMPT));
>             redTeam.submitTargetResponse(workflowId, SubmitTargetResponseBody.builder()
>                     .sessionId(action.getSessionId().orElse(""))
>                     // Send a non-empty string, as the Python helper does.
>                     .targetResponse(reply.isEmpty() ? " " : reply)
>                     .build());
>         }
>
>         long deadline = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5);
>         while (true) {
>             WorkflowStatusResponse status = redTeam.retrieveStatus(workflowId);
>             if (status.getStatus().equals("COMPLETED")) {
>                 return;
>             }
>             if (status.getStatus().equals("FAILED")) {
>                 throw new IllegalStateException("Workflow failed: " + status.getError().orElse(""));
>             }
>             if (TERMINAL_STATUSES.contains(status.getStatus())) {
>                 // A cancelled, terminated, or timed-out workflow has no results to read.
>                 throw new IllegalStateException("Workflow " + workflowId + " ended with status " + status.getStatus());
>             }
>             if (System.currentTimeMillis() > deadline) {
>                 throw new IllegalStateException("Workflow " + workflowId + " did not complete within 5 minutes");
>             }
>             Thread.sleep(3_000);
>         }
>     }
>
>     public static void main(String[] args) throws InterruptedException {
>         // Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET (or HIDDENLAYER_TOKEN).
>         HiddenLayerClient client = new HiddenLayerClientBuilder().build();
>         String workflowId = null;
>         try {
>             workflowId = client.evaluations()
>                     .redTeam()
>                     .create(ClientRedTeamBody.builder()
>                             .name("Acme support bot red team")
>                             .targetModel(TARGET_MODEL)
>                             .targetSystemPrompt(TARGET_SYSTEM_PROMPT)
>                             .executionStrategyType(ClientRedTeamBodyExecutionStrategyType.RANDOM)
>                             .maxTurns(3)
>                             .maxParallelTechniques(3)
>                             .build())
>                     .getWorkflowId();
>             System.out.println("Session started: " + workflowId);
>
>             runSession(client, workflowId);
>             System.out.println("Session complete.");
>
>             WorkflowResultResponse results = client.evaluations().redTeam().retrieveEvaluationResults(workflowId);
>             System.out.println("Status: " + results.getStatus().orElse("unknown"));
>             results.getResult().getEvaluationReport()
>                     .ifPresent(text -> System.out.println("\nEvaluation report:\n\n" + text));
>             results.getResult().getReport().flatMap(RedTeamReport::getSummary).ifPresent(summary -> {
>                 System.out.println("\nTotal sessions: " + summary.getTotalSessions());
>                 System.out.printf("Success rate:   %.1f%%%n", summary.getSuccessRatePct().orElse(0.0));
>                 System.out.println("Successful:     " + summary.getSuccessTotal() + " / " + summary.getAttemptsTotal());
>                 System.out.println("Errors:         " + summary.getErrorTotal());
>             });
>         } catch (HiddenLayerApiException e) {
>             System.err.println("HiddenLayer API error " + e.statusCode() + ": " + e.body() + " (workflow: " + workflowId + ")");
>             System.exit(1);
>         } finally {
>             client.close();
>         }
>     }
> }
> ```

**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.

> [!TIP]
>
> Print or log the workflow ID as soon as the session starts. If your program stops, you need it to [resume](#resume-a-session), [check status](#monitor-a-session), or [terminate](#terminate-a-session) the session.

> [accordion] Variant: target an OpenAI model
>
> 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.
>
> ```python Python theme={null}
> import os
> from typing import Any, Dict, List, Optional
>
> from openai import AsyncOpenAI
> from openai.types.chat import ChatCompletionMessageParam
>
> openai_client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
> TARGET_MODEL = "gpt-4o-mini"
> TARGET_SYSTEM_PROMPT = "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts."
>
>
> async def handler(
>     attack_prompt: Optional[str],
>     history: Optional[List[Dict[str, Any]]],
>     session_id: Optional[str],
>     target_system_prompt: Optional[str],
> ) -> str:
>     messages: List[ChatCompletionMessageParam] = [{"role": "system", "content": TARGET_SYSTEM_PROMPT}]
>     for turn in history or []:
>         content = str(turn.get("content", ""))
>         if turn.get("role") == "assistant":
>             messages.append({"role": "assistant", "content": content})
>         else:
>             messages.append({"role": "user", "content": content})
>     messages.append({"role": "user", "content": attack_prompt or ""})
>
>     response = await openai_client.chat.completions.create(model=TARGET_MODEL, messages=messages)
>     return response.choices[0].message.content or " "
> ```
>
> ```typescript TypeScript theme={null}
> const OPENAI_MODEL = "gpt-4o-mini";
>
> interface ChatCompletion {
>     choices: { message: { content: string | null } }[];
> }
>
> export async function callTarget(prompt: string, history: Record<string, unknown>[], systemPrompt: string): Promise<string> {
>     const messages = [
>         { role: "system", content: TARGET_SYSTEM_PROMPT },
>         ...history.map((turn) => ({
>             role: turn.role === "assistant" ? "assistant" : "user",
>             content: String(turn.content ?? ""),
>         })),
>         { role: "user", content: prompt },
>     ];
>     const response = await fetch("https://api.openai.com/v1/chat/completions", {
>         method: "POST",
>         headers: {
>             Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
>             "Content-Type": "application/json",
>         },
>         body: JSON.stringify({ model: OPENAI_MODEL, messages }),
>         // Aborts the request, including reading the body, after 60 seconds.
>         signal: AbortSignal.timeout(60_000),
>     });
>     if (!response.ok) {
>         throw new Error(`OpenAI returned ${response.status}: ${await response.text()}`);
>     }
>     const completion = (await response.json()) as ChatCompletion;
>     return completion.choices[0]?.message.content || " ";
> }
> ```
>
> ```java Java theme={null}
> import com.fasterxml.jackson.databind.JsonNode;
> import com.fasterxml.jackson.databind.ObjectMapper;
> import com.fasterxml.jackson.databind.node.ArrayNode;
> import com.fasterxml.jackson.databind.node.ObjectNode;
> import java.io.IOException;
> import java.io.UncheckedIOException;
> import java.util.List;
> import java.util.Map;
> import java.util.concurrent.TimeUnit;
> import okhttp3.MediaType;
> import okhttp3.OkHttpClient;
> import okhttp3.Request;
> import okhttp3.RequestBody;
> import okhttp3.Response;
>
> public class OpenAiTarget {
>     static final String OPENAI_MODEL = "gpt-4o-mini";
>     static final String TARGET_SYSTEM_PROMPT =
>             "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts.";
>     // OkHttp has no overall timeout by default. This one covers the request and reading the body.
>     static final OkHttpClient HTTP = new OkHttpClient.Builder().callTimeout(60, TimeUnit.SECONDS).build();
>     static final ObjectMapper JSON = new ObjectMapper();
>
>     static String callTarget(String prompt, List<Map<String, Object>> history, String systemPrompt) {
>         ObjectNode body = JSON.createObjectNode().put("model", OPENAI_MODEL);
>         ArrayNode messages = body.putArray("messages");
>         messages.addObject().put("role", "system").put("content", TARGET_SYSTEM_PROMPT);
>         for (Map<String, Object> turn : history) {
>             String role = "assistant".equals(turn.get("role")) ? "assistant" : "user";
>             messages.addObject().put("role", role).put("content", String.valueOf(turn.get("content")));
>         }
>         messages.addObject().put("role", "user").put("content", prompt);
>
>         Request request = new Request.Builder()
>                 .url("https://api.openai.com/v1/chat/completions")
>                 .header("Authorization", "Bearer " + System.getenv("OPENAI_API_KEY"))
>                 .post(RequestBody.create(body.toString(), MediaType.get("application/json")))
>                 .build();
>         try (Response response = HTTP.newCall(request).execute()) {
>             String text = response.body().string();
>             if (!response.isSuccessful()) {
>                 throw new IllegalStateException("OpenAI returned " + response.code() + ": " + text);
>             }
>             JsonNode content = JSON.readTree(text).path("choices").path(0).path("message").path("content");
>             return content.asText(" ").isEmpty() ? " " : content.asText(" ");
>         } catch (IOException e) {
>             throw new UncheckedIOException(e);
>         }
>     }
> }
> ```
>
> 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

> [tab] Python
>
> `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.

> [tab] TypeScript
>
> The `runSession` loop handles one attack prompt at a time. To handle several at once, as the Python helper does, ask for the next action repeatedly while it returns a ready `attack_task`, call your target for each one concurrently, and submit each reply with its own `session_id`. Keep the number of calls in flight within your target's rate limits.

> [tab] Java
>
> The `runSession` loop handles one attack prompt at a time. To handle several at once, as the Python helper does, ask for the next action repeatedly while it returns a ready `attack_task`, call your target for each one on an executor, and submit each reply with its own session ID. Keep the number of calls in flight within your target's rate limits.

## 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.

| Python argument | TypeScript field / Java builder method | Python default | Description |
| - | - | - | - |
| `name` | `name` / `name` | Required | Name of the evaluation, shown in the Console. Required in every SDK. |
| `target_model` | `target_model` / `targetModel` | Required | Free-form label for your target. Because your code calls the target, HiddenLayer does not validate this value against a model catalog. |
| `target_system_prompt` | `target_system_prompt` / `targetSystemPrompt` | `""` | Your target's system prompt. It gives the attacker context. The `single` and `random` strategies require it unless `config_id` supplies one: without it, HiddenLayer answers 422 (`target_system_prompt is required`), and an empty string counts as missing. |
| `objective_ids` | `objective_ids` / `objectiveIds` | Not sent | List of objective IDs to test, for example `["HLO.01", "HLO.03"]`. See [Basic custom attack](https://docs.hiddenlayer.ai/docs/products/ai-attack-simulation/custom-attack-sim/basic-custom-attack.md) for objective IDs and names. |
| `execution_strategy_type` | `execution_strategy_type` / `executionStrategyType` | `"random"` | Python takes `"single"`, `"random"`, or `"static_prompt_set"`, and raises `ValueError` for any other value. TypeScript takes `"SINGLE"`, `"RANDOM"`, or `"STATIC_PROMPT_SET"`. Java takes the `ClientRedTeamBodyExecutionStrategyType` constants `SINGLE`, `RANDOM`, and `STATIC_PROMPT_SET`. |
| `prompt_set_id` | `prompt_set_id` / `promptSetId` | Not sent | ID of a prompt set. Required for the static prompt set strategy. The SDKs do not check this for you. |
| `max_turns` | `max_turns` / `maxTurns` | `3` | Maximum conversation turns per attack session. Applies to the `single` and `random` strategies. |
| `n_random_techniques` | `n_random_techniques` / `nRandomTechniques` | `1` | Number of random techniques to use with the `random` strategy. |
| `max_parallel_techniques` | `max_parallel_techniques` / `maxParallelTechniques` | `1` | Number of techniques to run in parallel. In Python, also the default `max_parallel` for `run_with_callback_parallel`. |
| `sessions_per_technique` | `sessions_per_technique` / `sessionsPerTechnique` | `1` | Number of attack sessions per technique. With a static prompt set, the number of attempts per prompt. |
| `attacker_guidance` | `attacker_guidance` / `attackerGuidance` | Not sent | Plain-language text that focuses the attacker within your objectives. HiddenLayer rejects text that contains code, markup, or other disallowed characters with a 422 error. Ignored by the static prompt set strategy. |
| `severity_mapping` | `severity_mapping` / `severityMapping` | Not sent | Maps objective IDs to `CRITICAL`, `HIGH`, `MEDIUM`, `LOW`, or `NONE`. Used to derive each session's severity. |
| `config_id` | `config_id` / `configId` | Not sent | ID of a preset configuration. Any parameter you also pass overrides the preset value. |
| `hiddenlayer_project_id` | `hl_project_id` / `hlProjectId` | Not sent | HiddenLayer project ID or alias to associate the session with. |
| `attacker_model`, `refusal_judge_model`, `objective_judge_model`, `evaluation_report_model` | Same names in TypeScript; `attackerModel`, `refusalJudgeModel`, `objectiveJudgeModel`, `evaluationReportModel` in Java | Not sent | Overrides for the models HiddenLayer uses internally. The service default applies if omitted. |
| `attacker_max_generation_attempts` | `attacker_max_generation_attempts` / `attackerMaxGenerationAttempts` | `2` | Maximum attempts for the attacker to generate a prompt per turn. |
| `poll_interval` | Not applicable | `2.0` | Python only. Seconds between checks for the next attack prompt. In TypeScript and Java, your loop sets the interval. |
| `poll_max_wait` | Not applicable | `None` | Python only. Overall time limit, in seconds, for polling for attack prompts. See [Timeouts](#timeouts). |

## 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:

| Field | Description |
| - | - |
| `result.evaluation_report` | A text evaluation report. |
| `result.report` | Structured results: `summary` (with `total_sessions`, `success_rate_pct`, `success_total`, `attempts_total`, and `error_total`), `by_objective` (each objective ID mapped to its `success`, `attempts`, and `errors`), `by_technique`, and more. |
| `result.settings` | The settings the session ran with. |
| `result.usage` | Usage information. |
| `result.attacker_results` | Results for each attacker session. |

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:

```python Python theme={null}
import sys

from hiddenlayer import HiddenLayer
from hiddenlayer.core import ApiError

workflow_id = sys.argv[1]
client = HiddenLayer()

try:
    results = client.evaluations.red_team.retrieve_evaluation_results(workflow_id)
except ApiError as e:
    if e.status_code == 404:
        sys.exit(f"No results for workflow {workflow_id}: it hasn't completed, or it isn't in this region.")
    sys.exit(f"HiddenLayer API error {e.status_code}: {e.body}")

report = results.result.report
by_objective = (report.by_objective if report is not None else None) or {}
for objective_id, objective in by_objective.items():
    outcome = "PASS" if objective.success == 0 else "FAIL"
    print(f"{objective_id}: {objective.success}/{objective.attempts} attacks succeeded [{outcome}]")
```

```typescript TypeScript theme={null}
import { HiddenLayer, HiddenLayerError } from "@hiddenlayerai/hiddenlayer-sdk";

const workflowId = process.argv[2];
if (!workflowId) {
    throw new Error("Pass the workflow ID as the first argument.");
}

const client = new HiddenLayer();
try {
    const results = await client.evaluations.redTeam.retrieveEvaluationResults({ workflow_id: workflowId });

    for (const [objectiveId, objective] of Object.entries(results.result.report?.by_objective ?? {})) {
        const outcome = objective.success === 0 ? "PASS" : "FAIL";
        console.log(`${objectiveId}: ${objective.success}/${objective.attempts} attacks succeeded [${outcome}]`);
    }
} catch (err) {
    if (err instanceof HiddenLayerError && err.statusCode === 404) {
        console.error(`No results for workflow ${workflowId}: it hasn't completed, or it isn't in this region.`);
        process.exitCode = 1;
    } else {
        throw err;
    }
}
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.HiddenLayerApiException;
import com.hiddenlayer.api.types.RedTeamObjectiveBreakdown;
import com.hiddenlayer.api.types.RedTeamReport;
import com.hiddenlayer.api.types.WorkflowResultResponse;
import java.util.Collections;
import java.util.Map;

public class RedTeamPrintResults {
    public static void main(String[] args) {
        String workflowId = args[0];
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();
        WorkflowResultResponse results;
        try {
            results = client.evaluations().redTeam().retrieveEvaluationResults(workflowId);
        } catch (HiddenLayerApiException e) {
            if (e.statusCode() == 404) {
                System.err.println("No results for workflow " + workflowId
                        + ": it hasn't completed, or it isn't in this region.");
                System.exit(1);
            }
            throw e;
        } finally {
            client.close();
        }

        Map<String, RedTeamObjectiveBreakdown> byObjective = results.getResult()
                .getReport()
                .flatMap(RedTeamReport::getByObjective)
                .orElse(Collections.emptyMap());
        for (Map.Entry<String, RedTeamObjectiveBreakdown> entry : byObjective.entrySet()) {
            RedTeamObjectiveBreakdown objective = entry.getValue();
            String outcome = objective.getSuccess() == 0 ? "PASS" : "FAIL";
            System.out.println(entry.getKey() + ": " + objective.getSuccess() + "/" + objective.getAttempts()
                    + " attacks succeeded [" + outcome + "]");
        }
    }
}
```

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 Python theme={null}
import sys
from typing import Any, Dict, List, Optional

from hiddenlayer import HiddenLayer
from hiddenlayer.core import ApiError
from hiddenlayer.lib.red_team_exceptions import RedTeamSessionError

TARGET_SYSTEM_PROMPT = "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts."


def call_target(prompt: str, history: List[Dict[str, Any]], system_prompt: str) -> str:
    """Placeholder target. Replace the body with a call to your application or model."""
    return "I'm sorry, I can only help with questions about your own accounts."


def handler(
    attack_prompt: Optional[str],
    history: Optional[List[Dict[str, Any]]],
    session_id: Optional[str],
    target_system_prompt: Optional[str],
) -> str:
    return call_target(attack_prompt or "", history or [], target_system_prompt or TARGET_SYSTEM_PROMPT) or " "


client = HiddenLayer()
try:
    session = client.evaluation_sessions.red_team.start_session(
        name="Acme support bot red team (sync)",
        target_model="acme-support-bot",
        target_system_prompt=TARGET_SYSTEM_PROMPT,
        execution_strategy_type="random",
    )
    print(f"Session started: {session.workflow_id}")

    session.run_with_callback(handler)

    results = client.evaluations.red_team.retrieve_evaluation_results(session.workflow_id)
except RedTeamSessionError as e:
    sys.exit(f"Red team session error: {e}")
except ApiError as e:
    sys.exit(f"HiddenLayer API error {e.status_code}: {e.body}")

print(results.result.evaluation_report)
```

**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`).

| Strategy | What it does | Related parameters |
| - | - | - |
| `random` (Python default) | AI-generated, adaptive attacks that mix in additional randomly selected techniques per session for variety. | `max_turns`, `n_random_techniques` |
| `single` | AI-generated, adaptive attacks without the random technique mixing. | `max_turns` |
| `static_prompt_set` | Replays a fixed set of prompts. Useful for first-time setup checks, regression testing, and benchmarking. | `prompt_set_id` (required), `sessions_per_technique` |

> [!NOTE]
>
> The SDKs don't document the exact behavioral difference between `single` and `random`. The descriptions above follow the existing [usage examples](https://docs.hiddenlayer.ai/docs/products/ai-attack-simulation/custom-attack-sim/usage-examples.md).

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.

```python Python theme={null}
from hiddenlayer import AsyncHiddenLayer
from hiddenlayer.lib.red_team_session import AsyncRedTeamSession


async def start_static(client: AsyncHiddenLayer) -> AsyncRedTeamSession:
    prompt_sets = await client.evaluations.prompt_sets.list()
    prompt_set_id = next((p.id for p in prompt_sets.prompt_sets if p.name == "Financial Assistant Basic"), None)
    if prompt_set_id is None:
        raise LookupError("Prompt set not found")

    session = await client.evaluation_sessions.red_team.start_session(
        name="Static prompt regression test",
        target_model="acme-support-bot",
        execution_strategy_type="static_prompt_set",
        prompt_set_id=prompt_set_id,
    )
    return session
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

const { prompt_sets: promptSets } = await client.evaluations.promptSets.list();
const promptSet = promptSets.find((set) => set.name === "Financial Assistant Basic");
if (!promptSet) {
    throw new Error("Prompt set not found");
}

const { workflow_id: workflowId } = await client.evaluations.redTeam.create({
    name: "Static prompt regression test",
    target_model: "acme-support-bot",
    execution_strategy_type: "STATIC_PROMPT_SET",
    prompt_set_id: promptSet.id,
});
console.log(workflowId);
```

```java Java theme={null}
String promptSetId = client.evaluations().promptSets().list().getPromptSets().stream()
        .filter(set -> set.getName().equals("Financial Assistant Basic"))
        .map(PromptSetSummary::getId)
        .findFirst()
        .orElseThrow(() -> new IllegalStateException("Prompt set not found"));

String workflowId = client.evaluations()
        .redTeam()
        .create(ClientRedTeamBody.builder()
                .name("Static prompt regression test")
                .targetModel("acme-support-bot")
                .executionStrategyType(ClientRedTeamBodyExecutionStrategyType.STATIC_PROMPT_SET)
                .promptSetId(promptSetId)
                .build())
        .getWorkflowId();
```

## 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:

| Field | Description |
| - | - |
| `status` | Workflow status, for example `RUNNING`. Terminal statuses are `COMPLETED`, `FAILED`, `CANCELLED`, `TERMINATED`, and `TIMED_OUT`. |
| `phase` | Current phase of the workflow. |
| `progress_completed`, `progress_total` | Progress counters. Absent once the workflow has stopped, for example after it is terminated. |
| `total_sessions`, `active_sessions`, `completed_sessions`, `failed_sessions` | Attack session counts. |
| `elapsed_seconds`, `eta_seconds` | Elapsed time and estimated time remaining. |
| `error`, `message` | Error details and status messages, when present. |

```python Python theme={null}
import sys

from hiddenlayer import HiddenLayer
from hiddenlayer.core import ApiError

workflow_id = sys.argv[1]
client = HiddenLayer()

try:
    status = client.evaluations.red_team.retrieve_status(workflow_id)
except ApiError as e:
    sys.exit(f"HiddenLayer API error {e.status_code}: {e.body}")

print(f"{status.name}: {status.status} (phase: {status.phase})")
print(f"Progress: {status.progress_completed or 0}/{status.progress_total or 0}")
if status.error:
    print(f"Error: {status.error}")
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const workflowId = process.argv[2];
if (!workflowId) {
    throw new Error("Pass the workflow ID as the first argument.");
}

const client = new HiddenLayer();
const status = await client.evaluations.redTeam.retrieveStatus({ workflow_id: workflowId });

console.log(`${status.name}: ${status.status} (phase: ${status.phase})`);
console.log(`Progress: ${status.progress_completed ?? 0}/${status.progress_total ?? 0}`);
if (status.error) {
    console.log(`Error: ${status.error}`);
}
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.types.WorkflowStatusResponse;

public class RedTeamMonitor {
    public static void main(String[] args) {
        String workflowId = args[0];
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();
        WorkflowStatusResponse status = client.evaluations().redTeam().retrieveStatus(workflowId);
        client.close();

        System.out.println(status.getName() + ": " + status.getStatus() + " (phase: " + status.getPhase().orElse("") + ")");
        System.out.println("Progress: " + status.getProgressCompleted().orElse(0) + "/" + status.getProgressTotal().orElse(0));
        status.getError().ifPresent(error -> System.out.println("Error: " + error));
    }
}
```

## 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.

> [tab] Python
>
> 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 Python theme={null}
> import asyncio
> import sys
> from typing import Any, Dict, List, Optional
>
> from hiddenlayer import AsyncHiddenLayer
> from hiddenlayer.core import ApiError
> from hiddenlayer.lib.red_team_exceptions import RedTeamSessionError
>
>
> async def handler(
>     attack_prompt: Optional[str],
>     history: Optional[List[Dict[str, Any]]],
>     session_id: Optional[str],
>     target_system_prompt: Optional[str],
> ) -> str:
>     # Use the same handler as the original run.
>     return "I'm sorry, I can only help with questions about your own accounts."
>
>
> async def main(workflow_id: str) -> None:
>     client = AsyncHiddenLayer()
>     try:
>         session = await client.evaluation_sessions.red_team.resume_session(workflow_id, max_parallel_techniques=3)
>         status = await client.evaluations.red_team.retrieve_status(workflow_id)
>         print(f"Resumed {session.workflow_id}: {status.status}")
>
>         if status.status == "RUNNING":
>             await session.run_with_callback_parallel(handler)
>
>         results = await client.evaluations.red_team.retrieve_evaluation_results(workflow_id)
>     except (RedTeamSessionError, ApiError) as e:
>         sys.exit(f"Could not resume workflow {workflow_id}: {e}")
>
>     print(results.result.evaluation_report)
>
>
> if __name__ == "__main__":
>     asyncio.run(main(sys.argv[1]))
> ```

> [tab] TypeScript
>
> There is no session object to restore. Check the workflow's status, and if it is still running, call the `runSession` function from [Run a session](#run-a-session) with the saved workflow ID. Copy your `callTarget` function and `runSession` into this program rather than importing them: importing the Run a session program would also start a new workflow. Set `TARGET_SYSTEM_PROMPT` to the prompt of the original run.
>
> ```typescript TypeScript theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
> import { setTimeout as sleep } from "node:timers/promises";
>
> const TARGET_SYSTEM_PROMPT = "You are Acme Bank's support assistant. Only discuss the signed-in customer's own accounts.";
> const TERMINAL_STATUSES = new Set(["COMPLETED", "FAILED", "CANCELLED", "TERMINATED", "TIMED_OUT"]);
>
> // Paste your callTarget function and the runSession function from "Run a session" here.
>
> const workflowId = process.argv[2];
> if (!workflowId) {
>     throw new Error("Pass the workflow ID as the first argument.");
> }
>
> const client = new HiddenLayer();
> const status = await client.evaluations.redTeam.retrieveStatus({ workflow_id: workflowId });
> console.log(`Resuming ${workflowId}: ${status.status}`);
>
> if (status.status === "RUNNING") {
>     await runSession(client, workflowId);
> }
>
> const results = await client.evaluations.redTeam.retrieveEvaluationResults({ workflow_id: workflowId });
> console.log(results.result.evaluation_report);
> ```

> [tab] Java
>
> There is no session object to restore. Check the workflow's status, and if it is still running, call `RedTeamRun.runSession` from [Run a session](#run-a-session) with the saved workflow ID.
>
> ```java Java theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.types.WorkflowResultResponse;
> import com.hiddenlayer.api.types.WorkflowStatusResponse;
>
> public class RedTeamResume {
>     public static void main(String[] args) throws InterruptedException {
>         String workflowId = args[0];
>         HiddenLayerClient client = new HiddenLayerClientBuilder().build();
>         try {
>             WorkflowStatusResponse status = client.evaluations().redTeam().retrieveStatus(workflowId);
>             System.out.println("Resuming " + workflowId + ": " + status.getStatus());
>
>             if (status.getStatus().equals("RUNNING")) {
>                 RedTeamRun.runSession(client, workflowId);
>             }
>
>             WorkflowResultResponse results = client.evaluations().redTeam().retrieveEvaluationResults(workflowId);
>             System.out.println(results.getResult().getEvaluationReport().orElse(""));
>         } finally {
>             client.close();
>         }
>     }
> }
> ```

## 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.

> [!WARNING]
>
> Terminating a session is irreversible. The workflow stops and cannot be restarted. Confirm the workflow ID before you run this.

```python Python theme={null}
import sys

from hiddenlayer import HiddenLayer
from hiddenlayer.lib.red_team_exceptions import RedTeamSessionError

workflow_id = sys.argv[1]
client = HiddenLayer()

try:
    client.evaluation_sessions.red_team.terminate_session(workflow_id)
except RedTeamSessionError as e:
    sys.exit(f"Could not terminate workflow {workflow_id}: {e}")

print(f"Terminated {workflow_id}")
```

```typescript TypeScript theme={null}
import { HiddenLayer, HiddenLayerError } from "@hiddenlayerai/hiddenlayer-sdk";

const workflowId = process.argv[2];
if (!workflowId) {
    throw new Error("Pass the workflow ID as the first argument.");
}

const client = new HiddenLayer();
try {
    await client.evaluations.redTeam.terminate({ workflow_id: workflowId });
    console.log(`Terminated ${workflowId}`);
} catch (err) {
    if (err instanceof HiddenLayerError) {
        console.error(`Could not terminate workflow ${workflowId}: ${err.statusCode} ${err.message}`);
        process.exitCode = 1;
    } else {
        throw err;
    }
}
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.HiddenLayerApiException;

public class RedTeamTerminate {
    public static void main(String[] args) {
        String workflowId = args[0];
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();
        try {
            client.evaluations().redTeam().terminate(workflowId);
            System.out.println("Terminated " + workflowId);
        } catch (HiddenLayerApiException e) {
            System.err.println("Could not terminate workflow " + workflowId + ": " + e.statusCode() + " " + e.body());
            System.exit(1);
        } finally {
            client.close();
        }
    }
}
```

## 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.

> [tab] Python
>
> 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 Python theme={null}
> from hiddenlayer.lib.red_team_exceptions import PollTimeoutError
> from hiddenlayer.lib.red_team_session import AsyncHandler, AsyncRedTeamSession
>
>
> async def run_with_timeouts(session: AsyncRedTeamSession, handler: AsyncHandler) -> None:
>     try:
>         await session.run_with_callback_parallel(handler)
>     except PollTimeoutError as e:
>         if str(e).startswith("Polling timed out"):
>             # poll_max_wait passed while attack prompts were still coming. Resume the session later.
>             print(f"poll_max_wait exceeded; workflow {session.workflow_id} is still running.")
>         else:
>             # Every attack prompt was handled, but the workflow is still finalizing. Wait longer.
>             await session.wait_for_completion(max_wait=900.0)
> ```

> [tab] TypeScript
>
> Your loop controls how long the session runs. The `runSession` example waits up to five minutes for the workflow to finish after the last attack prompt. Change the deadline to suit your evaluations. Each API call also has its own request timeout, 60 seconds by default, which you can change with `timeoutInSeconds` on the client or on a single call.

> [tab] Java
>
> Your loop controls how long the session runs. The `runSession` example waits up to five minutes for the workflow to finish after the last attack prompt. Change the deadline to suit your evaluations. Each API call also has its own request timeout, 60 seconds by default, which you can change with `timeout` on the client builder or in a call's `RequestOptions`.

## Error handling

> [tab] Python
>
> Import the session helper exceptions from `hiddenlayer.lib.red_team_exceptions`:
>
> | Exception | Raised when |
> | - | - |
> | `RedTeamSessionError` | Base class for the exceptions below. Also raised directly when the workflow fails, when `resume_session` or `terminate_session` gets an API error other than 404, and when the next-action endpoint answers 500. |
> | `PollTimeoutError` | `poll_max_wait` passes, or `wait_for_completion` exceeds `max_wait`. |
> | `WorkflowNotFoundError` | The workflow ID doesn't exist. Raised by `resume_session`, `terminate_session`, `get_next_action`, and `wait_for_completion`. |
> | `InvalidSessionError` | `run_with_callback_parallel` submits a target response and the API answers 400. |
>
> Other API errors raise `hiddenlayer.core.ApiError` or one of its subclasses, as the examples on this page catch.

> [tab] TypeScript
>
> An error response throws a `HiddenLayerError`, or a subclass such as `HiddenLayerApi.NotFoundError`. Check `err.statusCode`: `404` means the workflow ID is wrong or belongs to another region, and `422` means a setting failed validation. A request that times out throws `HiddenLayerTimeoutError`, and a request that never reaches HiddenLayer throws a `HiddenLayerError` with no `statusCode`.

> [tab] Java
>
> An error response throws a `com.hiddenlayer.api.core.HiddenLayerApiException`, or a subclass from `com.hiddenlayer.api.errors`. Check `statusCode()`: `404` means the workflow ID is wrong or belongs to another region, and `422` means a setting failed validation. A request that times out or can't connect throws a `HiddenLayerException` with the `IOException` as its cause.

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](https://docs.hiddenlayer.ai/docs/integrations/sdk/error_handling.md) for the full error types of each SDK.

## Common errors and fixes

> [accordion] ValueError: execution\_strategy\_type must be 'single', 'random', or 'static\_prompt\_set'.
>
> 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`.

> [accordion] The static prompt set session fails or runs no prompts
>
> 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](#execution-strategies).

> [accordion] 422 Unprocessable Entity when starting a session
>
> 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.

> [accordion] PollTimeoutError: Workflow did not complete within 300.0s
>
> 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.

> [accordion] PollTimeoutError: Polling timed out after ...
>
> 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.

> [accordion] Workflow failed: ...
>
> 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.

> [accordion] 404 Not Found for a workflow ID
>
> 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.

> [accordion] 401 Unauthorized or 403 Forbidden
>
> Check your credentials and environment, and confirm that your tenant has access to AI Attack Simulation. See [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md).

## More examples

The Python SDK repository includes [example notebooks](https://github.com/hiddenlayerai/hiddenlayer-sdk-python/tree/main/examples/red_team) 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:

* [AI Attack Simulation overview](https://docs.hiddenlayer.ai/docs/products/ai-attack-simulation/overview.md)
* [Basic custom attack](https://docs.hiddenlayer.ai/docs/products/ai-attack-simulation/custom-attack-sim/basic-custom-attack.md)
* [Custom attack usage examples](https://docs.hiddenlayer.ai/docs/products/ai-attack-simulation/custom-attack-sim/usage-examples.md)
