使用 Spring AI 构建智能应用:完整入门教程(附示例代码)

Spring 团队发布的 Spring AI 是一个强大的库,它将人工智能的能力(如 OpenAI、Hugging Face、Azure OpenAI 等)整合进了 Spring Boot 应用中,让我们可以像操作数据库一样调用大语言模型(LLMs)。

本教程将详细讲解如何用 Spring AI 构建一个智能问答服务,使用 OpenAI 模型进行处理。


一、环境准备

创建 Spring Boot 项目

可以使用 Spring Initializr 创建项目,配置如下:

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.2+
  • Dependencies:
    • Spring Web
    • Spring AI OpenAI
    • Spring Boot Actuator(可选)
    • Lombok(可选)

二、添加配置

在 application.yml 或 application.properties 中配置 OpenAI Key:

spring:
  ai:
    openai:
      api-key: sk-你的key
      base-url: https://api.openai.com/v1
      chat:
        options:
          model: gpt-4
OpenAI API Key,可在 https://platform.openai.com 获取

三、创建 ChatClient 示例服务

Spring AI 提供了 ChatClient 接口,它就像操作数据库的 JdbcTemplate 一样,可以直接问问题、获取回复。

package com.example.springai.service;

import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AIService {

    private final ChatClient chatClient;

    @Autowired
    public AIService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String ask(String question) {
        return chatClient.call(question);
    }
}

四、创建 REST API 接口

package com.example.springai.controller;

import com.example.springai.service.AIService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    private final AIService aiService;

    public AIController(AIService aiService) {
        this.aiService = aiService;
    }

    @GetMapping("/ask")
    public String ask(@RequestParam String question) {
        return aiService.ask(question);
    }
}

五、运行与测试

启动项目后访问:

http://localhost:8080/api/ai/ask?question=介绍一下Spring Boot

返回:

Spring Boot 是一个由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程……

六、进阶:上下文多轮对话(Memory)

Spring AI 支持“内存”功能,可以让模型记住对话上下文。

添加依赖:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-memory-in-memory</artifactId>
</dependency>
修改代码支持多轮对话:
package com.example.springai.service;

import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AIService {

    private final ChatClient chatClient;
    private final ChatMemory chatMemory;

    @Autowired
    public AIService(ChatClient chatClient) {
        this.chatClient = chatClient;
        this.chatMemory = new InMemoryChatMemory();
    }

    public String chatWithMemory(String userInput) {
        Prompt prompt = new Prompt(userInput);
        chatMemory.add(prompt);
        String response = chatClient.call(chatMemory.get());
        chatMemory.add(response);
        return response;
    }
}

七、使用 Prompt Template 进行结构化提示

PromptTemplate template = new PromptTemplate("你是一位{role},请帮我解释:{question}");
template.add("role", "资深Java架构师");
template.add("question", "什么是微服务?");

String response = chatClient.call(template.create());
提示工程(Prompt Engineering)技巧
明确角色:你是一个专业医生,请...
限制格式:用 bullet points 总结...
指定语言:请用中文回答

九、其他模型支持

Spring AI 支持以下模型:
OpenAI(GPT-4、GPT-3.5)
Azure OpenAI
Hugging Face
Ollama(本地模型)
Vertex AI(Google)
Amazon Bedrock(Anthropic Claude、Titan 等)
只需切换配置或依赖即可。
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐