学习基于Langchain4j的大模型开发需要学习其中Ai Service的开发模式。里面对大模型做了一层封装,提供一些可以方便调用的api。其中有两种使用Ai Service的方式。
一.编程式开发
1.首先引入Langchain4的依赖。
<dependency><groupId>dev.langchain4j</groupId><artifactId>langchain4j</artifactId><version>1.1.0</version></dependency>
2.基于编程式开发构建Ai Service服务接口
通过@SystemMessage("你好,我是编程领域的小助手,有什么问题我可以帮你解答吗? ")定义系统提示词。
package com.example.aicode.ai;import dev.langchain4j.service.SystemMessage;/*** @author zhou* @version 1.0* @description TODO* @date 2025/9/16 21:45*/
public interface AiCodeService {@SystemMessage("你好,我是编程领域的小助手,有什么问题我可以帮你解答吗? ")String chat(String userMessage);
}
其中系统提示词也可以通过文件配置,特别是提示词比较长的时候。
package com.example.aicode.ai;import dev.langchain4j.service.SystemMessage;/*** @author zhou* @version 1.0* @description TODO* @date 2025/9/16 21:45*/
public interface AiCodeService {@SystemMessage(fromResource = "system-prompt.txt")String chat(String userMessage);
}
3.通过工厂模式创建AiCodeService。
需要提供第二步写的接口以及模型对象。这样AiService可以帮我们构造一个AiCodeService服务,相当于为接口创建了代理实现对象。
package com.example.aicode.ai;import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author zhou* @version 1.0* @description TODO* @date 2025/9/16 22:08*/
@Configuration
public class AiCodeServiceFactory {@Resourceprivate ChatModel qwenModel;@Beanpublic AiCodeService aiCodeService(){return AiServices.create(AiCodeService.class,qwenModel);}
}
其中AiService使用了创建者模式帮我们的接口创建实现类对象(底层使用了反射调用)。
4.创建测试类
package com.example.aicode.ai;import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class AiCodeServiceTest {@Resourceprivate AiCodeService aiCodeService;@Testvoid chat() {String chat = aiCodeService.chat("你好,我是一名程序员");System.out.println(chat);}
}
5.测试结果
二.基于注解
1.引入依赖
<dependency><groupId>dev.langchain4j</groupId><artifactId>langchain4j-community-dashscope-spring-boot-starter</artifactId><version>1.1.0-beta7</version></dependency>
2.直接在类上加注解
package com.example.aicode.ai;import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.spring.AiService;/*** @author zhou* @version 1.0* @description TODO* @date 2025/9/16 21:45*/
@AiService
public interface AiCodeService {@SystemMessage(fromResource = "system-prompt.txt")String chat(String userMessage);
}
不用创建工厂类,但是这种方式不太灵活。
3.测试结果