PageSourceSearch

https://yuluo-yx.github.io/assets/Spring-Cloud-Alibaba-AI-%E5%BF%AB%E9%80%9F%E4%BD%93%E9%AA%8C-DQAvOOJo.js

js yuluo-yx.github.io collected 2026-10-03 10:13:44 UTC 9,050 bytes, 307 lines download raw bytes

1const n=`---
2slug: spring-cloud-alibaba-ai-use
3title: Spring Cloud Alibaba AI 快速体验
4date: 2024-04-30 21:01:08
5authors: yuluo
6tags: [LLM, Spring AI Alibaba, Java, Spring Cloud Alibaba]
7keywords: [LLM, Spring AI Alibaba, Java, Spring Cloud Alibaba]
8---
9
10> **Spring Cloud Alibaba AI 已经迁移到 Spring AI Alibaba.**
11
12<!-- truncate -->
13
14## Spring Cloud Alibaba AI 快速体验
15
16[Spring AI](https://docs.spring.io/spring-ai/reference/0.8-SNAPSHOT/index.html) 旨在简化包含人工智能相关功能的应用程序的开发,避免不必要的复杂性。
17
18Spring AI 的核心是提供抽象,作为开发 AI 应用程序的基础。这些抽象有多种实现方式,只需极少的代码改动即可轻松实现各个大模型之间的切换。
19
20Spring AI 提供以下功能:
21
22- 支持所有主要模型提供商,例如 OpenAI、Microsoft、Amazon、Google 和 Huggingface。
23- 支持的模型类型包括“聊天”和“文本到图像”,还有更多模型类型正在开发中。
24- 跨 AI 提供商的可移植 API,用于聊天和嵌入模型。支持同步和流 API 选项。还支持下拉访问模型特定功能。
25- AI 模型输出到 POJO 的映射。
26- 支持所有主要矢量数据库提供商,例如 Azure 矢量搜索、Chroma、Milvus、Neo4j、PostgreSQL/PGVector、PineCone、Qdrant、Redis 和 Weaviate
27- 跨 Vector Store 提供商的可移植 API,包括同样可移植的新颖的类似 SQL 的元数据过滤器 API。
28- 函数调用
29- AI 模型和向量存储的 Spring Boot 自动配置和启动器。
30- 数据工程的 ETL 框架
31
32## Spring Cloud Alibaba AI
33
34Spring Cloud Alibaba AI (以下简称 SCA AI)基于 Spring AI 0.8.1 版本完成通义系列大模型的接入。
35
36DashScope灵积模型服务建立在 *模型即服务*(Model-as-a-Service,MaaS)的理念基础之上,围绕AI各领域模型,通过标准化的API提供包括模型推理、模型微调训练在内的多种模型服务。。
37
38SCA AI 目前支持的模型主要有:对话、文生图、文生语音,更多功能特性正在适配中。
39
40## 快速体验
41
42### 创建 SCA AI 应用
43
44在 pom.xml 中引入如下依赖配置:
45
46\`\`\`xml
47<dependency>
48    <groupId>com.alibaba.cloud</groupId>
49    <artifactId>spring-cloud-starter-alibaba-ai</artifactId>
50</dependency>
51
52<dependencyManagement>
53    <dependencies>
54        <dependency>
55            <groupId>com.alibaba.cloud</groupId>
56            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
57            <version>\${spring.cloud.alibaba.version}</version>
58            <type>pom</type>
59            <scope>import</scope>
60        </dependency>
61    </dependencies>
62</dependencyManagement>
63
64<!-- 因为 Spring AI 还没有正式发布到 maven 仓库,所以需要添加此配置项 目前 maven 仓库为假的。
65issue:https://github.com/spring-projects/spring-ai/issues/537
66-->
67<repositories>
68    <repository>
69        <id>spring-milestones</id>
70        <name>Spring Milestones</name>
71        <url>https://repo.spring.io/milestone</url>
72        <snapshots>
73            <enabled>false</enabled>
74        </snapshots>
75    </repository>
76    <repository>
77        <id>spring-snapshots</id>
78        <name>Spring Snapshots</name>
79        <url>https://repo.spring.io/snapshot</url>
80        <releases>
81            <enabled>false</enabled>
82        </releases>
83    </repository>
84</repositories>
85\`\`\`
86
87#### api-key 配置
88
89在正式开始体验之前,需要申请到模型的 api-key。申请地址:https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key
90
91您可以通过 DashScope 提供的方式配置 api-key,SCA AI 完全兼容 DashScope 环境变量配置 key 的方式:https://help.aliyun.com/zh/dashscope/developer-reference/api-key-settings
92
93当然也可以通过 SCA AI 中提供的如下配置项配置:
94
95\`\`\`yml
96spring:
97  cloud:
98    ai:
99      tongyi:
100        # api-key setting:
101        api-key: sk-xxxxxxxxxxxxxxxxxxx
102\`\`\`
103
104#### 聊天对话体验
105
106官方 Example:https://github.com/alibaba/spring-cloud-alibaba/tree/2023.x/spring-cloud-alibaba-examples/spring-cloud-ai-example
107
108\`\`\`java
109public class ChatService {
110
111    // 聊天客户端
112 private final ChatClient chatClient;
113 // stream 流式客户端
114 private final StreamingChatClient streamingChatClient;
115
116 @Autowired
117 public ChatService(ChatClient chatClient, StreamingChatClient streamingChatClient) {
118
119  this.chatClient = chatClient;
120  this.streamingChatClient = streamingChatClient;
121 }
122
123 @Override
124 public String normalCompletion(String message) {
125        
126  Prompt prompt = new Prompt(new UserMessage(message));
127  return chatClient.call(prompt).getResult().getOutput().getContent();
128 }
129
130 @Override
131 public Map<String, String> streamCompletion(String message) {
132        
133  StringBuilder fullContent = new StringBuilder();
134        
135  streamingChatClient.stream(new Prompt(message))
136    .flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults()))
137    .map(content -> content.getOutput().getContent())
138    .doOnNext(fullContent::append)
139    .last()
140    .map(lastContent -> Map.of(message, fullContent.toString()))
141    .block();
142  return Map.of(message, fullContent.toString());
143 }
144
145}
146\`\`\`
147
148之后,创建 controller 接口调用 service 服务:
149
150\`\`\`java
151@Autowired
152private ChatService chatService;
153
154@GetMapping("/example")
155public String completion(
156    @RequestParam(value = "message", defaultValue = "Tell me a joke")
157    String message
158) {
159
160    return chatService.completion(message);
161}
162
163@GetMapping("/stream")
164public Map<String, String> streamCompletion(
165    @RequestParam(value = "message", defaultValue = "请告诉我西红柿炖牛腩怎么做?")
166    String message
167) {
168
169    return chatService.streamCompletion(message);
170}
171\`\`\`
172
173下面进行接口测试:
174
175\`\`\`bash
176$ curl --get  --data-urlencode 'message=Tell me a joke about a cow.' http://localhost:8080/ai/example
177
178# 获得的响应如下:
179Here's a classic cow joke for you:
180
181Why did the farmer separate the chicken and the sheep from the cows?
182
183Because he wanted to have eggs-clusive relationships with his hens!
184\`\`\`
185
186#### 文生图体验
187
188\`\`\`java
189public class ImagesService {
190
191    // 图像生成客户端
192 private final ImageClient imageClient;
193
194 @Autowired
195 public ImagesService(ImageClient client) {
196
197  this.imageClient = client;
198 }
199
200 @Override
201 public ImageResponse genImg(String imgPrompt) {
202
203  var prompt = new ImagePrompt(imgPrompt);
204  return imageClient.call(prompt);
205 }
206
207}
208\`\`\`
209
210文生图对应的 controller 接口如下:
211
212\`\`\`java
213@Autowired
214private ImagesService imagesService;
215
216@GetMapping("/img")
217public ImageResponse genImg(
218    @RequestParam(value = "prompt", defaultValue = "Painting a picture of blue water and blue sky.") String imgPrompt
219) {
220
221    return imagesService.genImg(imgPrompt);
222}
223\`\`\`
224
225接口调用体验:
226
227\`\`\`bash
228$ curl http://localhost:8080/img?prompt="美女"
229
230# 响应数据为 base64 编码图片和图片网址,注意:图片 url 地址是有有效期的。
231\`\`\`
232
233点击地址我们可以看到如下生成的美女图片:
234
235![文生图体验](/img/scaai/audio.png)
236
237#### 文生语音体验
238
239\`\`\`java
240public class AudioService {
241
242 private final SpeechClient speechClient;
243
244 @Autowired
245 public AudioService(SpeechClient client) {
246
247  this.speechClient = client;
248 }
249
250 @Override
251 public String genAudio(String text) {
252
253  var resWAV = speechClient.call(text);
254  return save(resWAV, SpeechSynthesisAudioFormat.WAV.getValue());
255 }
256
257    // 辅助方法,用于将模型的响应保存到本地.
258 private String save(ByteBuffer audio, String type) {
259
260  String currentPath = System.getProperty("user.dir");
261  LocalDateTime now = LocalDateTime.now();
262  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-HH-mm-ss");
263  String fileName = currentPath + File.separator + now.format(formatter) + "." + type;
264  File file = new File(fileName);
265
266  try (FileOutputStream fos = new FileOutputStream(file)) {
267   fos.write(audio.array());
268  }
269  catch (Exception e) {
270   throw new RuntimeException(e);
271  }
272
273  return fileName;
274 }
275
276}
277\`\`\`
278
279controller 接口代码如下:
280
281\`\`\`java
282 @Autowired
283 private AudioService audioService;
284
285 @GetMapping("/audio")
286 public String genAudio(@RequestParam(value = "prompt",
287   defaultValue = "你好,Spring Cloud Alibaba AI 框架!") String prompt) {
288
289  return audioService.genAudio(prompt);
290 }
291\`\`\`
292
293调用接口体验:
294
295\`\`\`bash
296$ curl http://localhost:8080/ai/audio?prompt="你好,人工智能!"
297
298# 响应值为保存的音频路径。
299D:\\open_sources\\sca-ai\\spring-ai\\04-29-22-44-22.wav
300\`\`\`
301
302![image-20240429224559288](/img/scaai/meinv.png)
303
304至此,Spring Cloud Alibaba AI 提供的三种基本功能已经体验完成,后续您还可以通过设置一些个性化的参数来使大模型生成各种各样的图片和音频等。
305
306更多配置项可以参考:https://help.aliyun.com/zh/dashscope/developer-reference/api-details。社区相关的文档正在完善,更多功能正在开发中!
307`;export{n as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.