Spring AI 搶先體驗,5 分鐘玩轉 Java AI 應用開發

作者:劉軍

Spring AI 是 Spring 官方社區項目,旨在簡化 Java AI 應用程序開發,讓 Java 開發者像使用 Spring 開發普通應用一樣開發 AI 應用。

Spring Cloud Alibaba AI 以 Spring AI 爲基礎,並在此基礎上提供阿里雲通義系列大模型全面適配,讓用戶在 5 分鐘內開發基於通義大模型的 Java AI 應用。

Spring AI x 通義千問 Demo 已上線至 sca.aliyun.com

Spring AI 簡介

據 Spring AI 官網描述,該項目的靈感來自著名的 Python 項目,如 LangChain 和 LlamaIndex,但 Spring AI 並不是這些項目的直接複製。Spring AI 相信下一波 Generative AI 生成式應用程序將不僅面向 Python 開發人員,而且將在許多編程語言中廣泛應用。

Spring AI 的核心是提供抽象,作爲開發 Java AI 應用程序的基礎,提供以下功能:

  • 提供多種大模型服務對接能力,包括業界大多數主流大模型服務等;
  • 支持靈活的 Prompt Template 和模型輸出解析 Output Parsing 能力;
  • 支持多模態的生成式 AI 能力,如對話,文生圖、文生語音等;
  • 提供通用的可移植的 API 以訪問各類模型服務和 Embedding 服務,支持同步和流式調用,同時也支持傳遞特定模型的定製參數;
  • 支持 RAG 能力的基礎組件,包括 DocumentLoader、TextSpillter、EmobeddingClient、VectorStore 等;
  • 支持 AI Spring Boot Starter 實現配置自動裝配。

Spring Cloud Alibaba AI 簡介

Spring Cloud Alibaba AI 目前基於 Spring AI 0.8.1 [ 1] 版本 API 完成通義系列大模型的接入。通義接入是基於阿里雲靈積模型服務 [ 2] ,靈積模型服務建立在“模型即服務”(Model-as-a-Service,MaaS)的理念基礎之上,圍繞 AI 各領域模型,通過標準化的API提供包括模型推理、模型微調訓練在內的多種模型服務。

在當前最新版本中,Spring Cloud Alibaba AI 主要完成了幾種常見生成式模型的適配,包括對話、文生圖、文生語音等,開發者可以使用 Spring Cloud Alibaba AI 開發基於通義的聊天、圖片或語音生成 AI 應用,框架還提供 OutParser、Prompt Template、Stuff 等實用能力。

以下是當前官方提供的 Spring Cloud Alibaba AI 應用開發示例,訪問 sca.aliyun.com 可查看。

  • 聊天對話應用
  • 文生圖應用
  • 文生語音應用
  • 模型輸出解析OutputParser(實現從 String 到自動 POJO 映射)
  • 使用 Prompt Template
  • 讓 AI 模型接入外部數據(Prompt Stuff)

體驗第一個 Spring AI 應用開發

本項目演示如何使用 spring-cloud-starter-alibaba-ai 完成一個在線聊天 AI 應用,底層使用通義千問提供的模型服務。可在此查看完整示例源碼 [ 3]

開發聊天對話應用

  1. 在項目 pom.xml 中加入 2023.0.1.0 版本 Spring Cloud Alibaba 依賴:
<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>
  1. 在 application.yml 配置文件中加入以下配置:
spring:
  cloud:
    ai:
      tongyi:
        chat:
          options:
            # Replace the following key with a valid API-KEY.
            api-key: sk-a3d73b1709bf4a178c28ed7c8b3b5axx
  1. 編寫聊天服務實現類,由 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;
  }
}
  1. 提供具體聊天邏輯實現
@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());
  }

}
  1. 編寫 Spring 入口類並啓動應用
@SpringBootApplication
public class TongYiApplication {
  public static void main(String[] args) {
    SpringApplication.run(TongYiApplication.class);
  }
}

至此,便完成了最簡單的聊天 AI 應用開發,與普通的 Spring Boot 應用開發步驟完全一致!

驗證應用效果

啓動應用後,可通過如下兩種方式驗證應用效果。

方式一

瀏覽器地址欄輸入:http://localhost:8080/ai/example

返回如下響應:

{
    "Tell me a joke": "Sure, here's a classic one for you:\n\nWhy was the math book sad?\n\nBecause it had too many problems.\n\nI hope that made you smile! If you're looking for more, just let me know."
}

方式二

進入 resources/static 目錄下,使用瀏覽器打開 index.html 文件,輸入問題,即可獲得輸出響應(確保 api-key 有效):

申請通義API-KEY

爲使示例能夠正常接入通義大模型,需要在阿里雲開通 DashScope 靈積模型服務,申請有效的 API-KEY 並更新到應用配置文件。具體操作步驟可參見如下文檔:

https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key

未來規劃

當前版本 Spring Cloud Alibaba AI 主要完成了幾種常見生成式模型適配,包括對話、文生圖、文生語音等。接下來的版本中,我們將繼續完成 VectorStore、Embedding、ETL Pipeline 等更多適配,簡化 RAG 等更多 AI 應用開發場景。

請持續關注 https://sca.aliyun.com ,瞭解最新進展。也歡迎通過釘釘掃描下方二維碼加入社區釘羣。(羣號:64485010179

相關鏈接:

[1] Spring AI 0.8.1

https://docs.spring.io/spring-ai/reference/0.8-SNAPSHOT/index.html

[2] 靈積模型服務

https://help.aliyun.com/zh/dashscope/

[3] 完整示例源碼

https://github.com/alibaba/spring-cloud-alibaba/tree/2023.x/spring-cloud-alibaba-examples/spring-cloud-ai-example/src/main/java/com/alibaba/cloud/ai/example/tongyi/service/impl/helloworld

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章