> ## Documentation Index
> Fetch the complete documentation index at: https://help.decodo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain（Python）

> langchain-decodo 软件包：为 LangChain 智能体提供 Decodo 抓取、搜索、站点地图和爬取工具，并附带用于 RAG 流程的文档加载器

`langchain-decodo` 是面向 Decodo Web Data API 的 Python LangChain 软件包。它为 LangChain 智能体提供六个工具——网页抓取、两种搜索、站点地图和爬取——并附带一个文档加载器，可将网页转换为 LangChain `Document` 对象，用于 RAG 流程。

> [!NOTE]
>
> 源代码和最新版本请参阅 [**langchain 仓库**](https://github.com/Decodo/langchain/tree/master/libs/partners/decodo)。使用 Node.js 开发？请参阅 [**LangChain（TypeScript）**](https://help.decodo.com/docs/cn/langchain.md)。

## 功能

* **网页抓取**：抓取任何 URL，并以 Markdown 格式返回页面内容
* **解析式搜索**：Google 搜索和 Amazon 搜索，返回结构化结果
* **网页搜索**：搜索网络，返回带标题、链接和描述的排序结果
* **站点地图**：列出网站上的 URL，而不获取其内容
* **爬取**：爬取网站，并获取找到的每个页面的内容
* **文档加载器**：将一个或多个 URL 加载为 LangChain `Document` 对象，用于 RAG
* **LangChain 集成**：标准的 `BaseTool` 和 `BaseLoader` 类，可接入任何智能体或链

## 要求

* Python 3.10 及以上版本
* Decodo [**Web Data API 计划**](https://dashboard.decodo.com/web-data/pricing)。[**控制面板**](https://dashboard.decodo.com/)提供免费试用。

## 安装

```bash theme={null}
pip install langchain-decodo
```

## 身份验证

从 [**Web Data API 演练场**](https://dashboard.decodo.com/web-data/playground)复制您的 Web Data API 密钥，并将其存储在 `DECODO_API_TOKEN` 环境变量中。软件包中的每个类都从该变量读取密钥：

```bash theme={null}
export DECODO_API_TOKEN=your_api_key
```

至于如何传递密钥，则取决于该类属于哪一组。

### 抓取工具和加载器

`DecodoWebScrapeTool`、`DecodoSearchTool` 和 `DecodoLoader` 支持两种凭据类型，通过 `auth_mode` 选择。使用 API 密钥时需传入 `auth_mode="token"`：

```python theme={null}
from langchain_decodo import DecodoWebScrapeTool

tool = DecodoWebScrapeTool(auth_mode="token")
```

> [!WARNING]
>
> `auth_mode` 的默认值是 `"basic"`，而不是 `"token"`。如果省略该参数，API 密钥会被当作基本身份验证令牌发送，每个请求都会失败并返回 `Decodo API error: Username invalid.`

较旧的计划只有基本身份验证令牌（base64 编码的 `username:password`）。请将其放入 `DECODO_API_TOKEN` 并省略 `auth_mode`，因为 `"basic"` 就是默认值。

您也可以直接传入凭据，而不使用环境变量：两个工具使用 `decodo_api_token=`，加载器使用 `api_token=`。

### Web Data API 工具

`DecodoWebSearchTool`、`DecodoMapTool`、`DecodoCrawlTool` 和 `DecodoCrawlCancelTool` 调用的端点仅存在于 `data.decodo.com` 上，而该主机只接受 API 密钥。这四个工具**没有 `auth_mode` 参数**，也无法配合基本身份验证令牌使用。它们从环境变量读取 `DECODO_API_TOKEN`，或直接接受 `decodo_api_token=`：

```python theme={null}
from langchain_decodo import DecodoWebSearchTool

tool = DecodoWebSearchTool()  # 从 DECODO_API_TOKEN 读取 API 密钥
```

如果创建时没有提供密钥，会抛出 `ValueError: A Decodo Web Data API key is required.`。如果提供的是基本身份验证令牌，API 会拒绝该请求，并返回错误说明较旧计划的基本身份验证令牌在此处不可用。

## 快速开始

下面的 LangChain 智能体会搜索网络、挑选一个页面并抓取它。本示例通过 `langchain-openai` 使用 OpenAI，但 LangChain 支持的任何聊天模型都可以：

```bash theme={null}
pip install langchain-decodo langchain langchain-openai
export DECODO_API_TOKEN=your_api_key
export OPENAI_API_KEY=your_openai_key
```

```python theme={null}
# main.py
from langchain.agents import create_agent
from langchain_decodo import DecodoWebScrapeTool, DecodoWebSearchTool

agent = create_agent(
    model="openai:gpt-5-mini",
    tools=[
        DecodoWebSearchTool(),
        DecodoWebScrapeTool(auth_mode="token"),
    ],
)

result = agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "Find out who won the 2025 NBA Finals, then scrape the page you find and summarise it.",
            }
        ]
    }
)

print(result["messages"][-1].content)
```

请注意该示例中两种不同的身份验证方式：`DecodoWebSearchTool` 不接受 `auth_mode`，而 `DecodoWebScrapeTool` 需要 `auth_mode="token"`。两者读取的都是同一个 `DECODO_API_TOKEN`。

## 可用工具

| 类 | 向智能体公开的工具名称 | 用途 |
| - | - | - |
| `DecodoWebScrapeTool` | `decodo_scrape_url` | 抓取任何 URL 并返回 Markdown |
| `DecodoSearchTool` | `decodo_search` | Google 搜索或 Amazon 搜索，返回解析后的结果 |
| `DecodoWebSearchTool` | `decodo_web_search` | 搜索网络并返回排序结果 |
| `DecodoMapTool` | `decodo_map` | 列出网站上的 URL，默认 100 个，最多 500 个 |
| `DecodoCrawlTool` | `decodo_crawl` | 爬取网站并返回每个页面，默认 10 个，最多 100 个 |
| `DecodoCrawlCancelTool` | `decodo_crawl_cancel` | 停止正在运行的爬取任务 |

这些工具分为两组，区别在于身份验证方式和返回内容：

* **抓取工具**：`DecodoWebScrapeTool` 和 `DecodoSearchTool`。它们通过抓取端点抓取页面或搜索引擎的结果页，并接受两种凭据类型。
* **Web Data API 工具**：`DecodoWebSearchTool`、`DecodoMapTool`、`DecodoCrawlTool` 和 `DecodoCrawlCancelTool`。每个都有自己的输入结构，且四个都需要 API 密钥。

`DecodoLoader` 不是工具，而是 LangChain 文档加载器，详见下文的“文档加载器”一节。

您也可以不经智能体直接调用任何工具：

```python theme={null}
from langchain_decodo import DecodoMapTool, DecodoWebScrapeTool

scrape = DecodoWebScrapeTool(auth_mode="token")
markdown = scrape.invoke("https://quotes.toscrape.com")

site_map = DecodoMapTool()
urls = site_map.invoke({"url": "https://quotes.toscrape.com", "limit": 20})
```

## 抓取工具

### `DecodoWebScrapeTool`

接受单个 `url`，必须包含 `http://` 或 `https://`。它会调用 `universal` 目标并设置 `markdown: true`，以 Markdown 字符串的形式返回页面。当 API 没有返回内容时，该工具不会抛出异常，而是返回字符串 `(No content returned by Decodo API)`。

| 构造函数参数 | 默认值 | 说明 |
| - | - | - |
| `decodo_api_token` | `DECODO_API_TOKEN` | API 密钥，或较旧计划的基本身份验证令牌 |
| `auth_mode` | `"basic"` | 使用 API 密钥时设置为 `"token"` |
| `base_url` | – | 覆盖 `auth_mode` 所选择的主机，通常无需设置 |

### `DecodoSearchTool`

接受以下输入：

| 输入 | 默认值 | 说明 |
| - | - | - |
| `query` | – | 搜索查询。必填 |
| `engine` | `google` | `google` 调用 `google_search` 目标，`amazon` 调用 `amazon_search` |
| `num_results` | `10` | 以 `limit` 的形式发送给 API。接受 1 到 100 |

它始终发送 `parse: true`，并返回一个 JSON 字符串：一个列表，每个结果对应一个条目，包含 `content`、`status_code` 和 `url`。解析后的结果位于 `content` 中，例如 Google 自然搜索结果在 `content.results.results.organic`。

如果搜索失败，该工具会抛出带有状态码的 `RuntimeError`。失败的搜索可能以 HTTP 200 的形式从 API 返回，因此抛出异常可以让智能体重试，而不是将其视为“没有结果”。

> [!NOTE]
>
> 请在每次调用时传入 `engine`，如上面的示例所示。在创建工具时设置（`DecodoSearchTool(engine="amazon")`）不会生效，搜索仍会发送到 Google。

> [!NOTE]
>
> 工具无法识别的 `engine` 值不会被拒绝，而是回退到 Google。

> [!NOTE]
>
> `num_results` 并不限制返回的结果数量。即使将 `num_results` 设置为 3，Google 搜索仍会返回第一页的全部自然搜索结果。

## Web Data API 工具

### `DecodoWebSearchTool`

搜索网络并返回一份规范化的结果文档，而不像 `DecodoSearchTool` 那样抓取特定引擎的结果页。

| 输入 | 默认值 | 说明 |
| - | - | - |
| `query` | – | 搜索查询。必填 |
| `geo` | – | 发送请求的国家/地区，使用全称，例如 `United States` |
| `locale` | – | 界面语言，例如 `en-US` |
| `page` | `1` | 返回的结果页码。必须大于或等于 1 |

返回一个 JSON 字符串。排序后的结果位于 `organic` 之下，每条包含标题、链接和描述；当搜索包含相应内容时，还会有 `top_stories`、`people_also_ask` 和 `related_searches`。若要读取某条结果，请用 `decodo_scrape_url` 抓取它的链接。

当 API 报告搜索失败时，会抛出 `RuntimeError: Decodo search failed: ...`。

### `DecodoMapTool`

列出网站上的 URL 而不获取其内容——适合在只抓取所需页面之前，先缩小大型网站的范围。

`DecodoMapTool` 和 `DecodoCrawlTool` 都从一个 URL 开始并由此发现页面，因此共用以下输入：

| 输入 | 默认值 | 说明 |
| - | - | - |
| `url` | – | 作为起点的网站绝对 http 或 https URL。必填 |
| `sitemap` | – | `include`、`only` 或 `skip`——在链接之外同时使用网站的站点地图、仅使用站点地图，或跳过站点地图 |
| `domain_filter` | – | `domain`、`subdomain` 或 `all`——哪些主机算作该网站的一部分 |
| `select_paths` | – | 与 URL 路径匹配的正则表达式。只保留匹配其中之一的 URL |
| `exclude_paths` | – | 与 URL 路径匹配的正则表达式。匹配其中之一的 URL 会被丢弃 |
| `geo` | – | 发送请求的国家/地区，使用全称 |
| `locale` | – | 界面语言，例如 `en-US` |

`DecodoMapTool` 另外增加：

| 输入 | 默认值 | 说明 |
| - | - | - |
| `limit` | `100` | 返回的 URL 数量上限。接受 1 到 500 |
| `js_render` | `False` | 设置为 `True` 时，使用 JavaScript 渲染页面以发现链接。速度较慢，仅在网站需要时才启用 |

```python theme={null}
from langchain_decodo import DecodoMapTool

tool = DecodoMapTool()
result = tool.invoke(
    {
        "url": "https://www.python.org",
        "select_paths": ["^/downloads/"],
        "limit": 50,
    }
)
```

以 JSON 字符串的形式返回 API 的站点地图响应。如果无法映射该网站——例如网站屏蔽了请求——该工具会抛出 `RuntimeError: Decodo map failed (status ...)`。

### `DecodoCrawlTool`

从起始 URL 爬取网站，并返回找到的每个页面的内容。除上述共用的站点发现输入外，还接受：

| 输入 | 默认值 | 说明 |
| - | - | - |
| `limit` | `10` | 爬取的页面数量上限。接受 1 到 100 |
| `max_depth` | – | 从起始 URL 开始跟踪链接的深度。接受 1 到 10000 |
| `output` | `markdown` | `markdown` 或 `html`——页面内容的格式 |

与其他工具不同，它还接受两个控制等待时长的构造函数参数：

| 构造函数参数 | 默认值 | 说明 |
| - | - | - |
| `poll_interval` | `5.0` | 两次状态检查之间的间隔秒数 |
| `timeout` | `600.0` | 放弃等待爬取完成前的等待秒数 |

```python theme={null}
from langchain_decodo import DecodoCrawlTool

tool = DecodoCrawlTool(timeout=300, poll_interval=5)
result = tool.invoke({"url": "https://example.com", "limit": 10, "max_depth": 2})
```

> [!TIP]
>
> 在大型网站上，请先用 `select_paths` 或 `exclude_paths` 缩小爬取范围，或者用 `DecodoMapTool` 列出 URL，然后只抓取您需要的页面。

#### 爬取行为

该工具会等待爬取完成，然后返回形如 `{"status": {...}, "pages": [...]}` 的 JSON 字符串。`status` 是爬取任务的状态响应，其中包含 `crawl_id`；`pages` 中的每个条目都是 API 返回的页面，带有各自的状态。

> [!WARNING]
>
> 以 `faulted` 或 `cancelled` 结束的爬取，以及 `timeout` 用尽时仍处于 `pending` 的爬取，都会返回已收集到的页面，而不会抛出异常。请检查结果中的 `status.status`：只要不是 `done`，就说明爬取提前停止，`pages` 中只有网站的一部分内容。

当无法读取状态时——例如爬取完全没有收集到页面——`status` 为 `null`。

`timeout` 还会作为爬取任务的 `max_duration` 发送给 API，并以 API 的四小时上限为限，因此 Decodo 会停止该工具已不再等待的爬取任务。`timeout` 用尽时仍在运行的爬取会以 `pending` 返回，并附带已收集的页面，Decodo 随后会在同一上限处停止它。若要更早停止，请将 `status.crawl_id` 传给 `DecodoCrawlCancelTool`。

### `DecodoCrawlCancelTool`

停止正在运行的爬取任务，使其不再爬取更多页面。

| 输入 | 默认值 | 说明 |
| - | - | - |
| `crawl_id` | – | 要停止的爬取任务 ID：来自 `decodo_crawl` 结果的 `status.crawl_id`。必填 |

```python theme={null}
import json

from langchain_decodo import DecodoCrawlCancelTool, DecodoCrawlTool

result = json.loads(DecodoCrawlTool(timeout=60).invoke({"url": "https://example.com"}))
status = result["status"]
if status and status["status"] == "pending":
    DecodoCrawlCancelTool().invoke({"crawl_id": status["crawl_id"]})
```

请将它与 `DecodoCrawlTool` 一同注册，让智能体能够停止自己已不再等待的爬取任务。任何不是爬取任务 ID 的值都会在发送请求之前抛出 `ValueError: Not a crawl id: ...`。

## 文档加载器

`DecodoLoader` 抓取一个或多个 URL，并将每个页面作为 LangChain `Document` 返回，可直接用于切分、嵌入并存入 RAG 流程：

```python theme={null}
from langchain_decodo import DecodoLoader

loader = DecodoLoader(
    urls=["https://quotes.toscrape.com", "https://books.toscrape.com"],
    auth_mode="token",
)

for doc in loader.lazy_load():
    print(doc.metadata["url"], doc.metadata["status_code"], len(doc.page_content))
```

每个 `Document` 都在 `page_content` 中以 Markdown 保存页面内容。其 `metadata` 包含 `source`、`url` 和 `status_code`；当 API 返回时，还会包含 `task_id`、`created_at` 和 `updated_at`。URL 会按顺序逐个抓取。使用 `load()` 获取包含全部文档的列表，或使用 `lazy_load()` 在文档到达时逐个处理。

| 参数 | 默认值 | 说明 |
| - | - | - |
| `urls` | – | 单个 URL 或 URL 列表。必填 |
| `api_token` | `DECODO_API_TOKEN` | API 密钥，或较旧计划的基本身份验证令牌 |
| `auth_mode` | `"basic"` | 使用 API 密钥时设置为 `"token"` |
| `timeout` | `180` | 每个 URL 的请求超时秒数 |
| `continue_on_error` | `True` | 某个 URL 失败时继续加载其余 URL |

启用 `continue_on_error` 时，失败的 URL 仍会生成一个 `Document`，其 `page_content` 为空，错误信息位于 `metadata["error"]`。请在嵌入之前将其过滤掉。若要在首次失败时抛出异常，请设置 `continue_on_error=False`。

## 错误处理

对于 API 错误、超时和网络故障，每个工具都会抛出 `RuntimeError`，消息前缀会说明出了什么问题，例如 `Decodo API error: ...` 或 `Decodo API network error: ...`。四个 Web Data API 工具在响应不是 JSON 时也会抛出该异常。

有两种情况会在发送请求之前抛出 `ValueError`：缺少 API 密钥，以及 `crawl_id` 不是有效的爬取任务 ID。

> [!NOTE]
>
> 四个 Web Data API 工具之一发生身份验证失败时，返回的错误会指出可能的原因——密钥无效、计划不包含该端点，或在只能使用 API 密钥的地方使用了基本身份验证令牌。

完整的 API 参数列表请参阅[**参数**](https://help.decodo.com/docs/web-scraping-api-parameters-overview.md)。

***

## 相关内容

* [**LangChain（TypeScript）**](https://help.decodo.com/docs/cn/langchain.md)：Node.js 版 LangChain 工具。
* [**MCP 服务器**](https://help.decodo.com/docs/cn/mcp.md)：将 AI 智能体和兼容 MCP 的工具连接到 Decodo。
* [**AI 集成**](https://help.decodo.com/docs/cn/ai-integrations.md)：Decodo 的全部 AI 集成。
* [GitHub 仓库](https://github.com/Decodo/langchain/tree/master/libs/partners/decodo)：查看源代码和最新版本。

***

> [card] [支持](https://direct.lc.chat/12092754)
>
> 需要帮助或只是想打个招呼？我们的支持团队全天候为您服务。 \
> 您也可以随时通过电子邮件 [support@decodo.com](mailto:support@decodo.com) 联系我们。

> [card] [反馈](mailto:feedback@decodo.com)
>
> 找不到您要找的内容？请求一篇文章！ \
> 有反馈意见？分享您对我们如何改进的想法。


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