This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 7e10b35aec47 CAMEL-23943: Fix three defects in camel-langchain4j-tools 
producer (#24991)
7e10b35aec47 is described below

commit 7e10b35aec477d0eecda8a754f68437af485e45d
Author: Guillaume Nodet <[email protected]>
AuthorDate: Thu Jul 23 11:34:05 2026 +0200

    CAMEL-23943: Fix three defects in camel-langchain4j-tools producer (#24991)
    
    CAMEL-23943: Fix three defects in camel-langchain4j-tools producer
    
    1. Unbounded tool-calling loop — added maxToolCallingRoundTrips endpoint 
option (default 10)
    2. Crash on hallucinated tool names — graceful error message sent back to 
the LLM
    3. Tool errors swallowed silently — errors now sent back to the LLM as 
ToolExecutionResultMessage
    
    Co-authored-by: Claude Opus 4.6 <[email protected]>
---
 .../catalog/components/langchain4j-tools.json      |   5 +-
 .../tools/LangChain4jToolsEndpointConfigurer.java  |   6 +
 .../tools/LangChain4jToolsEndpointUriFactory.java  |   3 +-
 .../langchain4j/tools/langchain4j-tools.json       |   5 +-
 .../tools/LangChain4jToolsEndpoint.java            |  26 +++
 .../tools/LangChain4jToolsProducer.java            |  49 ++++-
 .../tools/LangChain4jToolDefectsTest.java          | 208 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_22.adoc    |  35 ++++
 .../LangChain4jToolsEndpointBuilderFactory.java    |  38 ++++
 9 files changed, 362 insertions(+), 13 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-tools.json
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-tools.json
index 0477acdec1cc..1197e5ae486a 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-tools.json
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/langchain4j-tools.json
@@ -47,7 +47,8 @@
     "camelToolParameter": { "index": 7, "kind": "parameter", "displayName": 
"Camel Tool Parameter", "group": "consumer (advanced)", "label": 
"consumer,advanced", "required": false, "type": "object", "javaType": 
"org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter", 
"deprecated": false, "deprecationNote": "", "autowired": false, "secret": 
false, "description": "Tool's Camel Parameters, programmatically define Tool 
description and parameters" },
     "exceptionHandler": { "index": 8, "kind": "parameter", "displayName": 
"Exception Handler", "group": "consumer (advanced)", "label": 
"consumer,advanced", "required": false, "type": "object", "javaType": 
"org.apache.camel.spi.ExceptionHandler", "optionalPrefix": "consumer.", 
"deprecated": false, "autowired": false, "secret": false, "description": "To 
let the consumer use a custom ExceptionHandler. Notice if the option 
bridgeErrorHandler is enabled then this option is not in use. By def [...]
     "exchangePattern": { "index": 9, "kind": "parameter", "displayName": 
"Exchange Pattern", "group": "consumer (advanced)", "label": 
"consumer,advanced", "required": false, "type": "enum", "javaType": 
"org.apache.camel.ExchangePattern", "enum": [ "InOnly", "InOut" ], 
"deprecated": false, "autowired": false, "secret": false, "description": "Sets 
the exchange pattern when the consumer creates an exchange." },
-    "lazyStartProducer": { "index": 10, "kind": "parameter", "displayName": 
"Lazy Start Producer", "group": "producer (advanced)", "label": 
"producer,advanced", "required": false, "type": "boolean", "javaType": 
"boolean", "deprecated": false, "autowired": false, "secret": false, 
"defaultValue": false, "description": "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 produ [...]
-    "chatModel": { "index": 11, "kind": "parameter", "displayName": "Chat 
Model", "group": "advanced", "label": "advanced", "required": false, "type": 
"object", "javaType": "dev.langchain4j.model.chat.ChatModel", "deprecated": 
false, "deprecationNote": "", "autowired": true, "secret": false, 
"configurationClass": 
"org.apache.camel.component.langchain4j.tools.LangChain4jToolsConfiguration", 
"configurationField": "configuration", "description": "Chat Model of type 
dev.langchain4j.model.cha [...]
+    "maxToolCallingRoundTrips": { "index": 10, "kind": "parameter", 
"displayName": "Max Tool Calling Round Trips", "group": "producer", "label": 
"producer", "required": false, "type": "integer", "javaType": "int", 
"deprecated": false, "deprecationNote": "", "autowired": false, "secret": 
false, "defaultValue": 10, "description": "Maximum number of tool-calling round 
trips (iterations) allowed before stopping. This prevents infinite loops when 
the LLM keeps requesting tool calls indefinite [...]
+    "lazyStartProducer": { "index": 11, "kind": "parameter", "displayName": 
"Lazy Start Producer", "group": "producer (advanced)", "label": 
"producer,advanced", "required": false, "type": "boolean", "javaType": 
"boolean", "deprecated": false, "autowired": false, "secret": false, 
"defaultValue": false, "description": "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 produ [...]
+    "chatModel": { "index": 12, "kind": "parameter", "displayName": "Chat 
Model", "group": "advanced", "label": "advanced", "required": false, "type": 
"object", "javaType": "dev.langchain4j.model.chat.ChatModel", "deprecated": 
false, "deprecationNote": "", "autowired": true, "secret": false, 
"configurationClass": 
"org.apache.camel.component.langchain4j.tools.LangChain4jToolsConfiguration", 
"configurationField": "configuration", "description": "Chat Model of type 
dev.langchain4j.model.cha [...]
   }
 }
diff --git 
a/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointConfigurer.java
 
b/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointConfigurer.java
index 65185ab644f1..ba46b334ac78 100644
--- 
a/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointConfigurer.java
+++ 
b/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointConfigurer.java
@@ -37,6 +37,8 @@ public class LangChain4jToolsEndpointConfigurer extends 
PropertyConfigurerSuppor
         case "exposed": target.setExposed(property(camelContext, 
boolean.class, value)); return true;
         case "lazystartproducer":
         case "lazyStartProducer": 
target.setLazyStartProducer(property(camelContext, boolean.class, value)); 
return true;
+        case "maxtoolcallingroundtrips":
+        case "maxToolCallingRoundTrips": 
target.setMaxToolCallingRoundTrips(property(camelContext, int.class, value)); 
return true;
         case "name": target.setName(property(camelContext, 
java.lang.String.class, value)); return true;
         case "parameters": target.setParameters(property(camelContext, 
java.util.Map.class, value)); return true;
         case "tags": target.setTags(property(camelContext, 
java.lang.String.class, value)); return true;
@@ -66,6 +68,8 @@ public class LangChain4jToolsEndpointConfigurer extends 
PropertyConfigurerSuppor
         case "exposed": return boolean.class;
         case "lazystartproducer":
         case "lazyStartProducer": return boolean.class;
+        case "maxtoolcallingroundtrips":
+        case "maxToolCallingRoundTrips": return int.class;
         case "name": return java.lang.String.class;
         case "parameters": return java.util.Map.class;
         case "tags": return java.lang.String.class;
@@ -91,6 +95,8 @@ public class LangChain4jToolsEndpointConfigurer extends 
PropertyConfigurerSuppor
         case "exposed": return target.isExposed();
         case "lazystartproducer":
         case "lazyStartProducer": return target.isLazyStartProducer();
+        case "maxtoolcallingroundtrips":
+        case "maxToolCallingRoundTrips": return 
target.getMaxToolCallingRoundTrips();
         case "name": return target.getName();
         case "parameters": return target.getParameters();
         case "tags": return target.getTags();
diff --git 
a/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointUriFactory.java
 
b/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointUriFactory.java
index 4438342fbb65..1d09ac4c5a7d 100644
--- 
a/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointUriFactory.java
+++ 
b/components/camel-ai/camel-langchain4j-tools/src/generated/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpointUriFactory.java
@@ -24,7 +24,7 @@ public class LangChain4jToolsEndpointUriFactory extends 
org.apache.camel.support
     private static final Set<String> ENDPOINT_IDENTITY_PROPERTY_NAMES;
     private static final Map<String, String> MULTI_VALUE_PREFIXES;
     static {
-        Set<String> props = new HashSet<>(12);
+        Set<String> props = new HashSet<>(13);
         props.add("bridgeErrorHandler");
         props.add("camelToolParameter");
         props.add("chatModel");
@@ -33,6 +33,7 @@ public class LangChain4jToolsEndpointUriFactory extends 
org.apache.camel.support
         props.add("exchangePattern");
         props.add("exposed");
         props.add("lazyStartProducer");
+        props.add("maxToolCallingRoundTrips");
         props.add("name");
         props.add("parameters");
         props.add("tags");
diff --git 
a/components/camel-ai/camel-langchain4j-tools/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/tools/langchain4j-tools.json
 
b/components/camel-ai/camel-langchain4j-tools/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/tools/langchain4j-tools.json
index 0477acdec1cc..1197e5ae486a 100644
--- 
a/components/camel-ai/camel-langchain4j-tools/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/tools/langchain4j-tools.json
+++ 
b/components/camel-ai/camel-langchain4j-tools/src/generated/resources/META-INF/org/apache/camel/component/langchain4j/tools/langchain4j-tools.json
@@ -47,7 +47,8 @@
     "camelToolParameter": { "index": 7, "kind": "parameter", "displayName": 
"Camel Tool Parameter", "group": "consumer (advanced)", "label": 
"consumer,advanced", "required": false, "type": "object", "javaType": 
"org.apache.camel.component.langchain4j.tools.spec.CamelSimpleToolParameter", 
"deprecated": false, "deprecationNote": "", "autowired": false, "secret": 
false, "description": "Tool's Camel Parameters, programmatically define Tool 
description and parameters" },
     "exceptionHandler": { "index": 8, "kind": "parameter", "displayName": 
"Exception Handler", "group": "consumer (advanced)", "label": 
"consumer,advanced", "required": false, "type": "object", "javaType": 
"org.apache.camel.spi.ExceptionHandler", "optionalPrefix": "consumer.", 
"deprecated": false, "autowired": false, "secret": false, "description": "To 
let the consumer use a custom ExceptionHandler. Notice if the option 
bridgeErrorHandler is enabled then this option is not in use. By def [...]
     "exchangePattern": { "index": 9, "kind": "parameter", "displayName": 
"Exchange Pattern", "group": "consumer (advanced)", "label": 
"consumer,advanced", "required": false, "type": "enum", "javaType": 
"org.apache.camel.ExchangePattern", "enum": [ "InOnly", "InOut" ], 
"deprecated": false, "autowired": false, "secret": false, "description": "Sets 
the exchange pattern when the consumer creates an exchange." },
-    "lazyStartProducer": { "index": 10, "kind": "parameter", "displayName": 
"Lazy Start Producer", "group": "producer (advanced)", "label": 
"producer,advanced", "required": false, "type": "boolean", "javaType": 
"boolean", "deprecated": false, "autowired": false, "secret": false, 
"defaultValue": false, "description": "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 produ [...]
-    "chatModel": { "index": 11, "kind": "parameter", "displayName": "Chat 
Model", "group": "advanced", "label": "advanced", "required": false, "type": 
"object", "javaType": "dev.langchain4j.model.chat.ChatModel", "deprecated": 
false, "deprecationNote": "", "autowired": true, "secret": false, 
"configurationClass": 
"org.apache.camel.component.langchain4j.tools.LangChain4jToolsConfiguration", 
"configurationField": "configuration", "description": "Chat Model of type 
dev.langchain4j.model.cha [...]
+    "maxToolCallingRoundTrips": { "index": 10, "kind": "parameter", 
"displayName": "Max Tool Calling Round Trips", "group": "producer", "label": 
"producer", "required": false, "type": "integer", "javaType": "int", 
"deprecated": false, "deprecationNote": "", "autowired": false, "secret": 
false, "defaultValue": 10, "description": "Maximum number of tool-calling round 
trips (iterations) allowed before stopping. This prevents infinite loops when 
the LLM keeps requesting tool calls indefinite [...]
+    "lazyStartProducer": { "index": 11, "kind": "parameter", "displayName": 
"Lazy Start Producer", "group": "producer (advanced)", "label": 
"producer,advanced", "required": false, "type": "boolean", "javaType": 
"boolean", "deprecated": false, "autowired": false, "secret": false, 
"defaultValue": false, "description": "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 produ [...]
+    "chatModel": { "index": 12, "kind": "parameter", "displayName": "Chat 
Model", "group": "advanced", "label": "advanced", "required": false, "type": 
"object", "javaType": "dev.langchain4j.model.chat.ChatModel", "deprecated": 
false, "deprecationNote": "", "autowired": true, "secret": false, 
"configurationClass": 
"org.apache.camel.component.langchain4j.tools.LangChain4jToolsConfiguration", 
"configurationField": "configuration", "description": "Chat Model of type 
dev.langchain4j.model.cha [...]
   }
 }
diff --git 
a/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpoint.java
 
b/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpoint.java
index 70e4ba176255..3038384089d5 100644
--- 
a/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpoint.java
+++ 
b/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsEndpoint.java
@@ -94,6 +94,14 @@ public class LangChain4jToolsEndpoint extends 
DefaultEndpoint {
               defaultValue = "true")
     private boolean exposed = true;
 
+    @Metadata(label = "producer")
+    @UriParam(description = "Maximum number of tool-calling round trips 
(iterations) allowed before stopping."
+                            + " This prevents infinite loops when the LLM 
keeps requesting tool calls indefinitely."
+                            + " Each round trip consists of one LLM call and 
the execution of all tools requested in that call."
+                            + " Set to 0 for unlimited (not recommended).",
+              defaultValue = "10")
+    private int maxToolCallingRoundTrips = 10;
+
     // Track the tool specification created by this endpoint for proper cleanup
     private CamelToolSpecification camelToolSpecification;
 
@@ -278,6 +286,24 @@ public class LangChain4jToolsEndpoint extends 
DefaultEndpoint {
         this.exposed = exposed;
     }
 
+    /**
+     * Maximum number of tool-calling round trips allowed
+     *
+     * @return the maximum number of round trips
+     */
+    public int getMaxToolCallingRoundTrips() {
+        return maxToolCallingRoundTrips;
+    }
+
+    public void setMaxToolCallingRoundTrips(int maxToolCallingRoundTrips) {
+        if (maxToolCallingRoundTrips < 0) {
+            throw new IllegalArgumentException(
+                    "maxToolCallingRoundTrips must be >= 0 (0 means unlimited, 
default is 10), got: "
+                                               + maxToolCallingRoundTrips);
+        }
+        this.maxToolCallingRoundTrips = maxToolCallingRoundTrips;
+    }
+
     @Override
     protected void doStop() throws Exception {
         super.doStop();
diff --git 
a/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsProducer.java
 
b/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsProducer.java
index b921fe4c5370..620998c06019 100644
--- 
a/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsProducer.java
+++ 
b/components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolsProducer.java
@@ -20,6 +20,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -44,6 +45,7 @@ import dev.langchain4j.model.output.TokenUsage;
 import org.apache.camel.Exchange;
 import org.apache.camel.InvalidPayloadException;
 import org.apache.camel.Message;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.TypeConverter;
 import 
org.apache.camel.component.langchain4j.tools.spec.CamelToolExecutorCache;
 import 
org.apache.camel.component.langchain4j.tools.spec.CamelToolSpecification;
@@ -130,8 +132,16 @@ public class LangChain4jToolsProducer extends 
DefaultProducer {
         FinishReason lastFinishReason = null;
 
         // First talk to the model to get the tools to be called
+        final int maxRoundTrips = endpoint.getMaxToolCallingRoundTrips();
         int i = 0;
         do {
+            // Guard against unbounded tool-calling loops
+            if (maxRoundTrips > 0 && i >= maxRoundTrips) {
+                throw new RuntimeCamelException(
+                        "Tool-calling loop exceeded maximum round trips (" + 
maxRoundTrips + "). "
+                                                + "Increase the 
maxToolCallingRoundTrips option or investigate why the LLM keeps requesting 
tools.");
+            }
+
             LOG.debug("Starting iteration {}", i);
             final ChatResponse chatResponse = chatWithLLM(chatMessages, 
toolPair, exchange);
 
@@ -213,10 +223,27 @@ public class LangChain4jToolsProducer extends 
DefaultProducer {
                 continue;
             }
 
+            // Find the tool specification — handle hallucinated tool names 
gracefully
             final CamelToolSpecification camelToolSpecification = 
toolPair.callableTools().stream()
-                    .filter(c -> 
c.getToolSpecification().name().equals(toolName)).findFirst().get();
+                    .filter(c -> 
c.getToolSpecification().name().equals(toolName))
+                    .findFirst()
+                    .orElse(null);
+
+            if (camelToolSpecification == null) {
+                LOG.warn("Tool '{}' requested by LLM not found in registered 
tools", toolName);
+                String availableToolNames = toolPair.callableTools().stream()
+                        .map(c -> c.getToolSpecification().name())
+                        .collect(Collectors.joining(", "));
+                chatMessages.add(new ToolExecutionResultMessage(
+                        toolExecutionRequest.id(),
+                        toolExecutionRequest.name(),
+                        "Error: Tool '" + toolName + "' not found. Available 
tools: " + availableToolNames));
+                i++;
+                continue;
+            }
 
             final Exchange toolExchange = ExchangeHelper.createCopy(baseline, 
true);
+            String toolResult;
 
             try {
                 TypeConverter typeConverter = 
endpoint.getCamelContext().getTypeConverter();
@@ -261,20 +288,26 @@ public class LangChain4jToolsProducer extends 
DefaultProducer {
                         });
 
                 // Execute the consumer route
-
                 
camelToolSpecification.getConsumer().getProcessor().process(toolExchange);
-                i++;
+
+                // Check for exception set by the processor (not thrown)
+                if (toolExchange.getException() != null) {
+                    throw toolExchange.getException();
+                }
+
+                ExchangeHelper.copyResults(exchange, toolExchange);
+                toolResult = toolExchange.getIn().getBody(String.class);
             } catch (Exception e) {
-                // How to handle this exception?
-                toolExchange.setException(e);
+                LOG.warn("Error executing tool '{}': {}", toolName, 
e.getMessage(), e);
+                String errorDetail = e.getMessage() != null ? e.getMessage() : 
e.getClass().getName();
+                toolResult = "Error executing tool '" + toolName + "': " + 
errorDetail;
             }
 
-            ExchangeHelper.copyResults(exchange, toolExchange);
-
             chatMessages.add(new ToolExecutionResultMessage(
                     toolExecutionRequest.id(),
                     toolExecutionRequest.name(),
-                    toolExchange.getIn().getBody(String.class)));
+                    toolResult));
+            i++;
         }
 
         // Clear route stop flag after all tools so it does not leak
diff --git 
a/components/camel-ai/camel-langchain4j-tools/src/test/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolDefectsTest.java
 
b/components/camel-ai/camel-langchain4j-tools/src/test/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolDefectsTest.java
new file mode 100644
index 000000000000..3efec31a7c8f
--- /dev/null
+++ 
b/components/camel-ai/camel-langchain4j-tools/src/test/java/org/apache/camel/component/langchain4j/tools/LangChain4jToolDefectsTest.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.langchain4j.tools;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import dev.langchain4j.data.message.ChatMessage;
+import dev.langchain4j.data.message.SystemMessage;
+import dev.langchain4j.data.message.UserMessage;
+import dev.langchain4j.model.chat.ChatModel;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.infra.openai.mock.OpenAIMock;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Tests for the three defects reported in CAMEL-23943:
+ * <ol>
+ * <li>Unbounded tool-calling loop (do/while(true) with no iteration cap)</li>
+ * <li>Crash on hallucinated tool names (.findFirst().get() throws 
NoSuchElementException)</li>
+ * <li>Tool errors swallowed silently</li>
+ * </ol>
+ */
+class LangChain4jToolDefectsTest extends CamelTestSupport {
+
+    protected ChatModel chatModel;
+
+    @RegisterExtension
+    static OpenAIMock openAIMock = new OpenAIMock().builder()
+            // Scenario 1: LLM always requests tools — never stops on its own.
+            // Uses a custom response function that returns a tool call on 
every request,
+            // simulating an LLM stuck in an infinite tool-calling loop.
+            .when("Infinite tool loop\n")
+            .thenRespondWith((exchange, input) -> 
createAlwaysToolCallResponse())
+            .end()
+            // Scenario 2: LLM hallucinates a tool name that doesn't exist
+            .when("Call a tool that does not exist\n")
+            .invokeTool("HallucinatedToolXyz")
+            .withParam("input", "test")
+            .end()
+            // Scenario 3: LLM calls a tool that throws an exception
+            .when("Call the failing tool\n")
+            .invokeTool("FailingTool")
+            .withParam("input", "test")
+            .build();
+
+    /**
+     * Creates a mock OpenAI response that always requests a tool call. Each 
invocation returns unique IDs to simulate a
+     * fresh tool call request from the LLM.
+     */
+    private static String createAlwaysToolCallResponse() {
+        return "{\"id\":\"" + UUID.randomUUID() + "\","
+               + "\"choices\":[{\"finish_reason\":\"tool_calls\",\"index\":0,"
+               + 
"\"message\":{\"role\":\"assistant\",\"refusal\":null,\"content\":null,"
+               + "\"tool_calls\":[{\"id\":\"" + UUID.randomUUID() + 
"\",\"type\":\"function\","
+               + "\"function\":{\"name\":\"RealTool\","
+               + "\"arguments\":\"{\\\"input\\\":\\\"loop\\\"}\"}}]}}],"
+               + 
"\"created\":1234567890,\"model\":\"openai-mock\",\"object\":\"chat.completion\"}";
+    }
+
+    @Override
+    protected void setupResources() throws Exception {
+        super.setupResources();
+        chatModel = ToolsHelper.createModel(openAIMock.getBaseUrl());
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        LangChain4jToolsComponent component
+                = context.getComponent(LangChain4jTools.SCHEME, 
LangChain4jToolsComponent.class);
+        component.getConfiguration().setChatModel(chatModel);
+        return context;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            public void configure() {
+                // Producer with low maxToolCallingRoundTrips for testing the 
iteration cap
+                from("direct:testMaxRoundTrips")
+                        
.to("langchain4j-tools:test1?tags=defect-test&maxToolCallingRoundTrips=2");
+
+                // Producer with default settings for hallucinated tool and 
error tests
+                from("direct:testHallucinatedTool")
+                        .to("langchain4j-tools:test1?tags=defect-test");
+
+                from("direct:testToolError")
+                        .to("langchain4j-tools:test1?tags=defect-test");
+
+                // A real tool that succeeds
+                from("langchain4j-tools:test1?tags=defect-test&name=RealTool"
+                     + "&description=A real tool that 
works&parameter.input=string")
+                        .setBody(simple("{\"result\": \"ok\", \"input\": 
\"${header.input}\"}"));
+
+                // A tool that always throws an exception
+                
from("langchain4j-tools:test1?tags=defect-test&name=FailingTool"
+                     + "&description=A tool that always 
fails&parameter.input=string")
+                        .throwException(new RuntimeException("Tool execution 
failed intentionally"));
+            }
+        };
+    }
+
+    /**
+     * CAMEL-23943 defect 1: The do/while(true) loop in toolsChat has no 
iteration cap. If the LLM keeps requesting
+     * tools indefinitely, this never terminates.
+     *
+     * This test uses a mock that always returns tool calls (never a final 
text response), simulating an LLM stuck in an
+     * infinite loop. Without the fix, this test would hang indefinitely 
(caught by the @Timeout annotation). With the
+     * fix, the loop is bounded by maxToolCallingRoundTrips and throws a 
RuntimeCamelException.
+     */
+    @Test
+    @Timeout(10) // Safety net: without the fix, the infinite loop would hang 
forever
+    void testMaxToolCallingRoundTripsExceeded() {
+        List<ChatMessage> messages = new ArrayList<>();
+        messages.add(new SystemMessage("You are a helpful assistant."));
+        messages.add(new UserMessage("Infinite tool loop\n"));
+
+        Exchange exchange = fluentTemplate.to("direct:testMaxRoundTrips")
+                .withBody(messages).request(Exchange.class);
+
+        assertThat(exchange).isNotNull();
+        assertThat(exchange.getException())
+                .as("Should throw when max round trips exceeded")
+                .isInstanceOf(RuntimeCamelException.class)
+                .hasMessageContaining("maximum round trips (2)");
+    }
+
+    /**
+     * CAMEL-23943 defect 2: When the LLM hallucinates a tool name that 
doesn't exist, .findFirst().get() throws
+     * NoSuchElementException, crashing the producer.
+     *
+     * With the fix, the producer sends an error message back to the LLM 
listing available tools, and the LLM responds
+     * with a final text answer instead of crashing.
+     */
+    @Test
+    void testHallucinatedToolNameHandledGracefully() {
+        List<ChatMessage> messages = new ArrayList<>();
+        messages.add(new SystemMessage("You are a helpful assistant."));
+        messages.add(new UserMessage("Call a tool that does not exist\n"));
+
+        Exchange exchange = fluentTemplate.to("direct:testHallucinatedTool")
+                .withBody(messages).request(Exchange.class);
+
+        assertThat(exchange).isNotNull();
+        // Should NOT have an exception — the error is sent back to the LLM 
gracefully
+        assertThat(exchange.getException())
+                .as("Hallucinated tool should not crash the producer")
+                .isNull();
+        // The LLM should have responded with a final text answer
+        String body = exchange.getMessage().getBody(String.class);
+        assertThat(body)
+                .as("LLM should return a text response after receiving the 
tool error")
+                .isNotNull();
+    }
+
+    /**
+     * CAMEL-23943 defect 3: When a tool route throws an exception, the catch 
block sets toolExchange.setException(e)
+     * but the error is swallowed — it's never propagated back to the LLM and 
subsequent logic overwrites the exchange
+     * state.
+     *
+     * With the fix, the error is sent back to the LLM as a 
ToolExecutionResultMessage, allowing the LLM to handle it
+     * gracefully.
+     */
+    @Test
+    void testToolExecutionErrorPropagatedToLLM() {
+        List<ChatMessage> messages = new ArrayList<>();
+        messages.add(new SystemMessage("You are a helpful assistant."));
+        messages.add(new UserMessage("Call the failing tool\n"));
+
+        Exchange exchange = fluentTemplate.to("direct:testToolError")
+                .withBody(messages).request(Exchange.class);
+
+        assertThat(exchange).isNotNull();
+        // Should NOT have an exception — the tool error is sent back to the 
LLM gracefully
+        assertThat(exchange.getException())
+                .as("Tool error should not crash the producer — it should be 
sent to the LLM")
+                .isNull();
+        // The LLM should have responded with a final text answer after 
receiving the error
+        String body = exchange.getMessage().getBody(String.class);
+        assertThat(body)
+                .as("LLM should return a text response after receiving the 
tool error")
+                .isNotNull();
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
index bc5d20fdbd83..1a8ceba558ae 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
@@ -247,6 +247,41 @@ They were not wired into the component; the `chatModel` is 
autowired instead.
 If you used these helpers directly, configure your `ChatModel` with 
LangChain4j's own builders or Spring Boot starters
 and inject it into the component.
 
+=== camel-langchain4j-tools
+
+==== Tool-calling round trips now bounded by default
+
+The `langchain4j-tools` producer now limits the number of tool-calling round 
trips to 10 by default
+(previously the loop was unbounded and could run indefinitely if the LLM kept 
requesting tools).
+Each round trip consists of one LLM call and the execution of all tools 
requested in that call.
+
+If your LLM interaction legitimately requires more than 10 iterations, 
increase the
+`maxToolCallingRoundTrips` endpoint option. Set to `0` for unlimited (not 
recommended).
+Negative values are rejected with `IllegalArgumentException`.
+
+When the limit is reached, the producer throws a `RuntimeCamelException` with 
a message indicating
+the maximum was exceeded.
+
+==== Hallucinated tool names no longer crash the producer
+
+When the LLM requests a tool name that does not exist among the registered 
tools, the producer
+now sends an error message back to the LLM listing the available tools, giving 
it a chance to
+self-correct. Previously this caused a `NoSuchElementException` crash.
+
+==== Tool execution errors sent to LLM instead of propagating to the route
+
+When a tool route throws an exception, the error is now sent back to the LLM 
as a
+`ToolExecutionResultMessage`, allowing the LLM to handle it gracefully (e.g., 
retry with different
+parameters or answer directly). Previously the exception was set on the tool 
exchange and
+`ExchangeHelper.copyResults` propagated it onto the main exchange, but the 
loop continued anyway,
+leaving the exchange in an inconsistent state.
+
+This is a behavior change: routes that used `onException(...)` to catch tool 
execution failures
+will no longer see those exceptions, since the error is now handled within the 
producer and sent
+back to the LLM. The previous behavior was unreliable — a later successful 
tool call would
+overwrite the exception via `copyResults` — but if you relied on it, be aware 
that tool errors
+are now consumed by the producer.
+
 === camel-langchain4j-web-search
 
 The `safeSearch` endpoint option is now correctly propagated to the 
LangChain4j `WebSearchRequest`.
diff --git 
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jToolsEndpointBuilderFactory.java
 
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jToolsEndpointBuilderFactory.java
index f53dd7e54b32..84c3900047f5 100644
--- 
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jToolsEndpointBuilderFactory.java
+++ 
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jToolsEndpointBuilderFactory.java
@@ -386,6 +386,44 @@ public interface LangChain4jToolsEndpointBuilderFactory {
             doSetProperty("tags", tags);
             return this;
         }
+        /**
+         * Maximum number of tool-calling round trips (iterations) allowed
+         * before stopping. This prevents infinite loops when the LLM keeps
+         * requesting tool calls indefinitely. Each round trip consists of one
+         * LLM call and the execution of all tools requested in that call. Set
+         * to 0 for unlimited (not recommended).
+         * 
+         * The option is a: <code>int</code> type.
+         * 
+         * Default: 10
+         * Group: producer
+         * 
+         * @param maxToolCallingRoundTrips the value to set
+         * @return the dsl builder
+         */
+        default LangChain4jToolsEndpointProducerBuilder 
maxToolCallingRoundTrips(int maxToolCallingRoundTrips) {
+            doSetProperty("maxToolCallingRoundTrips", 
maxToolCallingRoundTrips);
+            return this;
+        }
+        /**
+         * Maximum number of tool-calling round trips (iterations) allowed
+         * before stopping. This prevents infinite loops when the LLM keeps
+         * requesting tool calls indefinitely. Each round trip consists of one
+         * LLM call and the execution of all tools requested in that call. Set
+         * to 0 for unlimited (not recommended).
+         * 
+         * The option will be converted to a <code>int</code> type.
+         * 
+         * Default: 10
+         * Group: producer
+         * 
+         * @param maxToolCallingRoundTrips the value to set
+         * @return the dsl builder
+         */
+        default LangChain4jToolsEndpointProducerBuilder 
maxToolCallingRoundTrips(String maxToolCallingRoundTrips) {
+            doSetProperty("maxToolCallingRoundTrips", 
maxToolCallingRoundTrips);
+            return this;
+        }
     }
 
     /**


Reply via email to