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

# Container Functions with Python

Run your own Python code inside Aire Labs models. A container function is a Docker image that reads inputs from the model, runs your computation, and writes results back. You bring the Python code; the platform handles the rest.

Start by running a working example that computes Levelized Cost of Energy (LCOE) from bundled solar and wind cost data, then adapt it for your own computation. It is the Python counterpart of the [R example](https://docs.airelabs.com/developer/container-functions-r.md) and produces identical results. Terminal commands assume macOS or Linux.

## 1. Prerequisites

Install [OrbStack](https://orbstack.dev/) (recommended for macOS), [Docker Desktop](https://docs.docker.com/desktop/), or [Docker Engine for Linux](https://docs.docker.com/engine/install/), and make sure it is running:

```bash theme={null}
docker run --rm hello-world
```

> [!TIP]
>
> You should see `Hello from Docker!` in the output.

## 2. Quick start

Clone the example and build the image:

```bash theme={null}
git clone https://github.com/airelabsresearch/integration-language-python.git
cd integration-language-python

docker build -t lcoe-python .
```

Run it with a sample input file. This simulates what the platform does: it writes the inputs to a JSON file, runs your container, and reads the results back.

```bash theme={null}
mkdir -p /tmp/airelabs
cp fixtures/hook-input.json /tmp/airelabs/hook-input.json

docker run --rm \
  -v /tmp/airelabs:/airelabs \
  -e AIRELABS_HOOK_INPUT_PATH=/airelabs/hook-input.json \
  -e AIRELABS_HOOK_OUTPUT_PATH=/airelabs/hook-output.json \
  lcoe-python
```

> [!TIP]
>
> You should see: `OK — dataset=solar, year=2027, lcoe=43.39 USD/MWh`

Inspect the output your code produced:

```bash theme={null}
cat /tmp/airelabs/hook-output.json
```

```json theme={null}
{"results": [{"name": "dataset", "string": "solar"}, {"name": "capex", "number": {"value": "960.00", "unit": "USD/kW"}}, {"name": "opex", "number": {"value": "16.50", "unit": "USD/kW/yr"}}, {"name": "capacity_factor", "number": {"value": "0.28"}}, {"name": "lcoe", "number": {"value": "43.39", "unit": "USD/MWh"}}]}
```

The platform reads this file after your container exits and writes each result back into the model. [Inputs and Outputs](https://docs.airelabs.com/developer/container-functions-inputs.md) explains the file format, the value types, and how input names map to terms in your model.

## 3. The Python code

The example separates the model from the platform plumbing:

| Path | Purpose |
| - | - |
| `main.py` | Entry point: reads inputs, computes LCOE, writes results |
| `lcoe/model.py` | Pure LCOE logic. No JSON, Docker, or platform code |
| `lcoe/data_lookup.py` | Loads cost assumptions from the bundled `data/*.csv` |
| `lcoe/airelabs.py` | Input/output helpers. Standard library only; copy it into your own project |
| `data/` | Year-by-year cost projections, built into the image |
| `fixtures/` | Sample input files for local runs |

### main.py — the entry point

```python main.py theme={null}
def main() -> None:
    params = read_hook_input()

    dataset = require_string(params, "dataset")
    target_year = int(require_number(params, "target_year"))
    discount_rate = require_number(params, "discount_rate")
    lifetime_years = int(
        require_number(params, "lifetime_years", expected_unit="years")
    )

    costs = load_cost_assumptions(dataset, target_year)
    lcoe = compute_lcoe(
        capex=costs.capex,
        opex=costs.opex,
        capacity_factor=costs.capacity_factor,
        discount_rate=discount_rate,
        lifetime_years=lifetime_years,
    )

    write_hook_output(
        [
            string_result("dataset", dataset),
            number_result("capex", costs.capex, "USD/kW"),
            number_result("opex", costs.opex, "USD/kW/yr"),
            number_result("capacity_factor", costs.capacity_factor),
            number_result("lcoe", lcoe, "USD/MWh"),
        ]
    )
```

The full file also returns an `error` result for a non-positive discount rate, and wraps `main()` so any exception exits with code 1. A non-zero exit tells the platform the run failed.

### lcoe/airelabs.py — the helpers

Reads the input JSON and writes the output JSON, converting the platform's decimal strings to and from Python numbers:

* `read_hook_input()` returns the list of input parameters.
* `require_number()`, `require_string()`, `require_boolean()`, `require_date()` extract one parameter by name and raise if it is missing.
* `number_result()`, `number_array_result()`, `string_result()`, `boolean_result()`, `date_result()`, `error_result()` build result entries.
* `write_hook_output()` writes the results file.

> [!TIP]
>
> Keep your business logic in modules like `model.py` with no platform dependencies. You can then develop and test it in a REPL or notebook exactly as you normally would, and `main.py` stays a thin wrapper.

### lcoe/data\_lookup.py — bundled data

Containers have no network access when they run, so reference data is built into the image. `data_lookup.py` resolves `data/` relative to its own file, not the working directory, and raises a clear error for an unknown dataset or year. See [No Internet: Bundling Data](https://docs.airelabs.com/developer/no-internet-bundling-data.md) for why and for how to bring in data from remote sources.

## 4. Different inputs

Copy a different fixture into `/tmp/airelabs/hook-input.json` and re-run the `docker run` command from the quick start.

| Fixture | Result |
| - | - |
| `hook-input-wind.json` | `OK — dataset=wind, year=2030, lcoe=44.81 USD/MWh` |
| `hook-input-bad-rate.json` | Exit 0. The `lcoe` result is `{"name": "lcoe", "error": "INVALID_DISCOUNT_RATE"}`; the other outputs still have values |
| `hook-input-unknown-dataset.json` | `Error: unknown dataset 'geothermal' — available datasets: solar, wind`. Exit 1, no output file |

Run the tests inside the image:

```bash theme={null}
docker run --rm lcoe-python pytest tests/test_model.py
docker run --rm lcoe-python pytest tests/test_main.py
```

## 5. Writing your own function

1. **Write your model** as plain Python that takes arguments and returns values.
2. **Edit `main.py`** to read the parameters your model needs with the `require_*` helpers and write its results with the `*_result` helpers.
3. **Add a fixture** in `fixtures/` with the parameters your model expects.
4. **Add dependencies** to `dependencies` in `pyproject.toml`, then run `uv lock`. They are installed when the image is built.
5. **Rebuild and run** with `docker build` and the same `docker run` command, using your fixture.

## 6. The Dockerfile

The example uses the official [uv](https://docs.astral.sh/uv/) image and installs the locked dependencies at build time:

```dockerfile Dockerfile theme={null}
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim

ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy

WORKDIR /app

# Dependencies first, so editing code doesn't reinstall them.
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    --mount=type=bind,source=README.md,target=README.md \
    uv sync --locked --no-install-project

COPY . /app
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked

ENV PATH="/app/.venv/bin:$PATH"

CMD ["python", "main.py"]
```

* `uv sync --locked` installs exactly the versions in `uv.lock`, so every build gets the same packages.
* `COPY . /app` copies your code, `data/`, and fixtures into the image.
* `CMD` runs your entry point. It is a `CMD`, not an `ENTRYPOINT`, so you can override it locally, as the test commands above do.

> [!NOTE]
>
> The platform runs `linux/amd64` images. If you build on Apple Silicon, build with `docker build --platform linux/amd64` before you publish. The [publishing workflow](https://docs.airelabs.com/developer/publishing-container-functions.md) does this for you.

## 7. Develop with moon

The `docker` commands above need nothing but Docker. The example repository also defines its test, lint, build, and release steps as [moon](https://moonrepo.dev/moon) tasks. moon installs the pinned Python and uv versions, keeps the virtual environment in sync with `uv.lock`, and skips a task when its inputs have not changed since the last run. The same tasks run in the repository's GitHub Actions, so a green run on your machine means a green run in CI.

Install [proto](https://moonrepo.dev/proto), the toolchain manager, then provision the pinned versions from the repository root:

```bash theme={null}
proto install
```

This installs the moon, Python, and uv versions pinned in `.prototools`. There is no separate install step: moon runs `uv sync` before each task when the lockfile has changed.

| Command | What it does |
| - | - |
| `moon run lcoe:test` | Runs the pytest suite on your machine, no Docker needed |
| `moon run lcoe:lint` | Checks the code with ruff |
| `moon run lcoe:format` | Checks formatting (the CI gate) |
| `moon run lcoe:format-fix` | Applies formatting and lint fixes in place |
| `moon run lcoe:build` | Runs `test` and `lint`, then builds the `linux/amd64` image locally |
| `moon run lcoe:release` | Runs `test` and `lint`, then builds and pushes the image to your registry |

`lcoe:build` prints the name of the image it built. Use that name in place of `lcoe-python` in the `docker run` commands above.

To publish with `lcoe:release`, pass your organization ID and an API key with Registry Push permission (see [Publishing Container Functions](https://docs.airelabs.com/developer/publishing-container-functions.md)), and set `RELEASE_ENV=production`. Your organization ID is the part of your registry hostname between `org-` and `.registry`:

```bash theme={null}
REGISTRY_ORG_ID=<your-org-id> \
REGISTRY_PASSWORD=<your-api-key> \
RELEASE_ENV=production \
RELEASE_VERSION=v1.2.0 \
  moon run lcoe:release
```

This pushes `org-<your-org-id>.registry.airelabs.run/lcoe-python:v1.2.0`. Set `IMAGE_REPO` to publish under a different image name. Without `RELEASE_VERSION`, the tag is the git tag on the current commit, or `branch-<branch>-<short-sha>` if there is none.

> [!WARNING]
>
> `RELEASE_ENV` defaults to `stage`, an Aire Labs internal registry. Always set `RELEASE_ENV=production` to publish to your organization's registry.

## 8. What's next

Once your function works locally, publish it so your models can run it. [Publishing Container Functions from GitHub](https://docs.airelabs.com/developer/publishing-container-functions.md) sets up a GitHub Actions workflow that builds and pushes a new image every time you push a git tag. The workflow is the same for Python and R.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.