ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

Spring AI (1) : 快速构建智能应用

Spring AI (1) : 快速构建智能应用 目录一、为什么选择 Spring AI二、环境准备三、基础配置3.1 网络代理配置3.2 API Key 配置四、核心功能实现4.1 基础文本对话4.2 流式输出4.3 图像生成4.4 语音能力4.5 多模态识别五、Function Calling让 AI 调用外部能力5.1 工作流程5.2 代码实现5.3 核心原理六、国产模型集成方案6.1 阿里云通义千问七、总结一、为什么选择 Spring AI在 Java 生态中接入大语言模型目前主要有两条路径Spring AI 和 LangChain4j。实际建议如果团队已有 Spring Boot 技术栈优先选 Spring AI。若需要构建一个高度定制化的多模型网关层LangChain4j 更合适。二、环境准备dependencyManagementdependenciesdependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-bom/artifactIdversion1.0.0-SNAPSHOT/versiontypepom/typescopeimport/scope/dependency/dependencies/dependencyManagementdependencies!--Spring Web--dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency!--Spring AI OpenAI Starter--dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-openai-spring-boot-starter/artifactId /dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependency/dependencies三、基础配置3.1 网络代理配置如果使用的是海外模型 API需要通过代理访问SpringBootApplicationpublicclassAiApplication{publicstaticvoidmain(String[]args){// 根据实际代理地址和端口配置System.setProperty(proxyHost,127.0.0.1);System.setProperty(proxyPort,7890);System.setProperty(proxySet,true);SpringApplication.run(AiApplication.class,args);}}3.2 API Key 配置ai:aicore:key:${OPEN_AI_KEY}url:${OPEN_AI_URL}spring:ai:openai:api-key:${ai.aicore.key}base-url:${ai.aicore.url}四、核心功能实现4.1 基础文本对话RestControllerRequestMapping(/api/ai)RequiredArgsConstructorpublicclassAiController{privatefinalChatClientchatClient;GetMapping(/chat)publicMapString,Stringchat(RequestParam(defaultValue讲个笑话)Stringmessage){StringresponsechatClient.prompt().user(message).call().content();returnMap.of(result,response);}}4.2 流式输出适用于需要逐字展示回答的场景提升用户体验GetMapping(value/stream,producestext/sse;charsetUTF-8)publicFluxStringstreamChat(RequestParam(defaultValue讲个笑话)Stringmessage){returnchatClient.prompt().user(message).stream().content();}前端通过 EventSource 即可接收 SSE 流式数据。// 1. 创建 EventSource 实例指向后端的流式接口// 注意这里可以带上查询参数对应后端的 RequestParamconsteventSourcenewEventSource(/stream?message讲个笑话);// 2. 监听消息事件 (对应后端每次推送的文本)eventSource.onmessagefunction(event){// event.data 就是后端推送过来的一段文本内容console.log(收到流式数据:,event.data);// 在实际业务中你可以把 event.data 追加到网页的聊天框里实现逐字显示的效果// document.getElementById(chatBox).innerHTML event.data;};// 3. 监听错误事件 (连接断开、网络异常等)eventSource.onerrorfunction(error){console.error(EventSource 发生错误:,error);// 如果连接关闭可以在这里做重连或提示用户eventSource.close();};// 4. 监听连接打开事件 (可选)eventSource.onopenfunction(){console.log(SSE 连接已建立);};4.3 图像生成privatefinalOpenAiImageModelimageModel;GetMapping(/image)publicStringgenerateImage(RequestParam(defaultValue一只猫)Stringprompt){ImageResponseresponseimageModel.call(newImagePrompt(prompt,OpenAiImageOptions.builder().withModel(dall-e-2).withQuality(hd).withN(1).withHeight(256).withWidth(256).build()));StringimageUrlresponse.getResult().getOutput().getUrl();returnimg srcimageUrl/;}4.4 语音能力语音转文字privatefinalOpenAiAudioTranscriptionModeltranscriptionModel;GetMapping(/speech-to-text)publicStringspeechToText(){varoptionsOpenAiAudioTranscriptionOptions.builder().withResponseFormat(TranscriptResponseFormat.TEXT).withTemperature(0f).build();varaudioFilenewClassPathResource(/sample.mp3);varpromptnewAudioTranscriptionPrompt(audioFile,options);returntranscriptionModel.call(prompt).getResult().getOutput();}文字转语音privatefinalOpenAiAudioApiaudioApi;GetMapping(/text-to-speech)publicStringtextToSpeech()throwsIOException{varrequestSpeechRequest.builder().withVoice(SpeechRequest.Voice.ONYX).withInput(你好欢迎使用 Spring AI).build();ResponseEntitybyte[]responseaudioApi.createSpeech(request);byte[]audioDataresponse.getBody();// 保存为 MP3 文件try(FileOutputStreamfosnewFileOutputStream(output.mp3)){fos.write(audioData);}return语音生成成功;}4.5 多模态识别GPT-4 等模型支持图文混合输入privatefinalOpenAiChatModelchatModel;GetMapping(/multimodal)publicStringmultimodal(RequestParamStringtext)throwsIOException{byte[]imageDatanewClassPathResource(/test.png).getContentAsByteArray();UserMessagemessagenewUserMessage(text,List.of(newMedia(MimeTypeUtils.IMAGE_PNG,imageData)));ChatResponseresponsechatModel.call(newPrompt(message,OpenAiChatOptions.builder().withModel(gpt-4-turbo-preview).build()));returnresponse.getResult().getOutput().getContent();}五、Function Calling让 AI 调用外部能力大模型本身不具备实时信息获取能力例如询问今天北京的天气怎么样时模型无法直接回答。Function Calling 机制允许模型在需要时调用你注册的外部接口。5.1 工作流程用户发送提问请求携带已注册的 Function 描述模型判断需要调用哪个 Function返回参数Spring AI 自动执行对应的 Java 方法执行结果返回给模型模型组织最终答案返回用户5.2 代码实现定义服务类ComponentpublicclassWaitTimeServiceimplementsFunctionWaitTimeService.Request,WaitTimeService.Response{OverridepublicResponseapply(Requestrequest){// 实际业务查询排队人数intcountqueryQueueCount(request.location(),request.name());returnnewResponse(request.location()当前有 count 人排队);}privateintqueryQueueCount(Stringlocation,Stringname){// 调用第三方 API 或查询数据库return10;}publicrecordRequest(Stringname,Stringlocation){}publicrecordResponse(Stringdescription){}}注册 Function BeanConfigurationpublicclassAiConfig{BeanpublicFunctionWaitTimeService.Request,WaitTimeService.ResponsegetWaitTime(){returnnewWaitTimeService();}}调用时启用 FunctionGetMapping(/function-call)publicStringfunctionCall(RequestParamStringmessage){UserMessageuserMessagenewUserMessage(message);ChatResponseresponsechatModel.call(newPrompt(List.of(userMessage),OpenAiChatOptions.builder().withFunction(getWaitTime)// 对应 Bean 名称.build()));returnresponse.getResult().getOutput().getContent();}5.3 核心原理Spring AI 在处理 Function Calling 时的工作机制将 withFunction 中注册的 Bean 信息转换为 OpenAI API 的 tools 参数首次调用 Chat Completion API携带 Function 描述如果模型决定调用 Function返回的 tool_calls 中包含参数 JSONSpring AI 自动将 JSON 反序列化为 Request 对象执行对应的 apply 方法获得 Response将 Response 作为消息再次请求大模型大模型根据 Function 返回结果生成最终回答六、国产模型集成方案6.1 阿里云通义千问阿里已推出基于 Spring AI 的官方 StarterdependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-ai/artifactIdversion最新版本/version/dependency配置与 OpenAI 类似只需替换 base-url 和 api-key 为阿里百炼的凭证。七、总结
返回列表