创建一个SpringBoot工程

选择这两个依赖:

在src/main/resources/application.yml中配置信息(将application.properties改为application.yml):

spring:
  application:
    name: spring-ai-helloworld
  ai:
    openai:
      base-url: https://dashscope.aliyuncs.com/compatible-mode
      api-key: sk-b90ad31bb3eb***928356d39dc5
      chat:
        options:
          model: qwen-plus-latest
          temperature: 0.7
          max-tokens: 1024

api-key获取方式:

百炼控制台:https://bailian.console.aliyun.com/?tab=model#/api-key

在pom.xml中引入lombok依赖:

<dependency>

    <groupId>org.projectlombok</groupId>

    <artifactId>lombok</artifactId>

    <version>1.18.22</version>

</dependency>

创建两个类:ChatController和CommonConfiguration

结构如图:

效果演示:

在浏览器中输入:http://localhost:8080/ai/chat?prompt=你是谁?

具体代码:

package cn.xumistore.ai.config;


import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 码农编程进阶笔记
 * @description: TODO
 * @date 2025/5/12 11:27
 */

@Configuration
publicclassCommonConfiguration {
    @Bean
    public ChatClient chatClient(OpenAiChatModel model) {
        return ChatClient
                .builder(model)
                .build();
    }
}
/**
 * @author 码农编程进阶笔记
 * @description: TODO
 * @date 2025/5/12 11:29
 */

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
publicclassChatController {

    privatefinal ChatClient chatClient;


    @RequestMapping("/chat")
    public String chat(String prompt){


        return chatClient.prompt()
                .user(prompt)
                .call()
                .content();
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐