新闻详情

新闻详情

首页 / 资讯中心 / 详情

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

发布时间:2026/11/14 7:25:07来源:尧图网络
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 为阿里百炼的凭证。七、总结
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/14 3:51:47

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/12 23:59:09

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/13 10:09:00

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/13 13:31:48

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/13 16:11:45

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/14 3:51:43

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉