Camel Components

TypeSafe AI

Since Camel 4.23

Only producer is supported

The TypeSafe AI component evaluates explicit state against Noul (yes/no), Choice (one category), and Score (ordered rubric) questions using TypeSafe AI’s HTTP API. Jev is the default model; the model option can select another model supported by the API. It calls the service directly using the JDK HTTP client and Camel JSON utilities. For semantic conditions in Java, XML and YAML, use the TypeSafe AI language supplied by this component.

For named Semantic evaluations, add the separate TypeSafe AI Semantic expert (camel-semantic-typesafe-ai). The component and its TypeSafe AI language can be used independently of Semantic.

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-typesafe-ai</artifactId>
    <version>x.x.x</version>
</dependency>

Supported input

State accepts text (String) or structured application state (Map or List) containing JSON values. Binary Java objects and explicit image, audio or video parts are rejected before HTTP, even when nested inside structured state or a question’s instructions or criteria. A media part combines an explicit media discriminator with a payload, such as {type: image_url, image_url: {url: …​}} or {mimeType: audio/wav, data: …​}. Ordinary text and field names do not imply a media modality. The reserved $semanticInput media envelope is rejected, including when nested in application state. Values are neither stringified nor removed to make a request acceptable. Application records such as {type: document, url: …​, source: legal} remain structured data. Generic image, audio, video and binary type labels with ordinary url, source or data fields also remain application state, for example {type: image, url: …​, sku: 42}. A MIME label with a URL alone is metadata; a media or binary MIME label with data or bytes declares a payload. Generic media type labels require media-specific payload fields, bytes, or an explicitly typed source before they are treated as media parts. File and document parts require file-specific payload fields (such as file_data or file_url) or a structured source with an explicit type: base64 and data, or type: url and url.

URI format

typesafe-ai:name[?options]

name identifies an endpoint; it is not sent to the model. Producers and predicates using the same URI share its client and configuration. Each endpoint owns one HTTP client, connection pool, and default executor. Reuse the same endpoint URI when its configuration is shared. Camel manages its lifecycle and cancels in-flight requests on stop. Java 21 and later also close the HTTP client explicitly; on Java 17, the JDK reclaims its remaining resources after it becomes unreachable.

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 TypeSafe AI component supports the following options which are listed below.

Name Description Default Type

apiPath (common)

The path of the decision API, appended to baseUrl; the leading slash is optional. Only a path: no scheme, host, query or fragment. A service at another path must still accept the TypeSafe AI request and return its response format.

/v1/systemone

String

baseUrl (common)

The base URL of the TypeSafe AI API: an http or https URL without user info, query or fragment. apiPath is appended to it, keeping any path the base URL has, for example of a gateway. HTTP redirects are not followed.

https://api.typesafe.ai

String

configuration (producer)

The shared configuration: each endpoint starts from a copy of it, and its endpoint URI options override the copy.

TypeSafeAiConfiguration

maxConcurrentRequests (common)

The maximum number of evaluations that run at the same time on this endpoint, shared by its producers and the typesafe-ai language expressions that use it. A further evaluation fails at once with a RejectedExecutionException; it is not queued and not sent. Must be positive.

64

int

model (common)

The ID or alias of the TypeSafe AI model, sent in each request. A model entry in a request Map given as the message body takes precedence. Use a versioned ID instead of an alias such as jev-latest to keep the decisions stable.

jev-latest

String

questions (common)

The questions as a JSON object: each key is a question name and each value a question object with a type of noul (yes/no), choice or score, optional instructions and the criteria. When set, the producer sends these questions with the state selected by the state option; when neither questions nor questionsResource is set, the message body must be the complete request Map. Validated when the endpoint starts. Cannot be combined with questionsResource.

String

questionsResource (common)

The resource with the questions, in the same JSON format as the questions option, for example classpath:questions.json or file:questions.json (no prefix means the classpath). Read as UTF-8 and validated once when the endpoint starts; at most 4 MB. Cannot be combined with questions.

String

requestTimeout (common)

The timeout in milliseconds for an evaluation: connecting, sending the request and reading the complete response body. On timeout the HTTP request is cancelled and a java.util.concurrent.TimeoutException is thrown. Must be positive.

30000

long

state (common)

A Simple expression that selects the state to evaluate (the message body by default). Used by the producer when questions or questionsResource is set, and by the typesafe-ai language unless it sets its own state. The result must be text, or a Map or a List of JSON values; for bytes or a stream use $\{bodyAs(String)}. Must not be null.

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

resultProperty (producer)

The name of the exchange property to store the response JsonObject in, leaving the message body unchanged. When not set, the response replaces the message body.

String

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

threshold (advanced)

The default threshold of the typesafe-ai language: a predicate matches when the noul probability (of yes) is equal to or greater than this value. Between 0 and 1. Not used by the producer.

0.5

double

uncertainty (advanced)

The default uncertainty band of the typesafe-ai language: a noul probability within threshold minus and plus this value (inclusive) is uncertain and handled by uncertaintyPolicy. 0 turns the band off. threshold minus uncertainty must not be below 0 and threshold plus uncertainty not above 1. Not used by the producer.

0

double

uncertaintyPolicy (advanced)

The default for what the typesafe-ai language does when the noul probability is within the uncertainty band: NonMatch makes the predicate false, Fail throws a TypeSafeAiUncertainResultException. Not used by the producer.

Enum values:

  • NonMatch

  • Fail

NonMatch

UncertaintyPolicy

apiKey (security)

Required The TypeSafe AI API key, sent as a Bearer token in the Authorization header. Only visible ASCII characters are allowed.

String

Endpoint Options

The TypeSafe AI endpoint is configured using URI syntax:

typesafe-ai:name

With the following path and query parameters:

Path Parameters

Name Description Default Type

name (producer)

Required A name that identifies the endpoint; it is not sent to the service. Each endpoint has its own HTTP client and maxConcurrentRequests limit, and the typesafe-ai language uses typesafe-ai:default unless it selects another endpoint.

String

Query Parameters

Name Description Default Type

apiPath (common)

The path of the decision API, appended to baseUrl; the leading slash is optional. Only a path: no scheme, host, query or fragment. A service at another path must still accept the TypeSafe AI request and return its response format.

/v1/systemone

String

baseUrl (common)

The base URL of the TypeSafe AI API: an http or https URL without user info, query or fragment. apiPath is appended to it, keeping any path the base URL has, for example of a gateway. HTTP redirects are not followed.

https://api.typesafe.ai

String

maxConcurrentRequests (common)

The maximum number of evaluations that run at the same time on this endpoint, shared by its producers and the typesafe-ai language expressions that use it. A further evaluation fails at once with a RejectedExecutionException; it is not queued and not sent. Must be positive.

64

int

model (common)

The ID or alias of the TypeSafe AI model, sent in each request. A model entry in a request Map given as the message body takes precedence. Use a versioned ID instead of an alias such as jev-latest to keep the decisions stable.

jev-latest

String

questions (common)

The questions as a JSON object: each key is a question name and each value a question object with a type of noul (yes/no), choice or score, optional instructions and the criteria. When set, the producer sends these questions with the state selected by the state option; when neither questions nor questionsResource is set, the message body must be the complete request Map. Validated when the endpoint starts. Cannot be combined with questionsResource.

String

questionsResource (common)

The resource with the questions, in the same JSON format as the questions option, for example classpath:questions.json or file:questions.json (no prefix means the classpath). Read as UTF-8 and validated once when the endpoint starts; at most 4 MB. Cannot be combined with questions.

String

requestTimeout (common)

The timeout in milliseconds for an evaluation: connecting, sending the request and reading the complete response body. On timeout the HTTP request is cancelled and a java.util.concurrent.TimeoutException is thrown. Must be positive.

30000

long

state (common)

A Simple expression that selects the state to evaluate (the message body by default). Used by the producer when questions or questionsResource is set, and by the typesafe-ai language unless it sets its own state. The result must be text, or a Map or a List of JSON values; for bytes or a stream use $\{bodyAs(String)}. Must not be null.

String

resultProperty (producer)

The name of the exchange property to store the response JsonObject in, leaving the message body unchanged. When not set, the response replaces the message body.

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

threshold (advanced)

The default threshold of the typesafe-ai language: a predicate matches when the noul probability (of yes) is equal to or greater than this value. Between 0 and 1. Not used by the producer.

0.5

double

uncertainty (advanced)

The default uncertainty band of the typesafe-ai language: a noul probability within threshold minus and plus this value (inclusive) is uncertain and handled by uncertaintyPolicy. 0 turns the band off. threshold minus uncertainty must not be below 0 and threshold plus uncertainty not above 1. Not used by the producer.

0

double

uncertaintyPolicy (advanced)

The default for what the typesafe-ai language does when the noul probability is within the uncertainty band: NonMatch makes the predicate false, Fail throws a TypeSafeAiUncertainResultException. Not used by the producer.

Enum values:

  • NonMatch

  • Fail

NonMatch

UncertaintyPolicy

apiKey (security)

Required The TypeSafe AI API key, sent as a Bearer token in the Authorization header. Only visible ASCII characters are allowed.

String

Message Body

The message body at each side of the TypeSafe AI 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

map

The request: a Map with the state and a nonempty questions Map, and optionally the model. JSON text is not parsed: unmarshal it first. With questions or questionsResource, the state option (the body by default) selects the state instead: text, or a Map or a List of JSON values; bytes, a stream or a file fail, select ${bodyAs(String)}.

Not known when questions or questionsResource is set.

Producer output

map (org.apache.camel.util.json.JsonObject), as json

The response: a JsonObject with the model, the answers keyed by question name and the token usage. With resultProperty, the body is unchanged and the response is in that exchange property.

Not known when resultProperty is set.

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.

Configuration

Configure credentials through property placeholders or a supported vault:

camel.component.typesafe-ai.api-key={{env:TYPESAFE_API_KEY}}
camel.component.typesafe-ai.model=jev-1.13.0
camel.component.typesafe-ai.request-timeout=30000
camel.component.typesafe-ai.max-concurrent-requests=64

apiKey is a secret option. baseUrl defaults to https://api.typesafe.ai; the client appends apiPath, which defaults to /v1/systemone. A base path can address a proxy. HTTP redirects are not followed. Use HTTPS for the service; HTTP is useful for local testing.

model defaults to jev-latest. Pin a version when tuning thresholds; aliases can change behavior without a route change. The request map may explicitly override the endpoint’s model for that request. The response’s model identifies the model that answered. See available models.

Custom API path

Set apiPath when a service or gateway exposes the supported TypeSafe AI request and response schema at a different path:

camel.component.typesafe-ai.base-url=http://localhost:8100
camel.component.typesafe-ai.api-path=/v1/decision

The resulting request URL is http://localhost:8100/v1/decision. A path prefix in baseUrl is preserved: http://localhost:8100/gateway/ produces http://localhost:8100/gateway/v1/decision. The leading slash in apiPath is optional. The path must not be blank or include a scheme, authority, query or fragment.

An endpoint can override the component setting with typesafe-ai:refund?apiPath=/v1/decision. The Semantic language’s TypeSafe AI adapter inherits the component setting even when the route contains no typesafe-ai endpoint. Changing the path does not change the required request and response schema.

Concurrent requests

maxConcurrentRequests limits concurrent evaluations to 64 per endpoint by default and must be positive. Producers and predicates using the same endpoint share this limit. A component property sets the default for each endpoint; an endpoint URI can override it, for example typesafe-ai:refund?maxConcurrentRequests=8. Different endpoints have independent limits.

When the limit is reached, the evaluation fails immediately with java.util.concurrent.RejectedExecutionException before request validation, serialization, or HTTP submission. No request is queued. The slot is released when the evaluation finishes, including on failure, timeout, interruption, or cancellation. Camel’s error handler can handle the rejection through onException(RejectedExecutionException.class).

Questions from properties

For a fixed set of questions, select state and retain the business message using properties:

camel.component.typesafe-ai.questions={"refund":{"type":"noul","instructions":"Is a refund requested?"}}
camel.component.typesafe-ai.state=${body}
camel.component.typesafe-ai.result-property=evaluation
  • Java

  • YAML

from("direct:route")
    .to("typesafe-ai:refund")
    .choice()
        .when(simple("${exchangeProperty.evaluation[answers][refund][noul]} >= '0.8'"))
            .to("direct:refund-handler")
        .otherwise().to("direct:general-handler");
- route:
    from:
      uri: direct:route
      steps:
        - to:
            uri: typesafe-ai:refund
        - choice:
            when:
              - expression:
                  simple:
                    expression: "${exchangeProperty.evaluation[answers][refund][noul]} >= '0.8'"
                steps:
                  - to:
                      uri: direct:refund-handler
            otherwise:
              steps:
                - to:
                    uri: direct:general-handler

No manually registered beans are needed. state is a Simple expression, defaulting to ${body}. For an InputStream, use ${bodyAs(String)}. Only the selected state is sent. Without resultProperty, the response replaces the message body. Quote fractional thresholds in Simple predicates as shown, so Camel compares them as decimals instead of first coercing both operands to integers.

Questions from a JSON resource

Use questionsResource when the question set is too large for a property value. It accepts a Camel resource URI, including classpath: and file:, and contains only the named questions. The component reads and validates the UTF-8 JSON once when the endpoint starts. The resource is limited to 4 MB. questions and questionsResource cannot be used together. An invalid or missing resource prevents the endpoint from starting.

{
  "department": {
    "type": "choice",
    "instructions": "Which team should handle this request?",
    "criteria": {
      "billing": "Payments and refunds",
      "technical": "Bugs and outages",
      "sales": "Pricing and new accounts"
    }
  },
  "refund_requested": {
    "type": "noul",
    "instructions": "Does the customer explicitly request a refund?"
  }
}

Put this file at src/main/resources/typesafe/triage-questions.json and configure the endpoint and state through properties:

camel.component.typesafe-ai.questions-resource=classpath:typesafe/triage-questions.json
camel.component.typesafe-ai.state=${body}
camel.component.typesafe-ai.result-property=evaluation
  • Java

  • YAML

from("direct:triage")
    .to("typesafe-ai:triage")
    .choice()
        .when(simple("${exchangeProperty.evaluation[answers][department][choice]} == 'billing'"))
            .to("direct:billing")
        .otherwise().to("direct:other");
- route:
    from:
      uri: direct:triage
      steps:
        - to:
            uri: typesafe-ai:triage
        - choice:
            when:
              - expression:
                  simple:
                    expression: "${exchangeProperty.evaluation[answers][department][choice]} == 'billing'"
                steps:
                  - to:
                      uri: direct:billing
            otherwise:
              steps:
                - to:
                    uri: direct:other

The resource shape is the questions object from the TypeSafe AI System One request; it has no outer state, questions, or model fields. The component validates the question types, criteria and JSON values at startup using the same rules as inline questions. For editor validation, use the Camel-maintained JSON Schema in schema/typesafe-ai-questions.schema.json from this component’s JAR.

Producer request and response

Without configured questions, the input body must be a Map<String, Object> with state and a nonempty questions map. An optional model overrides the endpoint default. Each named question is a map with type (noul, choice, or score), optional instructions, and the applicable criteria. Instructions may be omitted or null. Noul criteria and either yes/no description may also be omitted or null, matching the official Python SDK and OpenAPI schema. State, instructions, and descriptions can be text or structured maps/lists. Nested content supports strings, finite numbers, booleans, nulls, lists, and maps with string keys. Convert other objects explicitly before submitting them. The component does not collect exchange headers or properties automatically. Do not send an entire exchange as state.

The output is an org.apache.camel.util.json.JsonObject, which implements Map<String, Object>. It preserves the API’s JSON structure, including additional fields. Nested objects are maps, arrays are lists, and numeric values implement Number; use doubleValue() or longValue() rather than assuming a specific numeric class.

Missing or mismatched answers, invalid numeric ranges, unknown choices, and incomplete probability maps fail the exchange. The selected Choice must have maximal probability; ties are allowed. Probabilities and scores are preserved as returned. Like the official Python SDK, the component does not enforce a probability-sum tolerance or recompute a Score from its returned probabilities, which may have been rounded independently.

Token counts may be missing or null. Missing values remain absent and null values remain null; neither is replaced with zero. Present counts must be nonnegative integers.

Map<String, Object> request = Map.of(
    "state", "Please refund the duplicate payment",
    "questions", Map.of(
        "refund", Map.of("type", "noul", "instructions", "Is a refund requested?",
            "criteria", Map.of("true", "An explicit request for money back", "false", "No refund requested")),
        "team", Map.of("type", "choice", "instructions", "Which team should handle this?",
            "criteria", Map.of("billing", "Payments and refunds", "technical", "Product failures",
                "other", "Neither team applies")),
        "urgency", Map.of("type", "score", "instructions", "How urgent is this?",
            "criteria", List.of("Routine", "Urgent", "Critical"))));

JsonObject response = template.requestBody("typesafe-ai:decisions", request, JsonObject.class);
JsonObject answers = response.getJsonObject("answers");
boolean requested = answers.getJsonObject("refund").getDouble("noul") >= 0.8;
String category = answers.getJsonObject("team").getString("choice");
double score = answers.getJsonObject("urgency").getDouble("score");

This mixed batch makes one HTTP request, with the same state for every question. There is no implicit batching across producer calls or predicates.

Answer

Mapping

Noul

noul is the probability of yes, in [0,1]. There is no separate confidence value.

Choice

choice, probabilities and confidence. Exactly one supplied category is selected. Criteria may contain up to 255 options; an option’s description may be null.

Score

score is a possibly fractional position in 1 to 10 ordered levels. legend and probabilities are maps keyed by string indices starting at "0"; legend descriptions may be strings, objects, or arrays. confidence describes uncertainty.

Response

model, answers, and usage. The input_tokens and output_tokens counts may be absent or null.

With resultProperty=evaluation, the producer stores the response in that exchange property and preserves the input body. It clears the property before each evaluation so failures cannot leave a stale result. The input request map is not mutated.

For category routing, submit one Choice question and route on its choice field. Independent Noul conditions instead preserve Camel Choice’s first-matching-branch semantics.

Timeouts and errors

Producer and language evaluations are synchronous. Each evaluation blocks the calling thread for a remote round trip and may incur token charges. There is no response cache or automatic retry. Loops and Camel redelivery can evaluate again; bound them and account for repeated calls.

requestTimeout bounds the HTTP request and complete response body. Connection, request and overall deadline failures all surface as java.util.concurrent.TimeoutException; an underlying JDK HTTP timeout is retained as the cause. Interruption and timeout cancel the HTTP future, including stalled response bodies. Cancellation cannot guarantee the service stopped processing or consumed no tokens.

An unsuccessful HTTP status raises TypeSafeAiHttpException with status code, request ID and Retry-After where available. Error bodies are omitted because they may contain submitted state. Invalid responses and network failures propagate. Language evaluations preserve the exception in Camel’s cause chain, so ordinary onException clauses can handle it. Failures never silently become a non-match. Endpoint stop cancels in-flight calls and rejects new evaluations until restart.

Only submit data permitted for the configured service. Test model decisions and thresholds against your application; structured output does not establish correctness.