Node.js中LangChain+Ollama集成DuckDuckGo工具时出现空值读取错误
问题解决:LangChain DuckDuckGoSearch 抛出 TypeError: Cannot read properties of null (reading '1')
问题描述
使用 Node.js 基于 LangChain 和 Ollama 开发智能 Agent 时,调用 DuckDuckGo 搜索工具持续触发以下错误:
DuckDuckGo search error: TypeError: Cannot read properties of null (reading '1')
尝试两种 DuckDuckGo 工具创建方式(直接实例化DuckDuckGoSearch、通过DynamicStructuredTool封装)均失败,但改用 Google 搜索工具可正常返回结果。
可能原因
该错误源于 LangChain 内置DuckDuckGoSearch工具的网页解析逻辑缺陷:工具依赖正则表达式匹配 DuckDuckGo 搜索结果页面的特定结构,当页面结构更新、网络请求返回异常内容时,正则匹配结果为null,后续代码尝试读取其索引1就会触发报错。
解决方案
1. 升级 LangChain 相关依赖
优先升级@langchain/community包(DuckDuckGoSearch所属包)至最新版本,开发者通常会及时适配页面结构变化:
npm update @langchain/community @langchain/core langchain
2. 自定义 DuckDuckGo 搜索实现(绕过内置工具的解析问题)
如果升级后问题仍存在,可直接调用 DuckDuckGo 官方 Instant Answer API 实现搜索,避免依赖网页解析:
import { DynamicStructuredTool } from "@langchain/core/tools"; import z from "zod"; export const duckDuckGoSearchTool = new DynamicStructuredTool({ name: "duckduckgo-search", description: "使用 DuckDuckGo 搜索网络信息,适用于查找最新资讯、事实类内容或知识库中不存在的数据。", schema: z.object({ query: z.string().describe("要在 DuckDuckGo 上搜索的查询词"), }), func: async ({ query }) => { try { // 调用 DuckDuckGo Instant Answer API const response = await fetch(`https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`); const data = await response.json(); // 整理返回结果 const results = []; if (data.AbstractText) results.push(`摘要: ${data.AbstractText}`); if (data.RelatedTopics && data.RelatedTopics.length > 0) { data.RelatedTopics.forEach((topic: any) => { if (topic.Text) results.push(`相关内容: ${topic.Text}`); }); } if (results.length === 0) return "未找到相关搜索结果。"; return results.join("\n"); } catch (error) { console.error("DuckDuckGo 搜索错误:", error); return "搜索过程中发生错误,服务可能暂时不可用。"; } }, });
3. 临时修复内置工具的正则逻辑(不推荐)
若必须使用内置DuckDuckGoSearch,可修改其内部代码添加 null 检查,但需注意依赖更新会覆盖此修改:
找到@langchain/community/tools/duckduckgo_search文件,将原正则匹配代码:
const match = html.match(/<div class="results">(.*?)<\/div>/s)[1];
修改为:
const match = html.match(/<div class="results">(.*?)<\/div>/s); if (!match) return []; const content = match[1];
验证
替换工具实现后,重新运行 Agent 并测试搜索功能,确认错误是否消除。
内容的提问来源于stack exchange,提问作者Melih Sahtiyan
相关产品推荐
相关产品推荐

