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