5分钟体验Spring Cloud Alibaba AI应用

343 阅读4分钟

Spring Cloud Alibaba AI 目前基于 Spring AI 0.8.1 版本 API 完成通义系列大模型的接入。通义接入是基于阿里云 灵积模型服务,灵积模型服务建立在"模型即服务"(Model-as-a-Service,MaaS)的理念基础之上,围绕 AI 各领域模型,通过标准化的API提供包括模型推理、模型微调训练在内的多种模型服务。

简介

在当前最新版本中,Spring Cloud Alibaba AI 主要完成了几种常见生成式模型的适配,包括对话、文生图、文生语音等,开发者可以使用 Spring Cloud Alibaba AI 开发基于通义的聊天、图片或语音生成 AI 应用,框架还提供 OutParser、Prompt Template、Stuff 等实用能力。

动手体验

1. 新建项目

首先新建一个Maven项目,JDK选的是17版本

2. pom.xml文件引入依赖

项目pom.xml文件引入spring-cloud-alibaba-dependenciesspring-cloud-starter-alibaba-ai两个依赖

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2023.0.1.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-ai</artifactId>
    </dependency>
</dependencies>

<!-- 添加以下配置解决拉取不到spring-ai-core依赖包问题 -->
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
</repositories>

3. 添加阿里云通义千问的API KEY

首先创建通义千问API KEY,具体教程链接如下:help.aliyun.com/zh/dashscop…

然后在Spring Boot项目添加application.properties配置文件,加入以下内容(替成你创建的api-key)

server.port=8089
spring.application.name=jms-ai-tongyi

spring.cloud.ai.tongyi.api-key=你创建的api-key

4. 添加Spring Boot启动类

添加Spring Boot启动类TongYiApplication

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

5. 添加Controller控制器类

新建一个控制器类TongYiController,添加文本模型、文生图模型、语音合成模型接口:

@RestController
@RequestMapping("/ai")
@CrossOrigin
@RequiredArgsConstructor
public class TongYiController {
    private final TongYiService tongYiService;

    /**
     * 对接文本模型
     *
     * @param message 消息内容
     * @return AI答案
     */
    @GetMapping("/example")
    public String completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return tongYiService.completion(message);
    }

    /**
     * 对接文生图模型
     *
     * @param imgPrompt 图片描述
     * @return AI答案
     */
    @GetMapping("/img")
    public ImageResponse genImg(@RequestParam(value = "prompt", defaultValue = "Painting a picture of blue water and blue sky.") String imgPrompt) {
        return tongYiService.genImg(imgPrompt);
    }

    /**
     * 对接语音合成模型
     *
     * @param message 消息内容
     * @return AI答案
     */
    @GetMapping("/audio")
    public String genAudio(@RequestParam(value = "message", defaultValue = "Hello,Spring Cloud Alibaba AI.") String message) {
        return tongYiService.genAudio(message);
    }
}

6. 添加Service服务接口和实现类

新建一个TongYiService接口,支持文本模型、文生图模型、语音合成模型处理方法:

public interface TongYiService {
    /**
     * 文本模型
     *
     * @param message 消息内容
     * @return AI答案
     */
    String completion(String message);

    /**
     * 文生图模型
     *
     * @param imgPrompt 图片描述
     * @return AI答案
     */
    ImageResponse genImg(String imgPrompt);

    /**
     * 语音合成模型
     *
     * @param message 消息内容
     * @return AI答案
     */
    String genAudio(String message);
}

新建一个TongYiServiceImpl类实现TongYiService接口,具体实现如下:

@Service
@RequiredArgsConstructor
public class TongYiServiceImpl implements TongYiService {
    private final ChatClient chatClient;
    private final ImageClient imageClient;
    private final SpeechClient speechClient;

    /**
     * 文本模型
     *
     * @param message 消息内容
     * @return AI答案
     */
    @Override
    public String completion(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatClient.call(prompt).getResult().getOutput().getContent();
    }

    /**
     * 文生图模型
     *
     * @param imgPrompt 图片描述
     * @return AI答案
     */
    @Override
    public ImageResponse genImg(String imgPrompt) {
        var prompt = new ImagePrompt(imgPrompt);
        return imageClient.call(prompt);
    }

    /**
     * 语音合成模型
     *
     * @param message 消息内容
     * @return AI答案
     */
    @Override
    public String genAudio(String message) {
        var resWAV = speechClient.call(message);
        return save(resWAV, SpeechSynthesisAudioFormat.WAV.getValue());
    }

    /**
     * 保存语音文件
     *
     * @param audio 语音内容
     * @param type  类型
     * @return 文件信息
     */
    private String save(ByteBuffer audio, String type) {
        String currentPath = System.getProperty("user.dir");
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-HH-mm-ss");
        String fileName = currentPath + File.separator + now.format(formatter) + "." + type;
        File file = new File(fileName);

        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return fileName;
    }
}

可以看到,几行代码就搞定了,非常简单。

接下来启动TongYiApplication应用来测试下效果!!!

测试

文本模型

调用文本模型接口,可以看到AI生成了一个笑话。

文生图模型

调用文生图模型接口,可以看到AI生成了我们想要的图片。

音频合成模型

调用音频合成模型接口,可以看到AI帮我们生成了音频文件。

总结

Spring Cloud Alibaba AI 框架提供了多种模型选择,简化了我们AI开发功能。目前接口响应时间较长,体验效果不是很好,静等官方后续接口优化。Spring Cloud Alibaba AI 介绍到此就结束了,感兴趣的同学可以去试试哈!

推荐阅读