mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-28 01:10:35 +00:00
feat(search): add Webz news search provider and setup integration (#5880)
* feat(search): add Webz news search provider and setup integration * fix(webz): honor caller result limits and clarify page counts * fix(frontend): render Webz search source links * fix(frontend): skip malformed search source entries
This commit is contained in:
parent
3b8141aa43
commit
a333ac3189
@ -11,6 +11,9 @@ SERPLY_API_KEY=your-serply-api-key
|
||||
# TAVILY API Key
|
||||
TAVILY_API_KEY=your-tavily-api-key
|
||||
|
||||
# Optional Webz.io News Search key (select Webz in make setup)
|
||||
# WEBZ_API_KEY=your-webz-api-key
|
||||
|
||||
# Jina API Key
|
||||
JINA_API_KEY=your-jina-api-key
|
||||
|
||||
|
||||
19
README.md
19
README.md
@ -1501,6 +1501,25 @@ reuse the search entry's key, so search can use a different provider. If you
|
||||
previously configured a shared Tavily key only under `web_search`, also set it
|
||||
under `web_fetch` or use `TAVILY_API_KEY` for both.
|
||||
|
||||
For news-focused research, select **Webz.io News Search** in `make setup`, or
|
||||
replace the `web_search` tool's `use` with
|
||||
`deerflow.community.webz.tools:web_search_tool` and set `WEBZ_API_KEY`.
|
||||
An explicit tool `api_key` takes precedence over the environment variable.
|
||||
An explicit call's `max_results` overrides the configured default; omission
|
||||
uses configuration or 5 (clamped to 1–100). Invalid configured counts, including
|
||||
booleans and fractional numbers, fall back to 5. Results include the matching
|
||||
passage, title, URL, publication date, and source metadata. The chat search step
|
||||
displays source titles and links, including after reloading a conversation, and
|
||||
skips malformed source entries without losing valid links. `returned_results`
|
||||
counts the returned page, not all matching news articles. Malformed entries are
|
||||
skipped with a warning while valid entries are retained; invalid responses or
|
||||
pages with no valid entries return an error. Empty result lists remain valid. The tool accepts
|
||||
language, country, source-domain, sentiment, category, and publication-date
|
||||
filters. Its `time_range` maps to a UTC lower date bound of 1, 7, 30, or 365
|
||||
days; an explicit `published_from` overrides that bound. Webz searches recent
|
||||
news rather than the general web: date filters cannot extend the provider's
|
||||
[documented 30-day coverage](https://docs.webz.io/docs/webz/news-search-api-response-format).
|
||||
|
||||
#### Exporting Custom Skills
|
||||
|
||||
Administrators can export their own custom skills from **Capability Center → Skills → My skills → View details → Export**. Review the file list and declared environment requirements, then choose **Download .skill**. The archive contains the currently saved skill, including supporting files and empty directories; disabled skills can also be exported. If the skill changes after preview, refresh the file list before downloading. Import the archive on another DeerFlow instance with **Install .skill**; existing-name conflicts and normal installation security checks still apply.
|
||||
|
||||
@ -0,0 +1 @@
|
||||
"""Webz.io News Search integration."""
|
||||
153
backend/packages/harness/deerflow/community/webz/tools.py
Normal file
153
backend/packages/harness/deerflow/community/webz/tools.py
Normal file
@ -0,0 +1,153 @@
|
||||
"""Async adapter for the Webz.io News Search context endpoint."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
from langchain.tools import tool
|
||||
|
||||
from deerflow.community.search_time_range import SearchTimeRange
|
||||
from deerflow.config import get_app_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _options() -> dict:
|
||||
config = get_app_config().get_tool_config("web_search")
|
||||
return dict(config.model_extra or {}) if config else {}
|
||||
|
||||
|
||||
def _count(value: object) -> int:
|
||||
try:
|
||||
if isinstance(value, bool) or (isinstance(value, float) and not value.is_integer()):
|
||||
raise ValueError("Expected an integer")
|
||||
return max(1, min(100, int(value)))
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
logger.warning("Invalid Webz max_results=%r; using default 5", value)
|
||||
return 5
|
||||
|
||||
|
||||
def _normalize(payload: object, count: int) -> list[dict]:
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("results"), list):
|
||||
raise ValueError("Invalid results")
|
||||
results = []
|
||||
for index, item in enumerate(payload["results"][:count]):
|
||||
try:
|
||||
if not isinstance(item, dict) or not isinstance(item.get("article"), dict):
|
||||
raise ValueError("Invalid article")
|
||||
article = item["article"]
|
||||
chunk, metadata = item.get("chunk", {}), item.get("metadata", {})
|
||||
if not isinstance(chunk, dict) or not isinstance(metadata, dict):
|
||||
raise ValueError("Invalid metadata")
|
||||
result = {
|
||||
"title": article.get("title", ""),
|
||||
"url": article.get("url", ""),
|
||||
"content": chunk.get("text") or article.get("summary") or "",
|
||||
"published_at": article.get("published_at", ""),
|
||||
}
|
||||
if any(not isinstance(value, str) for value in result.values()):
|
||||
raise ValueError("Invalid article fields")
|
||||
except ValueError:
|
||||
logger.warning("Skipping malformed Webz result at index %d", index)
|
||||
continue
|
||||
results.append({**result, "source": metadata})
|
||||
if payload["results"] and not results:
|
||||
raise ValueError("No valid articles")
|
||||
return results
|
||||
|
||||
|
||||
@tool("web_search", parse_docstring=True)
|
||||
async def web_search_tool(
|
||||
query: str,
|
||||
max_results: int | None = None,
|
||||
time_range: SearchTimeRange | None = None,
|
||||
published_from: str | None = None,
|
||||
published_to: str | None = None,
|
||||
language: list[str] | None = None,
|
||||
country: list[str] | None = None,
|
||||
source: list[str] | None = None,
|
||||
sentiment: list[Literal["positive", "negative", "neutral"]] | None = None,
|
||||
category: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Search recent news with Webz.io and return matching passages and source metadata.
|
||||
|
||||
This provider searches news, not the general web. Date filters do not extend
|
||||
the provider's available news coverage.
|
||||
|
||||
Args:
|
||||
query: News search query, at most 750 characters and 100 words.
|
||||
max_results: Maximum results, clamped to 1-100; uses configuration or 5 when omitted.
|
||||
time_range: Optional recency window: day, week, month, or year (UTC).
|
||||
published_from: Inclusive lower publication date in YYYY-MM-DD; overrides time_range.
|
||||
published_to: Inclusive upper publication date in YYYY-MM-DD.
|
||||
language: Optional language names, for example ["english"].
|
||||
country: Optional country codes, for example ["US"].
|
||||
source: Optional source domains, for example ["cnn.com"].
|
||||
sentiment: Optional positive, negative, or neutral sentiments.
|
||||
category: Optional news categories.
|
||||
|
||||
Returns:
|
||||
JSON containing query, returned_results (the returned page size) and results, or an error.
|
||||
"""
|
||||
query = query.strip()
|
||||
if not query or len(query) > 750 or len(query.split()) > 100:
|
||||
return json.dumps({"error": "Webz query must contain 1-750 characters and at most 100 words"})
|
||||
if published_from is None and time_range:
|
||||
days = {"day": 1, "week": 7, "month": 30, "year": 365}[time_range]
|
||||
published_from = (datetime.now(UTC).date() - timedelta(days=days)).isoformat()
|
||||
try:
|
||||
for value in (published_from, published_to):
|
||||
if value is not None and date.fromisoformat(value).isoformat() != value:
|
||||
raise ValueError("Non-canonical date")
|
||||
if published_from and published_to and published_from > published_to:
|
||||
raise ValueError("Reversed dates")
|
||||
except ValueError:
|
||||
return json.dumps({"error": "Webz dates must use YYYY-MM-DD with published_from <= published_to"})
|
||||
|
||||
# Lazy configuration resolution can read files; keep it off the event loop.
|
||||
options = await asyncio.to_thread(_options)
|
||||
key = options.get("api_key")
|
||||
key = key.strip() if isinstance(key, str) else ""
|
||||
key = key or os.getenv("WEBZ_API_KEY", "").strip()
|
||||
if not key:
|
||||
return json.dumps({"error": "Webz API key is missing; configure api_key or WEBZ_API_KEY"})
|
||||
count = _count(max_results if max_results is not None else options.get("max_results", 5))
|
||||
body = {"query": query, "k": count}
|
||||
filters = {
|
||||
name: value
|
||||
for name, value in {
|
||||
"published_from": published_from,
|
||||
"published_to": published_to,
|
||||
"language": language,
|
||||
"country": country,
|
||||
"domain": source,
|
||||
"sentiment": sentiment,
|
||||
"category": category,
|
||||
}.items()
|
||||
if value is not None
|
||||
}
|
||||
if filters:
|
||||
body["filters"] = filters
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0, follow_redirects=False) as client:
|
||||
response = await client.post(
|
||||
"https://api.webz.io/api/news/context",
|
||||
headers={"Authorization": f"Bearer {key}", "Accept": "application/json"},
|
||||
json=body,
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = _normalize(response.json(), count)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
return json.dumps({"error": f"Webz request failed (HTTP {exc.response.status_code})"})
|
||||
except httpx.TimeoutException:
|
||||
return json.dumps({"error": "Webz request timed out"})
|
||||
except httpx.RequestError:
|
||||
return json.dumps({"error": "Webz request failed"})
|
||||
except ValueError:
|
||||
logger.warning("Webz returned an unexpected response")
|
||||
return json.dumps({"error": "Webz returned an unexpected response"})
|
||||
return json.dumps({"query": query, "returned_results": len(results), "results": results}, ensure_ascii=False)
|
||||
28
backend/tests/blocking_io/test_webz_search_async.py
Normal file
28
backend/tests/blocking_io/test_webz_search_async.py
Normal file
@ -0,0 +1,28 @@
|
||||
"""Webz configuration resolution must not run on the agent event loop."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_webz_configuration_runs_off_event_loop(monkeypatch):
|
||||
import deerflow.community.webz.tools as module
|
||||
|
||||
loop_thread = threading.get_ident()
|
||||
config_threads = []
|
||||
|
||||
def config():
|
||||
config_threads.append(threading.get_ident())
|
||||
return SimpleNamespace(get_tool_config=lambda _: SimpleNamespace(model_extra={"api_key": "synthetic-key"}))
|
||||
|
||||
monkeypatch.setattr(module, "get_app_config", config)
|
||||
client_class = httpx.AsyncClient
|
||||
transport = httpx.MockTransport(lambda _: httpx.Response(200, json={"results": []}))
|
||||
monkeypatch.setattr(module.httpx, "AsyncClient", lambda **kwargs: client_class(transport=transport, **kwargs))
|
||||
result = json.loads(await module.web_search_tool.ainvoke({"query": "news"}))
|
||||
assert result["results"] == []
|
||||
assert config_threads and all(thread != loop_thread for thread in config_threads)
|
||||
263
backend/tests/test_webz_tools.py
Normal file
263
backend/tests/test_webz_tools.py
Normal file
@ -0,0 +1,263 @@
|
||||
"""Offline Webz request/response contract using the real httpx serializer."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import yaml
|
||||
from httpx import AsyncClient as RealAsyncClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def webz(monkeypatch):
|
||||
import deerflow.community.webz.tools as module
|
||||
|
||||
options = {"api_key": "synthetic-key"}
|
||||
monkeypatch.setattr(module, "get_app_config", lambda: SimpleNamespace(get_tool_config=lambda _: SimpleNamespace(model_extra=options)))
|
||||
monkeypatch.delenv("WEBZ_API_KEY", raising=False)
|
||||
requests = []
|
||||
response = {"results": []}
|
||||
status = [200]
|
||||
client_class = httpx.AsyncClient
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(status[0], json=response)
|
||||
|
||||
monkeypatch.setattr(module.httpx, "AsyncClient", lambda **kwargs: client_class(transport=httpx.MockTransport(handler), **kwargs))
|
||||
return module, options, requests, response, status
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_filters_and_normalized_results(webz, monkeypatch):
|
||||
module, _, requests, response, _ = webz
|
||||
monkeypatch.setenv("WEBZ_API_KEY", "unused-environment-key")
|
||||
response["results"] = [
|
||||
{
|
||||
"score": 8.5,
|
||||
"article": {"title": "News", "url": "https://example.com/news", "published_at": "2026-09-20T12:00:00Z", "summary": "Summary"},
|
||||
"chunk": {"text": "Matching passage"},
|
||||
"metadata": {"domain": "example.com", "language": "english", "country": "US"},
|
||||
}
|
||||
]
|
||||
result = json.loads(
|
||||
await module.web_search_tool.ainvoke(
|
||||
{
|
||||
"query": "renewable energy",
|
||||
"max_results": 3,
|
||||
"published_from": "2026-09-01",
|
||||
"published_to": "2026-09-20",
|
||||
"language": ["english"],
|
||||
"country": ["US"],
|
||||
"source": ["example.com"],
|
||||
"sentiment": ["positive"],
|
||||
"category": ["Environment"],
|
||||
}
|
||||
)
|
||||
)
|
||||
request = requests[0]
|
||||
assert str(request.url) == "https://api.webz.io/api/news/context"
|
||||
assert request.headers["authorization"] == "Bearer synthetic-key"
|
||||
assert json.loads(request.content) == {
|
||||
"query": "renewable energy",
|
||||
"k": 3,
|
||||
"filters": {"published_from": "2026-09-01", "published_to": "2026-09-20", "language": ["english"], "country": ["US"], "domain": ["example.com"], "sentiment": ["positive"], "category": ["Environment"]},
|
||||
}
|
||||
assert result == {
|
||||
"query": "renewable energy",
|
||||
"returned_results": 1,
|
||||
"results": [{"title": "News", "url": "https://example.com/news", "content": "Matching passage", "published_at": "2026-09-20T12:00:00Z", "source": {"domain": "example.com", "language": "english", "country": "US"}}],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("window", "start"), [("day", "2026-09-23"), ("week", "2026-09-17"), ("month", "2026-08-25"), ("year", "2025-09-24")])
|
||||
async def test_relative_window_uses_utc_and_explicit_lower_bound_wins(webz, monkeypatch, window, start):
|
||||
module, _, requests, _, _ = webz
|
||||
|
||||
class Clock(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls(2026, 9, 24, 12, tzinfo=UTC)
|
||||
|
||||
monkeypatch.setattr(module, "datetime", Clock)
|
||||
await module.web_search_tool.ainvoke({"query": "news", "time_range": window})
|
||||
assert json.loads(requests[-1].content)["filters"] == {"published_from": start}
|
||||
await module.web_search_tool.ainvoke({"query": "news", "time_range": window, "published_from": "2026-09-22"})
|
||||
assert json.loads(requests[-1].content)["filters"] == {"published_from": "2026-09-22"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_environment_key_configured_count_and_no_implicit_filters(webz, monkeypatch):
|
||||
module, options, requests, _, _ = webz
|
||||
options.update(api_key=" ", max_results="1000")
|
||||
monkeypatch.setenv("WEBZ_API_KEY", " env-key ")
|
||||
assert json.loads(await module.web_search_tool.ainvoke({"query": " news "})) == {"query": "news", "returned_results": 0, "results": []}
|
||||
assert requests[0].headers["authorization"] == "Bearer env-key"
|
||||
assert json.loads(requests[0].content) == {"query": "news", "k": 100}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_key_never_makes_request(webz):
|
||||
module, options, requests, _, _ = webz
|
||||
options.clear()
|
||||
assert "WEBZ_API_KEY" in json.loads(await module.web_search_tool.ainvoke({"query": "news"}))["error"]
|
||||
assert not requests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("arguments", [{"query": " "}, {"query": "x" * 751}, {"query": "word " * 101}, {"query": "news", "published_from": "yesterday"}, {"query": "news", "published_from": "2026-09-20", "published_to": "2026-09-01"}])
|
||||
async def test_invalid_input_never_makes_request(webz, arguments):
|
||||
module, _, requests, _, _ = webz
|
||||
assert "error" in json.loads(await module.web_search_tool.ainvoke(arguments))
|
||||
assert not requests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status_code", [302, 401, 429, 500])
|
||||
async def test_http_errors_do_not_echo_provider_body_or_credentials(webz, status_code, caplog):
|
||||
module, _, requests, response, status = webz
|
||||
response.update(error="synthetic-key")
|
||||
status[0] = status_code
|
||||
result = await module.web_search_tool.ainvoke({"query": "news"})
|
||||
assert str(status_code) in json.loads(result)["error"]
|
||||
assert "synthetic-key" not in result + caplog.text
|
||||
assert len(requests) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("payload", [{}, {"results": None}, {"results": [None]}, {"results": [{"article": []}]}])
|
||||
async def test_malformed_payload_is_an_error(webz, payload, caplog):
|
||||
module, _, _, response, _ = webz
|
||||
response.clear()
|
||||
response.update(payload)
|
||||
assert "error" in json.loads(await module.web_search_tool.ainvoke({"query": "news"}))
|
||||
assert "Webz returned an unexpected response" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancellation_propagates(webz, monkeypatch):
|
||||
module, _, _, _, _ = webz
|
||||
|
||||
async def cancelled(*args, **kwargs):
|
||||
raise asyncio.CancelledError
|
||||
|
||||
monkeypatch.setattr(RealAsyncClient, "post", cancelled)
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await module.web_search_tool.ainvoke({"query": "news"})
|
||||
|
||||
|
||||
def test_setup_wizard_offers_webz_with_env_key():
|
||||
from wizard.providers import SEARCH_PROVIDERS
|
||||
from wizard.writer import build_minimal_config
|
||||
|
||||
provider = next(p for p in SEARCH_PROVIDERS if p.name == "webz")
|
||||
assert provider.env_var == "WEBZ_API_KEY"
|
||||
config = build_minimal_config(provider_use="langchain_openai:ChatOpenAI", model_name="dummy", display_name="Dummy", api_key_field="api_key", env_var="OPENAI_API_KEY", search_use=provider.use, search_extra_config=provider.extra_config)
|
||||
assert next(t for t in yaml.safe_load(config)["tools"] if t["name"] == "web_search")["use"] == "deerflow.community.webz.tools:web_search_tool"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("exception", [httpx.ReadTimeout("synthetic-key"), httpx.ConnectError("synthetic-key")])
|
||||
async def test_transport_failures_are_sanitized(webz, monkeypatch, exception):
|
||||
module, _, _, _, _ = webz
|
||||
|
||||
async def fail(*args, **kwargs):
|
||||
raise exception
|
||||
|
||||
monkeypatch.setattr(RealAsyncClient, "post", fail)
|
||||
result = await module.web_search_tool.ainvoke({"query": "news"})
|
||||
assert "error" in json.loads(result)
|
||||
assert "synthetic-key" not in result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summary_fallback_and_output_limit(webz):
|
||||
module, _, _, response, _ = webz
|
||||
response["results"] = [{"article": {"title": "News", "url": "https://example.com", "summary": "Summary"}}] * 3
|
||||
response["total_results"] = 3
|
||||
result = json.loads(await module.web_search_tool.ainvoke({"query": "news", "max_results": 1}))
|
||||
assert result["returned_results"] == len(result["results"]) == 1
|
||||
assert "total_results" not in result
|
||||
assert result["results"][0]["content"] == "Summary"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("value, expected", [(None, 5), (True, 5), (False, 5), ("invalid", 5), (3.5, 5), (-3.5, 5), (float("inf"), 5), (float("nan"), 5), (3.0, 3), (-1, 1), ("12", 12), (200, 100)])
|
||||
async def test_configured_result_count(webz, value, expected):
|
||||
module, options, requests, _, _ = webz
|
||||
options["max_results"] = value
|
||||
await module.web_search_tool.ainvoke({"query": "news"})
|
||||
assert json.loads(requests[0].content)["k"] == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("configured, arguments, expected", [(5, {"max_results": 20}, 20), (20, {"max_results": 5}, 5), ("invalid", {"max_results": 3}, 3), (20, {}, 20), (20, {"max_results": None}, 20)])
|
||||
async def test_call_count_overrides_configuration_unless_omitted(webz, configured, arguments, expected):
|
||||
module, options, requests, _, _ = webz
|
||||
options["max_results"] = configured
|
||||
await module.web_search_tool.ainvoke({"query": "news", **arguments})
|
||||
assert json.loads(requests[0].content)["k"] == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_configured_count_defaults_to_five(webz):
|
||||
module, _, requests, _, _ = webz
|
||||
await module.web_search_tool.ainvoke({"query": "news"})
|
||||
assert json.loads(requests[0].content)["k"] == 5
|
||||
|
||||
|
||||
def test_doctor_recognizes_webz_credentials(tmp_path, monkeypatch):
|
||||
import doctor
|
||||
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text("tools:\n - name: web_search\n use: deerflow.community.webz.tools:web_search_tool\n", encoding="utf-8")
|
||||
monkeypatch.delenv("WEBZ_API_KEY", raising=False)
|
||||
missing = doctor.check_web_search(config)
|
||||
assert missing.status == "warn"
|
||||
assert "WEBZ_API_KEY" in missing.detail
|
||||
monkeypatch.setenv("WEBZ_API_KEY", "synthetic-key")
|
||||
present = doctor.check_web_search(config)
|
||||
assert present.status == "ok"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("bad_item", [None, {"article": []}, {"article": {}, "chunk": None}, {"article": {}, "metadata": "synthetic-key"}, {"article": {"title": ["synthetic-key"]}}])
|
||||
async def test_malformed_item_preserves_valid_neighbors(webz, bad_item, caplog):
|
||||
module, _, _, response, _ = webz
|
||||
response["results"] = [
|
||||
{"article": {"title": "First", "summary": "First summary"}},
|
||||
bad_item,
|
||||
{"article": {"title": "Last", "summary": "Last summary"}},
|
||||
]
|
||||
result = json.loads(await module.web_search_tool.ainvoke({"query": "news", "max_results": 3}))
|
||||
assert result["returned_results"] == 2
|
||||
assert [item["title"] for item in result["results"]] == ["First", "Last"]
|
||||
assert "Skipping malformed Webz result at index 1" in caplog.text
|
||||
assert "synthetic-key" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_json_is_logged_without_response_body(webz, monkeypatch, caplog):
|
||||
module, _, _, _, _ = webz
|
||||
|
||||
async def invalid_json(*args, **kwargs):
|
||||
return httpx.Response(200, text="synthetic-key", request=httpx.Request("POST", "https://api.webz.io/api/news/context"))
|
||||
|
||||
monkeypatch.setattr(RealAsyncClient, "post", invalid_json)
|
||||
result = await module.web_search_tool.ainvoke({"query": "news"})
|
||||
assert "unexpected response" in json.loads(result)["error"]
|
||||
assert "Webz returned an unexpected response" in caplog.text
|
||||
assert "synthetic-key" not in result + caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_configured_count_logs_value(webz, caplog):
|
||||
module, options, requests, _, _ = webz
|
||||
options["max_results"] = 3.5
|
||||
await module.web_search_tool.ainvoke({"query": "news"})
|
||||
assert json.loads(requests[0].content)["k"] == 5
|
||||
assert "max_results=3.5" in caplog.text
|
||||
@ -954,6 +954,14 @@ tools:
|
||||
# # hl: en # Optional interface language
|
||||
# # api_key: $SERPLY_API_KEY # Optional if the env var is set
|
||||
|
||||
# News search tool (uses Webz.io News Search, requires WEBZ_API_KEY)
|
||||
# Recent news coverage, not general web search. Replace the active web_search entry.
|
||||
# - name: web_search
|
||||
# group: web
|
||||
# use: deerflow.community.webz.tools:web_search_tool
|
||||
# max_results: 5 # Clamped to 1-100
|
||||
# # api_key: $WEBZ_API_KEY # Otherwise read from WEBZ_API_KEY
|
||||
|
||||
# Web search tool (uses Brave Search API, requires BRAVE_SEARCH_API_KEY)
|
||||
# Brave Search returns results from an independent index. Sign up at
|
||||
# https://brave.com/search/api/ to get a key. Unlike the DuckDuckGo
|
||||
|
||||
@ -193,6 +193,7 @@ export on a page error or non-advancing cursor; demos keep their fixture path.
|
||||
- **SSE replay gaps** are handled in `core/api/api-client.ts`, which wraps both initial and joined run streams because the upstream SDK ignores unknown event names. An id-less backend `gap` control frame clears stale reconnect metadata, emits an internal `stream_replay_gap` custom event, reloads durable thread values, and resumes after the server-provided retained tail when one exists (or rejoins without a cursor if the buffer is empty), with up to five recovery rejoins after the original stream (six total stream calls on an all-gap exhaustion path). The wrapper remains a lazy async iterable because the SDK consumes it with `for await`. `core/threads/hooks.ts` clears optimistic/transient/subtask state, invalidates durable history caches, and shows the localized recovery warning; never let a gap fall through as a normal stream finish or cancel the still-running backend run.
|
||||
- **Streaming Markdown rendering** is owned by `core/streamdown`: Streamdown's `animated` / `isAnimating` API handles incremental word animation, while the shared `streamdownRenderingPlugins` config registers the named code-highlighting and Mermaid plugins required by Streamdown 2.5. Keep wrappers and derived configs wired to that shared object; do not reintroduce a rehype plugin that wraps every word, because reparsing a growing block remounts old words and replays their animation.
|
||||
- Citation links in message and artifact Markdown must derive their `citation:` label from the full `ReactNode` children tree, since Streamdown may provide element or array children during streaming rather than a plain string.
|
||||
- Web-search steps accept either a provider result array or a Webz-style `{ query, returned_results, results }` envelope. Unwrap only in the web-search renderer; skip entries without string titles/URLs, preserve other tool payloads and apply the same link allowlist to both formats. UI regressions pin source titles/links and browser reloads, including malformed neighboring entries.
|
||||
- Tool-step links in `message-group.tsx` (`web_fetch` args, `web_search` / `image_search` result URLs) are model- or provider-controlled, so they pass the markdown `isSafeHref` allowlist; every surface renders a rejected href through the shared `UnsafeLink` marker.
|
||||
- **Environment validation** uses `@t3-oss/env-nextjs` with Zod schemas (`src/env.js`). Skip with `SKIP_ENV_VALIDATION=1`
|
||||
- **Subtask step history and runtime metadata** (`core/tasks/`) — the subtask card shows a subagent's full step timeline (#3779): its assistant reasoning turns interleaved with the tools it ran. The task tool's model-visible `description` is an optional progress label; `MessageList` uses the required `prompt` (then the localized generic subtask label) when a provider omits it, so a valid task call never renders a blank card title. `Subtask.steps[]` is accumulated live from `task_running` events (appended via `mergeSteps`, not overwritten) and backfilled on expand for historical runs by `fetchSubtaskSteps`, which pages the events endpoint scoped to one task (GET `/runs/{runId}/events?event_types=subagent.step&task_id=…&after_seq=…`) until a short page, so the run-wide limit can't truncate the timeline. `task_started` carries the effective `model_name`; `task_running` carries a cumulative usage snapshot after each completed LLM call. `core/tasks/lifecycle.ts` normalizes these additive events, and `computeNextSubtask` keeps the largest cumulative total so replayed or late SSE frames cannot double-count or roll the folded card backward. Terminal ToolMessage metadata (`subagent_model_name` / `subagent_token_usage`) restores the same values from normal history after reload; no per-card event fetch is needed. `core/tasks/steps.ts` is the pure step model: `messageToStep` (live), `eventsToSteps` (reload), `mergeSteps` (dedup by `message_index`), and `stepsForDisplay` (what the card renders — keeps tool steps + AI steps with text, drops the trailing final-answer AI step when completed since it's shown as `result`). `core/tasks/context.tsx`'s `useUpdateSubtask` applies updates against a `tasksRef` mirroring the latest state (not a closure snapshot), so a late-resolving `fetchSubtaskSteps` backfill merges into current state instead of clobbering SSE steps or sibling subtasks that arrived meanwhile. The owning `run_id` is carried onto history content messages in `buildVisibleHistoryMessages` so the card can resolve the events endpoint.
|
||||
|
||||
@ -838,18 +838,34 @@ function ToolCall({
|
||||
if (typeof args.query === "string") {
|
||||
label = t.toolCalls.searchOnWebFor(args.query);
|
||||
}
|
||||
const results = Array.isArray(result)
|
||||
? result
|
||||
: typeof result === "object" && result !== null
|
||||
? result.results
|
||||
: undefined;
|
||||
const sources = Array.isArray(results)
|
||||
? results.filter(
|
||||
(item: unknown): item is { title: string; url: string } =>
|
||||
typeof item === "object" &&
|
||||
item !== null &&
|
||||
"title" in item &&
|
||||
typeof item.title === "string" &&
|
||||
"url" in item &&
|
||||
typeof item.url === "string",
|
||||
)
|
||||
: [];
|
||||
return (
|
||||
<ChainOfThoughtStep
|
||||
key={id}
|
||||
label={resolveLabel(label)}
|
||||
icon={SearchIcon}
|
||||
>
|
||||
{Array.isArray(result) && (
|
||||
{sources.length > 0 && (
|
||||
<ChainOfThoughtSearchResults>
|
||||
{/* Tool args and results are model- or provider-controlled, so
|
||||
every tool link passes the same scheme allowlist as markdown
|
||||
links and degrades to the same UnsafeLink marker. */}
|
||||
{result.map((item) => (
|
||||
{sources.map((item) => (
|
||||
<ChainOfThoughtSearchResult key={item.url}>
|
||||
{isSafeHref(item.url) ? (
|
||||
<a href={item.url} target="_blank" rel="noopener noreferrer">
|
||||
|
||||
81
frontend/tests/e2e/web-search-results.spec.ts
Normal file
81
frontend/tests/e2e/web-search-results.spec.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { mockLangGraphAPI } from "./utils/mock-api";
|
||||
|
||||
for (const shape of ["array", "webz", "webz-malformed"] as const) {
|
||||
test(`search source links from ${shape} results survive reload`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const threadId = "00000000-0000-0000-0000-000000005880";
|
||||
const results: unknown[] = [
|
||||
{
|
||||
title: "Renewable energy news",
|
||||
url: "https://example.com/news",
|
||||
content: "Matching passage",
|
||||
published_at: "2026-09-20T12:00:00Z",
|
||||
source: { domain: "example.com", language: "english", country: "US" },
|
||||
},
|
||||
];
|
||||
if (shape === "webz-malformed") {
|
||||
results.unshift(null, {
|
||||
title: { text: "Invalid title" },
|
||||
url: "https://example.com/invalid",
|
||||
});
|
||||
results.push({ title: "Invalid URL", url: 42 });
|
||||
}
|
||||
const payload =
|
||||
shape === "array"
|
||||
? results
|
||||
: {
|
||||
query: "renewable energy",
|
||||
returned_results: results.length,
|
||||
results,
|
||||
};
|
||||
mockLangGraphAPI(page, {
|
||||
threads: [
|
||||
{
|
||||
thread_id: threadId,
|
||||
title: "News research",
|
||||
messages: [
|
||||
{ type: "human", id: "human", content: "Find recent energy news" },
|
||||
{
|
||||
type: "ai",
|
||||
id: "ai-search",
|
||||
content: "",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "search-5880",
|
||||
name: "web_search",
|
||||
args: { query: "renewable energy" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "tool",
|
||||
id: "search-result",
|
||||
tool_call_id: "search-5880",
|
||||
name: "web_search",
|
||||
content: JSON.stringify(payload),
|
||||
},
|
||||
{
|
||||
type: "ai",
|
||||
id: "answer",
|
||||
content: "The news search is complete.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
await page.goto(`/workspace/chats/${threadId}`);
|
||||
const link = page.getByRole("link", {
|
||||
name: "Renewable energy news",
|
||||
exact: true,
|
||||
});
|
||||
await expect(link).toBeVisible();
|
||||
await expect(link).toHaveAttribute("href", "https://example.com/news");
|
||||
await expect(link).toHaveAttribute("rel", "noopener noreferrer");
|
||||
await page.reload();
|
||||
await expect(link).toBeVisible();
|
||||
await expect(link).toHaveAttribute("href", "https://example.com/news");
|
||||
});
|
||||
}
|
||||
@ -37,6 +37,105 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("MessageGroup", () => {
|
||||
it.each(["array", "webz"])(
|
||||
"retains valid search links when %s results contain malformed entries",
|
||||
(shape) => {
|
||||
const results = [
|
||||
{ title: "First source", url: "https://example.com/first" },
|
||||
null,
|
||||
"not a result",
|
||||
{ title: { text: "Invalid title" }, url: "https://example.com/bad" },
|
||||
{ title: "Invalid URL", url: 42 },
|
||||
{ url: "https://example.com/missing-title" },
|
||||
{ title: "Missing URL" },
|
||||
{ title: "Last source", url: "https://example.com/last" },
|
||||
{ title: "Unsafe source", url: "javascript:alert(1)" },
|
||||
];
|
||||
const payload =
|
||||
shape === "webz"
|
||||
? { query: "news", returned_results: results.length, results }
|
||||
: results;
|
||||
const html = renderToolCall(
|
||||
"web_search",
|
||||
{ query: "news" },
|
||||
JSON.stringify(payload),
|
||||
);
|
||||
expect(html).toContain('href="https://example.com/first"');
|
||||
expect(html).toContain('href="https://example.com/last"');
|
||||
expect(anchorCount(html)).toBe(2);
|
||||
expect(unsafeMarkerCount(html)).toBe(1);
|
||||
expect(html).not.toContain("Invalid title");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["array", "webz"])(
|
||||
"renders source links from a %s search response",
|
||||
(shape) => {
|
||||
const results = [
|
||||
{
|
||||
title: "Renewable energy news",
|
||||
url: "https://example.com/news",
|
||||
content: "Matching passage",
|
||||
published_at: "2026-09-20T12:00:00Z",
|
||||
source: { domain: "example.com", language: "english", country: "US" },
|
||||
},
|
||||
];
|
||||
const payload =
|
||||
shape === "webz"
|
||||
? { query: "renewable energy", returned_results: 1, results }
|
||||
: results;
|
||||
const html = renderToolCall(
|
||||
"web_search",
|
||||
{ query: "renewable energy" },
|
||||
JSON.stringify(payload),
|
||||
);
|
||||
expect(html).toContain('href="https://example.com/news"');
|
||||
expect(html).toContain(">Renewable energy news</a>");
|
||||
expect(anchorCount(html)).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps unsafe links blocked inside a Webz response envelope", () => {
|
||||
const html = renderToolCall(
|
||||
"web_search",
|
||||
{ query: "news" },
|
||||
JSON.stringify({
|
||||
query: "news",
|
||||
returned_results: 1,
|
||||
results: [
|
||||
{
|
||||
title: "Unsafe source",
|
||||
url: "javascript:alert(1)",
|
||||
content: "",
|
||||
published_at: "",
|
||||
source: {},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(unsafeMarkerCount(html)).toBe(1);
|
||||
expect(anchorCount(html)).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
{ results: null },
|
||||
{ results: {} },
|
||||
{ error: "Webz request failed" },
|
||||
{ results: [] },
|
||||
])(
|
||||
"renders a search step without links for an empty or invalid envelope %j",
|
||||
(payload) => {
|
||||
const html = renderToolCall(
|
||||
"web_search",
|
||||
{ query: "news" },
|
||||
JSON.stringify(payload),
|
||||
);
|
||||
expect(html).toContain("news");
|
||||
expect(anchorCount(html)).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("renders unresolved streaming assistant text before a tool call arrives", () => {
|
||||
const html = renderGroup(
|
||||
[
|
||||
|
||||
@ -41,6 +41,18 @@ trimming its contents. Offline CLI coverage:
|
||||
|
||||
## Service Startup Contracts
|
||||
|
||||
The setup wizard offers Webz.io as a news-only `web_search` provider using
|
||||
`deerflow.community.webz.tools:web_search_tool` and `WEBZ_API_KEY`. Keep its
|
||||
entry aligned with the credential check in `doctor.py` and the example config.
|
||||
The adapter uses async HTTPS requests, offloads lazy config loading, and maps
|
||||
`source` to provider `domain`; explicit `published_from` overrides recency.
|
||||
Explicit `max_results` overrides the wizard's configured default; omission or
|
||||
null uses configuration or 5. Reject boolean/fractional configured counts before
|
||||
clamping to 1–100. `returned_results` is the normalized page size, not a match total.
|
||||
Skip malformed page entries with index-only warnings; retain valid neighbors.
|
||||
Reject malformed envelopes and nonempty pages with no valid entries, logging
|
||||
no provider payloads or credentials. Contract tests live in `backend/tests/test_webz_tools.py`.
|
||||
|
||||
Optional browser dependency detection reads the top-level `tools:` sequence
|
||||
without requiring `name` to be its first mapping key. Both indented and
|
||||
indentless lists are supported; nested option names and block-scalar text
|
||||
|
||||
@ -605,6 +605,7 @@ def check_web_tool(config_path: Path, *, tool_name: str, label: str) -> CheckRes
|
||||
"serply": "SERPLY_API_KEY",
|
||||
"sofya": "SOFYA_API_KEY",
|
||||
"tencent_wsa": "TENCENTCLOUD_WSA_APIKEY",
|
||||
"webz": "WEBZ_API_KEY",
|
||||
},
|
||||
"web_fetch": {
|
||||
"infoquest": "INFOQUEST_API_KEY",
|
||||
|
||||
@ -691,6 +691,14 @@ SEARCH_PROVIDERS: list[SearchProvider] = [
|
||||
env_var="GROUNDROUTE_API_KEY",
|
||||
extra_config={"max_results": 5},
|
||||
),
|
||||
SearchProvider(
|
||||
name="webz",
|
||||
display_name="Webz.io News Search",
|
||||
description="Recent news search (not general web search), API key required",
|
||||
use="deerflow.community.webz.tools:web_search_tool",
|
||||
env_var="WEBZ_API_KEY",
|
||||
extra_config={"max_results": 5},
|
||||
),
|
||||
]
|
||||
|
||||
WEB_FETCH_PROVIDERS: list[WebProvider] = [
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user