跳到主要内容

Generic Model API

为了为所有 AI Models 提供基础,创建了 Generic Model API。 这使得通过遵循通用模式轻松地为 Spring AI 贡献新的 AI Model 支持。 以下部分将介绍此 API。

类图​

Spring AI Generic Model API

Model​

Model 接口提供了调用 AI model 的通用 API。它旨在通过抽象发送请求和接收响应的过程来处理与各种类型的 AI model 的交互。该接口使用 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);

}

StreamingModel​

StreamingModel 接口提供了调用具有流式响应的 AI model 的通用 API。它抽象了发送请求和接收流式响应的过程。该接口使用 Java 泛型来容纳不同类型的请求和响应,增强了不同 AI model 实现的灵活性和适应性。

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 model 的请求。它封装了与 AI model 交互所需的信息,包括指令或输入(泛型类型 T)和附加的 model 选项。它提供了一种标准化的方式向 AI model 发送请求,确保包含所有必要的详细信息并易于管理。

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 model 交互的可自定义选项。此标记接口允许指定各种设置和参数,这些设置和参数可以影响 AI model 的行为和输出。它旨在在不同的 AI 场景中提供灵活性和适应性,确保可以根据特定要求微调 AI model。

public interface ModelOptions {

}

ModelResponse​

ModelResponse 接口表示从 AI model 接收的响应。此接口提供访问 AI model 生成的主要结果或结果列表以及响应元数据的方法。它作为封装和管理 AI model 输出的标准化方式,确保易于检索和处理生成的信息。

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 model 的主要输出和与此结果相关的元数据的方法。它旨在提供一种标准化和全面的方式来处理和解释 AI model 生成的输出。

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

}

Spring AI Alibaba 开源项目基于 Spring AI 构建,是阿里云通义系列模型及服务在 Java AI 应用开发领域的最佳实践,提供高层次的 AI API 抽象与云原生基础设施集成方案,帮助开发者快速构建 AI 应用。