Spring Alibaba Ai 实现聊天和文生图功能

lord_huang 2024-08-31 12:01:11 阅读 87

前言

spring ai前不久刚刚问世,但由于各种原因,我们无法正常使用。但感谢alibaba,让我们可以在开发中为项目便捷的引入各种ai功能。

首先获取Api-Key

为使示例能够正常接入spring alibaba ai,需要申请有效的 API-KEY 。具体操作步骤可参见官方文档:

https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key

icon-default.png?t=N7T8

https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key?spm=5176.29160081.0.0.74807a3ci0duRk

 创建springboot项目

idea新建springboot项目,选上spring web依赖

引入相关依赖

在pom.xml文件中添加如下内容

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

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

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-ai</artifactId>

</dependency>

编写配置文件

在application.yaml文件中添加内容,配置好一开始获取的api-key

这里填自己的api-key就行,上图为本人的api-key,为隐私信息故涂去

编写项目代码

项目结构

在项目中新建如下文件夹

controller

helloworld

images

models

service

serviceImpl

service文件夹

创建接口TongYiService,代码如下

<code>public interface TongYiService {

String completion(String message);

Map<String, String> streamCompletion(String message);

ActorsFilms genOutputParse(String actor);

AssistantMessage genPromptTemplates(String adjective, String topic);

AssistantMessage genRole(String message, String name, String voice);

Completion stuffCompletion(String message, boolean stuffit);

ImageResponse genImg(String imgPrompt);

String genAudio(String text);

String audioTranscription(String audioUrls);

List<Double> textEmbedding(String text);

}

serviceImpl文件夹

创建abstract类AbstractTongYiServiceImpl代码如下

public abstract class AbstractTongYiServiceImpl implements TongYiService {

private static final String INFO_PREFIX = "please implement ";

private static final String INFO_SUFFIX = "() method.";

@Override

public String completion(String message) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread().getStackTrace()[2].getMethodName());

}

@Override

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

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public ActorsFilms genOutputParse(String actor) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public AssistantMessage genPromptTemplates(String adjective, String topic) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public AssistantMessage genRole(String message, String name, String voice) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public Completion stuffCompletion(String message, boolean stuffit) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public ImageResponse genImg(String imgPrompt) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public String genAudio(String text) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public List<Double> textEmbedding(String text) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

@Override

public String audioTranscription(String url) {

throw new RuntimeException(INFO_PREFIX + Thread.currentThread()

.getStackTrace()[2].getMethodName() + INFO_SUFFIX);

}

}

models文件夹

创建工具类ActorFilms和Completion,代码如下

public class ActorsFilms {

private String actor;

private List<String> movies;

public ActorsFilms() {

}

public String getActor() {

return actor;

}

public void setActor(String actor) {

this.actor = actor;

}

public List<String> getMovies() {

return movies;

}

public void setMovies(List<String> movies) {

this.movies = movies;

}

@Override

public String toString() {

return "ActorsFilms{" + "actor='" + actor + '\'' + ", movies=" + movies + '}';

}

}

public class Completion {

private final String completion;

public Completion(String completion) {

this.completion = completion;

}

public String getCompletion() {

return completion;

}

}

 helloworld文件夹(实现chatgpt聊天功能)

创建类TongYiSimpleServiceImpl

@Service

public class TongYiSimpleServiceImpl extends AbstractTongYiServiceImpl {

private final ChatClient chatClient;

private final StreamingChatClient streamingChatClient;

@Autowired

public TongYiSimpleServiceImpl(ChatClient chatClient, StreamingChatClient streamingChatClient) {

this.chatClient = chatClient;

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 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());

}

}

image文件夹(实现文生图功能) 

 创建类TongYiImagesServiceImpl,代码如下

@Service

public class TongYiImagesServiceImpl extends AbstractTongYiServiceImpl {

private final ImageClient imageModel;

@Autowired

public TongYiImagesServiceImpl(ImageClient imageModel) {

this.imageModel = imageModel;

}

@Override

public ImageResponse genImg(String imgPrompt) {

var prompt = new ImagePrompt(imgPrompt);

return imageModel.call(prompt);

}

}

 controller文件夹

创建ChatController类

@RestController

public class ChatController {

@Autowired

@Qualifier("tongYiSimpleServiceImpl")code>

private TongYiService tongYiSimpleService;

@GetMapping("/example")

public String completion(

@RequestParam(value = "message", defaultValue = "Tell me a joke")

String message

) {

return tongYiSimpleService.completion(message);

}

@Autowired

@Qualifier("tongYiImagesServiceImpl")

private TongYiService tongYiImgService;

@GetMapping("/img")

public ImageResponse genImg(@RequestParam(value = "prompt",

defaultValue = "Painting a picture of blue water and blue sky.") String imgPrompt) {

return tongYiImgService.genImg(imgPrompt);

}

}

进行测试

访问http://localhost:8080/example,设置message参数为自己想问ai的问题

访问http://localhost:8080/img,设置prompt参数为对目标图像的描述

总结

以上即为简易的实现,如有任何问题



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。