Skip to main content
Parallel 是一个专为 LLM 和 AI 应用设计的实时网页搜索与内容提取平台。
ParallelWebSearchTool 提供对 Parallel Search API 的访问,将传统的”搜索 → 抓取 → 提取”流程整合为单次 API 调用,返回结构化、针对 LLM 优化的结果。

概述

集成详情

可序列化JS 支持包最新版本
ParallelWebSearchToollangchain-parallelPyPI - Latest version

工具功能

  • 实时网页搜索:访问网络上的最新信息
  • 结构化结果:返回压缩的、针对 LLM 优化的摘要
  • 灵活输入:支持自然语言目标或具体搜索查询
  • 域名过滤:通过来源策略包含或排除特定域名
  • 可定制输出:控制结果数量(1-40 条)和摘要长度(最少 100 字符)
  • 丰富元数据:可选的搜索耗时、结果数量和查询信息
  • 异步支持:完整的 async/await 支持,配合合适的执行器
  • 错误处理:全面的错误处理,提供详细的错误信息

设置

该集成位于 langchain-parallel 包中。
pip install -qU langchain-parallel

凭据

前往 Parallel 注册并生成 API 密钥。完成后,设置 PARALLEL_API_KEY 环境变量:
import getpass
import os

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

实例化

下面展示如何实例化 ParallelWebSearchTool。该工具可通过 API 密钥和基础 URL 参数进行配置:
from langchain_parallel import ParallelWebSearchTool

# 基本实例化 - 从环境变量读取 API 密钥
tool = ParallelWebSearchTool()

# 使用显式 API 密钥和自定义基础 URL
tool = ParallelWebSearchTool(
    api_key="your-api-key",
    base_url="https://api.parallel.ai",  # 默认值
)

调用

直接使用参数调用

可以使用 objective(自然语言描述)或具体的 search_queries 来调用工具。工具支持多种配置选项,包括域名过滤和元数据收集:
# 使用具体搜索查询和高级选项
result = tool.invoke(
    {
        "search_queries": [
            "AI breakthroughs 2024",
            "machine learning advances",
            "generative AI news",
        ],
        "max_results": 8,
        "excerpts": {"max_chars_per_result": 2000},
        "mode": "one-shot",  # 使用 'agentic' 获得节省 token 的结果
        "source_policy": {
            "include_domains": ["arxiv.org", "nature.com"],
            "exclude_domains": ["reddit.com", "twitter.com"],
        },
        "fetch_policy": {
            "max_age_seconds": 86400,  # 缓存内容 1 天
            "timeout_seconds": 60,
        },
        "include_metadata": True,
        "timeout": 120,  # 自定义超时(秒)
    }
)

print(result)
# 使用目标(自然语言)并附带元数据
result = tool.invoke(
    {
        "objective": "What are the latest developments in artificial intelligence in 2024?",
        "max_results": 5,
        "include_metadata": True,  # 包含搜索耗时和统计信息
    }
)

print(result)

# 示例响应结构:
# {
#     "search_id": "search_abc123...",
#     "results": [
#         {
#             "url": "https://example.com/ai-news",
#             "title": "Latest AI Developments 2024",
#             "excerpts": [
#                 "Recent breakthrough in transformer architectures...",
#                 "New applications in computer vision..."
#             ]
#         }
#     ],
#     "search_metadata": {
#         "search_duration_seconds": 4.123,
#         "search_timestamp": "2024-01-15T10:30:00",
#         "max_results_requested": 5,
#         "actual_results_returned": 4,
#         "search_id": "search_abc123...",
#         "query_count": 1,
#         "source_policy_applied": false
#     }
# }

使用 ToolCall 调用

也可以使用模型生成的 ToolCall 来调用工具,此时会返回 ToolMessage
# 通常由模型生成,此处直接创建工具调用用于演示。
model_generated_tool_call = {
    "args": {
        "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)
print(result)
print(f"Tool name: {tool.name}")  # parallel_web_search
print(f"Tool description: {tool.description}")

异步使用

该工具支持完整的 async/await 操作,适用于异步应用以提升性能:
async def search_async():
    return await tool.ainvoke(
        {
            "objective": "Latest quantum computing breakthroughs",
            "max_results": 5,
            "include_metadata": True,
        }
    )


# 运行异步搜索
result = await search_async()
print(result)

参数详情与校验

工具会进行全面的输入校验,支持以下参数:

必填参数

至少需要提供以下之一:
  • objective:自然语言描述(最多 5000 字符)
  • search_queries:搜索查询列表(最多 5 条,每条最多 200 字符)

可选参数:

  • max_results:返回结果数量(1-40,默认:10)
  • excerpts:摘要设置字典(例如 {"max_chars_per_result": 1500}
  • mode:搜索模式 - ‘one-shot’ 获取全面结果,‘agentic’ 获取节省 token 的结果
  • source_policy:域名过滤,包含 include_domains 和/或 exclude_domains 列表
  • fetch_policy:缓存控制字典(例如 {"max_age_seconds": 86400, "timeout_seconds": 60}
  • include_metadata:包含搜索耗时和统计信息(默认:True)
  • timeout:请求超时(秒,可选)

错误处理:

工具为校验失败和 API 错误提供详细的错误信息。
# 全参数使用示例
result = tool.invoke(
    {
        "objective": "Find comprehensive information about renewable energy policies in European countries",
        "max_results": 15,
        "excerpts": {
            "max_chars_per_result": 2500
        },  # 更长的摘要以获取详细信息
        "mode": "one-shot",  # 全面结果
        "source_policy": {
            "include_domains": ["europa.eu", "iea.org", "irena.org"],
            "exclude_domains": ["wikipedia.org", "reddit.com"],
        },
        "fetch_policy": {
            "max_age_seconds": 86400,  # 1 天缓存
            "timeout_seconds": 90,
        },
        "include_metadata": True,
        "timeout": 180,  # 全面搜索使用更长超时
    }
)

# 访问结果和元数据
print(f"Found {len(result['results'])} results")
if "search_metadata" in result:
    metadata = result["search_metadata"]
    print(f"Search took {metadata['search_duration_seconds']}s")
    print(f"Source policy applied: {metadata.get('source_policy_applied', False)}")

链式调用

可以通过先将工具绑定到支持工具调用的模型,然后调用它,将工具集成到链中:
👉 Read the OpenAI chat model integration docs
pip install -U "langchain[openai]"
import os
from langchain.chat_models import init_chat_model

os.environ["OPENAI_API_KEY"] = "sk-..."

model = init_chat_model("gpt-5.2")
# | output: false
# | echo: false

# !pip install -qU langchain langchain-openai
from langchain.chat_models import init_chat_model

llm = init_chat_model(model="gpt-4.1", model_provider="openai")
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig, chain

prompt = ChatPromptTemplate(
    [
        ("system", "You are a helpful assistant."),
        ("human", "{user_input}"),
        ("placeholder", "{messages}"),
    ]
)

# 指定 tool_choice 会强制模型调用此工具。
llm_with_tools = llm.bind_tools([tool], tool_choice=tool.name)

llm_chain = prompt | llm_with_tools


@chain
def tool_chain(user_input: str, config: RunnableConfig):
    input_ = {"user_input": user_input}
    ai_msg = llm_chain.invoke(input_, config=config)
    tool_msgs = tool.batch(ai_msg.tool_calls, config=config)
    return llm_chain.invoke({**input_, "messages": [ai_msg, *tool_msgs]}, config=config)


tool_chain.invoke("What are the latest breakthrough discoveries in quantum computing?")

最佳实践

  • 使用具体目标:目标越具体,结果越精准
  • 应用域名过滤:使用 source_policy 聚焦权威来源或排除不可靠域名
  • 包含元数据:设置 include_metadata: True 以便调试和性能优化
  • 优雅处理错误:工具为校验和 API 失败提供详细的错误信息
  • 异步以提升性能:在异步应用中使用 ainvoke() 以获得更好的性能

响应格式

该工具返回结构化字典,格式如下:
{
    "search_id": "search_abc123...",  # 唯一搜索标识符
    "results": [  # 搜索结果列表
        {
            "url": "https://example.com/page",
            "title": "Page Title",
            "excerpts": [  # 相关文本摘要
                "First relevant excerpt...",
                "Second relevant excerpt..."
            ]
        }
    ],
    "search_metadata": {  # 可选元数据(当 include_metadata=True 时)
        "search_duration_seconds": 4.123,
        "search_timestamp": "2024-01-15T10:30:00",
        "max_results_requested": 10,
        "actual_results_returned": 8,
        "search_id": "search_abc123...",
        "query_count": 3,  # 使用的查询数量
        "queries_used": ["query1", "query2", "query3"],  # 如果提供了 search_queries
        "source_policy_applied": true,  # 如果使用了 source_policy
        "included_domains": ["nature.com"],  # 包含的域名
        "excluded_domains": ["reddit.com"]   # 排除的域名
    }
}

API 参考

关于所有功能和配置选项的详细文档,请参阅 ParallelWebSearchTool API 参考或 Parallel search 参考文档