> ## Documentation Index
> Fetch the complete documentation index at: https://javaai.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Google 文本 向量模型

Vertex AI 支持两种类型的嵌入模型：文本和多模态。
本文档介绍如何使用 Vertex AI [文本嵌入 API](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api) 创建文本嵌入。

Vertex AI 文本嵌入 API 使用密集向量表示。
与稀疏向量（倾向于将单词直接映射到数字）不同，密集向量旨在更好地表示一段文本的含义。
在生成式 AI 中使用密集向量嵌入的好处在于，您可以更好地搜索与查询含义一致的段落，即使这些段落使用的语言不同，而不是搜索直接的单词或语法匹配。

## 先决条件

* 安装适用于您操作系统的 [gcloud](https://cloud.google.com/sdk/docs/install) CLI。
* 通过运行以下命令进行身份验证。
  将 `PROJECT_ID` 替换为您的 Google Cloud 项目 ID，并将 `ACCOUNT` 替换为您的 Google Cloud 用户名。

```bash theme={"system"}
gcloud config set project <PROJECT_ID> && \
gcloud auth application-default login <ACCOUNT>
```

### 添加存储库和 BOM

Spring AI 工件发布在 Maven Central 和 Spring Snapshot 存储库中。
请参阅[工件存储库](/spring4ai/getting-started#artifact-repositories)部分，将这些存储库添加到您的构建系统中。

为了帮助进行依赖管理，Spring AI 提供了一个 BOM (物料清单) 以确保在整个项目中使用一致版本的 Spring AI。请参阅[依赖管理](/spring4ai/getting-started#dependency-management)部分，将 Spring AI BOM 添加到您的构建系统中。

## 自动配置

> **注意**：Spring AI 自动配置和启动器模块的工件名称已发生重大更改。
> 有关更多信息，请参阅[升级说明](https://docs.spring.io/spring-ai/reference/upgrade-notes.html)。

Spring AI 为 VertexAI Embedding 模型提供 Spring Boot 自动配置。
要启用它，请将以下依赖项添加到项目的 Maven `pom.xml` 文件中：

```xml theme={"system"}
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-vertex-ai-embedding</artifactId>
</dependency>
```

或添加到您的 Gradle `build.gradle` 构建文件中。

```groovy theme={"system"}
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-vertex-ai-embedding'
}
```

> **提示**：请参阅[依赖管理](/spring4ai/getting-started#dependency-management)部分，将 Spring AI BOM 添加到您的构建文件中。

### Embedding 属性

前缀 `spring.ai.vertex.ai.embedding` 用作属性前缀，可让您连接到 VertexAI Embedding API。

| 属性                                        | 描述                          | 默认值 |
| :---------------------------------------- | :-------------------------- | :-- |
| spring.ai.vertex.ai.embedding.project-id  | Google Cloud Platform 项目 ID | -   |
| spring.ai.vertex.ai.embedding.location    | 区域                          | -   |
| spring.ai.vertex.ai.embedding.apiEndpoint | Vertex AI Embedding API 端点。 | -   |

> **注意**：嵌入自动配置的启用和禁用现在通过前缀为 `spring.ai.model.embedding` 的顶级属性进行配置。
>
> 要启用，请设置 spring.ai.model.embedding.text=vertexai (默认情况下启用)
>
> 要禁用，请设置 spring.ai.model.embedding.text=none (或任何与 vertexai 不匹配的值)
>
> 此更改是为了允许配置多个模型。

前缀 `spring.ai.vertex.ai.embedding.text` 是配置 VertexAI 文本嵌入的嵌入模型实现的属性前缀。

| 属性                                                       | 描述                                                                                                                                          | 默认值                  |
| :------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------- |
| spring.ai.vertex.ai.embedding.text.enabled (已删除且不再有效)    | 启用 Vertex AI Embedding API 模型。                                                                                                              | true                 |
| spring.ai.model.embedding.text                           | 启用 Vertex AI Embedding API 模型。                                                                                                              | vertexai             |
| spring.ai.vertex.ai.embedding.text.options.model         | 这是要使用的 [Vertex 文本嵌入模型](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings#supported-models)。              | text-embedding-004   |
| spring.ai.vertex.ai.embedding.text.options.task-type     | 预期的下游应用程序，以帮助模型生成更高质量的嵌入。可用的[任务类型](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#request_body)。 | `RETRIEVAL_DOCUMENT` |
| spring.ai.vertex.ai.embedding.text.options.title         | 可选标题，仅在 task\_type=RETRIEVAL\_DOCUMENT 时有效。                                                                                                 | -                    |
| spring.ai.vertex.ai.embedding.text.options.dimensions    | 生成的输出嵌入应具有的维度数。模型版本 004 及更高版本支持。您可以使用此参数来减小嵌入大小，例如，用于存储优化。                                                                                  | -                    |
| spring.ai.vertex.ai.embedding.text.options.auto-truncate | 设置为 true 时，将截断输入文本。设置为 false 时，如果输入文本长于模型支持的最大长度，则返回错误。                                                                                     | true                 |

## 示例控制器

[创建](https://start.spring.io/)一个新的 Spring Boot 项目，并将 `spring-ai-starter-model-vertex-ai-embedding` 添加到您的 pom (或 gradle) 依赖项中。

在 `src/main/resources` 目录下添加一个 `application.properties` 文件，以启用和配置 VertexAi 聊天模型：

```properties theme={"system"}
spring.ai.vertex.ai.embedding.project-id=<您的项目 ID>
spring.ai.vertex.ai.embedding.location=<您的项目位置>
spring.ai.vertex.ai.embedding.text.options.model=text-embedding-004
```

这将创建一个 `VertexAiTextEmbeddingModel` 实现，您可以将其注入到您的类中。
这是一个简单的 `@Controller` 类示例，它使用嵌入模型进行嵌入生成。

```java theme={"system"}
@RestController
public class EmbeddingController {

    private final EmbeddingModel embeddingModel;

    @Autowired
    public EmbeddingController(EmbeddingModel embeddingModel) {
        this.embeddingModel = embeddingModel;
    }

    @GetMapping("/ai/embedding")
    public Map embed(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        EmbeddingResponse embeddingResponse = this.embeddingModel.embedForResponse(List.of(message));
        return Map.of("embedding", embeddingResponse);
    }
}
```

## 手动配置

[VertexAiTextEmbeddingModel](https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-vertex-ai-embedding/src/main/java/org/springframework/ai/vertexai/embedding/VertexAiTextEmbeddingModel.java) 实现了 `EmbeddingModel`。

将 `spring-ai-vertex-ai-embedding` 依赖项添加到项目的 Maven `pom.xml` 文件中：

```xml theme={"system"}
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-vertex-ai-embedding</artifactId>
</dependency>
```

或添加到您的 Gradle `build.gradle` 构建文件中。

```groovy theme={"system"}
dependencies {
    implementation 'org.springframework.ai:spring-ai-vertex-ai-embedding'
}
```

> **提示**：请参阅[依赖管理](/spring4ai/getting-started#dependency-management)部分，将 Spring AI BOM 添加到您的构建文件中。

接下来，创建一个 `VertexAiTextEmbeddingModel` 并将其用于文本生成：

```java theme={"system"}
VertexAiEmbeddingConnectionDetails connectionDetails =
    VertexAiEmbeddingConnectionDetails.builder()
        .projectId(System.getenv(<VERTEX_AI_GEMINI_PROJECT_ID>))
        .location(System.getenv(<VERTEX_AI_GEMINI_LOCATION>))
        .build();

VertexAiTextEmbeddingOptions options = VertexAiTextEmbeddingOptions.builder()
    .model(VertexAiTextEmbeddingOptions.DEFAULT_MODEL_NAME)
    .build();

var embeddingModel = new VertexAiTextEmbeddingModel(this.connectionDetails, this.options);

EmbeddingResponse embeddingResponse = this.embeddingModel
    .embedForResponse(List.of("Hello World", "World is big and salvation is near"));
```

### 从 Google 服务帐户加载凭据

要从服务帐户 json 文件以编程方式加载 GoogleCredentials，可以使用以下方法：

```java theme={"system"}
GoogleCredentials credentials = GoogleCredentials.fromStream(<INPUT_STREAM_TO_CREDENTIALS_JSON>)
        .createScoped("https://www.googleapis.com/auth/cloud-platform");
credentials.refreshIfExpired();

VertexAiEmbeddingConnectionDetails connectionDetails =
    VertexAiEmbeddingConnectionDetails.builder()
        .projectId(System.getenv(<VERTEX_AI_GEMINI_PROJECT_ID>))
        .location(System.getenv(<VERTEX_AI_GEMINI_LOCATION>))
        .apiEndpoint(endpoint)
        .predictionServiceSettings(
            PredictionServiceSettings.newBuilder()
                .setEndpoint(endpoint)
                .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
                .build());
```

<Card title="文档有误？请协助编辑" icon="pencil" href="https://github.com/javaai-pig4cloud-com/javaai-docs/edit/main/spring-ai/api/embeddings/vertexai-embeddings-text.mdx">
  发现文档问题？点击此处直接在 GitHub 上编辑并提交 PR，帮助我们改进文档！
</Card>
