? ? ? ?學習基于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.測試結果