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

# WatsonxEmbeddings 集成

> 使用 LangChain Python 集成 WatsonxEmbeddings 嵌入模型。

> `WatsonxEmbeddings` 是 IBM [watsonx.ai](https://www.ibm.com/products/watsonx-ai) 基础模型的封装器。

本示例展示如何使用 `LangChain` 与 `watsonx.ai` 模型进行通信。

## 概述

### 集成详情

<ItemTable category="embeddings" item="IBM" />

## 设置

要访问 IBM watsonx.ai 模型，您需要创建一个 IBM watsonx.ai 账户，获取 API 密钥，并安装 `langchain-ibm` 集成包。

### 凭证

此单元格定义了使用 watsonx Embeddings 所需的 WML 凭证。

**操作：** 提供 IBM Cloud 用户 API 密钥。详情请参阅
[文档](https://cloud.ibm.com/docs/account?topic=account-userapikey\&interface=ui)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from getpass import getpass

watsonx_api_key = getpass()
os.environ["WATSONX_APIKEY"] = watsonx_api_key
```

此外，您还可以将其他密钥作为环境变量传递。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os

os.environ["WATSONX_URL"] = "您的服务实例 URL"
os.environ["WATSONX_TOKEN"] = "用于访问 CLOUD 或 CPD 集群的令牌"
os.environ["WATSONX_PASSWORD"] = "用于访问 CPD 集群的密码"
os.environ["WATSONX_USERNAME"] = "用于访问 CPD 集群的用户名"
os.environ["WATSONX_INSTANCE_ID"] = "用于访问 CPD 集群的实例 ID"
```

### 安装

LangChain IBM 集成位于 `langchain-ibm` 包中：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
!pip install -qU langchain-ibm
```

## 实例化

您可能需要针对不同的模型调整模型 `parameters`。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from ibm_watsonx_ai.metanames import EmbedTextParamsMetaNames

embed_params = {
    EmbedTextParamsMetaNames.TRUNCATE_INPUT_TOKENS: 3,
    EmbedTextParamsMetaNames.RETURN_OPTIONS: {"input_text": True},
}
```

使用先前设置的参数初始化 `WatsonxEmbeddings` 类。

**注意**：

* 为了给 API 调用提供上下文，您必须添加 `project_id` 或 `space_id`。更多信息请参阅 [文档](https://www.ibm.com/docs/en/watsonx-as-a-service?topic=projects)。
* 根据您预配的服务实例所在区域，使用相应的 [区域特定认证 URL](https://ibm.github.io/watsonx-ai-python-sdk/setup_cloud.html#authentication)。

在此示例中，我们将使用 `project_id` 和达拉斯 URL。

您需要指定用于推理的 `model_id`。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_ibm import WatsonxEmbeddings

watsonx_embedding = WatsonxEmbeddings(
    model_id="ibm/granite-embedding-107m-multilingual",
    url="https://us-south.ml.cloud.ibm.com",
    project_id="在此处粘贴您的 PROJECT_ID",
    params=embed_params,
)
```

或者，您可以使用 Cloud Pak for Data 凭证。详情请参阅 [文档](https://ibm.github.io/watsonx-ai-python-sdk/setup_cpd.html)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
watsonx_embedding = WatsonxEmbeddings(
    model_id="ibm/granite-embedding-107m-multilingual",
    url="在此处粘贴您的 URL",
    username="在此处粘贴您的用户名",
    password="在此处粘贴您的密码",
    instance_id="openshift",
    version="4.8",
    project_id="在此处粘贴您的 PROJECT_ID",
    params=embed_params,
)
```

对于某些需求，可以选择将 IBM 的 [`APIClient`](https://ibm.github.io/watsonx-ai-python-sdk/base.html#apiclient) 对象传递给 `WatsonxEmbeddings` 类。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from ibm_watsonx_ai import APIClient

api_client = APIClient(...)

watsonx_embedding = WatsonxEmbeddings(
    model_id="ibm/granite-embedding-107m-multilingual",
    watsonx_client=api_client,
)
```

## 索引与检索

嵌入模型通常用于检索增强生成（RAG）流程中，既用于索引数据，也用于后续检索。更详细的说明，请参阅我们的 [RAG 教程](/oss/python/langchain/rag)。

下面，我们将使用上面初始化的 `embeddings` 对象来演示如何索引和检索数据。在此示例中，我们将在 `InMemoryVectorStore` 中索引和检索一个示例文档。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 使用示例文本创建向量存储
from langchain_core.vectorstores import InMemoryVectorStore

text = "LangChain 是用于构建上下文感知推理应用程序的框架"

vectorstore = InMemoryVectorStore.from_texts(
    [text],
    embedding=watsonx_embedding,
)

# 将向量存储用作检索器
retriever = vectorstore.as_retriever()

# 检索最相似的文本
retrieved_documents = retriever.invoke("什么是 LangChain？")

# 显示检索到的文档内容
retrieved_documents[0].page_content
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'LangChain 是用于构建上下文感知推理应用程序的框架'
```

## 直接使用

在底层，向量存储和检索器的实现会调用 `embeddings.embed_documents(...)` 和 `embeddings.embed_query(...)`，分别为 `from_texts` 中使用的文本和检索 `invoke` 操作创建嵌入。

您可以直接调用这些方法来获取嵌入，用于您自己的用例。

### 嵌入单个文本

您可以使用 `embed_query` 嵌入单个文本或文档：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
text = "这是一个测试文档。"

query_result = watsonx_embedding.embed_query(text)
query_result[:5]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[0.009447193, -0.024981951, -0.026013248, -0.040483937, -0.05780445]
```

### 嵌入多个文本

您可以使用 `embed_documents` 嵌入多个文本：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
texts = ["这是文档的内容", "这是另一个文档"]

doc_result = watsonx_embedding.embed_documents(texts)
doc_result[0][:5]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[0.009447167, -0.024981938, -0.02601326, -0.04048393, -0.05780444]
```

***

## API 参考

有关 `WatsonxEmbeddings` 所有功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/python/integrations/langchain_ibm/WatsonxEmbeddings/)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\embeddings\ibm_watsonx.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
