基於開源框架SpringAIAlibaba快速構建Java應用

阿里妹導讀
本文旨在幫助開發者快速掌握並應用 Spring AI Alibaba,提升基於 Java 的大模型應用開發效率和安全性。
Spring AI介紹
當前Java呼叫大模型時,往往缺乏一個高效且統一的應用框架,Spring作為知名的Java應用框架提供商,推出了Spring AI來解決這個問題。它借鑑了langchain的一些核心理念,並結合了Java面向物件程式設計的優勢。Spring AI的核心優勢在於提供了統一的介面標準,開發者只需編寫一次程式碼就能輕鬆切換不同的AI服務提供者,如OpenAI、阿里雲等。此外,Spring AI還支援流式輸出相容性及自動POJO對映等功能,極大簡化了開發流程。並且由於有專門團隊維護,確保了長期穩定性和安全性。這種設計讓基於Java的大模型應用開發變得更加便捷和高效。
Spring AI Alibaba介紹
當大模型在國內應用時,面臨的主要挑戰是在確保內容安全的同時,滿足業務需求的智慧化水平。Spring AI Alibaba作為這一背景下的一種理想選擇,提供了強大的內容安全保障,並且基於Qwen-2.5模型,該模型在OpenCompass評估中被評為開源領域中的佼佼者。Spring AI Alibaba是將阿里雲最佳實踐與Spring AI框架本地化結合的結果,它不僅簡化了開發者對接不同AI服務的過程,而且透過統一介面標準使得遷移和適配變得異常簡單。其核心優勢在於支援多種生成式任務(如對話、文生圖等)、相容Flux流處理機制以及提供諸如Prompt Template、OutputParser等功能,極大提升了開發效率與靈活性。此外,Spring AI Alibaba還具備呼叫外部資料的能力,允許使用者根據實際需要定製化擴充套件AI功能,為構建更加智慧的應用提供了堅實的基礎。
Spring AI Alibaba 實戰:後端構建
為了基於Spring Boot整合Spring AI Alibaba並完成一個簡單的對話模型,構建一個支援prompt的流返回介面的專案,並確保GET介面支援CORS跨域,我們可以遵循以下步驟。本回答將詳細指導如何配置和編寫程式碼以達成這一目標。
1. 確認開發環境
  • 確保你的JDK版本在JDK17(含)以上。
  • 使用Spring Boot 3.3.x版本或更高版本。
2. 在阿里雲申請API Key
  • 訪問阿里雲百鍊頁面並登入賬號。
    https://www.aliyun.com/product/bailian
  • 開通“百鍊大模型推理”服務,獲取API Key。
  • 設定環境變數:
    export AI_DASHSCOPE_API_KEY=你的API_KEY 或直接在應用程式配置檔案中設定。
3. 新增倉庫和依賴
由於Spring AI當前版本還未提交到Maven正式倉庫,因此需要新增額外的倉庫來訪問這些資源:
<repositories><repository><id>sonatype-snapshots</id><url>https://oss.sonatype.org/content/repositories/snapshots</url><snapshots><enabled>true</enabled></snapshots></repository><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></repositories>
接著,在pom.xml中新增對spring-ai-alibaba-starter及Spring Boot parent專案的依賴:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.3.4</version><relativePath/><!-- lookup parent from repository --></parent><dependencies><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>1.0.0-M2.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- 其他可能需要的依賴項... --></dependencies>
這裡特別注意加入了spring-boot-starter-webflux,因為它對於處理響應式流(Flux)至關重要。
4. 配置application.properties
在專案的
src/main/resources/application.properties檔案中加入如下配置:
spring.ai.dashscope.api-key=${AI_DASHSCOPE_API_KEY}
5. 編寫Controller
建立一個新的控制器類ChatController.java,實現帶有CORS支援的聊天介面,該介面接受輸入引數並透過ChatClient傳送請求給AI模型,同時利用PromptTemplate提供更豐富的互動體驗。此外,此控制器還將使用WebFlux框架提供的功能來返回響應式型別Flux<String>
import org.springframework.web.bind.annotation.*;import org.springframework.web.reactive.function.server.ServerResponse;import reactor.core.publisher.Flux;@RestController@RequestMapping("/ai")@CrossOrigin(origins = "*")// 支援所有來源的跨域請求publicclassChatController{privatefinal ChatClient chatClient;@Value("classpath:your-prompt-template.st") Resource promptTemplateResource;public ChatController(ChatClient.Builder builder) {this.chatClient = builder.build(); }@GetMapping("/steamChat")public Flux<String> steamChat(@RequestParam String input) { PromptTemplate promptTemplate = new PromptTemplate(promptTemplateResource); Prompt prompt = promptTemplate.create(Map.of("input", input));return chatClient.prompt(prompt).stream().content(); }}
請確保your-prompt-template.st是一個位於src/main/resources/下的模板檔案,用於定義與AI互動時使用的具體提示文字格式,比如:
針對{input},給出回應。
透過上述步驟,你就成功地基於Spring Boot集成了Spring AI Alibaba,並實現了滿足題目要求的功能。這個過程涵蓋了從準備環境到最終編碼的所有關鍵點,包括了對外部庫的支援、特定功能的啟用以及REST API的設計等方面。
構建匹配的聊天前端應用
基於我瞭解的一些資訊,我們將採用React框架來建立一個簡單的聊天應用。該應用會透過HTTP請求與後端互動,並支援從後端接收流式資料(flux<String>)。
1. 初始化React專案
首先,確保你的機器上已安裝了Node.js和npm或yarn。然後執行以下命令以建立一個新的React應用:
npxcreate-react-app frontendcdfrontendnpminstall
這將建立一個名為frontend的基礎React專案,並自動安裝執行所需的所有依賴項。
2. 修改基本檔案結構
根據需求調整基礎檔案內容。這裡主要關注的是HTML模板、主入口檔案以及核心元件。
  • public/index.html
保持預設即可,此檔案定義了網頁的基本結構。
  • src/index.js
無需修改,預設配置足夠用於當前示例。
  • src/App.js
此檔案負責渲染根元件。我們將匯入並顯示自定義的ChatComponent
import React from'react';import ChatComponent from'./components/ChatComponent';functionApp() {return (<divclassName="App"><ChatComponent /></div> );}exportdefault App;
  • src/components/ChatComponent.js
這是實現使用者介面邏輯的主要部分,包括輸入框、傳送按鈕及展示訊息區域。我們還將在此處處理向伺服器傳送請求並監聽響應流的過程。
import React, { useState } from'react';const ChatComponent = () => {const [input, setInput] = useState('');const [messages, setMessages] = useState('');const handleInputChange = (event) => { setInput(event.target.value); };const handleSendMessage = async () => {if (!input.trim()) return; // 避免空訊息try {const response = await fetch(`http://localhost:8080/ai/steamChat?input=${encodeURIComponent(input)}`, { method: 'GET' });if (!response.ok) thrownewError('Network response was not ok');const reader = response.body.getReader();const decoder = new TextDecoder('utf-8');let done = false;while (!done) {const { value, done: readerDone } = await reader.read(); done = readerDone;const chunk = decoder.decode(value, { stream: true }); setMessages((prevMessages) => prevMessages + chunk); }// 新增分隔符區分不同輪次的訊息 setMessages((prevMessages) => prevMessages + '\n\n=============================\n\n'); } catch (error) {console.error('Error fetching data:', error); } finally { setInput(''); // 清空輸入框 } };const handleClearMessages = () => { setMessages(''); };return (<div><inputtype="text"value={input}onChange={handleInputChange}placeholder="Enter your message" /><buttononClick={handleSendMessage}>Send</button><buttononClick={handleClearMessages}>Clear</button><div><h3>Messages:</h3><pre>{messages}</pre></div></div> );};export default ChatComponent;
上述程式碼中,我們利用fetchAPI向指定URL發起GET請求,並使用ReadableStream讀取伺服器返回的資料流。每次接收到新的資料塊時,都會更新頁面上的訊息列表。此外,還包括了一個清空訊息記錄的功能。
3. 執行專案
完成以上步驟後,就可以啟動前端服務檢視效果了:
npm start
這會在本地啟動開發伺服器,預設訪問地址為http://localhost:3000。開啟瀏覽器進入該地址,你就能看到一個可以傳送訊息並即時接收回復的簡單聊天介面了。
注意:
  • 確保後端服務在http://localhost:8080上執行並且能夠正確響應/ai/steamChat路徑下的請求。
  • 如果遇到跨域資源共享(CORS)問題,請檢查後端是否已經允許來自前端域名的請求。

相關文章