# 《实战AI大模型》DeepSeek API实战-第03节:基于SpringAI实现智能问答系统

作者:冰河
星球:http://m6z.cn/6aeFbs (opens new window)
博客:https://binghe.gitcode.host (opens new window)
文章汇总:https://binghe.gitcode.host/md/all/all.html (opens new window)
源码获取地址:https://t.zsxq.com/0dhvFs5oR (opens new window)

大家好,我是冰河~~

在人工智能技术迅猛发展的今天,大语言模型正在深刻改变着人机交互的方式。然而对于广大Java开发者而言,如何将先进的AI能力快速、高效地集成到现有的Spring生态系统中,仍然面临着不小的挑战。今天,带着大家使用Spring AI构建一个功能完备的简单智能问答系统。

Spring AI作为Spring官方推出的AI集成框架,为开发者提供了统一、简洁的抽象层,极大地简化了AI能力的集成复杂度。无论是为现有业务系统添加智能客服功能,还是构建全新的AI驱动型应用,都可以使用SpringAI实现。

# 一、环境准备

# 1.1 项目依赖

首先,创建一个Spring Boot项目,并添加必要的依赖

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
    <repository>
        <name>Central Portal Snapshots</name>
        <id>central-portal-snapshots</id>
        <url>https://central.sonatype.com/repository/maven-snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-core</artifactId>
        <version>1.0.0-M6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        <version>1.0.0-M6</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.30</version>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.25</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <encoding>utf-8</encoding>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>3.2.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

# 1.2 配置API密钥

application.yml中配置API密钥

server:
  port: 5555

spring:
  ai:
    openai:
      api-key: sk-xxxxx # 替换成自己的硅基流动API密钥
      base-url: https://api.siliconflow.cn/
      embedding:
        options:
          model: BAAI/bge-m3
      chat:
        options:
          model: deepseek-ai/DeepSeek-V3
1
2
3
4
5
6
7
8
9
10
11
12
13
14

注意:为了安全起见,建议通过环境变量注入API密钥,而不是直接硬编码在配置文件中。

# 二、核心代码实现

# 2.1 主应用类

创建Spring Boot应用的入口类

源码详见:deepseek-case-qa-01工程下的io.binghe.framework.deepseek.qa.QaApplication。

@SpringBootApplication
public class QaApplication {

    public static void main(String[] args) {
        SpringApplication.run(QaApplication.class, args);
    }

    @Bean
    public ChatClient chatClient(OpenAiChatModel model){
        return ChatClient
                .builder(model)
                .build();
    }

    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        VectorStore vectorStore = SimpleVectorStore.builder(embeddingModel).build();

        // 构建测试数据
        List<Document> documents =
                List.of(new Document("Hello Spring AI"),
                        new Document("Hello Spring Boot"));
        // 添加到向量数据库
        vectorStore.add(documents);

        return vectorStore;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 2.2 请求模型

创建一个简单的模型类来封装问题请求。

源码详见:deepseek-case-qa-01工程下的io.binghe.framework.deepseek.qa.request.QuestionRequest。

@Data
public class QuestionRequest {
    private String question;
    private String sessionId;
}
1
2
3
4
5

# 2.3 问答服务

实现问答核心服务。

源码详见:deepseek-case-qa-01工程下的io.binghe.framework.deepseek.qa.service.QaService。

@Service
public class QaService {

    private final ChatClient chatClient;
    private final PromptTemplate promptTemplate;

    @Autowired
    public QaService(ChatClient chatClient) {
        this.chatClient = chatClient;
        // 创建一个提示模板,指导AI如何回答问题
        this.promptTemplate = new PromptTemplate("""
            你是一个智能问答助手,请简洁、准确地回答用户的问题。
            如果你不知道答案,请直接说不知道,不要编造信息。
            
            用户问题: {question}
            
            回答:
            """);
    }

    public String getAnswer(String question) {
        // 准备模板参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("question", question);

        // 创建提示
        Prompt prompt = promptTemplate.create(parameters);

        // 调用AI获取回答
        return chatClient.prompt(prompt).call().content();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 2.4 添加对话历史

支持多轮对话。

源码详见:deepseek-case-qa-01工程下的io.binghe.framework.deepseek.qa.service.ConversationService。

@Service
public class ConversationService {

    private final ChatClient chatClient;

    private final Map<String, List<Message>> conversations = new ConcurrentHashMap<>();

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

    public String chat(String sessionId, String userMessage) {
        // 获取或创建会话历史
        List<Message> messages = conversations.computeIfAbsent(sessionId, k -> new ArrayList<>());

        // 添加用户消息
        messages.add(new UserMessage(userMessage));

        // 创建带有历史上下文的提示
        Prompt prompt = new Prompt(messages);

        // 调用AI
        String response = chatClient.prompt(prompt).call().content();

        // 保存AI回复
        messages.add(new AssistantMessage(response));

        // 管理会话长度,避免超出Token限制
        if (messages.size() > 10) {
            messages = messages.subList(messages.size() - 10, messages.size());
            conversations.put(sessionId, messages);
        }

        return response;
    }

    public void clearConversation(String sessionId) {
        conversations.remove(sessionId);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 2.5 添加知识库集成

使用向量存储和检索增强生成(RAG)。

源码详见:deepseek-case-qa-01工程下的io.binghe.framework.deepseek.qa.service.KnowledgeBaseQaService。

# 查看完整文章

加入冰河技术 (opens new window)知识星球,解锁完整技术文章、小册、视频与完整代码