SringAi 1.0实战:快速使用 目录接入deepseek流式输出Options配置选项模型推理接入阿里百炼文生图文生语音语音翻译文生视频接入Ollama本地大模型1.本地大模型安装2.基于springai使用3.流式输出4.多模态1.创建项目注若要使用 Spring AI则要选择 Java 17 及往上的版本。?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version3.5.3/version relativePath/ !-- lookup parent from repository -- /parent groupIdcom.wyk.ai/groupId artifactIdspring-ai-parent/artifactId version0.0.1-xs/version namespring-ai-parent/name descriptionspring-ai-parent/description packagingpom/packaging !--创建子项目时使用-- modules modulequick-satrt/module /modules properties java.version17/java.version spring-ai-version1.0.0/spring-ai-version spring-ai-alibaba1.0.0.2/spring-ai-alibaba /properties dependencies !--web-- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency !--test-- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope /dependency /dependencies dependencyManagement dependencies dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-bom/artifactId version${spring-ai-version}/version typepom/type scopeimport/scope /dependency !--接入spring ai alibaba-- dependency groupIdcom.alibaba.cloud.ai/groupId artifactIdspring-ai-alibaba-bom/artifactId version1.0.0.2/version typepom/type scopeimport/scope /dependency /dependencies /dependencyManagement build plugins plugin groupIdorg.springframework.boot/groupId artifactIdspring-boot-maven-plugin/artifactId /plugin /plugins /build /project注在现在的 Spring Boot 版本中仅提供 Spring Boot 4.x但 Spring AI 1.0 中支持 Spring Boot 3.x我选择将版本改为 3.5.3 版本。接入deepseek1.在子项目中的pom!--父工程-- parent groupIdcom.wyk.ai/groupId artifactIdspring-ai-parent/artifactId version0.0.1-xs/version relativePath../pom.xml/relativePath /parent !--删除版本号-- groupIdcom.wyk.ai/groupId artifactIdquick-satrt/artifactId namequick-satrt/name descriptionquick-satrt/description !--接入deepseek依赖-- dependencies dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-starter-model-deepseek/artifactId /dependency /dependencies2.获取deepseek的apiKey创建APIkey:DeepSeek3.配置spring.ai.deepseek.api-key自己的apiKey spring.ai.deepseek.chat.options.modeldeepseek-chat4.简单测试SpringBootTest class TestDeepseek { //同步阻塞式响应 Test public void testDeepseek(Autowired DeepSeekChatModel deepSeekChatModel){ String content deepSeekChatModel.call(你好你是谁); System.out.println(content); } }流式输出Test public void testDeepseekStream(Autowired DeepSeekChatModel deepSeekChatModel){ FluxString content deepSeekChatModel.stream(你好你是谁); content.toIterable().forEach(System.out::println); }Options配置选项temperature参数:数值越高越有创造力越低越保守maxTokens:限制ai生成的最大token数类似与字数上限stop:截断ai的输出比如大模型输出一首诗使用.stop(Arrays.asList())让大模型输出诗中的一句//设置temperature参数maxTokens,stop Test public void testChatOptions(Autowired DeepSeekChatModel chatModel){ DeepSeekChatOptions optionsDeepSeekChatOptions.builder() .temperature(0.1) // .maxTokens(5) .stop(Arrays.asList()) .build(); Prompt prompt new Prompt(请写一首诗描述阳光。,options); ChatResponse reschatModel.call(prompt); System.out.println(res.getResult().getOutput().getText()); }模型推理设置深度思考即Chain of Thought (CoT)配置spring.ai.deepseek.chat.options.modeldeepseek-reasoner测试//设置思维链 //同步输出 Test public void testDeepseekChain(Autowired DeepSeekChatModel deepSeekChatModel){ Prompt prompt new Prompt(你好你是谁); ChatResponse response deepSeekChatModel.call(prompt); DeepSeekAssistantMessage assistantMessage (DeepSeekAssistantMessage) response.getResult().getOutput(); System.out.println(assistantMessage.getReasoningContent()); System.out.println(----------------------------); System.out.println(assistantMessage.getText()); } //流式输出 Test public void testDeepseekStreamChain(Autowired DeepSeekChatModel deepSeekChatModel){ FluxChatResponse stream deepSeekChatModel.stream(new Prompt(你好你是谁)); stream.toIterable().forEach(chatResponse - { DeepSeekAssistantMessage assistantMessage (DeepSeekAssistantMessage) chatResponse.getResult().getOutput(); System.out.println(assistantMessage.getReasoningContent()); }); System.out.println(-----------------------------------------); stream.toIterable().forEach(chatResponse - { DeepSeekAssistantMessage assistantMessage (DeepSeekAssistantMessage) chatResponse.getResult().getOutput(); System.out.println(assistantMessage.getText()); }); }注CoT中的思考过程和输出过程不会同时输出需要调用getReasoningContent()和getText()方法输出。接入阿里百炼1.申请apiKey:首次调用千问API-大模型服务平台百炼(Model Studio)-阿里云帮助中心2.依赖dependency groupIdcom.alibaba.cloud.ai/groupId artifactIdspring-ai-alibaba-starter-dashscope/artifactId /dependency3.配置#apiKey可以设置在系统环境变量中通过变量找 spring.ai.dashscope.api-key ${AI_DASHSCOPE_API_KEY} #dashscope自动装配了模型也可以通过下面的配置更换默认模型 #spring.ai.dashscope.chat.options.model4.使用Test public void testQwen(Autowired DashScopeChatModel dashScopeChatModel) { String content dashScopeChatModel.call(你好你是谁); System.out.println(content); }文生图//文生图 Test public void testImg(Autowired DashScopeImageModel dashScopeImageModel) { DashScopeImageOptions imageModel DashScopeImageOptions.builder() // .withN(1) // .withWidth() // .withHeigh() // .withBaseImageUrl() 带水印 .withModel(wanx2.1-t2i-turbo).build(); ImageResponse imageResponse dashScopeImageModel.call( new ImagePrompt(汉服美女,imageModel)); String imageUrl imageResponse.getResult().getOutput().getUrl(); System.out.println(imageUrl); }注withN()设置生成图片的数量.withBaseImageUrl() 设置图片水印文生语音//文生语音 Test public void testAudio(Autowired DashScopeSpeechSynthesisModel scopeSpeechSynthesisModel){ DashScopeSpeechSynthesisOptions options DashScopeSpeechSynthesisOptions.builder() //.voice(longyingtian) 设置音色 //.speed() 设置语速 //.model(cosyvoice-v2) 模型 // .responseFormat(DashScopeSpeechSynthesisApi.ResponseFormat.MP3) 生成文件类型 .build(); SpeechSynthesisResponse response scopeSpeechSynthesisModel.call( new SpeechSynthesisPrompt(你好我是王维居士,日子慢慢往前走不必急于求成。认真吃饭坚持运动沉下心做好手头的事。所有默默付出的时光终会变成属于自己的光亮。) ); File file new File( System.getProperty(user.dir) /output.mp3); try (FileOutputStream fos new FileOutputStream(file)) { ByteBuffer byteBuffer response.getResult().getOutput().getAudio(); fos.write(byteBuffer.array()); } catch (IOException e) { e.printStackTrace(); } }注在设置音色的时候要注意要选择非实时模型和与之匹配的的音色若不能则会使用的音色不会生效使用默认音效。语音翻译Test public void testAudio2Text( Autowired DashScopeAudioTranscriptionModel transcriptionModel ) throws MalformedURLException { DashScopeAudioTranscriptionOptions transcriptionOptions DashScopeAudioTranscriptionOptions.builder() .build(); AudioTranscriptionPrompt prompt new AudioTranscriptionPrompt( new UrlResource(AUDIO_RESOURCES_URL), transcriptionOptions ); AudioTranscriptionResponse response transcriptionModel.call( prompt ); System.out.println(response.getResult().getOutput()); }文生视频1.设置依赖https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java设置为最新版本dependency groupIdcom.alibaba/groupId artifactIddashscope-sdk-java/artifactId version2.23.1/version /dependencyTest public void text2Video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs new VideoSynthesis(); VideoSynthesisParam param VideoSynthesisParam.builder() .model(wanx2.1-t2v-turbo) .prompt(一只小猫在月光下奔跑) .size(1280*720) .apiKey(System.getenv(ALI_AI_KEY)) .build(); System.out.println(please wait...); VideoSynthesisResult result vs.call(param); System.out.println(result.getOutput().getVideoUrl()); }三种接入方式对比对比维度DeepSeek阿里百炼DashScopeOllama接入方式云端 API云端 API本地部署主要功能文本对话、流式输出、模型推理CoT文本对话、流式输出、文生图、文生语音、语音翻译、文生视频文本对话、流式输出、多模态适用场景需要深度思考、低成本文本推理的场景多模态能力丰富、需要图像/语音/视频生成的企业级应用数据隐私要求高、离线环境、本地私有化部署成本按量付费按量付费免费需自备硬件资源配置复杂度较低只需配置 apiKey 和模型名称中等需配置 apiKey多模态功能需额外引入 SDK 依赖较高需先安装 Ollama 并下载模型再配置本地服务地址接入Ollama本地大模型ollama是大语言模型的运行环境 支持将开源的大语言模型以离线的方式部署到本地进行私有化部署。1.本地大模型安装下载ollama:Download Ollama在以管理员身份打开命令行查看ollama的版本号ollama -v下载模型()ollama run qwen3:4b测试2.基于springai使用依赖:!--ollama-- dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-starter-model-ollama/artifactId /dependency配置spring.ai.ollama.base-url http://localhost:11434 ollama在系统中的端口号就是11434 spring.ai.ollama.chat.model qwen3:4b测试//接入本地大模型 Test public void testCaht(Autowired OllamaChatModel ollamaChatModel){ String text ollamaChatModel.call(你是谁/no_think); System.out.println(text); }3.流式输出//流式输出 Test public void testCahtStream(Autowired OllamaChatModel ollamaChatModel){ FluxString stream ollamaChatModel.stream(你是谁); stream.toIterable().forEach(System.out::println); }注在流式输出的时候大模型可能会生成许多的空格可以在在输出时设置输出判断防止输出空格。4.多模态目前ollama支持的多模态模型llama3.2-visionqwen2.5-vlminicpm-vllavagemma4//多模态 Test public void testMultimodality(Autowired OllamaChatModel ollamaChatModel){ var imageResoure new ClassPathResource(gradle.png); OllamaOptions options OllamaOptions.builder() .model(gemma3:4b) .build(); Media media new Media(MimeTypeUtils.IMAGE_PNG, imageResoure); ChatResponse response ollamaChatModel.call( new Prompt( UserMessage.builder().media(media) .text(识别图片,并用中文回答).build(), options ) ); System.out.println(response.getResult().getOutput().getText()); }