使用前介绍
我们以 Alibaba 的百炼平台作为Spring-AI的模型讲解,以最新稳定版作为架构。
spring-ai 的最新版本 1.1.2 ;alibaba-spring-ai 的最新版本 1.1.0.0-RC1。
需要注意一点:最新版本的 Spring Boot 4.0.0 不能适配,需要降低版本到 3.5.8。
原因是Spring Boot 4.0.0 不存在以下两个自动配置类,则两个类在alibaba-spring-ai 自动配置类中要用到。
org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration
代码部分
实现相当简单,3步即可完成。
-
引入项目工程的依赖
-
去百炼平台创建一个api-key,配置在 application 文件中
百炼平台注册一个账户,然后创建一个api-key即可
-
根据需要实现相应的功能
模型对话、文生图、文生语音、文生视频、多模态
必要时可以引入百炼平台的 SDK,最新版本为 2.22.3 ,即
com.alibaba:dashscope-sdk-java:2.22.3
-
项目依赖
plugins { id("java") } group = "com.yiyi" version = "1.0-SNAPSHOT" repositories { mavenCentral() maven("https://repo.spring.io/milestone") maven("https://repo.spring.io/snapshot") maven { name = "Central Portal Snapshots" url = uri("https://central.sonatype.com/repository/maven-snapshots/") } } dependencies { implementation(platform("org.springframework.boot:spring-boot-dependencies:3.5.8")) implementation(platform("org.springframework.ai:spring-ai-bom:1.1.2")) implementation(platform("com.alibaba.cloud.ai:spring-ai-alibaba-bom:1.1.0.0-RC1")) implementation("org.springframework.boot:spring-boot-starter-webflux") // implementation("org.springframework.ai:spring-ai-starter-model-deepseek") implementation("com.alibaba.cloud.ai:spring-ai-alibaba-starter-dashscope:1.1.0.0-RC1") implementation("com.alibaba:dashscope-sdk-java:2.22.3") // implementation("org.springframework.ai:spring-ai-redis-store") testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation(platform("org.junit:junit-bom:5.10.0")) testImplementation("org.junit.jupiter:junit-jupiter") testRuntimeOnly("org.junit.platform:junit-platform-launcher") } tasks.test { useJUnitPlatform() } -
application.yaml配置api-key : 为了安全,可采用 api-key 配置在环境变量中,然后使用环境变量的值spring: ai: dashscope: api-key: ${your-api-key} -
一个简单的实例(直接用测试用例的方式),正式项目用 webflux ,完成流式输出,提升用户体验。
package com.yiyi.coding.spring.ai; import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class DashScopeTest { @Test public void testChatModel(@Autowired DashScopeChatModel dashScopeChatModel) { System.out.println(dashScopeChatModel.call("你是谁")); } } -
运行后输出内容
我是通义千问,阿里巴巴集团旗下的超大规模语言模型。我能够回答问题、创作文字,如写故事、公文、邮件、剧本等,还能进行逻辑推理、编程,甚至表达观点和玩游戏。如果你有任何需要帮助的地方,欢迎随时告诉我!

5426

被折叠的 条评论
为什么被折叠?



