| """ |
| 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 |
|
|
| |
| try: |
| response = requests.get(url, timeout=25, headers={"User-Agent": "Mozilla/5.0"}) |
| response.raise_for_status() |
| except Exception as e: |
| return f"Error fetching the webpage: {e}" |
|
|
| |
| content = markdownify(response.text).strip() |
| |
| content = re.sub(r"\n{3,}", "\n\n", content) |
| |
| if len(content) > 40000: |
| content = content[:40000] + "\n...[truncated]" |
| return content |
|
|