Skip to content
Spring AI 文档版本 2.1.0-SNAPSHOT 源快照 284d304a 更新于 2026-10-16

通用模型 API

为了为所有 AI 模型提供基础,通用模型 API(Generic Model API)被创建出来。 它让你能依照一套通用模式,便捷地为 Spring AI 贡献新的 AI 模型支持。 以下各节将逐一走查该 API。

类图

Model

Model 接口提供了一个用于调用 AI 模型的通用 API。它旨在通过抽象“发送请求”与“接收响应”的过程,来处理与各类 AI 模型的交互。该接口使用 Java 泛型以适配不同类型的请求与响应,从而在不同 AI 模型实现之间增强灵活性与适应性。

该接口定义如下:

java
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 模型实现之间增强灵活性与适应性。

java
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 模型发送请求的标准化方式,确保所有必要细节都被包含且易于管理。

java
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 模型交互中可自定义的选项。这个标记接口允许指定 various 设置与参数,以影响 AI 模型的行为和输出。它旨在为不同 AI 场景提供灵活性与适应性,确保 AI 模型能依据特定需求被精细调优。

java
public interface ModelOptions {

}

ModelResponse

ModelResponse 接口表示从 AI 模型收到的响应。该接口提供了访问 AI 模型生成的主结果或结果列表、以及响应元数据的方法。它作为一种标准化方式来封装与管理 AI 模型的输出,确保生成信息易于检索与处理。

java
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 模型生成的输出。

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

}

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。