Spring Boot 集成國內AI,包含文心一言、通義千問和訊飛星火平臺實戰教程

Spring Boot 集成國內AI,包含文心一言、通義千問和訊飛星火平臺實戰教程

  • 一、項目結構
  • 二、添加Maven依賴
  • 三、配置API密鑰 (application.yml)
  • 四、配置類
    • 1. AI配置類 (AiProperties.java)
    • 2. 啟用配置類 (AiConfig.java)
  • 五、服務層實現
    • 1. 文心一言服務 (WenxinService.java)
    • 2. 通義千問服務 (QianwenService.java)
    • 3. 訊飛星火服務 (XinghuoService.java)
  • 六、統一控制器 (AiController.java)
  • 七、安全增強配置
    • 1. 添加API密鑰保護(自定義Filter)
    • 2. 添加Rate Limiting(使用Resilience4j)
  • 八、應用入口 (AiIntegrationApplication.java)
  • 九、測試示例
  • 十、最佳實踐建議

Spring Boot集成國內主流AI平臺的詳細實現方案,包含文心一言、通義千問和訊飛星火的對接代碼,助力快速構建智能應用。

一、項目結構

ai-integration-demo/
├── src/main/java
│   ├── com/example/ai
│   │   ├── config                # 配置類
│   │   ├── controller            # API控制器
│   │   ├── service               # 服務層
│   │   │   ├── impl              # 服務實現
│   │   ├── dto                   # 數據傳輸對象
├── resources
│   ├── application.yml           # 配置文件

二、添加Maven依賴

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- HTTP客戶端 --><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.11.0</version></dependency><!-- JSON處理 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency><!-- 配置處理 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>
</dependencies>

三、配置API密鑰 (application.yml)

ai:wenxin:api-key: YOUR_WENXIN_API_KEYsecret-key: YOUR_WENXIN_SECRET_KEYapi-url: https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completionsqianwen:api-key: YOUR_QIANWEN_API_KEYapi-url: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generationxinghuo:api-key: YOUR_XINGHUO_API_KEYsecret: YOUR_XINGHUO_SECRETappid: YOUR_XINGHUO_APPIDapi-url: https://spark-api.xf-yun.com/v3.5/chat

四、配置類

1. AI配置類 (AiProperties.java)

@ConfigurationProperties(prefix = "ai")
@Data
public class AiProperties {private Wenxin wenxin;private Qianwen qianwen;private Xinghuo xinghuo;@Datapublic static class Wenxin {private String apiKey;private String secretKey;private String apiUrl;}@Datapublic static class Qianwen {private String apiKey;private String apiUrl;}@Datapublic static class Xinghuo {private String apiKey;private String secret;private String appid;private String apiUrl;}
}

2. 啟用配置類 (AiConfig.java)

@Configuration
@EnableConfigurationProperties(AiProperties.class)
public class AiConfig {@Beanpublic OkHttpClient okHttpClient() {return new OkHttpClient();}
}

五、服務層實現

1. 文心一言服務 (WenxinService.java)

@Service
@RequiredArgsConstructor
public class WenxinService {private final AiProperties aiProperties;private final OkHttpClient okHttpClient;// 獲取AccessTokenprivate String getAccessToken() {String url = "https://aip.baidubce.com/oauth/2.0/token?"+ "grant_type=client_credentials"+ "&client_id=" + aiProperties.getWenxin().getApiKey()+ "&client_secret=" + aiProperties.getWenxin().getSecretKey();Request request = new Request.Builder().url(url).get().build();try (Response response = okHttpClient.newCall(request).execute()) {String responseBody = response.body().string();ObjectMapper objectMapper = new ObjectMapper();JsonNode rootNode = objectMapper.readTree(responseBody);return rootNode.get("access_token").asText();} catch (Exception e) {throw new RuntimeException("獲取文心一言Token失敗", e);}}public String chatCompletion(String prompt) {String accessToken = getAccessToken();String url = aiProperties.getWenxin().getApiUrl() + "?access_token=" + accessToken;JSONObject body = new JSONObject();body.put("messages", new JSONArray().put(new JSONObject().put("role", "user").put("content", prompt)));Request request = new Request.Builder().url(url).post(RequestBody.create(body.toString(), MediaType.get("application/json"))).build();try (Response response = okHttpClient.newCall(request).execute()) {if (!response.isSuccessful()) {throw new RuntimeException("文心一言API請求失敗: " + response);}String responseBody = response.body().string();JSONObject jsonResponse = new JSONObject(responseBody);return jsonResponse.getJSONObject("result").getString("content");} catch (Exception e) {throw new RuntimeException("調用文心一言API出錯", e);}}
}

2. 通義千問服務 (QianwenService.java)

@Service
@RequiredArgsConstructor
public class QianwenService {private final AiProperties aiProperties;private final OkHttpClient okHttpClient;public String generateText(String prompt) {JSONObject body = new JSONObject();body.put("model", "qwen-turbo");JSONObject input = new JSONObject();input.put("prompt", prompt);body.put("input", input);JSONObject parameters = new JSONObject();parameters.put("temperature", 0.85);parameters.put("top_p", 0.8);parameters.put("max_tokens", 1500);body.put("parameters", parameters);Request request = new Request.Builder().url(aiProperties.getQianwen().getApiUrl()).header("Authorization", "Bearer " + aiProperties.getQianwen().getApiKey()).post(RequestBody.create(body.toString(), MediaType.get("application/json"))).build();try (Response response = okHttpClient.newCall(request).execute()) {if (!response.isSuccessful()) {throw new RuntimeException("通義千問API請求失敗: " + response);}String responseBody = response.body().string();JSONObject jsonResponse = new JSONObject(responseBody);return jsonResponse.getJSONObject("output").getString("text");} catch (Exception e) {throw new RuntimeException("調用通義千問API出錯", e);}}
}

3. 訊飛星火服務 (XinghuoService.java)

@Service
@RequiredArgsConstructor
public class XinghuoService {private final AiProperties aiProperties;private final OkHttpClient okHttpClient;public String chat(String prompt) {try {// 構造鑒權URLString authUrl = generateAuthUrl();// 構造請求體JSONObject body = new JSONObject();JSONObject header = new JSONObject();header.put("app_id", aiProperties.getXinghuo().getAppid());JSONObject parameter = new JSONObject();JSONObject chat = new JSONObject();chat.put("domain", "generalv3.5");chat.put("temperature", 0.5);chat.put("max_tokens", 4096);parameter.put("chat", chat);JSONObject payload = new JSONObject();JSONObject message = new JSONObject();JSONArray text = new JSONArray();text.put(new JSONObject().put("role", "user").put("content", prompt));message.put("text", text);payload.put("message", message);body.put("header", header);body.put("parameter", parameter);body.put("payload", payload);// 發送請求Request request = new Request.Builder().url(authUrl).post(RequestBody.create(body.toString(), MediaType.get("application/json"))).build();try (Response response = okHttpClient.newCall(request).execute()) {if (!response.isSuccessful()) {throw new RuntimeException("訊飛星火API請求失敗: " + response);}String responseBody = response.body().string();JSONObject jsonResponse = new JSONObject(responseBody);return extractContent(jsonResponse);}} catch (Exception e) {throw new RuntimeException("調用訊飛星火API出錯", e);}}// 生成帶鑒權信息的URLprivate String generateAuthUrl() throws ParseException, InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {String apiUrl = aiProperties.getXinghuo().getApiUrl();String host = new URL(apiUrl).getHost();String path = new URL(apiUrl).getPath();// 創建日期對象SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);sdf.setTimeZone(TimeZone.getTimeZone("GMT"));String date = sdf.format(new Date());// 構造簽名String signatureOrigin = "host: " + host + "\n";signatureOrigin += "date: " + date + "\n";signatureOrigin += "POST " + path + " HTTP/1.1";Mac mac = Mac.getInstance("hmacsha256");SecretKeySpec secretKeySpec = new SecretKeySpec(aiProperties.getXinghuo().getSecret().getBytes("UTF-8"), "hmacsha256");mac.init(secretKeySpec);byte[] signatureSha = mac.doFinal(signatureOrigin.getBytes("UTF-8"));String signature = Base64.getEncoder().encodeToString(signatureSha);// 構造授權頭String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",aiProperties.getXinghuo().getApiKey(), "hmac-sha256", "host date request-line", signature);return apiUrl + "?authorization=" + Base64.getEncoder().encodeToString(authorization.getBytes("UTF-8"))+ "&date=" + URLEncoder.encode(date, "UTF-8")+ "&host=" + URLEncoder.encode(host, "UTF-8");}// 提取響應內容private String extractContent(JSONObject response) {JSONObject payload = response.getJSONObject("payload");JSONObject message = payload.getJSONObject("message");JSONArray text = message.getJSONArray("text");StringBuilder result = new StringBuilder();for (int i = 0; i < text.length(); i++) {JSONObject textObj = text.getJSONObject(i);if (textObj.has("content")) {result.append(textObj.getString("content"));}}return result.toString();}
}

六、統一控制器 (AiController.java)

@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiController {private final WenxinService wenxinService;private final QianwenService qianwenService;private final XinghuoService xinghuoService;@PostMapping("/wenxin")public ResponseEntity<String> wenxinChat(@RequestBody @Valid AiRequest request) {return ResponseEntity.ok(wenxinService.chatCompletion(request.getPrompt()));}@PostMapping("/qianwen")public ResponseEntity<String> qianwenGenerate(@RequestBody @Valid AiRequest request) {return ResponseEntity.ok(qianwenService.generateText(request.getPrompt()));}@PostMapping("/xinghuo")public ResponseEntity<String> xinghuoChat(@RequestBody @Valid AiRequest request) {return ResponseEntity.ok(xinghuoService.chat(request.getPrompt()));}@Datastatic class AiRequest {@NotBlank(message = "提示語不能為空")private String prompt;}
}

七、安全增強配置

1. 添加API密鑰保護(自定義Filter)

@Component
@RequiredArgsConstructor
public class ApiKeyFilter extends OncePerRequestFilter {private final AiProperties aiProperties;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {String clientId = request.getHeader("X-API-CLIENT-ID");String clientSecret = request.getHeader("X-API-CLIENT-SECRET");// 驗證客戶端憑證if (!isValidCredentials(clientId, clientSecret)) {response.sendError(HttpStatus.UNAUTHORIZED.value(), "無效的API憑證");return;}filterChain.doFilter(request, response);}private boolean isValidCredentials(String clientId, String clientSecret) {// 這里應該是從數據庫或配置中讀取驗證信息// 簡化示例:使用配置中的文心API密鑰做演示return clientId != null && clientSecret != null && clientId.equals("demo-app") && clientSecret.equals(aiProperties.getWenxin().getApiKey());}
}

2. 添加Rate Limiting(使用Resilience4j)

@Configuration
public class RateLimiterConfig {@Beanpublic RateLimiter wenxinRateLimiter() {return RateLimiter.of("wenxin-limiter", RateLimiterConfig.custom().limitRefreshPeriod(Duration.ofSeconds(10)).limitForPeriod(5).timeoutDuration(Duration.ofSeconds(5)).build());}
}// 在控制器中使用
@RestController
@RequestMapping("/api/ai")
public class AiController {private final RateLimiter wenxinRateLimiter;@PostMapping("/wenxin")@RateLimiter(name = "wenxin-limiter")public ResponseEntity<String> wenxinChat(@RequestBody AiRequest request) {// ...}
}

八、應用入口 (AiIntegrationApplication.java)

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

九、測試示例

使用cURL測試:

# 通義千問測試
curl -X POST http://localhost:8080/api/ai/qianwen \-H "Content-Type: application/json" \-d '{"prompt": "用100字介紹Spring Boot"}'# 文心一言測試
curl -X POST http://localhost:8080/api/ai/wenxin \-H "Content-Type: application/json" \-d '{"prompt": "用Java寫一個快速排序算法"}'# 訊飛星火測試
curl -X POST http://localhost:8080/api/ai/xinghuo \-H "Content-Type: application/json" \-d '{"prompt": "如何做好電商運營"}'

十、最佳實踐建議

  1. 異步處理:使用@Async注解異步調用AI接口,避免阻塞
  2. 緩存結果:對常見問題的結果進行緩存,減少API調用
  3. 錯誤重試:實現指數退避重試機制處理臨時錯誤
  4. 流量控制:針對不同AI平臺設置不同的QPS限制
  5. 統一接口:創建統一的AI門面服務,提供平臺無關的調用
@Service
public class AiFacadeService {private enum AiProvider { WENXIN, QIANWEN, XINGHUO }private final WenxinService wenxinService;private final QianwenService qianwenService;private final XinghuoService xinghuoService;public String unifiedChat(String prompt) {// 簡單輪詢策略AiProvider[] providers = AiProvider.values();AiProvider provider = providers[(int)(System.currentTimeMillis() % providers.length)];switch (provider) {case WENXIN: return wenxinService.chatCompletion(prompt);case QIANWEN: return qianwenService.generateText(prompt);case XINGHUO: return xinghuoService.chat(prompt);default: throw new IllegalStateException("未知的AI提供商");}}
}

本項目提供了完整的企業級Spring Boot集成國內主流AI平臺的實現方案,可根據實際需求進行擴展和優化。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/87152.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/87152.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/87152.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Elastic Search 學習筆記

1. Elasticsearch 是什么&#xff1f;有哪些應用場景&#xff1f; Elasticsearch 整體原理流程&#xff1f; Elasticsearch 是一個為海量數據提供近實時搜索和分析能力的分布式搜索引擎&#xff0c;廣泛應用于全文檢索、日志分析和大數據處理場景中。 Elasticsearch 整體原理…

動態規劃之斐波那契數(一)

解法一&#xff1a;遞歸 class Solution { public:int fib(int n) {if(n<2) return n;return fib(n-1)fib(n-2);} }; 解法二&#xff1a;dp class Solution { public:int fib(int N) {if (N < 1) return N;int dp[2];dp[0] 0;dp[1] 1;for (int i 2; i < N; i) {…

如何設置爬蟲的訪問頻率?

設置爬蟲的訪問頻率是爬蟲開發中的一個重要環節&#xff0c;尤其是在爬取大型網站&#xff08;如1688&#xff09;時&#xff0c;合理的訪問頻率可以避免對目標網站造成過大負擔&#xff0c;同時也能降低被封禁的風險。以下是一些常見的方法和建議&#xff0c;幫助你合理設置爬…

前端面試六之axios

一、axios簡介 Axios 是一個基于 Promise 的 HTTP 客戶端&#xff0c;用于瀏覽器和 Node.js 環境。在瀏覽器端&#xff0c;Axios 的底層實現是基于原生的 XMLHttpRequest&#xff08;XHR&#xff09;。它對 XHR 進行了封裝&#xff0c;增加了 Promise 支持、自動轉換 JSON 數據…

模板方法模式Template Method Pattern

模式定義 定義一個操作中算法的骨架&#xff0c;而將一些步驟延遲到子類中&#xff0c;模板方法使得子類可以不改變一個算法的結構即可重定義該算法的某些特定步驟 類行為型模式 模式結構 AbstractClass&#xff1a;抽象類ConcreteClass&#xff1a;具體子類 只有類之間的繼…

【行云流水AI筆記】游戲里面的強化學習使用場景

強化學習在游戲中的應用已從早期的棋類博弈擴展到現代復雜游戲的全流程優化&#xff0c;以下是結合最新技術進展的核心應用場景及典型案例&#xff1a; 一、競技游戲的策略突破 1. 策略博弈類游戲 代表案例&#xff1a;AlphaGo/AlphaZero&#xff08;圍棋&#xff09;、Alph…

使用Python和PyTorch框架,基于RetinaNet模型進行目標檢測,包含數據準備、模型訓練、評估指標計算和可視化

下面是一個完整的實現方案,使用Python和PyTorch框架,基于RetinaNet模型進行目標檢測,包含數據準備、模型訓練、評估指標計算和可視化。 import os import numpy as np import matplotlib.pyplot as plt import torch import torchvision from torchvision.models.detection…

springboot服務如何獲取pod當前ip方案及示例

在 Kubernetes 集群中&#xff0c;Spring Boot 服務獲取 Pod 當前 IP 的方案主要有兩種&#xff1a;通過環境變量注入 或 通過 Java 代碼動態獲取網絡接口 IP。以下是兩種方案的詳細說明及示例&#xff1a; 方案一&#xff1a;通過 Kubernetes Downward API 注入環境變量 原理…

1.MySQL三層結構

1.所謂安裝的Mysql數據庫&#xff0c;就是在電腦上安裝了一個數據庫管理系統&#xff08;【DBMS】database manage system&#xff09;&#xff0c;這個管理程序可以管理多個數據庫。 2.一個數據庫中可以創建多個表&#xff0c;以保存數據&#xff08;信息&#xff09;。【數據…

[深度學習]目標檢測基礎

目錄 一、實驗目的 二、實驗環境 三、實驗內容 3.1 LM_BoundBox 3.1.1 實驗代碼 3.1.2 實驗結果 3.2 LM_Anchor 3.2.1 實驗代碼 3.2.2 實驗結果 3.3 LM_Multiscale-object-detection 3.3.1 實驗代碼 3.3.2 實驗結果 四、實驗小結 一、實驗目的 了解python語…

ALOHA機器人平臺:低成本、高精度雙臂操作及其進展深度解析

原創1從感知決策到具身智能的技術躍遷與挑戰(基座模型與VLA模型)2ALOHA機器人平臺&#xff1a;低成本、高精度雙臂操作及其進展深度解析3(上)通用智能體與機器人Transformer&#xff1a;Gato和RT-1技術解析及與LLM Transformer的異同4(下)通用智能體與機器人Transformer&#x…

C++: 類 Class 的基礎用法

&#x1f3f7;? 標簽&#xff1a;C、面向對象、類、構造函數、成員函數、封裝、繼承、多態 &#x1f4c5; 更新時間&#xff1a;2025年6月15日 &#x1f4ac; 歡迎在評論區留言交流你的理解與疑問&#xff01; 文章目錄 前言一、什么是類&#xff1f;二、類的定義1.基本語法2.…

Java EE與Jakarta EE命名空間區別

在 Java 生態中&#xff0c;javax 和 jakarta 代表了 企業級 Java 規范&#xff08;Java EE/Jakarta EE&#xff09;的命名空間演進&#xff0c;核心區別在于歸屬權和管理組織的變更。以下是詳細對比&#xff1a; 1. 歷史背景 javax&#xff1a; 源自 Java EE&#xff08;Java …

2 Studying《Arm A715 Technical Reference Manual》

目錄 2. The Cortex?A715 core 2.1 Cortex?A715 core features 2.2 Cortex?A715 core confifiguration options 2.3 DSU-110 dependent features 2.4 Supported standards and specifications 2.6 Design tasks 3. Technical overview 3.1 Core components 3.2 Int…

使用Nodejs嘗試小程序后端服務編寫:簡單的待辦事項管理demo

文章目錄 結構demo步驟demo運行效果API測試(1) 添加待辦事項(2) 獲取所有待辦事項(3) 切換完成狀態(4) 刪除待辦事項 API測試-RESTClient一些其他的高級功能環境變量管理不同環境配置授權認證 測試需要登錄的接口保存響應測試腳本編寫自動化測試 bug解決 結構 嘗試寫一個簡單的…

CSS“多列布局”

多列布局是一種非常常見的布局方式&#xff0c;適用于內容豐富的頁面&#xff0c;如新聞網站、雜志或博客。 一、CSS多列布局概述 CSS多列布局允許我們將內容分成多個垂直列&#xff0c;使頁面布局更加靈活和多樣化。多列布局的主要屬性包括 ??column-count??、??col…

Pump上狙擊機制的功能優勢和實戰教學

加密世界的發展永遠伴隨著速度的革命。無論是新的 Token 上線&#xff0c;還是熱點項目的第一波流動性注入&#xff0c;搶先一步往往意味著利潤的幾何級增長。在這個講究「秒殺」與「先機」的賽道中&#xff0c;一項關鍵策略正悄然成為鏈上操作者的常規武器——狙擊&#xff08…

條件收斂的級數中項必須趨于 0,正負項抵消,但趨于 0 的速度不需要“足夠快”

條件收斂的級數中&#xff0c;項必須趨于 0&#xff0c;但趨于 0 的速度不需要“足夠快”的原因可以從以下幾個方面理解&#xff1a; 1. 收斂的必要條件&#xff1a;項趨于 0 對于任何收斂的級數&#xff08;無論是絕對收斂還是條件收斂&#xff09;&#xff0c;都必須滿足 li…

Tomcat 和 Spring MVC

Tomcat 和 Spring MVC 是 Java Web 開發中兩大核心組件&#xff0c;分別承擔不同的角色&#xff1a; 一、Tomcat 定義 Apache Tomcat 是一個開源的 Servlet 容器&#xff08;也稱為 Servlet 引擎&#xff09;&#xff0b; JSP 引擎&#xff0c;實現了 Java EE&#xff08;現稱 …

【微服務】134:SpringCloud

今天是劉小愛自學Java的第134天。 感謝你的觀看&#xff0c;謝謝你。 image 學習內容安排如下&#xff1a; SpringCloud的接觸。利用SpringCloud搭建微服務架構&#xff0c;當然這個估計要3天時間才能完成&#xff0c;今天主要是注冊中心Eureka的學習。 一、SpringCloud 微服務…