Kotlin+Quarkus中使用@Tool注解构建AI助手时出现构建错误
问题解决方案:Quarkus中@Tool注解不能用于接口方法的问题
问题原因
@Tool注解用于标记供AI代理调用的工具方法,这类方法需要具备可实例化的具体实现,而接口仅定义方法签名无实际实现,因此Quarkus的MCP处理器会拦截这种错误用法。
解决方案
拆分AI服务接口与工具实现,将@Tool注解移至具体类的方法上,让AI服务接口调用该工具类。
步骤1:修改AI服务接口
移除接口方法上的@Tool注解,调整为调用工具类的逻辑:
package prova.langchainkotlin import dev.langchain4j.service.SystemMessage import dev.langchain4j.service.UserMessage import io.quarkiverse.langchain4j.RegisterAiService @RegisterAiService(modelName = "config-assistant") @SystemMessage("You are a basic assistant that helps customers in their daily tasks.") interface ConfigAgent { @UserMessage("Provide some basic information to the customer\nRequest: {request}") fun handleRequest(request: String): String }
步骤2:创建独立工具类
实现具体业务逻辑,用@ApplicationScoped标记为CDI Bean,方法上添加@Tool注解:
package prova.langchainkotlin import dev.langchain4j.agent.tool.Tool import jakarta.enterprise.context.ApplicationScoped @ApplicationScoped class CustomerInfoTool { @Tool("Provide some basic information to the customer based on the request") fun provideInfo(request: String): String { // 这里实现具体的信息返回逻辑 return "Basic information related to your request: $request" } }
步骤3:让AI服务调用工具
修改AI服务接口,通过参数注入工具类并调用其方法(Quarkus LangChain4J会自动处理工具绑定):
package prova.langchainkotlin import dev.langchain4j.service.SystemMessage import dev.langchain4j.service.UserMessage import io.quarkiverse.langchain4j.RegisterAiService @RegisterAiService(modelName = "config-assistant") @SystemMessage("You are a basic assistant that helps customers in their daily tasks. Use the provided tool to get information.") interface ConfigAgent { @UserMessage("Provide some basic information to the customer\nRequest: {request}") fun handleRequest(request: String, tool: CustomerInfoTool): String }
验证配置
确保pom.xml中相关依赖版本兼容,当前使用的quarkus.langchain4j.version=0.27.0.CR2与quarkus.platform.version=3.23.0可正常配合。
内容的提问来源于stack exchange,提问作者Valerio Storch
相关产品推荐
相关产品推荐

