最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺析如何利用Spring AI構(gòu)建一個簡單的問答系統(tǒng)

 更新時間:2025年05月20日 08:15:06   作者:風(fēng)象南  
Spring AI是Spring生態(tài)系統(tǒng)的最新成員,旨在簡化AI服務(wù)與Spring應(yīng)用的集成過程,本文小編就來和大家簡單介紹一下如何利用Spring AI構(gòu)建一個簡單的問答系統(tǒng)吧

1. 引言

隨著大語言模型(LLM)技術(shù)的不斷發(fā)展,將AI能力集成到企業(yè)應(yīng)用中變得越來越重要。Spring AI是Spring生態(tài)系統(tǒng)的最新成員,旨在簡化AI服務(wù)與Spring應(yīng)用的集成過程。

本文將詳細介紹如何利用Spring AI構(gòu)建一個簡單的問答系統(tǒng),幫助開發(fā)者快速入門AI應(yīng)用開發(fā)。

2. 環(huán)境準(zhǔn)備

2.1 項目依賴

首先,創(chuàng)建一個Spring Boot項目,并添加必要的依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring-ai-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>


    <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>
            <version>3.4.2</version>
        </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>21</source>
                    <target>21</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>

</project>

2.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

注意:為了安全起見,建議通過環(huán)境變量注入API密鑰,而不是直接硬編碼在配置文件中。

3. 核心代碼實現(xiàn)

3.1 主應(yīng)用類

創(chuàng)建Spring Boot應(yīng)用的入口類:

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.List;

@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();

        // 構(gòu)建測試數(shù)據(jù)
        List<Document> documents =
                List.of(new Document("Hello Spring AI"),
                        new Document("Hello Spring Boot"));
        // 添加到向量數(shù)據(jù)庫
        vectorStore.add(documents);

        return vectorStore;
    }

}

3.2 請求模型

創(chuàng)建一個簡單的模型類來封裝問題請求:

import lombok.Data;

@Data
public class QuestionRequest {
    private String question;
    private String sessionId;
}

3.3 問答服務(wù)

實現(xiàn)問答核心服務(wù):

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class QaService {
    
    private final ChatClient chatClient;
    private final PromptTemplate promptTemplate;
    
    @Autowired
    public QaService(ChatClient chatClient) {
        this.chatClient = chatClient;
        // 創(chuàng)建一個提示模板,指導(dǎo)AI如何回答問題
        this.promptTemplate = new PromptTemplate("""
            你是一個智能問答助手,請簡潔、準(zhǔn)確地回答用戶的問題。
            如果你不知道答案,請直接說不知道,不要編造信息。
            
            用戶問題: {question}
            
            回答:
            """);
    }
    
    public String getAnswer(String question) {
        // 準(zhǔn)備模板參數(shù)
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("question", question);
        
        // 創(chuàng)建提示
        Prompt prompt = promptTemplate.create(parameters);
        
        // 調(diào)用AI獲取回答
        return chatClient.prompt(prompt).call().content();
    }
}

3.4 REST控制器

創(chuàng)建REST API接口,處理問題請求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/qa")
public class QaController {
    
    private final QaService qaService;

    private final ConversationService conversationService;

    private final KnowledgeBaseQaService knowledgeBaseQaService;
    
    @Autowired
    public QaController(QaService qaService,
                        ConversationService conversationService,
                        KnowledgeBaseQaService knowledgeBaseQaService
    ) {
        this.qaService = qaService;
        this.conversationService = conversationService;
        this.knowledgeBaseQaService = knowledgeBaseQaService;
    }
    
    @PostMapping("/ask")
    public Map<String, String> askQuestion(@RequestBody QuestionRequest request) {
        String answer = qaService.getAnswer(request.getQuestion());
        
        Map<String, String> response = new HashMap<>();
        response.put("question", request.getQuestion());
        response.put("answer", answer);
        
        return response;
    }

    @PostMapping("/ask-session")
    public Map<String, String> askSession(@RequestBody QuestionRequest request) {
        String answer = conversationService.chat(request.getSessionId(),request.getQuestion());

        Map<String, String> response = new HashMap<>();
        response.put("question", request.getQuestion());
        response.put("answer", answer);

        return response;
    }

    @PostMapping("/ask-knowledge")
    public Map<String, String> askKnowledge(@RequestBody QuestionRequest request) {
        String answer = knowledgeBaseQaService.getAnswerWithKnowledgeBase(request.getQuestion());

        Map<String, String> response = new HashMap<>();
        response.put("question", request.getQuestion());
        response.put("answer", answer);

        return response;
    }

}

3.5 簡單HTML前端

src/main/resources/static目錄下創(chuàng)建一個簡單的HTML頁面(qa.html):

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI問答系統(tǒng)</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            margin-top: 20px;
        }
        .question-form {
            margin-bottom: 20px;
        }
        #question {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .answer {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 4px;
            white-space: pre-wrap;
        }
        .loading {
            color: #888;
            font-style: italic;
            display: none;
        }
    </style>
</head>
<body>
<h1>AI問答系統(tǒng)</h1>

<div class="container">
    <div class="question-form">
        <h2>請輸入您的問題</h2>
        <textarea id="question" rows="4" placeholder="例如:什么是Spring AI?"></textarea>
        <button id="ask-button">提問</button>
        <p class="loading" id="loading">AI正在思考中,請稍候...</p>
    </div>

    <div class="answer" id="answer-container" style="display:none;">
        <h2>回答</h2>
        <div id="answer-text"></div>
    </div>
</div>

<script>
    document.getElementById('ask-button').addEventListener('click', async function() {
        const question = document.getElementById('question').value.trim();

        if (!question) {
            alert('請輸入問題');
            return;
        }

        // 顯示加載狀態(tài)
        document.getElementById('loading').style.display = 'block';
        document.getElementById('answer-container').style.display = 'none';

        try {
            // 普通模式   /api/qa/ask
            // 會話模式   /api/qa/ask-session
            // 知識庫模式 /api/qa/ask-knowledge
            const response = await fetch('/api/qa/ask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ question: question, sessionId: '12345' })
            });

            if (!response.ok) {
                throw new Error('服務(wù)器錯誤');
            }

            const data = await response.json();

            // 顯示回答
            document.getElementById('answer-text').textContent = data.answer;
            document.getElementById('answer-container').style.display = 'block';
        } catch (error) {
            console.error('Error:', error);
            document.getElementById('answer-text').textContent = '發(fā)生錯誤: ' + error.message;
            document.getElementById('answer-container').style.display = 'block';
        } finally {
            // 隱藏加載狀態(tài)
            document.getElementById('loading').style.display = 'none';
        }
    });
</script>
</body>
</html>

4. 運行與測試

完成上述代碼后,運行Spring Boot應(yīng)用:

mvn spring-boot:run

或者使用IDE直接運行QaApplication類。

啟動后,訪問http://localhost:5555/qa.html,即可使用問答系統(tǒng)。在文本框中輸入問題,點擊"提問"按鈕后,系統(tǒng)會將問題發(fā)送給AI,并展示回答結(jié)果。

5. 功能擴展

這個基礎(chǔ)的問答系統(tǒng)可以通過以下方式進行擴展

5.1 添加對話歷史

改進服務(wù),支持多輪對話

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ConversationService {
    
    private final ChatClient chatClient;

    // TODO 此處僅為簡單模擬,實際應(yīng)為數(shù)據(jù)庫或其他存儲方式
    private final Map<String, List<Message>> conversations = new ConcurrentHashMap<>();
    
    @Autowired
    public ConversationService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }
    
    public String chat(String sessionId, String userMessage) {
        // 獲取或創(chuàng)建會話歷史
        List<Message> messages = conversations.computeIfAbsent(sessionId, k -> new ArrayList<>());
        
        // 添加用戶消息
        messages.add(new UserMessage(userMessage));
        
        // 創(chuàng)建帶有歷史上下文的提示
        Prompt prompt = new Prompt(messages);
        
        // 調(diào)用AI
        String response = chatClient.prompt(prompt).call().content();
        
        // 保存AI回復(fù)
        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);
    }
}

5.2 添加知識庫集成

使用向量存儲和檢索增強生成(RAG)

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.Embedding;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class KnowledgeBaseQaService {
    
    private final ChatClient chatClient;
    private final VectorStore vectorStore;
    
    @Autowired
    public KnowledgeBaseQaService(
            ChatClient chatClient, 
            VectorStore vectorStore) {
        this.chatClient = chatClient;
        this.vectorStore = vectorStore;
    }
    
    public String getAnswerWithKnowledgeBase(String question) {
        // 在知識庫中搜索相關(guān)文檔
        List<Document> relevantDocs = vectorStore.similaritySearch(question);
        
        // 構(gòu)建上下文
        StringBuilder context = new StringBuilder();
        for (Document doc : relevantDocs) {
            context.append(doc.getText()).append("\n\n");
        }
        
        // 創(chuàng)建提示模板
        PromptTemplate promptTemplate = new PromptTemplate("""
            你是一個智能問答助手。請根據(jù)以下提供的信息回答用戶問題。
            如果無法從提供的信息中找到答案,請基于你的知識謹(jǐn)慎回答,并明確指出這是你的一般性了解。
            
            參考信息:
            {context}
            
            用戶問題: {question}
            
            回答:
            """);
        
        // 準(zhǔn)備參數(shù)
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("context", context.toString());
        parameters.put("question", question);
        
        // 創(chuàng)建提示并調(diào)用AI
        Prompt prompt = promptTemplate.create(parameters);
        return chatClient.prompt(prompt).call().content();
    }
}

6. 總結(jié)

本文詳細介紹了如何使用Spring AI創(chuàng)建一個簡單的問答系統(tǒng)。通過Spring AI提供的抽象層,我們能夠輕松地集成大語言模型,無需深入了解底層API細節(jié)。這種方式可以讓開發(fā)者專注于業(yè)務(wù)邏輯,同時保持了Spring生態(tài)系統(tǒng)的一致性。。

到此這篇關(guān)于淺析如何利用Spring AI構(gòu)建一個簡單的問答系統(tǒng)的文章就介紹到這了,更多相關(guān)Spring AI構(gòu)建問答系統(tǒng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決rocketmq-client查詢手動發(fā)送消息異常問題

    解決rocketmq-client查詢手動發(fā)送消息異常問題

    這篇文章主要介紹了解決rocketmq-client查詢手動發(fā)送消息異常問題,具有很好的參考價值,希望對大家大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 詳解批處理框架之Spring Batch

    詳解批處理框架之Spring Batch

    Spring Batch是一個輕量級的、完善的批處理框架,作為Spring體系中的一員,它擁有靈活、方便、生產(chǎn)可用的特點。在應(yīng)對高效處理大量信息、定時處理大量數(shù)據(jù)等場景十分簡便。結(jié)合調(diào)度框架能更大地發(fā)揮Spring Batch的作用
    2021-06-06
  • Java的MyBatis框架中對數(shù)據(jù)庫進行動態(tài)SQL查詢的教程

    Java的MyBatis框架中對數(shù)據(jù)庫進行動態(tài)SQL查詢的教程

    這篇文章主要介紹了Java的MyBatis框架中對數(shù)據(jù)庫進行動態(tài)SQL查詢的教程,講解了MyBatis中一些控制查詢流程的常用語句,需要的朋友可以參考下
    2016-04-04
  • Java中的異常和處理機制實例詳解

    Java中的異常和處理機制實例詳解

    這篇文章主要介紹了Java中的異常和處理機制,結(jié)合實例形式詳細分析了Java異常與處理機制的相關(guān)概念、原理、用法及操作注意事項,需要的朋友可以參考下
    2019-05-05
  • Mybatis聯(lián)合查詢XML與注解對比分析

    Mybatis聯(lián)合查詢XML與注解對比分析

    文章對比了MyBatis中XML配置方式和注解方式查詢多表關(guān)聯(lián)的效率和實現(xiàn)方式,XML配置方式執(zhí)行聯(lián)合查詢效率較高,但注解方式雖然可以獨立使用,但在處理復(fù)雜映射時不如XML靈活
    2026-03-03
  • 在Elasticsearch中添加字段的詳細步驟

    在Elasticsearch中添加字段的詳細步驟

    在ES中,增加字段相對比較容易,因為ES支持動態(tài)映射(Dynamic Mapping),這篇文章主要給大家介紹了關(guān)于在Elasticsearch中添加字段的詳細步驟,文中給出了詳細的代碼實例,需要的朋友可以參考下
    2024-07-07
  • java跳板執(zhí)行ssh命令方式

    java跳板執(zhí)行ssh命令方式

    本文分享了在Java中使用跳板機執(zhí)行SSH命令的方法,并推薦了一些Maven依賴,希望這些信息對大家有所幫助
    2024-12-12
  • java自定義類加載器如何實現(xiàn)類隔離

    java自定義類加載器如何實現(xiàn)類隔離

    這篇文章主要介紹了java自定義類加載器如何實現(xiàn)類隔離問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Spring?@Cacheable注解類內(nèi)部調(diào)用失效的解決方案

    Spring?@Cacheable注解類內(nèi)部調(diào)用失效的解決方案

    這篇文章主要介紹了Spring?@Cacheable注解類內(nèi)部調(diào)用失效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • SpringBoot整合WebSocket實現(xiàn)實時通信功能

    SpringBoot整合WebSocket實現(xiàn)實時通信功能

    在當(dāng)今互聯(lián)網(wǎng)時代,實時通信已經(jīng)成為了許多應(yīng)用程序的基本需求,而WebSocket作為一種全雙工通信協(xié)議,為開發(fā)者提供了一種簡單、高效的實時通信解決方案,本文將介紹如何使用SpringBoot框架來實現(xiàn)WebSocket的集成,快速搭建實時通信功能,感興趣的朋友可以參考下
    2023-11-11

最新評論

聂荣县| 望城县| 安平县| 谷城县| 高碑店市| 靖西县| 天峻县| 汤原县| 开远市| 张家口市| 盱眙县| 肥东县| 上林县| 阳城县| 盈江县| 土默特左旗| 瑞昌市| 蓝田县| 玉龙| 磴口县| 汾阳市| 黑河市| 淮安市| 安陆市| 满洲里市| 确山县| 志丹县| 秦安县| 边坝县| 古蔺县| 湖北省| 霞浦县| 星子县| 潼南县| 即墨市| 锦州市| 阳西县| 逊克县| 黄冈市| 改则县| 芦溪县|