Camel Components

TensorFlow Serving

Since Camel 4.10

Only producer is supported

The TensorFlow Serving component provides support for invoking the TensorFlow Serving Client API (gRPC). It enables Camel to access TensorFlow Serving model servers to run inference with TensorFlow saved models remotely.

To use the TensorFlow Serving component, Maven users will need to add the following dependency to their pom.xml:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-tensorflow-serving</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

tensorflow-serving:api[?options]

Where api represents one of the TensorFlow Serving Client API (gPRC). While its RESTful Client API is not directly supported by the component, you can refer to the doc to get an idea of each API that TensorFlow Serving provides.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The TensorFlow Serving component supports the following options which are listed below.

Name Description Default Type

configuration (producer)

The configuration that the endpoints start from. Each endpoint gets a copy of it, and the options of the endpoint replace its values.

TensorFlowServingConfiguration

modelName (common)

The name of the model (servable) to call. The CamelTensorFlowServingModelName header replaces this option, and the model_spec of a request in the body replaces both. The option or the header must be set, even when the request in the body names the model.

String

modelVersion (common)

The version number of the model to use. If no version and no version label is set, the server uses the best available version, typically the latest. The CamelTensorFlowServingModelVersion header replaces this option, and a version label, if one is set, is used instead of it.

Long

modelVersionLabel (common)

The label of the model version to use, as assigned by version_labels in the model server configuration, for example stable or canary. The CamelTensorFlowServingModelVersionLabel header replaces this option. A version label is used instead of a version number.

String

signatureName (common)

The name of the signature (SignatureDef) of the model to evaluate, for classify, regress and predict. If not set, the server uses the default signature, serving_default. The CamelTensorFlowServingSignatureName header replaces this option.

String

target (common)

The target of the gRPC channel to the model server, as host:port or as a gRPC target URI such as dns:///host:8500. The default is the gRPC port of TensorFlow Serving on the local host. The channel is created once, when the endpoint is initialized.

localhost:8500

String

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

credentials (security)

The io.grpc.ChannelCredentials of the gRPC channel, for example a TlsChannelCredentials for TLS, given as a bean reference. If not set, InsecureChannelCredentials is used, and the calls are sent in plaintext.

ChannelCredentials

Endpoint Options

The TensorFlow Serving endpoint is configured using URI syntax:

tensorflow-serving:api

With the following path and query parameters:

Path Parameters

Name Description Default Type

api (producer)

Required The TensorFlow Serving API that the producer calls: model-status (GetModelStatus of the ModelService), or model-metadata (GetModelMetadata), classify, regress or predict of the PredictionService.

Enum values:

  • model-status

  • model-metadata

  • classify

  • regress

  • predict

String

Query Parameters

Name Description Default Type

modelName (common)

The name of the model (servable) to call. The CamelTensorFlowServingModelName header replaces this option, and the model_spec of a request in the body replaces both. The option or the header must be set, even when the request in the body names the model.

String

modelVersion (common)

The version number of the model to use. If no version and no version label is set, the server uses the best available version, typically the latest. The CamelTensorFlowServingModelVersion header replaces this option, and a version label, if one is set, is used instead of it.

Long

modelVersionLabel (common)

The label of the model version to use, as assigned by version_labels in the model server configuration, for example stable or canary. The CamelTensorFlowServingModelVersionLabel header replaces this option. A version label is used instead of a version number.

String

signatureName (common)

The name of the signature (SignatureDef) of the model to evaluate, for classify, regress and predict. If not set, the server uses the default signature, serving_default. The CamelTensorFlowServingSignatureName header replaces this option.

String

target (common)

The target of the gRPC channel to the model server, as host:port or as a gRPC target URI such as dns:///host:8500. The default is the gRPC port of TensorFlow Serving on the local host. The channel is created once, when the endpoint is initialized.

localhost:8500

String

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

credentials (security)

The io.grpc.ChannelCredentials of the gRPC channel, for example a TlsChannelCredentials for TLS, given as a bean reference. If not set, InsecureChannelCredentials is used, and the calls are sent in plaintext.

ChannelCredentials

Message Headers

The TensorFlow Serving component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelTensorFlowServingTarget (producer)

Constant: TARGET

Deprecated The gRPC target of the model server. The component does not read this header. Deprecation note: Never read by the component. The gRPC channel is built once when the endpoint is initialised, so it cannot be redirected per exchange. Use the target endpoint option.

String

CamelTensorFlowServingCredentials (producer)

Constant: CREDENTIALS

Deprecated The credentials of the gRPC channel. The component does not read this header. Deprecation note: Never read by the component. The gRPC channel is built once when the endpoint is initialised, so it cannot be re-authenticated per exchange. Use the credentials endpoint option.

ChannelCredentials

CamelTensorFlowServingModelName (producer)

Constant: MODEL_NAME

The name of the model (servable) to call. It replaces the modelName option, and the model_spec of a request in the body replaces it.

String

CamelTensorFlowServingModelVersion (producer)

Constant: MODEL_VERSION

The version number of the model to use. It replaces the modelVersion option. A version label, if one is set, is used instead of it.

long

CamelTensorFlowServingModelVersionLabel (producer)

Constant: MODEL_VERSION_LABEL

The label of the model version to use, for example stable or canary. It replaces the modelVersionLabel option.

String

CamelTensorFlowServingSignatureName (producer)

Constant: SIGNATURE_NAME

The name of the signature (SignatureDef) of the model to evaluate. It replaces the signatureName option.

String

Message Body

The message body at each side of the TensorFlow Serving component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Producer input

pojo

The protobuf request of the api, or its Builder: a PredictRequest for predict, a ClassificationRequest or RegressionRequest, or the Input of one, for classify and regress. Another body that is not empty, such as text, JSON, bytes or a Map, is not parsed and fails the exchange with an InvalidPayloadException that names the request of the api: build the protobuf request before the endpoint. No body, a blank String or an empty byte array builds the request from the options and headers only, which is all model-status and model-metadata need; they read a GetModelStatusRequest or GetModelMetadataRequest when the body is one, and model-metadata asks for signature_def unless the request names its metadata fields. The model comes from the CamelTensorFlowServingModelName header, or else the modelName option.

  • With api=model-status: null or pojo

  • With api=model-metadata: null or pojo

Producer output

pojo

The protobuf response of the api, such as a PredictResponse with the output tensors by name.

  • With api=model-status: pojo (tensorflow.serving.GetModelStatus$GetModelStatusResponse)

  • With api=model-metadata: pojo (tensorflow.serving.GetModelMetadata$GetModelMetadataResponse)

  • With api=classify: pojo (tensorflow.serving.Classification$ClassificationResponse)

  • With api=regress: pojo (tensorflow.serving.RegressionOuterClass$RegressionResponse)

  • With api=predict: pojo (tensorflow.serving.Predict$PredictResponse)

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

The component supports the following APIs.

tensorflow-serving:<api>[?options]
API Description Options Input (Message Body) Result (Message Body)

model-status

Return the status of a model in the Model server.

modelName
modelVersion
modelVersionLabel

GetModelStatusRequest [1]
(optional)

GetModelStatusResponse [2]

model-metadata

Return the metadata of a model in the Model server.

modelName
modelVersion
modelVersionLabel

GetModelMetadataRequest [3]
(optional)

GetModelMetadataResponse [4]

classify

Run a classification with a model in the Model server.

modelName
modelVersion
modelVersionLabel
signatureName

ClassificationRequest [5]
Input [6]

ClassificationResponse [7]

regress

Run a regression with a model in the Model server.

modelName
modelVersion
modelVersionLabel
signatureName

RegressionRequest [8]
Input [9]

RegressionResponse [10]

predict

Provide generic access to a model in the Model server.

modelName
modelVersion
modelVersionLabel
signatureName

PredictRequest [11]

PredictResponse [12]

The input body is the protobuf request of the API or its Builder, and for classify and regress also an Input or its Builder. The component does not parse any other body that is not empty, such as text, JSON, bytes or a Map: the exchange fails with an InvalidPayloadException that names the request type of the API, so build the protobuf request before the endpoint. Without a body, or with an empty one (a blank String or an empty byte[]), the request is built from the options and headers only, which is all that model-status and model-metadata need.

Examples

Model status API

Check model status
  • Java

  • XML

  • YAML

from("direct:model-status")
    .to("tensorflow-serving:model-status?modelName=half_plus_two&modelVersion=123")
    .log("Status: ${body.getModelVersionStatus(0).state}");
<route>
  <from uri="direct:model-status"/>
  <to uri="tensorflow-serving:model-status?modelName=half_plus_two&amp;modelVersion=123"/>
  <log message="Status: ${body.getModelVersionStatus(0).state}"/>
</route>
- route:
    from:
      uri: direct:model-status
      steps:
        - to:
            uri: tensorflow-serving:model-status
            parameters:
              modelName: half_plus_two
              modelVersion: 123
        - log:
            message: "Status: ${body.getModelVersionStatus(0).state}"
Specify the model name and version with headers
  • Java

  • XML

  • YAML

from("direct:model-status-with-headers")
    .setHeader("CamelTensorFlowServingModelName", constant("half_plus_two"))
    .setHeader("CamelTensorFlowServingModelVersion", constant(123))
    .to("tensorflow-serving:model-status")
    .log("Status: ${body.getModelVersionStatus(0).state}");
<route>
  <from uri="direct:model-status-with-headers"/>
  <setHeader name="CamelTensorFlowServingModelName">
    <constant>half_plus_two</constant>
  </setHeader>
  <setHeader name="CamelTensorFlowServingModelVersion">
    <constant resultType="java.lang.Integer">123</constant>
  </setHeader>
  <to uri="tensorflow-serving:model-status"/>
  <log message="Status: ${body.getModelVersionStatus(0).state}"/>
</route>
- route:
    from:
      uri: direct:model-status-with-headers
      steps:
        - setHeader:
            name: CamelTensorFlowServingModelName
            expression:
              constant:
                expression: half_plus_two
        - setHeader:
            name: CamelTensorFlowServingModelVersion
            expression:
              constant:
                expression: 123
        - to:
            uri: tensorflow-serving:model-status
        - log:
            message: "Status: ${body.getModelVersionStatus(0).state}"

Model Metadata API

Currently, TensorFlow Serving only supports signature_def as the metadata field. See: get_model_metadata.proto

The component asks for signature_def, unless the GetModelMetadataRequest in the body names the metadata fields itself.

Fetch model metadata
  • Java

  • XML

  • YAML

from("direct:model-metadata")
    .to("tensorflow-serving:model-metadata?modelName=half_plus_two&modelVersion=123")
    .log("Metadata: ${body.getMetadataOrThrow('signature_def')}");
<route>
  <from uri="direct:model-metadata"/>
  <to uri="tensorflow-serving:model-metadata?modelName=half_plus_two&amp;modelVersion=123"/>
  <log message="Metadata: ${body.getMetadataOrThrow('signature_def')}"/>
</route>
- route:
    from:
      uri: direct:model-metadata
      steps:
        - to:
            uri: tensorflow-serving:model-metadata
            parameters:
              modelName: half_plus_two
              modelVersion: 123
        - log:
            message: "Metadata: ${body.getMetadataOrThrow('signature_def')}"
Specify the model name and version with headers
  • Java

  • XML

  • YAML

from("direct:model-metadata-with-headers")
    .setHeader("CamelTensorFlowServingModelName", constant("half_plus_two"))
    .setHeader("CamelTensorFlowServingModelVersion", constant(123))
    .to("tensorflow-serving:model-metadata")
    .log("Metadata: ${body.getMetadataOrThrow('signature_def')}");
<route>
  <from uri="direct:model-metadata-with-headers"/>
  <setHeader name="CamelTensorFlowServingModelName">
    <constant>half_plus_two</constant>
  </setHeader>
  <setHeader name="CamelTensorFlowServingModelVersion">
    <constant resultType="java.lang.Integer">123</constant>
  </setHeader>
  <to uri="tensorflow-serving:model-metadata"/>
  <log message="Metadata: ${body.getMetadataOrThrow('signature_def')}"/>
</route>
- route:
    from:
      uri: direct:model-metadata-with-headers
      steps:
        - setHeader:
            name: CamelTensorFlowServingModelName
            expression:
              constant:
                expression: half_plus_two
        - setHeader:
            name: CamelTensorFlowServingModelVersion
            expression:
              constant:
                expression: 123
        - to:
            uri: tensorflow-serving:model-metadata
        - log:
            message: "Metadata: ${body.getMetadataOrThrow('signature_def')}"

Classify API

The signature name should be resolved by looking up the model metadata.

Classify
from("direct:classify")
    .setBody(constant(InputOuterClass.Input.newBuilder()
        .setExampleList(InputOuterClass.ExampleList.newBuilder()
            .addExamples(Example.newBuilder()
                .setFeatures(Features.newBuilder()
                    .putFeature("x", Feature.newBuilder()
                        .setFloatList(FloatList.newBuilder().addValue(1.0f))
                        .build()))))
        .build()))
    .to("tensorflow-serving:classify?modelName=half_plus_two&modelVersion=123&signatureName=classify_x_to_y")
    .log("Result: ${body.result.getClassifications(0).getClasses(0).score}");
Specify the model and signature name with headers
from("direct:classify-with-headers")
    .setBody(constant(InputOuterClass.Input.newBuilder()
        .setExampleList(InputOuterClass.ExampleList.newBuilder()
            .addExamples(Example.newBuilder()
                .setFeatures(Features.newBuilder()
                    .putFeature("x", Feature.newBuilder()
                        .setFloatList(FloatList.newBuilder().addValue(1.0f))
                        .build()))))
        .build()))
    .setHeader("CamelTensorFlowServingModelName", constant("half_plus_two"))
    .setHeader("CamelTensorFlowServingModelVersion", constant(123))
    .setHeader("CamelTensorFlowServingSignatureName", constant("classify_x_to_y"))
    .to("tensorflow-serving:classify")
    .log("Result: ${body.result.getClassifications(0).getClasses(0).score}");

Regress API

The signature name should be resolved by looking up the model metadata.

Regress
from("direct:regress")
    .setBody(constant(InputOuterClass.Input.newBuilder()
        .setExampleList(InputOuterClass.ExampleList.newBuilder()
            .addExamples(Example.newBuilder()
                .setFeatures(Features.newBuilder()
                    .putFeature("x", Feature.newBuilder()
                        .setFloatList(FloatList.newBuilder().addValue(1.0f))
                        .build()))))
        .build()))
    .to("tensorflow-serving:regress?modelName=half_plus_two&modelVersion=123&signatureName=regress_x_to_y")
    .log("Result: ${body.result.getRegressions(0).value}");
Specify the model and signature name with headers
from("direct:regress-with-headers")
    .setBody(constant(InputOuterClass.Input.newBuilder()
        .setExampleList(InputOuterClass.ExampleList.newBuilder()
            .addExamples(Example.newBuilder()
                .setFeatures(Features.newBuilder()
                    .putFeature("x", Feature.newBuilder()
                        .setFloatList(FloatList.newBuilder().addValue(1.0f))
                        .build()))))
        .build()))
    .setHeader("CamelTensorFlowServingModelName", constant("half_plus_two"))
    .setHeader("CamelTensorFlowServingModelVersion", constant(123))
    .setHeader("CamelTensorFlowServingSignatureName", constant("regress_x_to_y"))
    .to("tensorflow-serving:regress")
    .log("Result: ${body.result.getRegressions(0).value}");

Predict API

The labels of inputs (x) and outputs (y) should be resolved by looking up the model metadata.

Predict
from("direct:predict")
    .setBody(constant(Predict.PredictRequest.newBuilder()
        .putInputs("x", TensorProto.newBuilder()
            .setDtype(DataType.DT_FLOAT)
            .setTensorShape(TensorShapeProto.newBuilder()
                .addDim(TensorShapeProto.Dim.newBuilder().setSize(3)))
            .addFloatVal(1.0f)
            .addFloatVal(2.0f)
            .addFloatVal(5.0f)
            .build())
        .build()))
    .to("tensorflow-serving:predict?modelName=half_plus_two&modelVersion=123")
    .log("Result1: ${body.getOutputsOrThrow('y').getFloatVal(0)}")
    .log("Result2: ${body.getOutputsOrThrow('y').getFloatVal(1)}")
    .log("Result3: ${body.getOutputsOrThrow('y').getFloatVal(2)}");
Specify the model name and version with headers
from("direct:predict-with-headers")
    .setBody(constant(Predict.PredictRequest.newBuilder()
        .putInputs("x", TensorProto.newBuilder()
            .setDtype(DataType.DT_FLOAT)
            .setTensorShape(TensorShapeProto.newBuilder()
                .addDim(TensorShapeProto.Dim.newBuilder().setSize(3)))
            .addFloatVal(1.0f)
            .addFloatVal(2.0f)
            .addFloatVal(5.0f)
            .build())
        .build()))
    .setHeader("CamelTensorFlowServingModelName", constant("half_plus_two"))
    .setHeader("CamelTensorFlowServingModelVersion", constant(123))
    .to("tensorflow-serving:predict")
    .log("Result1: ${body.getOutputsOrThrow('y').getFloatVal(0)}")
    .log("Result2: ${body.getOutputsOrThrow('y').getFloatVal(1)}")
    .log("Result3: ${body.getOutputsOrThrow('y').getFloatVal(2)}");

1. tensorflow.serving.GetModelStatus.GetModelStatusRequest
2. tensorflow.serving.GetModelStatus.GetModelStatusResponse
3. tensorflow.serving.GetModelMetadata.GetModelMetadataRequest
4. tensorflow.serving.GetModelMetadata.GetModelMetadataResponse
5. tensorflow.serving.Classification.ClassificationRequest
6. tensorflow.serving.InputOuterClass.Input
7. tensorflow.serving.Classification.ClassificationResponse
8. tensorflow.serving.RegressionOuterClass.RegressionRequest
9. tensorflow.serving.InputOuterClass.Input
10. tensorflow.serving.RegressionOuterClass.RegressionResponse
11. tensorflow.serving.Predict.PredictRequest
12. tensorflow.serving.Predict.PredictResponse