天天看點

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

作者:不秃頭程式員
Spring AI 搶先體驗,5 分鐘玩轉 Java AI 應用開發

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

Spring Cloud Alibaba AI 以 Spring AI 為基礎,并在此基礎上提供阿裡雲通義系列大模型全面适配,讓使用者在 5 分鐘内開發基于通義大模型的 Java 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>           

2. 在 application.yml 配置檔案中加入以下配置:

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;
  }
}           

4. 提供具體聊天邏輯實作

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

5. 編寫 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 有效):

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

申請通義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 應用開發場景。

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

相關連結:

[1] Spring AI 0.8.1

[2] 靈積模型服務

[3] 完整示例源碼

繼續閱讀