通用模型 API

為了替所有 AI 模型提供基礎,建立了通用模型 API。透過遵循通用模式,這讓 Spring AI 更容易貢獻新的 AI 模型支援。以下章節將逐步介紹此 API。

類別圖

spring ai generic model api

模型

Model 介面為調用 AI 模型提供通用 API。它旨在處理與各種類型 AI 模型的互動,方法是抽象化傳送請求和接收回應的過程。此介面使用 Java 泛型來容納不同類型的請求和回應,從而增強跨不同 AI 模型實作的彈性和適應性。

介面定義如下

public interface Model<TReq extends ModelRequest<?>, TRes extends ModelResponse<?>> {

	/**
	 * Executes a method call to the AI model.
	 * @param request the request object to be sent to the AI model
	 * @return the response from the AI model
	 */
	TRes call(TReq request);

}

串流模型

StreamingModel 介面為調用具有串流回應的 AI 模型提供通用 API。它抽象化了傳送請求和接收串流回應的過程。此介面使用 Java 泛型來容納不同類型的請求和回應,從而增強跨不同 AI 模型實作的彈性和適應性。

public interface StreamingModel<TReq extends ModelRequest<?>, TResChunk extends ModelResponse<?>> {

	/**
	 * Executes a method call to the AI model.
	 * @param request the request object to be sent to the AI model
	 * @return the streaming response from the AI model
	 */
	Flux<TResChunk> stream(TReq request);

}

模型請求

ModelRequest 介面代表對 AI 模型的請求。它封裝了與 AI 模型互動所需的必要資訊,包括指令或輸入(泛型 T 類型)和其他模型選項。它提供了一種標準化的方式來向 AI 模型傳送請求,確保包含所有必要的詳細資訊且易於管理。

public interface ModelRequest<T> {

	/**
	 * Retrieves the instructions or input required by the AI model.
	 * @return the instructions or input required by the AI model
	 */
	T getInstructions(); // required input

	/**
	 * Retrieves the customizable options for AI model interactions.
	 * @return the customizable options for AI model interactions
	 */
	ModelOptions getOptions();

}

模型選項

ModelOptions 介面代表 AI 模型互動的可自訂選項。此標記介面允許指定各種設定和參數,這些設定和參數可能會影響 AI 模型的行為和輸出。它旨在為不同的 AI 應用情境提供彈性和適應性,確保可以根據特定需求微調 AI 模型。

public interface ModelOptions {

}

模型回應

ModelResponse 介面代表從 AI 模型接收的回應。此介面提供存取 AI 模型產生的主要結果或結果列表以及回應中繼資料的方法。它作為一種標準化的方式來封裝和管理來自 AI 模型的輸出,確保可以輕鬆擷取和處理產生的資訊。

public interface ModelResponse<T extends ModelResult<?>> {

	/**
	 * Retrieves the result of the AI model.
	 * @return the result generated by the AI model
	 */
	T getResult();

	/**
	 * Retrieves the list of generated outputs by the AI model.
	 * @return the list of generated outputs
	 */
	List<T> getResults();

	/**
	 * Retrieves the response metadata associated with the AI model's response.
	 * @return the response metadata
	 */
	ResponseMetadata getMetadata();

}

模型結果

ModelResult 介面提供存取 AI 模型的主要輸出以及與此結果相關聯的中繼資料的方法。它旨在提供一種標準化且全面的方式來處理和解譯 AI 模型產生的輸出。

public interface ModelResult<T> {

	/**
	 * Retrieves the output generated by the AI model.
	 * @return the output generated by the AI model
	 */
	T getOutput();

	/**
	 * Retrieves the metadata associated with the result of an AI model.
	 * @return the metadata associated with the result
	 */
	ResultMetadata getMetadata();

}