feat(crawl4ai): configurable web_fetch output cap and a truncation note (#8553)

* feat(crawl4ai): configurable web_fetch output cap and a truncation note

Crawl4AI web_fetch cut pages to a hard-coded 4096 characters without saying so.
An optional max_chars tool setting (positive integer, default 4096) sets the
cap; invalid values keep the default with a warning. A cut page ends with
'[web_fetch: truncated to the first N of M characters]'.

Refs #8552

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): crawl4ai web_fetch max_chars

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(crawl4ai): fall back when max_chars cannot be parsed

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
Bas Cancrinus 2026-11-24 14:13:14 +01:00 committed by GitHub
parent efc98f1164
commit b5e19e03a0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 68 additions and 8 deletions

View File

@ -11,6 +11,10 @@ This section accumulates work toward the **2.3.0** milestone
([2.3.0](https://github.com/bytedance/deer-flow/milestone/4)).
### Added
- **crawl4ai:** `web_fetch` accepts an optional `max_chars` output cap (default
4096). A page cut at the cap ends with a note giving the kept and total
length. ([#8553](https://github.com/bytedance/deer-flow/pull/8553))
- **summarization:** The built-in compaction prompt guides the summarizer to
preserve active user requirements, literal approval phrases, action conditions,
and explicit revisions. Explicit `summarization.summary_prompt` configurations

View File

@ -14,6 +14,7 @@ logger = logging.getLogger(__name__)
DEFAULT_BASE_URL = "http://localhost:11235"
DEFAULT_TIMEOUT_S = 30
DEFAULT_FILTER = "fit"
DEFAULT_MAX_CHARS = 4096
VALID_FILTERS = ("fit", "raw", "bm25", "llm")
@ -45,6 +46,31 @@ def _coerce_timeout(value: object, default: int) -> float:
return float(default)
def _coerce_max_chars(value: object) -> int:
"""Coerce the ``max_chars`` output cap; anything but a positive integer keeps the default."""
if value is None:
return DEFAULT_MAX_CHARS
max_chars = value
if isinstance(value, str) and (digits := value.strip()).isdecimal():
try:
max_chars = int(digits)
except ValueError:
max_chars = None # Python can reject an integer string that exceeds its digit limit.
if isinstance(max_chars, int) and not isinstance(max_chars, bool) and max_chars > 0:
return max_chars
logger.warning("Crawl4AI web_fetch: invalid max_chars %r in config; using %s", value, DEFAULT_MAX_CHARS)
return DEFAULT_MAX_CHARS
def _truncate(markdown: str, max_chars: int) -> str:
"""Cut to ``max_chars`` and say so, so the model knows the page goes on."""
if len(markdown) <= max_chars:
return markdown
return f"{markdown[:max_chars]}\n\n[web_fetch: truncated to the first {max_chars} of {len(markdown)} characters]"
def _coerce_bool(value: object, default: bool) -> bool:
if isinstance(value, bool):
return value
@ -135,7 +161,7 @@ async def web_fetch_tool(url: str) -> str:
if markdown.startswith("Error:"):
return markdown
return markdown[:4096]
return _truncate(markdown, _coerce_max_chars(cfg.get("max_chars") if cfg is not None else None))
except Exception as e:
logger.error(f"Error in web_fetch_tool: {e}")

View File

@ -2,8 +2,10 @@
import ipaddress
import json
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import httpx
import pytest
from deerflow.community.crawl4ai.crawl4ai_client import Crawl4AiClient
@ -259,19 +261,43 @@ class TestCrawl4AiTools:
assert result == "# Title\n\nContent"
assert "Error:" not in result
@patch("deerflow.community.crawl4ai.tools._build_client")
@pytest.mark.parametrize(
("cfg", "length", "kept"),
[
(None, 5000, 4096), # default cap
({"max_chars": 8000}, 9000, 8000),
({"max_chars": "8000"}, 9000, 8000),
({"max_chars": 0}, 5000, 4096), # invalid values keep the default
({"max_chars": True}, 5000, 4096),
({"max_chars": "lots"}, 5000, 4096),
pytest.param({"max_chars": "²"}, 5000, 4096, id="nondecimal-digit"),
({"max_chars": 8000}, 8000, None), # fits: unchanged, no note
],
)
@pytest.mark.usefixtures("public_dns")
async def test_web_fetch_tool_truncates_to_4096(self, mock_build):
async def test_web_fetch_tool_truncates_to_max_chars(self, cfg, length, kept):
from deerflow.community.crawl4ai import tools
mock_client = MagicMock()
mock_client.fetch_markdown = AsyncMock(return_value="x" * 5000)
mock_build.return_value = mock_client
def respond(request):
assert request.url.path == "/md"
return httpx.Response(200, json={"success": True, "markdown": "x" * length})
with patch("deerflow.community.crawl4ai.tools._get_tool_config", return_value=None):
transport = httpx.MockTransport(respond)
mock_httpx = SimpleNamespace(
AsyncClient=lambda **kwargs: httpx.AsyncClient(transport=transport, **kwargs),
TimeoutException=httpx.TimeoutException,
RequestError=httpx.RequestError,
)
with (
patch("deerflow.community.crawl4ai.crawl4ai_client.httpx", mock_httpx),
patch("deerflow.community.crawl4ai.tools._get_tool_config", return_value=cfg),
):
result = await tools.web_fetch_tool.ainvoke("https://example.com")
assert len(result) == 4096
if kept is None:
assert result == "x" * length
else:
assert result == "x" * kept + f"\n\n[web_fetch: truncated to the first {kept} of {length} characters]"
@patch("deerflow.community.crawl4ai.tools._build_client")
@pytest.mark.usefixtures("public_dns")

View File

@ -1149,6 +1149,8 @@ tools:
# # # cannot be enforced end-to-end. Set true ONLY when its outbound network
# # # is isolated from private and cloud-metadata networks.
# # filter: fit # Markdown filter: fit (default) | raw | bm25 | llm
# # max_chars: 4096 # Output cap in characters (default 4096); a cut page ends with a note.
# # # Above tool_output.externalize_min_chars, output goes to a file instead.
# Web capture tool (uses Browserless /screenshot to render a page as an artifact)
# Browserless captures JavaScript-heavy pages with a real headless Chrome and

View File

@ -155,6 +155,8 @@ fences, including unclosed fences, in complete and streamed replies.
Self-hosted Browserless, Crawl4AI, Firecrawl, and fastCRW fetch backends require outbound isolation from private, loopback, link-local, and cloud-metadata networks before setting `network_isolation_confirmed: true` on each tool. DeerFlow rejects private or unverifiable backends by default because those services handle redirects, DNS resolution, and subresources themselves. `allow_private_addresses` permits intentional internal target URLs and does not bypass the backend check. See [delegated fetch deployment](../../backend/docs/CONFIGURATION.md#delegated-fetch-backend-isolation); `make doctor` reports backend configurations that would be refused.
Crawl4AI `web_fetch` accepts an optional `max_chars` tool setting (positive integer, default 4096) for its output cap. A page cut at the cap ends with a note giving the kept and total length, so the agent knows the page goes on. Outputs above `tool_output.externalize_min_chars` are still externalized to a file.
Jina fetches support opt-in bounded retries via `max_retries` (default `0`) and `retry_budget_seconds` (default `30`) in the tool configuration. Valid `Retry-After` hints set a minimum wait for HTTP 429/503; 429 without a valid hint stays terminal. Hints that cannot fit the remaining budget stop retries. Local backoff remains randomized. Retries may increase upstream requests and cost; see [Jina fetch retries](../../backend/docs/CONFIGURATION.md#jina-fetch-retries).
At DEBUG level, Jina emits one bounded crawl completion summary with attempts, elapsed/backoff seconds, outcome and stop reason. See [diagnostics](../../backend/docs/CONFIGURATION.md#jina-crawl-diagnostics) for configuration and correlation.