Sub topic 13
Chaining models with InferenceGraph
What this chapter covers
Some prediction tasks need more than one model. A fraud check might run a cheap model first and call an expensive one only for suspicious cases. An image pipeline might classify an image as cat or dog, then send dogs to a breed classifier. An InferenceGraph is a KServe resource that describes this wiring, so the routing lives in the cluster and not in client code.
This chapter assumes you can write an InferenceService (see "Your first InferenceService"), know how its URL is addressed, and are comfortable with V1-style JSON payloads. It also assumes you know what a transformer does.
Why a graph resource
Without a graph, the client has to call model A, read the answer, decide, and call model B. Every client then repeats that logic. A graph moves it to the server.
- Clients make one request to one URL.
- Routing rules are declared in YAML and versioned like any other manifest.
- Each model stays an ordinary
InferenceService, so it scales, rolls out and is monitored on its own.
An InferenceGraph does not run models itself. It creates a router, a small HTTP service that receives the request, calls the InferenceService endpoints in the order you describe, and returns the result.
The building blocks
A graph has a set of named nodes. One node must be named root, and it receives every incoming request. Each node has a routerType and a list of steps.
A step points at something to call:
serviceNamenames anInferenceServicein the same namespace.serviceUrlgives an arbitrary HTTP endpoint.nodeNamerefers to another node in the same graph, which lets you nest routers.
There are four router types.
| routerType | Behavior | Typical use |
|---|---|---|
| `Sequence` | Runs steps in order, one after another | Multi-stage pipelines |
| `Switch` | Sends the request to the first step whose `condition` matches | Routing by content |
| `Ensemble` | Sends the request to all steps in parallel and merges the results | Combining model votes |
| `Splitter` | Sends each request to one step, chosen by `weight` | A/B tests, traffic splits |
A first graph: Sequence with a condition
Assume two InferenceService resources already exist: cat-dog-classifier and dog-breed-classifier.
apiVersion: serving.kserve.io/v1alpha1
kind: InferenceGraph
metadata:
name: cat-dog-pipeline
spec:
nodes:
root:
routerType: Sequence
steps:
- name: cat_dog
serviceName: cat-dog-classifier
- name: breed
serviceName: dog-breed-classifier
data: $request
condition: "[@this].#(predictions.0==\"dog\")"Some details matter here.
- The API version is
v1alpha1, not thev1beta1used byInferenceService. Alpha APIs can change between KServe releases, so check the CRD in your installed version. - In a
Sequence, the output of one step becomes the input of the next by default. Thedatafield changes that.$requestmeans "send the original client request", and$responsemeans "send the previous step's response", which is the default. - Here the breed model needs the original image payload, not the label from the first model, so the second step uses
data: $request. conditionis a GJSON expression evaluated against the previous step's response. If it does not match, the step is skipped and the graph returns the last response it has. The expression above matches when the first prediction equalsdog. Check the GJSON syntax against your KServe version's documentation, because quoting inside YAML is easy to get wrong.
Deploy and call the graph
kubectl apply -f cat-dog-pipeline.yaml
kubectl get inferencegraph cat-dog-pipelineThe output shows a URL and a READY column. Wait for READY to be True. Then call the graph at its root URL. There is no /v1/models/<name>:predict path, because the graph is not a model.
GRAPH_HOST=$(kubectl get inferencegraph cat-dog-pipeline \
-o jsonpath='{.status.url}' | cut -d/ -f3)
curl -H "Host: ${GRAPH_HOST}" -H "Content-Type: application/json" \
http://${INGRESS_HOST}:${INGRESS_PORT} \
-d @./pet-input.jsonThe request body must be something the first step accepts. The router forwards it to the first service as is, so it should match that service's protocol (V1 or V2).
Splitter: weighted traffic
A Splitter picks one step per request. Weights are percentages and should add up to 100.
apiVersion: serving.kserve.io/v1alpha1
kind: InferenceGraph
metadata:
name: iris-ab-test
spec:
nodes:
root:
routerType: Splitter
steps:
- serviceName: sklearn-iris-a
weight: 80
- serviceName: sklearn-iris-b
weight: 20This differs from the canary rollout covered earlier. A canary splits traffic between two revisions of one InferenceService, and Knative or the deployment controls the split. A splitter splits between separate services, which can use different runtimes or even different model families. Use a canary to roll out a new version of one model. Use a splitter to compare two distinct services.
Ensemble: parallel calls and merged output
An Ensemble sends the same request to every step at once and returns a JSON object with one entry per step.
apiVersion: serving.kserve.io/v1alpha1
kind: InferenceGraph
metadata:
name: iris-ensemble
spec:
nodes:
root:
routerType: Ensemble
steps:
- name: tree
serviceName: iris-tree
- name: logreg
serviceName: iris-logreg
dependency: SoftThe response looks roughly like {"tree": {"predictions": [...]}, "logreg": {"predictions": [...]}}. The graph does not average or vote. It only gathers. If you want a combined answer, add a final step, for example a transformer or a small custom predictor, that takes the merged object and computes it.
The dependency field controls what happens when a step fails. With Soft, the graph still returns whatever the other steps produced. With Hard, the failure fails the whole request. Treat the default as something to verify in your version, and set the field explicitly so the behavior is documented in the manifest.
Combining router types with nodes
Because a step can reference a node with nodeName, you can build trees. This example routes by content, and one branch is itself a sequence.
apiVersion: serving.kserve.io/v1alpha1
kind: InferenceGraph
metadata:
name: routed-pipeline
spec:
nodes:
root:
routerType: Switch
steps:
- nodeName: image-path
condition: "[@this].#(kind==\"image\")"
- serviceName: text-classifier
condition: "[@this].#(kind==\"text\")"
image-path:
routerType: Sequence
steps:
- serviceName: image-preprocessor
- serviceName: image-classifier
data: $responseIn a Switch, the first matching condition wins, so order the steps from most specific to least specific. If nothing matches, the router returns the original request body unchanged, which is easy to mistake for a model answer. Write a final catch-all step if you want a defined fallback.
Gotchas and failure modes
- Payload shape between steps. The router does not translate formats. If step one returns
{"predictions": [...]}and step two expects{"instances": [...]}, step two fails. Fix it with a transformer on the second service, or change the services to share a format. - Latency adds up. Each step in a sequence is a full HTTP round trip plus the model's own time. A three-step sequence has at least three network hops. Ensembles cost only the slowest step, since the calls run in parallel.
- Cold starts multiply. If each service uses scale to zero in Serverless mode, a request to a cold graph can wait for several services to start one after another. Set
minReplicas: 1on the services in latency-sensitive paths. - The router is a workload too. It runs as its own pod or Knative service and needs resources. Under heavy load it can be the bottleneck, so watch its CPU and replica count.
- Failures surface at the router. A service that is not ready, or a wrong
serviceName, shows up as an error from the graph URL. Checkkubectl get inferenceservicefor the referenced services first, thenkubectl describe inferencegraph <name>and the router pod's logs.
Choosing a router type
- Do the models depend on each other's output? Use
Sequence. - Does the request content decide which model runs? Use
Switch. - Do you want several opinions on the same input? Use
Ensemble, and add a combining step. - Do you want to split live traffic between independent services? Use
Splitter.
If a graph grows beyond a few nodes, consider whether that logic belongs in a single custom predictor instead. A graph is best when each stage is already a separately deployed and scaled model. When the stages are tiny Python functions, one predictor avoids the extra network hops.
Exercise
A graph has a Sequence root with two steps. Step one is tokenizer. Step two is classifier, and it needs the original client request, not the tokenizer's output. Which field and value do you set on the second step, and what is the default behavior if you set nothing?
Show answer
Set data: $request on the second step. If you set nothing, the default is $response, so the classifier receives the tokenizer's response as its input.
Exercise
You use a Switch node with two steps, one matching kind==image and one matching kind==text. A client sends a request with kind set to audio. What does the graph return, and how would you make this case explicit?
Show answer
No condition matches, so the router returns the original request body unchanged. To make the case explicit, add a final step with no condition (or a condition that always matches) that points at a fallback service or an error-producing service.