AI Guardrail
Since Camel 4.25
Only consumer is supported
The AI Guardrail component makes a Camel route a guardrail: it checks the user text before it reaches an AI model (type=input), or the answer of the model (type=output). Guardrails are attached by tag, like AI Tool routes.
The outcomes and the chain rules are those of LangChain4j, and the routes run as LangChain4j InputGuardrail and OutputGuardrail. Use a route for what a guardrail class cannot do, such as asking a moderation service.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-ai-guardrail</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
ai-guardrail:name?type=input|output&tags=tag1,tag2[&order=10][&implicitSuccess=true][&timeout=30000]
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,*.yamlfiles, 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 AI Guardrail component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
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 |
Endpoint Options
The AI Guardrail endpoint is configured using URI syntax:
ai-guardrail:name
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
When true, a route that ends without the CamelAiGuardrailOutcome header passes the text, unless the route failed (an exception it handled, a recovered redelivery, an unsuccessful circuit breaker). By default the outcome is required and a route without one rejects the text (fatal). | false | boolean | |
The guardrails of a tag run by ascending order, then by name. | 0 | int | |
Required Comma-separated tags. CamelRouteInputGuardrail and CamelRouteOutputGuardrail of camel-langchain4j-core run the guardrails of their tags. | String | ||
How long a call waits for the route, time in the queue included, in milliseconds or as a duration such as 30s. A timeout rejects the text (fatal). | 30000 | long | |
Required What the guardrail checks: input (the user text, before the model) or output (the answer of the model). Enum values:
| AiGuardrailType | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Number of calls the route runs in parallel. | 4 | int | |
Number of calls that may wait for a free thread. Beyond it a call is rejected (fatal). | 64 | int |
Message Headers
The AI Guardrail component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelAiGuardrailOutcome (consumer) Constant: | The outcome the guardrail route returns: success, rewrite, failure or fatal. Required: absent is fatal, unless the endpoint sets implicitSuccess=true (then absent means success, unless the route failed). A blank or unknown value is always fatal. The body is the new text only with rewrite, and is ignored otherwise. A failure lets the other guardrails of the chain run; fatal stops the chain. | String | |
CamelAiGuardrailMessage (consumer) Constant: | The message of a failure or fatal outcome. The messages of all failures of a chain are joined by '; '. | String |
Message Body
The message body at each side of the AI Guardrail 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 |
|---|---|---|
Consumer |
| The text to check: the user text (input) or the answer of the model (output). The context of the call is in exchange properties. |
Consumer reply |
| The new text, converted to a String, when the route sets the outcome header to rewrite (no body is fatal then). Ignored with any other outcome. |
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
A guardrail route gets the text to check as the body: the user text (input) or the answer of the model (output). The context is in exchange properties: CamelAiGuardrailType, CamelAiGuardrailName, CamelAiGuardrailMemoryId, CamelAiGuardrailUserMessage (output only) and CamelAiGuardrailInvocationParameters. The route returns its verdict in the CamelAiGuardrailOutcome header (trimmed, case-insensitive):
| Outcome | Result |
|---|---|
| the text passes unchanged |
| the body replaces the text (the body is the new text only with |
| the text is rejected with |
| the text is rejected with |
The guardrails of the tags of a call run by ascending order, then by name. A rewrite passes the new text to the next guardrail, the failure messages are joined by `; `.
-
Java
-
YAML
from("ai-guardrail:moderation?type=input&tags=support")
.to("http:moderation-service/check")
.choice()
.when(jsonpath("$.flagged").isEqualTo(false))
.setHeader("CamelAiGuardrailOutcome", constant("success"))
.otherwise()
.setHeader("CamelAiGuardrailOutcome", constant("failure"))
.setHeader("CamelAiGuardrailMessage", constant("Rejected by moderation"))
.end(); - from:
uri: ai-guardrail:no-ssn
parameters:
type: input
tags: support
order: 10
steps:
- choice:
when:
- simple: "${body} regex '(?s).*\\b\\d{3}-\\d{2}-\\d{4}\\b.*'"
steps:
- setHeader:
name: CamelAiGuardrailOutcome
constant: failure
- setHeader:
name: CamelAiGuardrailMessage
constant: SSN is not allowed
otherwise:
steps:
- setHeader:
name: CamelAiGuardrailOutcome
constant: success Fail closed
These reject the text (fatal):
-
no outcome, unless
implicitSuccess=true; -
a blank,
nullor unknown outcome (retryandrepromptare not supported yet); -
rewritewithout a body; -
a route exception, or a timeout (
timeout, default 30 seconds, as millis or a duration such as10s, time in the queue included); -
an exception handled by the error handler (
onExceptionwithhandled(true), dead letter channel), whatever the outcome; -
an exchange marked rollback only, whatever the outcome;
-
with
implicitSuccess=trueand no outcome: an exception the route continued or caught (doCatch), a failure a redelivery recovered, or a circuit breaker call that did not succeed; -
a call rejected because the route is saturated (
concurrencyrunning,queueCapacitywaiting). A call that timed out keeps its place until the route really ends, or while it still waits in the queue, also with virtual threads; -
a route not started (also
autoStartup=false), stopped or suspended, until it starts; -
a tag of the call with no route of the type of the call.
A graceful stop of a route lets the calls already admitted finish; a new call meanwhile is fatal. If the stop times out and is aborted, the route keeps running and accepts calls again. A graceful stop of the context also admits new calls until the route is stopped, so the exchanges still in flight can complete. The message of a fatal names the guardrail, never the exception text, and the component never logs the checked text. The LangChain4j adapters log the cause of a fatal at DEBUG, and an exception text may quote the checked text: keep DEBUG off for org.apache.camel.component.langchain4j.core.guardrails where that matters.
Using the guardrails with LangChain4j
CamelRouteInputGuardrail and CamelRouteOutputGuardrail of camel-langchain4j-core run the routes of their tags. camel-ai-guardrail is an optional dependency of camel-langchain4j-core: add it next to it.
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.inputGuardrails(new CamelRouteInputGuardrail(camelContext, List.of("support")))
.outputGuardrails(new CamelRouteOutputGuardrail(camelContext, List.of("support")))
.build(); A rejected text ends the call with the LangChain4j InputGuardrailException or OutputGuardrailException, whose message carries CamelAiGuardrailMessage. Never put the checked text in it.
The routes check text only, and fail closed otherwise (fatal): a user message that is not a single text (for example text and an image, such as a multimodal prompt of the langchain4j-agent component), and an answer of the model without text (only tool calls).
Pitfalls
The component cannot detect these, and the text passes:
-
an HTTP call with
throwExceptionOnFailure=false: an error response is a normal message; -
a
successset unconditionally, or before a step whose failure adoCatchcatches: set the outcome last; -
a fallback,
doCatchorcontinued(true)that returns a valid-looking default with an explicit outcome; -
a masking route ordered before a blocking route hides the text from the blocker: give the blocker the lower
order.