Commit 246c233253f2a78a321d2aa4e139bfa3675f49ab

Authored by YunaiV
1 parent c5db9306

【优化】AI:通义千问的集成,从自己集成,换成 spring cloud alibaba ai 库

Showing 53 changed files with 4723 additions and 489 deletions
yudao-module-ai/yudao-module-ai-biz/src/main/java/cn/iocoder/yudao/module/ai/service/chat/AiChatMessageServiceImpl.java
... ... @@ -4,7 +4,6 @@ import cn.hutool.core.collection.CollUtil;
4 4 import cn.hutool.core.util.ObjUtil;
5 5 import cn.hutool.core.util.StrUtil;
6 6 import cn.iocoder.yudao.framework.ai.core.enums.AiPlatformEnum;
7   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenOptions;
8 7 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.XingHuoChatModel;
9 8 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.XingHuoOptions;
10 9 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
... ... @@ -23,6 +22,7 @@ import cn.iocoder.yudao.module.ai.enums.ErrorCodeConstants;
23 22 import cn.iocoder.yudao.module.ai.service.model.AiApiKeyService;
24 23 import cn.iocoder.yudao.module.ai.service.model.AiChatModelService;
25 24 import cn.iocoder.yudao.module.ai.service.model.AiChatRoleService;
  25 +import com.alibaba.cloud.ai.tongyi.chat.TongYiChatOptions;
26 26 import jakarta.annotation.Resource;
27 27 import lombok.extern.slf4j.Slf4j;
28 28 import org.springframework.ai.chat.messages.*;
... ... @@ -198,8 +198,7 @@ public class AiChatMessageServiceImpl implements AiChatMessageService {
198 198 return new XingHuoOptions().setChatModel(XingHuoChatModel.valueOfModel(model)).setTemperature(temperatureF)
199 199 .setMaxTokens(maxTokens);
200 200 case QIAN_WEN:
201   - // TODO @fan:增加 model、temperature 参数
202   - return new QianWenOptions().setMaxTokens(maxTokens);
  201 + return TongYiChatOptions.builder().withModel(model).withTemperature(temperature).withMaxTokens(maxTokens).build();
203 202 default:
204 203 throw new IllegalArgumentException(StrUtil.format("未知平台({})", platform));
205 204 }
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/pom.xml
... ... @@ -51,10 +51,11 @@
51 51 </dependency>
52 52  
53 53 <!-- 阿里云 通义千问 -->
  54 + <!-- TODO 芋艿:等 spring cloud alibaba ai 发布最新的时候,可以替换掉这个依赖,并且删除我们直接 cv 的代码 -->
54 55 <dependency>
55 56 <groupId>com.alibaba</groupId>
56 57 <artifactId>dashscope-sdk-java</artifactId>
57   - <version>2.11.0</version>
  58 + <version>2.14.0</version>
58 59 </dependency>
59 60  
60 61 <dependency>
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/config/YudaoAiAutoConfiguration.java
... ... @@ -4,18 +4,16 @@ import cn.iocoder.yudao.framework.ai.core.factory.AiClientFactory;
4 4 import cn.iocoder.yudao.framework.ai.core.factory.AiClientFactoryImpl;
5 5 import cn.iocoder.yudao.framework.ai.core.model.midjourney.api.MidjourneyApi;
6 6 import cn.iocoder.yudao.framework.ai.core.model.suno.api.SunoApi;
7   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenChatClient;
8   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenChatModal;
9   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenOptions;
10   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.api.QianWenApi;
11 7 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.XingHuoChatClient;
12 8 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.XingHuoOptions;
13 9 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.api.XingHuoApi;
  10 +import com.alibaba.cloud.ai.tongyi.TongYiAutoConfiguration;
14 11 import lombok.extern.slf4j.Slf4j;
15 12 import org.springframework.boot.autoconfigure.AutoConfiguration;
16 13 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
17 14 import org.springframework.boot.context.properties.EnableConfigurationProperties;
18 15 import org.springframework.context.annotation.Bean;
  16 +import org.springframework.context.annotation.Import;
19 17  
20 18 /**
21 19 * 芋道 AI 自动配置
... ... @@ -25,6 +23,7 @@ import org.springframework.context.annotation.Bean;
25 23 @AutoConfiguration
26 24 @EnableConfigurationProperties(YudaoAiProperties.class)
27 25 @Slf4j
  26 +@Import(TongYiAutoConfiguration.class)
28 27 public class YudaoAiAutoConfiguration {
29 28  
30 29 @Bean
... ... @@ -55,27 +54,6 @@ public class YudaoAiAutoConfiguration {
55 54 }
56 55  
57 56 @Bean
58   - @ConditionalOnProperty(value = "yudao.ai.qianwen.enable", havingValue = "true")
59   - public QianWenChatClient qianWenChatClient(YudaoAiProperties yudaoAiProperties) {
60   - YudaoAiProperties.QianWenProperties qianWenProperties = yudaoAiProperties.getQianwen();
61   - // 转换配置
62   - QianWenOptions qianWenOptions = new QianWenOptions();
63   -// qianWenOptions.setModel(qianWenProperties.getModel().getModel()); TODO @fan:这里报错了
64   - qianWenOptions.setTemperature(qianWenProperties.getTemperature());
65   -// qianWenOptions.setTopK(qianWenProperties.getTopK()); TODO 芋艿:后续弄
66   - qianWenOptions.setTopP(qianWenProperties.getTopP());
67   - qianWenOptions.setMaxTokens(qianWenProperties.getMaxTokens());
68   -// qianWenOptions.setTemperature(qianWenProperties.getTemperature()); TODO 芋艿:后续弄
69   - return new QianWenChatClient(
70   - new QianWenApi(
71   - qianWenProperties.getApiKey(),
72   - QianWenChatModal.QWEN_72B_CHAT
73   - ),
74   - qianWenOptions
75   - );
76   - }
77   -
78   - @Bean
79 57 @ConditionalOnProperty(value = "yudao.ai.midjourney.enable", havingValue = "true")
80 58 public MidjourneyApi midjourneyApi(YudaoAiProperties yudaoAiProperties) {
81 59 YudaoAiProperties.MidjourneyProperties config = yudaoAiProperties.getMidjourney();
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/config/YudaoAiProperties.java
1 1 package cn.iocoder.yudao.framework.ai.config;
2 2  
3 3 import cn.iocoder.yudao.framework.ai.core.enums.AiPlatformEnum;
4   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenChatModal;
5 4 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.XingHuoChatModel;
6 5 import lombok.Data;
7 6 import lombok.experimental.Accessors;
... ... @@ -20,7 +19,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
20 19 @ConfigurationProperties(prefix = "yudao.ai")
21 20 public class YudaoAiProperties {
22 21  
23   - private QianWenProperties qianwen;
24 22 private XingHuoProperties xinghuo;
25 23 private OpenAiImageProperties openAiImage;
26 24 private MidjourneyProperties midjourney;
... ... @@ -46,21 +44,6 @@ public class YudaoAiProperties {
46 44 }
47 45  
48 46 @Data
49   - @Accessors(chain = true)
50   - public static class QianWenProperties extends ChatProperties {
51   -
52   - /**
53   - * api key
54   - */
55   - private String apiKey;
56   - /**
57   - * model
58   - */
59   - private QianWenChatModal model;
60   -
61   - }
62   -
63   - @Data
64 47 public static class XingHuoProperties extends ChatProperties {
65 48  
66 49 private String appId;
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/factory/AiClientFactoryImpl.java
... ... @@ -11,11 +11,13 @@ import cn.iocoder.yudao.framework.ai.config.YudaoAiProperties;
11 11 import cn.iocoder.yudao.framework.ai.core.enums.AiPlatformEnum;
12 12 import cn.iocoder.yudao.framework.ai.core.model.midjourney.api.MidjourneyApi;
13 13 import cn.iocoder.yudao.framework.ai.core.model.suno.api.SunoApi;
14   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenChatClient;
15   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenChatModal;
16   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.api.QianWenApi;
17 14 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.XingHuoChatClient;
18 15 import cn.iocoder.yudao.framework.ai.core.model.xinghuo.api.XingHuoApi;
  16 +import com.alibaba.cloud.ai.tongyi.TongYiAutoConfiguration;
  17 +import com.alibaba.cloud.ai.tongyi.TongYiConnectionProperties;
  18 +import com.alibaba.cloud.ai.tongyi.chat.TongYiChatModel;
  19 +import com.alibaba.cloud.ai.tongyi.chat.TongYiChatProperties;
  20 +import com.alibaba.dashscope.aigc.generation.Generation;
19 21 import org.springframework.ai.autoconfigure.ollama.OllamaAutoConfiguration;
20 22 import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration;
21 23 import org.springframework.ai.autoconfigure.qianfan.QianFanAutoConfiguration;
... ... @@ -84,7 +86,7 @@ public class AiClientFactoryImpl implements AiClientFactory {
84 86 case XING_HUO:
85 87 return SpringUtil.getBean(XingHuoChatClient.class);
86 88 case QIAN_WEN:
87   - return SpringUtil.getBean(QianWenChatClient.class);
  89 + return SpringUtil.getBean(TongYiChatModel.class);
88 90 default:
89 91 throw new IllegalArgumentException(StrUtil.format("未知平台({})", platform));
90 92 }
... ... @@ -184,11 +186,16 @@ public class AiClientFactoryImpl implements AiClientFactory {
184 186 }
185 187  
186 188 /**
187   - * 可参考 {@link YudaoAiAutoConfiguration#qianWenChatClient(YudaoAiProperties)}
  189 + * 可参考 {@link TongYiAutoConfiguration#tongYiChatClient(Generation, TongYiChatProperties, TongYiConnectionProperties)}
188 190 */
189   - private static QianWenChatClient buildQianWenChatClient(String key) {
190   - QianWenApi qianWenApi = new QianWenApi(key, QianWenChatModal.QWEN_72B_CHAT);
191   - return new QianWenChatClient(qianWenApi);
  191 + private static TongYiChatModel buildQianWenChatClient(String key) {
  192 + com.alibaba.dashscope.aigc.generation.Generation generation = SpringUtil.getBean(Generation.class);
  193 + TongYiChatProperties chatOptions = SpringUtil.getBean(TongYiChatProperties.class);
  194 + // TODO @芋艿:貌似 apiKey 是全局唯一的???得测试下
  195 + // TODO @芋艿:貌似阿里云不是增量返回的
  196 + TongYiConnectionProperties connectionProperties = new TongYiConnectionProperties();
  197 + connectionProperties.setApiKey(key);
  198 + return new TongYiAutoConfiguration().tongYiChatClient(generation, chatOptions, connectionProperties);
192 199 }
193 200  
194 201 // private static VertexAiGeminiChatClient buildGoogleGemir(String key) {
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/QianWenChatClient.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi;
2   -
3   -import cn.iocoder.yudao.framework.ai.core.exception.ChatException;
4   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.api.QianWenApi;
5   -import com.alibaba.dashscope.aigc.generation.GenerationResult;
6   -import com.alibaba.dashscope.aigc.generation.models.QwenParam;
7   -import com.alibaba.dashscope.common.Message;
8   -import com.google.common.collect.Lists;
9   -import io.reactivex.Flowable;
10   -import lombok.extern.slf4j.Slf4j;
11   -import org.jetbrains.annotations.NotNull;
12   -import org.springframework.ai.chat.model.ChatModel;
13   -import org.springframework.ai.chat.model.ChatResponse;
14   -import org.springframework.ai.chat.model.Generation;
15   -import org.springframework.ai.chat.model.StreamingChatModel;
16   -import org.springframework.ai.chat.prompt.ChatOptions;
17   -import org.springframework.ai.chat.prompt.Prompt;
18   -import org.springframework.http.ResponseEntity;
19   -import org.springframework.retry.RetryCallback;
20   -import org.springframework.retry.RetryContext;
21   -import org.springframework.retry.RetryListener;
22   -import org.springframework.retry.support.RetryTemplate;
23   -import reactor.core.publisher.Flux;
24   -
25   -import java.time.Duration;
26   -import java.util.List;
27   -import java.util.stream.Collectors;
28   -
29   -// TODO @芋艿:暂时不需要重构;等 spring cloud alibaba 的 ai 发布最新的
30   -/**
31   - * 阿里 通义千问 client
32   - * <p>
33   - * 文档地址:https://help.aliyun.com/document_detail/2587494.html?spm=a2c4g.2587492.0.0.53f33c566sXskp
34   - * <p>
35   - * author: fansili
36   - * time: 2024/3/13 21:06
37   - */
38   -@Slf4j
39   -public class QianWenChatClient implements ChatModel, StreamingChatModel {
40   -
41   - private QianWenApi qianWenApi;
42   -
43   - private QianWenOptions qianWenOptions;
44   -
45   - public QianWenChatClient() {
46   - }
47   -
48   - public QianWenChatClient(QianWenApi qianWenApi) {
49   - this.qianWenApi = qianWenApi;
50   - }
51   -
52   - public QianWenChatClient(QianWenApi qianWenApi, QianWenOptions qianWenOptions) {
53   - this.qianWenApi = qianWenApi;
54   - this.qianWenOptions = qianWenOptions;
55   - }
56   -
57   - // TODO @fansili:看看咋公用出来,允许传入类似异常之类的参数;
58   - public final RetryTemplate retryTemplate = RetryTemplate.builder()
59   - // 最大重试次数 10
60   - .maxAttempts(10)
61   - .retryOn(Exception.class) // TODO 芋艿:临时这么写
62   - // 最大重试5次,第一次间隔3000ms,第二次3000ms * 2,第三次3000ms * 3,以此类推,最大间隔3 * 60000ms
63   - .exponentialBackoff(Duration.ofMillis(3000), 2, Duration.ofMillis(3 * 60000))
64   - .withListener(new RetryListener() {
65   - @Override
66   - public <T extends Object, E extends Throwable> void onError(RetryContext context,
67   - RetryCallback<T, E> callback, Throwable throwable) {
68   - log.warn("重试异常:" + context.getRetryCount(), throwable);
69   - }
70   - })
71   - .build();
72   -
73   - @Override
74   - public ChatResponse call(Prompt prompt) {
75   - return this.retryTemplate.execute(ctx -> {
76   - // ctx 会有重试的信息
77   - // 创建 request 请求,stream模式需要供应商支持
78   - QwenParam request = this.createRequest(prompt, false);
79   - // 调用 callWithFunctionSupport 发送请求
80   - ResponseEntity<GenerationResult> responseEntity = qianWenApi.chatCompletionEntity(request);
81   - // 获取结果封装 chatCompletion
82   - GenerationResult response = responseEntity.getBody();
83   -// if (!response.isSuccess()) {
84   -// return new ChatResponse(List.of(new Generation(String.format("failed to create completion, requestId: %s, code: %s, message: %s\n",
85   -// response.getRequestId(), response.getCode(), response.getMessage()))));
86   -// }
87   - // 转换为 Generation 返回
88   - return new ChatResponse(response.getOutput().getChoices().stream()
89   - .map(choices -> new Generation(choices.getMessage().getContent()))
90   - .collect(Collectors.toList()));
91   - });
92   - }
93   -
94   - @Override
95   - public ChatOptions getDefaultOptions() {
96   - // TODO 芋艿:需要跟进下
97   - throw new UnsupportedOperationException();
98   - }
99   -
100   - private QwenParam createRequest(Prompt prompt, boolean stream) {
101   - // 获取 ChatOptions
102   - QianWenOptions chatOptions = getChatOptions(prompt);
103   - //
104   - List<Message> messageList = Lists.newArrayList();
105   - prompt.getInstructions().stream().forEach(instruction -> {
106   - Message message = new Message();
107   - message.setRole(instruction.getMessageType().getValue());
108   - message.setContent(instruction.getContent());
109   - messageList.add(message);
110   - });
111   - return QwenParam.builder()
112   - .model(qianWenApi.getQianWenChatModal().getModel())
113   - .prompt(prompt.getContents())
114   - .messages(messageList)
115   - .maxTokens(chatOptions.getMaxTokens())
116   - .resultFormat(QwenParam.ResultFormat.MESSAGE)
117   - .topP(chatOptions.getTopP() == null ? null : Double.valueOf(chatOptions.getTopP()))
118   - .topK(chatOptions.getTopK())
119   - .temperature(chatOptions.getTemperature())
120   - // 控制流式输出模式,即后面的内容会包含已经输出的内容;设置为True,将开启增量输出模式,后面的输出不会包含已经输出的内容,您需要自行拼接整体输出
121   - .incrementalOutput(true)
122   - /* set the random seed, optional, default to 1234 if not set */
123   - .seed(100)
124   - .apiKey(qianWenApi.getApiKey())
125   - .build();
126   - }
127   -
128   - private @NotNull QianWenOptions getChatOptions(Prompt prompt) {
129   - // 两个都为null 则没有配置文件
130   - if (qianWenOptions == null && prompt.getOptions() == null) {
131   - throw new ChatException("ChatOptions 未配置参数!");
132   - }
133   - // 优先使用 Prompt 里面的 ChatOptions
134   - ChatOptions options = qianWenOptions;
135   - if (prompt.getOptions() != null) {
136   - options = (ChatOptions) prompt.getOptions();
137   - }
138   - // Prompt 里面是一个 ChatOptions,用户可以随意传入,这里做一下判断
139   - if (!(options instanceof QianWenOptions)) {
140   - throw new ChatException("Prompt 传入的不是 QianWenOptions!");
141   - }
142   - return (QianWenOptions) options;
143   - }
144   -
145   - @Override
146   - public Flux<ChatResponse> stream(Prompt prompt) {
147   - // ctx 会有重试的信息
148   - // 创建 request 请求,stream模式需要供应商支持
149   - QwenParam request = this.createRequest(prompt, true);
150   - // 调用 callWithFunctionSupport 发送请求
151   - Flowable<GenerationResult> responseResult = this.qianWenApi.chatCompletionStream(request);
152   -
153   - return Flux.create(fluxSink ->
154   - responseResult.subscribe(
155   - value -> fluxSink.next(
156   - new ChatResponse(value.getOutput().getChoices().stream()
157   - .map(choices -> new Generation(choices.getMessage().getContent()))
158   - .collect(Collectors.toList()))
159   - ),
160   - error -> fluxSink.error(error),
161   - () -> fluxSink.complete()
162   - )
163   - );
164   - }
165   -}
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/QianWenChatModal.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi;
2   -
3   -import lombok.AllArgsConstructor;
4   -import lombok.Getter;
5   -
6   -/**
7   - * 千问 chat 模型
8   - *
9   - * 模型地址:https://help.aliyun.com/document_detail/2712576.html
10   - * 模型介绍:https://help.aliyun.com/document_detail/2666503.html?spm=a2c4g.2701795.0.0.26eb34dfKzcWN4
11   - *
12   - * @author fansili
13   - * @time 2024/4/26 10:15
14   - * @since 1.0
15   - */
16   -@AllArgsConstructor
17   -@Getter
18   -public enum QianWenChatModal {
19   -
20   - // 千问付费模型
21   - QWEN_TURBO("通义千问超大规模语言模型", "qwen-turbo"),
22   - QWEN_PLUS("通义千问超大规模语言模型增强版", "qwen-plus"),
23   - QWEN_MAX("通义千问千亿级别超大规模语言模型", "qwen-max"),
24   - QWEN_MAX_0403("通义千问千亿级别超大规模语言模型-0403", "qwen-max-0403"),
25   - QWEN_MAX_0107("通义千问千亿级别超大规模语言模型-0107", "qwen-max-0107"),
26   - QWEN_MAX_1201("通义千问千亿级别超大规模语言模型-1201", "qwen-max-1201"),
27   - QWEN_MAX_LONGCONTEXT("通义千问千亿级别超大规模语言模型-28k tokens", "qwen-max-longcontext"),
28   -
29   - // 开源模型
30   - // https://help.aliyun.com/document_detail/2666503.html?spm=a2c4g.2701795.0.0.26eb34dfKzcWN4
31   - QWEN_72B_CHAT("通义千问1.5对外开源的72B规模参数量的经过人类指令对齐的chat模型", "qwen-72b-chat"),
32   -
33   - ;
34   -
35   - private String name;
36   -
37   - private String model;
38   -
39   - public static QianWenChatModal valueOfModel(String model) {
40   - for (QianWenChatModal itemEnum : QianWenChatModal.values()) {
41   - if (itemEnum.getModel().equals(model)) {
42   - return itemEnum;
43   - }
44   - }
45   - throw new IllegalArgumentException("Invalid MessageType value: " + model);
46   - }
47   -}
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/QianWenOptions.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi;
2   -
3   -import org.springframework.ai.chat.prompt.ChatOptions;
4   -import lombok.Data;
5   -import lombok.experimental.Accessors;
6   -
7   -import java.util.List;
8   -
9   -/**
10   - * 阿里云 千问 属性
11   - *
12   - * 地址:https://help.aliyun.com/document_detail/2684682.html?spm=a2c4g.2621347.0.0.195117e7Ytpkyo
13   - *
14   - * author: fansili
15   - * time: 2024/3/15 19:57
16   - */
17   -@Data
18   -@Accessors(chain = true)
19   -public class QianWenOptions implements ChatOptions {
20   -
21   - /**
22   - * 用户与模型的对话历史
23   - */
24   - private List<Message> messages;
25   - /**
26   - * 生成时,核采样方法的概率阈值。例如,取值为0.8时,仅保留累计概率之和大于等于0.8的概率分布中的token,
27   - * 作为随机采样的候选集。取值范围为(0,1.0),取值越大,生成的随机性越高;取值越低,生成的随机性越低。
28   - * 默认值为0.8。注意,取值不要大于等于1
29   - */
30   - private Float topP;
31   - /**
32   - * 用于限制模型生成token的数量,max_tokens设置的是生成上限,并不表示一定会生成这么多的token数量。其中qwen1.5-14b-chat、qwen1.5-7b-chat、qwen-14b-chat和qwen-7b-chat最大值和默认值均为1500,qwen-1.8b-chat、qwen-1.8b-longcontext-chat和qwen-72b-chat最大值和默认值均为2000
33   - */
34   - private Integer maxTokens = 1500;
35   - /**
36   - * 模型
37   - */
38   - private String model;
39   - /**
40   - * temperature
41   - */
42   - private Float temperature;
43   -
44   - //
45   - // 适配 ChatOptions
46   -
47   - @Override
48   - public Float getTemperature() {
49   - return null;
50   - }
51   -
52   - @Override
53   - public Integer getTopK() {
54   - return null;
55   - }
56   -
57   - public Float getTopP() {
58   - return topP;
59   - }
60   -
61   - @Data
62   - @Accessors
63   - public static class Message {
64   - /**
65   - * 角色: system、user或assistant
66   - */
67   - private String role;
68   - /**
69   - * 提示词或模型内容
70   - */
71   - private String content;
72   - }
73   -
74   - @Data
75   - @Accessors
76   - public static class Parameters {
77   - /**
78   - * 输出格式, 默认为"text"
79   - * "text"表示旧版本的text
80   - * "message"表示兼容openai的message
81   - */
82   - private String resultFormat;
83   - /**
84   - * 生成时,采样候选集的大小。例如,取值为50时,仅将单次生成中得分最高的50个token组成随机采样的候选集。
85   - * 取值越大,生成的随机性越高;取值越小,生成的确定性越高。
86   - * 注意:如果top_k参数为空或者top_k的值大于100,表示不启用top_k策略,此时仅有top_p策略生效,默认是空。
87   - */
88   - private Integer topK;
89   - /**
90   - * 生成时使用的随机数种子,用户控制模型生成内容的随机性。
91   - * seed支持无符号64位整数,默认值为1234。在使用seed时,模型将尽可能生成相同或相似的结果,但目前不保证每次生成的结果完全相同。
92   - */
93   - private Integer seed;
94   - /**
95   - * 用于控制随机性和多样性的程度。具体来说,temperature值控制了生成文本时对每个候选词的概率分布进行平滑的程度。
96   - * 较高的temperature值会降低概率分布的峰值,使得更多的低概率词被选择,
97   - * 生成结果更加多样化;而较低的temperature值则会增强概率分布的峰值,使得高概率词更容易被选择,生成结果更加确定。
98   - * 取值范围: [0, 2),系统默认值1.0。不建议取值为0,无意义。
99   - */
100   - private Float temperature;
101   - /**
102   - * 用于限制模型生成token的数量,max_tokens设置的是生成上限,并不表示一定会生成这么多的token数量。
103   - * 其中qwen-turbo 最大值和默认值为1500, qwen-max、qwen-max-1201 、qwen-max-longcontext 和 qwen-plus最大值和默认值均为2000。
104   - */
105   - private Integer maxTokens;
106   - /**
107   - * stop参数用于实现内容生成过程的精确控制,在生成内容即将包含指定的字符串或token_ids时自动停止,生成内容不包含指定的内容。
108   - * 例如,如果指定stop为"你好",表示将要生成"你好"时停止;如果指定stop为[37763, 367],表示将要生成"Observation"时停止。
109   - */
110   - private List<String> stop;
111   - /**
112   - * 用于控制流式输出模式,默认False,即后面内容会包含已经输出的内容;设置为True,将开启增量输出模式,
113   - * 后面输出不会包含已经输出的内容,您需要自行拼接整体输出,参考流式输出示例代码。
114   - */
115   - private Boolean incrementalOutput;
116   - }
117   -}
118   -
119   -
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/api/QianWenApi.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi.api;
2   -
3   -import cn.iocoder.yudao.framework.ai.core.model.tongyi.QianWenChatModal;
4   -import cn.iocoder.yudao.framework.ai.core.exception.AiException;
5   -import com.alibaba.dashscope.aigc.generation.Generation;
6   -import com.alibaba.dashscope.aigc.generation.GenerationResult;
7   -import com.alibaba.dashscope.aigc.generation.models.QwenParam;
8   -import com.alibaba.dashscope.exception.InputRequiredException;
9   -import com.alibaba.dashscope.exception.NoApiKeyException;
10   -import io.reactivex.Flowable;
11   -import lombok.Getter;
12   -import org.springframework.http.HttpStatusCode;
13   -import org.springframework.http.ResponseEntity;
14   -
15   -// TODO done @fansili:是不是挪到 api 包里?按照 spring ai 的结构;根目录只放 client 和 options
16   -
17   -/**
18   - * 阿里 通义千问
19   - * <p>
20   - * author: fansili
21   - * time: 2024/3/13 21:09
22   - */
23   -@Getter
24   -public class QianWenApi {
25   -
26   - // api key 获取地址:https://bailian.console.aliyun.com/?spm=5176.28197581.0.0.38db29a4G3GcVb&apiKey=1#/api-key
27   - private String apiKey = "sk-Zsd81gZYg7";
28   - private Generation gen = new Generation();
29   - private QianWenChatModal qianWenChatModal;
30   -
31   - public QianWenApi(String apiKey, QianWenChatModal qianWenChatModal) {
32   - this.apiKey = apiKey;
33   - this.qianWenChatModal = qianWenChatModal;
34   - }
35   -
36   - public ResponseEntity<GenerationResult> chatCompletionEntity(QwenParam request) {
37   - GenerationResult call;
38   - try {
39   - call = gen.call(request);
40   - } catch (NoApiKeyException e) {
41   - throw new AiException("没有找到apiKey!" + e.getMessage());
42   - } catch (InputRequiredException e) {
43   - throw new AiException("chat缺少必填字段!" + e.getMessage());
44   - }
45   - // 阿里云的这个 http code 随便设置,外面判断是否成功用的 CompletionsResponse.isSuccess
46   - return new ResponseEntity<>(call, HttpStatusCode.valueOf(200));
47   - }
48   -
49   - public Flowable<GenerationResult> chatCompletionStream(QwenParam request) {
50   - Flowable<GenerationResult> resultFlowable;
51   - try {
52   - resultFlowable = gen.streamCall(request);
53   - } catch (NoApiKeyException e) {
54   - throw new AiException("没有找到apiKey!" + e.getMessage());
55   - } catch (InputRequiredException e) {
56   - throw new AiException("chat缺少必填字段!" + e.getMessage());
57   - }
58   - return resultFlowable;
59   - }
60   -}
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/api/QianWenChatCompletion.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi.api;
2   -
3   -
4   -/**
5   - * author: fansili
6   - * time: 2024/3/13 21:07
7   - */
8   -public class QianWenChatCompletion {
9   -}
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/api/QianWenChatCompletionMessage.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi.api;
2   -
3   -/**
4   - * author: fansili
5   - * time: 2024/3/13 21:07
6   - */
7   -public class QianWenChatCompletionMessage {
8   -}
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/api/QianWenChatCompletionRequest.java deleted
1   -package cn.iocoder.yudao.framework.ai.core.model.tongyi.api;
2   -
3   -import com.alibaba.dashscope.aigc.generation.models.QwenParam;
4   -
5   -/**
6   - * 千问
7   - *
8   - * author: fansili
9   - * time: 2024/3/13 21:07
10   - */
11   -public class QianWenChatCompletionRequest extends QwenParam {
12   -
13   - protected QianWenChatCompletionRequest(QwenParamBuilder<?, ?> b) {
14   - super(b);
15   - }
16   -}
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/core/model/tongyi/package-info.java deleted
1   -/**
2   - * 阿里的 通义千问
3   - *
4   - * 链接:https://www.aliyun.com/search?k=%E9%80%9A%E4%B9%89%E5%A4%A7%E6%A8%A1%E5%9E%8B&scene=all
5   - *
6   - * 千问所有模型:https://bailian.console.aliyun.com/?spm=5176.28515448.J_TC9GqcHi2edq9zUs9ZsDQ.1.417338b17zJTjy#/efm/my_model
7   - *
8   - * author: fansili
9   - * time: 2024/3/13 21:05
10   - */
11   -package cn.iocoder.yudao.framework.ai.core.model.tongyi;
12 0 \ No newline at end of file
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/TongYiAutoConfiguration.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.speech.TongYiAudioSpeechModel;
  20 +import com.alibaba.cloud.ai.tongyi.audio.speech.TongYiAudioSpeechProperties;
  21 +import com.alibaba.cloud.ai.tongyi.audio.transcription.TongYiAudioTranscriptionModel;
  22 +import com.alibaba.cloud.ai.tongyi.audio.transcription.TongYiAudioTranscriptionProperties;
  23 +import com.alibaba.cloud.ai.tongyi.chat.TongYiChatModel;
  24 +import com.alibaba.cloud.ai.tongyi.chat.TongYiChatProperties;
  25 +import com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants;
  26 +import com.alibaba.cloud.ai.tongyi.common.exception.TongYiException;
  27 +import com.alibaba.cloud.ai.tongyi.embedding.TongYiTextEmbeddingModel;
  28 +import com.alibaba.cloud.ai.tongyi.embedding.TongYiTextEmbeddingProperties;
  29 +import com.alibaba.cloud.ai.tongyi.image.TongYiImagesModel;
  30 +import com.alibaba.cloud.ai.tongyi.image.TongYiImagesProperties;
  31 +import com.alibaba.dashscope.aigc.generation.Generation;
  32 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
  33 +import com.alibaba.dashscope.audio.asr.transcription.Transcription;
  34 +import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
  35 +import com.alibaba.dashscope.common.MessageManager;
  36 +import com.alibaba.dashscope.embeddings.TextEmbedding;
  37 +import com.alibaba.dashscope.exception.NoApiKeyException;
  38 +import com.alibaba.dashscope.utils.ApiKey;
  39 +import com.alibaba.dashscope.utils.Constants;
  40 +import org.springframework.ai.model.function.FunctionCallbackContext;
  41 +import org.springframework.boot.autoconfigure.AutoConfiguration;
  42 +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  43 +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  44 +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  45 +import org.springframework.boot.context.properties.EnableConfigurationProperties;
  46 +import org.springframework.context.ApplicationContext;
  47 +import org.springframework.context.annotation.Bean;
  48 +import org.springframework.context.annotation.Scope;
  49 +
  50 +import java.util.Objects;
  51 +
  52 +/**
  53 + * @author yuluo
  54 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  55 + * @since 2023.0.1.0
  56 + */
  57 +
  58 +@AutoConfiguration
  59 +@ConditionalOnClass({
  60 + MessageManager.class,
  61 + TongYiChatModel.class,
  62 + TongYiImagesModel.class,
  63 + TongYiAudioSpeechModel.class,
  64 + TongYiTextEmbeddingModel.class,
  65 + TongYiAudioTranscriptionModel.class
  66 +})
  67 +@EnableConfigurationProperties({
  68 + TongYiChatProperties.class,
  69 + TongYiImagesProperties.class,
  70 + TongYiAudioSpeechProperties.class,
  71 + TongYiConnectionProperties.class,
  72 + TongYiTextEmbeddingProperties.class,
  73 + TongYiAudioTranscriptionProperties.class
  74 +})
  75 +public class TongYiAutoConfiguration {
  76 +
  77 + @Bean
  78 + @Scope("prototype")
  79 + @ConditionalOnMissingBean
  80 + public Generation generation() {
  81 +
  82 + return new Generation();
  83 + }
  84 +
  85 + @Bean
  86 + @Scope("prototype")
  87 + @ConditionalOnMissingBean
  88 + public MessageManager msgManager() {
  89 +
  90 + return new MessageManager(10);
  91 + }
  92 +
  93 + @Bean
  94 + @Scope("prototype")
  95 + @ConditionalOnMissingBean
  96 + public ImageSynthesis imageSynthesis() {
  97 +
  98 + return new ImageSynthesis();
  99 + }
  100 +
  101 + @Bean
  102 + @Scope("prototype")
  103 + @ConditionalOnMissingBean
  104 + public SpeechSynthesizer speechSynthesizer() {
  105 +
  106 + return new SpeechSynthesizer();
  107 + }
  108 +
  109 + @Bean
  110 + @ConditionalOnMissingBean
  111 + public Transcription transcription() {
  112 +
  113 + return new Transcription();
  114 + }
  115 +
  116 + @Bean
  117 + @ConditionalOnMissingBean
  118 + public TextEmbedding textEmbedding() {
  119 +
  120 + return new TextEmbedding();
  121 + }
  122 +
  123 + @Bean
  124 + @ConditionalOnMissingBean
  125 + public FunctionCallbackContext springAiFunctionManager(ApplicationContext context) {
  126 +
  127 + FunctionCallbackContext manager = new FunctionCallbackContext();
  128 + manager.setApplicationContext(context);
  129 +
  130 + return manager;
  131 + }
  132 +
  133 + @Bean
  134 + @ConditionalOnProperty(
  135 + prefix = TongYiChatProperties.CONFIG_PREFIX,
  136 + name = "enabled",
  137 + havingValue = "true",
  138 + matchIfMissing = true
  139 + )
  140 + public TongYiChatModel tongYiChatClient(Generation generation,
  141 + TongYiChatProperties chatOptions,
  142 + TongYiConnectionProperties connectionProperties
  143 + ) {
  144 +
  145 + settingApiKey(connectionProperties);
  146 +
  147 + return new TongYiChatModel(generation, chatOptions.getOptions());
  148 + }
  149 +
  150 + @Bean
  151 + @ConditionalOnProperty(
  152 + prefix = TongYiImagesProperties.CONFIG_PREFIX,
  153 + name = "enabled",
  154 + havingValue = "true",
  155 + matchIfMissing = true
  156 + )
  157 + public TongYiImagesModel tongYiImagesClient(
  158 + ImageSynthesis imageSynthesis,
  159 + TongYiImagesProperties imagesOptions,
  160 + TongYiConnectionProperties connectionProperties
  161 + ) {
  162 +
  163 + settingApiKey(connectionProperties);
  164 +
  165 + return new TongYiImagesModel(imageSynthesis, imagesOptions.getOptions());
  166 + }
  167 +
  168 + @Bean
  169 + @ConditionalOnProperty(
  170 + prefix = TongYiAudioSpeechProperties.CONFIG_PREFIX,
  171 + name = "enabled",
  172 + havingValue = "true",
  173 + matchIfMissing = true
  174 + )
  175 + public TongYiAudioSpeechModel tongYiAudioSpeechClient(
  176 + SpeechSynthesizer speechSynthesizer,
  177 + TongYiAudioSpeechProperties speechProperties,
  178 + TongYiConnectionProperties connectionProperties
  179 + ) {
  180 +
  181 + settingApiKey(connectionProperties);
  182 +
  183 + return new TongYiAudioSpeechModel(speechSynthesizer, speechProperties.getOptions());
  184 + }
  185 +
  186 + @Bean
  187 + @ConditionalOnProperty(
  188 + prefix = TongYiAudioTranscriptionProperties.CONFIG_PREFIX,
  189 + name = "enabled",
  190 + havingValue = "true",
  191 + matchIfMissing = true
  192 + )
  193 + public TongYiAudioTranscriptionModel tongYiAudioTranscriptionClient(
  194 + Transcription transcription,
  195 + TongYiAudioTranscriptionProperties transcriptionProperties,
  196 + TongYiConnectionProperties connectionProperties) {
  197 +
  198 + settingApiKey(connectionProperties);
  199 +
  200 + return new TongYiAudioTranscriptionModel(
  201 + transcriptionProperties.getOptions(),
  202 + transcription
  203 + );
  204 + }
  205 +
  206 + @Bean
  207 + @ConditionalOnProperty(
  208 + prefix = TongYiTextEmbeddingProperties.CONFIG_PREFIX,
  209 + name = "enabled",
  210 + havingValue = "true",
  211 + matchIfMissing = true
  212 + )
  213 + public TongYiTextEmbeddingModel tongYiTextEmbeddingClient(
  214 + TextEmbedding textEmbedding,
  215 + TongYiConnectionProperties connectionProperties
  216 + ) {
  217 +
  218 + settingApiKey(connectionProperties);
  219 + return new TongYiTextEmbeddingModel(textEmbedding);
  220 + }
  221 +
  222 + /**
  223 + * Setting the API key.
  224 + * @param connectionProperties {@link TongYiConnectionProperties}
  225 + */
  226 + private void settingApiKey(TongYiConnectionProperties connectionProperties) {
  227 +
  228 + String apiKey;
  229 +
  230 + try {
  231 + // It is recommended to set the key by defining the api-key in an environment variable.
  232 + var envKey = System.getenv(TongYiConstants.SCA_AI_TONGYI_API_KEY);
  233 + if (Objects.nonNull(envKey)) {
  234 + Constants.apiKey = envKey;
  235 + return;
  236 + }
  237 + if (Objects.nonNull(connectionProperties.getApiKey())) {
  238 + apiKey = connectionProperties.getApiKey();
  239 + }
  240 + else {
  241 + apiKey = ApiKey.getApiKey(null);
  242 + }
  243 +
  244 + Constants.apiKey = apiKey;
  245 + }
  246 + catch (NoApiKeyException e) {
  247 +
  248 + throw new TongYiException(e.getMessage());
  249 + }
  250 +
  251 + }
  252 +
  253 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/TongYiConnectionProperties.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi;
  18 +
  19 +import org.springframework.boot.context.properties.ConfigurationProperties;
  20 +
  21 +import static com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants.SCA_AI_CONFIGURATION;
  22 +
  23 +/**
  24 + * Spring Cloud Alibaba AI TongYi LLM connection properties.
  25 + *
  26 + * @author yuluo
  27 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  28 + * @since 2023.0.1.0
  29 + */
  30 +
  31 +@ConfigurationProperties(TongYiConnectionProperties.CONFIG_PREFIX)
  32 +public class TongYiConnectionProperties {
  33 +
  34 + /**
  35 + * Spring Cloud Alibaba AI connection configuration Prefix.
  36 + */
  37 + public static final String CONFIG_PREFIX = SCA_AI_CONFIGURATION + "tongyi";
  38 +
  39 + /**
  40 + * TongYi LLM API key.
  41 + */
  42 + private String apiKey;
  43 +
  44 + public String getApiKey() {
  45 + return apiKey;
  46 + }
  47 +
  48 + public void setApiKey(String apiKey) {
  49 + this.apiKey = apiKey;
  50 + }
  51 +
  52 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/AudioSpeechModels.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio;
  18 +
  19 +/**
  20 + * More models see: https://help.aliyun.com/zh/dashscope/model-list?spm=a2c4g.11186623.0.i5
  21 + * Support all models in list.
  22 + *
  23 + * @author yuluo
  24 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  25 + * @since 2023.0.1.0
  26 + */
  27 +
  28 +public final class AudioSpeechModels {
  29 +
  30 + private AudioSpeechModels() {
  31 + }
  32 +
  33 + /**
  34 + * Male Voice of the Tongue(舌尖男声).
  35 + * zh & en.
  36 + * Default sample rate: 48 Hz.
  37 + */
  38 + public static final String SAMBERT_ZHICHU_V1 = "sambert-zhichu-v1";
  39 +
  40 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/AudioTranscriptionModels.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio;
  18 +
  19 +/**
  20 + * @author xYLiu
  21 + * @author yuluo
  22 + * @since 2023.0.1.0
  23 + */
  24 +
  25 +public final class AudioTranscriptionModels {
  26 +
  27 + private AudioTranscriptionModels() {
  28 + }
  29 +
  30 + /**
  31 + * Paraformer Chinese and English speech recognition model supports audio or video speech recognition with a sampling rate of 16kHz or above.
  32 + */
  33 + public static final String Paraformer_V1 = "paraformer-v1";
  34 + /**
  35 + * Paraformer Chinese speech recognition model, support 8kHz telephone speech recognition.
  36 + */
  37 + public static final String Paraformer_8K_V1 = "paraformer-8k-v1";
  38 + /**
  39 + * The Paraformer multilingual speech recognition model supports audio or video speech recognition with a sample rate of 16kHz or above.
  40 + */
  41 + public static final String Paraformer_MTL_V1 = "paraformer-mtl-v1";
  42 +
  43 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/TongYiAudioSpeechModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.AudioSpeechModels;
  20 +import com.alibaba.cloud.ai.tongyi.audio.speech.api.*;
  21 +import com.alibaba.cloud.ai.tongyi.metadata.audio.TongYiAudioSpeechResponseMetadata;
  22 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
  23 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
  24 +import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
  25 +import com.alibaba.dashscope.common.ResultCallback;
  26 +import io.reactivex.Flowable;
  27 +import org.slf4j.Logger;
  28 +import org.slf4j.LoggerFactory;
  29 +import org.springframework.util.Assert;
  30 +import reactor.core.publisher.Flux;
  31 +import reactor.core.scheduler.Schedulers;
  32 +
  33 +import java.nio.ByteBuffer;
  34 +
  35 +/**
  36 + * TongYiAudioSpeechClient is a client for TongYi audio speech service for Spring Cloud Alibaba AI.
  37 + *
  38 + * @author yuluo
  39 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  40 + * @since 2023.0.1.0
  41 + */
  42 +
  43 +public class TongYiAudioSpeechModel implements SpeechModel, SpeechStreamModel {
  44 +
  45 + private final Logger logger = LoggerFactory.getLogger(getClass());
  46 +
  47 + /**
  48 + * Default speed rate.
  49 + */
  50 + private static final float SPEED_RATE = 1.0f;
  51 +
  52 + /**
  53 + * TongYi models api.
  54 + */
  55 + private final SpeechSynthesizer speechSynthesizer;
  56 +
  57 + /**
  58 + * TongYi models options.
  59 + */
  60 + private final TongYiAudioSpeechOptions defaultOptions;
  61 +
  62 + /**
  63 + * TongYiAudioSpeechClient constructor.
  64 + * @param speechSynthesizer the speech synthesizer
  65 + */
  66 + public TongYiAudioSpeechModel(SpeechSynthesizer speechSynthesizer) {
  67 +
  68 + this(speechSynthesizer, null);
  69 + }
  70 +
  71 + /**
  72 + * TongYiAudioSpeechClient constructor.
  73 + * @param speechSynthesizer the speech synthesizer
  74 + * @param tongYiAudioOptions the tongYi audio options
  75 + */
  76 + public TongYiAudioSpeechModel(SpeechSynthesizer speechSynthesizer, TongYiAudioSpeechOptions tongYiAudioOptions) {
  77 +
  78 + Assert.notNull(speechSynthesizer, "speechSynthesizer must not be null");
  79 + Assert.notNull(tongYiAudioOptions, "tongYiAudioOptions must not be null");
  80 +
  81 + this.speechSynthesizer = speechSynthesizer;
  82 + this.defaultOptions = tongYiAudioOptions;
  83 + }
  84 +
  85 + /**
  86 + * Call the TongYi audio speech service.
  87 + * @param text the text message to be converted to audio.
  88 + * @return the audio byte buffer.
  89 + */
  90 + @Override
  91 + public ByteBuffer call(String text) {
  92 +
  93 + var speechRequest = new SpeechPrompt(text);
  94 +
  95 + return call(speechRequest).getResult().getOutput();
  96 + }
  97 +
  98 +
  99 + /**
  100 + * Call the TongYi audio speech service.
  101 + * @param prompt the speech prompt.
  102 + * @return the speech response.
  103 + */
  104 + @Override
  105 + public SpeechResponse call(SpeechPrompt prompt) {
  106 +
  107 + var SCASpeechParam = merge(prompt.getOptions());
  108 + var speechSynthesisParams = toSpeechSynthesisParams(SCASpeechParam);
  109 + speechSynthesisParams.setText(prompt.getInstructions().getText());
  110 + logger.info(speechSynthesisParams.toString());
  111 +
  112 + var res = speechSynthesizer.call(speechSynthesisParams);
  113 +
  114 + return convert(res, null);
  115 + }
  116 +
  117 + /**
  118 + * Call the TongYi audio speech service.
  119 + * @param prompt the speech prompt.
  120 + * @param callback the result callback.
  121 + * {@link SpeechSynthesizer#call(SpeechSynthesisParam, ResultCallback)}
  122 + */
  123 + public void call(SpeechPrompt prompt, ResultCallback<SpeechSynthesisResult> callback) {
  124 +
  125 + var SCASpeechParam = merge(prompt.getOptions());
  126 + var speechSynthesisParams = toSpeechSynthesisParams(SCASpeechParam);
  127 + speechSynthesisParams.setText(prompt.getInstructions().getText());
  128 +
  129 + speechSynthesizer.call(speechSynthesisParams, callback);
  130 + }
  131 +
  132 + /**
  133 + * Stream the TongYi audio speech service.
  134 + * @param prompt the speech prompt.
  135 + * @return the speech response.
  136 + * {@link SpeechSynthesizer#streamCall(SpeechSynthesisParam)}
  137 + */
  138 + @Override
  139 + public Flux<SpeechResponse> stream(SpeechPrompt prompt) {
  140 +
  141 + var SCASpeechParam = merge(prompt.getOptions());
  142 +
  143 + Flowable<SpeechSynthesisResult> resultFlowable = speechSynthesizer
  144 + .streamCall(toSpeechSynthesisParams(SCASpeechParam));
  145 +
  146 + return Flux.from(resultFlowable)
  147 + .flatMap(
  148 + res -> Flux.just(res.getAudioFrame())
  149 + .map(audio -> {
  150 + var speech = new Speech(audio);
  151 + var respMetadata = TongYiAudioSpeechResponseMetadata.from(res);
  152 + return new SpeechResponse(speech, respMetadata);
  153 + })
  154 + ).publishOn(Schedulers.parallel());
  155 + }
  156 +
  157 + public TongYiAudioSpeechOptions merge(TongYiAudioSpeechOptions target) {
  158 +
  159 + var mergeBuilder = TongYiAudioSpeechOptions.builder();
  160 +
  161 + mergeBuilder.withModel(defaultOptions.getModel() != null ? defaultOptions.getModel() : target.getModel());
  162 + mergeBuilder.withPitch(defaultOptions.getPitch() != null ? defaultOptions.getPitch() : target.getPitch());
  163 + mergeBuilder.withRate(defaultOptions.getRate() != null ? defaultOptions.getRate() : target.getRate());
  164 + mergeBuilder.withFormat(defaultOptions.getFormat() != null ? defaultOptions.getFormat() : target.getFormat());
  165 + mergeBuilder.withSampleRate(defaultOptions.getSampleRate() != null ? defaultOptions.getSampleRate() : target.getSampleRate());
  166 + mergeBuilder.withTextType(defaultOptions.getTextType() != null ? defaultOptions.getTextType() : target.getTextType());
  167 + mergeBuilder.withVolume(defaultOptions.getVolume() != null ? defaultOptions.getVolume() : target.getVolume());
  168 + mergeBuilder.withEnablePhonemeTimestamp(defaultOptions.isEnablePhonemeTimestamp() != null ? defaultOptions.isEnablePhonemeTimestamp() : target.isEnablePhonemeTimestamp());
  169 + mergeBuilder.withEnableWordTimestamp(defaultOptions.isEnableWordTimestamp() != null ? defaultOptions.isEnableWordTimestamp() : target.isEnableWordTimestamp());
  170 +
  171 + return mergeBuilder.build();
  172 + }
  173 +
  174 + public SpeechSynthesisParam toSpeechSynthesisParams(TongYiAudioSpeechOptions source) {
  175 +
  176 + var mergeBuilder = SpeechSynthesisParam.builder();
  177 +
  178 + mergeBuilder.model(source.getModel() != null ? source.getModel() : AudioSpeechModels.SAMBERT_ZHICHU_V1);
  179 + mergeBuilder.text(source.getText() != null ? source.getText() : "");
  180 +
  181 + if (source.getFormat() != null) {
  182 + mergeBuilder.format(source.getFormat());
  183 + }
  184 + if (source.getRate() != null) {
  185 + mergeBuilder.rate(source.getRate());
  186 + }
  187 + if (source.getPitch() != null) {
  188 + mergeBuilder.pitch(source.getPitch());
  189 + }
  190 + if (source.getTextType() != null) {
  191 + mergeBuilder.textType(source.getTextType());
  192 + }
  193 + if (source.getSampleRate() != null) {
  194 + mergeBuilder.sampleRate(source.getSampleRate());
  195 + }
  196 + if (source.isEnablePhonemeTimestamp() != null) {
  197 + mergeBuilder.enablePhonemeTimestamp(source.isEnablePhonemeTimestamp());
  198 + }
  199 + if (source.isEnableWordTimestamp() != null) {
  200 + mergeBuilder.enableWordTimestamp(source.isEnableWordTimestamp());
  201 + }
  202 + if (source.getVolume() != null) {
  203 + mergeBuilder.volume(source.getVolume());
  204 + }
  205 +
  206 + return mergeBuilder.build();
  207 + }
  208 +
  209 + /**
  210 + * Convert the TongYi audio speech service result to the speech response.
  211 + * @param result the audio byte buffer.
  212 + * @param synthesisResult the synthesis result.
  213 + * @return the speech response.
  214 + */
  215 + private SpeechResponse convert(ByteBuffer result, SpeechSynthesisResult synthesisResult) {
  216 +
  217 + if (synthesisResult == null) {
  218 +
  219 + return new SpeechResponse(new Speech(result));
  220 + }
  221 +
  222 + var responseMetadata = TongYiAudioSpeechResponseMetadata.from(synthesisResult);
  223 + var speech = new Speech(synthesisResult.getAudioFrame());
  224 +
  225 + return new SpeechResponse(speech, responseMetadata);
  226 + }
  227 +
  228 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/TongYiAudioSpeechOptions.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.AudioSpeechModels;
  20 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
  21 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisTextType;
  22 +import org.springframework.ai.model.ModelOptions;
  23 +
  24 +/**
  25 + * @author yuluo
  26 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  27 + * @since 2023.0.1.0
  28 + */
  29 +
  30 +public class TongYiAudioSpeechOptions implements ModelOptions {
  31 +
  32 +
  33 + /**
  34 + * Audio Speech models.
  35 + */
  36 + private String model = AudioSpeechModels.SAMBERT_ZHICHU_V1;
  37 +
  38 + /**
  39 + * Text content.
  40 + */
  41 + private String text;
  42 +
  43 + /**
  44 + * Input text type.
  45 + */
  46 + private SpeechSynthesisTextType textType = SpeechSynthesisTextType.PLAIN_TEXT;
  47 +
  48 + /**
  49 + * synthesis audio format.
  50 + */
  51 + private SpeechSynthesisAudioFormat format = SpeechSynthesisAudioFormat.WAV;
  52 +
  53 + /**
  54 + * synthesis audio sample rate.
  55 + */
  56 + private Integer sampleRate = 16000;
  57 +
  58 + /**
  59 + * synthesis audio volume.
  60 + */
  61 + private Integer volume = 50;
  62 +
  63 + /**
  64 + * synthesis audio speed.
  65 + */
  66 + private Float rate = 1.0f;
  67 +
  68 + /**
  69 + * synthesis audio pitch.
  70 + */
  71 + private Float pitch = 1.0f;
  72 +
  73 + /**
  74 + * enable word level timestamp.
  75 + */
  76 + private Boolean enableWordTimestamp = false;
  77 +
  78 + /**
  79 + * enable phoneme level timestamp.
  80 + */
  81 + private Boolean enablePhonemeTimestamp = false;
  82 +
  83 + public static Builder builder() {
  84 + return new Builder();
  85 + }
  86 +
  87 + public String getModel() {
  88 +
  89 + return model;
  90 + }
  91 +
  92 + public void setModel(String model) {
  93 +
  94 + this.model = model;
  95 + }
  96 +
  97 + public String getText() {
  98 +
  99 + return text;
  100 + }
  101 +
  102 + public void setText(String text) {
  103 +
  104 + this.text = text;
  105 + }
  106 +
  107 + public SpeechSynthesisTextType getTextType() {
  108 +
  109 + return textType;
  110 + }
  111 +
  112 + public void setTextType(SpeechSynthesisTextType textType) {
  113 +
  114 + this.textType = textType;
  115 + }
  116 +
  117 + public SpeechSynthesisAudioFormat getFormat() {
  118 +
  119 + return format;
  120 + }
  121 +
  122 + public void setFormat(SpeechSynthesisAudioFormat format) {
  123 +
  124 + this.format = format;
  125 + }
  126 +
  127 + public Integer getSampleRate() {
  128 +
  129 + return sampleRate;
  130 + }
  131 +
  132 + public void setSampleRate(Integer sampleRate) {
  133 +
  134 + this.sampleRate = sampleRate;
  135 + }
  136 +
  137 + public Integer getVolume() {
  138 +
  139 + return volume;
  140 + }
  141 +
  142 + public void setVolume(Integer volume) {
  143 +
  144 + this.volume = volume;
  145 + }
  146 +
  147 + public Float getRate() {
  148 +
  149 + return rate;
  150 + }
  151 +
  152 + public void setRate(Float rate) {
  153 +
  154 + this.rate = rate;
  155 + }
  156 +
  157 + public Float getPitch() {
  158 +
  159 + return pitch;
  160 + }
  161 +
  162 + public void setPitch(Float pitch) {
  163 +
  164 + this.pitch = pitch;
  165 + }
  166 +
  167 + public Boolean isEnableWordTimestamp() {
  168 +
  169 + return enableWordTimestamp;
  170 + }
  171 +
  172 + public void setEnableWordTimestamp(Boolean enableWordTimestamp) {
  173 +
  174 + this.enableWordTimestamp = enableWordTimestamp;
  175 + }
  176 +
  177 + public Boolean isEnablePhonemeTimestamp() {
  178 +
  179 + return enablePhonemeTimestamp;
  180 + }
  181 +
  182 + public void setEnablePhonemeTimestamp(Boolean enablePhonemeTimestamp) {
  183 +
  184 + this.enablePhonemeTimestamp = enablePhonemeTimestamp;
  185 + }
  186 +
  187 + /**
  188 + * Build a options instances.
  189 + */
  190 + public static class Builder {
  191 +
  192 + private final TongYiAudioSpeechOptions options = new TongYiAudioSpeechOptions();
  193 +
  194 + public Builder withModel(String model) {
  195 +
  196 + options.model = model;
  197 + return this;
  198 + }
  199 +
  200 + public Builder withText(String text) {
  201 +
  202 + options.text = text;
  203 + return this;
  204 + }
  205 +
  206 + public Builder withTextType(SpeechSynthesisTextType textType) {
  207 +
  208 + options.textType = textType;
  209 + return this;
  210 + }
  211 +
  212 + public Builder withFormat(SpeechSynthesisAudioFormat format) {
  213 +
  214 + options.format = format;
  215 + return this;
  216 + }
  217 +
  218 + public Builder withSampleRate(Integer sampleRate) {
  219 +
  220 + options.sampleRate = sampleRate;
  221 + return this;
  222 + }
  223 +
  224 + public Builder withVolume(Integer volume) {
  225 +
  226 + options.volume = volume;
  227 + return this;
  228 + }
  229 +
  230 + public Builder withRate(Float rate) {
  231 +
  232 + options.rate = rate;
  233 + return this;
  234 + }
  235 +
  236 + public Builder withPitch(Float pitch) {
  237 +
  238 + options.pitch = pitch;
  239 + return this;
  240 + }
  241 +
  242 + public Builder withEnableWordTimestamp(Boolean enableWordTimestamp) {
  243 +
  244 + options.enableWordTimestamp = enableWordTimestamp;
  245 + return this;
  246 + }
  247 +
  248 + public Builder withEnablePhonemeTimestamp(Boolean enablePhonemeTimestamp) {
  249 +
  250 + options.enablePhonemeTimestamp = enablePhonemeTimestamp;
  251 + return this;
  252 + }
  253 +
  254 + public TongYiAudioSpeechOptions build() {
  255 +
  256 + return options;
  257 + }
  258 +
  259 + }
  260 +
  261 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/TongYiAudioSpeechProperties.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.AudioSpeechModels;
  20 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
  21 +import org.springframework.boot.context.properties.ConfigurationProperties;
  22 +import org.springframework.boot.context.properties.NestedConfigurationProperty;
  23 +
  24 +import static com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants.SCA_AI_CONFIGURATION;
  25 +
  26 +/**
  27 + * TongYi audio speech configuration properties.
  28 + *
  29 + * @author yuluo
  30 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  31 + * @since 2023.0.1.0
  32 + */
  33 +
  34 +@ConfigurationProperties(TongYiAudioSpeechProperties.CONFIG_PREFIX)
  35 +public class TongYiAudioSpeechProperties {
  36 +
  37 + /**
  38 + * Spring Cloud Alibaba AI configuration prefix.
  39 + */
  40 + public static final String CONFIG_PREFIX = SCA_AI_CONFIGURATION + "audio.speech";
  41 + /**
  42 + * Default TongYi Chat model.
  43 + */
  44 + public static final String DEFAULT_AUDIO_MODEL_NAME = AudioSpeechModels.SAMBERT_ZHICHU_V1;
  45 +
  46 + /**
  47 + * Enable TongYiQWEN ai audio client.
  48 + */
  49 + private boolean enabled = true;
  50 +
  51 + @NestedConfigurationProperty
  52 + private TongYiAudioSpeechOptions options = TongYiAudioSpeechOptions.builder()
  53 + .withModel(DEFAULT_AUDIO_MODEL_NAME)
  54 + .withFormat(SpeechSynthesisAudioFormat.WAV)
  55 + .build();
  56 +
  57 + public TongYiAudioSpeechOptions getOptions() {
  58 +
  59 + return this.options;
  60 + }
  61 +
  62 + public void setOptions(TongYiAudioSpeechOptions options) {
  63 +
  64 + this.options = options;
  65 + }
  66 +
  67 + public boolean isEnabled() {
  68 +
  69 + return this.enabled;
  70 + }
  71 +
  72 + public void setEnabled(boolean enabled) {
  73 +
  74 + this.enabled = enabled;
  75 + }
  76 +
  77 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/Speech.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import org.springframework.ai.model.ModelResult;
  20 +import org.springframework.lang.Nullable;
  21 +
  22 +import java.nio.ByteBuffer;
  23 +import java.util.Arrays;
  24 +import java.util.Objects;
  25 +
  26 +/**
  27 + * @author yuluo
  28 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  29 + * @since 2023.0.1.0
  30 + */
  31 +
  32 +public class Speech implements ModelResult<ByteBuffer> {
  33 +
  34 + private final ByteBuffer audio;
  35 +
  36 + private SpeechMetadata speechMetadata;
  37 +
  38 + public Speech(ByteBuffer audio) {
  39 + this.audio = audio;
  40 + }
  41 +
  42 + @Override
  43 + public ByteBuffer getOutput() {
  44 + return this.audio;
  45 + }
  46 +
  47 + @Override
  48 + public SpeechMetadata getMetadata() {
  49 +
  50 + return speechMetadata != null ? speechMetadata : SpeechMetadata.NULL;
  51 + }
  52 +
  53 + public Speech withSpeechMetadata(@Nullable SpeechMetadata speechMetadata) {
  54 +
  55 + this.speechMetadata = speechMetadata;
  56 + return this;
  57 + }
  58 +
  59 + @Override
  60 + public boolean equals(Object o) {
  61 +
  62 + if (this == o) {
  63 +
  64 + return true;
  65 + }
  66 + if (!(o instanceof Speech that)) {
  67 +
  68 + return false;
  69 + }
  70 +
  71 + return Arrays.equals(audio.array(), that.audio.array())
  72 + && Objects.equals(speechMetadata, that.speechMetadata);
  73 + }
  74 +
  75 + @Override
  76 + public int hashCode() {
  77 +
  78 + return Objects.hash(Arrays.hashCode(audio.array()), speechMetadata);
  79 + }
  80 +
  81 + @Override
  82 + public String toString() {
  83 +
  84 + return "Speech{" + "text=" + audio + ", speechMetadata=" + speechMetadata + '}';
  85 + }
  86 +
  87 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/SpeechMessage.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import java.util.Objects;
  20 +
  21 +/**
  22 + * The {@link SpeechMessage} class represents a single text message to
  23 + * be converted to speech by the TongYi LLM TTS.
  24 + *
  25 + * @author yuluo
  26 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  27 + * @since 2023.0.1.0
  28 + */
  29 +
  30 +public class SpeechMessage {
  31 +
  32 + private String text;
  33 +
  34 + /**
  35 + * Constructs a new {@link SpeechMessage} object with the given text.
  36 + * @param text the text to be converted to speech
  37 + */
  38 + public SpeechMessage(String text) {
  39 + this.text = text;
  40 + }
  41 +
  42 + /**
  43 + * Returns the text of this speech message.
  44 + * @return the text of this speech message
  45 + */
  46 + public String getText() {
  47 + return text;
  48 + }
  49 +
  50 + /**
  51 + * Sets the text of this speech message.
  52 + * @param text the new text for this speech message
  53 + */
  54 + public void setText(String text) {
  55 + this.text = text;
  56 + }
  57 +
  58 + @Override
  59 + public boolean equals(Object o) {
  60 +
  61 + if (this == o) {
  62 +
  63 + return true;
  64 + }
  65 +
  66 + if (!(o instanceof SpeechMessage that)) {
  67 +
  68 + return false;
  69 + }
  70 +
  71 + return Objects.equals(text, that.text);
  72 + }
  73 +
  74 + @Override
  75 + public int hashCode() {
  76 +
  77 + return Objects.hash(text);
  78 + }
  79 +
  80 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/SpeechMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import org.springframework.ai.model.ResultMetadata;
  20 +
  21 +/**
  22 + * @author yuluo
  23 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  24 + * @since 2023.0.1.0
  25 + */
  26 +
  27 +public interface SpeechMetadata extends ResultMetadata {
  28 +
  29 + /**
  30 + * Null Object.
  31 + */
  32 + SpeechMetadata NULL = SpeechMetadata.create();
  33 +
  34 + /**
  35 + * Factory method used to construct a new {@link SpeechMetadata}.
  36 + * @return a new {@link SpeechMetadata}
  37 + */
  38 + static SpeechMetadata create() {
  39 + return new SpeechMetadata() {
  40 + };
  41 + }
  42 +
  43 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/SpeechModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import org.springframework.ai.model.Model;
  20 +
  21 +import java.nio.ByteBuffer;
  22 +
  23 +/**
  24 + * @author yuluo
  25 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  26 + * @since 2023.0.0.0-RC1
  27 + */
  28 +
  29 +@FunctionalInterface
  30 +public interface SpeechModel extends Model<SpeechPrompt, SpeechResponse> {
  31 +
  32 + /**
  33 + * Generates spoken audio from the provided text message.
  34 + * @param message the text message to be converted to audio.
  35 + * @return the resulting audio bytes.
  36 + */
  37 + default ByteBuffer call(String message) {
  38 +
  39 + SpeechPrompt prompt = new SpeechPrompt(message);
  40 +
  41 + return call(prompt).getResult().getOutput();
  42 + }
  43 +
  44 + /**
  45 + * Sends a speech request to the TongYi TTS API and returns the resulting speech response.
  46 + * @param request the speech prompt containing the input text and other parameters.
  47 + * @return the speech response containing the generated audio.
  48 + */
  49 + SpeechResponse call(SpeechPrompt request);
  50 +
  51 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/SpeechPrompt.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.speech.TongYiAudioSpeechOptions;
  20 +import org.springframework.ai.model.ModelRequest;
  21 +
  22 +import java.util.Objects;
  23 +
  24 +/**
  25 + * @author yuluo
  26 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  27 + * @since 2023.0.1.0
  28 + */
  29 +
  30 +public class SpeechPrompt implements ModelRequest<SpeechMessage> {
  31 +
  32 + private TongYiAudioSpeechOptions speechOptions;
  33 +
  34 + private final SpeechMessage message;
  35 +
  36 + public SpeechPrompt(String instructions) {
  37 +
  38 + this(new SpeechMessage(instructions), TongYiAudioSpeechOptions.builder().build());
  39 + }
  40 +
  41 + public SpeechPrompt(String instructions, TongYiAudioSpeechOptions speechOptions) {
  42 +
  43 + this(new SpeechMessage(instructions), speechOptions);
  44 + }
  45 +
  46 + public SpeechPrompt(SpeechMessage speechMessage) {
  47 + this(speechMessage, TongYiAudioSpeechOptions.builder().build());
  48 + }
  49 +
  50 + public SpeechPrompt(SpeechMessage speechMessage, TongYiAudioSpeechOptions speechOptions) {
  51 +
  52 + this.message = speechMessage;
  53 + this.speechOptions = speechOptions;
  54 + }
  55 +
  56 + @Override
  57 + public SpeechMessage getInstructions() {
  58 + return this.message;
  59 + }
  60 +
  61 + @Override
  62 + public TongYiAudioSpeechOptions getOptions() {
  63 +
  64 + return speechOptions;
  65 + }
  66 +
  67 + @Override
  68 + public boolean equals(Object o) {
  69 +
  70 + if (this == o) {
  71 +
  72 + return true;
  73 + }
  74 + if (!(o instanceof SpeechPrompt that)) {
  75 +
  76 + return false;
  77 + }
  78 +
  79 + return Objects.equals(speechOptions, that.speechOptions) && Objects.equals(message, that.message);
  80 + }
  81 +
  82 + @Override
  83 + public int hashCode() {
  84 +
  85 + return Objects.hash(speechOptions, message);
  86 + }
  87 +
  88 +
  89 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/SpeechResponse.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.metadata.audio.TongYiAudioSpeechResponseMetadata;
  20 +import org.springframework.ai.model.ModelResponse;
  21 +
  22 +import java.util.Collections;
  23 +import java.util.List;
  24 +import java.util.Objects;
  25 +
  26 +/**
  27 + * @author yuluo
  28 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  29 + * @since 2023.0.1.0
  30 + */
  31 +
  32 +public class SpeechResponse implements ModelResponse<Speech> {
  33 +
  34 + private final Speech speech;
  35 +
  36 + private final TongYiAudioSpeechResponseMetadata speechResponseMetadata;
  37 +
  38 + /**
  39 + * Creates a new instance of SpeechResponse with the given speech result.
  40 + * @param speech the speech result to be set in the SpeechResponse
  41 + * @see Speech
  42 + */
  43 + public SpeechResponse(Speech speech) {
  44 + this(speech, TongYiAudioSpeechResponseMetadata.NULL);
  45 + }
  46 +
  47 + /**
  48 + * Creates a new instance of SpeechResponse with the given speech result and speech
  49 + * response metadata.
  50 + * @param speech the speech result to be set in the SpeechResponse
  51 + * @param speechResponseMetadata the speech response metadata to be set in the
  52 + * SpeechResponse
  53 + * @see Speech
  54 + * @see TongYiAudioSpeechResponseMetadata
  55 + */
  56 + public SpeechResponse(Speech speech, TongYiAudioSpeechResponseMetadata speechResponseMetadata) {
  57 +
  58 + this.speech = speech;
  59 + this.speechResponseMetadata = speechResponseMetadata;
  60 + }
  61 +
  62 + @Override
  63 + public Speech getResult() {
  64 + return speech;
  65 + }
  66 +
  67 + @Override
  68 + public List<Speech> getResults() {
  69 + return Collections.singletonList(speech);
  70 + }
  71 +
  72 + @Override
  73 + public TongYiAudioSpeechResponseMetadata getMetadata() {
  74 + return speechResponseMetadata;
  75 + }
  76 +
  77 + @Override
  78 + public boolean equals(Object o) {
  79 +
  80 + if (this == o) {
  81 +
  82 + return true;
  83 + }
  84 + if (!(o instanceof SpeechResponse that)) {
  85 +
  86 + return false;
  87 + }
  88 +
  89 + return Objects.equals(speech, that.speech)
  90 + && Objects.equals(speechResponseMetadata, that.speechResponseMetadata);
  91 + }
  92 +
  93 + @Override
  94 + public int hashCode() {
  95 +
  96 + return Objects.hash(speech, speechResponseMetadata);
  97 + }
  98 +
  99 +
  100 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/speech/api/SpeechStreamModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.speech.api;
  18 +
  19 +import org.springframework.ai.model.StreamingModel;
  20 +import reactor.core.publisher.Flux;
  21 +
  22 +import java.nio.ByteBuffer;
  23 +
  24 +/**
  25 + * @author yuluo
  26 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  27 + * @since 2023.0.1.0
  28 + */
  29 +
  30 +@FunctionalInterface
  31 +public interface SpeechStreamModel extends StreamingModel<SpeechPrompt, SpeechResponse> {
  32 +
  33 + /**
  34 + * Generates a stream of audio bytes from the provided text message.
  35 + *
  36 + * @param message the text message to be converted to audio
  37 + * @return a Flux of audio bytes representing the generated speech
  38 + */
  39 + default Flux<ByteBuffer> stream(String message) {
  40 +
  41 + SpeechPrompt prompt = new SpeechPrompt(message);
  42 + return stream(prompt).map(SpeechResponse::getResult).map(Speech::getOutput);
  43 + }
  44 +
  45 + /**
  46 + * Sends a speech request to the TongYi TTS API and returns a stream of the resulting
  47 + * speech responses.
  48 + * @param prompt the speech prompt containing the input text and other parameters.
  49 + * @return a Flux of speech responses, each containing a portion of the generated audio.
  50 + */
  51 + @Override
  52 + Flux<SpeechResponse> stream(SpeechPrompt prompt);
  53 +
  54 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/transcription/TongYiAudioTranscriptionModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.transcription;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.AudioTranscriptionModels;
  20 +import com.alibaba.cloud.ai.tongyi.audio.transcription.api.AudioTranscriptionPrompt;
  21 +import com.alibaba.cloud.ai.tongyi.audio.transcription.api.AudioTranscriptionResponse;
  22 +import com.alibaba.cloud.ai.tongyi.audio.transcription.api.AudioTranscriptionResult;
  23 +import com.alibaba.cloud.ai.tongyi.common.exception.TongYiException;
  24 +import com.alibaba.cloud.ai.tongyi.metadata.audio.TongYiAudioTranscriptionResponseMetadata;
  25 +import com.alibaba.dashscope.audio.asr.transcription.*;
  26 +import org.springframework.ai.model.Model;
  27 +import org.springframework.core.io.Resource;
  28 +import org.springframework.util.Assert;
  29 +
  30 +import java.io.IOException;
  31 +import java.util.ArrayList;
  32 +import java.util.Arrays;
  33 +import java.util.List;
  34 +import java.util.stream.Collectors;
  35 +
  36 +/**
  37 + * TongYiAudioTranscriptionModel is a client for TongYi audio transcription service for
  38 + * Spring Cloud Alibaba AI.
  39 + * @author xYLiu
  40 + * @author yuluo
  41 + * @since 2023.0.1.0
  42 + */
  43 +
  44 +public class TongYiAudioTranscriptionModel
  45 + implements Model<AudioTranscriptionPrompt, AudioTranscriptionResponse> {
  46 +
  47 + /**
  48 + * TongYi models options.
  49 + */
  50 + private final TongYiAudioTranscriptionOptions defaultOptions;
  51 +
  52 + /**
  53 + * TongYi models api.
  54 + */
  55 + private final Transcription transcription;
  56 +
  57 + public TongYiAudioTranscriptionModel(Transcription transcription) {
  58 + this(null, transcription);
  59 + }
  60 +
  61 + public TongYiAudioTranscriptionModel(TongYiAudioTranscriptionOptions defaultOptions,
  62 + Transcription transcription) {
  63 + Assert.notNull(transcription, "transcription must not be null");
  64 + Assert.notNull(defaultOptions, "defaultOptions must not be null");
  65 +
  66 + this.defaultOptions = defaultOptions;
  67 + this.transcription = transcription;
  68 + }
  69 +
  70 + @Override
  71 + public AudioTranscriptionResponse call(AudioTranscriptionPrompt prompt) {
  72 +
  73 + TranscriptionParam transcriptionParam;
  74 +
  75 + if (prompt.getOptions() != null) {
  76 + var param = merge(prompt.getOptions());
  77 + transcriptionParam = toTranscriptionParam(param);
  78 + transcriptionParam.setFileUrls(prompt.getOptions().getFileUrls());
  79 + }
  80 + else {
  81 + Resource instructions = prompt.getInstructions();
  82 + try {
  83 + transcriptionParam = TranscriptionParam.builder()
  84 + .model(AudioTranscriptionModels.Paraformer_V1)
  85 + .fileUrls(List.of(String.valueOf(instructions.getURL())))
  86 + .build();
  87 + }
  88 + catch (IOException e) {
  89 + throw new TongYiException("Failed to create resource", e);
  90 + }
  91 + }
  92 +
  93 + List<TranscriptionTaskResult> taskResultList;
  94 + try {
  95 + // Submit a transcription request
  96 + TranscriptionResult result = transcription.asyncCall(transcriptionParam);
  97 + // Wait for the transcription to complete
  98 + result = transcription.wait(TranscriptionQueryParam
  99 + .FromTranscriptionParam(transcriptionParam, result.getTaskId()));
  100 + // Get the transcription results
  101 + System.out.println(result.getOutput().getAsJsonObject());
  102 + taskResultList = result.getResults();
  103 + System.out.println(Arrays.toString(taskResultList.toArray()));
  104 +
  105 + return new AudioTranscriptionResponse(
  106 + taskResultList.stream().map(taskResult ->
  107 + new AudioTranscriptionResult(taskResult.getTranscriptionUrl())
  108 + ).collect(Collectors.toList()),
  109 + TongYiAudioTranscriptionResponseMetadata.from(result)
  110 + );
  111 + }
  112 + catch (Exception e) {
  113 + throw new TongYiException("Failed to call audio transcription", e);
  114 + }
  115 +
  116 + }
  117 +
  118 + public TongYiAudioTranscriptionOptions merge(TongYiAudioTranscriptionOptions target) {
  119 + var mergeBuilder = TongYiAudioTranscriptionOptions.builder();
  120 +
  121 + mergeBuilder
  122 + .withModel(defaultOptions.getModel() != null ? defaultOptions.getModel()
  123 + : target.getModel());
  124 + mergeBuilder.withChannelId(
  125 + defaultOptions.getChannelId() != null ? defaultOptions.getChannelId()
  126 + : target.getChannelId());
  127 + mergeBuilder.withDiarizationEnabled(defaultOptions.getDiarizationEnabled() != null
  128 + ? defaultOptions.getDiarizationEnabled()
  129 + : target.getDiarizationEnabled());
  130 + mergeBuilder.withDisfluencyRemovalEnabled(
  131 + defaultOptions.getDisfluencyRemovalEnabled() != null
  132 + ? defaultOptions.getDisfluencyRemovalEnabled()
  133 + : target.getDisfluencyRemovalEnabled());
  134 + mergeBuilder.withTimestampAlignmentEnabled(
  135 + defaultOptions.getTimestampAlignmentEnabled() != null
  136 + ? defaultOptions.getTimestampAlignmentEnabled()
  137 + : target.getTimestampAlignmentEnabled());
  138 + mergeBuilder.withSpecialWordFilter(defaultOptions.getSpecialWordFilter() != null
  139 + ? defaultOptions.getSpecialWordFilter()
  140 + : target.getSpecialWordFilter());
  141 + mergeBuilder.withAudioEventDetectionEnabled(
  142 + defaultOptions.getAudioEventDetectionEnabled() != null
  143 + ? defaultOptions.getAudioEventDetectionEnabled()
  144 + : target.getAudioEventDetectionEnabled());
  145 +
  146 + return mergeBuilder.build();
  147 + }
  148 +
  149 + public TranscriptionParam toTranscriptionParam(
  150 + TongYiAudioTranscriptionOptions source) {
  151 + var mergeBuilder = TranscriptionParam.builder();
  152 +
  153 + mergeBuilder.model(source.getModel() != null ? source.getModel()
  154 + : AudioTranscriptionModels.Paraformer_V1);
  155 + mergeBuilder.fileUrls(
  156 + source.getFileUrls() != null ? source.getFileUrls() : new ArrayList<>());
  157 + if (source.getPhraseId() != null) {
  158 + mergeBuilder.phraseId(source.getPhraseId());
  159 + }
  160 + if (source.getChannelId() != null) {
  161 + mergeBuilder.channelId(source.getChannelId());
  162 + }
  163 + if (source.getDiarizationEnabled() != null) {
  164 + mergeBuilder.diarizationEnabled(source.getDiarizationEnabled());
  165 + }
  166 + if (source.getSpeakerCount() != null) {
  167 + mergeBuilder.speakerCount(source.getSpeakerCount());
  168 + }
  169 + if (source.getDisfluencyRemovalEnabled() != null) {
  170 + mergeBuilder.disfluencyRemovalEnabled(source.getDisfluencyRemovalEnabled());
  171 + }
  172 + if (source.getTimestampAlignmentEnabled() != null) {
  173 + mergeBuilder.timestampAlignmentEnabled(source.getTimestampAlignmentEnabled());
  174 + }
  175 + if (source.getSpecialWordFilter() != null) {
  176 + mergeBuilder.specialWordFilter(source.getSpecialWordFilter());
  177 + }
  178 + if (source.getAudioEventDetectionEnabled() != null) {
  179 + mergeBuilder
  180 + .audioEventDetectionEnabled(source.getAudioEventDetectionEnabled());
  181 + }
  182 +
  183 + return mergeBuilder.build();
  184 + }
  185 +
  186 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/transcription/TongYiAudioTranscriptionOptions.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.transcription;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.AudioTranscriptionModels;
  20 +import org.springframework.ai.model.ModelOptions;
  21 +
  22 +import java.util.ArrayList;
  23 +import java.util.Collections;
  24 +import java.util.List;
  25 +
  26 +/**
  27 + * @author xYLiu
  28 + * @author yuluo
  29 + * @since 2023.0.1.0
  30 + */
  31 +
  32 +public class TongYiAudioTranscriptionOptions implements ModelOptions {
  33 +
  34 + private String model = AudioTranscriptionModels.Paraformer_V1;
  35 +
  36 + private List<String> fileUrls = new ArrayList<>();
  37 +
  38 + private String phraseId = null;
  39 +
  40 + private List<Integer> channelId = Collections.singletonList(0);
  41 +
  42 + private Boolean diarizationEnabled = false;
  43 +
  44 + private Integer speakerCount = null;
  45 +
  46 + private Boolean disfluencyRemovalEnabled = false;
  47 +
  48 + private Boolean timestampAlignmentEnabled = false;
  49 +
  50 + private String specialWordFilter = "";
  51 +
  52 + private Boolean audioEventDetectionEnabled = false;
  53 +
  54 + public static Builder builder() {
  55 +
  56 + return new Builder();
  57 + }
  58 +
  59 + public String getModel() {
  60 + return model;
  61 + }
  62 +
  63 + public void setModel(String model) {
  64 + this.model = model;
  65 + }
  66 +
  67 + public List<String> getFileUrls() {
  68 + return fileUrls;
  69 + }
  70 +
  71 + public void setFileUrls(List<String> fileUrls) {
  72 + this.fileUrls = fileUrls;
  73 + }
  74 +
  75 + public String getPhraseId() {
  76 + return phraseId;
  77 + }
  78 +
  79 + public void setPhraseId(String phraseId) {
  80 + this.phraseId = phraseId;
  81 + }
  82 +
  83 + public List<Integer> getChannelId() {
  84 + return channelId;
  85 + }
  86 +
  87 + public void setChannelId(List<Integer> channelId) {
  88 + this.channelId = channelId;
  89 + }
  90 +
  91 + public Boolean getDiarizationEnabled() {
  92 + return diarizationEnabled;
  93 + }
  94 +
  95 + public void setDiarizationEnabled(Boolean diarizationEnabled) {
  96 + this.diarizationEnabled = diarizationEnabled;
  97 + }
  98 +
  99 + public Integer getSpeakerCount() {
  100 + return speakerCount;
  101 + }
  102 +
  103 + public void setSpeakerCount(Integer speakerCount) {
  104 + this.speakerCount = speakerCount;
  105 + }
  106 +
  107 + public Boolean getDisfluencyRemovalEnabled() {
  108 + return disfluencyRemovalEnabled;
  109 + }
  110 +
  111 + public void setDisfluencyRemovalEnabled(Boolean disfluencyRemovalEnabled) {
  112 + this.disfluencyRemovalEnabled = disfluencyRemovalEnabled;
  113 + }
  114 +
  115 + public Boolean getTimestampAlignmentEnabled() {
  116 + return timestampAlignmentEnabled;
  117 + }
  118 +
  119 + public void setTimestampAlignmentEnabled(Boolean timestampAlignmentEnabled) {
  120 + this.timestampAlignmentEnabled = timestampAlignmentEnabled;
  121 + }
  122 +
  123 + public String getSpecialWordFilter() {
  124 + return specialWordFilter;
  125 + }
  126 +
  127 + public void setSpecialWordFilter(String specialWordFilter) {
  128 + this.specialWordFilter = specialWordFilter;
  129 + }
  130 +
  131 + public Boolean getAudioEventDetectionEnabled() {
  132 + return audioEventDetectionEnabled;
  133 + }
  134 +
  135 + public void setAudioEventDetectionEnabled(Boolean audioEventDetectionEnabled) {
  136 + this.audioEventDetectionEnabled = audioEventDetectionEnabled;
  137 + }
  138 +
  139 + /**
  140 + * Builder class for constructing TongYiAudioTranscriptionOptions instances.
  141 + */
  142 + public static class Builder {
  143 +
  144 + private final TongYiAudioTranscriptionOptions options = new TongYiAudioTranscriptionOptions();
  145 +
  146 + public Builder withModel(String model) {
  147 + options.model = model;
  148 + return this;
  149 + }
  150 +
  151 + public Builder withFileUrls(List<String> fileUrls) {
  152 + options.fileUrls = fileUrls;
  153 + return this;
  154 + }
  155 +
  156 + public Builder withPhraseId(String phraseId) {
  157 + options.phraseId = phraseId;
  158 + return this;
  159 + }
  160 +
  161 + public Builder withChannelId(List<Integer> channelId) {
  162 + options.channelId = channelId;
  163 + return this;
  164 + }
  165 +
  166 + public Builder withDiarizationEnabled(Boolean diarizationEnabled) {
  167 + options.diarizationEnabled = diarizationEnabled;
  168 + return this;
  169 + }
  170 +
  171 + public Builder withSpeakerCount(Integer speakerCount) {
  172 + options.speakerCount = speakerCount;
  173 + return this;
  174 + }
  175 +
  176 + public Builder withDisfluencyRemovalEnabled(Boolean disfluencyRemovalEnabled) {
  177 + options.disfluencyRemovalEnabled = disfluencyRemovalEnabled;
  178 + return this;
  179 + }
  180 +
  181 + public Builder withTimestampAlignmentEnabled(Boolean timestampAlignmentEnabled) {
  182 + options.timestampAlignmentEnabled = timestampAlignmentEnabled;
  183 + return this;
  184 + }
  185 +
  186 + public Builder withSpecialWordFilter(String specialWordFilter) {
  187 + options.specialWordFilter = specialWordFilter;
  188 + return this;
  189 + }
  190 +
  191 + public Builder withAudioEventDetectionEnabled(
  192 + Boolean audioEventDetectionEnabled) {
  193 + options.audioEventDetectionEnabled = audioEventDetectionEnabled;
  194 + return this;
  195 + }
  196 +
  197 + public TongYiAudioTranscriptionOptions build() {
  198 + // Perform any necessary validation here before returning the built object
  199 + return options;
  200 + }
  201 + }
  202 +
  203 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/transcription/TongYiAudioTranscriptionProperties.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.transcription;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.AudioTranscriptionModels;
  20 +import org.springframework.boot.context.properties.ConfigurationProperties;
  21 +import org.springframework.boot.context.properties.NestedConfigurationProperty;
  22 +
  23 +import static com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants.SCA_AI_CONFIGURATION;
  24 +
  25 +/**
  26 + * @author xYLiu
  27 + * @author yuluo
  28 + * @since 2023.0.1.0
  29 + */
  30 +
  31 +@ConfigurationProperties(TongYiAudioTranscriptionProperties.CONFIG_PREFIX)
  32 +public class TongYiAudioTranscriptionProperties {
  33 +
  34 + /**
  35 + * Spring Cloud Alibaba AI configuration prefix.
  36 + */
  37 + public static final String CONFIG_PREFIX = SCA_AI_CONFIGURATION + "audio.transcription";
  38 +
  39 + /**
  40 + * Default TongYi Chat model.
  41 + */
  42 + public static final String DEFAULT_AUDIO_MODEL_NAME = AudioTranscriptionModels.Paraformer_V1;
  43 +
  44 + /**
  45 + * Enable TongYiQWEN ai audio client.
  46 + */
  47 + private boolean enabled = true;
  48 +
  49 + @NestedConfigurationProperty
  50 + private TongYiAudioTranscriptionOptions options = TongYiAudioTranscriptionOptions
  51 + .builder().withModel(DEFAULT_AUDIO_MODEL_NAME).build();
  52 +
  53 + public TongYiAudioTranscriptionOptions getOptions() {
  54 +
  55 + return this.options;
  56 + }
  57 +
  58 + public void setOptions(TongYiAudioTranscriptionOptions options) {
  59 +
  60 + this.options = options;
  61 + }
  62 +
  63 + public boolean isEnabled() {
  64 +
  65 + return this.enabled;
  66 + }
  67 +
  68 + public void setEnabled(boolean enabled) {
  69 +
  70 + this.enabled = enabled;
  71 + }
  72 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/transcription/api/AudioTranscriptionPrompt.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.transcription.api;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.audio.transcription.TongYiAudioTranscriptionOptions;
  20 +import org.springframework.ai.model.ModelRequest;
  21 +import org.springframework.core.io.Resource;
  22 +
  23 +/**
  24 + * @author xYLiu
  25 + * @author yuluo
  26 + * @since 2023.0.1.0
  27 + */
  28 +
  29 +public class AudioTranscriptionPrompt implements ModelRequest<Resource> {
  30 +
  31 + private Resource audioResource;
  32 +
  33 + private TongYiAudioTranscriptionOptions transcriptionOptions;
  34 +
  35 + public AudioTranscriptionPrompt(Resource resource) {
  36 + this.audioResource = resource;
  37 + }
  38 +
  39 + public AudioTranscriptionPrompt(Resource resource, TongYiAudioTranscriptionOptions transcriptionOptions) {
  40 + this.audioResource = resource;
  41 + this.transcriptionOptions = transcriptionOptions;
  42 + }
  43 +
  44 + @Override
  45 + public Resource getInstructions() {
  46 +
  47 + return audioResource;
  48 + }
  49 +
  50 + @Override
  51 + public TongYiAudioTranscriptionOptions getOptions() {
  52 +
  53 + return transcriptionOptions;
  54 + }
  55 +
  56 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/transcription/api/AudioTranscriptionResponse.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.transcription.api;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.metadata.audio.TongYiAudioTranscriptionResponseMetadata;
  20 +import org.springframework.ai.model.ModelResponse;
  21 +import org.springframework.ai.model.ResponseMetadata;
  22 +
  23 +import java.util.List;
  24 +
  25 +/**
  26 + * @author xYLiu
  27 + * @author yuluo
  28 + * @since 2023.0.1.0
  29 + */
  30 +
  31 +public class AudioTranscriptionResponse implements ModelResponse<AudioTranscriptionResult> {
  32 +
  33 + private List<AudioTranscriptionResult> resultList;
  34 +
  35 + private TongYiAudioTranscriptionResponseMetadata transcriptionResponseMetadata;
  36 +
  37 + public AudioTranscriptionResponse(List<AudioTranscriptionResult> result) {
  38 +
  39 + this(result, TongYiAudioTranscriptionResponseMetadata.NULL);
  40 + }
  41 +
  42 + public AudioTranscriptionResponse(List<AudioTranscriptionResult> result,
  43 + TongYiAudioTranscriptionResponseMetadata transcriptionResponseMetadata) {
  44 +
  45 + this.resultList = List.copyOf(result);
  46 + this.transcriptionResponseMetadata = transcriptionResponseMetadata;
  47 + }
  48 +
  49 + @Override
  50 + public AudioTranscriptionResult getResult() {
  51 +
  52 + return this.resultList.get(0);
  53 + }
  54 +
  55 + @Override
  56 + public List<AudioTranscriptionResult> getResults() {
  57 +
  58 + return this.resultList;
  59 + }
  60 +
  61 + @Override
  62 + public ResponseMetadata getMetadata() {
  63 +
  64 + return this.transcriptionResponseMetadata;
  65 + }
  66 +
  67 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/audio/transcription/api/AudioTranscriptionResult.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.audio.transcription.api;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.metadata.audio.TongYiAudioTranscriptionMetadata;
  20 +import org.springframework.ai.model.ModelResult;
  21 +import org.springframework.ai.model.ResultMetadata;
  22 +
  23 +import java.util.Objects;
  24 +
  25 +/**
  26 + * @author yuluo
  27 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  28 + * @since 2023.0.1.0
  29 + */
  30 +public class AudioTranscriptionResult implements ModelResult<String> {
  31 +
  32 + private String text;
  33 +
  34 + private TongYiAudioTranscriptionMetadata transcriptionMetadata;
  35 +
  36 + public AudioTranscriptionResult(String text) {
  37 + this.text = text;
  38 + }
  39 +
  40 + @Override
  41 + public String getOutput() {
  42 +
  43 + return this.text;
  44 + }
  45 +
  46 + @Override
  47 + public ResultMetadata getMetadata() {
  48 +
  49 + return transcriptionMetadata != null ? transcriptionMetadata : TongYiAudioTranscriptionMetadata.NULL;
  50 + }
  51 +
  52 + @Override
  53 + public boolean equals(Object o) {
  54 + if (this == o) {
  55 + return true;
  56 + }
  57 + if (o == null || getClass() != o.getClass()) {
  58 + return false;
  59 + }
  60 + AudioTranscriptionResult that = (AudioTranscriptionResult) o;
  61 + return Objects.equals(text, that.text) && Objects.equals(transcriptionMetadata, that.transcriptionMetadata);
  62 + }
  63 +
  64 + @Override
  65 + public int hashCode() {
  66 + return Objects.hash(text, transcriptionMetadata);
  67 + }
  68 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/chat/TongYiChatModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.chat;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.common.exception.TongYiException;
  20 +import com.alibaba.dashscope.aigc.conversation.ConversationParam;
  21 +import com.alibaba.dashscope.aigc.generation.Generation;
  22 +import com.alibaba.dashscope.aigc.generation.GenerationOutput;
  23 +import com.alibaba.dashscope.aigc.generation.GenerationResult;
  24 +import com.alibaba.dashscope.common.MessageManager;
  25 +import com.alibaba.dashscope.common.Role;
  26 +import com.alibaba.dashscope.exception.InputRequiredException;
  27 +import com.alibaba.dashscope.exception.NoApiKeyException;
  28 +import com.alibaba.dashscope.tools.FunctionDefinition;
  29 +import com.alibaba.dashscope.tools.ToolCallBase;
  30 +import com.alibaba.dashscope.tools.ToolCallFunction;
  31 +import com.alibaba.dashscope.utils.ApiKeywords;
  32 +import com.alibaba.dashscope.utils.JsonUtils;
  33 +import io.reactivex.Flowable;
  34 +import org.slf4j.Logger;
  35 +import org.slf4j.LoggerFactory;
  36 +import org.springframework.ai.chat.messages.Message;
  37 +import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
  38 +import org.springframework.ai.chat.model.ChatModel;
  39 +import org.springframework.ai.chat.model.ChatResponse;
  40 +import org.springframework.ai.chat.model.StreamingChatModel;
  41 +import org.springframework.ai.chat.prompt.ChatOptions;
  42 +import org.springframework.ai.chat.prompt.Prompt;
  43 +import org.springframework.ai.model.ModelOptionsUtils;
  44 +import org.springframework.ai.model.function.AbstractFunctionCallSupport;
  45 +import org.springframework.ai.model.function.FunctionCallbackContext;
  46 +import org.springframework.beans.factory.annotation.Autowired;
  47 +import org.springframework.util.CollectionUtils;
  48 +import reactor.core.publisher.Flux;
  49 +import reactor.core.scheduler.Schedulers;
  50 +
  51 +import java.util.HashSet;
  52 +import java.util.List;
  53 +import java.util.Objects;
  54 +import java.util.Set;
  55 +
  56 +
  57 +/**
  58 + * {@link ChatModel} and {@link StreamingChatModel} implementation for {@literal Alibaba DashScope}
  59 + * backed by {@link Generation}.
  60 + *
  61 + * @author yuluo
  62 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  63 + * @since 2023.0.1.0
  64 + * @see ChatModel
  65 + * @see com.alibaba.dashscope.aigc.generation
  66 + */
  67 +
  68 +public class TongYiChatModel extends
  69 + AbstractFunctionCallSupport<
  70 + com.alibaba.dashscope.common.Message,
  71 + ConversationParam,
  72 + GenerationResult>
  73 + implements ChatModel, StreamingChatModel {
  74 +
  75 + private static final Logger logger = LoggerFactory.getLogger(TongYiChatModel.class);
  76 +
  77 + /**
  78 + * DashScope generation client.
  79 + */
  80 + private final Generation generation;
  81 +
  82 + /**
  83 + * The TongYi models default chat completion api.
  84 + */
  85 + private TongYiChatOptions defaultOptions;
  86 +
  87 + /**
  88 + * User role message manager.
  89 + */
  90 + @Autowired
  91 + private MessageManager msgManager;
  92 +
  93 + /**
  94 + * Initializes an instance of the TongYiChatClient.
  95 + * @param generation DashScope generation client.
  96 + */
  97 + public TongYiChatModel(Generation generation) {
  98 +
  99 + this(generation,
  100 + TongYiChatOptions.builder()
  101 + .withTopP(0.8)
  102 + .withEnableSearch(true)
  103 + .withResultFormat(ConversationParam.ResultFormat.MESSAGE)
  104 + .build(),
  105 + null
  106 + );
  107 + }
  108 +
  109 + /**
  110 + * Initializes an instance of the TongYiChatClient.
  111 + * @param generation DashScope generation client.
  112 + * @param options TongYi model params.
  113 + */
  114 + public TongYiChatModel(Generation generation, TongYiChatOptions options) {
  115 +
  116 + this(generation, options, null);
  117 + }
  118 +
  119 + /**
  120 + * Create a TongYi models client.
  121 + * @param generation DashScope model generation client.
  122 + * @param options TongYi default chat completion api.
  123 + */
  124 + public TongYiChatModel(Generation generation, TongYiChatOptions options,
  125 + FunctionCallbackContext functionCallbackContext) {
  126 +
  127 + super(functionCallbackContext);
  128 + this.generation = generation;
  129 + this.defaultOptions = options;
  130 + }
  131 +
  132 + /**
  133 + * Get default sca chat options.
  134 + *
  135 + * @return TongYiChatOptions default object.
  136 + */
  137 + public TongYiChatOptions getDefaultOptions() {
  138 +
  139 + return this.defaultOptions;
  140 + }
  141 +
  142 + @Override
  143 + public ChatResponse call(Prompt prompt) {
  144 +
  145 + ConversationParam params = toTongYiChatParams(prompt);
  146 +
  147 + // TongYi models context loader.
  148 + com.alibaba.dashscope.common.Message message = new com.alibaba.dashscope.common.Message();
  149 + message.setRole(Role.USER.getValue());
  150 + message.setContent(prompt.getContents());
  151 + msgManager.add(message);
  152 + params.setMessages(msgManager.get());
  153 +
  154 + logger.trace("TongYi ConversationOptions: {}", params);
  155 + GenerationResult chatCompletions = this.callWithFunctionSupport(params);
  156 + logger.trace("TongYi ConversationOptions: {}", params);
  157 +
  158 + msgManager.add(chatCompletions);
  159 +
  160 + List<org.springframework.ai.chat.model.Generation> generations =
  161 + chatCompletions
  162 + .getOutput()
  163 + .getChoices()
  164 + .stream()
  165 + .map(choice ->
  166 + new org.springframework.ai.chat.model.Generation(
  167 + choice
  168 + .getMessage()
  169 + .getContent()
  170 + ).withGenerationMetadata(generateChoiceMetadata(choice)
  171 + ))
  172 + .toList();
  173 +
  174 + return new ChatResponse(generations);
  175 +
  176 + }
  177 +
  178 + @Override
  179 + public Flux<ChatResponse> stream(Prompt prompt) {
  180 +
  181 + Flowable<GenerationResult> genRes;
  182 + ConversationParam tongYiChatParams = toTongYiChatParams(prompt);
  183 +
  184 + // See https://help.aliyun.com/zh/dashscope/developer-reference/api-details?spm=a2c4g.11186623.0.0.655fc11aRR0jj7#b9ad0a10cfhpe
  185 + // tongYiChatParams.setIncrementalOutput(true);
  186 +
  187 + try {
  188 + genRes = generation.streamCall(tongYiChatParams);
  189 + }
  190 + catch (NoApiKeyException | InputRequiredException e) {
  191 + logger.warn("TongYi chat client: " + e.getMessage());
  192 + throw new TongYiException(e.getMessage());
  193 + }
  194 +
  195 + return Flux.from(genRes)
  196 + .flatMap(
  197 + message -> Flux.just(
  198 + message.getOutput()
  199 + .getChoices()
  200 + .get(0)
  201 + .getMessage()
  202 + .getContent())
  203 + .map(content -> {
  204 + var gen = new org.springframework.ai.chat.model.Generation(content)
  205 + .withGenerationMetadata(generateChoiceMetadata(
  206 + message.getOutput()
  207 + .getChoices()
  208 + .get(0)
  209 + ));
  210 + return new ChatResponse(List.of(gen));
  211 + })
  212 + )
  213 + .publishOn(Schedulers.parallel());
  214 +
  215 + }
  216 +
  217 + /**
  218 + * Configuration properties to Qwen model params.
  219 + * Test access.
  220 + *
  221 + * @param prompt {@link Prompt}
  222 + * @return Qwen models params {@link ConversationParam}
  223 + */
  224 + public ConversationParam toTongYiChatParams(Prompt prompt) {
  225 +
  226 + Set<String> functionsForThisRequest = new HashSet<>();
  227 +
  228 + List<com.alibaba.dashscope.common.Message> tongYiMessage = prompt.getInstructions().stream()
  229 + .map(this::fromSpringAIMessage)
  230 + .toList();
  231 +
  232 + ConversationParam chatParams = ConversationParam.builder()
  233 + .messages(tongYiMessage)
  234 + // models setting
  235 + // {@link HalfDuplexServiceParam#models}
  236 + .model(Generation.Models.QWEN_TURBO)
  237 + // {@link GenerationOutput}
  238 + .resultFormat(ConversationParam.ResultFormat.MESSAGE)
  239 +
  240 + .build();
  241 +
  242 + if (this.defaultOptions != null) {
  243 +
  244 + chatParams = merge(chatParams, this.defaultOptions);
  245 + Set<String> defaultEnabledFunctions = this.handleFunctionCallbackConfigurations(this.defaultOptions, !IS_RUNTIME_CALL);
  246 + functionsForThisRequest.addAll(defaultEnabledFunctions);
  247 + }
  248 + if (prompt.getOptions() != null) {
  249 + if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
  250 + TongYiChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
  251 + ChatOptions.class, TongYiChatOptions.class);
  252 +
  253 + chatParams = merge(updatedRuntimeOptions, chatParams);
  254 +
  255 + Set<String> promptEnabledFunctions = this.handleFunctionCallbackConfigurations(updatedRuntimeOptions,
  256 + IS_RUNTIME_CALL);
  257 + functionsForThisRequest.addAll(promptEnabledFunctions);
  258 +
  259 + }
  260 + else {
  261 + throw new IllegalArgumentException("Prompt options are not of type ConversationParam:"
  262 + + prompt.getOptions().getClass().getSimpleName());
  263 + }
  264 + }
  265 +
  266 + // Add the enabled functions definitions to the request's tools parameter.
  267 +
  268 + if (!CollectionUtils.isEmpty(functionsForThisRequest)) {
  269 + List<FunctionDefinition> tools = this.getFunctionTools(functionsForThisRequest);
  270 +
  271 + // todo chatParams.setTools(tools)
  272 + }
  273 +
  274 + return chatParams;
  275 + }
  276 +
  277 + private ChatGenerationMetadata generateChoiceMetadata(GenerationOutput.Choice choice) {
  278 +
  279 + return ChatGenerationMetadata.from(
  280 + String.valueOf(choice.getFinishReason()),
  281 + choice.getMessage().getContent()
  282 + );
  283 + }
  284 +
  285 + private List<FunctionDefinition> getFunctionTools(Set<String> functionNames) {
  286 + return this.resolveFunctionCallbacks(functionNames).stream().map(functionCallback -> {
  287 +
  288 + FunctionDefinition functionDefinition = FunctionDefinition.builder()
  289 + .name(functionCallback.getName())
  290 + .description(functionCallback.getDescription())
  291 + .parameters(JsonUtils.parametersToJsonObject(
  292 + ModelOptionsUtils.jsonToMap(functionCallback.getInputTypeSchema())
  293 + ))
  294 + .build();
  295 +
  296 + return functionDefinition;
  297 + }).toList();
  298 + }
  299 +
  300 +
  301 + private ConversationParam merge(ConversationParam tongYiParams, TongYiChatOptions scaChatParams) {
  302 +
  303 + if (scaChatParams == null) {
  304 +
  305 + return tongYiParams;
  306 + }
  307 +
  308 + return ConversationParam.builder()
  309 + .messages(tongYiParams.getMessages())
  310 + .maxTokens((tongYiParams.getMaxTokens() != null) ? tongYiParams.getMaxTokens() : scaChatParams.getMaxTokens())
  311 + // When merge options. Because ConversationParams is must not null. So is setting.
  312 + .model(scaChatParams.getModel())
  313 + .resultFormat((tongYiParams.getResultFormat() != null) ? tongYiParams.getResultFormat() : scaChatParams.getResultFormat())
  314 + .enableSearch((tongYiParams.getEnableSearch() != null) ? tongYiParams.getEnableSearch() : scaChatParams.getEnableSearch())
  315 + .topK((tongYiParams.getTopK() != null) ? tongYiParams.getTopK() : scaChatParams.getTopK())
  316 + .topP((tongYiParams.getTopP() != null) ? tongYiParams.getTopP() : scaChatParams.getTopP())
  317 + .incrementalOutput((tongYiParams.getIncrementalOutput() != null) ? tongYiParams.getIncrementalOutput() : scaChatParams.getIncrementalOutput())
  318 + .temperature((tongYiParams.getTemperature() != null) ? tongYiParams.getTemperature() : scaChatParams.getTemperature())
  319 + .repetitionPenalty((tongYiParams.getRepetitionPenalty() != null) ? tongYiParams.getRepetitionPenalty() : scaChatParams.getRepetitionPenalty())
  320 + .seed((tongYiParams.getSeed() != null) ? tongYiParams.getSeed() : scaChatParams.getSeed())
  321 + .build();
  322 +
  323 + }
  324 +
  325 + private ConversationParam merge(TongYiChatOptions scaChatParams, ConversationParam tongYiParams) {
  326 +
  327 + if (scaChatParams == null) {
  328 +
  329 + return tongYiParams;
  330 + }
  331 +
  332 + ConversationParam mergedTongYiParams = ConversationParam.builder()
  333 + .model(Generation.Models.QWEN_TURBO)
  334 + .messages(tongYiParams.getMessages())
  335 + .build();
  336 + mergedTongYiParams = merge(tongYiParams, scaChatParams);
  337 +
  338 + if (scaChatParams.getMaxTokens() != null) {
  339 + mergedTongYiParams.setMaxTokens(scaChatParams.getMaxTokens());
  340 + }
  341 +
  342 + if (scaChatParams.getStop() != null) {
  343 + mergedTongYiParams.setStopStrings(scaChatParams.getStop());
  344 + }
  345 +
  346 + if (scaChatParams.getTemperature() != null) {
  347 + mergedTongYiParams.setTemperature(scaChatParams.getTemperature());
  348 + }
  349 +
  350 + if (scaChatParams.getTopK() != null) {
  351 + mergedTongYiParams.setTopK(scaChatParams.getTopK());
  352 + }
  353 +
  354 + if (scaChatParams.getTopK() != null) {
  355 + mergedTongYiParams.setTopK(scaChatParams.getTopK());
  356 + }
  357 +
  358 + return mergedTongYiParams;
  359 + }
  360 +
  361 + private com.alibaba.dashscope.common.Message fromSpringAIMessage(Message message) {
  362 +
  363 + return switch (message.getMessageType()) {
  364 + case USER -> com.alibaba.dashscope.common.Message.builder()
  365 + .role(Role.USER.getValue())
  366 + .content(message.getContent())
  367 + .build();
  368 + case SYSTEM -> com.alibaba.dashscope.common.Message.builder()
  369 + .role(Role.SYSTEM.getValue())
  370 + .content(message.getContent())
  371 + .build();
  372 + case ASSISTANT -> com.alibaba.dashscope.common.Message.builder()
  373 + .role(Role.ASSISTANT.getValue())
  374 + .content(message.getContent())
  375 + .build();
  376 + default -> throw new IllegalArgumentException("Unknown message type " + message.getMessageType());
  377 + };
  378 +
  379 + }
  380 +
  381 + @Override
  382 + protected ConversationParam doCreateToolResponseRequest(
  383 + ConversationParam previousRequest,
  384 + com.alibaba.dashscope.common.Message responseMessage,
  385 + List<com.alibaba.dashscope.common.Message> conversationHistory
  386 + ) {
  387 + for (ToolCallBase toolCall : responseMessage.getToolCalls()) {
  388 + if (toolCall instanceof ToolCallFunction toolCallFunction) {
  389 + if (toolCallFunction.getFunction() != null) {
  390 + var functionName = toolCallFunction.getFunction().getName();
  391 + var functionArguments = toolCallFunction.getFunction().getArguments();
  392 +
  393 + if (!this.functionCallbackRegister.containsKey(functionName)) {
  394 + throw new IllegalStateException("No function callback found for function name: " + functionName);
  395 + }
  396 +
  397 + String functionResponse = this.functionCallbackRegister.get(functionName).call(functionArguments);
  398 +
  399 + // Add the function response to the conversation.
  400 + conversationHistory
  401 + .add(com.alibaba.dashscope.common.Message.builder()
  402 + .content(functionResponse)
  403 + .role(Role.BOT.getValue())
  404 + .toolCallId(toolCall.getId())
  405 + .build()
  406 + );
  407 + }
  408 + }
  409 +
  410 + }
  411 +
  412 + ConversationParam newRequest = ConversationParam.builder().messages(conversationHistory).build();
  413 +
  414 + // todo: No @JsonProperty fields.
  415 + newRequest = ModelOptionsUtils.merge(newRequest, previousRequest, ConversationParam.class);
  416 +
  417 + return newRequest;
  418 +
  419 + }
  420 +
  421 + @Override
  422 + protected List<com.alibaba.dashscope.common.Message> doGetUserMessages(ConversationParam request) {
  423 +
  424 + return request.getMessages();
  425 + }
  426 +
  427 + @Override
  428 + protected com.alibaba.dashscope.common.Message doGetToolResponseMessage(GenerationResult response) {
  429 +
  430 + var message = response.getOutput().getChoices().get(0).getMessage();
  431 + var assistantMessage = com.alibaba.dashscope.common.Message.builder().role(Role.ASSISTANT.getValue())
  432 + .content("").build();
  433 + assistantMessage.setToolCalls(message.getToolCalls());
  434 +
  435 + return assistantMessage;
  436 + }
  437 +
  438 + @Override
  439 + protected GenerationResult doChatCompletion(ConversationParam request) {
  440 +
  441 + GenerationResult result;
  442 + try {
  443 + result = generation.call(request);
  444 + }
  445 + catch (NoApiKeyException | InputRequiredException e) {
  446 + throw new RuntimeException(e);
  447 + }
  448 +
  449 + return result;
  450 + }
  451 +
  452 + @Override
  453 + protected Flux<GenerationResult> doChatCompletionStream(ConversationParam request) {
  454 + final Flowable<GenerationResult> genRes;
  455 + try {
  456 + genRes = generation.streamCall(request);
  457 + }
  458 + catch (NoApiKeyException | InputRequiredException e) {
  459 + logger.warn("TongYi chat client: " + e.getMessage());
  460 + throw new TongYiException(e.getMessage());
  461 + }
  462 + return Flux.from(genRes);
  463 +
  464 + }
  465 +
  466 + @Override
  467 + protected boolean isToolFunctionCall(GenerationResult response) {
  468 +
  469 + if (response == null || CollectionUtils.isEmpty(response.getOutput().getChoices())) {
  470 +
  471 + return false;
  472 + }
  473 + var choice = response.getOutput().getChoices().get(0);
  474 + if (choice == null || choice.getFinishReason() == null) {
  475 +
  476 + return false;
  477 + }
  478 +
  479 + return Objects.equals(choice.getFinishReason(), ApiKeywords.TOOL_CALLS);
  480 + }
  481 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/chat/TongYiChatOptions.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.chat;
  18 +
  19 +import com.alibaba.dashscope.aigc.generation.Generation;
  20 +import com.alibaba.dashscope.aigc.generation.GenerationParam;
  21 +import org.springframework.ai.chat.prompt.ChatOptions;
  22 +import org.springframework.ai.model.function.FunctionCallback;
  23 +import org.springframework.ai.model.function.FunctionCallingOptions;
  24 +import org.springframework.util.Assert;
  25 +
  26 +import java.util.*;
  27 +
  28 +/**
  29 + * @author yuluo
  30 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  31 + * @since 2023.0.1.0
  32 + */
  33 +
  34 +public class TongYiChatOptions implements FunctionCallingOptions, ChatOptions {
  35 +
  36 + /**
  37 + * TongYi Models.
  38 + * {@link Generation.Models}
  39 + */
  40 + private String model = Generation.Models.QWEN_TURBO;
  41 +
  42 + /**
  43 + * The random number seed used in generation, the user controls the randomness of the content generated by the model.
  44 + * seed supports unsigned 64-bit integers, with a default value of 1234.
  45 + * when using seed, the model will generate the same or similar results as much as possible, but there is currently no guarantee that the results will be exactly the same each time.
  46 + */
  47 + private Integer seed = 1234;
  48 +
  49 + /**
  50 + * Used to specify the maximum number of tokens that the model can generate when generating content,
  51 + * it defines the upper limit of generation but does not guarantee that this number will be generated every time.
  52 + * For qwen-turbo the maximum and default values are 1500 tokens.
  53 + * The qwen-max, qwen-max-1201, qwen-max-longcontext, and qwen-plus models have a maximum and default value of 2000 tokens.
  54 + */
  55 + private Integer maxTokens = 1500;
  56 +
  57 + /**
  58 + * The generation process kernel sampling method probability threshold,
  59 + * for example, takes the value of 0.8, only retains the smallest set of the most probable tokens with probabilities that add up to greater than or equal to 0.8 as the candidate set.
  60 + * The range of values is (0,1.0), the larger the value, the higher the randomness of generation; the lower the value, the higher the certainty of generation.
  61 + */
  62 + private Double topP = 0.8;
  63 +
  64 + /**
  65 + * The size of the sampling candidate set at the time of generation.
  66 + * For example, with a value of 50, only the 50 highest scoring tokens in a single generation will form a randomly sampled candidate set.
  67 + * The larger the value, the higher the randomness of the generation; the smaller the value, the higher the certainty of the generation.
  68 + * This parameter is not passed by default, and a value of None or when top_k is greater than 100 indicates that the top_k policy is not enabled,
  69 + * at which time, only the top_p policy is in effect.
  70 + */
  71 + private Integer topK;
  72 +
  73 + /**
  74 + * Used to control the repeatability of model generation.
  75 + * Increasing repetition_penalty reduces the repetition of model generation. 1.0 means no penalty.
  76 + */
  77 + private Double repetitionPenalty = 1.1;
  78 +
  79 + /**
  80 + * is used to control the degree of randomness and diversity.
  81 + * Specifically, the temperature value controls the extent to which the probability distribution of each candidate word is smoothed when generating text.
  82 + * Higher values of temperature reduce the peak of the probability distribution, allowing more low-probability words to be selected and generating more diverse results,
  83 + * while lower values of temperature enhance the peak of the probability distribution, making it easier for high-probability words to be selected and generating more certain results.
  84 + * Range: [0, 2), 0 is not recommended, meaningless.
  85 + * java version >= 2.5.1
  86 + */
  87 + private Double temperature = 0.85;
  88 +
  89 + /**
  90 + * The stop parameter is used to realize precise control of the content generation process, automatically stopping when the generated content is about to contain the specified string or token_ids,
  91 + * and the generated content does not contain the specified content.
  92 + * For example, if stop is specified as "Hello", it means stop when "Hello" will be generated; if stop is specified as [37763, 367], it means stop when "Observation" will be generated.
  93 + * The stop parameter can be passed as a list of arrays of strings or token_ids to support the scenario of using multiple stops.
  94 + * Explanation: Do not mix strings and token_ids in list mode, the element types should be the same in list mode.
  95 + */
  96 + private List<String> stop;
  97 +
  98 + /**
  99 + * Whether or not to use stream output. When outputting the result in stream mode, the interface returns the result as generator,
  100 + * you need to iterate to get the result, the default output is the whole sequence of the current generation for each output,
  101 + * the last output is the final result of all the generation, you can change the output mode to non-incremental output by the parameter incremental_output to False.
  102 + */
  103 + private Boolean stream = false;
  104 +
  105 + /**
  106 + * The model has a built-in Internet search service.
  107 + * This parameter controls whether the model refers to the use of Internet search results when generating text. The values are as follows:
  108 + * True: enable internet search, the model will use the search result as the reference information in the text generation process, but the model will "judge by itself" whether to use the internet search result based on its internal logic.
  109 + * False (default): Internet search is disabled.
  110 + */
  111 + private Boolean enableSearch = false;
  112 +
  113 + /**
  114 + * [text|message], defaults to text, when it is message,
  115 + * the output refers to the message result example.
  116 + * It is recommended to prioritize the use of message format.
  117 + */
  118 + private String resultFormat = GenerationParam.ResultFormat.MESSAGE;
  119 +
  120 + /**
  121 + * Control the streaming output mode, that is, the content will contain the content has been output;
  122 + * set to True, will open the incremental output mode, the output will not contain the content has been output,
  123 + * you need to splice the whole output, refer to the streaming output sample code.
  124 + */
  125 + private Boolean incrementalOutput = false;
  126 +
  127 + /**
  128 + * A list of tools that the model can optionally call.
  129 + * Currently only functions are supported, and even if multiple functions are entered, the model will only select one to generate the result.
  130 + */
  131 + private List<String> tools;
  132 +
  133 + @Override
  134 + public Float getTemperature() {
  135 +
  136 + return this.temperature.floatValue();
  137 + }
  138 +
  139 + public void setTemperature(Float temperature) {
  140 +
  141 + this.temperature = temperature.doubleValue();
  142 + }
  143 +
  144 + @Override
  145 + public Float getTopP() {
  146 +
  147 + return this.topP.floatValue();
  148 + }
  149 +
  150 + public void setTopP(Float topP) {
  151 +
  152 + this.topP = topP.doubleValue();
  153 + }
  154 +
  155 + @Override
  156 + public Integer getTopK() {
  157 +
  158 + return this.topK;
  159 + }
  160 +
  161 + public void setTopK(Integer topK) {
  162 +
  163 + this.topK = topK;
  164 + }
  165 +
  166 + public String getModel() {
  167 +
  168 + return model;
  169 + }
  170 +
  171 + public void setModel(String model) {
  172 +
  173 + this.model = model;
  174 + }
  175 +
  176 + public Integer getSeed() {
  177 +
  178 + return seed;
  179 + }
  180 +
  181 + public String getResultFormat() {
  182 +
  183 + return resultFormat;
  184 + }
  185 +
  186 + public void setResultFormat(String resultFormat) {
  187 +
  188 + this.resultFormat = resultFormat;
  189 + }
  190 +
  191 + public void setSeed(Integer seed) {
  192 +
  193 + this.seed = seed;
  194 + }
  195 +
  196 + public Integer getMaxTokens() {
  197 +
  198 + return maxTokens;
  199 + }
  200 +
  201 + public void setMaxTokens(Integer maxTokens) {
  202 +
  203 + this.maxTokens = maxTokens;
  204 + }
  205 +
  206 + public Float getRepetitionPenalty() {
  207 +
  208 + return repetitionPenalty.floatValue();
  209 + }
  210 +
  211 + public void setRepetitionPenalty(Float repetitionPenalty) {
  212 +
  213 + this.repetitionPenalty = repetitionPenalty.doubleValue();
  214 + }
  215 +
  216 + public List<String> getStop() {
  217 +
  218 + return stop;
  219 + }
  220 +
  221 + public void setStop(List<String> stop) {
  222 +
  223 + this.stop = stop;
  224 + }
  225 +
  226 + public Boolean getStream() {
  227 +
  228 + return stream;
  229 + }
  230 +
  231 + public void setStream(Boolean stream) {
  232 +
  233 + this.stream = stream;
  234 + }
  235 +
  236 + public Boolean getEnableSearch() {
  237 +
  238 + return enableSearch;
  239 + }
  240 +
  241 + public void setEnableSearch(Boolean enableSearch) {
  242 +
  243 + this.enableSearch = enableSearch;
  244 + }
  245 +
  246 + public Boolean getIncrementalOutput() {
  247 +
  248 + return incrementalOutput;
  249 + }
  250 +
  251 + public void setIncrementalOutput(Boolean incrementalOutput) {
  252 +
  253 + this.incrementalOutput = incrementalOutput;
  254 + }
  255 +
  256 + public List<String> getTools() {
  257 +
  258 + return tools;
  259 + }
  260 +
  261 + public void setTools(List<String> tools) {
  262 +
  263 + this.tools = tools;
  264 + }
  265 +
  266 + private List<FunctionCallback> functionCallbacks = new ArrayList<>();
  267 +
  268 + private Set<String> functions = new HashSet<>();
  269 +
  270 + @Override
  271 + public List<FunctionCallback> getFunctionCallbacks() {
  272 +
  273 + return this.functionCallbacks;
  274 + }
  275 +
  276 + @Override
  277 + public void setFunctionCallbacks(List<FunctionCallback> functionCallbacks) {
  278 +
  279 + this.functionCallbacks = functionCallbacks;
  280 + }
  281 +
  282 + @Override
  283 + public Set<String> getFunctions() {
  284 +
  285 + return this.functions;
  286 + }
  287 +
  288 + @Override
  289 + public void setFunctions(Set<String> functions) {
  290 +
  291 + this.functions = functions;
  292 + }
  293 +
  294 + @Override
  295 + public boolean equals(Object o) {
  296 +
  297 + if (this == o) {
  298 + return true;
  299 + }
  300 +
  301 + if (o == null || getClass() != o.getClass()) {
  302 + return false;
  303 + }
  304 +
  305 + TongYiChatOptions that = (TongYiChatOptions) o;
  306 +
  307 + return Objects.equals(model, that.model)
  308 + && Objects.equals(seed, that.seed)
  309 + && Objects.equals(maxTokens, that.maxTokens)
  310 + && Objects.equals(topP, that.topP)
  311 + && Objects.equals(topK, that.topK)
  312 + && Objects.equals(repetitionPenalty, that.repetitionPenalty)
  313 + && Objects.equals(temperature, that.temperature)
  314 + && Objects.equals(stop, that.stop)
  315 + && Objects.equals(stream, that.stream)
  316 + && Objects.equals(enableSearch, that.enableSearch)
  317 + && Objects.equals(resultFormat, that.resultFormat)
  318 + && Objects.equals(incrementalOutput, that.incrementalOutput)
  319 + && Objects.equals(tools, that.tools)
  320 + && Objects.equals(functionCallbacks, that.functionCallbacks)
  321 + && Objects.equals(functions, that.functions);
  322 + }
  323 +
  324 + @Override
  325 + public int hashCode() {
  326 +
  327 + return Objects.hash(
  328 + model,
  329 + seed,
  330 + maxTokens,
  331 + topP,
  332 + topK,
  333 + repetitionPenalty,
  334 + temperature,
  335 + stop,
  336 + stream,
  337 + enableSearch,
  338 + resultFormat,
  339 + incrementalOutput,
  340 + tools,
  341 + functionCallbacks,
  342 + functions
  343 + );
  344 + }
  345 +
  346 + @Override
  347 + public String toString() {
  348 +
  349 + final StringBuilder sb = new StringBuilder("TongYiChatOptions{");
  350 +
  351 + sb.append(", model='").append(model).append('\'');
  352 + sb.append(", seed=").append(seed);
  353 + sb.append(", maxTokens=").append(maxTokens);
  354 + sb.append(", topP=").append(topP);
  355 + sb.append(", topK=").append(topK);
  356 + sb.append(", repetitionPenalty=").append(repetitionPenalty);
  357 + sb.append(", temperature=").append(temperature);
  358 + sb.append(", stop=").append(stop);
  359 + sb.append(", stream=").append(stream);
  360 + sb.append(", enableSearch=").append(enableSearch);
  361 + sb.append(", resultFormat='").append(resultFormat).append('\'');
  362 + sb.append(", incrementalOutput=").append(incrementalOutput);
  363 + sb.append(", tools=").append(tools);
  364 + sb.append(", functionCallbacks=").append(functionCallbacks);
  365 + sb.append(", functions=").append(functions);
  366 + sb.append('}');
  367 +
  368 + return sb.toString();
  369 + }
  370 +
  371 + public static Builder builder() {
  372 +
  373 + return new Builder();
  374 + }
  375 +
  376 + public static class Builder {
  377 +
  378 + protected TongYiChatOptions options;
  379 +
  380 + public Builder() {
  381 +
  382 + this.options = new TongYiChatOptions();
  383 + }
  384 +
  385 + public Builder(TongYiChatOptions options) {
  386 +
  387 + this.options = options;
  388 + }
  389 +
  390 + public Builder withModel(String model) {
  391 + this.options.model = model;
  392 + return this;
  393 + }
  394 +
  395 + public Builder withMaxTokens(Integer maxTokens) {
  396 + this.options.maxTokens = maxTokens;
  397 + return this;
  398 + }
  399 +
  400 + public Builder withResultFormat(String rf) {
  401 + this.options.resultFormat = rf;
  402 + return this;
  403 + }
  404 +
  405 + public Builder withEnableSearch(Boolean enableSearch) {
  406 + this.options.enableSearch = enableSearch;
  407 + return this;
  408 + }
  409 +
  410 + public Builder withFunctionCallbacks(List<FunctionCallback> functionCallbacks) {
  411 + this.options.functionCallbacks = functionCallbacks;
  412 + return this;
  413 + }
  414 +
  415 + public Builder withFunctions(Set<String> functionNames) {
  416 + Assert.notNull(functionNames, "Function names must not be null");
  417 + this.options.functions = functionNames;
  418 + return this;
  419 + }
  420 +
  421 + public Builder withFunction(String functionName) {
  422 + Assert.hasText(functionName, "Function name must not be empty");
  423 + this.options.functions.add(functionName);
  424 + return this;
  425 + }
  426 +
  427 + public Builder withSeed(Integer seed) {
  428 + this.options.seed = seed;
  429 + return this;
  430 + }
  431 +
  432 + public Builder withStop(List<String> stop) {
  433 + this.options.stop = stop;
  434 + return this;
  435 + }
  436 +
  437 + public Builder withTemperature(Double temperature) {
  438 + this.options.temperature = temperature;
  439 + return this;
  440 + }
  441 +
  442 + public Builder withTopP(Double topP) {
  443 + this.options.topP = topP;
  444 + return this;
  445 + }
  446 +
  447 + public Builder withTopK(Integer topK) {
  448 + this.options.topK = topK;
  449 + return this;
  450 + }
  451 +
  452 + public Builder withRepetitionPenalty(Double repetitionPenalty) {
  453 + this.options.repetitionPenalty = repetitionPenalty;
  454 + return this;
  455 + }
  456 +
  457 + public TongYiChatOptions build() {
  458 +
  459 + return this.options;
  460 + }
  461 + }
  462 +
  463 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/chat/TongYiChatProperties.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.chat;
  18 +
  19 +import com.alibaba.dashscope.aigc.generation.Generation;
  20 +import com.alibaba.dashscope.aigc.generation.GenerationParam;
  21 +import org.springframework.boot.context.properties.ConfigurationProperties;
  22 +import org.springframework.boot.context.properties.NestedConfigurationProperty;
  23 +
  24 +import static com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants.SCA_AI_CONFIGURATION;
  25 +
  26 +/**
  27 + * @author yuluo
  28 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  29 + * @since 2023.0.1.0
  30 + */
  31 +
  32 +@ConfigurationProperties(TongYiChatProperties.CONFIG_PREFIX)
  33 +public class TongYiChatProperties {
  34 +
  35 + /**
  36 + * Spring Cloud Alibaba AI configuration prefix.
  37 + */
  38 + public static final String CONFIG_PREFIX = SCA_AI_CONFIGURATION + "chat";
  39 +
  40 + /**
  41 + * Default TongYi Chat model.
  42 + */
  43 + public static final String DEFAULT_DEPLOYMENT_NAME = Generation.Models.QWEN_TURBO;
  44 +
  45 + /**
  46 + * Default temperature speed.
  47 + */
  48 + private static final Double DEFAULT_TEMPERATURE = 0.8;
  49 +
  50 + /**
  51 + * Enable TongYiQWEN ai chat client.
  52 + */
  53 + private boolean enabled = true;
  54 +
  55 + @NestedConfigurationProperty
  56 + private TongYiChatOptions options = TongYiChatOptions.builder()
  57 + .withModel(DEFAULT_DEPLOYMENT_NAME)
  58 + .withTemperature(DEFAULT_TEMPERATURE)
  59 + .withEnableSearch(true)
  60 + .withResultFormat(GenerationParam.ResultFormat.MESSAGE)
  61 + .build();
  62 +
  63 + public TongYiChatOptions getOptions() {
  64 +
  65 + return this.options;
  66 + }
  67 +
  68 + public void setOptions(TongYiChatOptions options) {
  69 +
  70 + this.options = options;
  71 + }
  72 +
  73 + public boolean isEnabled() {
  74 +
  75 + return this.enabled;
  76 + }
  77 +
  78 + public void setEnabled(boolean enabled) {
  79 +
  80 + this.enabled = enabled;
  81 + }
  82 +
  83 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/common/constants/TongYiConstants.java 0 → 100644
  1 +/*
  2 + * Copyright 2024-2025 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.common.constants;
  18 +
  19 +/**
  20 + * @author yuluo
  21 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  22 + */
  23 +
  24 +public final class TongYiConstants {
  25 +
  26 + private TongYiConstants() {
  27 + }
  28 +
  29 + /**
  30 + * Spring Cloud Alibaba AI configuration prefix.
  31 + */
  32 + public static final String SCA_AI_CONFIGURATION = "spring.cloud.ai.tongyi.";
  33 +
  34 + /**
  35 + * Spring Cloud Alibaba AI constants prefix.
  36 + */
  37 + public static final String SCA_AI = "SPRING_CLOUD_ALIBABA_";
  38 +
  39 + /**
  40 + * TongYi AI apikey env name.
  41 + */
  42 + public static final String SCA_AI_TONGYI_API_KEY = SCA_AI + "TONGYI_API_KEY";
  43 +
  44 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/common/exception/TongYiException.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.common.exception;
  18 +
  19 +/**
  20 + * TongYi models runtime exception.
  21 + *
  22 + * @author yuluo
  23 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  24 + * @since 2023.0.1.0
  25 + */
  26 +
  27 +public class TongYiException extends RuntimeException {
  28 +
  29 + public TongYiException(String message) {
  30 +
  31 + super(message);
  32 + }
  33 +
  34 + public TongYiException(String message, Throwable cause) {
  35 +
  36 + super(message, cause);
  37 + }
  38 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/common/exception/TongYiImagesException.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.common.exception;
  18 +
  19 +/**
  20 + * TongYi models images exception.
  21 + *
  22 + * @author yuluo
  23 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  24 + * @since 2023.0.1.0
  25 + */
  26 +
  27 +public class TongYiImagesException extends TongYiException {
  28 +
  29 + public TongYiImagesException(String message) {
  30 +
  31 + super(message);
  32 + }
  33 +
  34 + public TongYiImagesException(String message, Throwable cause) {
  35 +
  36 + super(message, cause);
  37 + }
  38 +
  39 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/embedding/TongYiEmbeddingOptions.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.embedding;
  18 +
  19 +import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
  20 +import org.springframework.ai.embedding.EmbeddingOptions;
  21 +
  22 +import java.util.List;
  23 +
  24 +/**
  25 + * @author why_ohh
  26 + * @author yuluo
  27 + * @author <a href="mailto:550588941@qq.com">why_ohh</a>
  28 + * @since 2023.0.1.0
  29 + */
  30 +
  31 +public final class TongYiEmbeddingOptions implements EmbeddingOptions {
  32 +
  33 + private List<String> texts;
  34 +
  35 + private TextEmbeddingParam.TextType textType;
  36 +
  37 + public List<String> getTexts() {
  38 + return texts;
  39 + }
  40 +
  41 + public void setTexts(List<String> texts) {
  42 + this.texts = texts;
  43 + }
  44 +
  45 + public TextEmbeddingParam.TextType getTextType() {
  46 + return textType;
  47 + }
  48 +
  49 + public void setTextType(TextEmbeddingParam.TextType textType) {
  50 + this.textType = textType;
  51 + }
  52 +
  53 + public static Builder builder() {
  54 + return new Builder();
  55 + }
  56 +
  57 + public final static class Builder {
  58 +
  59 + private final TongYiEmbeddingOptions options;
  60 +
  61 + private Builder() {
  62 + this.options = new TongYiEmbeddingOptions();
  63 + }
  64 +
  65 + public Builder withtexts(List<String> texts) {
  66 +
  67 + options.setTexts(texts);
  68 + return this;
  69 + }
  70 +
  71 + public Builder withtextType(TextEmbeddingParam.TextType textType) {
  72 +
  73 + options.setTextType(textType);
  74 + return this;
  75 + }
  76 +
  77 + public TongYiEmbeddingOptions build() {
  78 +
  79 + return options;
  80 + }
  81 +
  82 + }
  83 +
  84 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/embedding/TongYiTextEmbeddingModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.embedding;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.common.exception.TongYiException;
  20 +import com.alibaba.cloud.ai.tongyi.metadata.TongYiTextEmbeddingResponseMetadata;
  21 +import com.alibaba.dashscope.embeddings.TextEmbedding;
  22 +import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
  23 +import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
  24 +import com.alibaba.dashscope.embeddings.TextEmbeddingResultItem;
  25 +import com.alibaba.dashscope.exception.InputRequiredException;
  26 +import com.alibaba.dashscope.exception.NoApiKeyException;
  27 +import org.slf4j.Logger;
  28 +import org.slf4j.LoggerFactory;
  29 +import org.springframework.ai.document.Document;
  30 +import org.springframework.ai.document.MetadataMode;
  31 +import org.springframework.ai.embedding.AbstractEmbeddingModel;
  32 +import org.springframework.ai.embedding.Embedding;
  33 +import org.springframework.ai.embedding.EmbeddingRequest;
  34 +import org.springframework.ai.embedding.EmbeddingResponse;
  35 +import org.springframework.util.Assert;
  36 +
  37 +import java.util.List;
  38 +import java.util.stream.Collectors;
  39 +
  40 +/**
  41 + * {@link TongYiTextEmbeddingModel} implementation for {@literal Alibaba DashScope}.
  42 + *
  43 + * @author why_ohh
  44 + * @author yuluo
  45 + * @author <a href="mailto:550588941@qq.com">why_ohh</a>
  46 + * @since 2023.0.1.0
  47 + */
  48 +
  49 +public class TongYiTextEmbeddingModel extends AbstractEmbeddingModel {
  50 +
  51 + private final Logger logger = LoggerFactory.getLogger(TongYiTextEmbeddingModel.class);
  52 +
  53 + /**
  54 + * TongYi Text Embedding client.
  55 + */
  56 + private final TextEmbedding textEmbedding;
  57 +
  58 + /**
  59 + * {@link MetadataMode}.
  60 + */
  61 + private final MetadataMode metadataMode;
  62 +
  63 + private final TongYiEmbeddingOptions defaultOptions;
  64 +
  65 + public TongYiTextEmbeddingModel(TextEmbedding textEmbedding) {
  66 +
  67 + this(textEmbedding, MetadataMode.EMBED);
  68 + }
  69 +
  70 + public TongYiTextEmbeddingModel(TextEmbedding textEmbedding, MetadataMode metadataMode) {
  71 +
  72 + this(textEmbedding, metadataMode,
  73 + TongYiEmbeddingOptions.builder()
  74 + .withtextType(TextEmbeddingParam.TextType.DOCUMENT)
  75 + .build()
  76 + );
  77 + }
  78 +
  79 + public TongYiTextEmbeddingModel(
  80 + TextEmbedding textEmbedding,
  81 + MetadataMode metadataMode,
  82 + TongYiEmbeddingOptions options
  83 + ) {
  84 + Assert.notNull(textEmbedding, "textEmbedding must not be null");
  85 + Assert.notNull(metadataMode, "Metadata mode must not be null");
  86 + Assert.notNull(options, "TongYiEmbeddingOptions must not be null");
  87 +
  88 + this.metadataMode = metadataMode;
  89 + this.textEmbedding = textEmbedding;
  90 + this.defaultOptions = options;
  91 + }
  92 +
  93 + public TongYiEmbeddingOptions getDefaultOptions() {
  94 +
  95 + return this.defaultOptions;
  96 + }
  97 +
  98 + @Override
  99 + public List<Double> embed(Document document) {
  100 +
  101 + return this.call(
  102 + new EmbeddingRequest(
  103 + List.of(document.getFormattedContent(this.metadataMode)),
  104 + null)
  105 + ).getResults().stream()
  106 + .map(Embedding::getOutput)
  107 + .flatMap(List::stream)
  108 + .toList();
  109 + }
  110 +
  111 + @Override
  112 + public EmbeddingResponse call(EmbeddingRequest request) {
  113 +
  114 + TextEmbeddingParam embeddingParams = toEmbeddingParams(request);
  115 + logger.debug("Embedding request: {}", embeddingParams);
  116 + TextEmbeddingResult resp;
  117 +
  118 + try {
  119 + resp = textEmbedding.call(embeddingParams);
  120 + }
  121 + catch (NoApiKeyException e) {
  122 + throw new TongYiException(e.getMessage());
  123 + }
  124 +
  125 + return genEmbeddingResp(resp);
  126 + }
  127 +
  128 + private EmbeddingResponse genEmbeddingResp(TextEmbeddingResult result) {
  129 +
  130 + return new EmbeddingResponse(
  131 + genEmbeddingList(result.getOutput().getEmbeddings()),
  132 + TongYiTextEmbeddingResponseMetadata.from(result.getUsage())
  133 + );
  134 + }
  135 +
  136 + private List<Embedding> genEmbeddingList(List<TextEmbeddingResultItem> embeddings) {
  137 +
  138 + return embeddings.stream()
  139 + .map(embedding ->
  140 + new Embedding(
  141 + embedding.getEmbedding(),
  142 + embedding.getTextIndex()
  143 + ))
  144 + .collect(Collectors.toList());
  145 + }
  146 +
  147 + /**
  148 + * We recommend setting the model parameters by passing the embedding parameters through the code;
  149 + * yml configuration compatibility is not considered here.
  150 + * It is not recommended that users set parameters from yml,
  151 + * as this reduces the flexibility of the configuration.
  152 + * Because the model name keeps changing, strings are used here and constants are undefined:
  153 + * Model list: <a href="https://help.aliyun.com/zh/dashscope/developer-reference/text-embedding-quick-start">Text Embedding Model List</a>
  154 + * @param requestOptions Client params. {@link EmbeddingRequest}
  155 + * @return {@link TextEmbeddingParam}
  156 + */
  157 + private TextEmbeddingParam toEmbeddingParams(EmbeddingRequest requestOptions) {
  158 +
  159 + TextEmbeddingParam tongYiEmbeddingParams = TextEmbeddingParam.builder()
  160 + .texts(requestOptions.getInstructions())
  161 + .textType(defaultOptions.getTextType() != null ? defaultOptions.getTextType() : TextEmbeddingParam.TextType.DOCUMENT)
  162 + .model("text-embedding-v1")
  163 + .build();
  164 +
  165 + try {
  166 + tongYiEmbeddingParams.validate();
  167 + }
  168 + catch (InputRequiredException e) {
  169 + throw new TongYiException(e.getMessage());
  170 + }
  171 +
  172 + return tongYiEmbeddingParams;
  173 + }
  174 +
  175 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/embedding/TongYiTextEmbeddingProperties.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.embedding;
  18 +
  19 +import org.springframework.boot.context.properties.ConfigurationProperties;
  20 +
  21 +import static com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants.SCA_AI_CONFIGURATION;
  22 +
  23 +/**
  24 + * @author why_ohh
  25 + * @author yuluo
  26 + * @author <a href="mailto:550588941@qq.com">why_ohh</a>
  27 + * @since 2023.0.1.0
  28 + */
  29 +
  30 +@ConfigurationProperties(TongYiTextEmbeddingProperties.CONFIG_PREFIX)
  31 +public class TongYiTextEmbeddingProperties {
  32 +
  33 + /**
  34 + * Prefix of TongYi Text Embedding properties.
  35 + */
  36 + public static final String CONFIG_PREFIX = SCA_AI_CONFIGURATION + "embedding";
  37 +
  38 + private boolean enabled = true;
  39 +
  40 + public boolean isEnabled() {
  41 +
  42 + return this.enabled;
  43 + }
  44 +
  45 + public void setEnabled(boolean enabled) {
  46 +
  47 + this.enabled = enabled;
  48 + }
  49 +
  50 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/image/TongYiImagesModel.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.image;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.common.exception.TongYiImagesException;
  20 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
  21 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
  22 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
  23 +import com.alibaba.dashscope.exception.NoApiKeyException;
  24 +import org.slf4j.Logger;
  25 +import org.slf4j.LoggerFactory;
  26 +import org.springframework.ai.image.*;
  27 +import org.springframework.util.Assert;
  28 +
  29 +import java.io.ByteArrayOutputStream;
  30 +import java.net.URL;
  31 +import java.util.Base64;
  32 +import java.util.stream.Collectors;
  33 +
  34 +import static com.alibaba.cloud.ai.tongyi.metadata.TongYiImagesResponseMetadata.from;
  35 +
  36 +/**
  37 + * TongYiImagesClient is a class that implements the ImageClient interface. It provides a
  38 + * client for calling the TongYi AI image generation API.
  39 + *
  40 + * @author yuluo
  41 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  42 + * @since 2023.0.1.0
  43 + */
  44 +
  45 +public class TongYiImagesModel implements ImageModel {
  46 +
  47 + private final Logger logger = LoggerFactory.getLogger(TongYiImagesModel.class);
  48 +
  49 + /**
  50 + * Gen Images API.
  51 + */
  52 + private final ImageSynthesis imageSynthesis;
  53 +
  54 + /**
  55 + * TongYi Gen images properties.
  56 + */
  57 + private TongYiImagesOptions defaultOptions;
  58 +
  59 + /**
  60 + * Adapt TongYi images api size properties.
  61 + */
  62 + private final String sizeConnection = "*";
  63 +
  64 + /**
  65 + * Get default images options.
  66 + *
  67 + * @return Default TongYiImagesOptions.
  68 + */
  69 + public TongYiImagesOptions getDefaultOptions() {
  70 +
  71 + return this.defaultOptions;
  72 + }
  73 +
  74 + /**
  75 + * TongYiImagesClient constructor.
  76 + * @param imageSynthesis the image synthesis
  77 + * {@link ImageSynthesis}
  78 + */
  79 + public TongYiImagesModel(ImageSynthesis imageSynthesis) {
  80 +
  81 + this(imageSynthesis, TongYiImagesOptions.
  82 + builder()
  83 + .withModel(ImageSynthesis.Models.WANX_V1)
  84 + .withN(1)
  85 + .build()
  86 + );
  87 + }
  88 +
  89 + /**
  90 + * TongYiImagesClient constructor.
  91 + * @param imageSynthesis {@link ImageSynthesis}
  92 + * @param imagesOptions {@link TongYiImagesOptions}
  93 + */
  94 + public TongYiImagesModel(ImageSynthesis imageSynthesis, TongYiImagesOptions imagesOptions) {
  95 +
  96 + Assert.notNull(imageSynthesis, "ImageSynthesis must not be null");
  97 + Assert.notNull(imagesOptions, "TongYiImagesOptions must not be null");
  98 +
  99 + this.imageSynthesis = imageSynthesis;
  100 + this.defaultOptions = imagesOptions;
  101 + }
  102 +
  103 + /**
  104 + * Call the TongYi images service.
  105 + * @param imagePrompt the image prompt.
  106 + * @return the image response.
  107 + * {@link ImageSynthesis#call(ImageSynthesisParam)}
  108 + */
  109 + @Override
  110 + public ImageResponse call(ImagePrompt imagePrompt) {
  111 +
  112 + ImageSynthesisResult result;
  113 + String prompt = imagePrompt.getInstructions().get(0).getText();
  114 + var imgParams = ImageSynthesisParam.builder()
  115 + .prompt("")
  116 + .model(ImageSynthesis.Models.WANX_V1)
  117 + .build();
  118 +
  119 + if (this.defaultOptions != null) {
  120 +
  121 + imgParams = merge(this.defaultOptions);
  122 + }
  123 +
  124 + if (imagePrompt.getOptions() != null) {
  125 +
  126 + imgParams = merge(toTingYiImageOptions(imagePrompt.getOptions()));
  127 + }
  128 + imgParams.setPrompt(prompt);
  129 +
  130 + try {
  131 + result = imageSynthesis.call(imgParams);
  132 + }
  133 + catch (NoApiKeyException e) {
  134 +
  135 + logger.error("TongYi models gen images failed: {}.", e.getMessage());
  136 + throw new TongYiImagesException(e.getMessage());
  137 + }
  138 +
  139 + return convert(result);
  140 + }
  141 +
  142 + public ImageSynthesisParam merge(TongYiImagesOptions target) {
  143 +
  144 + var builder = ImageSynthesisParam.builder();
  145 +
  146 + builder.model(this.defaultOptions.getModel() != null ? this.defaultOptions.getModel() : target.getModel());
  147 + builder.n(this.defaultOptions.getN() != null ? this.defaultOptions.getN() : target.getN());
  148 + builder.size((this.defaultOptions.getHeight() != null && this.defaultOptions.getWidth() != null)
  149 + ? this.defaultOptions.getHeight() + "*" + this.defaultOptions.getWidth()
  150 + : target.getHeight() + "*" + target.getWidth()
  151 + );
  152 +
  153 + // prompt is marked non-null but is null.
  154 + builder.prompt("");
  155 +
  156 + return builder.build();
  157 + }
  158 +
  159 + private ImageResponse convert(ImageSynthesisResult result) {
  160 +
  161 + return new ImageResponse(
  162 + result.getOutput().getResults().stream()
  163 + .flatMap(value -> value.entrySet().stream())
  164 + .map(entry -> {
  165 + String key = entry.getKey();
  166 + String value = entry.getValue();
  167 + try {
  168 + String base64Image = convertImageToBase64(value);
  169 + Image image = new Image(value, base64Image);
  170 + return new ImageGeneration(image);
  171 + }
  172 + catch (Exception e) {
  173 + throw new RuntimeException(e);
  174 + }
  175 + })
  176 + .collect(Collectors.toList()),
  177 + from(result)
  178 + );
  179 + }
  180 +
  181 + public TongYiImagesOptions toTingYiImageOptions(ImageOptions runtimeImageOptions) {
  182 +
  183 + var builder = TongYiImagesOptions.builder();
  184 +
  185 + if (runtimeImageOptions != null) {
  186 + if (runtimeImageOptions.getN() != null) {
  187 +
  188 + builder.withN(runtimeImageOptions.getN());
  189 + }
  190 + if (runtimeImageOptions.getModel() != null) {
  191 +
  192 + builder.withModel(runtimeImageOptions.getModel());
  193 + }
  194 + if (runtimeImageOptions.getHeight() != null) {
  195 +
  196 + builder.withHeight(runtimeImageOptions.getHeight());
  197 + }
  198 + if (runtimeImageOptions.getWidth() != null) {
  199 +
  200 + builder.withWidth(runtimeImageOptions.getWidth());
  201 + }
  202 +
  203 + // todo ImagesParams.
  204 + }
  205 +
  206 + return builder.build();
  207 + }
  208 +
  209 + /**
  210 + * Convert image to base64.
  211 + * @param imageUrl the image url.
  212 + * @return the base64 image.
  213 + * @throws Exception the exception.
  214 + */
  215 + public String convertImageToBase64(String imageUrl) throws Exception {
  216 +
  217 + var url = new URL(imageUrl);
  218 + var inputStream = url.openStream();
  219 + var outputStream = new ByteArrayOutputStream();
  220 + var buffer = new byte[4096];
  221 + int bytesRead;
  222 +
  223 + while ((bytesRead = inputStream.read(buffer)) != -1) {
  224 + outputStream.write(buffer, 0, bytesRead);
  225 + }
  226 +
  227 + var imageBytes = outputStream.toByteArray();
  228 +
  229 + String base64Image = Base64.getEncoder().encodeToString(imageBytes);
  230 +
  231 + inputStream.close();
  232 + outputStream.close();
  233 +
  234 + return base64Image;
  235 + }
  236 +
  237 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/image/TongYiImagesOptions.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.image;
  18 +
  19 +import com.alibaba.cloud.ai.tongyi.common.exception.TongYiImagesException;
  20 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
  21 +import org.springframework.ai.image.ImageOptions;
  22 +
  23 +import java.util.Objects;
  24 +
  25 +/**
  26 + * TongYi Image API options.
  27 + *
  28 + * @author yuluo
  29 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  30 + * @since 2023.0.1.0
  31 + */
  32 +
  33 +public class TongYiImagesOptions implements ImageOptions {
  34 +
  35 + /**
  36 + * Specify the model name, currently only wanx-v1 is supported.
  37 + */
  38 + private String model = ImageSynthesis.Models.WANX_V1;
  39 +
  40 + /**
  41 + * Gen images number.
  42 + */
  43 + private Integer n;
  44 +
  45 + /**
  46 + * The width of the generated images.
  47 + */
  48 + private Integer width = 1024;
  49 +
  50 + /**
  51 + * The height of the generated images.
  52 + */
  53 + private Integer height = 1024;
  54 +
  55 + @Override
  56 + public Integer getN() {
  57 +
  58 + return this.n;
  59 + }
  60 +
  61 + @Override
  62 + public String getModel() {
  63 +
  64 + return this.model;
  65 + }
  66 +
  67 + @Override
  68 + public Integer getWidth() {
  69 +
  70 + return this.width;
  71 + }
  72 +
  73 + @Override
  74 + public Integer getHeight() {
  75 +
  76 + return this.height;
  77 + }
  78 +
  79 + @Override
  80 + public String getResponseFormat() {
  81 +
  82 + throw new TongYiImagesException("unimplemented!");
  83 + }
  84 +
  85 + public void setModel(String model) {
  86 +
  87 + this.model = model;
  88 + }
  89 +
  90 + public void setN(Integer n) {
  91 +
  92 + this.n = n;
  93 + }
  94 +
  95 + public void setWidth(Integer width) {
  96 +
  97 + this.width = width;
  98 + }
  99 +
  100 + public void setHeight(Integer height) {
  101 +
  102 + this.height = height;
  103 + }
  104 +
  105 + @Override
  106 + public boolean equals(Object o) {
  107 + if (this == o) {
  108 +
  109 + return true;
  110 + }
  111 + if (o == null || getClass() != o.getClass()) {
  112 +
  113 + return false;
  114 + }
  115 +
  116 + TongYiImagesOptions that = (TongYiImagesOptions) o;
  117 +
  118 + return Objects.equals(model, that.model)
  119 + && Objects.equals(n, that.n)
  120 + && Objects.equals(width, that.width)
  121 + && Objects.equals(height, that.height);
  122 + }
  123 +
  124 + @Override
  125 + public int hashCode() {
  126 +
  127 + return Objects.hash(model, n, width, height);
  128 + }
  129 +
  130 + @Override
  131 + public String toString() {
  132 +
  133 + final StringBuilder sb = new StringBuilder("TongYiImagesOptions{");
  134 +
  135 + sb.append("model='").append(model).append('\'');
  136 + sb.append(", n=").append(n);
  137 + sb.append(", width=").append(width);
  138 + sb.append(", height=").append(height);
  139 + sb.append('}');
  140 +
  141 + return sb.toString();
  142 + }
  143 +
  144 + public static Builder builder() {
  145 + return new Builder();
  146 + }
  147 +
  148 + public final static class Builder {
  149 +
  150 + private final TongYiImagesOptions options;
  151 +
  152 + private Builder() {
  153 + this.options = new TongYiImagesOptions();
  154 + }
  155 +
  156 + public Builder withN(Integer n) {
  157 +
  158 + options.setN(n);
  159 + return this;
  160 + }
  161 +
  162 + public Builder withModel(String model) {
  163 +
  164 + options.setModel(model);
  165 + return this;
  166 + }
  167 +
  168 + public Builder withWidth(Integer width) {
  169 +
  170 + options.setWidth(width);
  171 + return this;
  172 + }
  173 +
  174 + public Builder withHeight(Integer height) {
  175 +
  176 + options.setHeight(height);
  177 + return this;
  178 + }
  179 +
  180 + public TongYiImagesOptions build() {
  181 +
  182 + return options;
  183 + }
  184 +
  185 + }
  186 +
  187 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/image/TongYiImagesProperties.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.image;
  18 +
  19 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
  20 +import org.springframework.boot.context.properties.ConfigurationProperties;
  21 +import org.springframework.boot.context.properties.NestedConfigurationProperty;
  22 +
  23 +import static com.alibaba.cloud.ai.tongyi.common.constants.TongYiConstants.SCA_AI_CONFIGURATION;
  24 +
  25 +/**
  26 + * TongYi Image API properties.
  27 + *
  28 + * @author yuluo
  29 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  30 + * @since 2023.0.1.0
  31 + */
  32 +
  33 +@ConfigurationProperties(TongYiImagesProperties.CONFIG_PREFIX)
  34 +public class TongYiImagesProperties {
  35 +
  36 + /**
  37 + * Spring Cloud Alibaba AI configuration prefix.
  38 + */
  39 + public static final String CONFIG_PREFIX = SCA_AI_CONFIGURATION + "images";
  40 +
  41 + /**
  42 + * Default TongYi Chat model.
  43 + */
  44 + public static final String DEFAULT_IMAGES_MODEL_NAME = ImageSynthesis.Models.WANX_V1;
  45 +
  46 + /**
  47 + * Enable TongYiQWEN ai images client.
  48 + */
  49 + private boolean enabled = true;
  50 +
  51 + @NestedConfigurationProperty
  52 + private TongYiImagesOptions options = TongYiImagesOptions.builder()
  53 + .withModel(DEFAULT_IMAGES_MODEL_NAME)
  54 + .withN(1)
  55 + .build();
  56 +
  57 + public TongYiImagesOptions getOptions() {
  58 +
  59 + return this.options;
  60 + }
  61 +
  62 + public void setOptions(TongYiImagesOptions options) {
  63 +
  64 + this.options = options;
  65 + }
  66 +
  67 + public boolean isEnabled() {
  68 +
  69 + return this.enabled;
  70 + }
  71 +
  72 + public void setEnabled(boolean enabled) {
  73 +
  74 + this.enabled = enabled;
  75 + }
  76 +
  77 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/TongYiAiChatResponseMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata;
  18 +
  19 +import com.alibaba.dashscope.aigc.generation.GenerationResult;
  20 +import org.springframework.ai.chat.metadata.ChatResponseMetadata;
  21 +import org.springframework.ai.chat.metadata.PromptMetadata;
  22 +import org.springframework.ai.chat.metadata.Usage;
  23 +import org.springframework.util.Assert;
  24 +
  25 +import java.util.HashMap;
  26 +
  27 +
  28 +
  29 +/**
  30 + * {@link ChatResponseMetadata} implementation for {@literal Alibaba DashScope}.
  31 + *
  32 + * @author yuluo
  33 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  34 + * @since 2023.0.1.0
  35 + */
  36 +
  37 +public class TongYiAiChatResponseMetadata extends HashMap<String, Object> implements ChatResponseMetadata {
  38 +
  39 + protected static final String AI_METADATA_STRING = "{ @type: %1$s, id: %2$s, usage: %3$s, rateLimit: %4$s }";
  40 +
  41 + @SuppressWarnings("all")
  42 + public static TongYiAiChatResponseMetadata from(GenerationResult chatCompletions,
  43 + PromptMetadata promptFilterMetadata) {
  44 +
  45 + Assert.notNull(chatCompletions, "Alibaba ai ChatCompletions must not be null");
  46 + String id = chatCompletions.getRequestId();
  47 + TongYiAiUsage usage = TongYiAiUsage.from(chatCompletions);
  48 +
  49 + return new TongYiAiChatResponseMetadata(
  50 + id,
  51 + usage,
  52 + promptFilterMetadata
  53 + );
  54 + }
  55 +
  56 + private final String id;
  57 +
  58 + private final Usage usage;
  59 +
  60 + private final PromptMetadata promptMetadata;
  61 +
  62 + protected TongYiAiChatResponseMetadata(String id, TongYiAiUsage usage, PromptMetadata promptMetadata) {
  63 +
  64 + this.id = id;
  65 + this.usage = usage;
  66 + this.promptMetadata = promptMetadata;
  67 + }
  68 +
  69 + public String getId() {
  70 + return this.id;
  71 + }
  72 +
  73 + @Override
  74 + public Usage getUsage() {
  75 + return this.usage;
  76 + }
  77 +
  78 + @Override
  79 + public PromptMetadata getPromptMetadata() {
  80 + return this.promptMetadata;
  81 + }
  82 +
  83 + @Override
  84 + public String toString() {
  85 +
  86 + return AI_METADATA_STRING.formatted(getClass().getTypeName(), getId(), getUsage(), getRateLimit());
  87 + }
  88 +
  89 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/TongYiAiUsage.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata;
  18 +
  19 +import com.alibaba.dashscope.aigc.generation.GenerationResult;
  20 +import com.alibaba.dashscope.aigc.generation.GenerationUsage;
  21 +import org.springframework.ai.chat.metadata.Usage;
  22 +import org.springframework.util.Assert;
  23 +
  24 +/**
  25 + * {@link Usage} implementation for {@literal Alibaba DashScope}.
  26 + *
  27 + * @author yuluo
  28 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  29 + * @since 2023.0.1.0
  30 + */
  31 +
  32 +public class TongYiAiUsage implements Usage {
  33 +
  34 + private final GenerationUsage usage;
  35 +
  36 + public TongYiAiUsage(GenerationUsage usage) {
  37 +
  38 + Assert.notNull(usage, "GenerationUsage must not be null");
  39 + this.usage = usage;
  40 + }
  41 +
  42 + public static TongYiAiUsage from(GenerationResult chatCompletions) {
  43 +
  44 + Assert.notNull(chatCompletions, "ChatCompletions must not be null");
  45 + return from(chatCompletions.getUsage());
  46 + }
  47 +
  48 + public static TongYiAiUsage from(GenerationUsage usage) {
  49 +
  50 + return new TongYiAiUsage(usage);
  51 + }
  52 +
  53 + protected GenerationUsage getUsage() {
  54 +
  55 + return this.usage;
  56 + }
  57 +
  58 + @Override
  59 + public Long getPromptTokens() {
  60 +
  61 + throw new UnsupportedOperationException("Unimplemented method 'getPromptTokens'");
  62 + }
  63 +
  64 + @Override
  65 + public Long getGenerationTokens() {
  66 +
  67 + return this.getUsage().getOutputTokens().longValue();
  68 + }
  69 +
  70 + @Override
  71 + public Long getTotalTokens() {
  72 +
  73 + return this.getUsage().getTotalTokens().longValue();
  74 + }
  75 +
  76 + @Override
  77 + public String toString() {
  78 +
  79 + return this.getUsage().toString();
  80 + }
  81 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/TongYiImagesResponseMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata;
  18 +
  19 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
  20 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisTaskMetrics;
  21 +import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisUsage;
  22 +import org.springframework.ai.image.ImageResponseMetadata;
  23 +import org.springframework.util.Assert;
  24 +
  25 +import java.util.HashMap;
  26 +import java.util.Objects;
  27 +
  28 +/**
  29 + * @author yuluo
  30 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  31 + * @since 2023.0.1.0
  32 + */
  33 +
  34 +public class TongYiImagesResponseMetadata extends HashMap<String, Object> implements ImageResponseMetadata {
  35 +
  36 + private final Long created;
  37 +
  38 + private String taskId;
  39 +
  40 + private ImageSynthesisTaskMetrics metrics;
  41 +
  42 + private ImageSynthesisUsage usage;
  43 +
  44 + public static TongYiImagesResponseMetadata from(ImageSynthesisResult synthesisResult) {
  45 +
  46 + Assert.notNull(synthesisResult, "TongYiAiImageResponse must not be null");
  47 +
  48 + return new TongYiImagesResponseMetadata(
  49 + System.currentTimeMillis(),
  50 + synthesisResult.getOutput().getTaskMetrics(),
  51 + synthesisResult.getOutput().getTaskId(),
  52 + synthesisResult.getUsage()
  53 + );
  54 + }
  55 +
  56 + protected TongYiImagesResponseMetadata(
  57 + Long created,
  58 + ImageSynthesisTaskMetrics metrics,
  59 + String taskId,
  60 + ImageSynthesisUsage usage
  61 + ) {
  62 +
  63 + this.taskId = taskId;
  64 + this.metrics = metrics;
  65 + this.created = created;
  66 + this.usage = usage;
  67 + }
  68 +
  69 + public ImageSynthesisUsage getUsage() {
  70 + return usage;
  71 + }
  72 +
  73 + public void setUsage(ImageSynthesisUsage usage) {
  74 + this.usage = usage;
  75 + }
  76 +
  77 + @Override
  78 + public Long getCreated() {
  79 + return created;
  80 + }
  81 +
  82 + public String getTaskId() {
  83 + return taskId;
  84 + }
  85 +
  86 + public void setTaskId(String taskId) {
  87 + this.taskId = taskId;
  88 + }
  89 +
  90 + public ImageSynthesisTaskMetrics getMetrics() {
  91 + return metrics;
  92 + }
  93 +
  94 + void setMetrics(ImageSynthesisTaskMetrics metrics) {
  95 + this.metrics = metrics;
  96 + }
  97 +
  98 +
  99 + public Long created() {
  100 + return this.created;
  101 + }
  102 +
  103 + @Override
  104 + public String toString() {
  105 + return "TongYiImagesResponseMetadata {" + "created=" + created + '}';
  106 + }
  107 +
  108 + @Override
  109 + public boolean equals(Object o) {
  110 + if (this == o) {
  111 +
  112 + return true;
  113 + }
  114 + if (o == null || getClass() != o.getClass()) {
  115 +
  116 + return false;
  117 + }
  118 +
  119 + TongYiImagesResponseMetadata that = (TongYiImagesResponseMetadata) o;
  120 +
  121 + return Objects.equals(created, that.created)
  122 + && Objects.equals(taskId, that.taskId)
  123 + && Objects.equals(metrics, that.metrics);
  124 + }
  125 +
  126 + @Override
  127 + public int hashCode() {
  128 + return Objects.hash(created, taskId, metrics);
  129 + }
  130 +
  131 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/TongYiTextEmbeddingResponseMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata;
  18 +
  19 +import com.alibaba.dashscope.embeddings.TextEmbeddingUsage;
  20 +import org.springframework.ai.embedding.EmbeddingResponseMetadata;
  21 +
  22 +/**
  23 + * @author why_ohh
  24 + * @author yuluo
  25 + * @author <a href="mailto:550588941@qq.com">why_ohh</a>
  26 + * @since 2023.0.1.0
  27 + */
  28 +
  29 +public class TongYiTextEmbeddingResponseMetadata extends EmbeddingResponseMetadata {
  30 +
  31 + private Integer totalTokens;
  32 +
  33 + protected TongYiTextEmbeddingResponseMetadata(Integer totalTokens) {
  34 +
  35 + this.totalTokens = totalTokens;
  36 + }
  37 +
  38 + public static TongYiTextEmbeddingResponseMetadata from(TextEmbeddingUsage usage) {
  39 +
  40 + return new TongYiTextEmbeddingResponseMetadata(usage.getTotalTokens());
  41 + }
  42 +
  43 + public Integer getTotalTokens() {
  44 +
  45 + return totalTokens;
  46 + }
  47 +
  48 + public void setTotalTokens(Integer totalTokens) {
  49 +
  50 + this.totalTokens = totalTokens;
  51 + }
  52 +
  53 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/audio/TongYiAudioSpeechResponseMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata.audio;
  18 +
  19 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
  20 +import com.alibaba.dashscope.audio.tts.SpeechSynthesisUsage;
  21 +import com.alibaba.dashscope.audio.tts.timestamp.Sentence;
  22 +import org.springframework.ai.chat.metadata.EmptyRateLimit;
  23 +import org.springframework.ai.chat.metadata.RateLimit;
  24 +import org.springframework.ai.model.ResponseMetadata;
  25 +import org.springframework.lang.Nullable;
  26 +import org.springframework.util.Assert;
  27 +
  28 +import java.util.HashMap;
  29 +
  30 +
  31 +
  32 +/**
  33 + * @author yuluo
  34 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  35 + * @since 2023.0.1.0
  36 + */
  37 +
  38 +public class TongYiAudioSpeechResponseMetadata extends HashMap<String, Object> implements ResponseMetadata {
  39 +
  40 + private SpeechSynthesisUsage usage;
  41 +
  42 + private String requestId;
  43 +
  44 + private Sentence time;
  45 +
  46 + protected static final String AI_METADATA_STRING = "{ @type: %1$s, requestsLimit: %2$s }";
  47 +
  48 + /**
  49 + * NULL objects.
  50 + */
  51 + public static final TongYiAudioSpeechResponseMetadata NULL = new TongYiAudioSpeechResponseMetadata() {
  52 + };
  53 +
  54 + public static TongYiAudioSpeechResponseMetadata from(SpeechSynthesisResult result) {
  55 +
  56 + Assert.notNull(result, "TongYi AI speech must not be null");
  57 + TongYiAudioSpeechResponseMetadata speechResponseMetadata = new TongYiAudioSpeechResponseMetadata();
  58 +
  59 +
  60 +
  61 + return speechResponseMetadata;
  62 + }
  63 +
  64 + public static TongYiAudioSpeechResponseMetadata from(String result) {
  65 +
  66 + Assert.notNull(result, "TongYi AI speech must not be null");
  67 + TongYiAudioSpeechResponseMetadata speechResponseMetadata = new TongYiAudioSpeechResponseMetadata();
  68 +
  69 + return speechResponseMetadata;
  70 + }
  71 +
  72 + @Nullable
  73 + private RateLimit rateLimit;
  74 +
  75 + public TongYiAudioSpeechResponseMetadata() {
  76 +
  77 + this(null);
  78 + }
  79 +
  80 + public TongYiAudioSpeechResponseMetadata(@Nullable RateLimit rateLimit) {
  81 +
  82 + this.rateLimit = rateLimit;
  83 + }
  84 +
  85 + @Nullable
  86 + public RateLimit getRateLimit() {
  87 +
  88 + RateLimit rateLimit = this.rateLimit;
  89 + return rateLimit != null ? rateLimit : new EmptyRateLimit();
  90 + }
  91 +
  92 + public TongYiAudioSpeechResponseMetadata withRateLimit(RateLimit rateLimit) {
  93 +
  94 + this.rateLimit = rateLimit;
  95 + return this;
  96 + }
  97 +
  98 + public TongYiAudioSpeechResponseMetadata withUsage(SpeechSynthesisUsage usage) {
  99 +
  100 + this.usage = usage;
  101 + return this;
  102 + }
  103 +
  104 + public TongYiAudioSpeechResponseMetadata withRequestId(String id) {
  105 +
  106 + this.requestId = id;
  107 + return this;
  108 + }
  109 +
  110 + public TongYiAudioSpeechResponseMetadata withSentence(Sentence sentence) {
  111 +
  112 + this.time = sentence;
  113 + return this;
  114 + }
  115 +
  116 + public SpeechSynthesisUsage getUsage() {
  117 + return usage;
  118 + }
  119 +
  120 + public String getRequestId() {
  121 + return requestId;
  122 + }
  123 +
  124 + public Sentence getTime() {
  125 + return time;
  126 + }
  127 +
  128 + @Override
  129 + public String toString() {
  130 + return AI_METADATA_STRING.formatted(getClass().getName(), getRateLimit());
  131 + }
  132 +
  133 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/audio/TongYiAudioTranscriptionMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata.audio;
  18 +
  19 +import org.springframework.ai.model.ResultMetadata;
  20 +
  21 +/**
  22 + * @author xYLiu
  23 + * @author yuluo
  24 + * @since 2023.0.1.0
  25 + */
  26 +
  27 +public interface TongYiAudioTranscriptionMetadata extends ResultMetadata {
  28 +
  29 + /**
  30 + * A constant instance of {@link TongYiAudioTranscriptionMetadata} that represents a null or empty metadata.
  31 + */
  32 + TongYiAudioTranscriptionMetadata NULL = TongYiAudioTranscriptionMetadata.create();
  33 +
  34 + /**
  35 + * Factory method for creating a new instance of {@link TongYiAudioTranscriptionMetadata}.
  36 + * @return a new instance of {@link TongYiAudioTranscriptionMetadata}
  37 + */
  38 + static TongYiAudioTranscriptionMetadata create() {
  39 + return new TongYiAudioTranscriptionMetadata() {
  40 + };
  41 + }
  42 +
  43 +}
... ...
yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/com/alibaba/cloud/ai/tongyi/metadata/audio/TongYiAudioTranscriptionResponseMetadata.java 0 → 100644
  1 +/*
  2 + * Copyright 2023-2024 the original author or authors.
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * https://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +
  17 +package com.alibaba.cloud.ai.tongyi.metadata.audio;
  18 +
  19 +import com.alibaba.dashscope.audio.asr.transcription.TranscriptionResult;
  20 +import com.google.gson.JsonObject;
  21 +import org.springframework.ai.chat.metadata.EmptyRateLimit;
  22 +import org.springframework.ai.chat.metadata.RateLimit;
  23 +import org.springframework.ai.model.ResponseMetadata;
  24 +import org.springframework.util.Assert;
  25 +
  26 +import javax.annotation.Nullable;
  27 +import java.util.HashMap;
  28 +
  29 +
  30 +
  31 +/**
  32 + * @author yuluo
  33 + * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
  34 + * @since 2023.0.1.0
  35 + */
  36 +
  37 +public class TongYiAudioTranscriptionResponseMetadata extends HashMap<String, Object> implements ResponseMetadata {
  38 +
  39 + @Nullable
  40 + private RateLimit rateLimit;
  41 +
  42 + private JsonObject usage;
  43 +
  44 + protected static final String AI_METADATA_STRING = "{ @type: %1$s, rateLimit: %4$s }";
  45 +
  46 + /**
  47 + * NULL objects.
  48 + */
  49 + public static final TongYiAudioTranscriptionResponseMetadata NULL = new TongYiAudioTranscriptionResponseMetadata() {
  50 + };
  51 +
  52 + protected TongYiAudioTranscriptionResponseMetadata() {
  53 +
  54 + this(null, new JsonObject());
  55 + }
  56 +
  57 + protected TongYiAudioTranscriptionResponseMetadata(JsonObject usage) {
  58 +
  59 + this(null, usage);
  60 + }
  61 +
  62 + protected TongYiAudioTranscriptionResponseMetadata(@Nullable RateLimit rateLimit, JsonObject usage) {
  63 +
  64 + this.rateLimit = rateLimit;
  65 + this.usage = usage;
  66 + }
  67 +
  68 + public static TongYiAudioTranscriptionResponseMetadata from(TranscriptionResult result) {
  69 +
  70 + Assert.notNull(result, "TongYi Transcription must not be null");
  71 + return new TongYiAudioTranscriptionResponseMetadata(result.getUsage());
  72 + }
  73 +
  74 + @Nullable
  75 + public RateLimit getRateLimit() {
  76 +
  77 + return this.rateLimit != null ? this.rateLimit : new EmptyRateLimit();
  78 + }
  79 +
  80 + public void setRateLimit(@Nullable RateLimit rateLimit) {
  81 + this.rateLimit = rateLimit;
  82 + }
  83 +
  84 + public JsonObject getUsage() {
  85 + return usage;
  86 + }
  87 +
  88 + public void setUsage(JsonObject usage) {
  89 + this.usage = usage;
  90 + }
  91 +
  92 + @Override
  93 + public String toString() {
  94 +
  95 + return AI_METADATA_STRING.formatted(getClass().getName(), getRateLimit());
  96 + }
  97 +
  98 +}
... ...
yudao-server/src/main/resources/application.yaml
... ... @@ -163,6 +163,11 @@ spring:
163 163 qianfan: # 文心一言
164 164 api-key: x0cuLZ7XsaTCU08vuJWO87Lg
165 165 secret-key: R9mYF9dl9KASgi5RUq0FQt3wRisSnOcK
  166 + cloud:
  167 + ai:
  168 + tongyi: # 通义千问
  169 + tongyi:
  170 + api-key: sk-Zsd81gZYg7
166 171  
167 172 yudao.ai:
168 173 xinghuo:
... ...