This is an automated email from the ASF dual-hosted git repository. JiriOndrusek pushed a commit to branch 3.40.x in repository https://gitbox.apache.org/repos/asf/camel-quarkus.git
commit af07ad5722ecadb998a22baf9b351780723e6896 Author: Jiří Ondrušek <[email protected]> AuthorDate: Mon Nov 23 10:57:46 2026 +0100 Fixes #9544. ai-tool: resolve @CamelAiTools tag from the AI service request The tag was passed through a ThreadLocal set by a CDI interceptor. A Multi AI service called on the event loop provides its tools on a worker thread, after the ThreadLocal was cleared, so it got all tools. Look the tag up from the request's invocation context interface name instead and drop the interceptor. Co-authored-by: jiriOndrusek-agent <[email protected]> Co-authored-by: Claude Sonnet 5.5 <[email protected]> (cherry picked from commit 54422e26d8dab4565e27185ff5dd6b6dad123246) --- .../ai/tool/deployment/AiToolProcessor.java | 7 --- .../component/ai/tool/CamelAiToolProvider.java | 20 ++---- .../quarkus/component/ai/tool/CamelAiTools.java | 5 -- .../component/ai/tool/CamelAiToolsInterceptor.java | 73 ---------------------- .../langchain4j/it/AiToolLangchain4jResource.java | 26 ++++++++ .../it/model/ToolNamesStreamingChatModel.java | 48 ++++++++++++++ .../it/model/WrongTagToolCallingChatModel.java | 2 +- .../it/service/WeatherStreamingAiService.java | 32 ++++++++++ .../it/AiToolLangchain4jOllamaTest.java | 4 +- .../tool/langchain4j/it/AiToolLangchain4jTest.java | 20 +++++- 10 files changed, 132 insertions(+), 105 deletions(-) diff --git a/extensions/ai-tool/deployment/src/main/java/org/apache/camel/quarkus/component/ai/tool/deployment/AiToolProcessor.java b/extensions/ai-tool/deployment/src/main/java/org/apache/camel/quarkus/component/ai/tool/deployment/AiToolProcessor.java index 579ebab368b..0a1be3231d9 100644 --- a/extensions/ai-tool/deployment/src/main/java/org/apache/camel/quarkus/component/ai/tool/deployment/AiToolProcessor.java +++ b/extensions/ai-tool/deployment/src/main/java/org/apache/camel/quarkus/component/ai/tool/deployment/AiToolProcessor.java @@ -33,7 +33,6 @@ import io.quarkus.runtime.configuration.ConfigurationException; import org.apache.camel.quarkus.component.ai.tool.AiToolRecorder; import org.apache.camel.quarkus.component.ai.tool.AiToolSpecConverterImpl; import org.apache.camel.quarkus.component.ai.tool.CamelAiToolProvider; -import org.apache.camel.quarkus.component.ai.tool.CamelAiToolsInterceptor; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.DotName; @@ -116,7 +115,6 @@ class AiToolProcessor { @Record(ExecutionTime.STATIC_INIT) void configureCamelAiToolTags( CombinedIndexBuildItem combinedIndex, - BuildProducer<AdditionalBeanBuildItem> additionalBeans, AiToolRecorder recorder) { IndexView index = combinedIndex.getIndex(); @@ -139,10 +137,5 @@ class AiToolProcessor { } recorder.setCamelAiToolTagMap(tagMap); - - additionalBeans.produce(AdditionalBeanBuildItem.builder() - .addBeanClasses(CamelAiToolsInterceptor.class) - .setUnremovable() - .build()); } } diff --git a/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolProvider.java b/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolProvider.java index b21f27a699b..9fa08dfb481 100644 --- a/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolProvider.java +++ b/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolProvider.java @@ -48,8 +48,6 @@ public class CamelAiToolProvider implements ToolProvider { private static final Logger LOG = Logger.getLogger(CamelAiToolProvider.class); static final Map<String, String> TAG_MAP = new ConcurrentHashMap<>(); - // Set by CamelAiToolsInterceptor before each AI service call so provideTools() can filter by the calling service's tag - private static final ThreadLocal<String> CURRENT_TAG = new ThreadLocal<>(); private static final Set<String> CAMEL_AGENT_SERVICE_INTERFACES = Set.of( "org.apache.camel.component.langchain4j.agent.api.AiAgentWithMemoryService", "org.apache.camel.component.langchain4j.agent.api.AiAgentWithoutMemoryService"); @@ -63,18 +61,6 @@ public class CamelAiToolProvider implements ToolProvider { @Inject AiToolSpecConverter converter; - static String getCurrentTag() { - return CURRENT_TAG.get(); - } - - static void setCurrentTag(String tag) { - CURRENT_TAG.set(tag); - } - - static void clearCurrentTag() { - CURRENT_TAG.remove(); - } - @Override public ToolProviderResult provideTools(ToolProviderRequest request) { if (isCamelAgentRequest(request)) { @@ -86,7 +72,11 @@ public class CamelAiToolProvider implements ToolProvider { } AiToolRegistry registry = AiToolRegistry.getOrCreate(camelContext); - String effectiveTag = CURRENT_TAG.get(); + // Resolved from the request, not from the calling thread: Multi-returning AI services called on the event + // loop provide their tools on a worker thread + String effectiveTag = request.invocationContext() != null + ? TAG_MAP.get(request.invocationContext().interfaceName()) + : null; Set<AiToolSpec> tools = effectiveTag != null ? registry.getToolsByTag(effectiveTag) : registry.getAllTools(); ToolProviderResult.Builder resultBuilder = ToolProviderResult.builder(); diff --git a/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiTools.java b/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiTools.java index 0e2efde5ffb..0cfff9ad8cf 100644 --- a/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiTools.java +++ b/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiTools.java @@ -22,9 +22,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import jakarta.enterprise.util.Nonbinding; -import jakarta.interceptor.InterceptorBinding; - /** * Filters the Camel AI tools exposed to a {@code @RegisterAiService} by tag. When placed on a * {@code @RegisterAiService} interface, only {@code ai-tool:} routes whose {@code tags} parameter includes the @@ -38,11 +35,9 @@ import jakarta.interceptor.InterceptorBinding; * } * </pre> */ -@InterceptorBinding @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface CamelAiTools { - @Nonbinding String value() default ""; } diff --git a/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolsInterceptor.java b/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolsInterceptor.java deleted file mode 100644 index 8ccd7ec0ffa..00000000000 --- a/extensions/ai-tool/runtime/src/main/java/org/apache/camel/quarkus/component/ai/tool/CamelAiToolsInterceptor.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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.quarkus.component.ai.tool; - -import jakarta.annotation.Priority; -import jakarta.interceptor.AroundInvoke; -import jakarta.interceptor.Interceptor; -import jakarta.interceptor.InvocationContext; - -/** - * CDI interceptor that sets the current Camel AI tool tag on a ThreadLocal before an AI service method executes. - * This allows {@link CamelAiToolProvider#provideTools} to filter tools by the tag associated with the calling AI - * service, - * enabling multiple {@code @RegisterAiService} interfaces with different {@code @CamelAiTools} tags in the same - * application. - */ -@Interceptor -@CamelAiTools -@Priority(Interceptor.Priority.LIBRARY_BEFORE + 100) -public class CamelAiToolsInterceptor { - - @AroundInvoke - Object aroundInvoke(InvocationContext ctx) throws Exception { - Class<?> targetClass = ctx.getTarget().getClass(); - String tag = resolveTag(targetClass); - String previous = CamelAiToolProvider.getCurrentTag(); - if (tag != null) { - CamelAiToolProvider.setCurrentTag(tag); - } - try { - return ctx.proceed(); - } finally { - if (previous != null) { - CamelAiToolProvider.setCurrentTag(previous); - } else { - CamelAiToolProvider.clearCurrentTag(); - } - } - } - - private String resolveTag(Class<?> targetClass) { - // Walk the full class hierarchy: ArC creates $$QuarkusImpl_Subclass extending $$QuarkusImpl, - // and the @CamelAiTools interface is declared on $$QuarkusImpl (not the subclass), so we - // must check superclasses and all their interfaces. - for (Class<?> clazz = targetClass; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { - String tag = CamelAiToolProvider.TAG_MAP.get(clazz.getName()); - if (tag != null) { - return tag; - } - for (Class<?> iface : clazz.getInterfaces()) { - tag = CamelAiToolProvider.TAG_MAP.get(iface.getName()); - if (tag != null) { - return tag; - } - } - } - return null; - } -} diff --git a/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jResource.java b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jResource.java index b7243e6036e..9a76852ddd6 100644 --- a/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jResource.java +++ b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jResource.java @@ -19,6 +19,9 @@ package org.apache.camel.quarkus.component.ai.tool.langchain4j.it; import java.util.Set; import java.util.stream.Collectors; +import io.smallrye.common.annotation.Blocking; +import io.smallrye.common.annotation.NonBlocking; +import io.smallrye.mutiny.Uni; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -35,6 +38,7 @@ import org.apache.camel.quarkus.component.ai.tool.langchain4j.it.service.AdminAi import org.apache.camel.quarkus.component.ai.tool.langchain4j.it.service.AllToolsAiService; import org.apache.camel.quarkus.component.ai.tool.langchain4j.it.service.WeatherAiService; import org.apache.camel.quarkus.component.ai.tool.langchain4j.it.service.WeatherAiServiceWrongTag; +import org.apache.camel.quarkus.component.ai.tool.langchain4j.it.service.WeatherStreamingAiService; @Path("/ai-tool-langchain4j") @ApplicationScoped @@ -55,6 +59,9 @@ public class AiToolLangchain4jResource { @Inject AllToolsAiService allToolsAiService; + @Inject + WeatherStreamingAiService weatherStreamingAiService; + @Path("/weather/chat") @POST @Consumes(MediaType.TEXT_PLAIN) @@ -87,6 +94,25 @@ public class AiToolLangchain4jResource { return allToolsAiService.chat(message); } + // Runs on the event loop, so quarkus-langchain4j resolves the tools of the Multi on a worker thread + @Path("/weather-streaming/non-blocking/chat") + @POST + @NonBlocking + @Consumes(MediaType.TEXT_PLAIN) + @Produces(MediaType.TEXT_PLAIN) + public Uni<String> weatherStreamingChatNonBlocking(String message) { + return weatherStreamingAiService.chat(message).collect().with(Collectors.joining()); + } + + @Path("/weather-streaming/blocking/chat") + @POST + @Blocking + @Consumes(MediaType.TEXT_PLAIN) + @Produces(MediaType.TEXT_PLAIN) + public Uni<String> weatherStreamingChatBlocking(String message) { + return weatherStreamingAiService.chat(message).collect().with(Collectors.joining()); + } + @Path("/tools/{tag}") @GET @Produces(MediaType.TEXT_PLAIN) diff --git a/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/ToolNamesStreamingChatModel.java b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/ToolNamesStreamingChatModel.java new file mode 100644 index 00000000000..6b6779d943e --- /dev/null +++ b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/ToolNamesStreamingChatModel.java @@ -0,0 +1,48 @@ +/* + * 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.quarkus.component.ai.tool.langchain4j.it.model; + +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import dev.langchain4j.agent.tool.ToolSpecification; +import dev.langchain4j.data.message.AiMessage; +import dev.langchain4j.model.chat.StreamingChatModel; +import dev.langchain4j.model.chat.request.ChatRequest; +import dev.langchain4j.model.chat.response.ChatResponse; +import dev.langchain4j.model.chat.response.StreamingChatResponseHandler; + +/** + * Streaming model that answers with the sorted, comma separated names of the tools it was offered. + */ +public class ToolNamesStreamingChatModel implements Supplier<StreamingChatModel> { + + @Override + public StreamingChatModel get() { + return new StreamingChatModel() { + @Override + public void doChat(ChatRequest chatRequest, StreamingChatResponseHandler handler) { + String toolNames = chatRequest.toolSpecifications().stream() + .map(ToolSpecification::name) + .sorted() + .collect(Collectors.joining(",")); + handler.onPartialResponse(toolNames); + handler.onCompleteResponse(ChatResponse.builder().aiMessage(AiMessage.from(toolNames)).build()); + } + }; + } +} diff --git a/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/WrongTagToolCallingChatModel.java b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/WrongTagToolCallingChatModel.java index 1a565161bda..64a6bdccdc3 100644 --- a/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/WrongTagToolCallingChatModel.java +++ b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/model/WrongTagToolCallingChatModel.java @@ -31,7 +31,7 @@ import dev.langchain4j.model.chat.response.ChatResponse; /** * Mock model for testing tag isolation. Calls {@code getWeather} only if it appears in the - * available tool specifications — when the interceptor works correctly and this service is + * available tool specifications — when the tag filter works correctly and this service is * tagged with {@code adminTag}, the weather tool should NOT be visible. */ public class WrongTagToolCallingChatModel implements Supplier<ChatModel> { diff --git a/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/service/WeatherStreamingAiService.java b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/service/WeatherStreamingAiService.java new file mode 100644 index 00000000000..b4987fba54a --- /dev/null +++ b/integration-tests/ai-tool-langchain4j/src/main/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/service/WeatherStreamingAiService.java @@ -0,0 +1,32 @@ +/* + * 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.quarkus.component.ai.tool.langchain4j.it.service; + +import dev.langchain4j.service.UserMessage; +import io.quarkiverse.langchain4j.RegisterAiService; +import io.smallrye.mutiny.Multi; +import jakarta.enterprise.context.ApplicationScoped; +import org.apache.camel.quarkus.component.ai.tool.CamelAiTools; +import org.apache.camel.quarkus.component.ai.tool.langchain4j.it.model.ToolNamesStreamingChatModel; + +@ApplicationScoped +@RegisterAiService(streamingChatLanguageModelSupplier = ToolNamesStreamingChatModel.class) +@CamelAiTools("weatherTag") +public interface WeatherStreamingAiService { + + Multi<String> chat(@UserMessage String message); +} diff --git a/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jOllamaTest.java b/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jOllamaTest.java index 5ed5e8bd299..e49b5ded468 100644 --- a/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jOllamaTest.java +++ b/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jOllamaTest.java @@ -44,9 +44,9 @@ class AiToolLangchain4jOllamaTest { .body(containsString("1111")); } - // Verifies that the @CamelAiTools interceptor filters tools by tag: a service tagged "adminTag" + // Verifies that @CamelAiTools filters tools by tag: a service tagged "adminTag" // should not see the getWeather tool (tagged "weatherTag"), so the real LLM won't call it - // and "1111" won't appear in the response. Fails if the interceptor is broken and all tools are visible. + // and "1111" won't appear in the response. Fails if the tag filter is broken and all tools are visible. @Test void weatherWithWrongTag() { RestAssured.given() diff --git a/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jTest.java b/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jTest.java index 6369ee30fdd..07b34317d10 100644 --- a/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jTest.java +++ b/integration-tests/ai-tool-langchain4j/src/test/java/org/apache/camel/quarkus/component/ai/tool/langchain4j/it/AiToolLangchain4jTest.java @@ -20,6 +20,8 @@ import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; @@ -83,9 +85,9 @@ class AiToolLangchain4jTest { .body(containsString("news")); } - // Verifies that the @CamelAiTools interceptor filters tools by tag: a service tagged "adminTag" + // Verifies that @CamelAiTools filters tools by tag: a service tagged "adminTag" // should not see the getWeather tool (tagged "weatherTag"), so the mock model won't call it - // and "1111" won't appear in the response. Fails if the interceptor is broken and all tools are visible. + // and "1111" won't appear in the response. Fails if the tag filter is broken and all tools are visible. @Test void weatherWithWrongTagTest() { RestAssured.given() @@ -126,4 +128,18 @@ class AiToolLangchain4jTest { .statusCode(200); } + // The streaming model answers with the names of the tools it was offered: only the tagged tool is expected, + // also when the Multi service is called on the event loop + @ParameterizedTest + @ValueSource(strings = { "non-blocking", "blocking" }) + void weatherStreamingServiceGetsOnlyTaggedTools(String mode) { + RestAssured.given() + .contentType("text/plain") + .body("What is the weather in Prague?") + .post("/ai-tool-langchain4j/weather-streaming/" + mode + "/chat") + .then() + .statusCode(200) + .body(is("getWeather")); + } + }
