目录
一.为什么要学习这个工具类?
二.使用步骤
1.引入依赖
2.声明接口
3.使用AiServices为接口创建代理对象
方式①:编写配置类
方式②:使用注解
4.在Controller中注入并使用
三.运行项目,测试效果
四.解释一下上面的ConsultantService接口
一.为什么要学习这个工具类?
我们之前学过下图所示的方式,实现在java项目中调用大模型。
但是这种方法有很大缺点,不能实现后续的高阶内容(比如会话记忆等等)。
因此要学习AiServices工具类,才能实现后面的高阶内容。
二.使用步骤
1.引入依赖
<!--AiServices相关的依赖--> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-spring-boot-starter</artifactId> <version>1.0.1-beta6</version> </dependency>2.声明接口
//思考:为什么这个接口叫ConsultantService? //答案:翻译成“咨询顾问接口”,说白了这个接口是负责回答用户提问的问题的 public interface ConsultantService { //用于聊天的方法 public String chat(String message); }3.使用AiServices为接口创建代理对象
方式①:编写配置类
先新建一个配置类
写代码
@Configuration public class CommonConfig { @Autowired private OpenAiChatModel model; @Bean public ConsultantService consultantService(){ ConsultantService consultantService = AiServices.builder(ConsultantService.class) .chatModel(model) .build(); return consultantService; } }方式②:使用注解
由于目前处于学习阶段,所以我们推荐使用手动装配,这样能更清晰自己做了什么。
4.在Controller中注入并使用
@RestController @RequestMapping("/api/chat") public class ChatController { //注入刚才创建的咨询接口 @Autowired private ConsultantService consultantService; @GetMapping("/chat") public String chat(String message){ String result = consultantService.chat(message); return result; } }三.运行项目,测试效果
可见此时运行成功!
四.解释一下上面的ConsultantService接口
@AiService( wiringMode = AiServiceWiringMode.EXPLICIT,//手动装配 chatModel = "openAiChatModel"//指定模型 ) //@AiService //自动装配 public interface ConsultantService { //用于聊天的方法 public String chat(String message); }解释上面的代码:
@AiService 注解:把Java接口变成AI服务
作用:标记接口为AI服务,自动实现AI调用
两个关键参数:
wiringMode = EXPLICIT- 手动配置依赖(避免自动装配混乱)
chatModel = "openAiChatModel"- 指定使用OpenAI模型
效果:接口中的每个方法都变成AI功能调用点
使用示例:
java
@AiService(wiringMode=EXPLICIT, chatModel="openAiChatModel") public interface ConsultantService { String chat(String message); // 直接调用AI聊天 }本质:让调用AI像调用普通Java方法一样简单
以上就是本篇文章的全部内容,喜欢的话可以留个免费的关注呦~~~