OpenClaw Web 工具深度实战:web_search 与 web_fetch 的配置、原理与安全边界

原创2026-10-15 09:32:32368 阅读
文章标签:人工智能大模型AI 应用后端LLM 网关即时通讯AI Agent插件系统本地部署MCP Clients

OpenClaw Web 工具深度实战:web_search 与 web_fetch 的配置、原理与安全边界

本篇围绕 OpenClaw 内置的两个轻量级 Web 工具 web_search 与 web_fetch 展开,覆盖搜索提供商选择(Brave Search / Perplexity Sonar)、API 密钥配置、完整参数说明与内容提取流水线。读完本文,你将能够独立完成 Web 搜索/抓取工具的启用与调优,理解其缓存、超时、SSRF 防护等底层机制,并结合仓库源码定位每一个配置项的实际生效位置。

工作原理

OpenClaw 提供两个轻量级 Web 工具:

  • web_search — 通过 Brave Search API(默认)或 Perplexity Sonar(直连或通过 OpenRouter)搜索网络。
  • web_fetch — HTTP 获取 + 可读性提取(HTML → markdown/文本)。

这些不是浏览器自动化。对于 JS 密集型网站或需要登录的情况,请使用浏览器工具。

从源码结构看,两者是职责不同的独立工具:

  • web_search 调用你配置的提供商并返回结果:
    • Brave(默认):返回结构化结果(标题、URL、摘要)。
    • Perplexity:返回带有实时网络搜索引用的 AI 综合答案。
  • 结果按查询缓存 15 分钟(可配置)。缓存常量定义在 web-shared.ts:DEFAULT_TIMEOUT_SECONDS = 30、DEFAULT_CACHE_TTL_MINUTES = 15,内存缓存最多保留 100 条(DEFAULT_CACHE_MAX_ENTRIES,见 web-shared.ts)。
  • web_fetch 执行普通 HTTP GET 并提取可读内容(HTML → markdown/文本)。它不执行 JavaScript。
  • web_fetch 默认启用(除非显式禁用),见 web-fetch.ts 中 resolveFetchEnabled 的默认值逻辑:未配置时返回 true。

选择搜索提供商

提供商 优点 缺点 API 密钥
Brave(默认) 快速、结构化结果、免费层 传统搜索结果 BRAVE_API_KEY
Perplexity AI 综合答案、引用、实时 需要 Perplexity 或 OpenRouter 访问 OPENROUTER_API_KEY 或 PERPLEXITY_API_KEY

参见 Brave Search 设置 和 Perplexity Sonar 了解提供商特定详情。

在配置中设置提供商:

{
  tools: {
    web: {
      search: {
        provider: "brave", // 或 "perplexity"
      },
    },
  },
}

示例:切换到 Perplexity Sonar(直连 API):

{
  tools: {
    web: {
      search: {
        provider: "perplexity",
        perplexity: {
          apiKey: "pplx-...",
          baseUrl: "https://api.perplexity.ai",
          model: "perplexity/sonar-pro",
        },
      },
    },
  },
}

从源码结构看,两个提供商都是注册进核心插件体系的 WebSearchProviderPlugin:Brave 实现位于 brave-web-search-provider.ts(autoDetectOrder: 10,凭证路径 plugins.entries.brave.config.webSearch.apiKey),Perplexity 实现位于 perplexity-web-search-provider.ts(autoDetectOrder: 50,支持 PERPLEXITY_API_KEY 与 OPENROUTER_API_KEY 两个环境变量)。自动检测顺序解释了为什么 Brave 默认优先。

获取 Brave API 密钥

  1. 在 Brave Search API 门户(https://brave.com/search/api/)创建 Brave Search API 账户
  2. 在控制面板中,选择 Data for Search 计划(不是"Data for AI")并生成 API 密钥。
  3. 运行 openclaw configure --section web 将密钥存储在配置中(推荐),或在环境中设置 BRAVE_API_KEY。

Brave 提供免费层和付费计划;查看 Brave API 门户了解当前限制和定价。

在哪里设置密钥(推荐)

推荐: 运行 openclaw configure --section web。它将密钥存储在 ~/.openclaw/openclaw.json 的 tools.web.search.apiKey 下。交互式向导在 configure.wizard.ts 中处理 tools.web.search / tools.web.fetch 两个分支。

环境变量替代方案: 在 Gateway 进程环境中设置 BRAVE_API_KEY。对于 Gateway 安装,将其放在 ~/.openclaw/.env(或你的服务环境)中。参见环境变量。

密钥解析优先级在源码中可以直接确认:brave-web-search-provider.ts 中 resolveBraveApiKey 先读 tools.web.search.apiKey(支持 SecretRef),读不到再回退到 BRAVE_API_KEY 环境变量。

缺密钥时的行为:web_search 不会崩溃,而是返回结构化的设置提示(missing_brave_api_key 错误 + 建议运行 openclaw configure --section web),见 brave-web-search-provider.ts。

web_search

使用配置的提供商搜索网络。

要求

  • tools.web.search.enabled 不能为 false(默认:启用)
  • 所选提供商的 API 密钥:
    • Brave:BRAVE_API_KEY 或 tools.web.search.apiKey
    • Perplexity:OPENROUTER_API_KEY、PERPLEXITY_API_KEY 或 tools.web.search.perplexity.apiKey

配置

{
  tools: {
    web: {
      search: {
        enabled: true,
        apiKey: "BRAVE_API_KEY_HERE", // 如果设置了 BRAVE_API_KEY 则可选
        maxResults: 5,
        timeoutSeconds: 30,
        cacheTtlMinutes: 15,
      },
    },
  },
}

这些字段的完整定义见 types.tools.ts:enabled、provider、apiKey(SecretInput)、maxResults(1–10)、timeoutSeconds、cacheTtlMinutes。默认值在 web-search-provider-common.ts 中确认:DEFAULT_SEARCH_COUNT = 5、MAX_SEARCH_COUNT = 10。

工具参数

  • query(必需)
  • count(1–10;默认来自配置,缺省为 5)
  • country(可选):用于特定地区结果的 2 字母国家代码(例如"DE"、"US"、"ALL")。如果省略,Brave 选择其默认地区。
  • search_lang(可选):搜索结果的 ISO 语言代码(例如"de"、"en"、"fr")
  • ui_lang(可选):UI 元素的 ISO 语言代码
  • freshness(可选,仅限 Brave):按发现时间过滤(pd、pw、pm、py 或 YYYY-MM-DDtoYYYY-MM-DD)

示例:

// 德国特定搜索
await web_search({
  query: "TV online schauen",
  count: 10,
  country: "DE",
  search_lang: "de",
});

// 带法语 UI 的法语搜索
await web_search({
  query: "actualités",
  country: "FR",
  search_lang: "fr",
  ui_lang: "fr",
});

// 最近结果(过去一周)
await web_search({
  query: "TMBG interview",
  freshness: "pw",
});

Brave 提供商的参数归一化(源码佐证)

从源码结构看,Brave 工具对参数做了较严格的防御性归一化(brave-web-search-provider.ts):

  • country 白名单:内置 39 个国家/地区代码集合(含 ALL),传入未知代码时折叠为 ALL,而不是直接报错,见 normalizeBraveCountry。
  • 语言别名:search_lang 支持别名映射,如 ja → jp、zh → zh-hans、zh-tw → zh-hant(BRAVE_SEARCH_LANG_ALIASES);不在支持列表内的值返回 invalid_search_lang 错误。
  • ui_lang 校验:必须是 语言-地区 形式的区域子标签(如 en-US),见 normalizeBraveUiLang。若把语言码和 UI 码传反了,源码会自动检测并交换(normalizeBraveLanguageParams)。
  • freshness 与日期范围互斥:freshness 支持 day/week/month/year(源码会自动归一化为 Brave 可识别的形式);精确日期区间通过 date_after / date_before(YYYY-MM-DD)表达,二者不能同时使用,否则返回 conflicting_time_filters 错误。
  • llm-context 模式:除常规 web 模式外,Brave 还支持 brave.mode: "llm-context",调用 https://api.search.brave.com/res/v1/llm/context 端点,返回预提取的页面内容分片(text chunks、表格、代码块),更利于 LLM 直接做 grounding;该模式下不支持 ui_lang、freshness、日期过滤,见 brave-web-search-provider.ts。
  • 所有请求经 withTrustedWebSearchEndpoint 发起,携带 X-Subscription-Token 请求头与超时控制;结果字段(title/description)经 wrapWebContent 包裹为不可信外部内容标记,防止提示注入类风险。

相关行为有测试覆盖:brave-web-search-provider.test.ts。

使用 Perplexity(直连或通过 OpenRouter)

Perplexity Sonar 模型具有内置的网络搜索功能,并返回带有引用的 AI 综合答案。你可以通过 OpenRouter 使用它们(无需信用卡 - 支持加密货币/预付费)。

获取 OpenRouter API 密钥

  1. 在 OpenRouter 站点(https://openrouter.ai/)创建账户
  2. 添加额度(支持加密货币、预付费或信用卡)
  3. 在账户设置中生成 API 密钥

设置 Perplexity 搜索

{
  tools: {
    web: {
      search: {
        enabled: true,
        provider: "perplexity",
        perplexity: {
          // API 密钥(如果设置了 OPENROUTER_API_KEY 或 PERPLEXITY_API_KEY 则可选)
          apiKey: "sk-or-v1-...",
          // 基础 URL(如果省略则根据密钥感知默认值)
          baseUrl: "https://openrouter.ai/api/v1",
          // 模型(默认为 perplexity/sonar-pro)
          model: "perplexity/sonar-pro",
        },
      },
    },
  },
}

环境变量替代方案: 在 Gateway 环境中设置 OPENROUTER_API_KEY 或 PERPLEXITY_API_KEY。对于 Gateway 安装,将其放在 ~/.openclaw/.env 中。密钥解析优先级(见 perplexity-web-search-provider.ts):tools.web.search.perplexity.apiKey → PERPLEXITY_API_KEY → OPENROUTER_API_KEY。

如果未设置基础 URL,OpenClaw 会根据 API 密钥来源选择默认值:

  • PERPLEXITY_API_KEY 或 pplx-... → https://api.perplexity.ai
  • OPENROUTER_API_KEY 或 sk-or-... → https://openrouter.ai/api/v1
  • 未知密钥格式 → OpenRouter(安全回退)

这一规则在源码中可直接验证:resolvePerplexityBaseUrl 按凭证来源选择端点,密钥前缀推断函数 inferPerplexityBaseUrlFromApiKey 识别 pplx- 前缀为直连、sk-or- 前缀为 OpenRouter,见 perplexity-web-search-provider.ts。

可用的 Perplexity 模型

模型 描述 最适合
perplexity/sonar 带网络搜索的快速问答 快速查询
perplexity/sonar-pro(默认) 带网络搜索的多步推理 复杂问题
perplexity/sonar-reasoning-pro 思维链分析 深度研究

双传输机制:Search API 与 Chat Completions(源码解析)

从源码结构看,Perplexity 提供商内部存在两条传输路径(PerplexityTransport = "search_api" | "chat_completions",见 perplexity-web-search-provider.ts):

  • 原生 Search API 路径(https://api.perplexity.ai/search,POST):当走直连 api.perplexity.ai 且没有手动覆盖 baseUrl/model 时启用,支持结构化过滤参数——country、language、date_after/date_before、domain_filter(最多 20 个域名,allowlist 与 denylist 不能混用,denylist 条目以 - 前缀)、max_tokens、max_tokens_per_page。
  • Chat Completions 路径({baseUrl}/chat/completions):当使用 OpenRouter 或显式配置了 baseUrl/model 时启用,通过 Sonar 模型做 AI 综合问答,引用从响应的 citations 或 message.annotations(url_citation 类型)中提取,见 extractPerplexityCitations。在该路径下传入 country、language、domain_filter 等结构化过滤参数会返回明确的 unsupported_* 错误,提示改用直连 Perplexity 密钥。
  • 一个细节值得注意:直连模式下,模型名会自动剥离 perplexity/ 前缀再发送(resolvePerplexityRequestModel),因此配置中写 perplexity/sonar-pro 在两条路径下都正确。
  • 缓存键包含 transport、baseUrl、model 与全部过滤参数(buildSearchCacheKey),确保不同模型/端点的结果不会串用缓存。

相关测试:perplexity-web-search-provider.test.ts。

web_fetch

获取 URL 并提取可读内容。

要求

  • tools.web.fetch.enabled 不能为 false(默认:启用)
  • 可选的 Firecrawl 回退:设置 tools.web.fetch.firecrawl.apiKey 或 FIRECRAWL_API_KEY

配置

{
  tools: {
    web: {
      fetch: {
        enabled: true,
        maxChars: 50000,
        timeoutSeconds: 30,
        cacheTtlMinutes: 15,
        maxRedirects: 3,
        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        readability: true,
        firecrawl: {
          enabled: true,
          apiKey: "FIRECRAWL_API_KEY_HERE", // 如果设置了 FIRECRAWL_API_KEY 则可选
          baseUrl: "https://api.firecrawl.dev",
          onlyMainContent: true,
          maxAgeMs: 86400000, // 毫秒(1 天)
          timeoutSeconds: 60,
        },
      },
    },
  },
}

完整的字段定义(含 maxCharsCap、maxResponseBytes 等文档未展开的项)见 types.tools.ts。从源码常量可以确认的默认值(web-fetch.ts):

配置项 默认值 说明
maxChars 50000 返回内容最大字符数,工具参数可临时覆盖(最小 100)
maxResponseBytes 2000000(2 MB) 响应体下载上限,合法区间 32 KB ~ 10 MB,超出部分截断并给出 warning
maxRedirects 3 最多跟随的重定向次数
timeoutSeconds 30 请求超时
cacheTtlMinutes 15 抓取结果缓存 TTL
userAgent 类 Chrome UA 默认发送 Mozilla/5.0 (Macintosh; ...) Chrome/122.0.0.0,并附带 Accept-Language: en-US,en;q=0.9
readability true 是否启用 Readability 主内容提取
firecrawl.maxAgeMs 172800000(2 天) Firecrawl 缓存内容最大年龄
firecrawl.onlyMainContent true Firecrawl 是否只保留主内容

工具参数

  • url(必需,仅限 http/https)
  • extractMode(markdown | text,默认 markdown)
  • maxChars(截断长页面)

内容提取流水线(源码解析)

实现位于 web-fetch.ts。web_fetch 首先使用 Readability(主要内容提取),然后使用 Firecrawl(如果已配置)。如果两者都失败,工具返回错误。从源码结构看,实际是一条带回退的四级流水线(按 Content-Type 分支):

  1. cf-markdown:如果响应 Content-Type 已是 text/markdown(如 Cloudflare 对 Agent 的预渲染 markdown),直接使用,不再做 HTML 处理。
  2. readability:对 text/html 响应运行主内容提取(extractReadableContent,实现见 web-fetch-utils.ts)。
  3. firecrawl:Readability 无产出时,若配置了 Firecrawl,则调用其 /v2/scrape 端点抓取(proxy: "auto"、storeInCache: true,即文档中提到的机器人规避模式与服务端缓存)。另外,当直连请求本身失败(网络异常或非 2xx)时,也会优先尝试 Firecrawl 回退(maybeFetchFirecrawlWebFetchPayload)。
  4. raw-html:基础 HTML 清理(extractBasicHtmlContent)作为最后一级兜底;仍无内容则抛出"Readability, Firecrawl, and basic HTML cleanup returned no content"错误。

对 application/json 响应则美化后原样返回(extractor: "json")。

响应载荷结构包含 url、finalUrl、status、contentType、title、extractor、truncated、rawLength/wrappedLength、fetchedAt、tookMs、text 与 warning;内容被标记为 externalContent: { untrusted: true, wrapped: true },即包裹为不可信外部内容再交给模型。

安全边界与缓存

注意:

  • web_fetch 默认发送类 Chrome 的 User-Agent 和 Accept-Language;如需要可覆盖 userAgent。
  • web_fetch 阻止私有/内部主机名并重新检查重定向(用 maxRedirects 限制)。源码中该行为由 fetchWithWebToolsNetworkGuard 的严格 SSRF 模式实现(web-guarded-fetch.ts,底层为 fetchWithSsrFGuard + withStrictGuardedFetchMode),重定向后的目标地址同样会复检,防止通过 302 跳转到内网地址;SSRF 行为有专门测试 web-fetch.ssrf.test.ts。
  • web_fetch 是尽力提取;某些网站需要浏览器工具。
  • 参见 Firecrawl 了解密钥设置和服务详情。
  • 响应会被缓存(默认 15 分钟)以减少重复获取。缓存键为 fetch:{url}:{extractMode}:{maxChars} 的小写归一化形式,命中缓存的响应带 cached: true 标记。
  • 如果你使用工具配置文件/允许列表,添加 web_search/web_fetch 或 group:web。
  • 如果缺少 Brave 密钥,web_search 返回一个简短的设置提示和文档链接。

常见排查与验证建议

  • 搜索无结果/报缺密钥:确认密钥位置(tools.web.search.apiKey 或对应环境变量),或运行 openclaw configure --section web 交互式补全;错误载荷中的 docs 字段会指向本文档。
  • Brave 语言/地区参数不生效:检查是否使用了支持列表内的代码(见上文白名单与别名表);未知 country 会静默退化为 ALL,未知 search_lang 则返回 invalid_search_lang 错误。
  • Perplexity 结构化过滤报错:若配置了 baseUrl/model 覆盖(走 Chat Completions 路径),country、domain_filter 等参数不可用,按错误提示移除覆盖或改用直连 Perplexity 密钥。
  • 抓取被截断:返回载荷中的 truncated、rawLength、warning 字段可以区分是字符数截断(maxChars)还是响应体截断(maxResponseBytes),按需调整配置。
  • 验证提取行为:仓库中 web-tools.fetch.test.ts、web-tools.readability.test.ts 覆盖了抓取与 Readability 路径的测试用例,可作为行为的参照实现。
登录后查看全文
openclaw-zero-token