From 4ba34652e174408df4c962f16b2107d9a0dca5e6 Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:28:56 -1000 Subject: [PATCH 1/7] Pin diffbot 3.4.1, add validated endpoint overrides, tri-state crawl flags Bump the plugin to 0.2.0. Base URL overrides are https on diffbot.com only. Crawl robots/proxy/canonical become default|on|off selects with new field names so saved false values cannot start ignoring robots.txt. Add the crawl regex, subdomain, notify and multi-header options, plus extract job and custom API name. Co-Authored-By: Claude Sonnet 5.5 --- diffbot/manifest.yaml | 2 +- diffbot/pyproject.toml | 4 +- diffbot/requirements.txt | 2 +- diffbot/tools/crawl_start.py | 58 +++++++++++++-- diffbot/tools/crawl_start.yaml | 131 ++++++++++++++++++++++++++++++--- diffbot/tools/extract.py | 19 +++-- diffbot/tools/extract.yaml | 12 +++ diffbot/tools/sdk.py | 48 +++++++++++- 8 files changed, 248 insertions(+), 28 deletions(-) diff --git a/diffbot/manifest.yaml b/diffbot/manifest.yaml index 3bd8de9..d9c6d52 100644 --- a/diffbot/manifest.yaml +++ b/diffbot/manifest.yaml @@ -1,4 +1,4 @@ -version: 0.1.0 +version: 0.2.0 type: plugin author: diffbot name: diffbot diff --git a/diffbot/pyproject.toml b/diffbot/pyproject.toml index 991a3d9..ca10c4e 100644 --- a/diffbot/pyproject.toml +++ b/diffbot/pyproject.toml @@ -1,10 +1,10 @@ [project] name = "diffbot" -version = "0.1.0" +version = "0.2.0" description = "Diffbot web search, page extraction, and Knowledge Graph tools for Dify" readme = "README.md" requires-python = ">=3.12" dependencies = [ "dify_plugin==0.11.0", - "diffbot==3.4.0", + "diffbot==3.4.1", ] diff --git a/diffbot/requirements.txt b/diffbot/requirements.txt index 413e758..9d4f2c7 100644 --- a/diffbot/requirements.txt +++ b/diffbot/requirements.txt @@ -1,2 +1,2 @@ dify_plugin==0.11.0 -diffbot==3.4.0 +diffbot==3.4.1 diff --git a/diffbot/tools/crawl_start.py b/diffbot/tools/crawl_start.py index 961d07d..ab38781 100644 --- a/diffbot/tools/crawl_start.py +++ b/diffbot/tools/crawl_start.py @@ -1,5 +1,6 @@ """Start a Diffbot crawl job. Returns the job name, never results.""" +import re from collections.abc import Generator from typing import Any @@ -12,6 +13,29 @@ from tools.sdk import crawl_start MAX_JOB_NAME = 30 +MAX_PATTERN = 1000 +MAX_HEADERS = 10 +MAX_HEADER = 500 +_EMAIL = re.compile(r"^[^@\s,;<>]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9.\-]{0,251}[A-Za-z0-9])?\.[A-Za-z]{2,63}$") +# Tri-state flags: "default" omits the parameter so the API default applies; off sends 0. +# (Saved Dify forms keep old boolean values, so these fields have new names.) +TRI_STATE = {"default": None, "on": True, "off": False} + + +def _tri_state(parameters: dict[str, Any], name: str) -> bool | None: + value = optional_text(parameters, name).lower() or "default" + if value not in TRI_STATE: + raise DiffbotError(f"{name} must be default, on, or off.") + return TRI_STATE[value] + + +def _headers(raw: str) -> list[str]: + headers = [line.strip() for line in raw.splitlines() if line.strip()] + if len(headers) > MAX_HEADERS: + raise DiffbotError(f"Too many custom headers ({MAX_HEADERS} maximum).") + if any(len(header) > MAX_HEADER for header in headers): + raise DiffbotError(f"A custom header is too long ({MAX_HEADER} characters maximum).") + return headers def _int(parameters: dict[str, Any], name: str, *, minimum: int, maximum: int) -> int | None: @@ -40,7 +64,7 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag name = optional_text(tool_parameters, "job_name") if name: # The crawler rejects names over 30 characters with HTTP 200 + errorCode 505 - # and creates nothing; diffbot 3.2.0 does not surface that, so check here. + # and creates nothing; the SDK raises APIError for it, but check here for a clearer message. if not all(c.isalnum() or c in "-_." for c in name) or len(name) > MAX_JOB_NAME: raise DiffbotError( f"job_name may use letters, digits, '-', '_' and '.' ({MAX_JOB_NAME} characters maximum)." @@ -54,16 +78,40 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag value = _int(tool_parameters, param, minimum=low, maximum=high) if value is not None: kwargs[key] = value - for param in ("restrict_domain", "obey_robots", "use_proxies"): - if isinstance(tool_parameters.get(param), bool): - kwargs[param] = tool_parameters[param] + if isinstance(tool_parameters.get("restrict_domain"), bool): + kwargs["restrict_domain"] = tool_parameters["restrict_domain"] + for param, key in ( + ("obey_robots_mode", "obey_robots"), + ("use_proxies_mode", "use_proxies"), + ("use_canonical_mode", "use_canonical"), + ): + flag = _tri_state(tool_parameters, param) + if flag is not None: + kwargs[key] = flag + for param in ("max_to_crawl_per_subdomain", "max_to_process_per_subdomain"): + value = _int(tool_parameters, param, minimum=1, maximum=10000) + if value is not None: + kwargs[param] = value delay = tool_parameters.get("crawl_delay") if delay not in (None, ""): kwargs["crawl_delay"] = float(bounded_number(delay, label="crawl_delay", minimum=-1, maximum=3600)) - for param in ("url_crawl_pattern", "url_process_pattern", "custom_headers"): + for param in ("url_crawl_pattern", "url_process_pattern", "url_crawl_regex", "url_process_regex", "page_process_pattern"): value = optional_text(tool_parameters, param) + if len(value) > MAX_PATTERN: + raise DiffbotError(f"{param} is too long ({MAX_PATTERN} characters maximum).") if value: kwargs[param] = value + headers = _headers(optional_text(tool_parameters, "custom_headers")) + if headers: + kwargs["custom_headers"] = headers + webhook = optional_text(tool_parameters, "notify_webhook") + if webhook: + kwargs["notify_webhook"] = validate_public_http_url(webhook) + email = optional_text(tool_parameters, "notify_email") + if email: + if len(email) > 254 or not _EMAIL.fullmatch(email): + raise DiffbotError("notify_email must be a valid email address.") + kwargs["notify_email"] = email api_url = optional_text(tool_parameters, "api_url") if api_url: kwargs["api_url"] = validate_public_http_url(api_url) diff --git a/diffbot/tools/crawl_start.yaml b/diffbot/tools/crawl_start.yaml index 8a5728d..e49868c 100644 --- a/diffbot/tools/crawl_start.yaml +++ b/diffbot/tools/crawl_start.yaml @@ -105,26 +105,133 @@ parameters: human_description: en_US: Seconds between requests; -1 uses the Diffbot default. llm_description: Seconds between requests; -1 uses the Diffbot default. - - name: obey_robots - type: boolean + - name: obey_robots_mode + type: select required: false form: form - default: false + default: default label: en_US: Obey robots.txt human_description: - en_US: Respect robots.txt. - llm_description: Respect robots.txt. - - name: use_proxies - type: boolean + en_US: Diffbot default leaves the setting to the crawler (it respects robots.txt). Off ignores robots.txt; only choose that for sites you own or have permission to crawl. + llm_description: Diffbot default leaves the setting to the crawler (it respects robots.txt). Off ignores robots.txt; only choose that for sites you own or have permission to crawl. + options: + - value: default + label: + en_US: Diffbot default + - value: "on" + label: + en_US: "On" + - value: "off" + label: + en_US: "Off" + - name: use_proxies_mode + type: select required: false form: form - default: false + default: default label: en_US: Use proxies human_description: - en_US: Route requests through Diffbot proxies. - llm_description: Route requests through Diffbot proxies. + en_US: Diffbot default leaves it to the crawler (proxies off). On routes requests through Diffbot proxies. + llm_description: Diffbot default leaves it to the crawler (proxies off). On routes requests through Diffbot proxies. + options: + - value: default + label: + en_US: Diffbot default + - value: "on" + label: + en_US: "On" + - value: "off" + label: + en_US: "Off" + - name: use_canonical_mode + type: select + required: false + form: form + default: default + label: + en_US: Use canonical URLs + human_description: + en_US: Diffbot default leaves it to the crawler. On or off sets canonical-link handling explicitly. + llm_description: Diffbot default leaves it to the crawler. On or off sets canonical-link handling explicitly. + options: + - value: default + label: + en_US: Diffbot default + - value: "on" + label: + en_US: "On" + - value: "off" + label: + en_US: "Off" + - name: url_crawl_regex + type: string + required: false + form: form + label: + en_US: URL crawl regex + human_description: + en_US: "Only follow URLs matching this regular expression (1000 characters maximum)." + llm_description: "Only follow URLs matching this regular expression (1000 characters maximum)." + - name: url_process_regex + type: string + required: false + form: form + label: + en_US: URL process regex + human_description: + en_US: "Only extract URLs matching this regular expression (1000 characters maximum)." + llm_description: "Only extract URLs matching this regular expression (1000 characters maximum)." + - name: page_process_pattern + type: string + required: false + form: form + label: + en_US: Page process pattern + human_description: + en_US: "Only extract pages whose HTML contains one of these strings." + llm_description: "Only extract pages whose HTML contains one of these strings." + - name: max_to_crawl_per_subdomain + type: number + required: false + form: form + min: 1 + max: 10000 + label: + en_US: Max pages to crawl per subdomain + human_description: + en_US: "Most pages to fetch on any one subdomain (1-10000)." + llm_description: "Most pages to fetch on any one subdomain (1-10000)." + - name: max_to_process_per_subdomain + type: number + required: false + form: form + min: 1 + max: 10000 + label: + en_US: Max pages to process per subdomain + human_description: + en_US: "Most pages to extract on any one subdomain (1-10000)." + llm_description: "Most pages to extract on any one subdomain (1-10000)." + - name: notify_webhook + type: string + required: false + form: form + label: + en_US: Notify webhook URL + human_description: + en_US: "Public https URL Diffbot calls when the job finishes. Do not put secrets in the URL: it is stored with the crawl job." + llm_description: "Public https URL Diffbot calls when the job finishes. Do not put secrets in the URL: it is stored with the crawl job." + - name: notify_email + type: string + required: false + form: form + label: + en_US: Notify email + human_description: + en_US: "Email address Diffbot writes to when the job finishes. It is sent to Diffbot with the crawl job." + llm_description: "Email address Diffbot writes to when the job finishes. It is sent to Diffbot with the crawl job." - name: api_url type: string required: false @@ -141,8 +248,8 @@ parameters: label: en_US: Custom headers human_description: - en_US: "Optional header to send with each request. Do not put secrets here: the crawler sends it to the sites." - llm_description: "Optional header to send with each request. Do not put secrets here: the crawler sends it to the sites." + en_US: "Optional headers to send with each request, one per line (10 maximum). Do not put secrets here: the crawler sends them to the sites and stores them with the job." + llm_description: "Optional headers, one per line. Do not put secrets here." extra: python: source: tools/crawl_start.py diff --git a/diffbot/tools/extract.py b/diffbot/tools/extract.py index a11ba70..257085d 100644 --- a/diffbot/tools/extract.py +++ b/diffbot/tools/extract.py @@ -13,11 +13,12 @@ from tools.sdk import as_dict, extract from tools.shape import summarize_lines, trim_extract -PAGE_TYPES = {"auto", "article", "product", "discussion", "image", "video", "list", "event"} +PAGE_TYPES = {"auto", "article", "product", "discussion", "image", "video", "list", "event", "job"} +CUSTOM_API = re.compile(r"^[A-Za-z0-9_-]{1,100}$") FIELD_PATTERN = re.compile(r"^[A-Za-z0-9_.*,\-]{1,500}$") -# Value sets from the SDK 3.3.0 types (ExtractMode, ExtractFallback, UseProxy, NaturalLanguageField). +# Value sets from the diffbot 3.4.1 types (ExtractMode, ExtractFallback, UseProxy, NaturalLanguageField). MODES = {"article", "product", "discussion", "image", "video", "list", "event", "llm"} FALLBACKS = {"article", "product", "discussion", "image", "video", "list", "event"} PROXIES = {"default", "none"} @@ -36,7 +37,7 @@ def _extract_options(parameters: dict[str, Any]) -> dict[str, Any]: - """Caller-set Extract options, named as in diffbot 3.3.0; unset ones are omitted.""" + """Caller-set Extract options, named as in diffbot 3.4.1; unset ones are omitted.""" options: dict[str, Any] = {} fields = optional_text(parameters, "fields").replace(" ", "") if fields: @@ -78,8 +79,12 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag page_type = optional_text(tool_parameters, "page_type").lower() or "auto" if page_type not in PAGE_TYPES: raise DiffbotError( - "page_type must be auto, article, product, discussion, image, video, list, or event." + "page_type must be auto, article, product, discussion, image, video, list, event, or job." ) + # An already-created custom API is called by name; managing custom APIs is out of scope. + custom_api = optional_text(tool_parameters, "custom_api") + if custom_api and not CUSTOM_API.fullmatch(custom_api): + raise DiffbotError("custom_api may use letters, digits, '-' and '_' (100 characters maximum).") output_format = optional_text(tool_parameters, "format").lower() or "markdown" if output_format not in {"markdown", "json"}: raise DiffbotError("format must be markdown or json.") @@ -88,12 +93,16 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag client = make_client(self.runtime.credentials) with client, mapped_errors(client): data = as_dict( - extract(client, url, "analyze" if page_type == "auto" else page_type, output_format, options), + extract( + client, url, custom_api or ("analyze" if page_type == "auto" else page_type), output_format, options + ), "extract", ) payload = trim_extract(data) payload["url"] = url payload["page_type"] = page_type + if custom_api: + payload["custom_api"] = custom_api lines = [] for obj in payload["objects"]: title = obj.get("title") or obj.get("pageUrl") or "Extracted page" diff --git a/diffbot/tools/extract.yaml b/diffbot/tools/extract.yaml index 13a4f49..c13a6f0 100644 --- a/diffbot/tools/extract.yaml +++ b/diffbot/tools/extract.yaml @@ -59,6 +59,18 @@ parameters: - value: event label: en_US: Event + - value: job + label: + en_US: Job posting + - name: custom_api + type: string + required: false + form: form + label: + en_US: Custom API name + human_description: + en_US: Optional name of a Custom API you already created in Diffbot (letters, digits, - and _). When set it is used instead of the page type. This plugin does not create or edit Custom APIs. + llm_description: Leave empty. - name: format type: select required: false diff --git a/diffbot/tools/sdk.py b/diffbot/tools/sdk.py index 3875183..09bfcf0 100644 --- a/diffbot/tools/sdk.py +++ b/diffbot/tools/sdk.py @@ -1,7 +1,7 @@ """Builds the Diffbot SDK client and adapts it to this plugin's policy. The plugin runs on the ``diffbot`` Python SDK (sync ``Diffbot`` client), pinned to -``diffbot==3.4.0``. Every call goes through the guarded transport built here, and SDK +``diffbot==3.4.1``. Every call goes through the guarded transport built here, and SDK errors are mapped to token-free plugin messages. """ @@ -11,6 +11,7 @@ import io import json import urllib.request +from urllib.parse import urlparse from collections.abc import Iterator, Mapping from contextlib import contextmanager from typing import Any, cast @@ -92,13 +93,56 @@ def parse_timeout(value: Any) -> float: return seconds +BASE_FIELDS = { + "api_base": "api_base", + "kg_base": "kg_base", + "llm_base": "llm_base", + "nlp_base": "nlp_base", +} +ALLOWED_BASE_DOMAIN = "diffbot.com" + + +def validate_base_url(value: str, label: str) -> str: + """Check an endpoint-override base: https, a Diffbot host, nothing else. + + The token travels to these hosts, so only ``diffbot.com`` and its subdomains pass. + The trailing slash is stripped because the SDK appends paths directly. + """ + value = value.strip() + if len(value) > 2048: + raise DiffbotError(f"{label} is too long.") + parsed = urlparse(value) + if parsed.scheme != "https": + raise DiffbotError(f"{label} must start with https://.") + if parsed.username or parsed.password: + raise DiffbotError(f"{label} must not include a username or password.") + if parsed.query or parsed.fragment or parsed.params: + raise DiffbotError(f"{label} must not include a query string or fragment.") + try: + port = parsed.port + except ValueError: + raise DiffbotError(f"{label} has an invalid port.") from None + if port not in (None, 443): + raise DiffbotError(f"{label} must use the default https port.") + host = (parsed.hostname or "").rstrip(".").lower() + check_public_host(host) + if host != ALLOWED_BASE_DOMAIN and not host.endswith("." + ALLOWED_BASE_DOMAIN): + raise DiffbotError(f"{label} must be a diffbot.com host.") + return value.rstrip("/") + + def make_client(credentials: Mapping[str, Any] | None, *, transport: httpx.BaseTransport | None = None) -> Diffbot: """Validate the credential form and return an SDK client behind the host guard.""" credentials = credentials or {} raw = credentials.get("diffbot_token", "") token = normalize_token(raw if isinstance(raw, str) else "") timeout = parse_timeout(credentials.get("request_timeout")) - return Diffbot(token, timeout=timeout, transport=GuardedTransport(transport)) + bases: dict[str, str] = {} + for field in BASE_FIELDS: + value = credentials.get(field) + if isinstance(value, str) and value.strip(): + bases[field] = validate_base_url(value, field) + return Diffbot(token, timeout=timeout, transport=GuardedTransport(transport), **bases) def api_error_message(exc: BaseException, token: str) -> str: From 808bc5243963fa44db3a502bff0ad8435006f097 Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:28:56 -1000 Subject: [PATCH 2/7] Add raw DQL and ontology tools, count_only, multi-query web search kg_query scrubs email/phone/html from JSON and caps output; kg_ontology uses a process-wide cache keyed by ontology URL. Organization industry is resolved against the OrganizationCategory taxonomy. Co-Authored-By: Claude Sonnet 5.5 --- diffbot/tools/common.py | 43 ++++- diffbot/tools/industry.py | 37 ++++ diffbot/tools/kg_ontology.py | 101 +++++++++++ diffbot/tools/kg_ontology.yaml | 84 +++++++++ diffbot/tools/kg_query.py | 140 +++++++++++++++ diffbot/tools/kg_query.yaml | 221 ++++++++++++++++++++++++ diffbot/tools/ontology_cache.py | 86 +++++++++ diffbot/tools/resolve_entities.yaml | 4 +- diffbot/tools/search_news.py | 9 +- diffbot/tools/search_news.yaml | 10 ++ diffbot/tools/search_organizations.py | 12 +- diffbot/tools/search_organizations.yaml | 12 +- diffbot/tools/search_people.py | 9 +- diffbot/tools/search_people.yaml | 10 ++ diffbot/tools/search_web.py | 20 ++- diffbot/tools/search_web.yaml | 36 ++++ diffbot/tools/shape.py | 45 +++++ 17 files changed, 859 insertions(+), 20 deletions(-) create mode 100644 diffbot/tools/industry.py create mode 100644 diffbot/tools/kg_ontology.py create mode 100644 diffbot/tools/kg_ontology.yaml create mode 100644 diffbot/tools/kg_query.py create mode 100644 diffbot/tools/kg_query.yaml create mode 100644 diffbot/tools/ontology_cache.py diff --git a/diffbot/tools/common.py b/diffbot/tools/common.py index a4aa702..1db104b 100644 --- a/diffbot/tools/common.py +++ b/diffbot/tools/common.py @@ -19,14 +19,18 @@ def optional_text(parameters: dict[str, Any], name: str) -> str: return str(value).strip() -def result_size(parameters: dict[str, Any], *, default: int, maximum: int) -> int: +def result_size(parameters: dict[str, Any], *, default: int, maximum: int, minimum: int = 1) -> int: value = parameters.get("size") if value is None or value == "": return default - number = bounded_number(value, label="size", minimum=1, maximum=maximum, integer=True) + number = bounded_number(value, label="size", minimum=minimum, maximum=maximum, integer=True) return int(number) +def is_count_only(parameters: dict[str, Any]) -> bool: + return parameters.get("count_only") is True + + def result_offset(parameters: dict[str, Any]) -> int: value = parameters.get("offset") if value is None or value == "": @@ -34,15 +38,44 @@ def result_offset(parameters: dict[str, Any]) -> int: return int(bounded_number(value, label="offset", minimum=0, maximum=100000, integer=True)) -def run_dql(credentials: dict[str, Any] | None, query: str, *, size: int, offset: int) -> dict[str, Any]: - """Run a DQL query through the SDK (POST) and record the query that ran.""" +def fetch_dql( + credentials: dict[str, Any] | None, + query: str, + *, + size: int, + offset: int, + format: str = "json", + **options: Any, +) -> Any: + """Run a DQL query through the SDK (POST). ``options`` are the SDK's named DQL options + (``type``, ``col``, ``filter``, ``filter_exclude``, ``exportspec``, ...); ``None`` is unset. + + The result depends on ``format``: json -> dict, jsonl -> materialized list of entities, + csv -> str, xls/xlsx -> bytes. Materializing happens inside the guarded client. + """ client = make_client(credentials) with client, mapped_errors(client): - data = as_dict(client.dql(query, size=size, from_=offset), "Knowledge Graph search") + result = client.dql(query, size=size, from_=offset, format=format, **options) # type: ignore[call-overload] + if format == "jsonl": + result = list(result) + return result + + +def run_dql(credentials: dict[str, Any] | None, query: str, *, size: int, offset: int, **options: Any) -> dict[str, Any]: + """Run a JSON DQL query through the SDK and record the query that ran.""" + data = as_dict( + fetch_dql(credentials, query, size=size, offset=offset, **options), + "Knowledge Graph search", + ) data["dql"] = query return data +def count_payload(data: dict[str, Any]) -> dict[str, Any]: + """Result shape for ``count_only``: the query and its hit count, no rows.""" + return {"dql": data.get("dql"), "hits": data.get("hits")} + + def messages(tool: Any, summary: str, payload: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: yield tool.create_text_message(clip(summary)) yield tool.create_json_message(payload) diff --git a/diffbot/tools/industry.py b/diffbot/tools/industry.py new file mode 100644 index 0000000..79e5dd3 --- /dev/null +++ b/diffbot/tools/industry.py @@ -0,0 +1,37 @@ +"""Resolve a free-text industry to a Knowledge Graph ``OrganizationCategory`` name.""" + +from __future__ import annotations + +import difflib +from typing import Any + +from tools.client import DiffbotError +from tools.ontology_cache import load_ontology + +TAXONOMY = "OrganizationCategory" + + +def resolve_industry(credentials: dict[str, Any] | None, industry: str) -> str: + """Exact match first, then case-insensitive; otherwise fail with close suggestions. + + If the ontology cannot be fetched the text is passed through unchanged, so a + temporary outage does not block searches that would otherwise work. + """ + try: + values = load_ontology(credentials).taxonomy_values(TAXONOMY) + except (DiffbotError, KeyError): + return industry + if industry in values: + return industry + lowered = {value.lower(): value for value in values} + if industry.lower() in lowered: + return lowered[industry.lower()] + needle = industry.lower() + contains = [value for value in values if needle in value.lower()] + close = difflib.get_close_matches(industry, values, n=5, cutoff=0.5) + suggestions = list(dict.fromkeys(contains[:5] + close))[:5] + hint = f" Did you mean: {', '.join(suggestions)}?" if suggestions else "" + raise DiffbotError( + f'"{industry}" is not a Knowledge Graph industry category.{hint} ' + "Use the Knowledge Graph ontology tool (taxonomy_values, OrganizationCategory) to list valid names." + ) diff --git a/diffbot/tools/kg_ontology.py b/diffbot/tools/kg_ontology.py new file mode 100644 index 0000000..640bc1b --- /dev/null +++ b/diffbot/tools/kg_ontology.py @@ -0,0 +1,101 @@ +"""Look up Knowledge Graph entity types, fields, enums, and taxonomy values.""" + +import re +from collections.abc import Generator +from typing import Any + +from dify_plugin import Tool +from dify_plugin.entities.tool import ToolInvokeMessage + +from tools.client import DiffbotError +from tools.common import make_client, mapped_errors, messages, optional_text +from tools.ontology_cache import load_ontology +from tools.shape import summarize_lines + +LOOKUPS = { + "types", "composites", "enums", "taxonomies", + "fields", "taxonomy_values", "enum_values", "find", "raw_file", +} +MAX_SEARCH = 200 +MAX_NAME = 100 +MAX_ITEMS = 500 +_NAME = re.compile(r"^[A-Za-z0-9_.\- ]{1,100}$") + + +def _literal(search: str) -> str | None: + """The caller's search as a literal (escaped) pattern, so it cannot be a regex bomb.""" + if not search: + return None + if len(search) > MAX_SEARCH: + raise DiffbotError(f"search is too long ({MAX_SEARCH} characters maximum).") + return re.escape(search) + + +def _capped(items: list[Any]) -> tuple[list[Any], bool]: + return items[:MAX_ITEMS], len(items) > MAX_ITEMS + + +class KgOntologyTool(Tool): + def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: + lookup = optional_text(tool_parameters, "lookup").lower() or "types" + if lookup not in LOOKUPS: + raise DiffbotError(f"lookup must be one of: {', '.join(sorted(LOOKUPS))}.") + name = optional_text(tool_parameters, "name") + if name and not _NAME.fullmatch(name): + raise DiffbotError("name may use letters, digits, '_', '.', '-' and spaces (100 characters maximum).") + search = _literal(optional_text(tool_parameters, "search")) + include_deprecated = tool_parameters.get("include_deprecated") is True + + if lookup == "raw_file": + client = make_client(self.runtime.credentials) + with client, mapped_errors(client): + text = client.dql_fetch_ontology_text() + blob = text.encode("utf-8") + yield self.create_blob_message(blob, meta={"mime_type": "application/json", "filename": "diffbot-ontology.json"}) + yield from messages(self, f"Diffbot ontology document ({len(blob)} bytes) attached.", {"bytes": len(blob)}) + return + + ontology = load_ontology(self.runtime.credentials) + payload: dict[str, Any] = {"lookup": lookup} + lines: list[str] = [] + try: + if lookup in ("types", "composites", "enums", "taxonomies"): + names = getattr(ontology, lookup)() + if search: + pattern = re.compile(search, re.IGNORECASE) + names = [n for n in names if pattern.search(n)] + names, truncated = _capped(names) + payload.update(names=names, truncated=truncated) + lines = [f"- {n}" for n in names] + elif lookup == "fields": + if not name: + raise DiffbotError("name (an entity type or composite such as Organization) is required for fields.") + rows = ontology.filter_fields(ontology.fields_for(name), search, include_deprecated) + rows, truncated = _capped(rows) + fields = [ + {"name": field, "description": ontology.format_field(field, meta), "deprecated": bool(meta.get("isDeprecated"))} + for field, meta in rows + ] + payload.update(name=name, fields=fields, truncated=truncated) + lines = [f"- {item['description']}" for item in fields] + elif lookup == "taxonomy_values": + if not name: + raise DiffbotError("name (a taxonomy such as OrganizationCategory) is required for taxonomy_values.") + values, truncated = _capped(ontology.taxonomy_values(name, search)) + payload.update(name=name, values=values, truncated=truncated) + lines = [f"- {v}" for v in values] + elif lookup == "enum_values": + if not name: + raise DiffbotError("name (an enum such as Language) is required for enum_values.") + values, truncated = _capped(ontology.enum_values(name)) + payload.update(name=name, values=values, truncated=truncated) + lines = [f"- {v}" for v in values] + else: # find + if not search: + raise DiffbotError("search is required for find.") + names, truncated = _capped(ontology.find_named(search)) + payload.update(names=names, truncated=truncated) + lines = [f"- {n}" for n in names] + except KeyError as exc: + raise DiffbotError(f"Not found in the ontology: {exc.args[0] if exc.args else name}") from None + yield from messages(self, summarize_lines(f"Ontology lookup {lookup}.", lines), payload) diff --git a/diffbot/tools/kg_ontology.yaml b/diffbot/tools/kg_ontology.yaml new file mode 100644 index 0000000..fb065b6 --- /dev/null +++ b/diffbot/tools/kg_ontology.yaml @@ -0,0 +1,84 @@ +identity: + name: kg_ontology + author: diffbot + label: + en_US: Knowledge Graph ontology +description: + human: + en_US: Look up the Diffbot Knowledge Graph schema (entity types, field names, enums, and taxonomy values such as organization categories) before writing a DQL query. The ontology is a public document; no token is sent to fetch it. + llm: > + Look up the Diffbot Knowledge Graph ontology so DQL uses real names. lookup types, composites, enums, + or taxonomies lists names. lookup fields with name (for example Organization or Location) lists field + paths and types. lookup taxonomy_values with name OrganizationCategory lists valid industry category names. + lookup enum_values lists the allowed values of an enum. lookup find searches every name in the ontology. + search is a plain case-insensitive substring, not a regular expression. +parameters: + - name: lookup + type: select + required: true + form: llm + default: types + label: + en_US: Lookup + human_description: + en_US: What to list. fields, taxonomy_values and enum_values need a name. find and raw_file ignore name. + llm_description: One of types, composites, enums, taxonomies, fields, taxonomy_values, enum_values, find. raw_file attaches the whole document and is for workflow builders. + options: + - value: types + label: + en_US: Entity types + - value: composites + label: + en_US: Composite types + - value: enums + label: + en_US: Enums + - value: taxonomies + label: + en_US: Taxonomies + - value: fields + label: + en_US: Fields of a type + - value: taxonomy_values + label: + en_US: Taxonomy values + - value: enum_values + label: + en_US: Enum values + - value: find + label: + en_US: Find a name + - value: raw_file + label: + en_US: Raw ontology file + - name: name + type: string + required: false + form: llm + label: + en_US: Name + human_description: + en_US: Type, composite, taxonomy or enum name for fields, taxonomy_values and enum_values. + llm_description: Type or composite name (Organization, Person, Location), taxonomy name (OrganizationCategory), or enum name. Case-sensitive. + - name: search + type: string + required: false + form: llm + label: + en_US: Search + human_description: + en_US: Case-insensitive text to look for in names (200 characters maximum). Not a regular expression. + llm_description: Case-insensitive substring to filter names (200 characters maximum). Required for find. + - name: include_deprecated + type: boolean + required: false + form: form + default: false + label: + en_US: Include deprecated fields + human_description: + en_US: Also list fields the ontology marks as deprecated (fields lookup only). + llm_description: Also list deprecated fields. Default false. +extra: + python: + source: tools/kg_ontology.py diff --git a/diffbot/tools/kg_query.py b/diffbot/tools/kg_query.py new file mode 100644 index 0000000..810148f --- /dev/null +++ b/diffbot/tools/kg_query.py @@ -0,0 +1,140 @@ +"""Raw Diffbot Query Language (DQL) search over the Knowledge Graph.""" + +import re +from collections.abc import Generator +from typing import Any + +from dify_plugin import Tool +from dify_plugin.entities.tool import ToolInvokeMessage + +from tools.client import DiffbotError +from tools.common import count_payload, fetch_dql, is_count_only, messages, optional_text, result_offset, result_size +from tools.shape import fit_rows, scrub_private, summarize_lines + +MAX_QUERY = 10_000 +MAX_OPTION = 2_000 +OUTPUT_LIMIT = 200_000 # characters of JSON returned to the model +EXPORT_LIMIT = 25 * 1024 * 1024 # bytes of a csv/xls/xlsx export file +TYPES = {"query", "text", "queryTextFallback", "crawl"} +JSONMODES = {"extended", "id"} +CLUSTERS = {"all", "best", "dedupe"} +FORMATS = {"json", "jsonl", "csv", "xls", "xlsx"} +FILE_FORMATS = { + "csv": "text/csv", + "xls": "application/vnd.ms-excel", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", +} +_FILENAME = re.compile(r"^[A-Za-z0-9_\-]{1,80}$") + + +def _choice(parameters: dict[str, Any], name: str, allowed: set[str]) -> str | None: + value = optional_text(parameters, name) + if not value: + return None + if value not in allowed: + raise DiffbotError(f"{name} must be one of: {', '.join(sorted(allowed))}.") + return value + + +def _text(parameters: dict[str, Any], name: str, limit: int = MAX_OPTION) -> str | None: + value = optional_text(parameters, name) + if not value: + return None + if len(value) > limit: + raise DiffbotError(f"{name} is too long ({limit} characters maximum).") + return value + + +def _flag(parameters: dict[str, Any], name: str) -> bool | None: + return True if parameters.get(name) is True else None # false is the API default + + +class KgQueryTool(Tool): + def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: + query = optional_text(tool_parameters, "query") + if not query: + raise DiffbotError("A DQL query is required.") + if len(query) > MAX_QUERY: + raise DiffbotError(f"The DQL query is too long ({MAX_QUERY} characters maximum).") + + fmt = _choice(tool_parameters, "format", FORMATS) or "json" + size = result_size(tool_parameters, default=10, maximum=100, minimum=0) + count_only = is_count_only(tool_parameters) or size == 0 + if count_only: + size, fmt = 0, "json" # a count needs no rows or export file + + separator = tool_parameters.get("exportseparator") + separator = None if separator in (None, "") else str(separator) + if separator is not None: + separator = "\t" if separator.lower() in ("tab", "\\t") else separator + if len(separator) > 5: + raise DiffbotError("exportseparator is too long.") + if separator and fmt != "csv": + raise DiffbotError("exportseparator applies to csv format only.") + filename = optional_text(tool_parameters, "exportfile") + if filename and not _FILENAME.fullmatch(filename): + raise DiffbotError("exportfile may use letters, digits, '-' and '_' (80 characters maximum).") + + options: dict[str, Any] = { + "type": _choice(tool_parameters, "type", TYPES), + "col": _text(tool_parameters, "col"), + "filter": _text(tool_parameters, "filter"), + "filter_exclude": _text(tool_parameters, "filter_exclude"), + "exportspec": _text(tool_parameters, "exportspec"), + "exportseparator": separator, + "jsonmode": _choice(tool_parameters, "jsonmode", JSONMODES), + "non_canonical_facts": _flag(tool_parameters, "non_canonical_facts"), + "no_dedup_articles": _flag(tool_parameters, "no_dedup_articles"), + "cluster": _choice(tool_parameters, "cluster", CLUSTERS), + } + # exportfile is deliberately not sent: a server-side file name means nothing in Dify. + data = fetch_dql( + self.runtime.credentials, + query, + size=size, + offset=result_offset(tool_parameters), + format=fmt, + **options, + ) + + if fmt in FILE_FORMATS: + blob = data.encode("utf-8") if isinstance(data, str) else data + if not isinstance(blob, (bytes, bytearray)): + raise DiffbotError("Diffbot Knowledge Graph search returned an unexpected response.") + if len(blob) > EXPORT_LIMIT: + raise DiffbotError("The export file is too large. Lower size or add a filter.") + name = f"{filename or 'diffbot-dql'}.{fmt}" + yield self.create_blob_message(bytes(blob), meta={"mime_type": FILE_FORMATS[fmt], "filename": name}) + note = "Export files are returned as Diffbot sent them and are not scrubbed of contact fields." + yield from messages( + self, + f"DQL {fmt} export attached as {name} ({len(blob)} bytes). {note}", + {"dql": query, "format": fmt, "filename": name, "bytes": len(blob), "scrubbed": False, "note": note}, + ) + return + + if fmt == "jsonl": + rows, truncated = fit_rows([scrub_private(row) for row in data], OUTPUT_LIMIT) + payload: dict[str, Any] = { + "dql": query, "format": "jsonl", "returned": len(rows), "truncated": truncated, "results": rows, + } + else: + if not isinstance(data, dict): + raise DiffbotError("Diffbot Knowledge Graph search returned an unexpected response.") + data = {**data, "dql": query} + if count_only: + payload = {**count_payload(data), "count_only": True} + else: + payload = scrub_private(data) + rows, truncated = fit_rows(payload.get("data") or [], OUTPUT_LIMIT) + if isinstance(payload.get("data"), list): + payload["data"] = rows + payload["returned"] = len(rows) + payload["truncated"] = truncated + lines = [] + if payload.get("hits") is not None: + lines.append(f"hits: {payload['hits']}") + if payload.get("truncated"): + lines.append(f"Output was cut at {OUTPUT_LIMIT} characters; lower size or narrow the query.") + title = "DQL count" if count_only else f"DQL returned {payload.get('returned', 0)} record(s)" + yield from messages(self, summarize_lines(title + ".", lines), payload) diff --git a/diffbot/tools/kg_query.yaml b/diffbot/tools/kg_query.yaml new file mode 100644 index 0000000..6d27d0f --- /dev/null +++ b/diffbot/tools/kg_query.yaml @@ -0,0 +1,221 @@ +identity: + name: kg_query + author: diffbot + label: + en_US: Knowledge Graph query (DQL) +description: + human: + en_US: Run a raw Diffbot Query Language (DQL) query against the Knowledge Graph. Use Search organizations, people, or news for simple lookups, and the Knowledge Graph ontology tool to find real field names. JSON output drops email, phone and html fields; csv, xls and xlsx export files are returned as Diffbot sent them and are not scrubbed. + llm: > + Run a raw DQL query against the Diffbot Knowledge Graph, for example + type:Organization name:"Diffbot" or type:Article tags.label:"Artificial Intelligence" sortBy:date. + Look up valid field names and taxonomy values with the Knowledge Graph ontology tool first. + Set count_only true to get just the number of matches (hits). Otherwise size is 0 to 100 (default 10). + Raw entities can be large, so keep size small and use col to choose columns. Email, phone and html + fields are removed from the output. Do not send secrets in the query. +parameters: + - name: query + type: string + required: true + form: llm + label: + en_US: DQL query + human_description: + en_US: The DQL query (10000 characters maximum), for example type:Organization location.country.name:"Japan". + llm_description: A DQL query string, at most 10000 characters. Quote values and use real field names from the ontology. + placeholder: + en_US: type:Organization name:"Diffbot" + - name: count_only + type: boolean + required: false + form: llm + default: false + label: + en_US: Count only + human_description: + en_US: "Return only the number of matches (hits), no records." + llm_description: "Return only the number of matches (hits), no records." + - name: size + type: number + required: false + form: llm + default: 10 + min: 0 + max: 100 + label: + en_US: Maximum results + human_description: + en_US: "How many records to return, from 0 to 100. Ignored when Count only is on." + llm_description: "Result cap from 0 to 100. Default 10. 0 returns only the hit count." + - name: offset + type: number + required: false + form: llm + default: 0 + min: 0 + max: 100000 + label: + en_US: Offset + human_description: + en_US: "Skip this many results first (0 to 100000). Sent to Diffbot as from." + llm_description: "Number of results to skip, 0 to 100000. Default 0." + - name: type + type: select + required: false + form: llm + label: + en_US: Query type + human_description: + en_US: "How Diffbot interprets the query: query (DQL), text, queryTextFallback or crawl." + llm_description: "query, text, queryTextFallback, or crawl. Leave empty for the default." + options: + - value: query + label: + en_US: query + - value: text + label: + en_US: text + - value: queryTextFallback + label: + en_US: queryTextFallback + - value: crawl + label: + en_US: crawl + - name: col + type: string + required: false + form: llm + label: + en_US: Columns + human_description: + en_US: "Comma-separated fields to return instead of the whole entity." + llm_description: "Comma-separated field paths to return (smaller output). Leave empty for whole entities." + - name: filter + type: string + required: false + form: llm + label: + en_US: Filter + human_description: + en_US: "Extra DQL filter applied to the results." + llm_description: "Optional extra filter expression applied to the results." + - name: filter_exclude + type: string + required: false + form: llm + label: + en_US: Exclude filter + human_description: + en_US: "Fields to leave out of each record (Diffbot filterExclude)." + llm_description: "Optional comma-separated fields to leave out of each record." + - name: format + type: select + required: false + form: form + default: json + label: + en_US: Output format + human_description: + en_US: "json and jsonl come back as data with email, phone and html removed. csv, xls and xlsx come back as a file that is NOT scrubbed." + llm_description: "json and jsonl come back as data with email, phone and html removed. csv, xls and xlsx come back as a file that is NOT scrubbed." + options: + - value: json + label: + en_US: json + - value: jsonl + label: + en_US: jsonl + - value: csv + label: + en_US: csv + - value: xls + label: + en_US: xls + - value: xlsx + label: + en_US: xlsx + - name: exportspec + type: string + required: false + form: form + label: + en_US: Export spec + human_description: + en_US: "Column spec for csv, xls and xlsx exports." + llm_description: "Column spec for csv, xls and xlsx exports." + - name: exportseparator + type: string + required: false + form: form + label: + en_US: CSV separator + human_description: + en_US: "Field separator for csv format only (use tab for a tab)." + llm_description: "Field separator for csv format only (use tab for a tab)." + - name: exportfile + type: string + required: false + form: form + label: + en_US: Export file name + human_description: + en_US: "Name for the attached export file, without extension (letters, digits, - and _). Not sent to Diffbot." + llm_description: "Name for the attached export file, without extension (letters, digits, - and _). Not sent to Diffbot." + - name: jsonmode + type: select + required: false + form: form + label: + en_US: JSON mode + human_description: + en_US: "extended returns full linked entities; id returns ids only." + llm_description: "extended returns full linked entities; id returns ids only." + options: + - value: extended + label: + en_US: extended + - value: id + label: + en_US: id + - name: non_canonical_facts + type: boolean + required: false + form: form + default: false + label: + en_US: Non-canonical facts + human_description: + en_US: "Include facts that are not the canonical value." + llm_description: "Include facts that are not the canonical value." + - name: no_dedup_articles + type: boolean + required: false + form: form + default: false + label: + en_US: Keep duplicate articles + human_description: + en_US: "Do not de-duplicate article results." + llm_description: "Do not de-duplicate article results." + - name: cluster + type: select + required: false + form: form + label: + en_US: Article clustering + human_description: + en_US: "Article queries only: return all, the best, or one deduplicated article per cluster." + llm_description: "Article queries only: return all, the best, or one deduplicated article per cluster." + options: + - value: all + label: + en_US: all + - value: best + label: + en_US: best + - value: dedupe + label: + en_US: dedupe +extra: + python: + source: tools/kg_query.py diff --git a/diffbot/tools/ontology_cache.py b/diffbot/tools/ontology_cache.py new file mode 100644 index 0000000..07528a7 --- /dev/null +++ b/diffbot/tools/ontology_cache.py @@ -0,0 +1,86 @@ +"""Process-wide cache of the Knowledge Graph ontology. + +The ontology document is public: the SDK fetches it without a token, so it is the same +for every credential and differs only by URL. One parsed ``Ontology`` per resolved URL is +held for 24 hours. A failed refresh serves the stale copy, and after a failed fetch with +nothing to serve the cache backs off for about five minutes instead of refetching on every call. +""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +from diffbot import Diffbot +from diffbot.ontology import Ontology + +from tools.client import DiffbotError +from tools.sdk import make_client, mapped_errors + +TTL_SECONDS = 24 * 60 * 60 +BACKOFF_SECONDS = 5 * 60 + + +@dataclass +class _Entry: + ontology: Ontology | None = None + fetched_at: float = 0.0 + retry_after: float = 0.0 + + +class OntologyCache: + def __init__( + self, + clock: Callable[[], float] = time.monotonic, + ttl: float = TTL_SECONDS, + backoff: float = BACKOFF_SECONDS, + ) -> None: + self._clock = clock + self._ttl = ttl + self._backoff = backoff + self._lock = threading.Lock() + self._entries: dict[str, _Entry] = {} + + def get(self, client: Diffbot) -> Ontology: + """Return the ontology for ``client.ontology_url``, fetching at most once per TTL. + + The lock is held across the fetch so concurrent callers share one download. + """ + url = client.ontology_url + with self._lock: + now = self._clock() + entry = self._entries.setdefault(url, _Entry()) + if entry.ontology is not None and now - entry.fetched_at < self._ttl: + return entry.ontology + if now < entry.retry_after: + if entry.ontology is not None: + return entry.ontology + raise DiffbotError("The Knowledge Graph ontology is temporarily unavailable. Try again in a few minutes.") + try: + ontology = client.dql_fetch_ontology() + except Exception: + entry.retry_after = now + self._backoff + if entry.ontology is not None: + return entry.ontology # stale beats nothing + raise + entry.ontology = ontology + entry.fetched_at = now + entry.retry_after = 0.0 + return ontology + + def clear(self) -> None: + with self._lock: + self._entries.clear() + + +CACHE = OntologyCache() + + +def load_ontology(credentials: dict[str, Any] | None, cache: OntologyCache | None = None) -> Ontology: + """Fetch (or reuse) the ontology through the normal guarded client.""" + client = make_client(credentials) # a valid-format token is required even though none is sent + with client, mapped_errors(client): + return (cache or CACHE).get(client) diff --git a/diffbot/tools/resolve_entities.yaml b/diffbot/tools/resolve_entities.yaml index 0de33a3..01a5126 100644 --- a/diffbot/tools/resolve_entities.yaml +++ b/diffbot/tools/resolve_entities.yaml @@ -9,8 +9,8 @@ description: llm: > Run Diffbot natural language entity recognition on plain text. Returns each mention's name, types, confidence, salience, sentiment, and Knowledge Graph id when linked. - Also returns dql_filter, an id:or(...) clause. This v1 plugin does not execute that clause; - use Search organizations, Search people, or a later raw DQL tool with the ids. + Also returns dql_filter, an id:or(...) clause. Pass it to the Knowledge Graph query (DQL) + tool to look up those records, or use Search organizations or Search people. Maximum 20000 characters. Do not send secrets, credentials, or private messages. parameters: - name: text diff --git a/diffbot/tools/search_news.py b/diffbot/tools/search_news.py index ccbdae9..a98e59c 100644 --- a/diffbot/tools/search_news.py +++ b/diffbot/tools/search_news.py @@ -6,7 +6,7 @@ from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage -from tools.common import messages, optional_text, result_offset, result_size, run_dql +from tools.common import count_payload, is_count_only, messages, optional_text, result_offset, result_size, run_dql from tools.dql_builder import build_news_query from tools.shape import summarize_lines, trim_kg @@ -23,9 +23,14 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag "until": optional_text(tool_parameters, "until"), } query = build_news_query(parameters) - size = result_size(tool_parameters, default=5, maximum=100) + count_only = is_count_only(tool_parameters) + size = 0 if count_only else result_size(tool_parameters, default=5, maximum=100) include_text = bool(tool_parameters.get("include_text")) data = run_dql(self.runtime.credentials, query, size=size, offset=result_offset(tool_parameters)) + if count_only: + payload = count_payload(data) + yield from messages(self, f"{payload['hits']} matching article record(s) in the Knowledge Graph.", payload) + return payload = trim_kg(data, "article", include_text=include_text, limit=size) lines = [] for index, row in enumerate(payload["results"], start=1): diff --git a/diffbot/tools/search_news.yaml b/diffbot/tools/search_news.yaml index a204347..55b8661 100644 --- a/diffbot/tools/search_news.yaml +++ b/diffbot/tools/search_news.yaml @@ -86,6 +86,16 @@ parameters: human_description: en_US: Include a truncated article body. Off by default. llm_description: When true, each result includes a truncated text field. Default false. + - name: count_only + type: boolean + required: false + form: llm + default: false + label: + en_US: Count only + human_description: + en_US: Return only the number of matches (hits), with no records. + llm_description: Set true to get only the number of matching records. Default false. - name: size type: number required: false diff --git a/diffbot/tools/search_organizations.py b/diffbot/tools/search_organizations.py index 55a41b0..aa756d3 100644 --- a/diffbot/tools/search_organizations.py +++ b/diffbot/tools/search_organizations.py @@ -6,7 +6,8 @@ from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage -from tools.common import messages, optional_text, result_offset, result_size, run_dql +from tools.common import count_payload, is_count_only, messages, optional_text, result_offset, result_size, run_dql +from tools.industry import resolve_industry from tools.dql_builder import build_organizations_query from tools.shape import summarize_lines, trim_kg @@ -25,9 +26,16 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag "max_revenue": tool_parameters.get("max_revenue"), "is_public": optional_text(tool_parameters, "is_public").lower() or "any", } + if parameters["industry"]: + parameters["industry"] = resolve_industry(self.runtime.credentials, parameters["industry"]) query = build_organizations_query(parameters) - size = result_size(tool_parameters, default=5, maximum=100) + count_only = is_count_only(tool_parameters) + size = 0 if count_only else result_size(tool_parameters, default=5, maximum=100) data = run_dql(self.runtime.credentials, query, size=size, offset=result_offset(tool_parameters)) + if count_only: + payload = count_payload(data) + yield from messages(self, f"{payload['hits']} matching organization record(s) in the Knowledge Graph.", payload) + return payload = trim_kg(data, "organization", limit=size) lines = [] for index, row in enumerate(payload["results"], start=1): diff --git a/diffbot/tools/search_organizations.yaml b/diffbot/tools/search_organizations.yaml index 291140b..dc84c95 100644 --- a/diffbot/tools/search_organizations.yaml +++ b/diffbot/tools/search_organizations.yaml @@ -8,7 +8,7 @@ description: en_US: Find companies and other organizations in the Diffbot Knowledge Graph by name, homepage, industry category, headquarters, headcount, revenue, or public-company status. llm: > Search Diffbot Knowledge Graph organizations. Use this for firmographic facts, not for general web search. - Industry must match a Knowledge Graph category name such as "Software Companies"; free text often misses. + Industry is matched against Knowledge Graph category names such as "Software Companies" (case-insensitive); a miss returns suggestions. Set count_only to get just the number of matches. Revenue values are the raw revenue.value numbers, typically US dollars, not strings like 10M. At least one filter is required. Results omit employee rosters and contact details. parameters: @@ -117,6 +117,16 @@ parameters: - value: "false" label: en_US: Not public + - name: count_only + type: boolean + required: false + form: llm + default: false + label: + en_US: Count only + human_description: + en_US: Return only the number of matches (hits), with no records. + llm_description: Set true to get only the number of matching records. Default false. - name: size type: number required: false diff --git a/diffbot/tools/search_people.py b/diffbot/tools/search_people.py index 44272df..172fcb8 100644 --- a/diffbot/tools/search_people.py +++ b/diffbot/tools/search_people.py @@ -6,7 +6,7 @@ from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage -from tools.common import messages, optional_text, result_offset, result_size, run_dql +from tools.common import count_payload, is_count_only, messages, optional_text, result_offset, result_size, run_dql from tools.dql_builder import build_people_query from tools.shape import summarize_lines, trim_kg @@ -21,8 +21,13 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag "country": optional_text(tool_parameters, "country"), } query = build_people_query(parameters) - size = result_size(tool_parameters, default=5, maximum=100) + count_only = is_count_only(tool_parameters) + size = 0 if count_only else result_size(tool_parameters, default=5, maximum=100) data = run_dql(self.runtime.credentials, query, size=size, offset=result_offset(tool_parameters)) + if count_only: + payload = count_payload(data) + yield from messages(self, f"{payload['hits']} matching person record(s) in the Knowledge Graph.", payload) + return payload = trim_kg(data, "person", limit=size) lines = [] for index, row in enumerate(payload["results"], start=1): diff --git a/diffbot/tools/search_people.yaml b/diffbot/tools/search_people.yaml index 195e4af..74daad4 100644 --- a/diffbot/tools/search_people.yaml +++ b/diffbot/tools/search_people.yaml @@ -58,6 +58,16 @@ parameters: human_description: en_US: Country on the public profile. llm_description: location.country.name. + - name: count_only + type: boolean + required: false + form: llm + default: false + label: + en_US: Count only + human_description: + en_US: Return only the number of matches (hits), with no records. + llm_description: Set true to get only the number of matching records. Default false. - name: size type: number required: false diff --git a/diffbot/tools/search_web.py b/diffbot/tools/search_web.py index 1616bb7..a128c1e 100644 --- a/diffbot/tools/search_web.py +++ b/diffbot/tools/search_web.py @@ -12,6 +12,7 @@ from tools.shape import summarize_lines, trim_web_search SNIPPETS = {"short", "medium", "long", "full"} +QUERY_FIELDS = ("query", "query_2", "query_3", "query_4", "query_5") def _is_page_lookup(query: str) -> bool: @@ -21,11 +22,18 @@ def _is_page_lookup(query: str) -> bool: class SearchWebTool(Tool): def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: - query = optional_text(tool_parameters, "query") - if not query: + # Up to five queries; blanks are dropped before counting. + queries = [ + text + for text in (optional_text(tool_parameters, name) for name in QUERY_FIELDS) + if text + ] + if not queries: raise DiffbotError("A search query is required.") - if len(query) > 2000: - raise DiffbotError("Search query is too long (2000 characters maximum).") + for text in queries: + if len(text) > 2000: + raise DiffbotError("Search query is too long (2000 characters maximum each).") + query = queries[0] num_value = tool_parameters.get("num_results") if num_value is None or num_value == "": @@ -36,7 +44,7 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag ) snippet = optional_text(tool_parameters, "snippet_length").lower() - if not snippet and _is_page_lookup(query): + if not snippet and len(queries) == 1 and _is_page_lookup(query): snippet = "full" # a lone url: query asks for the stored page if snippet and snippet not in SNIPPETS: raise DiffbotError("snippet_length must be short, medium, long, or full.") @@ -53,7 +61,7 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag # Blank snippet_length is omitted so the API default (long) applies. data = as_dict( client.web_search( - query, + queries[0] if len(queries) == 1 else queries, num_results=num_results, max_tokens=max_tokens, snippet_length=snippet or None, # type: ignore[arg-type] diff --git a/diffbot/tools/search_web.yaml b/diffbot/tools/search_web.yaml index 90a5b63..6762e3f 100644 --- a/diffbot/tools/search_web.yaml +++ b/diffbot/tools/search_web.yaml @@ -26,6 +26,42 @@ parameters: A query of only url:https://example.com/page returns the stored page. placeholder: en_US: hypothyroidism treatment guidelines + - name: query_2 + type: string + required: false + form: llm + label: + en_US: Additional query 1 + human_description: + en_US: Optional extra search text, searched together with the first query (2000 characters maximum). + llm_description: "Optional additional search text. Up to five queries in total. The url: shortcut applies only when there is a single query." + - name: query_3 + type: string + required: false + form: llm + label: + en_US: Additional query 2 + human_description: + en_US: Optional extra search text, searched together with the first query (2000 characters maximum). + llm_description: "Optional additional search text. Up to five queries in total. The url: shortcut applies only when there is a single query." + - name: query_4 + type: string + required: false + form: llm + label: + en_US: Additional query 3 + human_description: + en_US: Optional extra search text, searched together with the first query (2000 characters maximum). + llm_description: "Optional additional search text. Up to five queries in total. The url: shortcut applies only when there is a single query." + - name: query_5 + type: string + required: false + form: llm + label: + en_US: Additional query 4 + human_description: + en_US: Optional extra search text, searched together with the first query (2000 characters maximum). + llm_description: "Optional additional search text. Up to five queries in total. The url: shortcut applies only when there is a single query." - name: num_results type: number required: false diff --git a/diffbot/tools/shape.py b/diffbot/tools/shape.py index 3bfe45f..04a2bb1 100644 --- a/diffbot/tools/shape.py +++ b/diffbot/tools/shape.py @@ -219,3 +219,48 @@ def trim_resolved_entities(data: dict[str, Any]) -> dict[str, Any]: def summarize_lines(title: str, lines: list[str]) -> str: body = "\n".join(lines) if lines else "No matching records." return clip(f"{title}\n{body}", SUMMARY_LIMIT) + + +# Keys dropped from raw Knowledge Graph and NLP output (case-insensitive). These are the +# contact fields the PRIVACY.md promise covers, plus the full-page HTML the trimmed tools drop. +PRIVATE_KEYS = frozenset( + { + "emails", + "email", + "emailaddress", + "emailaddresses", + "phonenumbers", + "phonenumber", + "phones", + "phone", + "html", + } +) + + +def scrub_private(value: Any) -> Any: + """Return ``value`` with every private key removed at any depth (dicts and lists).""" + if isinstance(value, dict): + return { + key: scrub_private(item) + for key, item in value.items() + if not (isinstance(key, str) and key.lower() in PRIVATE_KEYS) + } + if isinstance(value, list): + return [scrub_private(item) for item in value] + return value + + +def fit_rows(rows: list[Any], limit: int) -> tuple[list[Any], bool]: + """Keep leading ``rows`` while their JSON size stays within ``limit`` characters. + + Returns the kept rows and whether any were dropped. + """ + kept: list[Any] = [] + used = 0 + for row in rows: + used += len(json.dumps(row, default=str)) + if used > limit: + return kept, True + kept.append(row) + return kept, False From a4e93c8b4f995e673af20022b5764271df656655 Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:28:56 -1000 Subject: [PATCH 3/7] Add ask, nlp and account_usage tools and credential base URL fields Co-Authored-By: Claude Sonnet 5.5 --- diffbot/provider/diffbot.yaml | 43 ++++++++++++++- diffbot/tools/account_usage.py | 35 ++++++++++++ diffbot/tools/account_usage.yaml | 27 +++++++++ diffbot/tools/ask.py | 95 ++++++++++++++++++++++++++++++++ diffbot/tools/ask.yaml | 74 +++++++++++++++++++++++++ diffbot/tools/nlp.py | 82 +++++++++++++++++++++++++++ diffbot/tools/nlp.yaml | 82 +++++++++++++++++++++++++++ 7 files changed, 437 insertions(+), 1 deletion(-) create mode 100644 diffbot/tools/account_usage.py create mode 100644 diffbot/tools/account_usage.yaml create mode 100644 diffbot/tools/ask.py create mode 100644 diffbot/tools/ask.yaml create mode 100644 diffbot/tools/nlp.py create mode 100644 diffbot/tools/nlp.yaml diff --git a/diffbot/provider/diffbot.yaml b/diffbot/provider/diffbot.yaml index 297d650..adba125 100644 --- a/diffbot/provider/diffbot.yaml +++ b/diffbot/provider/diffbot.yaml @@ -4,7 +4,7 @@ identity: label: en_US: Diffbot description: - en_US: Search the web, extract a page into structured text, and look up organizations, people, and news in the Diffbot Knowledge Graph. + en_US: Search the web, extract pages, ask Diffbot's LLM, run NLP, query the Diffbot Knowledge Graph (including raw DQL and its ontology), run crawls, and check account usage. icon: icon.png tags: - search @@ -31,6 +31,42 @@ credentials_for_provider: en_US: "30" help: en_US: Seconds to wait for each Diffbot call, from 5 to 300. Leave blank for 30. + api_base: + type: text-input + required: false + label: + en_US: API base URL (advanced) + placeholder: + en_US: https://api.diffbot.com + help: + en_US: "Advanced. Leave blank for https://api.diffbot.com. Must be https on a diffbot.com host, with no query string or credentials. Your token is sent to this host, so only use a Diffbot-operated host." + kg_base: + type: text-input + required: false + label: + en_US: Knowledge Graph base URL (advanced) + placeholder: + en_US: https://kg.diffbot.com + help: + en_US: "Advanced. Leave blank for https://kg.diffbot.com. Must be https on a diffbot.com host, with no query string or credentials. Your token is sent to this host, so only use a Diffbot-operated host." + llm_base: + type: text-input + required: false + label: + en_US: LLM and web search base URL (advanced) + placeholder: + en_US: https://llm.diffbot.com + help: + en_US: "Advanced. Leave blank for https://llm.diffbot.com. Must be https on a diffbot.com host, with no query string or credentials. Your token is sent to this host, so only use a Diffbot-operated host." + nlp_base: + type: text-input + required: false + label: + en_US: Natural language base URL (advanced) + placeholder: + en_US: https://nl.diffbot.com + help: + en_US: "Advanced. Leave blank for https://nl.diffbot.com. Must be https on a diffbot.com host, with no query string or credentials. Your token is sent to this host, so only use a Diffbot-operated host." tools: - tools/search_web.yaml - tools/extract.yaml @@ -40,6 +76,11 @@ tools: - tools/crawl_start.yaml - tools/crawl_jobs.yaml - tools/resolve_entities.yaml + - tools/kg_query.yaml + - tools/kg_ontology.yaml + - tools/ask.yaml + - tools/nlp.yaml + - tools/account_usage.yaml extra: python: source: provider/diffbot.py diff --git a/diffbot/tools/account_usage.py b/diffbot/tools/account_usage.py new file mode 100644 index 0000000..1e614b7 --- /dev/null +++ b/diffbot/tools/account_usage.py @@ -0,0 +1,35 @@ +"""Diffbot account plan, status, and recent usage. Never returns the token or email.""" + +from collections.abc import Generator +from typing import Any + +from dify_plugin import Tool +from dify_plugin.entities.tool import ToolInvokeMessage + +from tools.common import as_dict, make_client, mapped_errors, messages +from tools.dql_builder import bounded_number +from tools.shape import summarize_lines + +DEFAULT_DAYS = 7 +USAGE_KEYS = ("date", "nlp", "credits", "extractions", "proxies", "entities", "refresh", "facets", "videos", "subtitles") + + +def _usage_row(row: Any) -> dict[str, Any]: + return {key: row[key] for key in USAGE_KEYS if isinstance(row, dict) and key in row} + + +class AccountUsageTool(Tool): + def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: + raw_days = tool_parameters.get("days") + days = DEFAULT_DAYS if raw_days in (None, "") else int( + bounded_number(raw_days, label="days", minimum=1, maximum=366, integer=True) + ) + client = make_client(self.runtime.credentials) + with client, mapped_errors(client): + data = as_dict(client.account(days=days), "account") + # Allowlist only: the response also holds the token, child tokens and the account email. + usage = [_usage_row(row) for row in (data.get("usage") or [])[:366]] if isinstance(data.get("usage"), list) else [] + payload = {"plan": data.get("plan"), "status": data.get("status"), "days": days, "usage": usage} + lines = [f"{row.get('date', '?')}: " + ", ".join(f"{k} {v}" for k, v in row.items() if k != "date") for row in usage[:30]] + title = f"Diffbot plan {payload['plan'] or 'unknown'} ({payload['status'] or 'unknown'}), last {days} day(s)." + yield from messages(self, summarize_lines(title, lines), payload) diff --git a/diffbot/tools/account_usage.yaml b/diffbot/tools/account_usage.yaml new file mode 100644 index 0000000..1c133c1 --- /dev/null +++ b/diffbot/tools/account_usage.yaml @@ -0,0 +1,27 @@ +identity: + name: account_usage + author: diffbot + label: + en_US: Account usage +description: + human: + en_US: Show the plan, status, and recent daily usage of the Diffbot account behind the saved token. The token and account email are never returned. + llm: > + Read-only. Returns the Diffbot plan, account status, and daily usage counts (credits, extractions, and so on) + for the saved token. Use it to check remaining capacity. It never returns the token or email. +parameters: + - name: days + type: number + required: false + form: form + default: 7 + min: 1 + max: 366 + label: + en_US: Days of usage + human_description: + en_US: How many recent days of usage to include (1 to 366). + llm_description: How many recent days of usage to include, 1 to 366. +extra: + python: + source: tools/account_usage.py diff --git a/diffbot/tools/ask.py b/diffbot/tools/ask.py new file mode 100644 index 0000000..ed40d0f --- /dev/null +++ b/diffbot/tools/ask.py @@ -0,0 +1,95 @@ +"""Ask Diffbot's LLM a question; it answers using Diffbot's web and Knowledge Graph search.""" + +import json +from collections.abc import Generator +from typing import Any + +from diffbot import ValidationError +from dify_plugin import Tool +from dify_plugin.entities.tool import ToolInvokeMessage + +from tools.client import DiffbotError +from tools.common import make_client, mapped_errors, messages, optional_text +from tools.shape import clip + +MAX_QUESTION = 8000 +MAX_SYSTEM = 8000 +MAX_SCHEMA_BYTES = 20_000 +MAX_ANSWER = 60_000 # characters of streamed or joined text +OUTPUTS = {"text", "json", "json_schema"} + + +def _schema(raw: str) -> dict[str, Any]: + if len(raw.encode("utf-8")) > MAX_SCHEMA_BYTES: + raise DiffbotError("json_schema is too large (20 KB maximum).") + try: + parsed = json.loads(raw) + except ValueError: + raise DiffbotError("json_schema must be valid JSON.") from None + if not isinstance(parsed, dict): + raise DiffbotError("json_schema must be a JSON object.") + return parsed + + +class AskTool(Tool): + def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: + question = optional_text(tool_parameters, "question") + if not question: + raise DiffbotError("A question is required.") + if len(question) > MAX_QUESTION: + raise DiffbotError(f"The question is too long ({MAX_QUESTION} characters maximum).") + system_prompt = optional_text(tool_parameters, "system_prompt") + if len(system_prompt) > MAX_SYSTEM: + raise DiffbotError(f"system_prompt is too long ({MAX_SYSTEM} characters maximum).") + output = optional_text(tool_parameters, "output").lower() or "text" + if output not in OUTPUTS: + raise DiffbotError("output must be text, json, or json_schema.") + schema = None + if output == "json_schema": + raw_schema = optional_text(tool_parameters, "json_schema") + if not raw_schema: + raise DiffbotError("json_schema is required when output is json_schema.") + schema = _schema(raw_schema) + # The stream flag only controls progressive text; json output is always read whole. + stream = tool_parameters.get("stream") is not False and output == "text" + + chat: list[dict[str, str]] = [] + if system_prompt: + chat.append({"role": "system", "content": system_prompt}) + chat.append({"role": "user", "content": question}) + + client = make_client(self.runtime.credentials) + if output != "text": + with client, mapped_errors(client): + try: + # ask_json builds a json_schema response format (never bare json_object). + answer: Any = client.ask_json(chat, schema) # type: ignore[arg-type] + except ValidationError: + raise DiffbotError( + "Diffbot did not return valid JSON for that request. Try again or simplify the schema." + ) from None + yield from messages(self, clip(json.dumps(answer, default=str), 4000), {"output": output, "answer": answer}) + return + + parts: list[str] = [] + used = 0 + truncated = False + # Iterate inside the guard so a 401/429 or a dropped connection mid-stream is mapped. + with client, mapped_errors(client): + for chunk in client.ask(chat): + room = MAX_ANSWER - used + if room <= 0: + truncated = True + break + if len(chunk) > room: + chunk, truncated = chunk[:room], True + used += len(chunk) + parts.append(chunk) + if stream: + yield self.create_text_message(chunk) + if truncated: + break + answer_text = "".join(parts) + if not stream: + yield self.create_text_message(answer_text or "Diffbot returned an empty answer.") + yield self.create_json_message({"output": "text", "answer": answer_text, "truncated": truncated}) diff --git a/diffbot/tools/ask.yaml b/diffbot/tools/ask.yaml new file mode 100644 index 0000000..647c321 --- /dev/null +++ b/diffbot/tools/ask.yaml @@ -0,0 +1,74 @@ +identity: + name: ask + author: diffbot + label: + en_US: Ask Diffbot +description: + human: + en_US: Ask Diffbot's LLM a question and get an answer grounded in its web and Knowledge Graph search. Answers can be streamed text, a JSON object, or JSON that follows your schema. The underlying endpoint is not publicly documented, so its behavior may change. + llm: > + Ask Diffbot's LLM a factual question and get a grounded answer. Use output text for prose, + json for a free-form JSON object, or json_schema with a JSON Schema for a fixed shape. + Answers are model output and can be wrong; cite sources with Web search when it matters. + Maximum question length 8000 characters. Do not send secrets. +parameters: + - name: question + type: string + required: true + form: llm + label: + en_US: Question + human_description: + en_US: The question to ask (8000 characters maximum). + llm_description: The question to ask, at most 8000 characters. Do not include secrets. + - name: system_prompt + type: string + required: false + form: form + label: + en_US: System prompt + human_description: + en_US: Optional instructions that shape the answer (8000 characters maximum). + llm_description: Optional system instructions (8000 characters maximum). + - name: output + type: select + required: false + form: form + default: text + label: + en_US: Output + human_description: + en_US: text for prose, json for a JSON object, json_schema for JSON that follows the schema below. + llm_description: text, json, or json_schema. + options: + - value: text + label: + en_US: Text + - value: json + label: + en_US: JSON object + - value: json_schema + label: + en_US: JSON with schema + - name: json_schema + type: string + required: false + form: form + label: + en_US: JSON schema + human_description: + en_US: A JSON Schema object (20 KB maximum). Used only when Output is JSON with schema. + llm_description: A JSON Schema object as text, used only when output is json_schema. + - name: stream + type: boolean + required: false + form: form + default: true + label: + en_US: Stream text + human_description: + en_US: Send text as it arrives. Ignored for JSON output, which is returned whole. + llm_description: Send text as it arrives. Ignored for JSON output. +extra: + python: + source: tools/ask.py diff --git a/diffbot/tools/nlp.py b/diffbot/tools/nlp.py new file mode 100644 index 0000000..8b867b1 --- /dev/null +++ b/diffbot/tools/nlp.py @@ -0,0 +1,82 @@ +"""Diffbot Natural Language analysis of one document.""" + +import re +from collections.abc import Generator +from typing import Any + +from dify_plugin import Tool +from dify_plugin.entities.tool import ToolInvokeMessage + +from tools.client import DiffbotError +from tools.common import as_dict, make_client, mapped_errors, messages, optional_text +from tools.dql_builder import bounded_number, validate_language +from tools.shape import fit_rows, scrub_private, summarize_lines, trim_resolved_entities + +MAX_TEXT = 20000 +FIELDS = ("entities", "sentiment", "facts", "records", "categories", "sentences", "language", "summary") +DEFAULT_FIELDS = ("entities", "sentiment") +FORMATS = {"plain text", "plain text with title"} +LIST_FIELDS = ("facts", "records", "categories", "sentences") +LIST_LIMIT = 50 +OUTPUT_LIMIT = 100_000 +_DOCUMENT_TYPE = re.compile(r"^[A-Za-z0-9 _\-]{1,50}$") + + +class NlpTool(Tool): + def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: + text = optional_text(tool_parameters, "text") + if not text: + raise DiffbotError("Text to analyze is required.") + if len(text) > MAX_TEXT: + raise DiffbotError(f"Text is too long ({MAX_TEXT} characters maximum).") + raw_fields = optional_text(tool_parameters, "fields").replace(" ", "") + fields = [part for part in raw_fields.split(",") if part] or list(DEFAULT_FIELDS) + bad = [part for part in fields if part not in FIELDS] + if bad: + raise DiffbotError(f"fields must use: {', '.join(FIELDS)}.") + lang = optional_text(tool_parameters, "lang").lower() or "auto" + if lang != "auto": + lang = validate_language(lang) + fmt = optional_text(tool_parameters, "format").lower() or "plain text" + if fmt not in FORMATS: + raise DiffbotError("format must be 'plain text' or 'plain text with title'.") + document_type = optional_text(tool_parameters, "document_type") or None + if document_type and not _DOCUMENT_TYPE.fullmatch(document_type): + raise DiffbotError("document_type may use letters, digits, spaces, '_' and '-' (50 characters maximum).") + options: dict[str, Any] = {} + sentences = tool_parameters.get("max_number_of_sentences") + if sentences not in (None, ""): + count = int(bounded_number(sentences, label="max_number_of_sentences", minimum=1, maximum=50, integer=True)) + options["custom_summary"] = {"max_number_of_sentences": count} + + client = make_client(self.runtime.credentials) + with client, mapped_errors(client): + data = as_dict( + client.nlp(text, fields=fields, lang=lang, format=fmt, document_type=document_type, **options), # type: ignore[arg-type] + "NLP analysis", + ) + data = scrub_private(data) + payload: dict[str, Any] = {"fields": fields} + truncated = False + if "entities" in data: + resolved = trim_resolved_entities(data) + payload["entities"] = resolved["entities"] + payload["dql_filter"] = resolved["dql_filter"] + for key in ("sentiment", "language", "summary"): + if key in data: + payload[key] = data[key] + for key in LIST_FIELDS: + value = data.get(key) + if isinstance(value, list): + rows, cut = fit_rows(value[:LIST_LIMIT], OUTPUT_LIMIT // 4) + payload[key] = rows + truncated = truncated or cut or len(value) > LIST_LIMIT + elif key in data: + payload[key] = value + payload["truncated"] = truncated + lines = [f"- {name}: {len(payload[name])}" for name in LIST_FIELDS if isinstance(payload.get(name), list)] + if payload.get("entities") is not None: + lines.append(f"- entities: {len(payload['entities'])}") + if "sentiment" in payload: + lines.append(f"- sentiment: {payload['sentiment']}") + yield from messages(self, summarize_lines("Diffbot NLP analysis.", lines), payload) diff --git a/diffbot/tools/nlp.yaml b/diffbot/tools/nlp.yaml new file mode 100644 index 0000000..b0a68cb --- /dev/null +++ b/diffbot/tools/nlp.yaml @@ -0,0 +1,82 @@ +identity: + name: nlp + author: diffbot + label: + en_US: Natural language analysis +description: + human: + en_US: Analyze one passage of text with Diffbot NLP. Choose which results to return, such as entities, sentiment, facts, records, categories, sentences, language, and a summary. Use Resolve entities for a Knowledge Graph filter. + llm: > + Run Diffbot natural language processing on one plain-text document (20000 characters maximum). + fields is a comma-separated list from entities, sentiment, facts, records, categories, sentences, + language, and summary; the default is entities,sentiment. Email and phone values in the output are removed. + Do not send secrets, credentials, or private messages. +parameters: + - name: text + type: string + required: true + form: llm + label: + en_US: Text + human_description: + en_US: Plain text to analyze (20000 characters maximum). + llm_description: Plain text to analyze. Do not include secrets. Maximum 20000 characters. + - name: fields + type: string + required: false + form: llm + default: entities,sentiment + label: + en_US: Fields + human_description: + en_US: "Comma-separated results to return: entities, sentiment, facts, records, categories, sentences, language, summary." + llm_description: "Comma-separated list from entities, sentiment, facts, records, categories, sentences, language, summary. Default entities,sentiment." + - name: lang + type: string + required: false + form: llm + label: + en_US: Language + human_description: + en_US: Language of the text. Leave empty for auto, or pass a code such as en. + llm_description: auto, or a 2- or 3-letter ISO code. Default auto. + - name: format + type: select + required: false + form: form + default: plain text + label: + en_US: Text format + human_description: + en_US: Whether the first line of the text is a title. + llm_description: plain text, or plain text with title when the first line is a title. + options: + - value: plain text + label: + en_US: Plain text + - value: plain text with title + label: + en_US: Plain text with title + - name: document_type + type: string + required: false + form: form + label: + en_US: Document type + human_description: + en_US: Optional document type hint for Diffbot (letters, digits, spaces, - and _). + llm_description: Optional document type hint. + - name: max_number_of_sentences + type: number + required: false + form: form + min: 1 + max: 50 + label: + en_US: Summary sentences + human_description: + en_US: Most sentences in the summary (1 to 50). Used when the summary field is requested. + llm_description: Most sentences in the summary, 1 to 50. +extra: + python: + source: tools/nlp.py From c58b1d2132afc682a306e0ded84a7990f1099e88 Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:28:56 -1000 Subject: [PATCH 4/7] Add parity tests for new tools, overrides, crawl flags and ontology cache Co-Authored-By: Claude Sonnet 5.5 --- tests/test_parity_3_4_1.py | 554 +++++++++++++++++++++++++++++++++++++ 1 file changed, 554 insertions(+) create mode 100644 tests/test_parity_3_4_1.py diff --git a/tests/test_parity_3_4_1.py b/tests/test_parity_3_4_1.py new file mode 100644 index 0000000..d15b4c3 --- /dev/null +++ b/tests/test_parity_3_4_1.py @@ -0,0 +1,554 @@ +"""Plugin parity with diffbot 3.4.1: new tools, crawl flags, endpoint overrides, ontology cache. + +All HTTP is served by httpx.MockTransport; no live Diffbot calls. +""" + +import json +import threading + +import httpx +import pytest + +from provider.diffbot import DiffbotProvider +from tools import ontology_cache, sdk +from tools.account_usage import AccountUsageTool +from tools.ask import AskTool +from tools.client import DiffbotError +from tools.crawl_start import CrawlStartTool +from tools.extract import ExtractTool +from tools.kg_ontology import KgOntologyTool +from tools.kg_query import KgQueryTool +from tools.nlp import NlpTool +from tools.search_news import SearchNewsTool +from tools.search_organizations import SearchOrganizationsTool +from tools.search_people import SearchPeopleTool +from tools.search_web import SearchWebTool + +TOKEN = "a" * 32 +CREDS = {"diffbot_token": TOKEN} + +ONTOLOGY = { + "types": {"Organization": {"fields": {"name": {"type": "String"}, "oldField": {"type": "String", "isDeprecated": True}}}}, + "composites": {"Location": {"fields": {"city": {"type": "LinkedEntity", "leType": ["Place"]}}}}, + "enums": {"Language": {"values": ["en", "fr"]}}, + "taxonomies": { + "OrganizationCategory": { + "categories": [{"name": "Software Companies", "children": [{"name": "Enterprise Software Companies"}]}] + } + }, +} + + +@pytest.fixture +def serve(monkeypatch): + seen: list[httpx.Request] = [] + + def install(handler): + def wrapped(request): + seen.append(request) + return handler(request) + + monkeypatch.setattr("tools.sdk.httpx.HTTPTransport", lambda **_: httpx.MockTransport(wrapped)) + return seen + + return install + + +@pytest.fixture(autouse=True) +def fresh_ontology_cache(): + ontology_cache.CACHE.clear() + yield + ontology_cache.CACHE.clear() + + +def _json(messages): + return [m for m in messages if m.type.value == "json"][-1].message.json_object + + +def run(tool_cls, params, creds=CREDS): + return list(tool_cls.from_credentials(creds).invoke(params)) + + +def _body(request): + return json.loads(request.content) + + +# ------------------------------------------------------------ kg_query + + +def test_kg_query_sends_wire_names_and_offset_as_from(serve): + seen = serve(lambda r: httpx.Response(200, json={"hits": 1, "data": []})) + run(KgQueryTool, { + "query": "type:Organization", "size": 7, "offset": 3, "type": "text", "col": "name", "filter": "a", + "filter_exclude": "b", "jsonmode": "id", "non_canonical_facts": True, "no_dedup_articles": True, + "cluster": "best", "exportfile": "ignored", + }) + body = _body(seen[0]) + assert seen[0].method == "POST" and seen[0].url.path == "/kg/v3/dql" + assert body["size"] == 7 and body["from"] == 3 + assert body["filterExclude"] == "b" and body["filter"] == "a" + assert body["nonCanonicalFacts"] is True and body["noDedupArticles"] is True + assert body["jsonmode"] == "id" and body["cluster"] == "best" and body["type"] == "text" and body["col"] == "name" + assert "exportfile" not in body # blob file name only, never a server-side name + assert "token" not in body + + +def test_kg_query_count_only_sends_size_zero_and_returns_hits_only(serve): + seen = serve(lambda r: httpx.Response(200, json={"hits": 42, "data": [{"name": "x"}]})) + payload = _json(run(KgQueryTool, {"query": "type:Organization", "count_only": True, "size": 50})) + assert _body(seen[0])["size"] == 0 + assert payload["hits"] == 42 and "data" not in payload and "results" not in payload + + +@pytest.mark.parametrize("tool,params", [ + (SearchOrganizationsTool, {"name": "Diffbot"}), + (SearchPeopleTool, {"name": "Ada"}), + (SearchNewsTool, {"mentions": "Diffbot"}), +]) +def test_template_tools_count_only(serve, tool, params): + seen = serve(lambda r: httpx.Response(200, json={"hits": 9, "data": [{"name": "x"}]})) + payload = _json(run(tool, {**params, "count_only": True})) + assert _body(seen[0])["size"] == 0 + assert payload["hits"] == 9 and "results" not in payload + + +def test_kg_query_scrubs_contact_fields_and_html_recursively(serve): + entity = { + "name": "Acme", "emailAddresses": [{"value": "a@b.com"}], "html": "

x

", + "nested": {"phoneNumbers": ["+1"], "Emails": ["x@y.z"], "keep": 1}, + "list": [{"phone": "1", "ok": True}], + } + serve(lambda r: httpx.Response(200, json={"hits": 1, "data": [{"entity": entity}]})) + payload = _json(run(KgQueryTool, {"query": "type:Organization"})) + text = json.dumps(payload) + for leaked in ("a@b.com", "

", "+1", "x@y.z", "emailAddresses", "phoneNumbers"): + assert leaked not in text + assert payload["data"][0]["entity"]["nested"] == {"keep": 1} + assert payload["data"][0]["entity"]["list"] == [{"ok": True}] + + +def test_kg_query_scrubs_jsonl(serve): + lines = "\n".join(json.dumps({"name": n, "emails": ["a@b.c"]}) for n in ("a", "b")) + serve(lambda r: httpx.Response(200, text=lines)) + payload = _json(run(KgQueryTool, {"query": "type:Organization", "format": "jsonl"})) + assert payload["returned"] == 2 and "emails" not in json.dumps(payload) + + +def test_kg_query_caps_output_and_flags_truncation(serve, monkeypatch): + monkeypatch.setattr("tools.kg_query.OUTPUT_LIMIT", 100) + rows = [{"entity": {"name": "n" * 40}} for _ in range(10)] + serve(lambda r: httpx.Response(200, json={"hits": 10, "data": rows})) + payload = _json(run(KgQueryTool, {"query": "type:Organization"})) + assert payload["truncated"] is True and payload["returned"] < 10 + + +@pytest.mark.parametrize("fmt,content,mime", [ + ("csv", "a,b\n1,2\n", "text/csv"), + ("xlsx", b"PK\x03\x04bytes", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), + ("xls", b"\xd0\xcf\x11bytes", "application/vnd.ms-excel"), +]) +def test_kg_query_exports_are_blob_files(serve, fmt, content, mime): + seen = serve(lambda r: httpx.Response(200, content=content if isinstance(content, bytes) else content.encode())) + messages = run(KgQueryTool, {"query": "type:Organization", "format": fmt, "exportfile": "orgs"}) + blob = next(m for m in messages if m.type.value == "blob") + assert blob.message.blob == (content if isinstance(content, bytes) else content.encode()) + assert blob.meta["mime_type"] == mime and blob.meta["filename"] == f"orgs.{fmt}" + assert _body(seen[0])["format"] == fmt + assert _json(messages)["scrubbed"] is False + + +def test_kg_query_validation(serve): + serve(lambda r: httpx.Response(200, json={})) + with pytest.raises(DiffbotError, match="too long"): + run(KgQueryTool, {"query": "x" * 10_001}) + with pytest.raises(DiffbotError, match="format"): + run(KgQueryTool, {"query": "x", "format": "xml"}) + with pytest.raises(DiffbotError, match="csv"): + run(KgQueryTool, {"query": "x", "exportseparator": ";"}) + with pytest.raises(DiffbotError): + run(KgQueryTool, {"query": "x", "size": 101}) + + +# ------------------------------------------------------------ crawl flags and options + + +def test_crawl_tri_state_flags_are_absent_by_default_and_zero_only_for_off(serve): + seen = serve(lambda r: httpx.Response(200, json={})) + run(CrawlStartTool, {"seeds": "example.org", "job_name": "j"}) + params = seen[0].url.params + for wire in ("obeyRobots", "useProxies", "useCanonical"): + assert wire not in params + run(CrawlStartTool, {"seeds": "example.org", "job_name": "j", "obey_robots_mode": "off", + "use_proxies_mode": "off", "use_canonical_mode": "on"}) + params = seen[1].url.params + assert params["obeyRobots"] == "0" and params["useProxies"] == "0" and params["useCanonical"] == "1" + run(CrawlStartTool, {"seeds": "example.org", "job_name": "j", "obey_robots_mode": "on"}) + assert seen[2].url.params["obeyRobots"] == "1" + + +def test_legacy_boolean_crawl_values_do_not_change_robots_behavior(serve): + seen = serve(lambda r: httpx.Response(200, json={})) + run(CrawlStartTool, {"seeds": "example.org", "job_name": "j", "obey_robots": False, "use_proxies": False}) + assert "obeyRobots" not in seen[0].url.params and "useProxies" not in seen[0].url.params + + +def test_crawl_new_options_reach_the_wire(serve): + seen = serve(lambda r: httpx.Response(200, json={})) + run(CrawlStartTool, { + "seeds": "example.org", "job_name": "j", "url_crawl_regex": "a.*", "url_process_regex": "b.*", + "page_process_pattern": " stale copy, then back off + assert cache.get(client) is first and client.calls == 2 + assert cache.get(client) is first and client.calls == 2 + now[0] = 112 # backoff over; refresh succeeds + assert cache.get(client) is second and client.calls == 3 + + +def test_ontology_cache_backs_off_after_failure_with_no_stale_copy_and_keys_by_url(): + now = [0.0] + cache = ontology_cache.OntologyCache(clock=lambda: now[0], ttl=100, backoff=10) + bad = FakeClient("u1", [httpx.ConnectError("down"), "ok"]) + with pytest.raises(httpx.ConnectError): + cache.get(bad) + with pytest.raises(DiffbotError, match="temporarily"): + cache.get(bad) + assert bad.calls == 1 + other = FakeClient("u2", ["other"]) + assert cache.get(other) == "other" # a different URL has its own entry + now[0] = 11 + assert cache.get(bad) == "ok" + + +def test_ontology_lookups(serve): + _ontology_server(serve, []) + assert _json(run(KgOntologyTool, {"lookup": "types"}))["names"] == ["Organization"] + fields = _json(run(KgOntologyTool, {"lookup": "fields", "name": "Organization"}))["fields"] + assert [f["name"] for f in fields] == ["name"] # deprecated hidden + fields = _json(run(KgOntologyTool, {"lookup": "fields", "name": "Organization", "include_deprecated": True}))["fields"] + assert {f["name"] for f in fields} == {"name", "oldField"} + values = _json(run(KgOntologyTool, {"lookup": "taxonomy_values", "name": "OrganizationCategory", "search": "enterprise"})) + assert values["values"] == ["Enterprise Software Companies"] + assert _json(run(KgOntologyTool, {"lookup": "find", "search": "enterprise"}))["names"] == ["Enterprise Software Companies"] + with pytest.raises(DiffbotError, match="Not found"): + run(KgOntologyTool, {"lookup": "fields", "name": "Nope"}) + + +def test_ontology_search_is_literal_and_length_capped(serve): + _ontology_server(serve, []) + assert _json(run(KgOntologyTool, {"lookup": "find", "search": "(a+)+$["}))["names"] == [] # no regex error + with pytest.raises(DiffbotError, match="too long"): + run(KgOntologyTool, {"lookup": "find", "search": "x" * 201}) + + +def test_ontology_raw_file_is_a_blob(serve): + _ontology_server(serve, []) + messages = run(KgOntologyTool, {"lookup": "raw_file"}) + blob = next(m for m in messages if m.type.value == "blob") + assert json.loads(blob.message.blob)["enums"]["Language"]["values"] == ["en", "fr"] + + +# ------------------------------------------------------------ industry, web search, extract + + +def test_industry_resolves_case_insensitively_and_suggests_on_miss(serve): + seen = _ontology_server(serve, []) + run(SearchOrganizationsTool, {"industry": "software companies"}) + query = _body(seen[-1])["query"] + assert 'categories.name:"Software Companies"' in query + with pytest.raises(DiffbotError, match="Did you mean: .*Software Companies"): + run(SearchOrganizationsTool, {"industry": "software company"}) + + +def test_industry_passes_through_when_the_ontology_is_unavailable(serve): + def handler(request): + if request.url.path == "/kg/ontology": + return httpx.Response(500, json={"message": "down"}) + return httpx.Response(200, json={"hits": 0, "data": []}) + + seen = serve(handler) + run(SearchOrganizationsTool, {"industry": "Whatever"}) + assert 'categories.name:"Whatever"' in _body(seen[-1])["query"] + + +def test_web_search_takes_up_to_five_queries_and_drops_blanks(serve): + seen = serve(lambda r: httpx.Response(200, json={"search_results": []})) + run(SearchWebTool, {"query": "a", "query_2": " ", "query_3": "c"}) + assert seen[0].url.params.get_list("text") == ["a", "c"] + run(SearchWebTool, {"query": "a", "query_2": "b", "query_3": "c", "query_4": "d", "query_5": "e"}) + assert len(seen[1].url.params.get_list("text")) == 5 + with pytest.raises(DiffbotError, match="too long"): + run(SearchWebTool, {"query": "a", "query_2": "x" * 2001}) + + +def test_url_shortcut_applies_only_to_a_single_query(serve): + seen = serve(lambda r: httpx.Response(200, json={"search_results": []})) + run(SearchWebTool, {"query": "url:https://example.org/a"}) + assert seen[0].url.params["snippetLength"] == "FULL" + run(SearchWebTool, {"query": "url:https://example.org/a", "query_2": "other"}) + assert "snippetLength" not in seen[1].url.params + + +def test_extract_supports_job_and_custom_api(serve): + seen = serve(lambda r: httpx.Response(200, json={"objects": []})) + run(ExtractTool, {"url": "https://example.org/j", "page_type": "job"}) + assert seen[0].url.path.endswith("/job") + run(ExtractTool, {"url": "https://example.org/j", "custom_api": "my_api-2"}) + assert seen[1].url.path.endswith("/my_api-2") + with pytest.raises(DiffbotError, match="custom_api"): + run(ExtractTool, {"url": "https://example.org/j", "custom_api": "../x"}) From 57b56b0e5439e1ce75a37c7f18d6f088ecc52a44 Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:28:56 -1000 Subject: [PATCH 5/7] Update README, PRIVACY, CHANGELOG and SUBMISSION for 0.2.0 Mark the 3.4.0 validator results stale until rerun on 0.2.0. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 25 +++++++++++++++++++++++- README.md | 19 +++++++++++------- SUBMISSION.md | 48 ++++++++++++++++++++++++++++------------------ diffbot/PRIVACY.md | 13 +++++++++++-- diffbot/README.md | 24 +++++++++++++++-------- 5 files changed, 92 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f2379af..9f571dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,29 @@ # Changelog -## Unreleased (still plugin 0.1.0) +## 0.2.0 - SDK 3.4.1 parity + +Pins `diffbot==3.4.1` (exact). Not released: no tag, no marketplace submission. + +### Added + +- `kg_query`: raw DQL with count-only, `size` 0 to 100, offset, and the SDK's named options (`type`, `col`, `filter`, `filter_exclude`, `exportspec`, `exportseparator`, `jsonmode`, `non_canonical_facts`, `no_dedup_articles`, `cluster`, `format`). JSON and jsonl are scrubbed of `emails`, `phoneNumbers`, and `html` and capped at 200,000 characters (`truncated` flag). csv, xls and xlsx come back as files and are not scrubbed. +- `kg_ontology`: types, composites, enums, taxonomies, fields, taxonomy values, enum values, name search, and a raw ontology file. One in-memory copy per ontology URL, 24 hour TTL, stale copy served on a failed refresh, five minute back-off. +- `ask`: Diffbot's LLM with text (streamed), JSON, or JSON-schema output. +- `nlp`: single-document NLP with selectable fields, language, format, document type, and summary length. +- `account_usage`: plan, status and daily usage only. Never the token, child tokens, or email. +- Advanced credential fields `api_base`, `kg_base`, `llm_base`, `nlp_base`. https on `diffbot.com` hosts only. +- `search_web`: up to five queries. +- `search_organizations`, `search_people`, `search_news`: `count_only`. The organization `industry` is matched against the `OrganizationCategory` taxonomy, with suggestions on a miss. +- `extract`: the `job` page type and an optional Custom API name. +- `crawl_start`: `url_crawl_regex`, `url_process_regex`, `page_process_pattern`, per-subdomain limits, `notify_webhook`, `notify_email`, and multi-line `custom_headers`. + +### Changed + +- Crawl robots.txt, proxy and canonical settings are now three-way selects (`obey_robots_mode`, `use_proxies_mode`, `use_canonical_mode`): Diffbot default (parameter omitted), on, off (`0`). On SDK 3.4.1 an explicit `False` is sent as `0`, so the old boolean fields, which Dify saves as `false`, would have made existing nodes ignore robots.txt. The old field names are no longer read. +- Plugin version 0.2.0 (`manifest.yaml` and `pyproject.toml`). The memory limit stays at 64 MB. +- Marketplace validator results in SUBMISSION.md are for the 3.4.0 / 0.1.0 package and are stale until rerun on 0.2.0. + +## Earlier, still plugin 0.1.0 - Removed the `client.request()` fallbacks in `diffbot/tools/sdk.py` for `verify_token`, `crawl_download`, and extract options, and the local response TypedDicts in `tools/sdk_types.py`. `diffbot==3.4.0` has all of them natively. No behavior change. - Reran the marketplace validator on the rebuilt package; results are in SUBMISSION.md. diff --git a/README.md b/README.md index aed027c..021f6bc 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,15 @@ The installable plugin is in [`diffbot/`](diffbot/). Its [README](diffbot/README | Start crawl | `GET https://api.diffbot.com/v3/crawl` (create only; returns a job name) | | Crawl jobs | list / status / results / **delete (destructive)** on `/v3/crawl` and `/v3/crawl/data` | | Resolve entities | `POST https://nl.diffbot.com/v1/` | +| Knowledge Graph query | `POST https://kg.diffbot.com/kg/v3/dql` (raw DQL; JSON/jsonl scrubbed, csv/xls/xlsx exports not) | +| Knowledge Graph ontology | `GET https://kg.diffbot.com/kg/ontology` (no token; 24 h in-memory cache) | +| Ask Diffbot | `POST https://llm.diffbot.com/rag/v1/chat/completions` (bearer token; undocumented endpoint) | +| Natural language analysis | `POST https://nl.diffbot.com/v1/` | +| Account usage | `GET https://api.diffbot.com/v4/account` | Saving the credential checks `GET https://api.diffbot.com/v4/account?days=1`. Get a free token at [app.diffbot.com/get-started](https://app.diffbot.com/get-started). -Raw DQL, ontology lookup, Ask, places, and deals are not in this version. See SUBMISSION.md for why. +The plugin covers the `diffbot` 3.4.1 sync client. Enhance, Bulk Extract, Custom API management, crawl pause/restart, and the file-writing ontology refresh are not included. See SUBMISSION.md. All HTTP goes through the [Diffbot Python SDK](https://github.com/diffbot/diffbot-python) (`diffbot.Diffbot`), behind a transport that refuses private, loopback, and cloud-metadata hosts. @@ -33,23 +38,23 @@ Python 3.12+: ```bash python -m venv .venv && . .venv/bin/activate -pip install -r requirements-dev.txt # dify_plugin, pytest, and diffbot==3.4.0 +pip install -r requirements-dev.txt # dify_plugin, pytest, and diffbot==3.4.1 pytest -q ``` -`diffbot/requirements.txt` pins `diffbot==3.4.0`, which is on PyPI. `requirements-dev.txt` does not contain a machine-local path. +`diffbot/requirements.txt` pins `diffbot==3.4.1`, which is on PyPI. `requirements-dev.txt` does not contain a machine-local path. -The tests serve every request from `httpx.MockTransport` and make no Diffbot calls. The wiring tests run against the pinned SDK (`diffbot==3.4.0`) and its native `verify_token`, `crawl_download`, and extract options. +The tests serve every request from `httpx.MockTransport` and make no Diffbot calls. The wiring tests run against the pinned SDK (`diffbot==3.4.1`) and its native `verify_token`, `crawl_download`, and extract options. -GitHub CI (`.github/workflows/test.yml`) installs `diffbot/requirements.txt`, including `diffbot==3.4.0`, and runs the full suite. +GitHub CI (`.github/workflows/test.yml`) installs `diffbot/requirements.txt`, including `diffbot==3.4.1`, and runs the full suite. ## Package Install the Dify plugin CLI from [langgenius/dify-plugin-daemon](https://github.com/langgenius/dify-plugin-daemon) and run from the repository root: ```bash -dify plugin package ./diffbot -o dist/diffbot-0.1.0.difypkg -dify plugin checksum dist/diffbot-0.1.0.difypkg +dify plugin package ./diffbot -o dist/diffbot-0.2.0.difypkg +dify plugin checksum dist/diffbot-0.2.0.difypkg ``` `dist/` is ignored by git. The package is unsigned; Dify signs marketplace builds after review. Self-hosted Dify rejects unsigned local installs unless an administrator trusts a signature or turns off verification. Signing commands are in `diffbot/README.md`. Never commit a private key. diff --git a/SUBMISSION.md b/SUBMISSION.md index 146a799..ba2763a 100644 --- a/SUBMISSION.md +++ b/SUBMISSION.md @@ -1,6 +1,8 @@ # Publishing the Diffbot plugin to the Dify Marketplace -This is the runbook for publishing the plugin from the Diffbot organization. The source is public at https://github.com/diffbot/dify-diffbot. The plugin described here is the `feat/sdk-3.x-wiring` branch: eight tools, including crawl, built on the `diffbot` Python SDK (pinned to `diffbot==3.4.0`) and httpx instead of `requests`. As of 18 November 2026 no pull request has been opened against `langgenius/dify-plugins`, and this version has not been installed in Dify Community Edition or Dify Cloud. `diffbot` 3.4.0 was published to PyPI on 18 November 2026. The same day the SDK feature-detect fallbacks were removed, the package was rebuilt, and the marketplace validator was rerun on it: 0 blocking failures (results below). The live smoke test against the real API has not been rerun yet. The pre-SDK v0.1 results that used to be here no longer describe this package and have been removed. +> **Stale validator results.** The validator, checksum, package-size and start-up results below are for plugin 0.1.0 on `diffbot==3.4.0` (18 November 2026). Plugin 0.2.0 (`diffbot==3.4.1`, 13 tools) has not been packaged or validated yet. Rerun the validator and refresh those numbers, the package contents list, and the PR body before submitting. + +This is the runbook for publishing the plugin from the Diffbot organization. The source is public at https://github.com/diffbot/dify-diffbot. The plugin described here is the `feat/sdk-3.4.1-parity` branch (version 0.2.0): thirteen tools, including crawl, built on the `diffbot` Python SDK (pinned to `diffbot==3.4.1`) and httpx instead of `requests`. As of 18 November 2026 no pull request has been opened against `langgenius/dify-plugins`, and this version has not been installed in Dify Community Edition or Dify Cloud. `diffbot` 3.4.0 was published to PyPI on 18 November 2026. The same day the SDK feature-detect fallbacks were removed, the package was rebuilt, and the marketplace validator was rerun on it: 0 blocking failures (results below). The live smoke test against the real API has not been rerun yet. The pre-SDK v0.1 results that used to be here no longer describe this package and have been removed. Checked on 9 November 2026 against: @@ -25,8 +27,8 @@ Done: - Public source: https://github.com/diffbot/dify-diffbot, linked from `manifest.yaml` `repo` and the plugin README. - Contact: `support@diffbot.com` in `manifest.yaml`, the plugin README, PRIVACY.md, and the PR body. - Icon: `_assets/icon.png` is the official 2026 Diffbot logomark, the green rounded-square tile (512×512 PNG). -- `meta.minimum_dify_version`: 1.14.0. The dify_plugin 0.11.0 README lists Dify 1.14.0 for SDK 0.8.1 and later. The plugin uses no later gated feature (OAuth, dynamic-select, multiple selects, reset_on_change). -- Unit tests: `pytest` with mocked HTTP, run by GitHub CI against `diffbot==3.4.0` from PyPI. +- `meta.minimum_dify_version`: 1.14.0. The dify_plugin 0.11.0 README lists Dify 1.14.0 for SDK 0.8.1 and later. The plugin uses no later gated feature (OAuth, dynamic-select, multiple selects, reset_on_change). The optional dynamic-select for the organization industry was not added. +- Unit tests: `pytest` with mocked HTTP, run by GitHub CI against `diffbot==3.4.1` from PyPI. - `diffbot` 3.4.0 is on PyPI (18 November 2026) and pinned. The feature-detect fallbacks in `diffbot/tools/sdk.py` (`verify_token`, `crawl_download`, extract options) and the local TypedDicts in `tools/sdk_types.py` are gone; the plugin calls the native 3.4.0 methods. - Marketplace validator rerun on the rebuilt package on 18 November 2026: exit 0, 0 blocking failures, serverless start-up test passed. See "Results for the current package". @@ -42,7 +44,7 @@ Still to do: ### Tools -`provider/diffbot.yaml` registers eight tools, one YAML and one Python file each under `diffbot/tools/`: +`provider/diffbot.yaml` registers thirteen tools, one YAML and one Python file each under `diffbot/tools/`: | Tool | Diffbot host | What it does | | --- | --- | --- | @@ -54,14 +56,21 @@ Still to do: | `crawl_start` | api.diffbot.com (`/v3/crawl`) | Starts a background Diffbot crawl job on 1 to 20 public seed URLs and returns only the job name. | | `crawl_jobs` | api.diffbot.com (`/v3/crawl`, `/v3/crawl/data`) | `list`, `status`, `results` (up to 1,000 rows, flagged when truncated), or `delete`. Delete is destructive. | | `resolve_entities` | nl.diffbot.com | Finds entities in up to 20,000 characters of pasted text and links them to Knowledge Graph ids, with sentiment. | +| `kg_query` | kg.diffbot.com | Raw DQL (`POST /kg/v3/dql`) with count-only, size 0 to 100, offset, and the SDK's named options. The query is capped at 10,000 characters. JSON and jsonl output drop `emails`, `phoneNumbers`, `html` and close aliases at any depth and are capped at 200,000 characters (`truncated` flag). csv, xls and xlsx are attached as files and are not scrubbed. The help text and PRIVACY.md say so. | +| `kg_ontology` | kg.diffbot.com (no token) | Types, composites, enums, taxonomies, fields, taxonomy values, enum values, name search, and a raw ontology file. In-memory cache keyed by ontology URL, 24 hours, `threading.Lock`, stale on failed refresh, 5 minute back-off. Search text is escaped (literal) and capped at 200 characters. | +| `ask` | llm.diffbot.com | Diffbot's LLM (`/rag/v1/chat/completions`, undocumented). Text (streamed), `json`, or `json_schema` through `ask_json`, never a bare `json_object`. Question 8,000 characters, schema 20 KB. | +| `nlp` | nl.diffbot.com | One document, selectable fields (including facts and records, scrubbed of email and phone), language, format, document type, summary length. 20,000 characters. | +| `account_usage` | api.diffbot.com | Plan, status and daily usage only (allowlisted). Never the token, child tokens or email. | + +The `enhance_entity` tool was removed (commit 7323b7b) so the tool set matches the Diffbot Python SDK surface. Raw DQL is available through `kg_query`, behind the scrub and size caps above. -The `enhance_entity` tool was removed (commit 7323b7b) so the tool set matches the Diffbot Python SDK surface. The plugin has no raw DQL tool. +The optional `industry` handling on `search_organizations` is not a dynamic-select: the field stays an LLM-fillable string and is resolved against the `OrganizationCategory` taxonomy on the server side (exact, then case-insensitive, otherwise suggestions). `search_web` takes up to five queries, the three search tools take `count_only`, `extract` supports `job` and an existing Custom API by name. ### Crawl support - **Background jobs.** `crawl_start` always calls the SDK with `watch=False` and returns as soon as Diffbot reports the job name. Polling would run past the plugin's 300-second call limit. The job keeps running on Diffbot after the Dify call returns, and it uses the account's crawl quota until it finishes or someone deletes it. The model is told to check `crawl_jobs` `status` and then fetch `results`. - **Job names, 30 characters max.** Optional `job_name` may use letters, digits, `-`, `_`, and `.`, up to 30 characters. Leave it empty and Diffbot generates `crawl-`. The plugin checks the length itself because the crawler answers a longer name with HTTP 200 plus `errorCode` 505 and creates nothing. -- **Bounds.** Up to 20 seeds. `max_to_crawl` and `max_to_process` are 1 to 10,000 (default 100). `hops` is 0 to 10 (default 2). `restrict_domain` is on by default. `crawl_delay` is −1 to 3,600 seconds (−1 means the Diffbot default). Optional URL crawl and process patterns, `obey_robots` (form default off; see the robots.txt note under risks), `use_proxies` (default off), a custom request header, and an optional `api_url` for per-page extraction. +- **Bounds.** Up to 20 seeds. `max_to_crawl` and `max_to_process` are 1 to 10,000 (default 100). `hops` is 0 to 10 (default 2). `restrict_domain` is on by default. `crawl_delay` is −1 to 3,600 seconds (−1 means the Diffbot default). Optional URL crawl and process patterns and regular expressions, a page process pattern, per-subdomain limits, `notify_webhook` and `notify_email` (workflow builders only, validated), robots.txt, proxy and canonical-URL settings as three-way selects (`default` omits the parameter; `off` sends 0), custom request headers (one per line), and an optional `api_url` for per-page extraction. - **Delete is destructive.** `crawl_jobs` `delete` permanently removes the job and the data it collected. There is no undo. The tool, action label, and LLM description all say so, and the LLM description tells the model to delete only when the user explicitly asks. The plugin itself has no confirmation step, so an agent that ignores that instruction can still delete a job. - **Account scope.** `list`, `status`, `results`, and `delete` work on every crawl job owned by the token's Diffbot account, including jobs made outside Dify. Nothing limits a Dify workspace to the jobs it started. - **Results.** Up to 1,000 rows, string cells clipped to 500 characters. The plugin asks for one extra row so it can set `truncated`. `result_type: urls` returns the crawled-URL report (CSV, parsed to rows). @@ -69,10 +78,10 @@ The `enhance_entity` tool was removed (commit 7323b7b) so the tool set matches t ### Dependencies and transport - `dify_plugin==0.11.0`. -- `diffbot==3.4.0`, the official Diffbot Python SDK, pinned in `diffbot/requirements.txt` and `diffbot/pyproject.toml`. It is on PyPI (published 18 November 2026). `requirements-dev.txt` has no machine-local path. +- `diffbot==3.4.1`, the official Diffbot Python SDK, pinned exactly in `diffbot/requirements.txt` and `diffbot/pyproject.toml` (not a range: the SDK has shipped breaking changes in minor releases). `requirements-dev.txt` has no machine-local path. - `httpx` is the HTTP client. It comes in through the SDK (`httpx>=0.27.0`, along with the SDK's `click` and `rich`) and is not pinned directly by the plugin. `requests` is gone: it is no longer imported or listed, and the old `requests==2.34.2` pin was dropped. -- Every SDK call goes through `GuardedTransport` (`tools/sdk.py`). It is an httpx transport that refuses non-http(s) schemes and loopback, private, link-local, reserved, multicast, `localhost`, `*.local`/`*.internal`, and cloud-metadata hosts before a socket opens. The guard is always on; there is no credential to turn it off, and the plugin does not support self-hosted gateways or custom base URLs. It also honors `HTTP(S)_PROXY`/`ALL_PROXY`/`NO_PROXY` like the old `requests` client did, so proxied Dify deployments still work. -- Token verification, crawl data download, and extract options call the native SDK methods (`verify_token`, `crawl_download`, and `extract` options, all in 3.4.0). The old `client.request()` fallbacks were removed on 18 November 2026. +- Every SDK call goes through `GuardedTransport` (`tools/sdk.py`). It is an httpx transport that refuses non-http(s) schemes and loopback, private, link-local, reserved, multicast, `localhost`, `*.local`/`*.internal`, and cloud-metadata hosts before a socket opens. The guard is always on; there is no credential to turn it off. The advanced credential fields `api_base`, `kg_base`, `llm_base` and `nlp_base` may override the four Diffbot bases, but only with an https URL on `diffbot.com` or a subdomain, no userinfo, query, fragment or non-default port, and a public host. The plugin does not support self-hosted gateways or other custom hosts. `verify_token` follows `api_base`. It also honors `HTTP(S)_PROXY`/`ALL_PROXY`/`NO_PROXY` like the old `requests` client did, so proxied Dify deployments still work. +- Token verification, crawl data download, and extract options call the native SDK methods (`verify_token`, `crawl_download`, and `extract` options, all in 3.4.0 and later). The old `client.request()` fallbacks were removed on 18 November 2026. - The SDK sends the token as a `token` query parameter to api, kg, and nl.diffbot.com, and as `Authorization: Bearer` to llm.diffbot.com (Web Search). Errors are mapped to plugin-safe text and the token is redacted from them. ### Credential fields @@ -172,15 +181,16 @@ Fill this in from the live template. Keep every section. Check exactly one risk ## What changed -New tool plugin for Diffbot, built on the official Diffbot Python SDK (`diffbot==3.4.0`). Eight tools: +New tool plugin for Diffbot, built on the official Diffbot Python SDK (`diffbot==3.4.1`). Thirteen tools: - Web search on llm.diffbot.com - Extract a page on api.diffbot.com (auto or a specific page type) - Knowledge Graph search for organizations, people, and news - Start a Diffbot crawl job, and list, check, fetch results of, or delete crawl jobs (delete is destructive) - Resolve entities in pasted text to Knowledge Graph ids +- Raw DQL and ontology lookup, Ask, NLP analysis, and account usage -Authentication is a Diffbot token (free at https://app.diffbot.com/get-started). The plugin calls the Account API to check the token when the credential is saved. One optional credential field sets the request timeout (5 to 300 seconds). The private-host guard is always on. The plugin has no raw DQL tool and takes no email, phone, or IP inputs. +Authentication is a Diffbot token (free at https://app.diffbot.com/get-started). The plugin calls the Account API to check the token when the credential is saved. Optional credential fields set the request timeout (5 to 300 seconds) and the four Diffbot base URLs (https `diffbot.com` hosts only). The private-host guard is always on. The raw DQL tool can send any query; its JSON output is scrubbed of email and phone fields, but csv, xls and xlsx export files are not. Crawl notification takes an email address and a webhook URL, settable only by workflow builders. ## Risk level @@ -195,22 +205,22 @@ Extract and crawl both send user-supplied http(s) URLs to Diffbot, and Diffbot f - [x] I have read and followed the [Marketplace submission requirements](https://github.com/langgenius/dify-plugins/blob/main/docs/plugin-submission-requirements.md). - [x] I have read and comply with the [Plugin Development Guidelines](https://docs.dify.ai/en/develop-plugin/publishing/standards/contributor-covenant-code-of-conduct). - [ ] I tested this plugin on Dify Community Edition and Dify Cloud, or documented any limitation below. -- [x] The package contains only files needed at runtime. +- [x] The package contains only files needed at runtime. (Re-verify on the 0.2.0 package.) - [x] The package does not contain secrets, local credentials, `.env` files, `.git` directories, virtual environments, caches, logs, or IDE files. - [x] The package does not contain executables or bundled binaries, or I explained why they are required below. - [x] The plugin README includes setup steps, usage instructions, required APIs or credentials, connection requirements, and the source repository link. - [x] The plugin includes `PRIVACY.md` or a hosted privacy policy, and `manifest.yaml` references it. - [x] All user-facing text is primarily in English, with any localized README files following the [i18n guidance](https://docs.dify.ai/en/develop-plugin/features-and-specs/plugin-types/multilingual-readme). - + ## Security and privacy notes -- Outbound hosts: the plugin process only calls api.diffbot.com, kg.diffbot.com, llm.diffbot.com, and nl.diffbot.com, through the Diffbot SDK over httpx. No credential or parameter changes those base URLs. A guarded httpx transport refuses non-http(s) schemes and private, loopback, link-local, and metadata hosts before connecting. +- Outbound hosts: the plugin process only calls api.diffbot.com, kg.diffbot.com, llm.diffbot.com, and nl.diffbot.com, through the Diffbot SDK over httpx. The advanced base-URL credential fields can only swap in another `diffbot.com` host over https; the manifest `network.domains` list still names the four defaults, so confirm how Dify enforces it for a subdomain override. A guarded httpx transport refuses non-http(s) schemes and private, loopback, link-local, and metadata hosts before connecting. - User-supplied URLs: extract `url`, crawl `seeds`, and crawl `api_url` must be http(s), have no userinfo, be at most 2,048 characters, and not be a local name or a literal private, loopback, link-local, reserved, or metadata address. Bare domains get `https://`. The check is on the literal host only. The plugin does not resolve DNS, because Diffbot does the fetching from its own infrastructure. -- Crawling: crawl jobs run on Diffbot in the background and use the account's quota until they finish or are deleted. Limits: 20 seeds, 10,000 pages crawled and processed, 10 hops. The crawl stays on the seed domains by default. `obey_robots` is off in the form by default. When it is off the SDK leaves out `obeyRobots`, so the Diffbot crawler's own default applies. A custom request header can be set and is sent to the crawled sites, and the parameter text tells users not to put secrets there. Job names are at most 30 characters. +- Crawling: crawl jobs run on Diffbot in the background and use the account's quota until they finish or are deleted. Limits: 20 seeds, 10,000 pages crawled and processed, 10 hops. The crawl stays on the seed domains by default. The robots.txt setting is a three-way select, default `default`, which omits `obeyRobots` so the crawler's own default applies; only an explicit `off` sends `obeyRobots=0` (SDK 3.4.1 sends an explicit False as 0). The earlier boolean `obey_robots` field is gone, so saved nodes cannot silently ignore robots.txt. A custom request header can be set and is sent to the crawled sites, and the parameter text tells users not to put secrets there. Job names are at most 30 characters. - Destructive action: `crawl_jobs` with `delete` permanently removes a crawl job and its collected data. The action is labeled destructive, and the model is told to delete only on an explicit user request. List, status, results, and delete cover every crawl job on the token's account, not only jobs started from Dify. -- Limits: each call has a configurable timeout of 5 to 300 seconds (default 30). Web search returns at most 50 results, and Knowledge Graph searches return at most 100 records. Crawl results return at most 1,000 rows with cells clipped to 500 characters. Entity resolution accepts up to 20,000 characters. Long text fields are clipped before they reach the model. Errors are rewritten so they never contain the token. Email and phone fields are removed from Knowledge Graph records. +- Limits: each call has a configurable timeout of 5 to 300 seconds (default 30). Web search returns at most 50 results, and Knowledge Graph searches return at most 100 records. Crawl results return at most 1,000 rows with cells clipped to 500 characters. Entity resolution accepts up to 20,000 characters. Long text fields are clipped before they reach the model. Errors are rewritten so they never contain the token. Email and phone fields are removed from Knowledge Graph and NLP JSON, including raw DQL JSON and jsonl. They are not removed from csv, xls and xlsx DQL export files. - Personal data: people search and entity resolution process names, public profile fields, and location text. Neither tool accepts email, phone, or IP input. The Knowledge Graph cannot be filtered by age, so a public profile of a minor could come back. The privacy policy tells users not to send data about children. - Financial data: organization search can return public revenue and headcount figures. The plugin does not move money. - No command execution, code execution, shell, SQL against a customer database, SSH/SFTP, file operations, or browser automation. @@ -295,13 +305,13 @@ A third-party write-up of Marketplace tool installs on 16 October 2026 put Tavil `diffbot-mcp` tools on 9 November 2026: `extract`, `search_web`, `crawl`, `resolve_entities`, `search_news`, `search_organizations`, `search_people`, `search_places`, `search_deals`, `dql`, `dql_probe`, `dql_ontology`. The October 2026 changelog removed MCP `enhance` in favor of `resolve_entities` plus the typed searches. This plugin dropped its `enhance_entity` tool for the same reason (commit 7323b7b), so it matches the Diffbot Python SDK surface. -v1 has what a Dify user expects from Tavily or Firecrawl: search, extract, and crawl. It adds the Knowledge Graph lookups that set Diffbot apart: organizations, people, news, and entity linking. There is no raw DQL tool, so a model cannot send an unbounded query. Crawl is in v1 because Tavily and Firecrawl both offer it. That decision moves the plugin into the "crawl arbitrary URLs" high-risk case. Places, deals, ontology browse, and hit-count probes can come in a later version once v1 has been installed for real. +v1 has what a Dify user expects from Tavily or Firecrawl: search, extract, and crawl. It adds the Knowledge Graph lookups that set Diffbot apart: organizations, people, news, and entity linking. Version 0.2.0 adds a raw DQL tool; it caps size at 100 rows, query length at 10,000 characters and JSON output at 200,000 characters, and scrubs email, phone and html from JSON output (not from csv/xls/xlsx exports). Crawl is in v1 because Tavily and Firecrawl both offer it. That decision moves the plugin into the "crawl arbitrary URLs" high-risk case. Places, deals, ontology browse, and hit-count probes can come in a later version once v1 has been installed for real. The SDK handles authentication as the API docs describe. Extract, Account, Crawl, DQL, and Natural Language take `token` as a query parameter on `api.diffbot.com`, `kg.diffbot.com`, and `nl.diffbot.com`. Web Search on `llm.diffbot.com` uses `Authorization: Bearer`, so the token does not appear in that host's query string. ## Results for the current package -Unit tests: no network, mocked HTTP, run by GitHub CI against `diffbot==3.4.0` from PyPI. They now cover only the native SDK methods; the "legacy SDK" parametrization went away with the fallbacks. +Unit tests: no network, mocked HTTP, run by GitHub CI against `diffbot==3.4.1` from PyPI. They now cover only the native SDK methods; the "legacy SDK" parametrization went away with the fallbacks. Package, 18 November 2026, `dify` CLI v0.6.15, built from the commit that removed the fallbacks: `dist/diffbot-0.1.0.difypkg`, 48,816 bytes, 32 files, sha256 `018d6e6a7951cb1dd033ff6fcb1f2f36734fc7c543f6fb6fe6faf0d6ba74267e`, `dify plugin checksum` `7c9012578f4a2a98b02b0693fe484962de3305620dd0fb63b2de165bb85e3e91`. Contents: `manifest.yaml`, `main.py`, `requirements.txt`, `pyproject.toml`, `README.md`, `PRIVACY.md`, `_assets/icon.png`, `provider/` (`__init__.py`, `diffbot.py`, `diffbot.yaml`), eight tool YAML/Python pairs, and the shared modules `tools/__init__.py`, `client.py`, `common.py`, `sdk.py`, `dql_builder.py`, `shape.py`. No `.env`, `__pycache__`, tests, or `dist/`. `.env.example` stays in git for remote debugging, and `.difyignore` keeps it out of the package. `dist/` is not tracked in git. @@ -321,7 +331,7 @@ Blockers before a real PR: Crawl scope and risk: - Crawling user-supplied URLs is the main reason this plugin is high risk. An agent can start a crawl of any public site the user or the model names. The crawl follows links up to the configured limits and runs on Diffbot's infrastructure, against the user's own Diffbot account and quota. The plugin's URL guard stops literal private and metadata targets. It does not resolve hostnames, and it cannot judge whether the user is allowed to crawl a site. That depends on Diffbot's terms and the user's account. -- The `obey_robots` form field defaults to off. The SDK sends `obeyRobots=1` only when it is on. When it is off, nothing is sent and the Diffbot crawler's own robots.txt default applies, whatever that default is. So the toggle can say "off" while the crawler is still obeying robots.txt, or the reverse. Confirm the API default before release and make the label match it. A reviewer may also want robots.txt respected by default in a Dify-facing tool. That is a product call, and the change is a one-line YAML edit. +- Robots.txt is now a three-way select (`default`, `on`, `off`). `default` sends nothing and the crawler's own default applies; `off` sends `obeyRobots=0`. Confirm the API default before release and word the label to match it. `use_proxies` and `use_canonical` use the same control. A reviewer may prefer robots.txt to be explicitly on by default; that is a product call. - Crawl jobs outlive the tool call. A user who starts a large crawl from an agent keeps using quota after the conversation ends, and the plugin has no cleanup. The tool text says the job runs in the background, and `crawl_jobs` can stop it with `delete`. - `delete` is irreversible and has no confirmation step in the plugin. All that keeps a model from deleting is the LLM description ("only use delete when the user explicitly asks"). It also reaches every crawl job on the token's account, including jobs created outside Dify. If reviewers object, the options are to split delete into its own tool that users can leave disabled, or to limit delete to job names the plugin generated. - The custom header parameter is sent to every crawled site. The parameter text warns against putting secrets there, but the plugin does not enforce that. diff --git a/diffbot/PRIVACY.md b/diffbot/PRIVACY.md index 9a98ee5..e5e98c1 100644 --- a/diffbot/PRIVACY.md +++ b/diffbot/PRIVACY.md @@ -19,8 +19,17 @@ Every tool call leaves the Dify workspace and is processed by Diffbot Technologi | Page URL and page type | `api.diffbot.com` Extract | Fetch and structure one public page. Diffbot retrieves the URL. | | Names, homepages, categories, places, employee and revenue bounds, article phrases, publishers, dates | `kg.diffbot.com` DQL | Search the Knowledge Graph. | | Plain text from the user, up to 20,000 characters, and an optional language code | `nl.diffbot.com` | Recognize and link named entities. | - -The plugin does not offer parameters for email address, phone number, or IP address. If a Knowledge Graph response still contains email or phone values, the plugin drops them before returning the tool result. It also drops article HTML and, unless the news tool is asked for an excerpt, article body text. +| Plain text from the user, up to 20,000 characters, the requested result fields (entities, sentiment, facts, records, categories, sentences, language, summary), language, text format, document type, and summary length | `nl.diffbot.com` NLP | Analyze one document. Facts and records can restate personal data that appears in the text. | +| The question, an optional system prompt (each up to 8,000 characters), the answer format, and an optional JSON schema (up to 20 KB) | `llm.diffbot.com` Ask | Get an answer from Diffbot's LLM. The token is sent as a bearer header. The endpoint is not publicly documented. | +| A raw DQL query (up to 10,000 characters) and its options: type, columns, filters, export spec and separator, JSON mode, clustering, offset, and size | `kg.diffbot.com` DQL | Run any Knowledge Graph query a user or model writes. JSON and jsonl results are scrubbed of email, phone and html fields. csv, xls and xlsx export files are returned as Diffbot sent them and are **not** scrubbed. | +| Nothing from the user. No token or query is sent | `kg.diffbot.com` ontology | Download the public ontology document for the ontology tool and industry matching. The plugin keeps one copy in memory for 24 hours per Diffbot host. | +| Seed URLs, URL patterns and regular expressions, page process pattern, custom request headers, and per-subdomain limits | `api.diffbot.com` Crawl | Start a crawl job. Diffbot stores the settings with the job, and the crawler sends the headers to the crawled sites. Do not put secrets in headers or patterns. | +| An email address (`notify_email`) | `api.diffbot.com` Crawl | Diffbot emails that address about the crawl job. It is personal data. Only a workflow builder can set it, not the model. | +| A webhook URL (`notify_webhook`) | `api.diffbot.com` Crawl | Diffbot calls that URL when the job finishes. Do not put secrets in the URL. Only a workflow builder can set it. | +| The token and the number of days (1 to 366) | `api.diffbot.com` Account API | The Account usage tool reads plan, status and daily usage. The plugin returns only those; it never returns the token, child tokens, or the account email. | +| The token, and queries or text as above | A different Diffbot host, if the optional base URL fields are set | The advanced credential fields (`api_base`, `kg_base`, `llm_base`, `nlp_base`) can point at another host. Only https hosts on `diffbot.com` are accepted. Leave them blank for the defaults. | + +The search tools do not offer parameters for email address, phone number, or IP address (the crawl notification email is the one exception, described above). If a Knowledge Graph or NLP response contains email or phone values, the plugin drops them from the JSON it returns. That includes raw DQL JSON and jsonl output. It does not apply to csv, xls and xlsx export files from the raw DQL tool, which are returned unfiltered. It also drops article HTML and, unless the news tool is asked for an excerpt, article body text. People and organization results can still contain personal data that is already public on the web: names, job titles, employers, cities, countries, homepage URLs, and LinkedIn profile URLs. Diffbot describes people in its index as search subjects whose information was published on publicly available sites. News results can quote public articles. Entity resolution can identify people named in text the user pasted. diff --git a/diffbot/README.md b/diffbot/README.md index 61b7dd2..6f4ae3e 100644 --- a/diffbot/README.md +++ b/diffbot/README.md @@ -2,7 +2,7 @@ Search the public web and the Diffbot Knowledge Graph from a Dify agent or workflow. -Diffbot structures pages and keeps a knowledge graph of organizations, people, and articles. This plugin exposes a small v1 of that API: web search, page extraction, organization and people lookup, news search, and named-entity resolution. A free token from [app.diffbot.com/get-started](https://app.diffbot.com/get-started) is enough to authenticate. +Diffbot structures pages and keeps a knowledge graph of organizations, people, and articles. This plugin covers the Diffbot Python SDK 3.4.1 feature set: web search, Ask, page extraction, raw DQL and ontology lookup, organization, people and news search, crawling, NLP, entity resolution, and account usage. A free token from [app.diffbot.com/get-started](https://app.diffbot.com/get-started) is enough to authenticate. Published by Diffbot. Source: https://github.com/diffbot/dify-diffbot. Support: support@diffbot.com. @@ -18,8 +18,15 @@ Published by Diffbot. Source: https://github.com/diffbot/dify-diffbot. Support: | Start crawl | `GET https://api.diffbot.com/v3/crawl` | Start a background crawl of public seed URLs. Returns a job name, never results. | | Crawl jobs | `/v3/crawl`, `/v3/crawl/data` | List jobs, check status, fetch results (up to 1000 rows, truncated), or delete a job. **Delete is destructive** and removes the job and its data. | | Resolve entities | `POST https://nl.diffbot.com/v1/` | Names in a passage, linked to Knowledge Graph ids when Diffbot can match them. | +| Knowledge Graph query (DQL) | `POST https://kg.diffbot.com/kg/v3/dql` | Any DQL query, with count-only, columns, filters, JSON mode, clustering and csv/xls/xlsx/jsonl output. JSON and jsonl drop email, phone and html fields. Export files (csv, xls, xlsx) are **not** scrubbed. | +| Knowledge Graph ontology | `GET https://kg.diffbot.com/kg/ontology` (no token) | Entity types, fields, enums, and taxonomy values, so DQL uses real names. Cached in memory for 24 hours. | +| Ask Diffbot | `POST https://llm.diffbot.com/rag/v1/chat/completions` | A grounded answer as streamed text, JSON, or JSON that follows your schema. The endpoint is not publicly documented, so it may change. | +| Natural language analysis | `POST https://nl.diffbot.com/v1/` | Entities, sentiment, facts, records, categories, sentences, language and summary for one document. | +| Account usage | `GET https://api.diffbot.com/v4/account` | Plan, status and daily usage. Never returns the token or email. | -Raw DQL, ontology lookup, Ask, places, and deals are not in this version. Industry filters must already be exact category names such as `Software Companies`. The plugin does not resolve free text onto the taxonomy. +Search organizations, people and news accept Count only, which returns just the number of matches. The organization industry text is matched against the ontology's `OrganizationCategory` taxonomy (exact, then case-insensitive); a miss returns close suggestions. Extract also supports the `job` page type and calling a Custom API you already created by name. Start crawl has per-subdomain limits, regex patterns, and webhook and email notification (workflow builders only). Places and deals have no dedicated tool; use the DQL tool. Not included: Enhance, Bulk Extract, Custom API management, crawl pause and restart, and the SDK's file-writing ontology refresh. + +The crawl robots.txt, proxy and canonical-URL settings are three-way selects: **Diffbot default** leaves the parameter out so the API default applies, and **Off** sends `0`. They replace the old on/off fields, so workflows saved with the old fields fall back to the Diffbot default instead of silently ignoring robots.txt. ## Credentials @@ -27,6 +34,7 @@ Raw DQL, ontology lookup, Ask, places, and deals are not in this version. Indust 2. In Dify, open Plugins, install this package, and choose Diffbot. 3. Paste the token into **Diffbot token**. 4. Optional: set **Request timeout** (5 to 300 seconds, default 30). +5. Advanced, optional: **API base URL**, **Knowledge Graph base URL**, **LLM and web search base URL**, and **Natural language base URL**. Leave them blank. A value must be an https URL on `diffbot.com` or a subdomain, with no credentials, query, or fragment, because your token is sent there. Dify stores the value as a secret. The plugin sends it only to the Diffbot hosts listed in `manifest.yaml`. Web Search uses `Authorization: Bearer`. The other calls use the `token` query parameter, which is how those APIs authenticate. Saving the credential calls `GET https://api.diffbot.com/v4/account` with `days=1` and does not show the account payload. @@ -34,7 +42,7 @@ The token needs access to Extract, Web Search, Knowledge Graph, and Natural Lang ## Use the tools -In an Agent, add the Diffbot tools and ask for a company, a news topic, or a URL. In a Workflow, add a tool node and pick one action. Required fields are marked on each tool. Limits: up to 50 web results, 100 Knowledge Graph rows per call (page with Offset), and 20,000 characters of text for entity resolution. Extract has optional caller-set options (fields, timeout, mode, paging, natural language, and others). +In an Agent, add the Diffbot tools and ask for a company, a news topic, or a URL. In a Workflow, add a tool node and pick one action. Required fields are marked on each tool. Limits: up to 5 web search queries and 50 results, 100 Knowledge Graph rows per call (page with Offset), 20,000 characters of text for entity resolution and NLP, 8,000 characters for an Ask question, and 200,000 characters of DQL JSON output (a `truncated` flag is set when it is cut). Extract has optional caller-set options (fields, timeout, mode, paging, natural language, and others). Extract accepts `http` and `https` URLs; a bare domain such as `example.com` gets `https://`. Localhost, link-local, and private literal addresses are rejected before the request is sent. @@ -43,15 +51,15 @@ Extract accepts `http` and `https` URLs; a bare domain such as `example.com` get From the repository root, with the [Dify plugin CLI](https://github.com/langgenius/dify-plugin-daemon) installed: ```bash -dify plugin package ./diffbot -o dist/diffbot-0.1.0.difypkg +dify plugin package ./diffbot -o dist/diffbot-0.2.0.difypkg ``` In Dify, open Plugins and install the `.difypkg` from a local file. Self-hosted Dify verifies signatures by default. Either install on a server that trusts a key you control, or sign the file: ```bash dify signature generate -f your_key_pair -dify signature sign dist/diffbot-0.1.0.difypkg -p your_key_pair.private.pem -dify signature verify dist/diffbot-0.1.0.signed.difypkg -p your_key_pair.public.pem +dify signature sign dist/diffbot-0.2.0.difypkg -p your_key_pair.private.pem +dify signature verify dist/diffbot-0.2.0.signed.difypkg -p your_key_pair.public.pem ``` Keep the private key off this repository. Marketplace publication signs with Dify's key after review, so a third-party signature is only for Community Edition installs outside the marketplace. See [third-party signature verification](https://docs.dify.ai/en/develop-plugin/publishing/standards/third-party-signature-verification). @@ -67,7 +75,7 @@ Outbound HTTPS to: - `llm.diffbot.com` - `nl.diffbot.com` -No database, filesystem, or browser is required. The plugin does not call any host other than those four. +No database, filesystem, or browser is required. The plugin does not call any host other than those four, unless you fill in an advanced base URL field, and then only another `diffbot.com` host. ## Source repository and support @@ -77,4 +85,4 @@ No database, filesystem, or browser is required. The plugin does not call any ho ## Privacy -See [PRIVACY.md](PRIVACY.md). Queries, URLs, and passage text are sent to Diffbot. The plugin does not store them. +See [PRIVACY.md](PRIVACY.md). Queries, URLs, passage text, questions, and crawl settings are sent to Diffbot. The plugin does not store them. From 63f375bf0ba3c05e9b4b28445f1d8870aa56696e Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:38:10 -1000 Subject: [PATCH 6/7] Tighten NLP summary cap, ontology validation and crawl webhook scheme - nlp: max_number_of_sentences is 1 to 10, as the SDK documents (was 1 to 50). - ontology_cache: a non-object ontology document is treated as a failed fetch (backoff, stale copy if any) instead of being cached and crashing later lookups or industry matching with AttributeError. - crawl_start: notify_webhook must be https, matching its help text. - Tests for all three. Co-Authored-By: Claude Opus 5.5 --- diffbot/tools/crawl_start.py | 5 ++++- diffbot/tools/nlp.py | 2 +- diffbot/tools/nlp.yaml | 6 +++--- diffbot/tools/ontology_cache.py | 3 +++ tests/test_parity_3_4_1.py | 33 ++++++++++++++++++++++++++++----- 5 files changed, 39 insertions(+), 10 deletions(-) diff --git a/diffbot/tools/crawl_start.py b/diffbot/tools/crawl_start.py index ab38781..b98f9a6 100644 --- a/diffbot/tools/crawl_start.py +++ b/diffbot/tools/crawl_start.py @@ -106,7 +106,10 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag kwargs["custom_headers"] = headers webhook = optional_text(tool_parameters, "notify_webhook") if webhook: - kwargs["notify_webhook"] = validate_public_http_url(webhook) + webhook = validate_public_http_url(webhook) + if not webhook.lower().startswith("https://"): + raise DiffbotError("notify_webhook must start with https://.") + kwargs["notify_webhook"] = webhook email = optional_text(tool_parameters, "notify_email") if email: if len(email) > 254 or not _EMAIL.fullmatch(email): diff --git a/diffbot/tools/nlp.py b/diffbot/tools/nlp.py index 8b867b1..c04dcf7 100644 --- a/diffbot/tools/nlp.py +++ b/diffbot/tools/nlp.py @@ -46,7 +46,7 @@ def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessag options: dict[str, Any] = {} sentences = tool_parameters.get("max_number_of_sentences") if sentences not in (None, ""): - count = int(bounded_number(sentences, label="max_number_of_sentences", minimum=1, maximum=50, integer=True)) + count = int(bounded_number(sentences, label="max_number_of_sentences", minimum=1, maximum=10, integer=True)) options["custom_summary"] = {"max_number_of_sentences": count} client = make_client(self.runtime.credentials) diff --git a/diffbot/tools/nlp.yaml b/diffbot/tools/nlp.yaml index b0a68cb..8b3d06a 100644 --- a/diffbot/tools/nlp.yaml +++ b/diffbot/tools/nlp.yaml @@ -71,12 +71,12 @@ parameters: required: false form: form min: 1 - max: 50 + max: 10 label: en_US: Summary sentences human_description: - en_US: Most sentences in the summary (1 to 50). Used when the summary field is requested. - llm_description: Most sentences in the summary, 1 to 50. + en_US: Most sentences in the summary (1 to 10). Used when the summary field is requested. + llm_description: Most sentences in the summary, 1 to 10. extra: python: source: tools/nlp.py diff --git a/diffbot/tools/ontology_cache.py b/diffbot/tools/ontology_cache.py index 07528a7..e9a748f 100644 --- a/diffbot/tools/ontology_cache.py +++ b/diffbot/tools/ontology_cache.py @@ -61,6 +61,9 @@ def get(self, client: Diffbot) -> Ontology: raise DiffbotError("The Knowledge Graph ontology is temporarily unavailable. Try again in a few minutes.") try: ontology = client.dql_fetch_ontology() + if not isinstance(getattr(ontology, "data", None), dict): + # e.g. an error page or a JSON list: do not cache something the lookups cannot read + raise DiffbotError("Diffbot returned an unexpected ontology document.") except Exception: entry.retry_after = now + self._backoff if entry.ontology is not None: diff --git a/tests/test_parity_3_4_1.py b/tests/test_parity_3_4_1.py index d15b4c3..76636c2 100644 --- a/tests/test_parity_3_4_1.py +++ b/tests/test_parity_3_4_1.py @@ -8,6 +8,7 @@ import httpx import pytest +from diffbot.ontology import Ontology from provider.diffbot import DiffbotProvider from tools import ontology_cache, sdk @@ -211,6 +212,7 @@ def test_crawl_new_options_reach_the_wire(serve): @pytest.mark.parametrize("extra,match", [ ({"notify_webhook": "http://localhost/x"}, "not allowed"), ({"notify_webhook": "ftp://example.org"}, "http"), + ({"notify_webhook": "http://hooks.example.org/x"}, "https"), ({"notify_email": "not-an-email"}, "email"), ({"job_name": "j" * 31}, "30 characters"), ]) @@ -325,6 +327,8 @@ def test_nlp_validation(): run(NlpTool, {"text": "x" * 20_001}) with pytest.raises(DiffbotError, match="fields"): run(NlpTool, {"text": "x", "fields": "bogus"}) + with pytest.raises(DiffbotError, match="max_number_of_sentences"): + run(NlpTool, {"text": "x", "max_number_of_sentences": 11}) def test_account_usage_returns_only_allowlisted_fields(serve): @@ -450,7 +454,7 @@ def dql_fetch_ontology(self): def test_ontology_cache_ttl_stale_on_failure_and_backoff(): now = [0.0] cache = ontology_cache.OntologyCache(clock=lambda: now[0], ttl=100, backoff=10) - first, second = object(), object() + first, second = Ontology({"types": {}}), Ontology({"types": {}}) client = FakeClient("u1", [first, httpx.ConnectError("down"), second]) assert cache.get(client) is first and cache.get(client) is first and client.calls == 1 now[0] = 101 # expired; refresh fails -> stale copy, then back off @@ -463,16 +467,35 @@ def test_ontology_cache_ttl_stale_on_failure_and_backoff(): def test_ontology_cache_backs_off_after_failure_with_no_stale_copy_and_keys_by_url(): now = [0.0] cache = ontology_cache.OntologyCache(clock=lambda: now[0], ttl=100, backoff=10) - bad = FakeClient("u1", [httpx.ConnectError("down"), "ok"]) + ok, other_doc = Ontology({"types": {}}), Ontology({"enums": {}}) + bad = FakeClient("u1", [httpx.ConnectError("down"), ok]) with pytest.raises(httpx.ConnectError): cache.get(bad) with pytest.raises(DiffbotError, match="temporarily"): cache.get(bad) assert bad.calls == 1 - other = FakeClient("u2", ["other"]) - assert cache.get(other) == "other" # a different URL has its own entry + other = FakeClient("u2", [other_doc]) + assert cache.get(other) is other_doc # a different URL has its own entry now[0] = 11 - assert cache.get(bad) == "ok" + assert cache.get(bad) is ok + + +def test_ontology_cache_rejects_a_non_object_document_and_backs_off(): + now = [0.0] + cache = ontology_cache.OntologyCache(clock=lambda: now[0], ttl=100, backoff=10) + client = FakeClient("u1", [Ontology(["not", "a", "dict"])]) # type: ignore[arg-type] + with pytest.raises(DiffbotError, match="unexpected ontology"): + cache.get(client) + with pytest.raises(DiffbotError, match="temporarily"): + cache.get(client) + assert client.calls == 1 + + +def test_industry_passes_through_when_the_ontology_is_not_an_object(serve): + seen = serve(lambda r: httpx.Response(200, json=[1, 2]) if r.url.path == "/kg/ontology" + else httpx.Response(200, json={"hits": 0, "data": []})) + run(SearchOrganizationsTool, {"industry": "Widgets"}) + assert 'categories.name:"Widgets"' in _body(seen[-1])["query"] def test_ontology_lookups(serve): From 9a6c262edf2074748334975397ddd1ad876eac41 Mon Sep 17 00:00:00 2001 From: Andrew Wessels Date: Fri, 27 Nov 2026 12:38:10 -1000 Subject: [PATCH 7/7] Fix stale SUBMISSION claims and PRIVACY scrub wording for 0.2.0 - SUBMISSION.md: base URLs can now be overridden (diffbot.com https only), so drop "neither credentials nor parameters can change the SDK base URLs" and the matching access_domains note; runbook commands and PR body use 0.2.0; mark the 0.1.0 checksum and validator lines stale inline; remove the "PRIVACY.md does not describe crawl" blocker; ontology and hit counts are no longer "later version" items. - PRIVACY.md: say the scrub drops email and phone fields, not every email or phone value in free text. Co-Authored-By: Claude Opus 5.5 --- SUBMISSION.md | 51 +++++++++++++++++++++++----------------------- diffbot/PRIVACY.md | 2 +- 2 files changed, 26 insertions(+), 27 deletions(-) diff --git a/SUBMISSION.md b/SUBMISSION.md index ba2763a..15cc328 100644 --- a/SUBMISSION.md +++ b/SUBMISSION.md @@ -29,7 +29,7 @@ Done: - Icon: `_assets/icon.png` is the official 2026 Diffbot logomark, the green rounded-square tile (512×512 PNG). - `meta.minimum_dify_version`: 1.14.0. The dify_plugin 0.11.0 README lists Dify 1.14.0 for SDK 0.8.1 and later. The plugin uses no later gated feature (OAuth, dynamic-select, multiple selects, reset_on_change). The optional dynamic-select for the organization industry was not added. - Unit tests: `pytest` with mocked HTTP, run by GitHub CI against `diffbot==3.4.1` from PyPI. -- `diffbot` 3.4.0 is on PyPI (18 November 2026) and pinned. The feature-detect fallbacks in `diffbot/tools/sdk.py` (`verify_token`, `crawl_download`, extract options) and the local TypedDicts in `tools/sdk_types.py` are gone; the plugin calls the native 3.4.0 methods. +- `diffbot==3.4.1` is pinned exactly (3.4.0 was published 18 November 2026; 3.4.1 adds the tri-state `obeyRobots`/`useProxies` fix). The feature-detect fallbacks in `diffbot/tools/sdk.py` (`verify_token`, `crawl_download`, extract options) and the local TypedDicts in `tools/sdk_types.py` are gone; the plugin calls the native SDK methods. - Marketplace validator rerun on the rebuilt package on 18 November 2026: exit 0, 0 blocking failures, serverless start-up test passed. See "Results for the current package". Still to do: @@ -102,16 +102,16 @@ From `provider/diffbot.yaml` `credentials_for_provider`: - `llm.diffbot.com` (Web Search) - `nl.diffbot.com` (Natural Language) -The plugin process only talks to these four hosts. Neither credentials nor parameters can change the SDK base URLs. User-supplied URLs (extract `url`, crawl `seeds`, crawl `api_url`) go to Diffbot as parameters, and Diffbot's own infrastructure fetches them. The plugin does not. +By default the plugin process only talks to these four hosts. Tool parameters cannot change the SDK base URLs. The optional advanced credential fields (`api_base`, `kg_base`, `llm_base`, `nlp_base`) can, but `make_client` accepts only https URLs on `diffbot.com` or a subdomain, with no credentials, query, fragment, or non-default port, so the token can only go to a Diffbot host. A `*.diffbot.com` host other than the four above is not in `network.domains` and may be blocked where Dify enforces that list. User-supplied URLs (extract `url`, crawl `seeds`, crawl `api_url`) go to Diffbot as parameters, and Diffbot's own infrastructure fetches them. The plugin does not. ## Package the file they will attach From a checkout of the plugin, with the Dify plugin CLI (the 18 November 2026 run used `dify` v0.6.15, the same as the v0.1 run): ```bash -dify plugin package ./diffbot -o dist/diffbot-0.1.0.difypkg -dify plugin checksum dist/diffbot-0.1.0.difypkg -python3 validator/validate-difypkg.py dist/diffbot-0.1.0.difypkg --output-dir ./validation-report +dify plugin package ./diffbot -o dist/diffbot-0.2.0.difypkg +dify plugin checksum dist/diffbot-0.2.0.difypkg +python3 validator/validate-difypkg.py dist/diffbot-0.2.0.difypkg --output-dir ./validation-report ``` The validator lives in [langgenius/dify-marketplace-toolkit](https://github.com/langgenius/dify-marketplace-toolkit) (it needs `yq` on `PATH`). Exit code 0 means no blocking package errors. Warnings still need an explanation in the PR. The PR body below already carries the 18 November 2026 run's results. @@ -120,8 +120,8 @@ The validator lives in [langgenius/dify-marketplace-toolkit](https://github.com/ ```bash dify signature generate -f your_key_pair -dify signature sign dist/diffbot-0.1.0.difypkg -p your_key_pair.private.pem -c community -dify signature verify dist/diffbot-0.1.0.signed.difypkg -p your_key_pair.public.pem +dify signature sign dist/diffbot-0.2.0.difypkg -p your_key_pair.private.pem -c community +dify signature verify dist/diffbot-0.2.0.signed.difypkg -p your_key_pair.public.pem ``` Keep the private key out of git. `dify signature verify` with no `-p` checks the Marketplace public key and will reject this package, which is expected before Dify signs it. Community Edition with `FORCE_VERIFYING_SIGNATURE=true` will also reject the unsigned file until an admin adds the matching public key. See the signature doc linked above. @@ -131,10 +131,10 @@ Keep the private key out of git. `dify signature verify` with no `-p` checks the Fork `langgenius/dify-plugins`, sync `main`, and branch. The current publishing guide wants exactly one new `.difypkg` in the PR. Suggested path: ```text -diffbot/diffbot/diffbot-0.1.0.difypkg +diffbot/diffbot/diffbot-0.2.0.difypkg ``` -That is `//-.difypkg`. Owner, plugin name, and version must match `manifest.yaml` (`diffbot`, `diffbot`, `0.1.0`). +That is `//-.difypkg`. Owner, plugin name, and version must match `manifest.yaml` (`diffbot`, `diffbot`, `0.2.0`). ```bash git clone https://github.com//dify-plugins.git @@ -143,13 +143,13 @@ git remote add upstream https://github.com/langgenius/dify-plugins.git git fetch upstream git switch main git merge --ff-only upstream/main -git switch -c add-diffbot-0.1.0 +git switch -c add-diffbot-0.2.0 mkdir -p diffbot/diffbot -cp /path/to/diffbot-0.1.0.difypkg diffbot/diffbot/ -git add diffbot/diffbot/diffbot-0.1.0.difypkg +cp /path/to/diffbot-0.2.0.difypkg diffbot/diffbot/ +git add diffbot/diffbot/diffbot-0.2.0.difypkg git status --short git diff --stat -git commit -m "add diffbot 0.1.0" +git commit -m "add diffbot 0.2.0" git push -u origin HEAD ``` @@ -157,7 +157,7 @@ Open the PR against `langgenius/dify-plugins:main`. Do not open it as a draft un The repository README still says to commit plugin source next to the package. The current publish guide and the Exa resubmission (`langgenius/dify-plugins` #2692, merged 13 July 2026) say the opposite: CI must see one `.difypkg`, and source stays in the public repo linked from the manifest. Follow the current guide. If a reviewer asks for the source tree inside `dify-plugins`, add it only in the way they specify, in that same PR. -Later versions add a new file such as `diffbot/diffbot/diffbot-0.2.0.difypkg` and leave the old package in place unless a maintainer says to delete it. Bump `version` in `manifest.yaml`. Do not reuse `0.1.0`. +0.1.0 was never submitted, so the first submission is 0.2.0. Later versions add a new file such as `diffbot/diffbot/diffbot-0.3.0.difypkg` and leave the old package in place unless a maintainer says to delete it. Bump `version` in `manifest.yaml`. Do not reuse a submitted version. ## PR body to paste @@ -170,7 +170,7 @@ Fill this in from the live template. Keep every section. Check exactly one risk - **Author**: diffbot - **Plugin name**: diffbot -- **Version**: 0.1.0 +- **Version**: 0.2.0 - **Source repository**: https://github.com/diffbot/dify-diffbot - **Contact**: support@diffbot.com @@ -229,20 +229,20 @@ Extract and crawl both send user-supplied http(s) URLs to Diffbot, and Diffbot f ## Local validation ```text -dify plugin package ./diffbot -o dist/diffbot-0.1.0.difypkg # dify CLI v0.6.15 -dify plugin checksum dist/diffbot-0.1.0.difypkg -python3 validator/validate-difypkg.py dist/diffbot-0.1.0.difypkg --output-dir ./validation-report --pr-body-file pr-body.md +dify plugin package ./diffbot -o dist/diffbot-0.2.0.difypkg # dify CLI v0.6.15 +dify plugin checksum dist/diffbot-0.2.0.difypkg +python3 validator/validate-difypkg.py dist/diffbot-0.2.0.difypkg --output-dir ./validation-report --pr-body-file pr-body.md ``` -Checksum (`dify plugin checksum`): `7c9012578f4a2a98b02b0693fe484962de3305620dd0fb63b2de165bb85e3e91`. Archive: 48,816 bytes, 32 files. +Checksum (`dify plugin checksum`): STALE, from the 0.1.0 package: `7c9012578f4a2a98b02b0693fe484962de3305620dd0fb63b2de165bb85e3e91`. Archive: 48,816 bytes, 32 files. Replace with the 0.2.0 numbers. -Validator (dify-marketplace-toolkit `83ee707`): exit 0, 0 blocking failures, 0 execution failures. All 12 checks PASS: package_contents, package_secrets, package_binaries, manifest_metadata, readme_metadata, package_dependencies, python_compile, sensitive_capabilities (blocking), and python_safety, prohibited_financial_activity, access_domains, dependency_vulnerabilities (warning). Warnings, explained: -- dependency_vulnerabilities: `requirements.txt` has 2 pinned, 0 unpinned (`dify_plugin==0.11.0`, `diffbot==3.4.0`). OSV reports no known vulnerabilities in the pinned set. -- access_domains: "manifest declares network.domains but the static scan found no literal hostname; this is expected for SDK-based plugins." The Diffbot base URLs live inside the `diffbot` SDK. The plugin cannot change them, and the four declared hosts are the only ones the SDK calls. +Validator (dify-marketplace-toolkit `83ee707`, STALE: 0.1.0 package, rerun on 0.2.0): exit 0, 0 blocking failures, 0 execution failures. All 12 checks PASS: package_contents, package_secrets, package_binaries, manifest_metadata, readme_metadata, package_dependencies, python_compile, sensitive_capabilities (blocking), and python_safety, prohibited_financial_activity, access_domains, dependency_vulnerabilities (warning). Warnings, explained: +- dependency_vulnerabilities: `requirements.txt` has 2 pinned, 0 unpinned (`dify_plugin==0.11.0`, `diffbot==3.4.0` in the stale run). OSV reports no known vulnerabilities in the pinned set. +- access_domains: "manifest declares network.domains but the static scan found no literal hostname; this is expected for SDK-based plugins." The Diffbot base URLs live inside the `diffbot` SDK, and the four declared hosts are the only ones it calls by default. The optional advanced credential fields can point it at another https `diffbot.com` host and nothing else. - package_secrets: `tools/sdk.py` `INVALID_TOKEN` was flagged for review. It is the error text "Invalid or unauthorized Diffbot token.", not a secret. - python_safety: `tools/sdk.py` returns or raises values that may contain credentials (the `Diffbot(...)` client built with the user's token, and error messages). Every error string passes through `redact(..., token)` first, and the client object never reaches tool output. -Unit tests: `pytest` with mocked HTTP, green in GitHub CI on `diffbot==3.4.0`. Plugin start-up (`validator/test-plugin-install.py`, `INSTALL_METHOD=serverless`): success ("Serving Flask app", request to port 8080 succeeded). +Unit tests: `pytest` with mocked HTTP, run in GitHub CI on `diffbot==3.4.1` (confirm green before pasting). Plugin start-up (`validator/test-plugin-install.py`, `INSTALL_METHOD=serverless`): success ("Serving Flask app", request to port 8080 succeeded). Live smoke test: PENDING. Rerun every tool, including a crawl start/status/results/delete cycle, against the Diffbot API with a real token. @@ -305,7 +305,7 @@ A third-party write-up of Marketplace tool installs on 16 October 2026 put Tavil `diffbot-mcp` tools on 9 November 2026: `extract`, `search_web`, `crawl`, `resolve_entities`, `search_news`, `search_organizations`, `search_people`, `search_places`, `search_deals`, `dql`, `dql_probe`, `dql_ontology`. The October 2026 changelog removed MCP `enhance` in favor of `resolve_entities` plus the typed searches. This plugin dropped its `enhance_entity` tool for the same reason (commit 7323b7b), so it matches the Diffbot Python SDK surface. -v1 has what a Dify user expects from Tavily or Firecrawl: search, extract, and crawl. It adds the Knowledge Graph lookups that set Diffbot apart: organizations, people, news, and entity linking. Version 0.2.0 adds a raw DQL tool; it caps size at 100 rows, query length at 10,000 characters and JSON output at 200,000 characters, and scrubs email, phone and html from JSON output (not from csv/xls/xlsx exports). Crawl is in v1 because Tavily and Firecrawl both offer it. That decision moves the plugin into the "crawl arbitrary URLs" high-risk case. Places, deals, ontology browse, and hit-count probes can come in a later version once v1 has been installed for real. +v1 has what a Dify user expects from Tavily or Firecrawl: search, extract, and crawl. It adds the Knowledge Graph lookups that set Diffbot apart: organizations, people, news, and entity linking. Version 0.2.0 adds a raw DQL tool; it caps size at 100 rows, query length at 10,000 characters and JSON output at 200,000 characters, and scrubs email, phone and html from JSON output (not from csv/xls/xlsx exports). Crawl is in v1 because Tavily and Firecrawl both offer it. That decision moves the plugin into the "crawl arbitrary URLs" high-risk case. Version 0.2.0 also adds ontology lookup (`kg_ontology`) and hit counts (`count_only`). Places and deals can come in a later version once the plugin has been installed for real. The SDK handles authentication as the API docs describe. Extract, Account, Crawl, DQL, and Natural Language take `token` as a query parameter on `api.diffbot.com`, `kg.diffbot.com`, and `nl.diffbot.com`. Web Search on `llm.diffbot.com` uses `Authorization: Bearer`, so the token does not appear in that host's query string. @@ -323,8 +323,7 @@ Live smoke test: **PENDING.** It needs a real Diffbot token, and none was availa Blockers before a real PR: -- The live smoke test (every tool, including a crawl cycle) has not been rerun on the 3.4.0 package. -- PRIVACY.md does not describe crawl yet. +- The live smoke test (every tool, including a crawl cycle and the new 0.2.0 tools) has not been run on the 0.2.0 package. - The package has not been installed in Dify Community Edition or Dify Cloud. Do that, or write the limitation in the PR. - Whoever opens the PR must be allowed to publish under the `diffbot` author name. Open it from a fork owned by, or on behalf of, the `diffbot` organization. diff --git a/diffbot/PRIVACY.md b/diffbot/PRIVACY.md index e5e98c1..0d5248e 100644 --- a/diffbot/PRIVACY.md +++ b/diffbot/PRIVACY.md @@ -29,7 +29,7 @@ Every tool call leaves the Dify workspace and is processed by Diffbot Technologi | The token and the number of days (1 to 366) | `api.diffbot.com` Account API | The Account usage tool reads plan, status and daily usage. The plugin returns only those; it never returns the token, child tokens, or the account email. | | The token, and queries or text as above | A different Diffbot host, if the optional base URL fields are set | The advanced credential fields (`api_base`, `kg_base`, `llm_base`, `nlp_base`) can point at another host. Only https hosts on `diffbot.com` are accepted. Leave them blank for the defaults. | -The search tools do not offer parameters for email address, phone number, or IP address (the crawl notification email is the one exception, described above). If a Knowledge Graph or NLP response contains email or phone values, the plugin drops them from the JSON it returns. That includes raw DQL JSON and jsonl output. It does not apply to csv, xls and xlsx export files from the raw DQL tool, which are returned unfiltered. It also drops article HTML and, unless the news tool is asked for an excerpt, article body text. +The search tools do not offer parameters for email address, phone number, or IP address (the crawl notification email is the one exception, described above). If a Knowledge Graph or NLP response contains email or phone fields (such as `emails`, `emailAddresses`, or `phoneNumbers`), the plugin drops those fields from the JSON it returns. It does not search free text, such as descriptions or article bodies, for addresses or numbers. That includes raw DQL JSON and jsonl output. It does not apply to csv, xls and xlsx export files from the raw DQL tool, which are returned unfiltered. It also drops article HTML and, unless the news tool is asked for an excerpt, article body text. People and organization results can still contain personal data that is already public on the web: names, job titles, employers, cities, countries, homepage URLs, and LinkedIn profile URLs. Diffbot describes people in its index as search subjects whose information was published on publicly available sites. News results can quote public articles. Entity resolution can identify people named in text the user pasted.