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

# Apply Risk Segmentation After Analysis

> Learn how to use the Python SDK to create or replace a risk segmentation configuration on every completed analysis in an engagement.

This example demonstrates how to apply a risk segmentation configuration using the
[Python SDK](https://pypi.org/project/mindbridge-api-python-client/) after analyses are completed. You will connect to an existing
engagement, skip analyses that have not finished running, and create the same named configuration on each completed analysis result. If a
configuration with that name already exists, the script deletes it first so reruns replace the previous settings.

## Prerequisites

Complete [Get started](https://developer.mindbridge.ai/sdk/python/get-started.md) so the Python SDK is installed and configured.

You also need:

* A MindBridge tenant host that you can access, such as `{your-tenant}.mindbridge.ai`.
* An engagement ID for an engagement that contains one or more analyses.

## Overview

In this guide you will:

* Authenticate with the MindBridge API and load an engagement by ID.
* Iterate through every analysis in the engagement and skip runs that are not complete.
* Create a risk segmentation configuration on each completed analysis result, replacing any existing configuration with the same name.

## Configure Your Inputs

Adjust the values in the **Configure inputs** section at the top of the script below to match your tenant, engagement, and segmentation
requirements. Typically, you only need to update that section; the rest of the script follows a standard process.

* **`mindbridge_url`**: The MindBridge host for your tenant.
* **`engagement_id`**: The ID of the engagement whose completed analyses should receive the configuration.
* **`risk_segmentation_config`**: The `RiskSegmentationConfigItem` to apply. Update `name`, `segments`, and `columns` to match the grouping
  and metrics you want in MindBridge. The script copies this item and sets `analysis_id` for each completed analysis.

The listing below is one continuous script you can save and run. Step boundaries are marked with comments inside the code.

## Complete example

```python theme={null}
import os
import mindbridgeapi as mbapi

# --- Configure inputs (edit for your environment) ---
mindbridge_url = "{your-tenant}.mindbridge.ai"
api_token = os.environ.get("MINDBRIDGE_API_TOKEN", "")
engagement_id = "{ENGAGEMENT_ID}"
risk_segmentation_config = mbapi.RiskSegmentationConfigItem(
    name="New Risk Segmentation Config",
    segments=["risk_score"],
    columns=["total_count"],
)

# --- Step 1: Connect and load the engagement ---
server = mbapi.Server(url=mindbridge_url, token=api_token)
engagement = server.engagements.get_by_id(engagement_id)

print(f"Updating all completed analyses in {engagement.name!r} ({engagement.id})")

# --- Step 2: Apply the config to each completed analysis ---
# Skip analyses that have not finished. For each completed
# run, delete a same-named config if one exists, then
# create the new configuration on the latest result.
for analysis in engagement.analyses:
    if not analysis.latest_analysis_result_id:
        print(f"{analysis.name!r} ({analysis.id}) was not done: no action taken")
        continue

    updated_or_created_text = "Created"

    for existing_config in server.risk_segmentation_configs.get(
        query_filter={"analysisId": analysis.latest_analysis_result_id}
    ):
        if existing_config.name == risk_segmentation_config.name:
            server.risk_segmentation_configs.delete(existing_config)
            updated_or_created_text = "Updated"

    created_config = server.risk_segmentation_configs.create(
        risk_segmentation_config.model_copy(
            update={"analysis_id": analysis.latest_analysis_result_id}
        )
    )
    print(
        f"{updated_or_created_text} {created_config.name!r} "
        f"in {analysis.name!r} ({analysis.id})"
    )
```

***

When the script finishes, each completed analysis in the engagement has a risk segmentation configuration with the name you specified.
Analyses without a latest result are left unchanged. To modify this workflow, adjust `segments`, `columns`, or the configuration `name` to
match how your team reviews risk in MindBridge.
