BiGuan/Agent
0
1"""2tools/visit_webpage.py —— 工具③:打开并阅读一个网页3 4上面的搜索工具只能给出"标题 + 简短摘要",信息量不够。这个工具负责"点进去看全文":5给它一个网址,它把那个网页的完整内容抓下来,转成干净的纯文字交给大模型阅读。6 7典型配合:先用 web_search 搜到一批结果 → 挑最相关的网址 → 用本工具打开它读详情。8"""9 10import re11 12from langchain_core.tools import tool13 14 15@tool16def visit_webpage(url: str) -> str:17 """Fetch a web page and return its content as markdown text. Use this to read a page18 found via `web_search` or a url given in the question."""19 import requests20 from markdownify import markdownify # 把网页的 HTML 代码转成清爽的 Markdown 文字21 22 # 访问网页。User-Agent 是伪装成普通浏览器的标识,否则有些网站会拒绝程序访问。23 try:24 response = requests.get(url, timeout=25, headers={"User-Agent": "Mozilla/5.0"})25 response.raise_for_status() # 访问失败(如 404)就报错26 except Exception as e:27 return f"Error fetching the webpage: {e}" # 出错时返回错误说明,而不是让程序崩溃28 29 # 把网页源代码转成纯文字,并去掉首尾空白。30 content = markdownify(response.text).strip()31 # 把连续 3 个以上的换行压缩成 2 个,让排版更紧凑、好读。32 content = re.sub(r"\n{3,}", "\n\n", content)33 # 同样地,网页太长就截断到 4 万字,避免内容过多。34 if len(content) > 40000:35 content = content[:40000] + "\n...[truncated]"36 return content37 