> ## 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.

# Apify 数据集集成

> 使用 LangChain Python 与 Apify 数据集文档加载器集成。

> [Apify 数据集](https://docs.apify.com/platform/storage/dataset) 是一个可扩展的仅追加存储，具有顺序访问功能，专为存储结构化的网页抓取结果而设计，例如产品列表或 Google SERP，然后可以将其导出为 JSON、CSV 或 Excel 等各种格式。数据集主要用于保存 [Apify Actor](https://apify.com/store) 的结果——这些是用于各种网页抓取、爬取和数据提取用例的无服务器云程序。

本笔记本展示了如何将 Apify 数据集加载到 LangChain。

### 集成详情

| 类                                                                | 包                                                              | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/document_loaders/web_loaders/apify_dataset) |                                               版本                                              |
| :--------------------------------------------------------------- | :------------------------------------------------------------- | :--: | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------: |
| [`ApifyDatasetLoader`](https://github.com/apify/langchain-apify) | [`langchain-apify`](https://pypi.org/project/langchain-apify/) |   ❌  |                                                ✅                                               | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-apify?style=flat-square\&label=%20) |

### 加载器特性

|     来源    | 文档延迟加载 | 原生异步支持 |
| :-------: | :----: | :----: |
| Apify 数据集 |    ❌   |    ❌   |

## 前提条件

您需要在 Apify 平台上拥有一个现有的数据集。此示例展示了如何加载由 [Website Content Crawler](https://apify.com/apify/website-content-crawler) 生成的数据集。

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

首先，将 `ApifyDatasetLoader` 导入到您的源代码中：

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

找到您的 [Apify API 令牌](https://console.apify.com/account/integrations) 和 [OpenAI API 密钥](https://platform.openai.com/account/api-keys)，并将它们初始化为环境变量：

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

os.environ["APIFY_TOKEN"] = "your-apify-token"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
```

## 定价

Apify Actor 的定价方式可能不同，具体取决于您运行的 Actor。
许多 Actor 支持 [按事件付费 (PPE) 定价](https://docs.apify.com/platform/actors/publishing/monetize/pay-per-event)，您需要为 Actor 作者定义的明确事件付费（例如，按数据集项目计费）。这对于您希望获得清晰、按操作计费成本的代理工作负载来说可能是一个不错的选择。

## 将数据集项目映射到文档

接下来，定义一个函数，将 Apify 数据集记录字段映射到 LangChain [`Document`](https://reference.langchain.com/python/langchain-core/documents/base/Document) 格式。

例如，如果您的数据集项目结构如下：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
    "url": "https://apify.com",
    "text": "Apify is the best web scraping and automation platform."
}
```

下面代码中的映射函数会将它们转换为 LangChain [`Document`](https://reference.langchain.com/python/langchain-core/documents/base/Document) 格式，以便您可以进一步与任何 LLM 模型一起使用（例如用于问答）。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = ApifyDatasetLoader(
    dataset_id="your-dataset-id",
    dataset_mapping_function=lambda dataset_item: Document(
        page_content=dataset_item["text"], metadata={"source": dataset_item["url"]}
    ),
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
data = loader.load()
```

## 一个问答示例

在此示例中，我们使用数据集中的数据来回答问题。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.indexes import VectorstoreIndexCreator
from langchain_apify import ApifyWrapper
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import ChatOpenAI
from langchain_openai.embeddings import OpenAIEmbeddings
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = ApifyDatasetLoader(
    dataset_id="your-dataset-id",
    dataset_mapping_function=lambda item: Document(
        page_content=item["text"] or "", metadata={"source": item["url"]}
    ),
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
index = VectorstoreIndexCreator(
    vectorstore_cls=InMemoryVectorStore, embedding=OpenAIEmbeddings()
).from_loaders([loader])
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
llm = ChatOpenAI(model="gpt-5-mini")
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
query = "What is Apify?"
result = index.query_with_sources(query, llm=llm)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print(result["answer"])
print(result["sources"])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
 Apify is a platform for developing, running, and sharing serverless cloud programs. It enables users to create web scraping and automation tools and publish them on the Apify platform.

https://docs.apify.com/platform/actors, https://docs.apify.com/platform/actors/running/actors-in-store, https://docs.apify.com/platform/security, https://docs.apify.com/platform/actors/examples
```

***

## 使用 Apify MCP 服务器

不确定使用哪个 Actor 或它需要什么参数？[Apify MCP（模型上下文协议）服务器](https://mcp.apify.com) 可以帮助您发现可用的 Actor，探索其输入模式，并了解参数要求。

通过 HTTP 连接到 Apify MCP 服务器时，请在请求头中包含您的 Apify 令牌：

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Authorization: Bearer <APIFY_TOKEN>
```

更多信息，请参阅 [LangChain MCP 文档](/oss/python/langchain/mcp)。

***

<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/document_loaders/apify_dataset.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
