Spring AI 1.0.0 M4 版本釋出

釋出 | Mark Pollack | 2024年11月20日 | ...

我們很高興地宣佈 Spring AI 1.0.0 Milestone 4 版本釋出。

此版本修復了大部分報告的 bug,並在多個領域帶來了顯著的增強。

Amazon Bedrock Converse

Spring AI 現在支援 Amazon Bedrock Converse API,它為 Amazon 提供的 AI 聊天模型提供了一個統一的介面。與舊的 Bedrock Invoke API 不同,Converse 引入了令人興奮的新功能,例如 **工具呼叫** 和 **多模態/視覺能力**(針對支援這些功能 _的模型_)。這使其成為使用 Amazon 聊天模型的更強大、更通用的選擇。

在很多方面,Converse API 的作用與 Spring AI 本身類似,它提供了跨模型 API 的可移植性,但僅限於 Amazon 的聊天模型。我們建議聊天模型遷移到 Converse 模組。請注意,嵌入模型不受影響。

有關此新功能的詳細資訊,請參閱 Spring AI Bedrock Converse 文件。您也可以關注 即將進行的改進 以瞭解未來的增強功能。非常感謝 Max Jiang 啟動這項艱鉅的任務。

Function Calling 改進

函式型別和方法

最近的改進透過 FunctionCallback Builder 類擴充套件了對各種函式型別和方法(Function types and methods)的支援。這允許呼叫 java.util.FunctionSupplierConsumer 介面。

基本函式回撥

FunctionCallback callback = FunctionCallback.builder()
    .description("Process a new order")
    .function("processOrder", (Order order) -> processOrderLogic(order))
    .inputType(Order.class)
    .build();

使用 ToolContext {#using-toolcontext}

使用 ToolContextBiFunction<I, ToolContext, O> 訪問其他狀態或上下文。

@Bean
@Description("Get the weather in location")
public BiFunction<WeatherService.Request, ToolContext, WeatherService.Response> weatherFunctionWithContext() {
    return (request, context) -> new MockWeatherService().apply(request);
}

方法呼叫

方法呼叫支援為 M5 中即將釋出的 @ToolMapping 註解提供了基礎。

public static class LightControl {
    private static final Logger logger = LoggerFactory.getLogger(LightControl.class);
    private final Map<String, Object> arguments = new HashMap<>();

    public void controlLight(String roomName, boolean on) {
        arguments.put("roomName", roomName);
        arguments.put("on", on);
        logger.info("Setting light in room '{}' to: {}", roomName, on ? "ON" : "OFF");
    }
}

用法

LightControl lightControl = new LightControl();

String response = ChatClient.create(this.chatModel)
    .prompt("Turn light on in the living room.")
    .functions(
        FunctionCallback.builder()
            .description("Controls lights by room name, allowing them to be turned on or off.")
            .method("controlLight", String.class, boolean.class)
            .targetObject(lightControl)
            .build()
    )
    .call()
    .content();

有關其他功能,請查閱 FunctionCallback 文件,其中涵蓋了

  • Schema 型別配置(JSON Schema 和 OpenAPI Schema 支援)
  • 自定義響應處理和物件對映
  • 使用 ParameterizedTypeReference 支援泛型輸入型別
  • 從 Java 型別自動生成 Schema,包括 Jackson 註解支援
  • 編寫有效的函式描述和錯誤處理指南

Kotlin 支援

Spring AI 引入了對 Kotlin 的支援,使 Kotlin 開發人員能夠更輕鬆地將 AI 功能整合到他們的應用程式中。此版本引入了慣用的 Kotlin 擴充套件和型別安全的 API。非常感謝 Sebastien Deleuze 完成這項工作。

型別安全響應處理

新的 Kotlin 擴充套件使得處理 AI 響應的方式更加簡潔和型別安全。您現在可以使用 Kotlin 的具體化泛型(reified generics),而不是使用 Java 風格的型別宣告。

import org.springframework.ai.chat.client.entity

data class Joke(val setup: String, val punchline: String)

@SpringBootApplication
class KotlinHelloWorldApplication {

   @Bean
   fun jokeRunner(chatModel: ChatModel) = CommandLineRunner {
      val response = ChatClient.create(chatModel).prompt().user("Tell me a joke").call().entity<Joke>()

      println("\nJoke:")
      println("Setup: ${response.setup}")
      println("Punchline: ${response.punchline}")
   }
}

fun main(args: Array<String>) {
   runApplication<KotlinHelloWorldApplication>(*args)
}

函式註冊

現在可以將 Kotlin 函式直接註冊為 AI 工具。語法很簡單。

@Configuration
class Config {

   @Bean
   fun weatherFunctionInfo(currentWeather: (WeatherRequest) -> WeatherResponse): FunctionCallback {
      return FunctionCallback.builder()
         .description(
            "Find the weather conditions, forecasts, and temperatures for a location, like a city or state."
         )
         .function("WeatherInfo", currentWeather)
         .inputType(WeatherRequest::class.java)
         .build()
   }

   @Bean
   @Description("Get current weather")
   fun currentWeather(): (WeatherRequest) -> WeatherResponse = { request ->
      MockKotlinWeatherService().invoke(request)
   }
}

然後,可以使用如下方式。

@Bean
open fun init(chatModel: ChatModel) = CommandLineRunner {

   try {
      val userMessage = UserMessage(
         "What are the weather conditions in San Francisco, Tokyo, and Paris? Find the temperature in Celsius for each of the three locations."
      )

      val response = chatModel.call(
         Prompt(
            listOf(userMessage),
            OpenAiChatOptions.builder().withFunction("WeatherInfo").build()
         )
      )

      println("Response: $response")
   } 
   catch (e: Exception) {
      println("Error during weather check: ${e.message}")
   }
}

參考文件已更新,包含 Kotlin 示例,您也可以在 spring-ai-examples 倉庫中找到其他示例。

其他專案資源

倉庫 awesome-spring-ai 遵循其他“awseome”倉庫的主題,收集了 Spring AI 的社群相關資源,如書籍、簡報、示例程式碼等。如果您發現任何有用的資料,請透過 PR 貢獻給該倉庫。

倉庫 spring-ai-integration-tests 現已可用,並正在努力每天兩次執行專案的全部整合測試。

倉庫 spring-ai-examples 現已可用,用於託管“官方”示例。快來看看反射代理示例!

此外,作為專案介紹,請檢視博文 Why Spring AI

高階和模組化 RAG

Spring AI 引入了對基於模組化 RAG 系統設計的最新研究的先進檢索增強生成 (RAG) 的實驗性支援,特別是論文 Modular RAG: Transforming RAG Systems into LEGO-like Reconfigurable FrameworksRetrieval-Augmented Generation for Large Language Models: A Survey。非常感謝 Thomas Vittale 領導這項工作。

以下是關鍵構建塊:

預檢索元件

  • QueryTransformer:轉換查詢以提高檢索效果(例如,翻譯、改寫)
  • QueryExpander:將單個查詢擴充套件為多個變體,以捕獲更廣泛的上下文

編排元件

  • QueryRouter:根據元資料或語義分析將查詢路由到適當的檢索器

檢索元件

  • DocumentRetriever:檢索相關文件的核心介面
  • DocumentJoiner:組合來自多個檢索器/查詢的結果

後檢索元件

  • DocumentCompressor:在保留關鍵資訊的同時減少文件內容
  • DocumentRanker:按相關性重新排序文件
  • DocumentSelector:根據標準過濾檢索到的文件

增強元件

  • QueryAugmenter:使用檢索到的上下文增強查詢
  • ContextualQueryAugmenter:專注於文件上下文整合的預設實現

基於我們的模組化 RAG 元件,RetrievalAugmentationAdvisor 提供了一個實現,可以幫助您入門,並提供線性的 RAG 流。

  1. 查詢建立:使用 PromptTemplate 從使用者文字建立查詢
  2. 查詢轉換:應用 QueryTransformers 鏈
  3. 查詢擴充套件:透過 QueryExpander 建立多個查詢
  4. 文件檢索:路由和執行並行檢索
  5. 文件整合:合併所有來源的結果
  6. 上下文增強:使用檢索到的上下文增強查詢

您可以在 Bean 定義中組合這些協作的構建塊元件,例如:

@Bean
public RetrievalAugmentationAdvisor customRagAdvisor(VectorStore vectorStore) {
    return RetrievalAugmentationAdvisor.builder()
        .queryTransformers(List.of(new TranslationQueryTransformer(...)))
        .queryExpander(new MultiQueryExpander(...))
        .queryRouter(
            AllRetrieversQueryRouter.builder()
                .documentRetrievers(new VectorStoreDocumentRetriever(...))
                .build()
        )
        .documentJoiner(new ConcatenationDocumentJoiner())
        .queryAugmenter(new ContextualQueryAugmenter(...))
        .build();
}

雖然 RetrievalAugmentationAdvisor 實現的是線性流程,但使用者可以為條件、分支、遞迴和自適應流程等高階模式實現自定義 Advisor。更多文件即將釋出,我們鼓勵您在我們的 github issue tracker 上提供反饋。

其他改進

模型模組中有幾個地方使用了 Spring Boot。現在不再是這樣了。僅有的對 Spring Boot 的依賴已隔離到 autoconfigure 模組。

Azure OpenAI SDK 已升級到 12 beta 版。

文件

  • 已新增一個全面的聊天模型比較頁面。
  • 重構了文件導航,以提高可訪問性。
  • 更新了聊天模型架構圖。
  • 添加了有關使用服務帳戶以程式設計方式配置 Vertex 嵌入的指南。
  • 增強了整合指南。
  • Ollama 更新
    • 新的自動拉取功能
    • Llama32-Vision 支援
  • Spring AI 功能
    • 開箱即用地支援 Llama32-Vision。
    • 可移植的多模態 API。
  • 向量資料庫配置
    • Milvus
    • Chroma
    • OpenSearch

擴充套件了配置和設定文件,重點關注:

  • 屬性覆蓋
  • 程式碼示例
  • 不同模型型別的整合模式

向量儲存和嵌入改進

  • 為 Oracle Coherence 和 Azure Cosmos 添加了新的向量儲存實現。
  • 增強了現有的向量儲存。
    • Azure:提供了匹配預先存在的欄位名和使用無金鑰身份驗證的能力。
    • Milvus:添加了對非預設資料庫的支援。
    • Chroma:引入了 Builder 模式以更好地初始化。
    • OpenSearch:改進了配置結構。
  • 為 TokenTextSplitter 引入了 Builder 模式。

貢獻者

大量貢獻者對程式碼進行了其他重構、錯誤修復和文件增強。如果您的 PR 尚未處理,我們將盡快處理,請耐心等待。感謝以下貢獻者:

路線圖

我們計劃在 12 月下旬進行最後一次里程碑版本釋出,即 1.0.0 M5,重點關注設計問題,例如在 ChatResponse 中返回更多資訊,對 VectorStore API 進行大修以支援新增/刪除和不同查詢型別,統一各種 Builder 的 API 風格,等等。然後,在 1 月份,我們將釋出 1.0.0 RC1 版本,並迅速跟進 1.0.0 GA 版本。

獲取 Spring 新聞通訊

透過 Spring 新聞通訊保持聯絡

訂閱

領先一步

VMware 提供培訓和認證,助您加速進步。

瞭解更多

獲得支援

Tanzu Spring 提供 OpenJDK™、Spring 和 Apache Tomcat® 的支援和二進位制檔案,只需一份簡單的訂閱。

瞭解更多

即將舉行的活動

檢視 Spring 社群所有即將舉行的活動。

檢視所有