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

# Python SDK Setup Guide

> Install, initialize, and optimize the HyperProbe Python SDK inside in-process Python applications.

The HyperProbe Python SDK runs as an extremely lightweight in-process agent. It uses Python's `sys.monitoring` APIs to capture variables, stack frames, and logs without blocking your application.

***

## Technical Prerequisites

* **Runtime:** Python 3.12 and later.
* **Metadata:** Access to the active git commit SHA (mandatory for matching local source coordinates to production builds).

***

## Installation

Add the SDK as a dependency using your package manager:

<CodeGroup>
  ```bash pip theme={null}
  pip install hyperprobe-agent
  ```

  ```bash poetry theme={null}
  poetry add hyperprobe-agent
  ```

  ```bash pipenv theme={null}
  pipenv install hyperprobe-agent
  ```

  ```bash uv theme={null}
  uv add hyperprobe-agent
  ```
</CodeGroup>

***

## Initialization Walkthrough

Follow these steps to initialize the HyperProbe agent inside your application:

<Steps>
  <Step title="Choose an initialization method">
    Select one of the following initialization methods:

    <Tabs>
      <Tab title="Code Initialization">
        Create a dedicated file named `hyperprobe_init.py` in your project source root:

        ```python hyperprobe_init.py theme={null}
        import os

        from hyperprobe import HyperProbe

        HyperProbe.start({
            "service_id": "<service-uuid-from-dashboard>",
            "environment": os.getenv("PYTHON_ENV"),
            "broker_url": "https://logger.app.hyperprobe.co",
            "commit_sha": os.getenv("GIT_COMMIT"),
        })
        ```
      </Tab>

      <Tab title="Auto Initialization">
        Prepend your normal application startup command with the `hyperprobe-run` launcher:

        ```bash theme={null}
        export GIT_COMMIT=$(git rev-parse HEAD)
        export HYPERPROBE_SERVICE_ID=<service-uuid-from-dashboard>
        export HYPERPROBE_ENVIRONMENT=production
        export HYPERPROBE_BROKER_URL=https://logger.app.hyperprobe.co

        hyperprobe-run python main.py
        ```

        This method works with standard Python scripts and WSGI/ASGI runners, such as `gunicorn` and `uvicorn`.
      </Tab>
    </Tabs>
  </Step>

  <Step title="Import it in your entrypoint">
    In your main application file, import `hyperprobe_init` **as early as possible** before starting your application:

    ```python main.py theme={null}
    import hyperprobe_init

    from app import create_app

    app = create_app()
    ```

    <Warning>
      **Environment Variables Loading Order:** If `hyperprobe_init.py` reads variables loaded by a library such as `python-dotenv`, load those variables before importing `hyperprobe_init`.
    </Warning>
  </Step>

  <Step title="Configure your Dockerfile">
    To enable Docker-based deployments, define a `GIT_COMMIT` build argument inside your `Dockerfile` with a default value of `unknown`:

    ```dockerfile Dockerfile theme={null}
    ARG GIT_COMMIT=unknown
    ENV GIT_COMMIT=${GIT_COMMIT}
    ```
  </Step>

  <Step title="Run local Docker builds">
    For building and testing Docker containers locally, inject your active git commit:

    ```bash theme={null}
    docker build --build-arg GIT_COMMIT=$(git rev-parse HEAD) -t api:latest .
    ```
  </Step>

  <Step title="Inject correct SHA in CI/CD (The PR Merge Trap)">
    To protect source alignment, HyperProbe refuses to start if `commit_sha` resolves to `unknown`. Pass the real commit SHA to `GIT_COMMIT` during deployment.

    Always use your CI/CD platform's native commit SHA variable:

    | Platform / Engine         | Configuration Option             | Build Argument Syntax                                                              |
    | :------------------------ | :------------------------------- | :--------------------------------------------------------------------------------- |
    | **GitHub Actions**        | PR-Safe HEAD Check (Recommended) | `--build-arg GIT_COMMIT=${{ github.event.pull_request.head.sha \|\| github.sha }}` |
    | **GitHub Actions (Push)** | Standard Branch Push             | `--build-arg GIT_COMMIT=${{ github.sha }}`                                         |
    | **GitLab CI/CD**          | GitLab Variable                  | `--build-arg GIT_COMMIT=$CI_COMMIT_SHA`                                            |
    | **CircleCI**              | CircleCI Variable                | `--build-arg GIT_COMMIT=$CIRCLE_SHA1`                                              |

    <Warning>
      **Beware of the PR Merge Commit Trap:** By default, GitHub Actions checks out a virtual merge commit for a `pull_request` trigger instead of the commit from your branch.

      If you use `git rev-parse HEAD` or `${{ github.sha }}` in a pull request workflow, source mapping can fail. Use `${{ github.event.pull_request.head.sha || github.sha }}` for pull request builds.
    </Warning>
  </Step>
</Steps>

***

## Configuration & Environment Variables Reference

You can configure the agent by passing properties inside your `HyperProbe.start()` options object, or by using **environment variables**.

The following example includes the available programmatic options and their corresponding environment variables:

```python hyperprobe_init.py theme={null}
import os

from hyperprobe import HyperProbe

HyperProbe.start({
    # --- CORE OPTIONS ---
    "service_id": "<service-uuid-from-dashboard>",
    "environment": os.getenv("PYTHON_ENV"),
    "broker_url": "https://logger.app.hyperprobe.co",
    "commit_sha": os.getenv("GIT_COMMIT"),

    # --- BUFFERING & PERFORMANCE ---
    "max_queue_size": 100,      # Env: HYPERPROBE_MAX_QUEUE_SIZE
    "flush_interval_ms": 1000,  # Env: HYPERPROBE_FLUSH_INTERVAL_MS
    "sync_interval_ms": 60000,  # Env: HYPERPROBE_SYNC_INTERVAL_MS

    # --- SAFETY GUARDRAILS ---
    "hits_per_sec": 10,         # Env: HYPERPROBE_HITS_PER_SEC
    "bandwidth_kb_per_sec": 1024, # Env: HYPERPROBE_BANDWIDTH_KB_PER_SEC

    # --- DATA & REDACTION CONTROLS ---
    "redact_keys": [            # Env: HYPERPROBE_REDACT_KEYS
        "password", "secret", "token", "authorization", "cookie", "key", "signature"
    ],
    "redact_values": [],        # Env: HYPERPROBE_REDACT_VALUES
    "max_object_depth": 3,      # Env: HYPERPROBE_MAX_OBJECT_DEPTH
    "max_array_length": 3,      # Env: HYPERPROBE_MAX_ARRAY_LENGTH
    "max_object_properties": 50, # Env: HYPERPROBE_MAX_OBJECT_PROPERTIES
    "max_string_length": 1024,  # Env: HYPERPROBE_MAX_STRING_LENGTH
    "stack_frame_depth": 3,     # Env: HYPERPROBE_STACK_FRAME_DEPTH
})
```

***

## Safety Shields

Because dynamic monitoring could affect application performance during heavy execution spikes, the Python Agent includes active **Safety Shields**:

* **Yellow Threshold:** Logs a warning when execution lag or cumulative pause time reaches 50% of its limit.
* **Red Threshold:** Suspends tracing when execution lag exceeds 50 ms or cumulative pause time exceeds 15 ms.
* **Auto-Recovery:** Resumes instrumentation after the cooldown period when application performance stabilizes.
