Pinecone

本部分将指导您设置 Pinecone VectorStore 以存储文档嵌入并执行相似性搜索。

What is Pinecone?

Pinecone是一个流行的基于云的向量数据库,它可以让您高效地存储和搜索向量。

Prerequisites

  1. Pinecone 帐户:开始前,请注册 Pinecone account

  2. Pinecone 项目:注册后,创建一个新项目、一个索引并生成一个 API 密钥。您需要这些详细信息进行配置。

  3. OpenAI 帐户:在 OpenAI Signup上创建一个帐户并生成 API Keys上的令牌。

Configuration

为了设置 PineconeVectorStore,请从你的 Pinecone 账户中收集以下详细信息:

  • Pinecone API Key

  • Pinecone Environment

  • Pinecone Project ID

  • Pinecone Index Name

  • Pinecone Namespace

在 Pinecone UI 门户网站中可以看到这些信息。

在设置嵌入时,选择 1536 的矢量维度。这匹配了 OpenAI 模型 text-embedding-ada-002 的维数,我们将在本指南中使用此模型。

此外,你需要提供你的 OpenAI API 秘钥。像这样将其设置为环境变量:

export SPRING_AI_OPENAI_API_KEY='Your_OpenAI_API_Key'

Repository

为了获取 Spring AI 构件,声明 Spring 快照储存库:

<repository>
	<id>spring-snapshots</id>
	<name>Spring Snapshots</name>
	<url>https://repo.spring.io/snapshot</url>
	<releases>
		<enabled>false</enabled>
	</releases>
</repository>

Dependencies

将这些依赖项添加到你的项目中:

  • OpenAI:用于计算嵌入。

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
  • Pinecone

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-pinecone</artifactId>
</dependency>
  1. 参见 Dependency Management 部分,将 Spring AI BOM 添加到你的构建文件中。

Sample Code

为了在你的应用程序中配置 Pinecone,你可以使用以下设置:

@Bean
public PineconeVectorStoreConfig pineconeVectorStoreConfig() {

    return PineconeVectorStoreConfig.builder()
        .withApiKey(<PINECONE_API_KEY>)
        .withEnvironment("gcp-starter")
        .withProjectId("89309e6")
        .withIndexName("spring-ai-test-index")
        .withNamespace("") // the free tier doesn't support namespaces.
        .build();
}

通过向你的项目中添加 Spring Boot OpenAI 启动器来与 OpenAI 的嵌入集成。这为你提供了嵌入客户端的实现:

@Bean
public VectorStore vectorStore(PineconeVectorStoreConfig config, EmbeddingClient embeddingClient) {
    return new PineconeVectorStore(config, embeddingClient);
}

在你的主代码中,创建一些文档:

List<Document> documents = List.of(
	new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
	new Document("The World is Big and Salvation Lurks Around the Corner"),
	new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

将这些文档添加到 Pinecone:

vectorStore.add(List.of(document));

最后,检索与查询类似的文档:

List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5));

如果一切都顺利,你应该检索包含文本 “Spring AI rocks!!” 的文档。