首页 > 其他分享 >快速上手Spring Cloud Alibaba AI

快速上手Spring Cloud Alibaba AI

时间:2024-07-25 23:26:46浏览次数:10  
标签:return String AI Spring Alibaba new message public

文章目录

什么是 Spring Cloud Alibaba AI

原始的Spring AI并没有国内相关大模型的接入,对国内开发者不太友好。

总的来说,Spring Cloud Alibaba AI 目前基于Spring AI 0.8.1版本 API 完成通义系列大模型的接入。

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

动手体验 Spring Cloud Alibaba AI

使用Ai的jdk最低版本17,使用老版本的需要重新下载jdk。

https://www.oracle.com/cn/java/technologies/downloads/#java17

jdk17的Windows版本链接已提供,只需要下载解压即可以使用。

1.创建maven项目 导入以下依赖

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

    <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>

因为 Spring AI 还没有正式发布到 maven 仓库,所以需要添加仓库配置项

<!-- 因为 Spring AI 还没有正式发布到 maven 仓库,所以需要添加此配置项 目前 maven 仓库为假的。
issue:https://github.com/spring-projects/spring-ai/issues/537
-->
<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>

2.在Resource包中创建application.yml文件,并配置api-key

在正式开始体验之前,需要申请到模型的 api-key。申请地址:https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key

申请完只有30天的免费试用。

spring:
  cloud:
    ai:
      tongyi:
        # api-key setting:
        api-key: sk-xxxxxxxxxxxxxxxxxxx

3.创建Controller和service开始使用

聊天对话、图片生成、语音生成体验

Controller代码

@RestController
@CrossOrigin
@RequestMapping("/ai")
public class TongYiController {

    @Resource
    private TongYiService tongYiService;

	 /**
     * 聊天对话体验
     * @param msg
     * @return
     */
    @GetMapping("/getMsg")
    public String getMessage(@RequestParam(value = "msg",defaultValue = "讲一个笑话") String msg){
        return tongYiService.completion(msg);
    }
	 /**
     * 体验生成图片
     * @param msg
     * @return
     */
    @GetMapping("/getImage")
    public ResponseEntity<byte[]> getImage(@RequestParam(value = "msg",defaultValue = "动漫女主图片") String msg){
        ResponseEntity<byte[]> responseEntity = tongYiService.genImg(msg);
        return responseEntity;
    }
      
    /**
     * 流式客户端形式
     * @param message
     * @return
     */
    @GetMapping("/stream")
    public Map<String, String> streamCompletion(
            @RequestParam(value = "message", defaultValue = "请告诉我西红柿炖牛腩怎么做?") String message) {
        return tongYiService.streamCompletion(message);
    }
    
      /**
     * 生成语音
     * @param prompt
     * @return
     */
    @GetMapping("/audio")
    public String genAudio(@RequestParam(value = "prompt",
            defaultValue = "你好,Spring Cloud Alibaba AI 框架!") String prompt) {

        return tongYiService.genAudio(prompt);
    }
    
}

service代码

public interface TongYiService {

    /**
     * 基本问答
     */
    String completion(String message);
    
    /**
     * 文生图
     */
    ResponseEntity<byte[]> genImg(String imgPrompt);

    /**
     * 语音合成
     */
    String genAudio(String text);
	    
	 /**
     * 流式回答
     * @param message
     * @return
     */
    Map<String, String> streamCompletion(String message);

}

service实现类代码(只能使用的构造器注入)推荐使用client封装一个工具类,而不是写在service里面。

@Service
public class TongYiSimpleServiceImpl implements TongYiService {
    /**
     * 自动注入ChatClient、imageClient、StreamingChatClient,屏蔽模型调用细节
     */
    private final ChatClient chatClient;

    private final ImageClient imageClient;

    private final StreamingChatClient streamingChatClient;

    @Autowired
    public TongYiSimpleServiceImpl(ChatClient chatClient, StreamingChatClient streamingChatClient,ImageClient imageClient) {
        this.chatClient = chatClient;
        this.imageClient = imageClient;
        this.streamingChatClient = streamingChatClient;
    }
    
    /**
     * 具体实现:
     */
    @Override
    public String completion(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatClient.call(prompt).getResult().getOutput().getContent();
    }

    @Override
    public ResponseEntity<byte[]> genImg(String imgPrompt) {
        ImagePrompt imagePrompt = new ImagePrompt(imgPrompt);
        ImageResponse response = imageClient.call(imagePrompt);
        //处理生成的图片base64码
        String b64Json = response.getResult().getOutput().getB64Json();
        //将b64转换成图片返回给前端
        byte[] decode = Base64.getDecoder().decode(b64Json);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(decode,httpHeaders, HttpStatus.OK);
    }
    
    @Override
    public Map<String, String> streamCompletion(String message) {

        StringBuilder fullContent = new StringBuilder();

        streamingChatClient.stream(new Prompt(message))
                .flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults()))
                .map(content -> content.getOutput().getContent())
                .doOnNext(fullContent::append)
                .last()
                .map(lastContent -> Map.of(message, fullContent.toString()))
                .block();
        return Map.of(message, fullContent.toString());
    }
        @Override
    public String genAudio(String text) {
        var resWAV = speechClient.call(text);
        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;
    }
    
}

启动项目,浏览器输入地址测试

1.localhost:8080/ai/getMsg聊天对话测试

在这里插入图片描述

localhost:8080/ai/stream采用流式客户端方式测试(对话形式)

在这里插入图片描述

2.getImage (1024×1024)生成图片测试

在这里插入图片描述

  1. localhost:8080/ai/audio生成语音测试,返回路径(默认项目路径)

在这里插入图片描述

封装工具类

有了之前的实现,我们封装工具类就很方便

@Component
public class CloudAiUtil {

    private final ChatClient chatClient;
    //图片客户端
    private final ImageClient imageClient;

    //语言客户端
    private final SpeechClient speechClient;

    // stream 流式客户端
    private final StreamingChatClient streamingChatClient;

    @Autowired
    public CloudAiUtil(ChatClient chatClient, StreamingChatClient streamingChatClient, ImageClient imageClient, SpeechClient speechClient) {
        this.chatClient = chatClient;
        this.imageClient = imageClient;
        this.streamingChatClient = streamingChatClient;
        this.speechClient = speechClient;
    }

    public String completion(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatClient.call(prompt).getResult().getOutput().getContent();
    }

    public ResponseEntity<byte[]> genImg(String imgPrompt) {
        ImagePrompt imagePrompt = new ImagePrompt(imgPrompt);
        ImageResponse response = imageClient.call(imagePrompt);
        //处理生成的图片base64码
        String b64Json = response.getResult().getOutput().getB64Json();
        //将b64转换成图片返回给前端
        byte[] decode = Base64.getDecoder().decode(b64Json);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(decode, httpHeaders, HttpStatus.OK);
    }

    public Map<String, String> streamCompletion(String message) {

        StringBuilder fullContent = new StringBuilder();

        streamingChatClient.stream(new Prompt(message))
                .flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults()))
                .map(content -> content.getOutput().getContent())
                .doOnNext(fullContent::append)
                .last()
                .map(lastContent -> Map.of(message, fullContent.toString()))
                .block();
        return Map.of(message, fullContent.toString());
    }


    public String genAudio(String text) {
        var resWAV = speechClient.call(text);
        return save(resWAV, SpeechSynthesisAudioFormat.WAV.getValue());
    }

    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;
    }

}

这样我们service代码就很简介,同时这个工具类可以在任意service使用

@Service
public class TongYiSimpleServiceImpl implements TongYiService {
    @Resource
    private CloudAiUtil cloudAiUtil;

    @Override
    public String completion(String message) {
       return cloudAiUtil.completion(message);
    }
 }

标签:return,String,AI,Spring,Alibaba,new,message,public
From: https://blog.csdn.net/zyy030616/article/details/140702190

相关文章

  • 基于SpringBoot+Vue+uniapp的旅游网站的详细设计和实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • Spring Boot日志
    一,日志是什么日志我们在一开始的学习中就有了解,一开始我们就已经使用过了System.out.print来打印日志了。但在项目中这种肯定满足不了。就需要一些专门的日志框架来达到我们的要求。1.1日志的用途1.系统监控我们在这里可以设置不同的值,在达到一定程度的超过阈值之后,进行报......
  • LangChain的快速入门指南
    初识LangChain的快速入门指南在现代人工智能的世界里,语言模型(LanguageModel,LM)正在变得越来越重要。这些模型通过处理自然语言数据,为用户提供智能化的解决方案。LangChain作为一种创新工具,旨在简化语言模型的集成和使用,尤其是在开发复杂应用时。本文将为您详细介绍LangCh......
  • 实现一个自己的OpenFeign 远程调用验证协议--Springboot 自定义拦截器验证请求合法性-
    Springboot如何实现一个自定义的拦截器处理系统发出的请求以及接收到的请求(实现一个用于feign远程调用验证的简单协议)文章目录Springboot如何实现一个自定义的拦截器处理系统发出的请求以及接收到的请求(实现一个用于feign远程调用验证的简单协议)**实现Feign拦截器的意......
  • Springboot 的Bean生命周期五步、七步、十步详解以及框架源码解读生命周期-面试热点-x
    文章目录Springboot的Bean生命周期五步、七步、十步详解以及框架源码解读生命周期为什么要知道Bean的生命周期Bean的生命周期之五步堆栈信息:代码验证执行结果为Bean生命周期之七步执行结果Bean生命周期之十步增加的三步测试代码如下:执行结果:Bean的生命周期总结其他......
  • AI外包团队 Unity3D结合AI教育大模型 开发AI教师 AI外教 AI英语教师 AI课堂案例
    自2022年底ChatGPT引爆全球之后,大模型技术便迎来了一段崭新的快速发展期,由其在GPT4.0发布后,AI与教育领域结合产品研发、已成为教育+AI科技竞争的新高地、未来产业的新赛道、经济发展的新引擎和新产品的诞生地。据不完全统计,目前国内已有包括科大讯飞、百度、阿里、华为、网易在......
  • Android开发 - Canvas类与Paint画笔的绘制详解与使用
    Canvas类是什么Android中Canvas类常用于自定义View等操作中,Canvas则如同一张画布可以在上面绘制内容,然后这张画布也可以叠加其他的图层或者平移旋转等操作。Canvas对象的获取方式有两种:一种我们通过重写onDraw方法,View中重写onDraw(Canvascanvas)Canvas对象会被当做参数传递过......
  • UNRAID-虚拟机:扩容
    目录背景UNRAID下界面操作基于命令的扩容方式(qcow2)其他说明背景UNRAID建立的虚拟机前期分配的容量太小,后期有办法扩容吗?UNRAID是基于KVM+QEMU的,如果使用qcow2创建的虚拟机是可以进行扩容的。(raw默认是不可以动态扩展的,但是可以使用dd或者truncate来完成或转为qcow......
  • 基于SpringBoot+Vue+uniapp的在线考试系统的详细设计和实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • 基于SpringBoot+Vue+uniapp的计算机课程管理平台的详细设计和实现(源码+lw+部署文档+
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......