探索 Spring AI 的 ChatClient API:構建智能對話應用的利器
前言
在當今人工智能蓬勃發展的時代,智能對話系統成為了眾多應用的核心組成部分。無論是客服機器人、智能助手還是聊天應用,都離不開高效、靈活的對話處理能力。Spring AI 作為 Spring 生態系統中專注于人工智能的框架,為開發者提供了強大的工具和功能。其中,ChatClient API 是一個關鍵組件,它提供了與 AI 模型進行通信的流暢接口,支持同步和流式編程模型,極大地簡化了開發智能對話應用的過程。本文將深入探討 Spring AI 的 ChatClient API,介紹其使用方法、特性以及如何利用它構建強大的智能對話應用。
一、ChatClient 的創建
1.1 使用自動配置的 ChatClient.Builder
Spring AI 提供了 Spring Boot 自動配置,可創建一個原型 ChatClient.Builder bean,方便注入到類中。以下是一個簡單的示例:
@RestController
class MyController {private final ChatClient chatClient;public MyController(ChatClient.Builder chatClientBuilder) {this.chatClient = chatClientBuilder.build();}@GetMapping("/ai")String generation(String userInput) {return this.chatClient.prompt().user(userInput).call().content();}
}
在這個示例中,用戶輸入設置用戶消息的內容,call()
方法向 AI 模型發送請求,content()
方法將 AI 模型的響應作為字符串返回。
1.2 以編程方式創建 ChatClient
如果需要禁用自動配置,可以通過設置屬性 spring.ai.chat.client.enabled=false
。然后,根據需要創建 ChatClient.Builder 實例:
ChatModel myChatModel = ... // usually autowiredChatClient.Builder builder = ChatClient.builder(this.myChatModel);// or create a ChatClient with the default builder settings:ChatClient chatClient = ChatClient.create(this.myChatModel);
二、ChatClient Fluent API
ChatClient 的 Fluent API 允許使用重載的 prompt
方法啟動流式 API,支持多種方式構建提示信息:
prompt()
:不帶參數,允許開始構建用戶、系統和提示的其他部分。prompt(Prompt prompt)
:接受 Prompt 參數,允許傳入 Prompt 實例。prompt(String content)
:獲取用戶的文本內容。
三、ChatClient 響應處理
3.1 返回 ChatResponse
AI 模型的響應是一個豐富的結構 ChatResponse
,包含有關響應生成方式的元數據和多個響應。可以通過調用 chatResponse()
方法獲取:
ChatResponse chatResponse = chatClient.prompt().user("Tell me a joke").call().chatResponse();
3.2 返回實體
可以使用 entity()
方法將返回的字符串轉換為實體類。例如,對于 Java 記錄 ActorFilms
:
record ActorFilms(String actor, List<String> movies) {}ActorFilms actorFilms = chatClient.prompt().user("Generate the filmography for a random actor.").call().entity(ActorFilms.class);
還支持泛型列表的轉換:
List<ActorFilms> actorFilms = chatClient.prompt().user("Generate the filmography of 5 movies for Tom Hanks and Bill Murray.").call().entity(new ParameterizedTypeReference<List<ActorFilms>>() {});
3.3 流式響應
使用 stream()
方法可以獲得異步響應:
Flux<String> output = chatClient.prompt().user("Tell me a joke").stream().content();
也可以流式傳輸 ChatResponse
:
Flux<ChatResponse> chatResponse = chatClient.prompt().user("Tell me a joke").stream().chatResponse();
四、使用默認值
在 @Configuration
類中創建 ChatClient
可以簡化運行時代碼,通過設置默認值,避免在每個請求中重復設置系統文本。
4.1 默認系統文本
@Configuration
class Config {@BeanChatClient chatClient(ChatClient.Builder builder) {return builder.defaultSystem("You are a friendly chat bot that answers question in the voice of a Pirate").build();}}@RestController
class AIController {private final ChatClient chatClient;AIController(ChatClient chatClient) {this.chatClient = chatClient;}@GetMapping("/ai/simple")public Map<String, String> completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {return Map.of("completion", this.chatClient.prompt().user(message).call().content());}
}
4.2 帶參數的默認系統文本
@Configuration
class Config {@BeanChatClient chatClient(ChatClient.Builder builder) {return builder.defaultSystem("You are a friendly chat bot that answers question in the voice of a {voice}").build();}}@RestController
class AIController {private final ChatClient chatClient;AIController(ChatClient chatClient) {this.chatClient = chatClient;}@GetMapping("/ai")Map<String, String> completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message, String voice) {return Map.of("completion",this.chatClient.prompt().system(sp -> sp.param("voice", voice)).user(message).call().content());}}
五、顧問(Advisors)
Advisors API 提供了一種靈活而強大的方法來攔截、修改和增強 Spring 應用程序中的 AI 驅動的交互。常見的使用場景是在提示中附加上下文數據,如對話歷史記錄或自定義數據。
5.1 ChatClient 中的 Advisor 配置
ChatClient.builder(chatModel).build().prompt().advisors(new MessageChatMemoryAdvisor(chatMemory),new QuestionAnswerAdvisor(vectorStore)).user(userText).call().content();
在這個配置中,MessageChatMemoryAdvisor
將首先執行,將對話歷史記錄添加到提示符中,然后 QuestionAnswerAdvisor
將根據用戶的問題和添加的對話歷史記錄執行搜索,提供更相關的結果。
5.2 不同類型的 Advisor 實現
MessageChatMemoryAdvisor
:檢索內存并將其作為消息集合添加到提示符中。PromptChatMemoryAdvisor
:檢索內存并將其添加到提示的系統文本中。VectorStoreChatMemoryAdvisor
:允許指定 VectorStore 實例、默認對話 ID、聊天歷史記錄窗口大小和順序。
六、日志記錄
SimpleLoggerAdvisor
是一個用于記錄 ChatClient 請求和響應數據的顧問,可用于調試和監控 AI 交互。要啟用日志記錄,將其添加到顧問鏈中,并設置日志級別為 DEBUG:
ChatResponse response = ChatClient.create(chatModel).prompt().advisors(new SimpleLoggerAdvisor()).user("Tell me a joke?").call().chatResponse();
在 application.properties
或 application.yaml
文件中添加:
logging.level.org.springframework.ai.chat.client.advisor=DEBUG
七、聊天內存(Chat Memory)
ChatMemory
接口表示聊天對話歷史的存儲,提供了添加消息、檢索消息和清除對話歷史的方法。目前有四種實現:InMemoryChatMemory
、CassandraChatMemory
、Neo4jChatMemory
和 JdbcChatMemory
,分別提供了內存存儲、Cassandra 持久化存儲、Neo4j 持久化存儲和 JDBC 持久化存儲。
7.1 CassandraChatMemory
CassandraChatMemory.create(CassandraChatMemoryConfig.builder().withTimeToLive(Duration.ofDays(1)).build());
7.2 Neo4jChatMemory
支持多個配置參數,可通過屬性文件進行配置。
7.3 JdbcChatMemory
JdbcChatMemory.create(JdbcChatMemoryConfig.builder().jdbcTemplate(jdbcTemplate).build());
也可以通過添加依賴進行自動配置:
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-chat-memory-jdbc</artifactId>
</dependency>
總結
Spring AI 的 ChatClient API 為開發者提供了一個強大而靈活的工具,用于構建智能對話應用。通過其流暢的 API、豐富的響應處理方式、默認值設置、顧問機制、日志記錄和聊天內存管理等功能,開發者可以更輕松地實現與 AI 模型的交互,處理復雜的對話場景。無論是創建簡單的聊天機器人還是復雜的智能客服系統,ChatClient API 都能幫助開發者快速搭建高效、智能的對話應用。在使用過程中,開發者需要根據具體需求合理配置和使用各個組件,同時注意日志記錄中的敏感信息處理,確保應用的安全性和可靠性。隨著人工智能技術的不斷發展,Spring AI 的 ChatClient API 也將不斷完善和擴展,為開發者帶來更多的便利和可能性。