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

# 并行搜索集成

> 使用 LangChain Python 与 ParallelSearchTool 工具集成。

> [Parallel](https://platform.parallel.ai/) 是一个为 LLM 和 AI 应用构建的实时网络搜索和内容提取平台。

`ParallelSearchTool` 调用 Parallel 的 [Search API](https://docs.parallel.ai/search/search-quickstart)，该 API 将传统的搜索 → 抓取 → 提取流程合并为一次调用，并返回结构化的、针对 LLM 优化的摘要。

<Note>
  `ParallelSearchTool` 是规范的类名。早期的 `ParallelWebSearchTool` 仍可作为同一类的别名使用。需要一个可直接放入 RAG 链的 `BaseRetriever`？请参阅 [ParallelSearchRetriever](/oss/python/integrations/retrievers/parallel)。
</Note>

## 概述

### 集成详情

| 类                                                                                                                | 包                                                                                  | 可序列化 | JS 支持 |                                                                                                                        包最新版本                                                                                                                       |
| :--------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | :--: | :---: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| [`ParallelSearchTool`](https://reference.langchain.com/python/langchain-parallel/search_tool/ParallelSearchTool) | [`langchain-parallel`](https://reference.langchain.com/python/langchain-parallel/) |   ❌  |   ❌   | <a href="https://pypi.org/project/langchain-parallel/" target="_blank"><img src="https://img.shields.io/pypi/v/langchain-parallel?style=flat-square&label=%20&color=orange" alt="PyPI - Latest version" noZoom height="100" class="rounded" /></a> |

## 设置

该集成位于 `langchain-parallel` 包中。

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langchain-parallel
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langchain-parallel
  ```
</CodeGroup>

### 凭证

前往 [Parallel](https://platform.parallel.ai) 注册并生成 API 密钥。在您的环境中设置 `PARALLEL_API_KEY`：

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

if not os.environ.get("PARALLEL_API_KEY"):
    os.environ["PARALLEL_API_KEY"] = getpass.getpass("Parallel API key:\n")
```

## 实例化

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

tool = ParallelSearchTool()

# 或者传递显式密钥 / 覆盖基础 URL：
# tool = ParallelSearchTool(
#     api_key="your-api-key",
#     base_url="https://api.parallel.ai",  # 默认值
# )
```

## 调用

### 使用参数直接调用

该工具需要 `search_queries`（一个或多个关键词字符串）。可将其与 `objective` 配对以获得更丰富的相关性排序，并根据需要添加域名过滤、获取策略和其他设置。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
result = tool.invoke(
    {
        "search_queries": [
            "AI breakthroughs 2026",
            "machine learning advances",
            "generative AI news",
        ],
        "objective": "What are the latest developments in AI?",
        "max_results": 8,
        "excerpts": {"max_chars_per_result": 2000},
        "mode": "advanced",
        "source_policy": {
            "include_domains": ["arxiv.org", "nature.com"],
            "exclude_domains": ["reddit.com", "twitter.com"],
        },
        "fetch_policy": {
            "max_age_seconds": 86400,
            "timeout_seconds": 60,
        },
        "include_metadata": True,
    }
)

print(f"Found {len(result['results'])} results")
for r in result["results"][:3]:
    print(r["title"], "—", r["url"])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Found 8 results
Latest AI Developments 2026 — https://arxiv.org/abs/...
...
```

`mode="basic"` 是延迟较低的设置；`mode="advanced"` 运行更高质量的搜索。

### 使用 ToolCall 调用

使用模型生成的 `ToolCall` 调用会返回一个 `ToolMessage`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
model_generated_tool_call = {
    "args": {
        "search_queries": [
            "climate change initiatives",
            "global climate policy 2026",
        ],
        "objective": "Find recent news about climate change initiatives",
        "max_results": 3,
        "source_policy": {
            "include_domains": ["ipcc.ch", "unfccc.int", "nature.com"],
        },
        "include_metadata": True,
    },
    "id": "call_123",
    "name": tool.name,  # "parallel_web_search"
    "type": "tool_call",
}

result = tool.invoke(model_generated_tool_call)
```

### 异步用法

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
async def search_async():
    return await tool.ainvoke(
        {
            "search_queries": ["quantum computing breakthroughs"],
            "objective": "Latest quantum computing breakthroughs",
            "max_results": 5,
        }
    )

result = await search_async()
```

### 参数

#### 必需

* `search_queries`：关键词字符串列表（每个 3-6 个词效果最佳）。

#### 可选

* `objective`：检索目标的自然语言描述。
* `max_results`：返回的结果数量（默认 10）。
* `excerpts`：每个结果的摘要设置，例如 `{"max_chars_per_result": 1500}`。
* `mode`：`"basic"`（延迟较低）或 `"advanced"`（质量更高）。
* `source_policy`：域名过滤。接受 `SourcePolicy` pydantic 模型或包含 `include_domains` / `exclude_domains` / `after_date` 的原始字典。
* `fetch_policy`：缓存控制，例如 `{"max_age_seconds": 86400, "timeout_seconds": 60}`。
* `max_chars_total`：所有结果组合摘要长度的上限。
* `client_model` / `session_id` / `location`：转发给 Parallel 用于下游归因和个性化。
* `include_metadata`：在响应中包含客户端计时信息（默认 `True`）。
* `timeout`：每个请求的超时时间（秒）。

### SourcePolicy pydantic 模型

[`SourcePolicy`](https://reference.langchain.com/python/langchain-parallel/_types/SourcePolicy) 映射了 API 的 `include_domains` / `exclude_domains` / `after_date`。使用它可获得类型安全；也接受原始字典。

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

result = tool.invoke({
    "search_queries": ["renewable energy policy Europe"],
    "source_policy": SourcePolicy(
        include_domains=["europa.eu", "iea.org", "irena.org"],
        exclude_domains=["wikipedia.org", "reddit.com"],
    ),
    "max_results": 15,
})
```

## 链式调用

将该工具绑定到任何支持工具调用的聊天模型，并使用 [`create_agent`](/oss/python/langchain/agents) 驱动代理：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model

llm = init_chat_model(model="claude-opus-4-7")
agent = create_agent(model=llm, tools=[tool])

agent.invoke({"messages": [("human", "What are the latest breakthroughs in quantum computing?")]})
```

<Note>
  `ChatParallel` 本身不支持工具调用。请将其用作链中的研究助手，或与其他支持工具调用的模型一起使用 Parallel 搜索/提取工具。
</Note>

## 响应格式

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
    "search_id": "search_abc123...",
    "session_id": "sess_...",
    "results": [
        {
            "url": "https://example.com/page",
            "title": "Page Title",
            "publish_date": "2026-04-01",
            "excerpts": [
                "First relevant excerpt...",
                "Second relevant excerpt...",
            ],
        },
    ],
    "warnings": [...],
    "usage": {...},
    "search_metadata": {  # 当 include_metadata=True（默认）时由本工具添加
        "search_duration_seconds": 2.451,
        "search_timestamp": "2026-04-15T10:30:00",
        "actual_results_returned": 5,
    },
}
```

## API 参考

详细文档请访问 [`ParallelSearchTool`](https://reference.langchain.com/python/langchain-parallel/search_tool/ParallelSearchTool) API 参考或 [Parallel Search 参考](https://docs.parallel.ai/api-reference/search/search)。

***

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

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