mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(jina): preserve web_fetch HTTP failure status (#8450)
* fix: 保留 Jina 网页抓取的 HTTP 错误状态 * fix: Jina 响应体超限时保留 HTTP 状态码
This commit is contained in:
parent
d6f1c1d0b7
commit
4bd3c4c6ac
@ -1063,6 +1063,11 @@ Authentication, payment/credit and other statuses remain terminal even with hint
|
||||
error-body prose never enables retries. Empty successful responses, read/write
|
||||
timeouts and arbitrary exceptions are not retried.
|
||||
|
||||
When Jina returns a terminal HTTP error, `web_fetch` passes its status code to
|
||||
the harness for error classification. On HTTP 401, the tool result points to
|
||||
`JINA_API_KEY` and advises the agent to use another available source or report
|
||||
the fetch limitation.
|
||||
|
||||
`Retry-After` accepts non-negative ASCII integer seconds or an HTTP-date
|
||||
(including obsolete HTTP date forms); past dates mean a zero server floor.
|
||||
Signed/fractional delays and non-HTTP dates are invalid. Local backoff ceilings
|
||||
@ -1169,10 +1174,11 @@ Enabled fetches stream and count actual content-decoded bytes (after decompressi
|
||||
before text decoding), ignoring `Content-Length`. Exactly the limit is accepted.
|
||||
The first chunk exceeding it stops consumption and closes the response, returning
|
||||
an explicit size `Error:` without body content, partial success or readability
|
||||
extraction. This applies to all statuses, including 502/503/504, and oversize never
|
||||
retries. Each retry response has its own counter within the existing shared time
|
||||
budget. Streams close on success, errors, cancellation and read failures. Responses
|
||||
within the limit retain charset decoding and existing status/retry handling.
|
||||
extraction. The tool result retains the received HTTP status. Oversize responses
|
||||
are terminal for all statuses, including 502/503/504. Each retry response has its
|
||||
own counter within the existing shared time budget. Streams close on success,
|
||||
errors, cancellation and read failures. Responses within the limit retain charset
|
||||
decoding and existing status/retry handling.
|
||||
|
||||
This limits response retention/consumption, not wire-byte bandwidth or allocations
|
||||
inside HTTPX's decompressor; it is not a hard process-memory bound. The final
|
||||
|
||||
@ -8,6 +8,7 @@ import time
|
||||
from contextlib import asynccontextmanager, nullcontext
|
||||
from datetime import UTC, datetime
|
||||
from email.utils import parsedate_to_datetime
|
||||
from typing import Self
|
||||
|
||||
import httpx
|
||||
|
||||
@ -143,6 +144,22 @@ async def _plain_client(options):
|
||||
yield client
|
||||
|
||||
|
||||
class JinaHTTPFailure(str):
|
||||
"""Keep the crawl string contract while carrying the received HTTP status."""
|
||||
|
||||
status_code: int
|
||||
|
||||
@classmethod
|
||||
def with_status(cls, status_code: int, message: str) -> Self:
|
||||
result = cls(message)
|
||||
result.status_code = status_code
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def from_response(cls, status_code: int, response_text: str) -> Self:
|
||||
return cls.with_status(status_code, f"Error: Jina API returned status {status_code}: {response_text}")
|
||||
|
||||
|
||||
class JinaClient:
|
||||
async def crawl(
|
||||
self,
|
||||
@ -231,7 +248,10 @@ class JinaClient:
|
||||
if max_response_bytes is not None and len(content) + len(chunk) > max_response_bytes:
|
||||
reason = "response_limit"
|
||||
pending_return = True
|
||||
return f"Error: Jina API response exceeds max_response_bytes ({max_response_bytes})"
|
||||
return JinaHTTPFailure.with_status(
|
||||
response.status_code,
|
||||
f"Error: Jina API response exceeds max_response_bytes ({max_response_bytes})",
|
||||
)
|
||||
content.extend(chunk)
|
||||
response_text = content.decode(response.encoding or "utf-8", errors="replace")
|
||||
except (httpx.ConnectError, httpx.ConnectTimeout):
|
||||
@ -254,17 +274,16 @@ class JinaClient:
|
||||
retryable = response.status_code in {502, 503, 504} or (response.status_code == 429 and server_floor is not None)
|
||||
if not retryable or attempt == max_retries:
|
||||
reason = "attempt_exhaustion" if retryable or (response.status_code == 429 and attempt == max_retries and attempt > 0) else "nonretryable_http"
|
||||
error_message = f"Jina API returned status {response.status_code}: {response_text}"
|
||||
logger.error(error_message)
|
||||
logger.error("Jina API returned status %s", response.status_code)
|
||||
pending_return = True
|
||||
return f"Error: {error_message}"
|
||||
return JinaHTTPFailure.from_response(response.status_code, response_text)
|
||||
|
||||
# Only allowlisted failures reach the non-blocking wait.
|
||||
remaining = deadline - asyncio.get_running_loop().time()
|
||||
if server_floor is not None and server_floor >= remaining:
|
||||
reason = "retry_after_unfit"
|
||||
pending_return = True
|
||||
return f"Error: Jina API returned status {response.status_code}: {response_text}"
|
||||
return JinaHTTPFailure.from_response(response.status_code, response_text)
|
||||
if remaining <= 0:
|
||||
raise _RetryBudgetExhausted
|
||||
wait = min(delay, remaining) * random.uniform(0.5, 1.0)
|
||||
@ -273,7 +292,7 @@ class JinaClient:
|
||||
if wait >= remaining:
|
||||
reason = "retry_after_unfit"
|
||||
pending_return = True
|
||||
return f"Error: Jina API returned status {response.status_code}: {response_text}"
|
||||
return JinaHTTPFailure.from_response(response.status_code, response_text)
|
||||
async with _retry_budget_timeout_at(deadline if admission else None):
|
||||
wait_started = time.monotonic() if diagnostic else 0.0
|
||||
try:
|
||||
|
||||
@ -2,7 +2,7 @@ import asyncio
|
||||
|
||||
from langchain.tools import tool
|
||||
|
||||
from deerflow.community.jina_ai.jina_client import JinaClient
|
||||
from deerflow.community.jina_ai.jina_client import JinaClient, JinaHTTPFailure
|
||||
from deerflow.community.url_safety import validate_hosted_fetch_url
|
||||
from deerflow.config import get_app_config
|
||||
from deerflow.utils.readability import ReadabilityExtractor
|
||||
@ -42,8 +42,8 @@ def _coerce_proxy(value: object) -> str | None:
|
||||
return proxy or None
|
||||
|
||||
|
||||
@tool("web_fetch", parse_docstring=True)
|
||||
async def web_fetch_tool(url: str) -> str:
|
||||
@tool("web_fetch", parse_docstring=True, response_format="content_and_artifact")
|
||||
async def web_fetch_tool(url: str) -> tuple[str, dict | None]:
|
||||
"""Fetch the contents of a web page at a given URL.
|
||||
Only fetch EXACT URLs that have been provided directly by the user or have been returned in results from the web_search and web_fetch tools.
|
||||
This tool can NOT access content that requires authentication, such as private Google Docs or pages behind login walls.
|
||||
@ -55,7 +55,7 @@ async def web_fetch_tool(url: str) -> str:
|
||||
"""
|
||||
url_error = validate_hosted_fetch_url(url)
|
||||
if url_error:
|
||||
return url_error
|
||||
return url_error, None
|
||||
|
||||
jina_client = JinaClient()
|
||||
timeout = 10
|
||||
@ -70,7 +70,12 @@ async def web_fetch_tool(url: str) -> str:
|
||||
trust_env = _coerce_bool(config.model_extra.get("trust_env"), trust_env)
|
||||
request_options = {key: config.model_extra[key] for key in ("max_retries", "retry_budget_seconds", "max_response_bytes", "request_admission") if key in config.model_extra}
|
||||
html_content = await jina_client.crawl(url, return_format="html", timeout=timeout, proxy=proxy, trust_env=trust_env, **request_options)
|
||||
if isinstance(html_content, str) and html_content.startswith("Error:"):
|
||||
return html_content
|
||||
if isinstance(html_content, JinaHTTPFailure):
|
||||
content = str(html_content)
|
||||
if html_content.status_code == 401:
|
||||
content += "\n\nCheck JINA_API_KEY before retrying Jina Reader. Use another available source or report the fetch limitation."
|
||||
return content, {"deerflow_http_response": {"status_code": html_content.status_code}}
|
||||
if html_content.startswith("Error:"):
|
||||
return html_content, None
|
||||
article = await asyncio.to_thread(readability_extractor.extract_article, html_content, url=url)
|
||||
return article.to_markdown()[:4096]
|
||||
return article.to_markdown()[:4096], None
|
||||
|
||||
@ -10,6 +10,8 @@ import httpx
|
||||
import pytest
|
||||
|
||||
import deerflow.community.jina_ai.jina_client as jina_client_module
|
||||
from deerflow.agents.middlewares.tool_result_meta import TOOL_META_KEY, normalize_tool_message
|
||||
from deerflow.community.jina_ai import tools as jina_tools
|
||||
from deerflow.community.jina_ai.jina_client import JinaClient
|
||||
from deerflow.community.jina_ai.tools import (
|
||||
_coerce_bool,
|
||||
@ -340,6 +342,87 @@ async def test_web_fetch_tool_returns_error_on_crawl_failure(monkeypatch):
|
||||
assert "429" in result
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def install_jina_fetch_transport(monkeypatch):
|
||||
def install(handle, **options):
|
||||
local_httpx = SimpleNamespace(
|
||||
AsyncClient=lambda **kwargs: httpx.AsyncClient(transport=httpx.MockTransport(handle), **kwargs),
|
||||
ConnectError=httpx.ConnectError,
|
||||
ConnectTimeout=httpx.ConnectTimeout,
|
||||
)
|
||||
monkeypatch.setattr(jina_client_module, "httpx", local_httpx)
|
||||
monkeypatch.delenv("JINA_API_KEY", raising=False)
|
||||
config = SimpleNamespace(model_extra={"max_retries": 2, **options})
|
||||
monkeypatch.setattr(jina_tools, "get_app_config", lambda: SimpleNamespace(get_tool_config=lambda _: config))
|
||||
|
||||
return install
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(
|
||||
("http_status", "body", "expected_status", "expected_category"),
|
||||
[
|
||||
(401, '{"code":401,"status":40103,"name":"AuthenticationRequiredError"}', "error", "auth"),
|
||||
(429, "Rate limited", "error", "rate_limited"),
|
||||
(200, "<html><body><p>401 AuthenticationRequiredError explained</p></body></html>", "success", None),
|
||||
],
|
||||
)
|
||||
async def test_web_fetch_tool_preserves_jina_http_failure_status(install_jina_fetch_transport, http_status, body, expected_status, expected_category):
|
||||
requests = []
|
||||
|
||||
def handle(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(http_status, text=body)
|
||||
|
||||
install_jina_fetch_transport(handle)
|
||||
url = "https://example.com"
|
||||
message = await web_fetch_tool.ainvoke({"type": "tool_call", "name": "web_fetch", "id": "fetch-1", "args": {"url": url}})
|
||||
assert len(requests) == 1
|
||||
assert str(requests[0].url) == "https://r.jina.ai/"
|
||||
meta = normalize_tool_message(message).additional_kwargs[TOOL_META_KEY]
|
||||
assert (meta["status"], meta["error_type"]) == (expected_status, expected_category)
|
||||
if expected_status == "error":
|
||||
assert message.artifact["deerflow_http_response"]["status_code"] == http_status
|
||||
if http_status == 401:
|
||||
assert "JINA_API_KEY" in message.content
|
||||
assert message.content == await web_fetch_tool.ainvoke({"url": url})
|
||||
if http_status == 200:
|
||||
assert message.artifact is None
|
||||
assert "401 AuthenticationRequiredError explained" in message.content
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(("status", "category"), [(200, "unknown"), (401, "auth")])
|
||||
async def test_tool_response_limit_retains_http_status(install_jina_fetch_transport, status, category):
|
||||
class OversizedResponse(httpx.AsyncByteStream):
|
||||
closed = False
|
||||
|
||||
async def __aiter__(self):
|
||||
yield b"provider-body:" + b"x" * 256
|
||||
pytest.fail("web_fetch continued reading after reaching the response limit")
|
||||
|
||||
async def aclose(self):
|
||||
self.closed = True
|
||||
|
||||
stream = OversizedResponse()
|
||||
requests = []
|
||||
|
||||
def handle(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(status, stream=stream)
|
||||
|
||||
install_jina_fetch_transport(handle, max_response_bytes=256)
|
||||
message = await web_fetch_tool.ainvoke({"type": "tool_call", "name": "web_fetch", "id": "fetch-1", "args": {"url": "https://example.com"}})
|
||||
|
||||
assert stream.closed and len(requests) == 1
|
||||
assert message.content.startswith("Error: Jina API response exceeds max_response_bytes (256)")
|
||||
assert "provider-body" not in message.content
|
||||
meta = normalize_tool_message(message).additional_kwargs[TOOL_META_KEY]
|
||||
assert (meta["status"], meta["error_type"]) == ("error", category)
|
||||
assert message.artifact["deerflow_http_response"]["status_code"] == status
|
||||
assert ("JINA_API_KEY" in message.content) == (status == 401)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_web_fetch_tool_returns_markdown_on_success(monkeypatch):
|
||||
"""Test that web_fetch_tool returns extracted markdown on successful crawl."""
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user