通用模型 API
為了為所有 AI 模型提供基礎,建立了通用模型 API。透過遵循通用模式,可以輕鬆地為 Spring AI 貢獻新的 AI 模型支援。以下部分將介紹此 API。
Model
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
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
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
ModelOptions
介面表示 AI 模型互動的可定製選項。這個標記介面允許指定各種設定和引數,這些設定和引數可以影響 AI 模型的行為和輸出。它旨在為不同的 AI 場景提供靈活性和適應性,確保 AI 模型可以根據特定要求進行微調。
public interface ModelOptions {
}
ModelResponse
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
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();
}