【Python】联网搜索工具
·
方案一:使用 Tavily
Tavily 是专门为 Agent 设计的搜索引擎,国内访问速度极快,而且它返回的结果是清洗过的,非常适合 LLM 阅读。LangChain 对它的支持也是最好的。
优点: 速度快、结果精准、自带防屏蔽、有免费额度。
步骤:
去 Tavily 官网申请一个免费的 API Key。
安装库: pip install langchain-community tavily-python
替换代码:
import os
from langchain_community.tools import TavilySearchResults
# 设置环境变量
os.environ["TAVILY_API_KEY"] = "你的_TAVILY_API_KEY"
# 替换原来的 DuckDuckGoSearchRun
# max_results=1 限制只搜一条,防止它啰嗦
search_tool = TavilySearchResults(max_results=1)
方案二:使用 BingSearch(微软必应中国版)
如果你不想注册新服务,可以用必应。它在国内的搜索质量很高,且不需要复杂的代理。
优点: 大厂服务,稳定,国内直连。
步骤:
去 Azure Portal 或 Bing Search API 页面申请一个 Key(有免费额度)。
安装库: pip install langchain-community
替换代码:
import os
from langchain_community.tools import BingSearchResults
os.environ["BING_SEARCH_URL"] = "https://api.bing.microsoft.com/v7.0/search"
os.environ["BING_SUBSCRIPTION_KEY"] = "你的_BING_API_KEY"
# 替换工具
search_tool = BingSearchResults()
方案三:使用 SearxNG(完全免费,无需 API Key)
如果你不想申请任何 Key,可以部署一个开源的元搜索引擎 SearxNG,或者使用别人搭建的公共实例。
优点: 开源、隐私保护、聚合了百度/谷歌/必应等多个源。
代码:
from langchain_community.tools import SearxSearchWrapper
# 使用公共实例(不稳定),或者你自己部署的 http://localhost:8080
searx_tool = SearxSearchWrapper(
searx_host="https://searx.be",
engines=["baidu", "bing"] # 指定只用国内能用的引擎
)
import os
from langchain_community.tools import TavilySearchResults
from langchain.agents import tool
# 1. 配置 Tavily
os.environ["TAVILY_API_KEY"] = "你的_API_KEY"
# 2. 定义工具 (Tavily 默认就很稳,不需要复杂的 try-except)
@tool
def search_tool(query: str) -> str:
"""搜索国内互联网信息。"""
tavily = TavilySearchResults(max_results=1)
try:
result = tavily.run(query)
return result
except Exception as e:
# 即使 Tavily 挂了,也返回友好的提示
return f"搜索服务暂时不可用: {str(e)}"
# 3. 记得把原来的 DuckDuckGoSearchRun 删掉,用这个 search_tool
tools = [search_tool]
更多推荐



所有评论(0)