端午安康
先登录:阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台
先创建ApiKey,之后引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.14.0</version>
</dependency>
或者gradle
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/'}
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.4.13'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot
implementation group: 'org.springframework.boot', name: 'spring-boot', version: '2.4.13'
//ai
implementation 'com.alibaba:dashscope-sdk-java:2.14.0'
implementation 'com.alibaba.fastjson2:fastjson2:2.0.51'
}
注入配置Bean
@Configuration
public class AliAiConfig {
@Bean
public Generation generation() {
return new Generation();
}
}
编写一个控制器 ,浏览器输入
/**
* @author heart
*/
@Slf4j
@RestController
@RequestMapping("/")
public class AiController {
@Value("${api-key}")
private String apiKey;
@Resource
private Generation generation;
/**
* 单轮对话
*
* @param text
* @return
*/
@RequestMapping(value = "/advisory", method = RequestMethod.GET)
public String textAsk(String text) {
try {
//用户与模型的对话历史。list中的每个元素形式为{“role”:角色, “content”: 内容}。
Message userMessage = Message.builder()
.role(Role.USER.getValue())
.content(text)
.build();
GenerationParam param = GenerationParam.builder()
//接入模型 可选
.model("qwen-plus")
.messages(Arrays.asList(userMessage))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
//申请的阿里云秘钥
.apiKey(apiKey)
.topP(0.8)
//开启互联网搜索
.enableSearch(true)
.build();
GenerationResult generationResult = generation.call(param);
;
log.info("QWen Result:{}", JSON.toJSONString(generationResult));
return "AI reply: " + generationResult.getOutput().getChoices().get(0).getMessage().getContent();
} catch (Exception exception) {
log.error(exception.getMessage());
return exception.getMessage();
}
}
}
更多详情请参考官方文档 产品概述_模型服务灵积(DashScope)-阿里云帮助中心