You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LangChain.js的GoogleCustomSearch工具中指定语言参数?

如何在LangChain.js的GoogleCustomSearch工具中指定语言参数?

我之前也碰到过这个问题,确实官方文档这块说得有点模糊,不过有两种可行的解决办法,根据你的场景选就行:


方法一:初始化工具时固定语言(适合不需要动态切换语言的场景)

Google Custom Search API本身支持通过lr(language restrict)参数指定搜索语言,我们可以在创建GoogleCustomSearch实例的时候,通过searchOptions把这个参数传进去,这样所有的搜索请求都会默认用这个语言返回结果。

比如要固定为法语的话,代码可以这么写:

import { GoogleCustomSearch } from "@langchain/community/tools/google_custom_search";

// 初始化工具时指定默认语言为法语
const googleTool = new GoogleCustomSearch({
  apiKey: "你的Google API密钥",
  cseId: "你的自定义搜索引擎ID",
  searchOptions: {
    lr: "lang_fr" // 语言参数格式为lang_xx,比如lang_en是英语,lang_es是西班牙语
  }
});

const search = async (query: string) => {
  const results = JSON.parse(await googleTool.invoke(query));
  return results;
};

// 示例调用:返回法语的气候变化相关结果
const results = await search("climate change");

方法二:动态切换语言(适合需要根据请求调整语言的场景)

原工具的invoke方法只接受字符串查询,没办法直接传额外的语言参数,这时候我们可以自定义一个继承自GoogleCustomSearch的工具,重写它的_run方法,让它支持传入包含查询和语言的对象参数:

import { GoogleCustomSearch } from "@langchain/community/tools/google_custom_search";

// 自定义工具,支持动态传入语言参数
class CustomGoogleSearch extends GoogleCustomSearch {
  async _run(
    input: { query: string; language: string },
    _kwargs?: any
  ): Promise<string> {
    const { query, language } = input;
    // 构建Google API要求的语言参数格式
    const lrParam = `lang_${language}`;
    
    // 调用Google Custom Search API,传入语言参数
    const res = await this.google.customsearch.cse.list({
      q: query,
      cx: this.cseId,
      auth: this.apiKey,
      lr: lrParam,
      ...this.searchOptions,
    });

    return JSON.stringify(res.data.items || []);
  }
}

// 初始化自定义工具
const googleTool = new CustomGoogleSearch({
  apiKey: "你的Google API密钥",
  cseId: "你的自定义搜索引擎ID",
});

const search = async (query: string, language: string) => {
  // 传入包含查询内容和语言的对象
  const results = JSON.parse(await googleTool.invoke({ query, language }));
  return results;
};

// 示例调用:动态指定法语返回结果
const results = await search("climate change", "fr");

另外补充一下:你之前尝试在查询字符串里加lang:fr没用,是因为那是普通Google网页搜索的语法,但Google Custom Search API并不支持这种写法,必须用官方API提供的lr参数来指定语言才行。你可以根据需要的语言,替换对应的lang_xx后缀,比如德语是lang_de,日语是lang_ja等等。

备注:内容来源于stack exchange,提问作者Satsuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 11:34:35