IT评测·应用市场-qidao123.com技术社区

标题: Spring AI ChatClient [打印本页]

作者: 知者何南    时间: 2025-3-28 08:49
标题: Spring AI ChatClient
Spring AI中的ChatClient是一个提供流畅API(Fluent API)的客户端,它重要用于与各种AI模子进行通讯。ChatClient 提供了与 AI 模子通讯的 Fluent API,它支持同步和反应式(Reactive)编程模子。与 ChatModel、Message、ChatMemory 等原子 API 相比,使用 ChatClient 可以将与 LLM 及其他组件交互的复杂性隐藏在背后,由于基于 LLM 的应用步伐通常要多个组件协同工作(比方,提示词模板、聊天记忆、LLM Model、输出解析器、RAG 组件:嵌入模子和存储),并且通常涉及多个交互,因此和谐它们会让编码变得繁琐。固然使用 ChatModel 等原子 API 可以为应用步伐带来更多的灵活性,成本就是您需要编写大量样板代码。
一、核心功能与特点

二、应用场景

ChatClient可以应用于多种业务场景,包罗但不限于:
三、使用方式

四、源代码解读

ChatClient接口

  1. public interface ChatClient {
  2.         ..... 创建ChatClient方法。
  3.         create
  4.         .....
  5.         ..... 创建Builder方法
  6.         builder
  7.         .....
  8.         .....用于设置聊天请求的规范,如提示信息等。
  9.         ChatClientRequestSpec prompt();
  10.         ChatClientRequestSpec prompt(String content);
  11.         ChatClientRequestSpec prompt(Prompt prompt);
  12.         .....
  13.         .....用于创建新的 Builder  其设置将复制自当前客户端的默认
  14.         Builder mutate();
  15.         .....配置用户提示
  16.         interface PromptUserSpec {......}
  17.         .....
  18.         .....配置系统提示
  19.         interface PromptSystemSpec {......}
  20.         .....
  21.         interface AdvisorSpec {......}
  22.         ......回调的响应规格
  23.         interface CallResponseSpec {......}
  24.         ......
  25.         ......流式响应的规格
  26.         interface StreamResponseSpec {......}
  27.         ......提示响应响应的规格
  28.         interface CallPromptResponseSpec {......}
  29.         ......
  30.         ......流式提示响应响应的规格       
  31.         interface StreamPromptResponseSpec {......}
  32.         ......       
  33.         ......聊天客户端的请求规格
  34.         interface ChatClientRequestSpec {......}
  35.         ......
  36.         ......提供了一种构建 ChatClient 对象的方式,允许设置默认的顾问、选项、用户和系统提示等。
  37.         interface Builder {
  38.                 Builder defaultAdvisors(Advisor... advisor);
  39.                 Builder defaultAdvisors(Consumer<AdvisorSpec> advisorSpecConsumer);
  40.                 Builder defaultAdvisors(List<Advisor> advisors);
  41.                 Builder defaultOptions(ChatOptions chatOptions);
  42.                 Builder defaultUser(String text);
  43.                 Builder defaultUser(Resource text, Charset charset);
  44.                 Builder defaultUser(Resource text);
  45.                 Builder defaultUser(Consumer<PromptUserSpec> userSpecConsumer);
  46.                 Builder defaultSystem(String text);
  47.                 Builder defaultSystem(Resource text, Charset charset);
  48.                 Builder defaultSystem(Resource text);
  49.                 Builder defaultSystem(Consumer<PromptSystemSpec> systemSpecConsumer);
  50.                 /**
  51.                  * @deprecated use {@link #defaultFunctions(FunctionCallback...)} instead.
  52.                  */
  53.                 @Deprecated
  54.                 <I, O> Builder defaultFunction(String name, String description, java.util.function.Function<I, O> function);
  55.                 /**
  56.                  * @deprecated use {@link #defaultFunctions(FunctionCallback...)} instead.
  57.                  */
  58.                 @Deprecated
  59.                 <I, O> Builder defaultFunction(String name, String description,
  60.                                 java.util.function.BiFunction<I, ToolContext, O> function);
  61.                 Builder defaultFunctions(String... functionNames);
  62.                 Builder defaultFunctions(FunctionCallback... functionCallbacks);
  63.                 Builder defaultToolContext(Map<String, Object> toolContext);
  64.                 Builder clone();
  65.                 ChatClient build();
  66.         }
  67. }
复制代码
ChatClient 实现类 DefaultChatClient类
创建

使用 ChatClient.Builder 对象创建 ChatClient 实例,您可以自动注入由Spring Boot 自动配置创建的默认 ChatClient.Builder 实例,您也可以通过编程方式自行创建一个 ChatClient.Builder 实例并用它来得到 ChatClient 实例。
  1.     @RestController
  2.     public class ChatController {
  3.       private final ChatClient chatClient;
  4.       public ChatController(ChatClient.Builder builder) {
  5.         this.chatClient = builder.build();
  6.       }
  7.       @GetMapping("/chat")
  8.       public String chat(String input) {
  9.         return this.chatClient.prompt()
  10.             .user(input)
  11.             .call()
  12.             .content();
  13.       }
  14.     }
复制代码
  在这个示例中,首先设置了用户消息的内容,call 方法向 AI 模子发送哀求,content 方法以字符串情势返回 AI 模子的响应。
  
  1.     ChatModel myChatModel = ... // usually autowired
  2.     ChatClient.Builder builder = ChatClient.builder(myChatModel);
  3.     // or create a ChatClient with the default builder settings:
  4.     ChatClient chatClient = ChatClient.create(myChatModel);
复制代码
ChatClient 响应

  1. public class ChatResponse implements ModelResponse<Generation> {
  2.     private final ChatResponseMetadata chatResponseMetadata;
  3.         private final List<Generation> generations;
  4.         @Override
  5.         public ChatResponseMetadata getMetadata() {...}
  6.     @Override
  7.         public List<Generation> getResults() {...}
  8.     // other methods omitted
  9. }
复制代码
Generation
  1. public class Generation implements ModelResult<AssistantMessage> {
  2.         private final AssistantMessage assistantMessage;
  3.         private ChatGenerationMetadata chatGenerationMetadata;
  4.         @Override
  5.         public AssistantMessage getOutput() {...}
  6.         @Override
  7.         public ChatGenerationMetadata getMetadata() {...}
  8.     // other methods omitted
  9. }
复制代码
下面的代码段表现了通过调用 chatResponse() 返回 ChatResponse 的示例,相比于调用 content() 方法,这里在调用 call() 方法之后调用 chatResponse()。
  1.     ChatResponse chatResponse = chatClient.prompt()
  2.         .user("Tell me a joke")
  3.         .call()
  4.         .chatResponse();
复制代码
  1.   ActorFilms aFilms = chatClient.prompt()
  2.         .user("Generate the filmography for a random actor.")
  3.         .call()
  4.         .entity(ActorFilms.class);
复制代码
entity 还有一种带有参数的重载方法 entity(ParameterizedTypeReference<T> type),可让您指定如泛型 List 等类型:
  1.     List<ActorFilms> aFilms = chatClient.prompt()
  2.         .user("Generate the filmography of 5 movies for Tom Hanks and Bill Murray.")
  3.         .call()
  4.         .entity(new ParameterizedTypeReference<List<ActorFilms>>() {
  5.         });
复制代码
  1.     Flux<String> oput = chatClient.prompt()
  2.         .user("Tell me a joke")
  3.         .stream()
  4.         .content();
复制代码
还可以使用 Flux<ChatResponse> chatResponse() 方法得到 ChatResponse 响应数据流。
   call 返回值
ChatClient.call() 方法支持几种差别类型的响应格式。
  
    stream() 返回值
还可以调用该stream方法而call不是,在指定stream方法后ChatClient,响应类型有几个选项:
  
  示例代码:

由ChatClient.Builder创建
  1. @RestController
  2. public class MyController {
  3.     private final ChatClient chatClient;
  4.     // 通过构造函数注入ChatClient的Bean
  5.     public MyController(ChatClient.Builder chatClientBuilder) {
  6.         this.chatClient = chatClientBuilder.build();
  7.     }
  8.     @GetMapping("/ai")
  9.     public String generateResponse(String userInput) {
  10.         // 设置请求参数并发起请求
  11.         ChatResponse chatResponse = chatClient.prompt()
  12.                 .user(userInput) // 设置用户输入
  13.                 .call() // 向AI模型发送请求
  14.                 .chatResponse(); // 获取包含元数据的ChatResponse对象
  15.         // 处理响应结果(这里只是简单地返回响应内容)
  16.         return chatResponse.getContent();
  17.     }
  18. }
复制代码
ChatClient 默认值

使用 ChatClient.Builder.build() 快速创建了一个 ChatClient 实例,开发者还可以通过修改 ChatClient.Builder 定制 ChatClient 实例。
   注意,创建 ChatClient 时指定的配置将作为与模子交互时的默认参数,如许可以避免每次调用都重复设置。
  
  1.        @Configuration
  2.     class Config {
  3.         @Bean
  4.         ChatClient chatClient(ChatClient.Builder builder) {
  5.             return builder.defaultSystem("You are a friendly chat bot that answers question in the voice of a {voice}")
  6.                     .build();
  7.         }
  8.     }
  9.     @RestController
  10.     class AIController {
  11.       private final ChatClient chatClient
  12.       AIController(ChatClient chatClient) {
  13.         this.chatClient = chatClient;
  14.       }
  15.       @GetMapping("/ai")
  16.       Map<String, String> completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message, String voice) {
  17.         return Map.of(
  18.             "completion",
  19.             chatClient.prompt()
  20.                 .system(sp -> sp.param("voice", voice))
  21.                 .user(message)
  22.                 .call()
  23.                 .content());
  24.       }
  25.     }
复制代码
启动示例,通过 curl 测试效果:
  1. > curl http localhost:8080/ai?voice=='Robert DeNiro'
  2.     {
  3.         "completion": "You talkin' to me? Okay, here's a joke for ya: Why couldn't the bicycle stand up by itself? Because it was two tired! Classic, right?"
  4.     }
复制代码
Advisors

使用上下文数据附加或扩充 Prompt,最终使用扩充后的 Prompt 与模子交互。
扩充 Prompt 的上下文数据可以是差别类型的,常见类型包罗:
- 自己的数据:这是 AI 模子尚未训练过的数据,如特定领域知识、产物文档等,即使模子已经看到过类似的数据,附加的上下文数据也会优老师成响应。
- 对话历史记载:聊天模子的 API 是无状态的,如果告诉 AI 模子您的姓名,它不会在后续交互中记住它,每次哀求都必须发送对话历史记载,以确保在生成响应时思量到先前的交互。
检索增强生成(RAG)

向量数据库存储的是 AI 模子不知道的数据,当用户题目被发送到 AI 模子时,会在向量数据库中查询与用户题目相关的文档。
来自向量数据库的响应被附加到用户消息 Prompt 中,为 AI 模子生成响应提供上下文。
假设已将数据加载到中 VectorStore,则可以通过向 ChatClient 提供 QuestionAnswerAdvisor 实例来执行检索增强生成 (RAG ) 。
  1.     ChatResponse response = ChatClient.builder(chatModel)
  2.             .build().prompt()
  3.             .advisors(new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults()))
  4.             .user(userText)
  5.             .call()
  6.             .chatResponse();
复制代码
在此示例,SearchRequest.defaults() 将对 Vector 向量数据库中的所有文档执行相似性搜索。为了限定要搜索的文档类型。
记忆

ChatMemory 接口表示聊天对话历史记载存储,提供向对话添加消息、从对话中检索消息以及扫除对话历史记载的方法。
目条件供两种实现方式 InMemoryChatMemoryCassandraChatMemory,分别为聊天对话历史记载提供内存存储time-to-live 类型的恒久存储。
创建一个包含 time-to-live 配置的 CassandraChatMemory
  1. CassandraChatMemory.create(CassandraChatMemoryConfig.builder().withTimeToLive(Duration.ofDays(1)).build());
复制代码
以下 Advisor 实现使用 ChatMemory 接口来使用对话历史记载来增强(advice)Prompt,这些 advisor 实现在怎样将对话历史记载添加到 Prompt 的细节上有所差别。

下面的 @Service 提供了一个使用多个 Advisor 的示例实现:
  1.     import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
  2.     import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;
  3.     @Service
  4.     public class CustomerSupportAssistant {
  5.         private final ChatClient chatClient;
  6.         public CustomerSupportAssistant(ChatClient.Builder builder, VectorStore vectorStore, ChatMemory chatMemory) {
  7.         this.chatClient = builder
  8.                 .defaultSystem("""
  9.                         You are a customer chat support agent of an airline named "Funnair".", Respond in a friendly,
  10.                         helpful, and joyful manner.
  11.                         If there is a charge for the change, you MUST ask the user to consent before proceeding.
  12.                         """)
  13.                 .defaultAdvisors(
  14.                         new PromptChatMemoryAdvisor(chatMemory),
  15.                         // new MessageChatMemoryAdvisor(chatMemory), // CHAT MEMORY
  16.                         new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults()),
  17.                         new LoggingAdvisor()) // RAG
  18.                 .defaultFunctions("getBookingDetails", "changeBooking", "cancelBooking") // FUNCTION CALLING
  19.                 .build();
  20.     }
  21.     public Flux<String> chat(String chatId, String userMessageContent) {
  22.         return this.chatClient.prompt()
  23.                 .user(userMessageContent)
  24.                 .advisors(a -> a
  25.                         .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
  26.                         .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100))
  27.                 .stream().content();
  28.         }
  29.     }
复制代码
日记记载

SimpleLoggerAdvisor 是一个用于记载 ChatClient 的 request 和 response 数据 Advisor,这对于调试和监控 AI 交互非常有效。
要启用日记记载,请在创建 ChatClient 时将 SimpleLoggerAdvisor 添加到 Advisor 链中。建议将其添加到链的末尾:
  1.     ChatResponse response = ChatClient.create(chatModel).prompt()
  2.             .advisors(new SimpleLoggerAdvisor())
  3.             .user("Tell me a joke")
  4.             .call()
  5.             .chatResponse();
复制代码
要查察日记,请将 Advisor 包的日记记载级别设置为 DEBUG:
  1. org.springframework.ai.chat.client.advisor=DEBUG
复制代码
将其添加到 application.properties 或 application.yaml 文件中。
可以使用以下构造函数自界说怎样使用 SimpleLoggerAdvisor 记载来自 AdvisedRequest 和 ChatResponse 的数据:
  1.     SimpleLoggerAdvisor(
  2.         Function<AdvisedRequest, String> requestToString,
  3.         Function<ChatResponse, String> responseToString
  4.     )
复制代码
使用示例:
  1.     javaCopySimpleLoggerAdvisor customLogger = new SimpleLoggerAdvisor(
  2.         request -> "Custom request: " + request.userText,
  3.         response -> "Custom response: " + response.getResult()
  4.     );
复制代码
参考项目

紫汐AI
   综上所述,Spring AI的ChatClient是一个功能强大且灵活的客户端工具,它可以或许帮助开发者轻松地与各种AI模子进行通讯,并实现丰富的交互功能。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4