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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈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博客