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

# WatsonxEmbeddings 集成

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

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

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

## 概览

### 集成细节

## 配置

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

### 凭据

此单元定义了与 watsonx 嵌入交互所需的 WML凭据。

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

```python theme={null}
import os
from getpass import getpass

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

此外，您还可以通过环境变量传递额外的密钥。

```python theme={null}
import os

os.environ["WATSONX_URL"] = "your service instance url"
os.environ["WATSONX_TOKEN"] = "your token for accessing the CLOUD or CPD cluster"
os.environ["WATSONX_PASSWORD"] = "your password for accessing the CPD cluster"
os.environ["WATSONX_USERNAME"] = "your username for accessing the CPD cluster"
os.environ["WATSONX_INSTANCE_ID"] = "your instance_id for accessing the CPD cluster"
```

### 安装

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

```python theme={null}
!pip install -qU langchain-ibm
```

## 初始化

根据不同模型可能需要调整 `parameters`。

```python theme={null}
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` 和 Dallas URL。

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

```python theme={null}
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="PASTE YOUR PROJECT_ID HERE",
    params=embed_params,
)
```

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

```python theme={null}
watsonx_embedding = WatsonxEmbeddings(
    model_id="ibm/granite-embedding-107m-multilingual",
    url="PASTE YOUR URL HERE",
    username="PASTE YOUR USERNAME HERE",
    password="PASTE YOUR PASSWORD HERE",
    instance_id="openshift",
    version="4.8",
    project_id="PASTE YOUR PROJECT_ID HERE",
    params=embed_params,
)
```

对于特定需求，可以传入 IBM 的 [`APIClient`](https://ibm.github.io/watsonx-ai-python-sdk/base.html#apiclient) 对象到 `WatsonxEmbeddings` 类中。

```python theme={null}
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 教程](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/rag.md)。

以下展示如何使用上述初始化的 `embeddings` 对象进行索引与检索。本示例将索引并检索 `InMemoryVectorStore` 中的样本文档。

```python theme={null}
# Create a vector store with a sample text
from langchain_core.vectorstores import InMemoryVectorStore

text = "LangChain is the framework for building context-aware reasoning applications"

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

# Use the vectorstore as a retriever
retriever = vectorstore.as_retriever()

# Retrieve the most similar text
retrieved_documents = retriever.invoke("What is LangChain?")

# show the retrieved document's content
retrieved_documents[0].page_content
```

```text theme={null}
'LangChain is the framework for building context-aware reasoning applications'
```

## 直接使用

底层向量存储和检索器通过 `embeddings.embed_documents(...)` 和 `embeddings.embed_query(...)` 分别为 `from_texts` 和检索 `invoke` 操作生成嵌入。

您可以直接调用这些方法实现自定义场景。

### 单文本嵌入

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

```python theme={null}
text = "This is a test document."

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

```text theme={null}
[0.009447193, -0.024981951, -0.026013248, -0.040483937, -0.05780445]
```

### 多文本嵌入

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

```python theme={null}
texts = ["This is a content of the document", "This is another document"]

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

```text theme={null}
[0.009447167, -0.024981938, -0.02601326, -0.04048393, -0.05780444]
```

***

## API 参考

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

***

> 官方原文：[src/oss/python/integrations/embeddings/ibm\_watsonx.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/embeddings/ibm_watsonx.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.