JiriOndrusek opened a new pull request, #31289:
URL: https://github.com/apache/camel/pull/31289

   # Description
   
   Ref CAMEL-27912
   
   This is the first of 3 PRs for CAMEL-27912. It is fully functional on its 
own: any LangChain4j AI service can use route guardrails through the two 
adapters. The agent option and the observability extras follow (see Follow-ups).
   
   ## What this brings
   
   `camel-ai-guardrail`, a consumer-only component: a Camel route becomes a 
LangChain4j input or output guardrail. A guardrail can then check text with 
anything Camel reaches (a moderation API, a rules engine, a PII detector, a 
database lookup) instead of a hand-written Java class. Guardrails are selected 
by tag, the same way `ai-tool` routes are.
   
   The LangChain4j side is two adapters in `camel-langchain4j-core` (package 
`org.apache.camel.component.langchain4j.core.guardrails`): 
`CamelRouteInputGuardrail` and `CamelRouteOutputGuardrail`. They implement 
LangChain4j's `InputGuardrail` / `OutputGuardrail` and run the routes of the 
given tags. Support level: Preview.
   
   ```java
   from("ai-guardrail:pii?type=input&tags=support&order=1")
       .choice()
           .when(body().regex("(?s).*\\b\\d{3}-\\d{2}-\\d{4}\\b.*"))
               .setHeader("CamelAiGuardrailOutcome", constant("failure"))
               .setHeader("CamelAiGuardrailMessage", constant("The prompt 
contains an SSN"))
           .otherwise()
               .setHeader("CamelAiGuardrailOutcome", constant("success"));
   
   // any LangChain4j AI service, e.g. 
AiServices.builder(...).inputGuardrails(guardrail)
   InputGuardrail guardrail = new CamelRouteInputGuardrail(camelContext, 
List.of("support"));
   ```
   
   ## Building blocks
   
   ```mermaid
   flowchart TB
       subgraph G["camel-ai-guardrail"]
           direction TB
           Comp["AiGuardrailComponent"] --> Ep["AiGuardrailEndpoint<br/>name, 
options, tags"]
           Ep --> Cons["AiGuardrailConsumer<br/>registers the route, owns a 
bounded pool"]
           Cons --> Reg["AiGuardrailRegistry<br/>per CamelContext: tag to 
guardrails"]
           Reg --> Spec["AiGuardrailSpec<br/>name, type, order, tags"]
           Exec["AiGuardrailExecutor<br/>runs a chain and one route"] --> Reg
           Exec --> Cons
           Exec --> RR["AiGuardrailRequest / AiGuardrailResult<br/>Success, 
Rewrite, Failure, Fatal"]
       end
       subgraph C["camel-langchain4j-core"]
           In["CamelRouteInputGuardrail"] --> Sup["CamelRouteGuardrailSupport"]
           Out["CamelRouteOutputGuardrail"] --> Sup
       end
       LC["LangChain4j AI service"] --> In
       LC --> Out
       In --> Exec
       Out --> Exec
   ```
   
   ## Technical details
   
   ```
   validate(request)                                
(CamelRouteInput/OutputGuardrail)
      │
      ├─ routes of the tags and type, by order, then name
      │    a tag without a route of this type ──> fatal
      │
      └─ per route (AiGuardrailExecutor)
           ├─ route not running / rejected (concurrency + queueCapacity) ──> 
fatal
           ├─ InOut exchange on the guardrail's own bounded pool
           │    body: the text to check
           │    properties: CamelAiGuardrailType, CamelAiGuardrailName, 
CamelAiGuardrailMemoryId,
           │                CamelAiGuardrailUserMessage (output only), 
CamelAiGuardrailInvocationParameters
           ├─ wait up to timeout (queue time included) ──late──> fatal
           ├─ exception, rollback, exception handled by an error handler ──> 
fatal
           └─ header CamelAiGuardrailOutcome
                success    pass the text on
                rewrite    the body is the new text (no body: fatal)
                failure    collect CamelAiGuardrailMessage, run the other 
guardrails
                fatal      stop at once
                missing    fatal; with implicitSuccess=true success, unless the 
route failed
                           (caught/continued/redelivered exception, 
unsuccessful circuit breaker)
                blank / unknown (also retry, reprompt) ──> fatal
   ```
   
   - **Fails closed.** Every case that is not an explicit outcome fails the 
call: a missing outcome (unless `implicitSuccess=true`), a blank or unknown 
outcome, a route error (also one an error handler marked handled), a 
rollback-only exchange, a timeout, a rejected call, a route that is not 
running, a tag with no route of the call's type.
   - **Chain rules** follow LangChain4j: `failure` collects its message and 
lets the next guardrails run, `fatal` stops at once, `rewrite` hands the new 
text to the next guardrail.
   - **Options.** `type` (`input` / `output`), `tags`, `order` (0), 
`implicitSuccess` (false), `timeout` (30000 ms, or a duration such as `30s`); 
advanced `concurrency` (4) and `queueCapacity` (64). The bounds are enforced by 
the guardrail itself, so they also hold with virtual threads; a timed-out call 
keeps its slot until the route really ends, or while it still waits in the 
queue.
   - **Context.** The memory id, the user message the model answered (output 
only) and the invocation parameters are exchange properties; a route should 
take any identity from the invocation parameters, never from the checked text.
   - **Lifecycle.** A guardrail is registered when its route is created and 
removed when the route is removed or the context stops. While the route is not 
started (also `autoStartup=false`), stopped or suspended, calls fail closed 
(not running). Graceful shutdown lets admitted calls finish; a context stop 
still admits calls from in-flight exchanges, and an aborted route stop leaves 
the guardrail usable.
   
   Documentation: new component page `ai-guardrail` (options, outcomes, 
fail-closed rules, Java and YAML examples, pitfalls).
   
   Tests: `AiGuardrailExecutorTest` (outcomes, fail-closed cases, bounds, 
lifecycle), `AiGuardrailVirtualThreadsTest` (bounds and timeout with virtual 
threads) and `CamelRouteGuardrailTest` (the LangChain4j adapters, chain rules, 
order, rewrite).
   
   The PR has 3 commits to ease the review: the implementation (with the 
component's own generated files), the catalog/DSL files and docs, the tests.
   
   ## Follow-ups
   
   Because of the size, the rest comes in separate PRs:
   1. `langchain4j-agent` option `guardrailTags`: attaches the guardrail routes 
of the tags to an agent (validated at startup).
   2. `AiGuardrailEvent`, JMX counters per outcome, and a shared 
`configuration` bean.
   3. Later, its own Jira: retry and reprompt outcomes.
   
   _Generated with [Claude Code](https://claude.com/claude-code) on behalf of 
@JiriOndrusek_
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to