关于springboot对接通义千问大模型的尝试

今天正在路上刷手机,突然看到群里有人发了一个链接,内容是Spring Cloud Alibaba AI 的使用,spring cloud AI的使用,于是就想着玩一玩试试,难度不大,就是有些文档的坑,这里做一个记录,后续会继续更新这个系列的,毕竟AI时代,我们springer也得搭一下顺风车。

一、文档阅读

我们看到文档其实描述了他的能力如下图,但是我们这里只尝试一下文生文的能力,其实说人话就是对话。
在这里插入图片描述

二、快速开始

我们基于文档描述开始搭建这个环境。

1、基于文档搭建环境

  • 1、 引入依赖
    我们按照文档的内容引入如下依赖。
<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>

<dependencies>
  <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-ai</artifactId>
  </dependency>
</dependencies>
  • 2、在 application.yml 配置文件中加入以下配置:
    这个API-KEY需要你通过阿里云去获取,具体操作步骤:获取通义千问api-key
spring:
  cloud:
    ai:
      tongyi:
        chat:
          options:
            # Replace the following key with a valid API-KEY.
            api-key: sk-a3d73b1709bf4a178c28ed7c8b3b5axx
  • 3、编写聊天服务实现类,由 Spring AI 自动注入 ChatClient、StreamingChatClient,ChatClient 屏蔽底层通义大模型交互细节。
@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;
  }
}

提供具体聊天逻辑实现

@Service
public class TongYiSimpleServiceImpl extends AbstractTongYiServiceImpl {
   

  // ......

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

    log.info(fullContent.toString());

    return Map.of(message, fullContent.toString());
  }

}

编写 Spring 入口类并启动应用

@SpringBootApplication
public class TongYiApplication {
   
  public static void main(String[] args) {
   
    SpringApplication.run(TongYiApplication.class);
  }
}

2、踩坑

2.1、maven导入失败

我在按照如上环境搭建好之后,reload maven发现报错。
在这里插入图片描述
从阿里云的maven镜像库里面拉不下来这些依赖。我用的maven库如下:

<mirror>
	<id>alimaven</id>
	<name>aliyun maven</name>
	<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
	<mirrorOf>central</mirrorOf>
</mirror>

既然踩了坑,那就去文档找吧,估计不止我一个人踩坑。翻了一下找到了一个阿里cloud答疑问题的网址。spring cloud alibaba答疑区
最后翻到了一个这个spring ai maven无法引入问题解决
我们就按照他这个加一个maven的仓库配置,

<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
### Spring Framework 与通义在人工智能应用中的集成与比较 #### 集成方面 Spring Cloud Alibaba 提供了一种机制来实现与阿里巴巴集团内部技术栈的无缝对接。通过 Spring AI 的基础架构支持,Spring Cloud Alibaba 已经完成了对通义系列大模型的接入工作[^1]。这意味着开发者可以利用 Spring 生态系统的灵活性和模块化特性,在构建机器学习或自然语言处理应用程序时轻松调用通义的能力。 具体来说,这种集成为开发人员提供了以下优势: - **简化配置流程**:借助于 Spring Boot 自动配置功能,减少了手动设置参数的工作量。 - **增强可维护性**:遵循一致的设计模式使得代码更易于理解和扩展。 - **促进微服务部署**:允许将复杂的 NLP 功能作为独立的服务单元运行并与其他业务逻辑协同操作。 以下是展示如何在一个简单的 Java 应用程序中初始化并与通义交互的一个基本例子: ```java @SpringBootApplication public class TongyiQianwenApplication { public static void main(String[] args) { SpringApplication.run(TongyiQianwenApplication.class, args); // 假设这里有一个方法用于连接到通义API String response = callTongyiQianwenApi("你好"); System.out.println(response); } private static String callTongyiQianwenApi(String input){ RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, Object> map = new HashMap<>(); map.put("prompt", input); HttpEntity<Map<String, Object>> entity = new HttpEntity<>(map, headers); ResponseEntity<String> result = restTemplate.postForEntity( "https://example.com/tongyi-qianwen-api", entity, String.class ); return result.getBody(); } } ``` 此代码片段展示了如何使用 `RestTemplate` 向假设存在的通义 API 发送请求,并打印返回的结果。 #### 对比分析 当考虑 Spring通义之间的差异时,可以从以下几个维度来进行评估: 1. **目标领域** - Spring 是一个通用的企业级框架,适用于各种类型的软件项目开发。 - 而通义专注于提供强大的自然语言理解能力以及生成高质量文本的功能。 2. **适用场景** - 使用 Spring 可以为任何规模的应用创建结构良好的解决方案。 - 通义则特别适合那些需要高级对话代理或者自动化写作等功能的任务。 3. **技术支持方式** - 开发者社区围绕着 Spring 形成了庞大的生态系统和技术文档资源。 - 关于通义的支持主要来源于阿里云官方指南及其关联的学习材料。 尽管两者服务于不同的目的,但它们能够很好地互补——即由 Spring 构建稳定可靠的后端环境,而让通义负责前端用户体验优化和服务智能化升级。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值