为了为所有 AI 模型提供基础,创建了通用模型 API。 这使得通过遵循通用模式很容易为 Spring AI 贡献新的 AI 模型支持。 以下部分将介绍此 API。
型
该接口提供了用于调用 AI 模型的通用 API。它旨在通过抽象发送请求和接收响应的过程来处理与各种类型的 AI 模型的交互。该接口使用 Java 泛型来适应不同类型的请求和响应,从而提高不同 AI 模型实施的灵活性和适应性。Model
接口定义如下:
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);
}
流模型
该接口提供了一个通用 API,用于使用流式响应调用 AI 模型。它抽象了发送请求和接收流式响应的过程。该接口使用 Java 泛型来适应不同类型的请求和响应,从而提高不同 AI 模型实施的灵活性和适应性。StreamingModel
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 模型交互所需的必要信息,包括指令或输入(泛型)和其他模型选项。它提供了一种向 AI 模型发送请求的标准化方法,确保包含所有必要的详细信息并且可以轻松管理。ModelRequest
T
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 模型可以根据特定需求进行微调。ModelOptions
public interface ModelOptions {
}
ModelResponse 模型响应
该接口表示从 AI 模型接收的响应。此接口提供了访问 AI 模型生成的主结果或结果列表以及响应元数据的方法。它用作封装和管理 AI 模型输出的标准化方法,确保轻松检索和处理生成的信息。ModelResponse
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 模型生成的输出。ModelResult
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();
}