
Spring-AI 入门案例1.创建工程创建一个spring boot工程版本3.5.13jdk版本为17。选择依赖web、mysql、ollamapom文件如下?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion3.5.13/versionrelativePath/!-- lookup parent from repository --/parentgroupIdcom.example/groupIdartifactIdspring-ai-demo/artifactIdversion0.0.1-SNAPSHOT/versionpropertiesjava.version17/java.versionspring-ai.version1.1.4/spring-ai.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-model-ollama/artifactId/dependencydependencygroupIdcom.mysql/groupIdartifactIdmysql-connector-j/artifactIdscoperuntime/scope/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency/dependenciesdependencyManagementdependenciesdependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-bom/artifactIdversion${spring-ai.version}/versiontypepom/typescopeimport/scope/dependency/dependencies/dependencyManagementbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project2.application配置文件配置文件中指定大模型的地址和名称。因为是调用本地模型不需要api_key。server:port:8081spring:application:name:spring-ai-demoai:ollama:base-url:http://localhost:11434chat:model:deepseek-r1:7b3. 配置访问大模型的客户端添加如下配置类ConfigurationpublicclassCommonConfig{BeanpublicChatClientchatClient(OllamaChatModelmodel){returnChatClient.builder(model).defaultSystem(你的名字叫丽莎请以丽莎的身份和语气回答问题。).build();}}4. 测试访问以下案例中调用方式不同。RestControllerRequestMapping(/ai)RequiredArgsConstructorpublicclassChatController{privatefinalChatClientchatClient;GetMapping(/chat)publicStringchat(Stringprompt){returnchatClient.prompt().user(prompt).call().content();}/** * 流式输出一个字一个字的输出最常用 * param prompt * return */GetMapping(value/chat/stream,producestext/html;charsetutf-8)publicFluxStringchatStream(Stringprompt){returnchatClient.prompt().user(prompt).stream().content();}}Eage浏览器访问和google不太一样应该不是浏览器的差异而是每次调用接口输出结果都不一样。