通用模型 API

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

类图

spring ai generic model 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();

}