Sub topic 6
Calling the endpoint: V1 and V2 protocols
An InferenceService is only useful once clients can call it. KServe exposes two REST request formats, the V1 protocol and the V2 protocol, which is also called the Open Inference Protocol. This chapter explains how each one works, how to choose between them, and the errors people commonly hit.
This chapter assumes you have applied an InferenceService (the previous chapters covered this) and can reach the cluster ingress with curl. It also assumes you can read JSON. You should know the Host header trick from the first-service chapter: the ingress routes on the service's host name, so every request carries Host: ${SERVICE_HOSTNAME}.
Why two protocols exist
V1 is the original KServe (KFServing) format. It is simple and tensor-agnostic: you send a list of instances and get a list of predictions. The server decides what each instance means.
V2 was designed to be shared across serving systems, including Triton, MLServer and TorchServe. It describes data as named, typed tensors with explicit shapes. That makes it stricter, but it is also the same for every model type and every runtime that implements it. V2 also has a gRPC binding and standard endpoints for health and metadata.
| Aspect | V1 | V2 (Open Inference) |
|---|---|---|
| Predict path | `/v1/models/<name>:predict` | `/v2/models/<name>/infer` |
| Request key | `instances` | `inputs` (named tensors) |
| Response key | `predictions` | `outputs` (named tensors) |
| Types and shapes | Implicit | Explicit `datatype` and `shape` |
| Readiness | `GET /v1/models/<name>` | `GET /v2/models/<name>/ready` |
| Transport | REST | REST and gRPC |
The V1 protocol
You have already sent one V1 request. Here is the request and response in full.
curl -H "Host: ${SERVICE_HOSTNAME}" -H "Content-Type: application/json" \
http://${INGRESS_HOST}:${INGRESS_PORT}/v1/models/sklearn-iris:predict \
-d '{"instances": [[6.8, 2.8, 4.8, 1.4], [6.0, 3.4, 4.5, 1.6]]}'{"predictions": [1, 1]}Each element of instances is one example, and each element of predictions is the result for the example at the same position. The order is preserved. For the iris model, each prediction is a class index.
V1 has these endpoints:
GET /v1/models/<name>returns the model's readiness.POST /v1/models/<name>:predictruns inference.POST /v1/models/<name>:explainruns an explainer, if one is configured.
Note the colon in :predict. It is part of the path, not a port.
The V2 protocol
V2 puts the data in a list of tensors. Each tensor has a name, a shape, a datatype and a flat data array in row-major order.
{
"inputs": [
{
"name": "input-0",
"shape": [2, 4],
"datatype": "FP32",
"data": [6.8, 2.8, 4.8, 1.4, 6.0, 3.4, 4.5, 1.6]
}
]
}The shape [2, 4] says there are 2 rows of 4 features. The data array holds all 8 values, row after row. The response has the same structure:
{
"model_name": "sklearn-iris",
"outputs": [
{"name": "predict", "shape": [2], "datatype": "INT64", "data": [1, 1]}
]
}The common datatypes are BOOL, UINT8, INT32, INT64, FP16, FP32, FP64 and BYTES (used for strings and raw bytes). The output tensor names depend on the runtime. MLServer's scikit-learn runtime names its output predict, for example.
V2 also defines these endpoints:
GET /v2/health/liveandGET /v2/health/readyreport server health.GET /v2/models/<name>returns metadata such as input and output names, shapes and datatypes.GET /v2/models/<name>/readyreports whether one model is loaded.POST /v2/models/<name>/inferruns inference.
The metadata endpoint is useful when you don't know a model's input names. Call it first, then build your request from what it reports.
Choosing the protocol in the InferenceService
The protocol is a property of the predictor. By default, a runtime that supports V1 serves V1. To ask for V2, set protocolVersion under model:
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: sklearn-iris-v2
spec:
predictor:
model:
modelFormat:
name: sklearn
protocolVersion: v2
storageUri: gs://kfserving-examples/models/sklearn/1.0/modelKServe uses protocolVersion along with modelFormat when it picks a ServingRuntime. For scikit-learn, V1 selects the KServe sklearn server, and V2 selects MLServer. The chapter on serving runtimes explains how the match works. This means that changing the protocol can change the container that serves your model. Check the model artifact against the runtime you end up with. MLServer's sklearn runtime, for example, looks for a file named model.joblib, model.pkl or model.pickle.
kubectl apply -f sklearn-iris-v2.yaml
kubectl get inferenceservice sklearn-iris-v2Wait until READY is True, then call the V2 endpoint:
curl -H "Host: ${SERVICE_HOSTNAME}" -H "Content-Type: application/json" \
http://${INGRESS_HOST}:${INGRESS_PORT}/v2/models/sklearn-iris-v2/infer \
-d '{"inputs":[{"name":"input-0","shape":[2,4],"datatype":"FP32","data":[6.8,2.8,4.8,1.4,6.0,3.4,4.5,1.6]}]}'Here SERVICE_HOSTNAME is the host name of the sklearn-iris-v2 service, which you can read from kubectl get inferenceservice sklearn-iris-v2 -o jsonpath='{.status.url}'.
How a request travels
If the service has a transformer, the request goes to the transformer first. The transformer converts it and then calls the predictor. Both ends must agree on the protocol.
A client in Python
Typing JSON into curl gets old quickly. This script builds both request types from the same NumPy-free data and prints the results. It reads the same environment variables as the shell examples.
import os
import requests
ingress = f"http://{os.environ['INGRESS_HOST']}:{os.environ['INGRESS_PORT']}"
headers = {
"Host": os.environ["SERVICE_HOSTNAME"],
"Content-Type": "application/json",
}
rows = [[6.8, 2.8, 4.8, 1.4], [6.0, 3.4, 4.5, 1.6]]
def predict_v1(model: str) -> list:
url = f"{ingress}/v1/models/{model}:predict"
resp = requests.post(url, headers=headers, json={"instances": rows}, timeout=10)
resp.raise_for_status()
return resp.json()["predictions"]
def infer_v2(model: str) -> list:
url = f"{ingress}/v2/models/{model}/infer"
flat = [value for row in rows for value in row]
body = {
"inputs": [
{
"name": "input-0",
"shape": [len(rows), len(rows[0])],
"datatype": "FP32",
"data": flat,
}
]
}
resp = requests.post(url, headers=headers, json=body, timeout=10)
resp.raise_for_status()
return resp.json()["outputs"][0]["data"]
if __name__ == "__main__":
kind = os.environ.get("PROTOCOL", "v1")
model = os.environ.get("MODEL_NAME", "sklearn-iris")
print(predict_v1(model) if kind == "v1" else infer_v2(model))Run it with PROTOCOL=v2 MODEL_NAME=sklearn-iris-v2 python client.py against the V2 service. Set SERVICE_HOSTNAME to match the service you call, because each InferenceService has its own host name.
Common errors
- 404 Not Found. The path doesn't match the protocol. A
/v2/...path sent to a V1-only server returns 404. Check whichprotocolVersionthe service was deployed with. - 404 with a correct path. The
Hostheader is missing or belongs to another service, so the ingress can't route the request. - 400 or 500 with a shape or type message. In V2,
shapemust multiply out to the length ofdata, anddatatypemust match what the model expects. In the example above, 2 × 4 = 8 values. - Wrong numbers, no error. V2
datais flattened row by row. If you flatten by column, the model gets different features and returns plausible but wrong predictions. - A 503 right after deploying. The pod may still be downloading the model. Wait for
READY: Truebefore sending traffic. - Mixed protocols in a pipeline. A transformer that speaks V1 to a V2 predictor fails. Make the two components use the same protocol.
gRPC
V2 also defines a gRPC service with the same operations. Using it with KServe means exposing the container's port with the name h2c and setting protocolVersion: grpc-v2. The ingress must also support HTTP/2. gRPC uses a compact binary encoding, which cuts payload size and parsing cost for large tensors. For small tabular requests, REST is usually fast enough, and it is easier to debug.
Custom predictors
A custom predictor built with the KServe Python SDK, like the SumModel from the previous chapter, receives a decoded payload in its predict method. The SDK serves the V1 endpoints, and recent versions also serve the V2 REST endpoints. Which payload shape your predict sees depends on the endpoint the client called. If your code reads payload["instances"], it handles V1 requests only. Decide which protocol your clients will use, and handle that shape.
Choosing between them
- Use V1 for simple models, quick tests, and cases where your clients already send
instances. - Use V2 when you need explicit types and shapes, runtimes such as Triton or MLServer, a metadata endpoint, or gRPC.
- Keep one protocol per service. Clients are easier to maintain when the contract does not change when the runtime does.
Exercise
A client sends {"inputs":[{"name":"input-0","shape":[3,4],"datatype":"FP32","data":[1,2,3,4,5,6,7,8]}]} and gets an error. What is wrong, and what should the request contain?
Show answer
The shape says 3 rows of 4 features, which requires 12 values, but data has only 8. Either change the shape to [2,4] or supply 12 values in row-major order.
Exercise
You deployed an InferenceService without protocolVersion, and POST /v2/models/my-model/infer returns 404. What are two ways to fix it?
Show answer
Redeploy with protocolVersion: v2 under predictor.model, so that a runtime serving V2 (such as MLServer for sklearn) is selected. Or change the client to call /v1/models/my-model:predict with an instances body.