SpringBoot?整合?Langchain4j?AIService?深度使用操作實戰(zhàn)教程
一、前言
LangChain4j 是一個基于 Java 的框架,旨在簡化與大型語言模型(LLMs)的集成和應(yīng)用開發(fā)。它提供了豐富的工具和組件,幫助開發(fā)者快速構(gòu)建基于 LLM 的應(yīng)用程序,如聊天機(jī)器人、問答系統(tǒng)、文本生成等。利用LangChain4j ,SpringBoot微服務(wù)應(yīng)用可以快速實現(xiàn)對接市場上各種主流大模型的能力,從而快速驗證業(yè)務(wù)的價值,本文以LangChain4j 中一個非常核心的與大模型交互的組件AIService 為例進(jìn)行詳細(xì)的說明。
市場上主流的 Java 調(diào)用大模型的工具庫有兩種:
- LangChain4j
- Spring AI
LangChain4j 是一個 面向 Java 的開源框架,用于構(gòu)建 基于大語言模型(LLMs) 的應(yīng)用程序。
它是 LangChain(Python 生態(tài)中非常流行的 LLM 應(yīng)用框架)的 Java 實現(xiàn),旨在讓 Java 開發(fā)者能夠輕松地集成和使用各種 LLM 服務(wù),快速開發(fā) 智能聊天機(jī)器人、智能搜索、文檔問答、Agent系統(tǒng) 等 AI 驅(qū)動的應(yīng)用。
官網(wǎng)文檔:https://docs.langchain4j.dev/。
二、AIService 介紹
2.1 AiService 是什么
AiService 是 LangChain4j 中的一個核心組件,用于將 AI 模型(如 OpenAI、通義千問,DeepSeek,Hugging Face 等)的能力封裝為服務(wù)接口,方便開發(fā)者調(diào)用。通過 AiService,開發(fā)者可以輕松地將 AI 模型集成到應(yīng)用程序中,而無需直接處理復(fù)雜的模型調(diào)用和數(shù)據(jù)處理邏輯。

2.2 AiService 主要功能
AiService 主要提供了如下的功能:
- 模型調(diào)用封裝:
- AiService 將 AI 模型的調(diào)用邏輯封裝為簡單的 Java 接口,開發(fā)者只需定義接口方法即可調(diào)用模型。
- 自動請求/響應(yīng)處理:
- AiService 會自動處理輸入數(shù)據(jù)的預(yù)處理和輸出數(shù)據(jù)的后處理,簡化開發(fā)流程。
- 多模型支持:
- 支持多種 AI 模型(如 GPT、BERT 等),并可以根據(jù)需要切換模型。
- 異步調(diào)用:
- 支持異步調(diào)用 AI 模型,提升應(yīng)用程序的性能和響應(yīng)速度。
2.3 AiService 使用步驟
AiService 在實際開發(fā)使用中,遵循下面的幾步即可:
- 定義服務(wù)接口:創(chuàng)建一個 Java 接口,定義需要調(diào)用的 AI 模型功能。
- 配置模型:在配置文件中指定使用的 AI 模型及其參數(shù)。
- 創(chuàng)建服務(wù)實例:通過 AiService 創(chuàng)建服務(wù)實例。
- 調(diào)用服務(wù):通過服務(wù)實例調(diào)用定義的方法,獲取 AI 模型的輸出。
通過 AiService,開發(fā)者可以更高效地將 AI 能力集成到 Java 應(yīng)用程序中,降低開發(fā)復(fù)雜度,提升開發(fā)效率。
三、AIService 操作實踐
3.1 前置準(zhǔn)備
3.1.1 獲取apikey
為了方便與大模型交互,本文案例使用阿里云百煉平臺進(jìn)行對接,所以需要先去百煉大模型平臺獲取apikey,操作入口:大模型服務(wù)平臺百煉控制臺

3.1.2 導(dǎo)入核心依賴
創(chuàng)建一個springboot 工程,并導(dǎo)入下面的核心依賴
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>3.2.6</spring-boot.version>
<langchain4j.version>1.0.0-beta3</langchain4j.version>
<mybatis-plus.version>3.5.11</mybatis-plus.version>
</properties>
<dependencies>
<!-- web應(yīng)用程序核心依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 編寫和運(yùn)行測試用例 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 接入阿里云百煉平臺 -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-dashscope-spring-boot-starter</artifactId>
</dependency>
<!--langchain4j高級功能-->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-starter</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!--引入SpringBoot依賴管理清單-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--引入langchain4j依賴管理清單-->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bom</artifactId>
<version>${langchain4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--引入百煉依賴管理清單-->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-bom</artifactId>
<version>${langchain4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>3.1.3 添加配置文件
在工程的配置文件中添加下面的配置信息
server:
port: 8082
#直接對接的是deepseek官網(wǎng)的的大模型
langchain4j:
#阿里百煉平臺的模型
community:
dashscope:
chat-model:
api-key: 你的apikey #這個是白煉平臺的apikey
model-name: qwen-max
logging:
level:
root: debug3.1.4 前置導(dǎo)入案例
還記得在之前學(xué)習(xí)Langchain4j與大模型整合進(jìn)行對話時,像下面的這樣的接口寫法:
package com.congge.controller;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.output.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
@RestController
@RequestMapping("/qwen")
public class QwenCahtController {
@Autowired
private QwenChatModel qwenChatModel;
//localhost:8082/qwen/chat?question=你是誰
@GetMapping("/chat")
public Object chat(@RequestParam("question") String question){
String chat = qwenChatModel.chat(question);
return chat;
}
}調(diào)用一下接口,可以得到預(yù)期的結(jié)果

盡管大模型給出了回復(fù),但是細(xì)心的同學(xué)會發(fā)現(xiàn),這種方式的實現(xiàn),很明顯在調(diào)用chat方法的時候需要依賴具體的模型提供商,假如說本次使用的是千問大模型,下一次如果更換為openai大模型,再下一次更換為deepseek的話,代碼是不是就需要調(diào)整了,這么來看,使用這種方式是存在一定的局限性的,于是在Langchain4j中,還提供了另一種更為簡單靈活,并且更優(yōu)雅的實現(xiàn)方式,即使用AIService 這個組件。
3.2 AIService 案例操作詳解
官方文檔:AI Services | LangChain4j

3.2.1 入門案例使用
參考官方文檔可以看到,AIService 的使用很簡單。首先需要定義一個接口,里面定義一個chat方法,然后基于AiServices 這個對象創(chuàng)建chat方法所在的接口代理對象,最后就可以調(diào)用這個chat方法與大模型進(jìn)行對話了。
1)定義一個接口
如下,自定義一個接口,里面有一個chat方法
package com.congge.assistant;
public interface Assistant {
String chat(String userMessage);
}2)添加測試接口
添加一個測試接口,從下面這段代碼不難看出,使用這種方式,其核心就是通過AiServices這個對象創(chuàng)建出接口的帶理對象,然后再由帶理對象調(diào)用chat方法,相比傳統(tǒng)的方式,這樣的寫法顯得更加靈活便捷
package com.congge.controller;
import com.congge.assistant.Assistant;
//import com.congge.assistant.QwenAssistant;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/assistant")
public class AssistantController {
@Autowired
private QwenChatModel qwenChatModel;
//localhost:8082/assistant/chat/v1?userMessage=你是誰
@GetMapping("/chat/v1")
public String chat(@RequestParam("userMessage") String userMessage) {
Assistant assistant = AiServices.create(Assistant.class, qwenChatModel);
String chatRes = assistant.chat(userMessage);
return chatRes;
}
}3)接口效果測試
啟動工程后,調(diào)用下接口,可以正常與大模型進(jìn)行對話

3.2.2 簡化寫法
上面這種方式需要通過AiServices對象創(chuàng)建代理對象來調(diào)用,實際上,AiService還提供了更簡單的方式,即只需要在接口上面增加一個 @AiService注解即可 ,這樣就可以直接將接口注入到需要調(diào)用的類中就能使用了,簡單改造下,如下代碼:
1)接口改造
package com.congge.assistant;
import dev.langchain4j.service.spring.AiService;
@AiService
public interface Assistant {
String chat(String userMessage);
}2)測試接口
改為注入Assistant
package com.congge.controller;
import com.congge.assistant.Assistant;
//import com.congge.assistant.QwenAssistant;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/assistant")
public class AssistantController {
@Autowired
private Assistant assistant;
//localhost:8082/assistant/chat/v1?userMessage=你是誰
@GetMapping("/chat/v1")
public String chat(@RequestParam("userMessage") String userMessage) {
//Assistant assistant = AiServices.create(Assistant.class, qwenChatModel);
String chatRes = assistant.chat(userMessage);
return chatRes;
}
}3)效果測試
調(diào)用一下接口,可以看到仍然可以得到預(yù)期的效果

3.2.3 問題說明
基于上面的這一步,細(xì)心的同學(xué)會發(fā)現(xiàn),使用上面帶注解的方式改造后,在測試的接口中并沒有注入具體的ChatModel,最后也能夠正常與大模型對話,這是因為在上面的配置文件中,我們配置的是與百煉的apikey,使用的是千問大模型,所以@AiService 注解就會在上下文環(huán)境中查找并自動注入了千問的ChatModel,在@AiService注解源碼中也可以看到該注解可以接收一個chatModel的屬性

但是假如在你的配置文件中,同時配置了多個大模型廠商的信息,在工程啟動的時候報就會報下面找不到ChatModel的錯誤

遇到這個問題的時候,在控制臺中,錯誤的提示中也給出了解決建議

參照這個提示,接口改造后代碼如下:
package com.congge.assistant;
import dev.langchain4j.service.spring.AiService;
import dev.langchain4j.service.spring.AiServiceWiringMode;
@AiService(wiringMode = AiServiceWiringMode.EXPLICIT, chatModel = "qwenChatModel")
public interface Assistant {
String chat(String userMessage);
}再次啟動的時候,如果保持配置文件不變,仍然配置了多個大模型的信息,此時就不會報錯了。
3.3 AIService 高級用法
3.3.1 @SystemMessage 注解使用
AIService 還可以基于接口中的方法,搭配@SystemMessage 注解使用,通過這個注解,可以賦予接口中的方法更靈活的能力,比如在實際使用中,為了將這個chat方法以更靈活的模板方式進(jìn)行封裝,可以通過傳入更多的參數(shù),然后以參數(shù)的形式傳遞到模板描述中,如下:
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
import dev.langchain4j.service.spring.AiService;
@AiService
public interface Assistant {
//String chat(String userMessage);
@SystemMessage("你是一個知名的散文作家,根據(jù)輸入的{{title}},寫一篇不超過{{count}}字的散文")
String chat(@UserMessage String message, @V("title") String title, @V("count") Long count);
}3.3.2 添加測試接口
增加一個測試接口,可以接收上述新增的方法中的多個參數(shù)
package com.congge.controller;
import com.congge.assistant.Assistant;
//import com.congge.assistant.QwenAssistant;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/assistant")
public class AssistantController {
@Autowired
private Assistant assistant;
//localhost:8082/assistant/chat/v1?userMessage=歌頌祖國的大好河山&title=歌頌祖國的大好河山&count=300
@GetMapping("/chat/v1")
public String chat(
@RequestParam("userMessage") String userMessage,
@RequestParam("title") String title,
@RequestParam("count") Long count) {
String chatRes = assistant.chat(userMessage, title, count);
return chatRes;
}
} 3.3.3 接口效果測試
調(diào)用一下接口,可以看到下面的效果

不難看出,有了@SystemMessage這個注解,在實際的開發(fā)中,讓對接大模型的程序,在設(shè)計上提供了更多的擴(kuò)展性,也讓程序的可定制性增強(qiáng)了,從而讓應(yīng)用更靈活。
3.4 AIService 原理解讀
3.4.1 AIService 核心原理
AiServices會組裝Assistant接口以及其他組件,并使用反射機(jī)制創(chuàng)建一個實現(xiàn)Assistant接口的代理對象。這個代理對象會處理輸入和輸出的所有轉(zhuǎn)換工作。在上面的案例中,chat方法的輸入是一個字符串,但是大模型需要一個 UserMessage 對象。所以,代理對象將這個字符串轉(zhuǎn)換為 UserMessage ,并調(diào)用聊天語言模型。chat方法的輸出類型也是字符串,但是大模型返回的是 AiMessage 對象,代理對象會將其轉(zhuǎn)換為字符串。
3.4.2 AIService 代碼跟蹤
通過上面的代碼演示基本掌握了AIService的用法,下面對其原理做一下詳細(xì)的說明,方便我們對其底層設(shè)計有更深刻的理解,通過 AiServices.create 方法進(jìn)入到下面的源碼中
public static <T> T create(Class<T> aiService, ChatLanguageModel chatLanguageModel) {
return builder(aiService).chatLanguageModel(chatLanguageModel).build();
}啟動工程后,執(zhí)行接口調(diào)用 ,進(jìn)入到下面的 new DefaultAiServices 方法

繼續(xù)往下走,進(jìn)入到下面的方法,在這個方法中可以看到,需要接收aiService 和 chatLanguageModel

這一步創(chuàng)建完成后,代理對象就有了,最后使用assistant調(diào)用chat方法的時候,通過debug源碼可以看到,此時的assistant就是一個代理對象了

四、寫在文末
本文通過較大的篇幅詳細(xì)介紹了Langchain4j中的核心組件AIService的使用,并通過案例演示了其實際的使用過程,希望對看到的同學(xué)有用哦,本篇到此結(jié)束,感謝觀看。
到此這篇關(guān)于SpringBoot 整合 Langchain4j AIService 深度使用操作實戰(zhàn)教程的文章就介紹到這了,更多相關(guān)SpringBoot Langchain4j AIService使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Springboot 后端使用Mockito庫進(jìn)行單元測試流程分析
使用Mock進(jìn)行單元測試可以避免啟動整個Spring框架,節(jié)省時間并降低外部依賴影響,Mock允許模擬外部方法和類,專注于測試方法的功能邏輯,本文給大家介紹Java Springboot 后端使用Mockito庫進(jìn)行單元測試流程分析,感興趣的朋友跟隨小編一起看看吧2024-10-10
基于springcloud異步線程池、高并發(fā)請求feign的解決方案
這篇文章主要介紹了基于springcloud異步線程池、高并發(fā)請求feign的解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
java學(xué)習(xí)之junit單元測試案例(經(jīng)典版)
這篇文章主要介紹了java學(xué)習(xí)之junit單元測試的相關(guān)資料,文中講解了JUnit單元測試的基本概念、作用、使用assert進(jìn)行驗證、覆蓋率分析、BeforeEach和AfterAll的使用、通過反射和注解實現(xiàn)測試,需要的朋友可以參考下2024-12-12
SSH框架網(wǎng)上商城項目第25戰(zhàn)之使用java email給用戶發(fā)送郵件
這篇文章主要為大家詳細(xì)介紹了SSH框架網(wǎng)上商城項目第25戰(zhàn)之使用java email給用戶發(fā)送郵件,感興趣的小伙伴們可以參考一下2016-06-06
Maven中Junit測試@Test等注解無法識別的問題及解決
這篇文章主要介紹了Maven中Junit測試@Test等注解無法識別的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

