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

# Nebius 集成

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

[Nebius Token Factory](https://tokenfactory.nebius.com/) 通过统一接口提供对高质量嵌入模型的 API 访问。Nebius 嵌入模型将文本转换为捕获语义含义的数值向量，使其可用于语义搜索、聚类和推荐等各种应用。

## 概述

`NebiusEmbeddings` 类通过 LangChain 提供对 Nebius Token Factory 嵌入模型的访问。这些嵌入可用于语义搜索、文档相似性以及其他需要文本向量表示的 NLP 任务。

### 集成详情

* **提供商**：Nebius Token Factory
* **模型类型**：文本嵌入模型
* **主要用例**：生成文本的向量表示，用于语义相似性和检索
* **当前突出显示的模型**：`Qwen/Qwen3-Embedding-8B`
* **嵌入维度**：4,096（适用于 `Qwen/Qwen3-Embedding-8B`）

## 设置

### 安装

可以通过 pip 安装 Nebius 集成：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -U langchain-nebius
```

### 凭证

Nebius 需要一个 API 密钥，可以作为初始化参数 `api_key` 传递，或设置为环境变量 `NEBIUS_API_KEY`。您可以通过在 [Nebius Token Factory](https://tokenfactory.nebius.com/) 上创建账户来获取 API 密钥。

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

# 确保您已将 API 密钥设置为环境变量
if "NEBIUS_API_KEY" not in os.environ:
    os.environ["NEBIUS_API_KEY"] = getpass.getpass("Enter your Nebius API key: ")
```

## 实例化

`NebiusEmbeddings` 类可以通过可选的 API 密钥和模型名称参数进行实例化：

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

# 初始化嵌入模型
embeddings = NebiusEmbeddings(
    # api_key="YOUR_API_KEY",  # 您可以直接传递 API 密钥
    model="Qwen/Qwen3-Embedding-8B"  # 默认嵌入模型
)
```

### 可用模型

支持的模型列表可在 [Nebius Token Factory 模型页面](https://tokenfactory.nebius.com/models?modality=embedding) 查看

## 索引和检索

嵌入模型通常用于检索增强生成（RAG）流程中，既用于索引数据，也用于后续检索。以下示例演示了如何将 `NebiusEmbeddings` 与向量存储结合用于文档检索。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.vectorstores import FAISS
from langchain_core.documents import Document

# 准备文档
docs = [
    Document(
        page_content="Machine learning algorithms build mathematical models based on sample data"
    ),
    Document(page_content="Deep learning uses neural networks with many layers"),
    Document(page_content="Climate change is a major global environmental challenge"),
    Document(
        page_content="Neural networks are inspired by the human brain's structure"
    ),
]

# 创建向量存储
vector_store = FAISS.from_documents(docs, embeddings)

# 执行相似性搜索
query = "How does the brain influence AI?"
results = vector_store.similarity_search(query, k=2)

print("Search results for query:", query)
for i, doc in enumerate(results):
    print(f"Result {i + 1}: {doc.page_content}")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Search results for query: How does the brain influence AI?
Result 1: Neural networks are inspired by the human brain's structure
Result 2: Deep learning uses neural networks with many layers
```

### 与 InMemoryVectorStore 一起使用

您也可以将 `InMemoryVectorStore` 用于轻量级应用：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.vectorstores import InMemoryVectorStore

# 创建示例文本
text = "LangChain is a framework for developing applications powered by language models"

# 创建向量存储
vectorstore = InMemoryVectorStore.from_texts(
    [text],
    embedding=embeddings,
)

# 用作检索器
retriever = vectorstore.as_retriever()

# 检索相似文档
docs = retriever.invoke("What is LangChain?")
print(f"Retrieved document: {docs[0].page_content}")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Retrieved document: LangChain is a framework for developing applications powered by language models
```

## 直接使用

您可以直接使用 `NebiusEmbeddings` 类为文本生成嵌入，而无需使用向量存储。

### 嵌入单个文本

您可以使用 `embed_query` 方法嵌入单个文本：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
query = "What is machine learning?"
query_embedding = embeddings.embed_query(query)

# 检查嵌入维度
print(f"Embedding dimension: {len(query_embedding)}")
print(f"First few values: {query_embedding[:5]}")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Embedding dimension: 4096
First few values: [0.007419586181640625, 0.002246856689453125, 0.00193023681640625, -0.0066070556640625, -0.0179901123046875]
```

### 嵌入多个文本

您可以使用 `embed_documents` 方法一次嵌入多个文本：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
documents = [
    "Machine learning is a branch of artificial intelligence",
    "Deep learning is a subfield of machine learning",
    "Natural language processing deals with interactions between computers and human language",
]

document_embeddings = embeddings.embed_documents(documents)

# 检查结果
print(f"Number of document embeddings: {len(document_embeddings)}")
print(f"Each embedding has {len(document_embeddings[0])} dimensions")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Number of document embeddings: 3
Each embedding has 4096 dimensions
```

### 异步支持

NebiusEmbeddings 支持异步操作：

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


async def generate_embeddings_async():
    # 嵌入单个查询
    query_result = await embeddings.aembed_query("What is the capital of France?")
    print(f"Async query embedding dimension: {len(query_result)}")

    # 嵌入多个文档
    docs = [
        "Paris is the capital of France",
        "Berlin is the capital of Germany",
        "Rome is the capital of Italy",
    ]
    docs_result = await embeddings.aembed_documents(docs)
    print(f"Async document embeddings count: {len(docs_result)}")


await generate_embeddings_async()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Async query embedding dimension: 4096
Async document embeddings count: 3
```

### 文档相似性示例

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import numpy as np
from scipy.spatial.distance import cosine

# 创建一些文档
documents = [
    "Machine learning algorithms build mathematical models based on sample data",
    "Deep learning uses neural networks with many layers",
    "Climate change is a major global environmental challenge",
    "Neural networks are inspired by the human brain's structure",
]

# 嵌入文档
embeddings_list = embeddings.embed_documents(documents)


# 计算相似性的函数
def calculate_similarity(embedding1, embedding2):
    return 1 - cosine(embedding1, embedding2)


# 打印相似性矩阵
print("Document Similarity Matrix:")
for i, emb_i in enumerate(embeddings_list):
    similarities = []
    for j, emb_j in enumerate(embeddings_list):
        similarity = calculate_similarity(emb_i, emb_j)
        similarities.append(f"{similarity:.4f}")
    print(f"Document {i + 1}: {similarities}")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document Similarity Matrix:
Document 1: ['1.0000', '0.8282', '0.5811', '0.7985']
Document 2: ['0.8282', '1.0000', '0.5897', '0.8315']
Document 3: ['0.5811', '0.5897', '1.0000', '0.5918']
Document 4: ['0.7985', '0.8315', '0.5918', '1.0000']
```

***

## API 参考

有关 Nebius Token Factory API 的更多详情，请访问 [Nebius Token Factory 文档](https://docs.tokenfactory.nebius.com/quickstart)。

***

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

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