springai第二个例子使用配置类配置chatclient

package com.haojg.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ChatModelConfig {

    @Bean
    public ChatClient chatClient(ChatModel chatModel) {
        return ChatClient.builder(chatModel)
                .build();
    }

}
package com.haojg.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class ChatController {

    @Autowired
    private ChatClient chatClient;

    // 第1种方式通过ChatClient.Builder创建
//    public ChatController(ChatClient.Builder builder) {
//        this.chatClient=builder.build();
//    }
    // 第2种通过ChatModel创建
//    public ChatController(ChatModel chatModel) {
//        this.chatClient = ChatClient.builder(chatModel).build();
//        this.chatClient = ChatClient.create(chatModel);
//    }
    // 第3种通过ChatModel创建
//    public ChatController(ChatModel chatModel) {
//        this.chatClient = ChatClient.create(chatModel);
//    }

    @GetMapping(value = "/chat", produces = "text/plain")
    public String chat(String message) {
        String content = chatClient.prompt(message).call().content();
        log.info("message={}, content:{}", message, content);
        return content;
    }

}

 

posted on 2026-01-09 19:41  zhaofeng555  阅读(3)  评论(0)    收藏  举报