> For the complete documentation index, see [llms.txt](https://docs.valohai.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.valohai.com/serving-your-models/real-time-endpoints/deploy-real-time.md). Agents can also search and read this documentation through its [MCP server](https://docs.valohai.com/~gitbook/mcp).

# Deploy Real-Time Endpoint

Deploy a machine learning model as a RESTful API endpoint on Kubernetes for low-latency predictions.

> **Important:** Valohai only creates endpoints from Git-versioned code. Commit and push your code before creating a deployment.

### Create the inference code

Build a FastAPI endpoint that loads your model and handles predictions.

Create `predict.py`:

```python
from fastapi import FastAPI, File, UploadFile
import tensorflow as tf
import numpy
from PIL import Image
from io import BytesIO

app = FastAPI()

model_path = "model.h5"
loaded_model = None


@app.post("{full_path:path}")
async def predict(image: UploadFile = File(...)):
    img = Image.open(BytesIO(await image.read()))

    # Preprocess for MNIST
    img = img.resize((28, 28)).convert("L")
    img_array = numpy.array(img)
    image_data = numpy.reshape(img_array, (1, 28, 28))

    # Load model once, reuse for subsequent requests
    global loaded_model
    if not loaded_model:
        loaded_model = tf.keras.models.load_model(model_path)

    # Run prediction
    prediction = loaded_model.predict_classes(image_data)

    return f"Predicted_Digit: {prediction[0]}"
```

**Why this pattern:**

* Loading the model once improves response time for subsequent requests
* FastAPI handles async requests efficiently
* The catch-all path `{full_path:path}` works with Valohai's URL routing

> **Need a model?** Download a pre-trained MNIST model: [model.h5](https://valohai-public-files.s3.eu-west-1.amazonaws.com/tutorials/inference/model.h5)

### Test locally

Validate your endpoint before deploying:

```shell
pip install tensorflow==2.5.1 fastapi Pillow python-multipart

uvicorn --debug --reload predict:app
```

Visit `http://localhost:8000/docs` to see FastAPI's interactive documentation.

### Define the endpoint

Add this to your `valohai.yaml`:

```yaml
- endpoint:
    name: digits
    description: predict digits from image inputs
    image: tiangolo/uvicorn-gunicorn-fastapi:python3.7
    server-command: uvicorn predict:app --host 0.0.0.0 --port 8000
    files:
      - name: model
        description: Model output file from TensorFlow
        path: model.h5
```

**Configuration explained:**

* `image` - Base Docker environment (includes FastAPI + Uvicorn)
* `server-command` - How to start your HTTP server
* `files` - Model artifacts to include (path is where they'll be saved)

**Using multiple model files:** You can include multiple models in one endpoint:

```yaml
files:
  - name: classifier
    path: classifier.pkl
  - name: regressor
    path: regressor.pkl
```

Both files become available in your endpoint container at the specified paths.

#### Set endpoint resources

Set the CPU, memory and ephemeral storage for each replica under `resources`. Each resource takes a `min` (the Kubernetes request) and a `max` (the Kubernetes limit):

```yaml
- endpoint:
    name: digits
    image: tiangolo/uvicorn-gunicorn-fastapi:python3.7
    server-command: uvicorn predict:app --host 0.0.0.0 --port 8000
    resources:
      cpu:
        min: 0.5  # fractional CPU cores
        max: 2
      memory:
        min: 1024  # megabytes
        max: 2048
      ephemeral-storage:
        min: 1000  # megabytes
        max: 5000
```

* `cpu` is in fractional CPU cores, for example `0.5` for half a core.
* `memory` and `ephemeral-storage` are in megabytes.
* Ephemeral storage covers the container's writable layer, `emptyDir` volumes and logs. Kubernetes evicts a replica that uses more than the maximum.
* Each `min` must be less than or equal to its `max`.

Setting a CPU maximum can cause throttling even when the node has spare CPU capacity. Consider setting only `min` so the endpoint can use more CPU when it needs it.

These values pre-fill the resource fields when you create a deployment version, and you can change them for each version. When neither `valohai.yaml` nor the version sets a value, the cluster's default applies. To drop an ephemeral storage value set in `valohai.yaml` and use the cluster's default instead, enter `0`.

#### Installing additional packages

If your base image doesn't include all dependencies, create `requirements-deployment.txt`:

```
valohai-utils
tensorflow==2.5.1
Pillow
python-multipart
```

Valohai installs these when building your deployment.

**If Uvicorn isn't in your base image:** Update `server-command` to use the installed path:

```yaml
server-command: ~/.local/bin/uvicorn predict:app --host 0.0.0.0 --port 8000
```

> **Scripts in subfolders:** Use Python module syntax, not file paths. For a script at `myfolder/predict.py`, use `myfolder.predict:app` instead of `myfolder/predict:app`.

### Push to Git

Commit your deployment code:

```shell
git add valohai.yaml predict.py requirements-deployment.txt
git commit -m "Add digit prediction endpoint"
git push
```

### Create the deployment

1. Open your project in Valohai
2. Click **Fetch repository** to pull your latest commit
3. Navigate to the **Deployment** tab
4. Click **Create deployment**
5. Name your deployment and select your deployment target (default: Valohai.Cloud)
6. Click **Create version**
7. Select the `digits` endpoint
8. Choose a `model.h5` file from your previous training runs
9. Review the endpoint's resources, such as replicas, CPU and memory. The deployment target sets the maximum number of replicas per endpoint: by default 1000 on a private target and 1 on a shared one.
10. Click **Create version**

**Deployment status:** Watch the build progress. When it shows "100% - Available", your endpoint is ready.

#### Use a dataset or a model version as the endpoint file

Each file in the endpoint definition has a switch above the file picker:

* **Datum** - pick a single file, for example an output of a training execution.
* **Datum URL** - enter a `datum://` URI, either a datum ID such as `datum://<datum-id>` or a [datum alias](https://docs.valohai.com/data/data-versioning/metadata-overview/aliases.md) in the deployment's project, such as `datum://production-model`.
* **Dataset** - enter a dataset version URI, such as `dataset://digit-models/v3`. The dataset version must be published.
* **Model** - enter a model version URI, such as `model://digits/4`. `model://digits/latest` uses the latest approved version.

Valohai resolves the URI when you create the deployment version. The version keeps using the files it resolved, even when the dataset or the model gets new versions later. To deploy a newer model version, create a new deployment version.

A dataset or a model version can hold several files. Valohai treats the `path` of the endpoint file as a directory and places each file in it under its own name. With `path: model` and a model version that contains `model.h5` and `labels.json`, your code reads `model/model.h5` and `model/labels.json`.

#### Create a version with the API

To create deployment versions from CI or a script, send a `POST` to `/api/v0/deployment-versions/`. Find the deployment's ID with `GET /api/v0/deployments/?project=<project-id>`.

```python
import os

import requests

headers = {"Authorization": f"Token {os.environ['VH_API_TOKEN']}"}

payload = {
    "deployment": "<deployment-id>",
    "commit": "main",  # a commit identifier or a branch name
    "suggest_name": True,
    "endpoint_configurations": {
        "digits": {
            "files": {"model": "model://digits/latest"},
            "replicas": 1,
            "cpu_request": 0.5,
            "memory_request": 1024,
        },
    },
}

resp = requests.post(
    "https://app.valohai.com/api/v0/deployment-versions/",
    json=payload,
    headers=headers,
)
resp.raise_for_status()
print(resp.json()["name"])
```

* `name` or `suggest_name` - give the version a `name`, or set `suggest_name` to `true` to let Valohai generate a name from the date and a counter, such as `20260315.0`. Don't send both.
* `files` - maps each file name in the endpoint definition to a datum ID, a `datum://` URI or datum alias, a `dataset://` URI or a `model://` URI. Both you and the deployment's owner need access to the datum; a datum that's purged or inaccessible is reported as not found.
* `replicas` - the number of replicas for the endpoint, at most the deployment's `target_max_replicas`.
* Resources - `cpu_request` and `cpu_limit` in CPU cores, and `memory_request`, `memory_limit`, `ephemeral_storage_request` and `ephemeral_storage_limit` in megabytes. Values you leave out come from the endpoint's `resources` in `valohai.yaml`.

Valohai starts building the endpoint images after it creates the version.

### Test your endpoint

Verify it works from the Valohai UI:

1. Open your deployment
2. Click **Test deployment**
3. Select your `digits` endpoint
4. Add a field named `image` with type **File**
5. Upload a test image
6. Click **Send request**

**Example test image:**

You should see a response like: `Predicted_Digit: 7`

***

**Next steps:**

* [Monitor your endpoint](https://docs.valohai.com/serving-your-models/real-time-endpoints/monitor.md) with custom metrics
* [Set up aliases](https://github.com/valohai/dokuhai/tree/main/docs/concepts/real-time-deployment.md#deployment-alias) for production routing
* [Handle route prefixes](https://docs.valohai.com/serving-your-models/real-time-endpoints/deployment-prefix.md) for path-based routing


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.valohai.com/serving-your-models/real-time-endpoints/deploy-real-time.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
