【Spring AI Alibaba】接入大模型
目录
一、申请API-KEY
二、引入依赖
三、配置文件
四、使用ChatModel调用大模型
五、使用ChatClient调用大模型
(1)创建ChatClient:
(2)关于ChatClient的响应格式
六、AI响应内容如何返回给前端?
七、最后
大家好,今天带大家来一起使用Spring AI Alibaba来调用一下大模型,实现一个基础的聊天机器人,这次我们因为直接用阿里继承的springAI,所以直接就使用阿里云百炼里面的大模型即可。
官方文档:Spring AI Alibaba 官网_快速构建 JAVA AI 应用
一、申请API-KEY
地址:大模型服务平台百炼控制台
二、引入依赖
<!-- Spring AI Alibaba --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>1.0.0-M6.1</version><exclusions><exclusion><artifactId>logback-adapter</artifactId><groupId>com.alibaba.nacos</groupId></exclusion></exclusions></dependency>
这里排除了logback相关的依赖,防止和web依赖冲突。
三、配置文件
spring:ai:dashscope:chat:options:model: deepseek-r1 #如果想使用千问,改为:qwq-plusapi-key: ${ai.dashscope.api-key}
四、使用ChatModel调用大模型
@Component
public class SpringAiAiInvoke implements CommandLineRunner {@Resourceprivate ChatModel dashscopeChatModel;@Overridepublic void run(String... args) throws Exception {AssistantMessage output = dashscopeChatModel.call(new Prompt("你好,我是千语。你的版本是什么")).getResult().getOutput();System.out.println(output.getText());}
}
代码解释:
途中那段字符串就是用户提问的内容了,可以从前端接收参数,然后再发给大模型
CommandLineRunner这个接口的方法会在Bean被初始化的时候执行,所以这里的run方法只要项目已启动就会被执行,然后就会调用大模型了,然后就可以看到输出结果了。
是的,调用大模型就只需这么简单的四步即可完成。但如果更深入地使用还要进一步学习。
五、使用ChatClient调用大模型
相比于ChatModel,ChatClient翻译过来就是创建一个客户端,使用ChatClient可以更定制化地调用AI。(比如更深入的RAG知识库、advisor顾问等等)
(1)创建ChatClient:
@Component
@Slf4j
public class MyApp {private final ChatClient chatClient;private final String SYSTEM_PROMPT = "这里是系统提示词,你可以给大模型设定一个身份,并且定义大模型的输出风格";public MyApp (ChatModel dashScopeChatModel) {ChatMemory chatMemory = new MySQLBasedChatMemory(conversationMemoryService);//基于MySQL的对话记忆chatClient = ChatClient.builder(dashScopeChatModel).defaultSystem(SYSTEM_PROMPT)//系统提示词.build();}/*** 会话方法** @param message 用户输入的文本* @param charId 会话id,后续可以使用这个id来获取会话的上下文记忆,现在可以不使用* @return 返回给用户的文本*/public String doChat(String message, String charId) {ChatResponse chatResponse = chatClient.prompt().user(message).call()//发送请求.chatResponse();//获取返回结果String respText = chatResponse.getResult().getOutput().getText();log.info(respText);return respText;}}
上面这段代码,用构造函数初始化了ChatClient,在构造函数中,设置的都是对这个大模型的全局设置,比如系统提示词。并且在成员方法中使用它调用了大模型。
虽然在全局设置了系统提示词,但是我们还可以在调用大模型的时候,动态的重置系统提示词:
// 定义默认系统提示词
ChatClient chatClient = ChatClient.builder(chatModel).defaultSystem("You are a friendly chat bot that answers question in the voice of a {voice}").build();// 对话时动态更改系统提示词的变量
chatClient.prompt().system(sp -> sp.param("voice", voice)).user(message).call().content());
(2)关于ChatClient的响应格式
// ChatClient支持多种响应格式
// 1. 返回 ChatResponse 对象(包含元数据如 token 使用量)
ChatResponse chatResponse = chatClient.prompt().user("Tell me a joke").call().chatResponse();// 2. 返回实体对象(自动将 AI 输出映射为 Java 对象)
// 2.1 返回单个实体
record ActorFilms(String actor, List<String> movies) {}
ActorFilms actorFilms = chatClient.prompt().user("Generate the filmography for a random actor.").call().entity(ActorFilms.class);// 2.2 返回泛型集合
List<ActorFilms> multipleActors = chatClient.prompt().user("Generate filmography for Tom Hanks and Bill Murray.").call().entity(new ParameterizedTypeReference<List<ActorFilms>>() {});// 3. 流式返回(适用于打字机效果)
Flux<String> streamResponse = chatClient.prompt().user("Tell me a story").stream().content();// 也可以流式返回ChatResponse
Flux<ChatResponse> streamWithMetadata = chatClient.prompt().user("Tell me a story").stream().chatResponse();
六、AI响应内容如何返回给前端?
请查阅博客:【java】AI内容用SSE流式输出-CSDN博客
七、最后
至此,AI的基本调用问题就完成了,更深入的用法,例如对话记忆、RAG知识库、工具调用、MCP服务等等,请关注后续博客。