> ## Documentation Index
> Fetch the complete documentation index at: https://nvd-54.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 向量嵌入模型集成

> 使用 LangChain JavaScript 集成 embedding models。

## 概述

<Note>
  本概述涵盖**基于文本的向量嵌入模型**。LangChain 目前不支持多模态向量嵌入。
</Note>

向量嵌入模型将原始文本（如句子、段落或推文）转换为一个固定长度的数字向量，以捕获其**语义含义**。这些向量使机器能够基于含义而非精确词汇来比较和搜索文本。

在实践中，这意味着具有相似含义的文本在向量空间中被放置在相近的位置。例如，向量嵌入不仅可以匹配 *"machine learning"* 这一短语，还可以找到讨论相关概念的文档，即使使用了不同的措辞。

### 工作原理

1. **Vectorization** — The model encodes each input string as a high-dimensional vector.
2. **Similarity scoring** — Vectors are compared using mathematical metrics to measure how closely related the underlying texts are.

### 相似度指标

通常使用以下几种指标来比较向量嵌入：

* **Cosine similarity** — measures the angle between two vectors.
* **Euclidean distance** — measures the straight-line distance between points.
* **Dot product** — measures how much one vector projects onto another.

## 接口

LangChain 通过 [Embeddings](https://reference.langchain.com/javascript/langchain-core/embeddings/Embeddings) 接口为文本向量嵌入模型（如 OpenAI、Cohere、Hugging Face）提供标准接口。

提供两个主要方法：

* `embedDocuments(documents: string[]) → number[][]`: Embeds a list of documents.
* `embedQuery(text: string) → number[]`: Embeds a single query.

<Note>
  该接口允许查询和文档使用不同的策略进行嵌入，尽管大多数提供商在实践中以相同方式处理它们。
</Note>

## 安装和使用

<AccordionGroup>
  <Accordion title="OpenAI">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/openai
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/openai
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/openai
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    OPENAI_API_KEY=your-api-key
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { OpenAIEmbeddings } from "@langchain/openai";

    const embeddings = new OpenAIEmbeddings({
      model: "text-embedding-3-large"
    });
    ```
  </Accordion>

  <Accordion title="Azure">
    安装依赖

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/openai
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/openai
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/openai
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    AZURE_OPENAI_API_INSTANCE_NAME=<YOUR_INSTANCE_NAME>
    AZURE_OPENAI_API_KEY=<YOUR_KEY>
    AZURE_OPENAI_API_VERSION="2024-02-01"
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { AzureOpenAIEmbeddings } from "@langchain/openai";

    const embeddings = new AzureOpenAIEmbeddings({
      azureOpenAIApiEmbeddingsDeploymentName: "text-embedding-ada-002"
    });
    ```
  </Accordion>

  <Accordion title="AWS">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/aws
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/aws
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/aws
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    BEDROCK_AWS_REGION=your-region
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { BedrockEmbeddings } from "@langchain/aws";

    const embeddings = new BedrockEmbeddings({
      model: "amazon.titan-embed-text-v1"
    });
    ```
  </Accordion>

  <Accordion title="Google Gemini">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/google-genai
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/google-genai
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/google-genai
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    GOOGLE_API_KEY=your-api-key
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";

    const embeddings = new GoogleGenerativeAIEmbeddings({
      model: "text-embedding-004"
    });
    ```
  </Accordion>

  <Accordion title="Google Vertex">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/google-vertexai
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/google-vertexai
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/google-vertexai
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    GOOGLE_APPLICATION_CREDENTIALS=credentials.json
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { VertexAIEmbeddings } from "@langchain/google-vertexai";

    const embeddings = new VertexAIEmbeddings({
      model: "gemini-embedding-001"
    });
    ```
  </Accordion>

  <Accordion title="MistralAI">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/mistralai
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/mistralai
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/mistralai
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    MISTRAL_API_KEY=your-api-key
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { MistralAIEmbeddings } from "@langchain/mistralai";

    const embeddings = new MistralAIEmbeddings({
      model: "mistral-embed"
    });
    ```
  </Accordion>

  <Accordion title="Cohere">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/cohere
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/cohere
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/cohere
      ```
    </CodeGroup>

    添加环境变量：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    COHERE_API_KEY=your-api-key
    ```

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { CohereEmbeddings } from "@langchain/cohere";

    const embeddings = new CohereEmbeddings({
      model: "embed-english-v3.0"
    });
    ```
  </Accordion>

  <Accordion title="Ollama">
    安装依赖：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm i @langchain/ollama
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/ollama
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/ollama
      ```
    </CodeGroup>

    实例化模型：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { OllamaEmbeddings } from "@langchain/ollama";

    const embeddings = new OllamaEmbeddings({
      model: "llama2",
      baseUrl: "http://localhost:11434", // Default value
    });
    ```
  </Accordion>
</AccordionGroup>

## 缓存

向量嵌入可以被存储或临时缓存，以避免重新计算。

可以使用 `CacheBackedEmbeddings` 来缓存向量嵌入。此包装器将向量嵌入存储在键值存储中，文本被哈希处理，哈希值用作缓存中的键。

The main supported way to initialize a `CacheBackedEmbeddings` is `fromBytesStore`. It takes the following parameters:

* **underlyingEmbeddings**: The embedder to use for embedding.
* **documentEmbeddingStore**: Any [`BaseStore`](/oss/javascript/integrations/stores/) for caching document embeddings.
* **options.namespace**: (optional, defaults to `""`) The namespace to use for the document cache. Helps avoid collisions (e.g., set it to the embedding model name).

<Important>
  - Always set the `namespace` parameter to avoid collisions when using different embedding models.
  - `CacheBackedEmbeddings` does not cache query embeddings by default. To enable this, specify a `query_embedding_store`.
</Important>

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { CacheBackedEmbeddings } from "@langchain/classic/embeddings/cache_backed";
import { InMemoryStore } from "@langchain/core/stores";

const underlyingEmbeddings = new OpenAIEmbeddings();

const inMemoryStore = new InMemoryStore();

const cacheBackedEmbeddings = CacheBackedEmbeddings.fromBytesStore(
  underlyingEmbeddings,
  inMemoryStore,
  {
    namespace: underlyingEmbeddings.model,
  }
);

// Example: caching a query embedding
const tic = Date.now();
const queryEmbedding = cacheBackedEmbeddings.embedQuery("Hello, world!");
console.log(`First call took: ${Date.now() - tic}ms`);

// Example: caching a document embedding
const tic = Date.now();
const documentEmbedding = cacheBackedEmbeddings.embedDocuments(["Hello, world!"]);
console.log(`Cached creation time: ${Date.now() - tic}ms`);
```

在生产环境中，你通常会使用更稳健的持久化存储，如数据库或云存储。请参阅[存储集成](/oss/javascript/integrations/stores/)了解可选方案。

## 所有集成

<Columns cols={3}>
  <Card title="Alibaba Tongyi" icon="link" href="/oss/javascript/integrations/embeddings/alibaba_tongyi" arrow="true" cta="查看指南" />

  <Card title="Azure OpenAI" icon="link" href="/oss/javascript/integrations/embeddings/azure_openai" arrow="true" cta="查看指南" />

  <Card title="Baidu Qianfan" icon="link" href="/oss/javascript/integrations/embeddings/baidu_qianfan" arrow="true" cta="查看指南" />

  <Card title="Amazon Bedrock" icon="link" href="/oss/javascript/integrations/embeddings/bedrock" arrow="true" cta="查看指南" />

  <Card title="ByteDance Doubao" icon="link" href="/oss/javascript/integrations/embeddings/bytedance_doubao" arrow="true" cta="查看指南" />

  <Card title="Cloudflare Workers AI" icon="link" href="/oss/javascript/integrations/embeddings/cloudflare_ai" arrow="true" cta="查看指南" />

  <Card title="Cohere" icon="link" href="/oss/javascript/integrations/embeddings/cohere" arrow="true" cta="查看指南" />

  <Card title="DeepInfra" icon="link" href="/oss/javascript/integrations/embeddings/deepinfra" arrow="true" cta="查看指南" />

  <Card title="Fireworks" icon="link" href="/oss/javascript/integrations/embeddings/fireworks" arrow="true" cta="查看指南" />

  <Card title="Google Generative AI" icon="link" href="/oss/javascript/integrations/embeddings/google_generative_ai" arrow="true" cta="查看指南" />

  <Card title="Google Vertex AI" icon="link" href="/oss/javascript/integrations/embeddings/google_vertex_ai" arrow="true" cta="查看指南" />

  <Card title="Gradient AI" icon="link" href="/oss/javascript/integrations/embeddings/gradient_ai" arrow="true" cta="查看指南" />

  <Card title="HuggingFace Inference" icon="link" href="/oss/javascript/integrations/embeddings/hugging_face_inference" arrow="true" cta="查看指南" />

  <Card title="IBM watsonx.ai" icon="link" href="/oss/javascript/integrations/embeddings/ibm" arrow="true" cta="查看指南" />

  <Card title="Jina" icon="link" href="/oss/javascript/integrations/embeddings/jina" arrow="true" cta="查看指南" />

  <Card title="Llama CPP" icon="link" href="/oss/javascript/integrations/embeddings/llama_cpp" arrow="true" cta="查看指南" />

  <Card title="Minimax" icon="link" href="/oss/javascript/integrations/embeddings/minimax" arrow="true" cta="查看指南" />

  <Card title="MistralAI" icon="link" href="/oss/javascript/integrations/embeddings/mistralai" arrow="true" cta="查看指南" />

  <Card title="Mixedbread AI" icon="link" href="/oss/javascript/integrations/embeddings/mixedbread_ai" arrow="true" cta="查看指南" />

  <Card title="Nomic" icon="link" href="/oss/javascript/integrations/embeddings/nomic" arrow="true" cta="查看指南" />

  <Card title="Ollama" icon="link" href="/oss/javascript/integrations/embeddings/ollama" arrow="true" cta="查看指南" />

  <Card title="Oracle AI Database" icon="link" href="/oss/javascript/integrations/embeddings/oracleai" arrow="true" cta="查看指南" />

  <Card title="OpenAI" icon="link" href="/oss/javascript/integrations/embeddings/openai" arrow="true" cta="查看指南" />

  <Card title="Pinecone" icon="link" href="/oss/javascript/integrations/embeddings/pinecone" arrow="true" cta="查看指南" />

  <Card title="Prem AI" icon="link" href="/oss/javascript/integrations/embeddings/premai" arrow="true" cta="查看指南" />

  <Card title="Tencent Hunyuan" icon="link" href="/oss/javascript/integrations/embeddings/tencent_hunyuan" arrow="true" cta="查看指南" />

  <Card title="TensorFlow" icon="link" href="/oss/javascript/integrations/embeddings/tensorflow" arrow="true" cta="查看指南" />

  <Card title="TogetherAI" icon="link" href="/oss/javascript/integrations/embeddings/togetherai" arrow="true" cta="查看指南" />

  <Card title="HuggingFace Transformers" icon="link" href="/oss/javascript/integrations/embeddings/transformers" arrow="true" cta="查看指南" />

  <Card title="Voyage AI" icon="link" href="/oss/javascript/integrations/embeddings/voyageai" arrow="true" cta="查看指南" />

  <Card title="ZhipuAI" icon="link" href="/oss/javascript/integrations/embeddings/zhipuai" arrow="true" cta="查看指南" />
</Columns>

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接到](/use-these-docs) Claude、VSCode 等工具，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/embeddings/index.mdx) 或 [提交 issue](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
