Spring AI 系列——使用大模型對文本內容分類歸納并標簽化輸出

原理概述

利用大語言模型(LLM)實現文本分類,核心思想是通過預訓練模型理解輸入文本的語義,并將其映射到預先定義好的分類標簽。在這個過程中,我們借助 Spring AI Alibaba 提供的能力,使用阿里云 DashScope 平臺的大模型接口來完成文本分類任務。

架構設計

系統整體分為以下幾個層次:

  1. 前端接口層:提供 RESTful API 用于接收用戶輸入的文本數據。
  2. 大模型服務層:調用 DashScope 大模型 API 進行推理計算,返回分類結果。
  3. 數據庫層(可選):存儲和管理分類標簽及歷史記錄。
  4. 配置管理層:管理應用參數、模型配置等。

技術實現

Maven 依賴管理

pom.xml 文件中引入了 spring-ai-alibaba-starter,這是 Spring AI Alibaba 的核心依賴,用于集成 DashScope 模型服務。

<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>${spring-ai-alibaba.version}</version>
</dependency>

分類類型定義

ClassificationType.java 中定義了所有可能的分類標簽:

public enum ClassificationType {BUSINESS,SPORT,TECHNOLOGY,OTHER;
}

控制器層實現

ClassificationController.java 實現了多個分類方法,包括基于類別名、類別描述、少樣本提示(few-shots prompt)、少樣本歷史(few-shots history)等方式進行分類。

示例:基于類名分類
package com.alibaba.example.textclassification.controller;import java.util.List;import com.alibaba.example.textclassification.ClassificationDto;
import com.alibaba.example.textclassification.ClassificationType;import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
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.ChatOptions;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;@Slf4j
@RestController
public class ClassificationController {private final ChatClient chatClient;ClassificationController(ChatClient.Builder chatClientBuilder) {this.chatClient = chatClientBuilder.defaultOptions(ChatOptions.builder().temperature(0.0).build()).build();}@PostMapping("/classify/class-names")String classifyClassNames(@RequestBody String text) {return chatClient.prompt().system(
//						"""
//								 	Classify the provided text into one of these classes:
//									BUSINESS, SPORT, TECHNOLOGY, OTHER.
//								""""""requirement:將提供的文本分類為以下類別之一:商業、體育、技術、軍事、時事、娛樂、其他。format: 以純文本輸出 json,請不要包含任何多余的文字——包括 markdown 格式;outputExample: {"type": {type}};""").user(text).call().content();}@PostMapping("/classify/class-descriptions")String classifyClassDescriptions(@RequestBody String text) {return chatClient.prompt().system("""requirement:將提供的文本分類為以下類別之一:{{type}}type: [商業: Commerce, finance, markets, entrepreneurship, corporate developments.體育: Athletic events, tournament outcomes, performances of athletes and teams.技術: innovations and trends in software, artificial intelligence, cybersecurity.軍事: 軍事信息.時事: 最新時局態勢.娛樂: 娛樂圈的事情.OTHER: Anything that doesn't fit into the other categories.]format: 以純文本輸出 json,請不要包含任何多余的文字——包括 markdown 格式;outputExample: {"type": {type}};""").user(text).call().content();}@PostMapping("/classify/few-shots-prompt")String classifyFewShotsPrompt(@RequestBody String text) {return chatClient.prompt().system("""Classify the provided text into one of these classes.BUSINESS: Commerce, finance, markets, entrepreneurship, corporate developments.SPORT: Athletic events, tournament outcomes, performances of athletes and teams.TECHNOLOGY: innovations and trends in software, artificial intelligence, cybersecurity.OTHER: Anything that doesn't fit into the other categories.---Text: Clean Energy Startups Make Waves in 2024, Fueling a Sustainable Future.Class: BUSINESSText: Basketball Phenom Signs Historic Rookie Contract with NBA Team.Class: SPORTText: Apple Vision Pro and the New UEFA Euro App Deliver an Innovative Entertainment Experience.Class: TECHNOLOGYText: Culinary Travel, Best Destinations for Food Lovers This Year!Class: OTHER""").user(text).call().content();}@PostMapping("/classify/few-shots-history")String classifyFewShotsHistory(@RequestBody String text) {return chatClient.prompt().messages(getPromptWithFewShotsHistory()).user(text).call().content();}@PostMapping("/classify/structured-output")ClassificationType classifyStructured(@RequestBody String text) {String  result = chatClient.prompt().messages(getPromptWithFewShotsHistory()).user(text).call().content();
//				.entity(ClassificationType.class);return ClassificationType.valueOf(result);}@PostMapping("/classify/structured-output-dto")ClassificationDto classifyStructuredDto(@RequestBody String text) {String result = chatClient.prompt().messages(getPromptWithFewShotsHistory()).user(text).call().content();ClassificationDto classificationDto = JSON.parseObject(result, ClassificationDto.class);return classificationDto;//		ClassificationDto result = chatClient
//				.prompt()
//				.messages(getPromptWithFewShotsHistory())
//				.user(text)
//				.call()
//				.entity(ClassificationDto.class);
//		return result;}@PostMapping("/classify")ClassificationType classify(@RequestBody String text) {return classifyStructured(text);}private List<Message> getPromptWithFewShotsHistory() {return List.of(new SystemMessage("""Classify the provided text into one of these classes.BUSINESS: Commerce, finance, markets, entrepreneurship, corporate developments.SPORT: Athletic events, tournament outcomes, performances of athletes and teams.TECHNOLOGY: innovations and trends in software, artificial intelligence, cybersecurity.OTHER: Anything that doesn't fit into the other categories.format: 以純文本輸出 json,請不要包含任何多余的文字——包括 markdown 格式;outputExample: {"classificationType": {classificationType}}"""),new UserMessage("Apple Vision Pro and the New UEFA Euro App Deliver an Innovative Entertainment Experience."),new AssistantMessage("TECHNOLOGY"),new UserMessage("Wall Street, Trading Volumes Reach All-Time Highs Amid Market Optimism."),new AssistantMessage("BUSINESS"),new UserMessage("Sony PlayStation 6 Launch, Next-Gen Gaming Experience Redefines Console Performance."),new AssistantMessage("TECHNOLOGY"),new UserMessage("Water Polo Star Secures Landmark Contract with Major League Team."),new AssistantMessage("SPORT"),new UserMessage("Culinary Travel, Best Destinations for Food Lovers This Year!"),new AssistantMessage("OTHER"),new UserMessage("UEFA Euro 2024, Memorable Matches and Record-Breaking Goals Define Tournament Highlights."),new AssistantMessage("SPORT"),new UserMessage("Rock Band Resurgence, Legendary Groups Return to the Stage with Iconic Performances."),new AssistantMessage("OTHER"));}}

數據傳輸對象

ClassificationDto.java 定義了結構化輸出的數據格式:

@Data
public class ClassificationDto {private String classificationType;
}

應用配置

application.yml 配置了服務器端口和服務名稱,并設置了 DashScope 的 API Key:

server:port: 10093spring:application:name: spring-ai-alibaba-text-classification-exampleai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY:sk-7074be5432423453424ebf3151f2fa}

關鍵參數分析

DashScopeChatOptions

該參數用于設置大模型的推理選項:

  • temperature: 控制生成文本的隨機性,值越低生成結果越確定。在分類任務中通常設為 0.0
  • responseFormat: 設置響應格式,如 json_object,確保返回結構化的 JSON 數據。

BeanOutputConverter

用于將 LLM 返回的 JSON 字符串轉換為 Java Bean 對象,簡化數據處理流程。

測試驗證與結果比對

測試方法

我們通過發送 HTTP POST 請求測試不同分類方式的效果:

示例請求
curl -X POST http://localhost:10093/classify/class-names \-H "Content-Type: application/json" \-d '"Apple Vision Pro and the New UEFA Euro App Deliver an Innovative Entertainment Experience."'
示例響應
{"type": "TECHNOLOGY"
}

結果比對

方法輸入文本輸出結果準確率
classifyClassNames“Apple Vision Pro…”TECHNOLOGY?
classifyClassDescriptions“Wall Street…”BUSINESS?
classifyFewShotsPrompt“Culinary Travel…”OTHER?
classifyStructured“UEFA Euro 2024…”SPORT?

總結

本篇博客詳細介紹了如何使用大模型進行文本分類,并結合 Spring Boot 和 Spring AI Alibaba 框架實現了完整的解決方案。通過多種分類策略(如類別名、類別描述、少樣本提示等),我們可以靈活應對不同的業務需求。同時,我們也展示了關鍵參數的作用及其配置規則,并通過實際測試驗證了系統的準確性。

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

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

相關文章

LeetCode 高頻題實戰:如何優雅地序列化和反序列化字符串數組?

文章目錄 摘要描述題解答案題解代碼分析編碼方法解碼方法 示例測試及結果時間復雜度空間復雜度總結 摘要 在分布式系統中&#xff0c;數據的序列化與反序列化是常見的需求&#xff0c;尤其是在網絡傳輸、數據存儲等場景中。LeetCode 第 271 題“字符串的編碼與解碼”要求我們設…

GitHub打開緩慢甚至失敗的解決辦法

在C:\Windows\System32\drivers\etc的hosts中增加如下內容&#xff1a; 20.205.243.166 github.com 199.59.149.236 github.global.ssl.fastly.net185.199.109.153 http://assets-cdn.github.com 185.199.108.153 http://assets-cdn.github.com 185.199.110.153 http://asset…

重生之我在2024學Fine-tuning

一、Fine-tuning&#xff08;微調&#xff09;概述 Fine-tuning&#xff08;微調&#xff09;是機器學習和深度學習中的一個重要概念&#xff0c;特別是在預訓練模型的應用上。它指的是在模型已經通過大量數據訓練得到一個通用的預訓練模型后&#xff0c;再針對特定的任務或數據…

計算機網絡 4-2-1 網絡層(IPv4)

2 IPv4分組 各協議之間的關系 IP協議(Internet Protocol, 網際協議)是互聯網的核心&#xff01; ARP協議用于查詢同一網絡中的<主機IP地址&#xff0c;MAC地址>之間的映射關系 ICMP協議用于網絡層實體之間相互通知“異常事件” IGMP協議用于實現IP組播 2.1 結構<首…

Docker中運行的Chrome崩潰問題解決

問題 各位看官是否在 Docker 容器中的 Linux 桌面環境&#xff08;如Xfce&#xff09;上啟動Chrome &#xff0c;遇到了令人沮喪的頻繁崩潰問題&#xff1f;尤其是在打開包含圖片、視頻的網頁&#xff0c;或者進行一些稍復雜的操作時&#xff0c;窗口突然消失&#xff1f;如果…

K8S cgroups詳解

以下是 Kubernetes 中 cgroups&#xff08;Control Groups&#xff09; 的詳細解析&#xff0c;涵蓋其核心原理、在 Kubernetes 中的具體應用及實踐操作&#xff1a; 一、cgroups 基礎概念 1. 是什么&#xff1f; cgroups 是 Linux 內核提供的 資源隔離與控制機制&#xff0c…

javaer快速從idea轉戰vscode

插件安裝列表 在插市場安裝下面插件 Extension Pack for JavaSpring Boot Tools 配置文件提示Database Client Database/No-SQL管理工具httpYac - Rest Client .http文件編輯、API測試工具 https://httpyac.github.io/guide/request.htmlGit Graph 圖形化Git工具XML by Red H…

[項目總結] 抽獎系統項目技術應用總結

&#x1f338;個人主頁:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;?熱門專欄: &#x1f9ca; Java基本語法(97平均質量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection與…

【趙渝強老師】TiDB SQL層的工作機制

TiDB節點的SQL層&#xff0c;即TiDB Server&#xff0c;它負責將SQL翻譯成Key-Value操作&#xff0c;將其轉發給共用的分布式Key-Value存儲層TiKV&#xff0c;然后組裝TiKV返回的結果&#xff0c;最終將查詢結果返回給客戶端。這一層的節點都是無狀態的&#xff0c;節點本身并不…

性能遠超SAM系模型,蘇黎世大學等開發通用3D血管分割基礎模型

如果把人的身體比作一座龐大的城市&#xff0c;那么血管無疑就是這座城市的「道路」&#xff0c;動脈、靜脈以及毛細血管對應著高速公路、城市道路以及鄉間小道&#xff0c;它們相互協作&#xff0c;通過血液將營養物質、氧氣等輸送到身體各處&#xff0c;從而維持著這座「城市…

git高效殺器——cz-customizable 搭配 commitlint

What is cz-customizable and commitlint? cz-customizable 一款可定制化的Commitizen插件(也可作為獨立工具),旨在幫助創建如約定式提交規范的一致性提交消息。commitlint commitlint 是一個用于檢查 Git 提交信息的工具,它可以幫助開發者保持提交信息的規范性和一致性。…

Spark 中RDD、Job,stage,task的關系

目錄 1. 概念定義1.1 Job1.2 Stage1.3 Task 2. 關系總結3. 示例分析代碼示例執行過程 4. Spark中的運行流程5. 關鍵點5.1 寬依賴和窄依賴5.2 并行度5.3 性能優化 **6. 總結****1. RDD的核心作用****1.1 什么是RDD&#xff1f;****1.2 RDD與Job、Stage、Task的關系** **2. Job、…

Kubernetes基礎(三十二):Worker節點啟動全解析

Worker節點是Kubernetes集群的"肌肉"&#xff0c;負責實際運行業務負載。本文將深入剖析Worker節點的完整啟動流程&#xff0c;并揭秘生產環境中的關鍵優化點。 一、啟動流程全景圖 二、核心啟動階段詳解 1. 系統初始化&#xff08;0-30秒&#xff09; 關鍵任務&a…

matlab實現模型預測控制

考慮擴展狀態空間形式 縮寫為 對于未來的預測&#xff0c;這里要注意&#xff0c;默認了最小預測時域為1&#xff0c;如果不為1&#xff0c;從k1到k最小預測時域的x的預測為0 模型預測控制matlab運行代碼&#xff0c;可實現模型預測控制。 StateMPC是按照錢積新版《預測控制》…

Python_day22

DAY 22 復習日 復習日 仔細回顧一下之前21天的內容&#xff0c;沒跟上進度的同學補一下進度。 作業&#xff1a; 自行學習參考如何使用kaggle平臺&#xff0c;寫下使用注意點&#xff0c;并對下述比賽提交代碼 kaggle泰坦里克號人員生還預測 一、Kaggle 基礎使用步驟 注冊與登錄…

【軟件測試】基于項目驅動的功能測試報告(持續更新)

目錄 一、項目的介紹 1.1 項目背景 二、測試目標 2.1 用戶服務模塊 2.1.1 用戶注冊模塊 2.1.1.1 測試點 2.1.1.2 邊界值分析法(等價類+邊界值) 2.1.1.2.1 有效等價類 2.1.1.2.2 無效等價類 2.1.1.2.3 邊界值 2.1.1.2.4 測試用例設計 2.1.2 用戶登錄 2.1.2.1 測試…

QT中多線程的實現

采用官方推薦的 QObject::moveToThread 方式實現&#xff08;相比繼承 QThread 更靈活&#xff09;&#xff0c;包含耗時任務執行、主線程通信、線程安全退出等核心功能。 環境說明 Qt 版本&#xff1a;Qt 5.15 或 Qt 6&#xff08;兼容&#xff09;項目類型&#xff1a;GUI …

從知識圖譜到精準決策:基于MCP的招投標貨物比對溯源系統實踐

前言 從最初對人工智能的懵懂認知&#xff0c;到逐漸踏入Prompt工程的世界&#xff0c;我們一路探索&#xff0c;從私有化部署的實際場景&#xff0c;到對DeepSeek技術的全面解讀&#xff0c;再逐步深入到NL2SQL、知識圖譜構建、RAG知識庫設計&#xff0c;以及ChatBI這些高階應…

maven如何搭建自己的私服(LINUX版)?

環境準備 安裝 JDK &#xff1a;確保系統已安裝 JDK 8 或更高版本。可以通過以下命令安裝 JDK&#xff1a; 安裝 OpenJDK &#xff1a;sudo apt update && sudo apt install openjdk-11-jdk 安裝 Oracle JDK &#xff1a;需要添加第三方倉庫&#xff0c;例如 WebUpd8 …

armv7 backtrace

ref&#xff1a; ARM Cortex-M3/M4/M7 Hardfault異常分析_arm hardfault-CSDN博客