当前位置:   article > 正文

Spring接入阿里云通义千问Demo_spring ai接入通义千问

spring ai接入通义千问

端午安康

先登录:阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台

先创建ApiKey,之后引入依赖

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>dashscope-sdk-java</artifactId>
  4. <version>2.14.0</version>
  5. </dependency>

或者gradle

  1. repositories {
  2. maven { url 'http://maven.aliyun.com/nexus/content/groups/public/'}
  3. mavenCentral()
  4. }
  5. dependencies {
  6. testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
  7. testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.1'
  8. testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
  9. // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
  10. implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.4.13'
  11. // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot
  12. implementation group: 'org.springframework.boot', name: 'spring-boot', version: '2.4.13'
  13. //ai
  14. implementation 'com.alibaba:dashscope-sdk-java:2.14.0'
  15. implementation 'com.alibaba.fastjson2:fastjson2:2.0.51'
  16. }

注入配置Bean 

  1. @Configuration
  2. public class AliAiConfig {
  3. @Bean
  4. public Generation generation() {
  5. return new Generation();
  6. }
  7. }

编写一个控制器 ,浏览器输入

  1. /**
  2. * @author heart
  3. */
  4. @Slf4j
  5. @RestController
  6. @RequestMapping("/")
  7. public class AiController {
  8. @Value("${api-key}")
  9. private String apiKey;
  10. @Resource
  11. private Generation generation;
  12. /**
  13. * 单轮对话
  14. *
  15. * @param text
  16. * @return
  17. */
  18. @RequestMapping(value = "/advisory", method = RequestMethod.GET)
  19. public String textAsk(String text) {
  20. try {
  21. //用户与模型的对话历史。list中的每个元素形式为{“role”:角色, “content”: 内容}。
  22. Message userMessage = Message.builder()
  23. .role(Role.USER.getValue())
  24. .content(text)
  25. .build();
  26. GenerationParam param = GenerationParam.builder()
  27. //接入模型 可选
  28. .model("qwen-plus")
  29. .messages(Arrays.asList(userMessage))
  30. .resultFormat(GenerationParam.ResultFormat.MESSAGE)
  31. //申请的阿里云秘钥
  32. .apiKey(apiKey)
  33. .topP(0.8)
  34. //开启互联网搜索
  35. .enableSearch(true)
  36. .build();
  37. GenerationResult generationResult = generation.call(param);
  38. ;
  39. log.info("QWen Result:{}", JSON.toJSONString(generationResult));
  40. return "AI reply: " + generationResult.getOutput().getChoices().get(0).getMessage().getContent();
  41. } catch (Exception exception) {
  42. log.error(exception.getMessage());
  43. return exception.getMessage();
  44. }
  45. }
  46. }

更多详情请参考官方文档 产品概述_模型服务灵积(DashScope)-阿里云帮助中心 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/838010
推荐阅读
相关标签
  

闽ICP备14008679号