背景
在现如今AI时代,spring也对ai进行了各种兼容匹配,推出了Spring AI来支持各大AI厂商,持的模型类型包括聊天和文本到图像,但是由于国内的机制以及各大厂商的限制,Spring AI在国内使用不便,因此阿里巴巴推出了Spring Cloud Alibaba AI ,完成通义系列大模型的接入。
Spring Cloud Alibaba AI 主要完成了几种常见生成式模型的适配,包括对话、文生图、文生语音等,开发者可以使用 Spring Cloud Alibaba AI 开发基于通义的聊天、图片或语音生成 AI 应用。
使用
在使用前,要了解到Spring Cloud Alibaba AI对Java版本有要求,所以要先提前预装好Java17环境。
1.依赖引入
Maven文件需要引入spring-cloud-starter-alibaba-ai这个依赖。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-ai</artifactId>
<version>2023.0.1.0</version>
</dependency>
2.API-KEY获取
需要使用阿里云账号或者tb账号,登录:https://bailian.console.aliyun.com/
点击头像位置有个API-KEY管理,获取到,然后配置在项目中
spring:
cloud:
ai:
tongyi:
api-key: XXXXXXXXXXXXXXX
3.创建demo
@Tag(name = "Demo 测试")
@RestController
@Validated
@RequestMapping("/api/v1/demo")
public class DemoController {
@Autowired
private ChatClient chatClient;
@GetMapping("/example")
public String completion() {
Prompt prompt = new Prompt(new UserMessage("你是谁你能做什么?"));
String content = chatClient.call(prompt).getResult().getOutput().getContent();
System.out.println(content);
return content;
}
}
4.测试验证
项目启动,使用postman请求对应接口路径,可以发现,打印日志中已经做出了回复,证明当前项目已经接入了阿里通义大模型。
[2024-10-19 14:13:14.767] [http-nio-8080-exec-3] [INFO] org.springframework.web.servlet.DispatcherServlet line=532 Initializing Servlet 'dispatcherServlet'
[2024-10-19 14:13:14.771] [http-nio-8080-exec-3] [INFO] org.springframework.web.servlet.DispatcherServlet line=554 Completed initialization in 4 ms
我是Qwen,是阿里云开发的一款大型语言模型。我能够回答各种问题、提供信息查询、进行文本生成和对话等任务。无论是需要学习资料、解答疑惑还是寻找创意灵感,我都尽力帮助您。如果您有任何问题或需要我的帮助,请随时告诉我!