当前位置: 首页 > news >正文

Spring AI 1.1.4 开发者使用手册

1. 快速开始

1.1 概述

Spring AI 是 Spring 生态系统的 AI 应用开发框架,提供统一的 API 抽象,支持 20+ AI 模型提供商和 19+ 向量数据库。

1.2 最小可运行示例

@SpringBootApplication public class MyAiApplication {        public static void main(String[] args) {        SpringApplication.run(MyAiApplication.class, args);   }        @Bean    CommandLineRunner demo(ChatClient chatClient) {        return args -> {            String response = chatClient.prompt()               .user("Hello, Spring AI!")               .call()               .content();            System.out.println(response);       };   } }

2. 环境搭建与依赖配置

2.1 系统要求

组件最低版本推荐版本
Java1721
Spring Boot3.2.x3.5.x
Maven3.6+3.9+

2.2 BOM 依赖管理

pom.xml中添加 Spring AI BOM:

<properties>    <spring-ai.version>1.1.4</spring-ai.version> </properties> ​ <dependencyManagement>    <dependencies>        <dependency>            <groupId>org.springframework.ai</groupId>            <artifactId>spring-ai-bom</artifactId>            <version>${spring-ai.version}</version>            <type>pom</type>            <scope>import</scope>        </dependency>    </dependencies> </dependencyManagement>

2.3 模型提供商依赖

OpenAI
<dependency>    <groupId>org.springframework.ai</groupId>    <artifactId>spring-ai-starter-model-openai</artifactId> </dependency>

application.yml 配置:

spring: ai:   openai:     api-key: ${OPENAI_API_KEY}     base-url: https://api.openai.com  # 可选,用于代理     chat:       options:         model: gpt-4         temperature: 0.7         max-tokens: 2000
智谱 AI (ZhiPuAI)
<dependency>    <groupId>org.springframework.ai</groupId>    <artifactId>spring-ai-starter-model-zhipuai</artifactId> </dependency>

application.yml 配置:

spring: ai:   zhipuai:     api-key: ${ZHIPUAI_API_KEY}     chat:       options:         model: glm-4         temperature: 0.7         max-tokens: 2000
Ollama(本地模型)
<dependency>    <groupId>org.springframework.ai</groupId>    <artifactId>spring-ai-starter-model-ollama</artifactId> </dependency>

application.yml 配置:

spring: ai:   ollama:     base-url: http://localhost:11434     chat:       options:         model: llama3         temperature: 0.7

2.4 环境变量管理

开发环境-.env文件(配合spring-dotenv):

# .env OPENAI_API_KEY=sk-xxx ZHIPUAI_API_KEY=xxx.xxx PGVECTOR_HOST=localhost PGVECTOR_PORT=5432 PGVECTOR_DATABASE=vectordb PGVECTOR_USER=postgres PGVECTOR_PASSWORD=secret

生产环境- Kubernetes Secret:

apiVersion: v1 kind: Secret metadata: name: ai-config type: Opaque stringData: OPENAI_API_KEY: "sk-xxx" ZHIPUAI_API_KEY: "xxx"

3. ChatModel 集成指南

3.1 基础对话实现

方式一:使用 ChatClient(推荐)
@Service public class ChatService {        private final ChatClient chatClient;        public ChatService(ChatClient.Builder chatClientBuilder) {        this.chatClient = chatClientBuilder           .defaultSystem("你是一个专业的技术助手")           .defaultOptions(ChatOptions.builder()               .temperature(0.7)               .maxTokens(2000)               .build())           .build();   }        public String chat(String message) {        return chatClient.prompt()           .user(message)           .call()           .content();   } }
方式二:直接使用 ChatModel
@Service public class AdvancedChatService {        @Autowired    private ChatModel chatModel;        public String chatWithHistory(String message, List<Message> history) {        List<Message> messages = new ArrayList<>(history);        messages.add(new UserMessage(message));                Prompt prompt = new Prompt(messages);        ChatResponse response = chatModel.call(prompt);                return response.getResult().getOutput().getText();   } }

3.2 系统提示与用户提示

public String chatWithContext(String userMessage) {    return chatClient.prompt()       .system("""            你是一个专业的 Java 开发助手。            请遵循以下原则:            1. 提供清晰的代码示例            2. 解释关键概念            3. 指出最佳实践            """)       .user(userMessage)       .call()       .content(); }

3.3 参数配置详解

参数类型说明推荐值
temperatureDouble创造性程度(0-2)0.3-0.7
maxTokensInteger最大生成 token 数500-4000
topPDouble核采样概率0.9-1.0
frequencyPenaltyDouble频率惩罚(-2~2)0.0
presencePenaltyDouble存在惩罚(-2~2)0.0

运行时动态配置

public String chatWithOptions(String message, double temperature) {    return chatClient.prompt()       .user(message)       .options(ChatOptions.builder()           .temperature(temperature)           .maxTokens(1000)           .build())       .call()       .content(); }

3.4 结构化输出

POJO 定义
public record ActorFilms(    String actor,    List<String> movies ) {} ​ public record WeatherResponse(    String city,    double temperature,    String condition,    @JsonProperty("humidity_percent") int humidity ) {}
实体映射
public ActorFilms getActorFilms(String actorName) { return chatClient.prompt() .user("列出 " + actorName + " 主演的5部电影") .call() .entity(ActorFilms.class); }
列表输出
public List<String> getMovieRecommendations(String genre) { return chatClient.prompt() .user("推荐5部" + genre + "类型的电影") .call() .entity(new ParameterizedTypeReference<List<String>>() {}); }

3.5 多轮对话管理

@Service public class ConversationService {        private final ChatClient chatClient;    private final ChatMemory chatMemory;        public String chat(String conversationId, String message) {        return chatClient.prompt()           .advisors(new MessageChatMemoryAdvisor(chatMemory, conversationId, 10))           .user(message)           .call()           .content();   } } ​ // ChatMemory 配置 @Bean public ChatMemory chatMemory() {    // 内存存储(开发/测试)    return new InMemoryChatMemory();        // 或 Redis 存储(生产)    // return new RedisChatMemory(redisTemplate, Duration.ofHours(24)); }

4. StreamingChatModel 流式响应

4.1 基础流式实现

@RestController @RequestMapping("/api/chat") public class ChatStreamController {        @Autowired    private ChatClient chatClient;        @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)    public Flux<String> streamChat(@RequestParam String message) {        return chatClient.prompt()           .user(message)           .stream()           .content();   } }

4.2 带上下文的流式响应

@GetMapping(value = "/stream-with-context", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<String>> streamWithContext(@RequestParam String message) {    return chatClient.prompt()      
http://www.jsqmd.com/news/579174/

相关文章:

  • 轻量级双二阶滤波器库biquadFilter嵌入式实践
  • OpenClaw安全指南:gemma-3-12b-it本地化部署的数据边界管控
  • OpenClaw异常处理:Qwen3.5-9B自动修复失败任务
  • 神马网站 SEO 优化对网站转化率的影响
  • 千问3.5-9B+OpenClaw内容处理:自动生成技术博客草稿
  • 15个实用电脑使用小技巧,零基础也会,效率翻倍、电脑更流畅
  • 关于一些Git的学习
  • 小端走错的路——学会魔搭CLI
  • BilibiliDown终极指南:3步掌握B站视频下载神器
  • 成功在本地部署openclaw,使用本地模型,并可以exec执行任务,tool执行成功
  • 2026年靠谱的医用材料疲劳试验机公司对比推荐 - 品牌宣传支持者
  • 小端火爆计划:我的第一步
  • macOS下OpenClaw一键安装指南:对接千问3.5-35B-A3B-FP8实现本地自动化
  • [具身智能-202]:Visual Studio vs. Visual Studio Code
  • Ubuntu极简安装Conda指南
  • C语言中的对齐(alignment)与#pragma pack
  • 2026年评价高的电池疲劳试验机口碑好的厂家推荐 - 品牌宣传支持者
  • OpenClaw安全防护:Qwen3.5-9B操作权限管理与风险指令拦截
  • 【Linux】库的制作与使用(2)ELF静态链接
  • 什么是精益生产管理八大浪费?精益生产管理八大浪费详解
  • 电机轴承异响?5分钟教你用振动分析仪定位故障(附实测案例)
  • AI浪潮下的核心密码:Token如何重塑智能经济与未来竞争格局?
  • 本源量子开发工具链全解析:从QPanda到VQNet,构建量子计算生态
  • ReactNative项目OpenHarmony三方库集成实战:react-native-render-html
  • OpenClaw+Qwen2.5-VL-7B:3种方法提升图文任务成功率
  • 星图平台快速体验:OpenClaw镜像+Qwen3.5-9B完成图片分析沙盒测试
  • 嵌入式开发中的位操作技巧与实战应用
  • 关于eclipse2019中导入克隆的web项目
  • OpenClaw+Qwen3.5-9B办公自动化:3类图片处理场景实测
  • Spring IoC 与 DI 核心详解 —— 基于 XML 配置:Bean 创建、依赖注入与生命周期全解析(Spring系列1)