From 39d9ff46d294cd6890f104e393b6a00f7f776002 Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Mon, 30 Mar 2026 12:59:17 -0700 Subject: [PATCH 1/9] feat(nodes): add Exa semantic web search node for real-time data enrichment Adds a new tool_exa_search node that integrates with the Exa API (exa.ai) to provide semantic web search capabilities for pipelines. Agents can invoke this tool to search the web in real time and retrieve structured results including titles, URLs, text content, relevance scores, and published dates. Closes #429 Co-Authored-By: Claude Opus 4.6 (1M context) --- nodes/src/nodes/tool_exa_search/IGlobal.py | 85 +++++ nodes/src/nodes/tool_exa_search/IInstance.py | 48 +++ nodes/src/nodes/tool_exa_search/__init__.py | 29 ++ nodes/src/nodes/tool_exa_search/exa_driver.py | 338 ++++++++++++++++++ .../nodes/tool_exa_search/requirements.txt | 1 + nodes/src/nodes/tool_exa_search/services.json | 93 +++++ 6 files changed, 594 insertions(+) create mode 100644 nodes/src/nodes/tool_exa_search/IGlobal.py create mode 100644 nodes/src/nodes/tool_exa_search/IInstance.py create mode 100644 nodes/src/nodes/tool_exa_search/__init__.py create mode 100644 nodes/src/nodes/tool_exa_search/exa_driver.py create mode 100644 nodes/src/nodes/tool_exa_search/requirements.txt create mode 100644 nodes/src/nodes/tool_exa_search/services.json diff --git a/nodes/src/nodes/tool_exa_search/IGlobal.py b/nodes/src/nodes/tool_exa_search/IGlobal.py new file mode 100644 index 0000000000..104d0fc89c --- /dev/null +++ b/nodes/src/nodes/tool_exa_search/IGlobal.py @@ -0,0 +1,85 @@ +# ============================================================================= +# RocketRide Engine +# ============================================================================= +# MIT License +# Copyright (c) 2026 Aparavi Software AG +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# ============================================================================= + +""" +Exa Search tool node - global (shared) state. + +Reads the Exa API key and search configuration from the node config, +then creates an ExaSearchDriver that implements the ToolsBase interface. +""" + +from __future__ import annotations + +from ai.common.config import Config +from rocketlib import IGlobalBase, OPEN_MODE, warning + +from .exa_driver import ExaSearchDriver + + +class IGlobal(IGlobalBase): + """Global state for tool_exa_search.""" + + driver: ExaSearchDriver | None = None + + def beginGlobal(self) -> None: + if self.IEndpoint.endpoint.openMode == OPEN_MODE.CONFIG: + return + + cfg = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) + + apikey = str((cfg.get('apikey') or '')).strip() + + if not apikey: + raise Exception('tool_exa_search: apikey is required') + + num_results = int(cfg.get('numResults') or 10) + use_autoprompt = bool(cfg.get('useAutoprompt', True)) + search_type = str(cfg.get('searchType') or 'auto').strip() + include_text = bool(cfg.get('includeText', True)) + + try: + self.driver = ExaSearchDriver( + server_name='exa', + apikey=apikey, + num_results=num_results, + use_autoprompt=use_autoprompt, + search_type=search_type, + include_text=include_text, + ) + except Exception as e: + warning(str(e)) + raise + + def validateConfig(self) -> None: + try: + cfg = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) + apikey = str((cfg.get('apikey') or '')).strip() + if not apikey: + warning('apikey is required') + except Exception as e: + warning(str(e)) + + def endGlobal(self) -> None: + self.driver = None diff --git a/nodes/src/nodes/tool_exa_search/IInstance.py b/nodes/src/nodes/tool_exa_search/IInstance.py new file mode 100644 index 0000000000..449f44c624 --- /dev/null +++ b/nodes/src/nodes/tool_exa_search/IInstance.py @@ -0,0 +1,48 @@ +# ============================================================================= +# RocketRide Engine +# ============================================================================= +# MIT License +# Copyright (c) 2026 Aparavi Software AG +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# ============================================================================= + +""" +Exa Search tool node instance. + +Delegates tool invoke operations to the ExaSearchDriver. +""" + +from __future__ import annotations + +from typing import Any + +from rocketlib import IInstanceBase + +from .IGlobal import IGlobal + + +class IInstance(IInstanceBase): + IGlobal: IGlobal + + def invoke(self, param: Any) -> Any: # noqa: ANN401 + driver = getattr(self.IGlobal, 'driver', None) + if driver is None: + raise RuntimeError('tool_exa_search: driver not initialized') + return driver.handle_invoke(param) diff --git a/nodes/src/nodes/tool_exa_search/__init__.py b/nodes/src/nodes/tool_exa_search/__init__.py new file mode 100644 index 0000000000..37de11f283 --- /dev/null +++ b/nodes/src/nodes/tool_exa_search/__init__.py @@ -0,0 +1,29 @@ +# ============================================================================= +# RocketRide Engine +# ============================================================================= +# MIT License +# Copyright (c) 2026 Aparavi Software AG +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# ============================================================================= + +from .IGlobal import IGlobal +from .IInstance import IInstance + +__all__ = ['IGlobal', 'IInstance'] diff --git a/nodes/src/nodes/tool_exa_search/exa_driver.py b/nodes/src/nodes/tool_exa_search/exa_driver.py new file mode 100644 index 0000000000..3f98bd0096 --- /dev/null +++ b/nodes/src/nodes/tool_exa_search/exa_driver.py @@ -0,0 +1,338 @@ +# ============================================================================= +# RocketRide Engine +# ============================================================================= +# MIT License +# Copyright (c) 2026 Aparavi Software AG +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# ============================================================================= + +""" +Exa Search tool-provider driver. + +Implements ``tool.query``, ``tool.validate``, and ``tool.invoke`` for the Exa +semantic web search API. Exposes a single ``exa_search`` tool that agents can +invoke with a natural-language query to retrieve real-time web results. +""" + +from __future__ import annotations + +import json +import time +from typing import Any, Dict, List + +import requests + +from rocketlib import debug, warning + +from ai.common.tools import ToolsBase + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +EXA_SEARCH_URL = 'https://api.exa.ai/search' +EXA_CONTENTS_URL = 'https://api.exa.ai/contents' + +VALID_SEARCH_TYPES = {'auto', 'neural', 'keyword'} + +INPUT_SCHEMA: Dict[str, Any] = { + 'type': 'object', + 'required': ['query'], + 'properties': { + 'query': { + 'type': 'string', + 'description': 'The search query. Can be a natural language question or keyword phrase.', + }, + 'num_results': { + 'type': 'integer', + 'description': 'Number of results to return (1-50). Defaults to the node config value.', + }, + 'type': { + 'type': 'string', + 'enum': sorted(VALID_SEARCH_TYPES), + 'description': 'Search type: "auto" (default), "neural" (semantic), or "keyword" (traditional).', + }, + 'use_autoprompt': { + 'type': 'boolean', + 'description': 'Whether to let Exa optimize the query for better results.', + }, + 'include_domains': { + 'type': 'array', + 'items': {'type': 'string'}, + 'description': 'Only return results from these domains (e.g. ["arxiv.org", "github.com"]).', + }, + 'exclude_domains': { + 'type': 'array', + 'items': {'type': 'string'}, + 'description': 'Exclude results from these domains.', + }, + 'start_published_date': { + 'type': 'string', + 'description': 'Only return results published after this date (ISO 8601, e.g. "2024-01-01").', + }, + 'end_published_date': { + 'type': 'string', + 'description': 'Only return results published before this date (ISO 8601, e.g. "2025-12-31").', + }, + 'include_text': { + 'type': 'boolean', + 'description': 'Whether to include full text content in results. Defaults to node config value.', + }, + }, +} + + +class ExaSearchDriver(ToolsBase): + """Tool provider for Exa semantic web search.""" + + def __init__( + self, + *, + server_name: str, + apikey: str, + num_results: int = 10, + use_autoprompt: bool = True, + search_type: str = 'auto', + include_text: bool = True, + ) -> None: + """Initialize the Exa search driver with API key and default search parameters.""" + self._server_name = (server_name or '').strip() or 'exa' + self._apikey = apikey + self._num_results = max(1, min(50, num_results)) + self._use_autoprompt = use_autoprompt + self._search_type = search_type if search_type in VALID_SEARCH_TYPES else 'auto' + self._include_text = include_text + + def _bare_name(self, tool_name: str) -> str: + """Strip server prefix, accepting both bare and namespaced tool names.""" + prefix = f'{self._server_name}.' + return tool_name[len(prefix) :] if tool_name.startswith(prefix) else tool_name + + # ------------------------------------------------------------------ + # ToolsBase hooks + # ------------------------------------------------------------------ + + def _tool_query(self) -> List[ToolsBase.ToolDescriptor]: + return [ + { + 'name': f'{self._server_name}.exa_search', + 'description': ( + 'Search the web using Exa semantic search. ' + 'Provide a natural language "query" to find relevant web pages. ' + 'Returns structured results with title, URL, text content, relevance score, and published date. ' + 'Optional: "num_results", "type" (auto/neural/keyword), "use_autoprompt", ' + '"include_domains", "exclude_domains", "start_published_date", "end_published_date", "include_text".' + ), + 'inputSchema': INPUT_SCHEMA, + } + ] + + def _tool_validate(self, *, tool_name: str, input_obj: Any) -> None: # noqa: ANN401 + bare = self._bare_name(tool_name) + if bare != 'exa_search': + raise ValueError(f'Unknown tool {tool_name!r} (expected exa_search)') + + if not isinstance(input_obj, dict): + raise ValueError('Tool input must be a JSON object') + + query = input_obj.get('query') + if not query or not isinstance(query, str) or not query.strip(): + raise ValueError('query is required and must be a non-empty string') + + search_type = input_obj.get('type') + if search_type is not None and search_type not in VALID_SEARCH_TYPES: + raise ValueError(f'type must be one of {sorted(VALID_SEARCH_TYPES)}; got {search_type!r}') + + num_results = input_obj.get('num_results') + if num_results is not None: + if not isinstance(num_results, int) or num_results < 1 or num_results > 50: + raise ValueError('num_results must be an integer between 1 and 50') + + def _tool_invoke(self, *, tool_name: str, input_obj: Any) -> Any: # noqa: ANN401 + input_obj = _normalize_tool_input(input_obj) + self._tool_validate(tool_name=tool_name, input_obj=input_obj) + return self._invoke_search(input_obj) + + # ------------------------------------------------------------------ + # Search implementation + # ------------------------------------------------------------------ + + def _invoke_search(self, args: Dict[str, Any]) -> Dict[str, Any]: + query = args['query'].strip() + num_results = args.get('num_results', self._num_results) + search_type = args.get('type', self._search_type) + use_autoprompt = args.get('use_autoprompt', self._use_autoprompt) + include_text = args.get('include_text', self._include_text) + + # Build the search request payload + payload: Dict[str, Any] = { + 'query': query, + 'numResults': max(1, min(50, num_results)), + 'useAutoprompt': use_autoprompt, + 'type': search_type, + } + + # Optional domain filters + include_domains = args.get('include_domains') + if include_domains and isinstance(include_domains, list): + payload['includeDomains'] = include_domains + + exclude_domains = args.get('exclude_domains') + if exclude_domains and isinstance(exclude_domains, list): + payload['excludeDomains'] = exclude_domains + + # Optional date filters + start_date = args.get('start_published_date') + if start_date: + payload['startPublishedDate'] = str(start_date) + + end_date = args.get('end_published_date') + if end_date: + payload['endPublishedDate'] = str(end_date) + + # If we want text content, request it inline via the contents field + if include_text: + payload['contents'] = { + 'text': True, + } + + headers = { + 'accept': 'application/json', + 'content-type': 'application/json', + 'x-api-key': self._apikey, + } + + response = _request_with_retry( + url=EXA_SEARCH_URL, + headers=headers, + payload=payload, + ) + + # Parse and structure the results + results = [] + for item in response.get('results', []): + result_entry: Dict[str, Any] = { + 'title': item.get('title', ''), + 'url': item.get('url', ''), + 'score': item.get('score'), + 'published_date': item.get('publishedDate'), + 'author': item.get('author'), + } + # Text content is returned inline when contents.text is requested + text = item.get('text') + if text: + result_entry['text'] = text + results.append(result_entry) + + return { + 'success': True, + 'query': query, + 'num_results': len(results), + 'results': results, + } + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _request_with_retry( + *, + url: str, + headers: Dict[str, str], + payload: Dict[str, Any], + max_retries: int = 3, + base_delay: float = 2.0, +) -> Dict[str, Any]: + """Execute an HTTP POST to the Exa API with retry logic for transient errors.""" + for attempt in range(max_retries + 1): + try: + resp = requests.post(url, headers=headers, json=payload, timeout=30) + + if resp.status_code == 429: + if attempt < max_retries: + delay = base_delay * (2**attempt) + debug(f'Exa rate limit hit (429), retrying in {delay}s (attempt {attempt + 1}/{max_retries})') + time.sleep(delay) + continue + resp.raise_for_status() + + if 500 <= resp.status_code < 600: + if attempt < max_retries: + delay = base_delay * (2**attempt) + debug(f'Exa server error ({resp.status_code}), retrying in {delay}s (attempt {attempt + 1}/{max_retries})') + time.sleep(delay) + continue + resp.raise_for_status() + + resp.raise_for_status() + return resp.json() + + except requests.exceptions.Timeout: + if attempt < max_retries: + delay = base_delay * (2**attempt) + debug(f'Exa request timeout, retrying in {delay}s (attempt {attempt + 1}/{max_retries})') + time.sleep(delay) + continue + raise + + # Should not reach here, but just in case + raise RuntimeError('Exa search: max retries exceeded') + + +def _normalize_tool_input(input_obj: Any) -> Dict[str, Any]: + """Normalize whatever the engine/framework passes as tool input into a plain dict. + + Handles: None, dict, Pydantic model, JSON string, and nested ``input`` wrappers + that some framework paths produce. + """ + if input_obj is None: + return {} + + # Pydantic model -> dict + if hasattr(input_obj, 'model_dump') and callable(getattr(input_obj, 'model_dump')): + input_obj = input_obj.model_dump() + elif hasattr(input_obj, 'dict') and callable(getattr(input_obj, 'dict')): + input_obj = input_obj.dict() + + # JSON string -> dict + if isinstance(input_obj, str): + try: + parsed = json.loads(input_obj) + if isinstance(parsed, dict): + input_obj = parsed + except Exception: + pass + + if not isinstance(input_obj, dict): + warning(f'exa_search: unexpected input type {type(input_obj).__name__}: {input_obj!r}') + return {} + + # Unwrap ``{"input": {...}}`` wrappers that some framework paths leave behind + if 'input' in input_obj and isinstance(input_obj['input'], dict): + inner = input_obj['input'] + extras = {k: v for k, v in input_obj.items() if k != 'input'} + input_obj = {**inner, **extras} + + # Drop framework-injected keys that aren't tool args + input_obj.pop('security_context', None) + + return input_obj diff --git a/nodes/src/nodes/tool_exa_search/requirements.txt b/nodes/src/nodes/tool_exa_search/requirements.txt new file mode 100644 index 0000000000..f2293605cf --- /dev/null +++ b/nodes/src/nodes/tool_exa_search/requirements.txt @@ -0,0 +1 @@ +requests diff --git a/nodes/src/nodes/tool_exa_search/services.json b/nodes/src/nodes/tool_exa_search/services.json new file mode 100644 index 0000000000..6f6446afb7 --- /dev/null +++ b/nodes/src/nodes/tool_exa_search/services.json @@ -0,0 +1,93 @@ +{ + "title": "Exa Search", + "protocol": "tool_exa_search://", + "classType": ["tool"], + "capabilities": ["invoke"], + "register": "filter", + "node": "python", + "path": "nodes.tool_exa_search", + "prefix": "exa", + "icon": "exa.svg", + "description": [ + "Exposes Exa semantic web search as an agent tool.", + "Performs real-time web searches via the Exa API and returns structured results with titles, URLs, text content, relevance scores, and dates." + ], + "tile": [], + "lanes": {}, + "preconfig": { + "default": "default", + "profiles": { + "default": { + "title": "Exa Search", + "apikey": "", + "numResults": 10, + "useAutoprompt": true, + "searchType": "auto", + "includeText": true + } + } + }, + "fields": { + "tool_exa_search.apikey": { + "type": "string", + "title": "API Key", + "description": "Exa API key (from https://exa.ai)", + "default": "", + "secure": true, + "ui": { + "ui:widget": "ApiKeyWidget" + } + }, + "tool_exa_search.numResults": { + "type": "number", + "title": "Number of Results", + "description": "Maximum number of search results to return (1-50)", + "default": 10 + }, + "tool_exa_search.useAutoprompt": { + "type": "boolean", + "title": "Use Autoprompt", + "description": "Let Exa optimize the query for better results", + "default": true, + "enum": [ + [true, "Yes"], + [false, "No"] + ] + }, + "tool_exa_search.searchType": { + "type": "string", + "title": "Search Type", + "description": "Type of search to perform", + "default": "auto", + "enum": [ + ["auto", "Auto"], + ["neural", "Neural"], + ["keyword", "Keyword"] + ] + }, + "tool_exa_search.includeText": { + "type": "boolean", + "title": "Include Text Content", + "description": "Include full text content in results (uses get_contents)", + "default": true, + "enum": [ + [true, "Yes"], + [false, "No"] + ] + } + }, + "shape": [ + { + "section": "Pipe", + "title": "Exa Search", + "properties": [ + "type", + "tool_exa_search.apikey", + "tool_exa_search.numResults", + "tool_exa_search.useAutoprompt", + "tool_exa_search.searchType", + "tool_exa_search.includeText" + ] + } + ] +} From 5b46c32cf8dc0b354372dcf517de267aabe6dbda Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Mon, 30 Mar 2026 13:13:36 -0700 Subject: [PATCH 2/9] refactor(nodes): remove dead EXA_CONTENTS_URL constant The constant was defined but never referenced anywhere in the codebase. Co-Authored-By: Claude Opus 4.6 (1M context) --- nodes/src/nodes/tool_exa_search/exa_driver.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nodes/src/nodes/tool_exa_search/exa_driver.py b/nodes/src/nodes/tool_exa_search/exa_driver.py index 3f98bd0096..ad7857cb03 100644 --- a/nodes/src/nodes/tool_exa_search/exa_driver.py +++ b/nodes/src/nodes/tool_exa_search/exa_driver.py @@ -48,7 +48,6 @@ # --------------------------------------------------------------------------- EXA_SEARCH_URL = 'https://api.exa.ai/search' -EXA_CONTENTS_URL = 'https://api.exa.ai/contents' VALID_SEARCH_TYPES = {'auto', 'neural', 'keyword'} From 39bfaeed76987c51062e913b84acf8f04f0a883c Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Mon, 30 Mar 2026 13:13:45 -0700 Subject: [PATCH 3/9] fix(nodes): add min/max validation to numResults in Exa services.json Add "minimum": 1 and "maximum": 50 constraints to match the Python clamping logic in exa_driver.py. Co-Authored-By: Claude Opus 4.6 (1M context) --- nodes/src/nodes/tool_exa_search/services.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nodes/src/nodes/tool_exa_search/services.json b/nodes/src/nodes/tool_exa_search/services.json index 6f6446afb7..89494c9545 100644 --- a/nodes/src/nodes/tool_exa_search/services.json +++ b/nodes/src/nodes/tool_exa_search/services.json @@ -42,7 +42,9 @@ "type": "number", "title": "Number of Results", "description": "Maximum number of search results to return (1-50)", - "default": 10 + "default": 10, + "minimum": 1, + "maximum": 50 }, "tool_exa_search.useAutoprompt": { "type": "boolean", From 980990688b18aea976359b086b8c1cd08fa1371a Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Mon, 30 Mar 2026 13:13:49 -0700 Subject: [PATCH 4/9] fix(nodes): sanitize Exa retry exceptions to prevent API key leakage Catch requests.RequestException and re-raise as RuntimeError with a sanitized message that omits headers. Also wrap the Timeout re-raise to avoid exposing request details. Co-Authored-By: Claude Opus 4.6 (1M context) --- nodes/src/nodes/tool_exa_search/exa_driver.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/nodes/src/nodes/tool_exa_search/exa_driver.py b/nodes/src/nodes/tool_exa_search/exa_driver.py index ad7857cb03..946404fd17 100644 --- a/nodes/src/nodes/tool_exa_search/exa_driver.py +++ b/nodes/src/nodes/tool_exa_search/exa_driver.py @@ -291,7 +291,13 @@ def _request_with_retry( debug(f'Exa request timeout, retrying in {delay}s (attempt {attempt + 1}/{max_retries})') time.sleep(delay) continue - raise + raise RuntimeError('Exa search: request timed out after all retries') from None + + except requests.RequestException as exc: + # Re-raise with a sanitized message so the API key in headers is never leaked. + status = getattr(getattr(exc, 'response', None), 'status_code', None) + detail = f' (HTTP {status})' if status else '' + raise RuntimeError(f'Exa search request failed{detail}: {type(exc).__name__}') from None # Should not reach here, but just in case raise RuntimeError('Exa search: max retries exceeded') From 03603944d6b6ce07069d4c19c03bec8a71f4d9c1 Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Wed, 8 Apr 2026 00:10:20 -0700 Subject: [PATCH 5/9] fix(nodes): address review feedback on Exa search node - Normalize input in _tool_validate() for JSON strings, Pydantic models, and wrapped payloads (not just in invoke) - Remove raw input from warning log to prevent leaking sensitive data - Add EXA_API_KEY env var fallback in IGlobal beginGlobal/validateConfig - Validate all advertised schema fields (use_autoprompt, include_text, domain filters, date bounds) in _tool_validate - Change numResults type from "number" to "integer" in services.json - Fix includeText description (remove stale "uses get_contents" reference) Co-Authored-By: Claude Opus 4.6 (1M context) --- nodes/src/nodes/tool_exa_search/IGlobal.py | 6 ++-- nodes/src/nodes/tool_exa_search/exa_driver.py | 31 ++++++++++++++++++- nodes/src/nodes/tool_exa_search/services.json | 4 +-- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/nodes/src/nodes/tool_exa_search/IGlobal.py b/nodes/src/nodes/tool_exa_search/IGlobal.py index 104d0fc89c..5ae7d9ed3b 100644 --- a/nodes/src/nodes/tool_exa_search/IGlobal.py +++ b/nodes/src/nodes/tool_exa_search/IGlobal.py @@ -32,6 +32,8 @@ from __future__ import annotations +import os + from ai.common.config import Config from rocketlib import IGlobalBase, OPEN_MODE, warning @@ -49,7 +51,7 @@ def beginGlobal(self) -> None: cfg = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) - apikey = str((cfg.get('apikey') or '')).strip() + apikey = str(cfg.get('apikey') or os.environ.get('EXA_API_KEY', '')).strip() if not apikey: raise Exception('tool_exa_search: apikey is required') @@ -75,7 +77,7 @@ def beginGlobal(self) -> None: def validateConfig(self) -> None: try: cfg = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) - apikey = str((cfg.get('apikey') or '')).strip() + apikey = str(cfg.get('apikey') or os.environ.get('EXA_API_KEY', '')).strip() if not apikey: warning('apikey is required') except Exception as e: diff --git a/nodes/src/nodes/tool_exa_search/exa_driver.py b/nodes/src/nodes/tool_exa_search/exa_driver.py index 946404fd17..6f5b7ea1b5 100644 --- a/nodes/src/nodes/tool_exa_search/exa_driver.py +++ b/nodes/src/nodes/tool_exa_search/exa_driver.py @@ -148,6 +148,9 @@ def _tool_validate(self, *, tool_name: str, input_obj: Any) -> None: # noqa: AN if bare != 'exa_search': raise ValueError(f'Unknown tool {tool_name!r} (expected exa_search)') + # Normalize input so validation works for JSON strings, Pydantic models, etc. + input_obj = _normalize_tool_input(input_obj) + if not isinstance(input_obj, dict): raise ValueError('Tool input must be a JSON object') @@ -164,6 +167,32 @@ def _tool_validate(self, *, tool_name: str, input_obj: Any) -> None: # noqa: AN if not isinstance(num_results, int) or num_results < 1 or num_results > 50: raise ValueError('num_results must be an integer between 1 and 50') + use_autoprompt = input_obj.get('use_autoprompt') + if use_autoprompt is not None and not isinstance(use_autoprompt, bool): + raise ValueError('use_autoprompt must be a boolean') + + include_text = input_obj.get('include_text') + if include_text is not None and not isinstance(include_text, bool): + raise ValueError('include_text must be a boolean') + + include_domains = input_obj.get('include_domains') + if include_domains is not None: + if not isinstance(include_domains, list) or not all(isinstance(d, str) for d in include_domains): + raise ValueError('include_domains must be an array of strings') + + exclude_domains = input_obj.get('exclude_domains') + if exclude_domains is not None: + if not isinstance(exclude_domains, list) or not all(isinstance(d, str) for d in exclude_domains): + raise ValueError('exclude_domains must be an array of strings') + + start_published_date = input_obj.get('start_published_date') + if start_published_date is not None and not isinstance(start_published_date, str): + raise ValueError('start_published_date must be a string in ISO 8601 format') + + end_published_date = input_obj.get('end_published_date') + if end_published_date is not None and not isinstance(end_published_date, str): + raise ValueError('end_published_date must be a string in ISO 8601 format') + def _tool_invoke(self, *, tool_name: str, input_obj: Any) -> Any: # noqa: ANN401 input_obj = _normalize_tool_input(input_obj) self._tool_validate(tool_name=tool_name, input_obj=input_obj) @@ -328,7 +357,7 @@ def _normalize_tool_input(input_obj: Any) -> Dict[str, Any]: pass if not isinstance(input_obj, dict): - warning(f'exa_search: unexpected input type {type(input_obj).__name__}: {input_obj!r}') + warning(f'exa_search: unexpected input type {type(input_obj).__name__}') return {} # Unwrap ``{"input": {...}}`` wrappers that some framework paths leave behind diff --git a/nodes/src/nodes/tool_exa_search/services.json b/nodes/src/nodes/tool_exa_search/services.json index 89494c9545..7e1b66854e 100644 --- a/nodes/src/nodes/tool_exa_search/services.json +++ b/nodes/src/nodes/tool_exa_search/services.json @@ -39,7 +39,7 @@ } }, "tool_exa_search.numResults": { - "type": "number", + "type": "integer", "title": "Number of Results", "description": "Maximum number of search results to return (1-50)", "default": 10, @@ -70,7 +70,7 @@ "tool_exa_search.includeText": { "type": "boolean", "title": "Include Text Content", - "description": "Include full text content in results (uses get_contents)", + "description": "Include full text content in results", "default": true, "enum": [ [true, "Yes"], From 25a481c6994851e4c358721b6f0fbd59052688d2 Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Fri, 10 Apr 2026 16:18:29 -0700 Subject: [PATCH 6/9] fix(nodes): migrate exa search to @tool_function pattern and address review feedback - Delete exa_driver.py and move search logic into IInstance.py using @tool_function decorator, matching the tool_firecrawl pattern - Add output_schema and summary to the @tool_function decorator - Fix bare Exception in IGlobal.py: use rocketlib.error() + ValueError - Store config values directly on IGlobal instead of the driver object - Add test config with default profile to services.json --- nodes/src/nodes/tool_exa_search/IGlobal.py | 41 +- nodes/src/nodes/tool_exa_search/IInstance.py | 246 +++++++++++- nodes/src/nodes/tool_exa_search/exa_driver.py | 372 ------------------ nodes/src/nodes/tool_exa_search/services.json | 13 + 4 files changed, 267 insertions(+), 405 deletions(-) delete mode 100644 nodes/src/nodes/tool_exa_search/exa_driver.py diff --git a/nodes/src/nodes/tool_exa_search/IGlobal.py b/nodes/src/nodes/tool_exa_search/IGlobal.py index 5ae7d9ed3b..c92a8fbcad 100644 --- a/nodes/src/nodes/tool_exa_search/IGlobal.py +++ b/nodes/src/nodes/tool_exa_search/IGlobal.py @@ -26,8 +26,8 @@ """ Exa Search tool node - global (shared) state. -Reads the Exa API key and search configuration from the node config, -then creates an ExaSearchDriver that implements the ToolsBase interface. +Reads the Exa API key and search configuration from the node config. +Tool logic lives on IInstance via @tool_function. """ from __future__ import annotations @@ -35,15 +35,17 @@ import os from ai.common.config import Config -from rocketlib import IGlobalBase, OPEN_MODE, warning - -from .exa_driver import ExaSearchDriver +from rocketlib import IGlobalBase, OPEN_MODE, error, warning class IGlobal(IGlobalBase): """Global state for tool_exa_search.""" - driver: ExaSearchDriver | None = None + apikey: str = '' + num_results: int = 10 + use_autoprompt: bool = True + search_type: str = 'auto' + include_text: bool = True def beginGlobal(self) -> None: if self.IEndpoint.endpoint.openMode == OPEN_MODE.CONFIG: @@ -54,25 +56,14 @@ def beginGlobal(self) -> None: apikey = str(cfg.get('apikey') or os.environ.get('EXA_API_KEY', '')).strip() if not apikey: - raise Exception('tool_exa_search: apikey is required') - - num_results = int(cfg.get('numResults') or 10) - use_autoprompt = bool(cfg.get('useAutoprompt', True)) - search_type = str(cfg.get('searchType') or 'auto').strip() - include_text = bool(cfg.get('includeText', True)) + error('tool_exa_search: apikey is required — set it in node config or EXA_API_KEY env var') + raise ValueError('tool_exa_search: apikey is required') - try: - self.driver = ExaSearchDriver( - server_name='exa', - apikey=apikey, - num_results=num_results, - use_autoprompt=use_autoprompt, - search_type=search_type, - include_text=include_text, - ) - except Exception as e: - warning(str(e)) - raise + self.apikey = apikey + self.num_results = max(1, min(50, int(cfg.get('numResults') or 10))) + self.use_autoprompt = bool(cfg.get('useAutoprompt', True)) + self.search_type = str(cfg.get('searchType') or 'auto').strip() + self.include_text = bool(cfg.get('includeText', True)) def validateConfig(self) -> None: try: @@ -84,4 +75,4 @@ def validateConfig(self) -> None: warning(str(e)) def endGlobal(self) -> None: - self.driver = None + self.apikey = '' diff --git a/nodes/src/nodes/tool_exa_search/IInstance.py b/nodes/src/nodes/tool_exa_search/IInstance.py index 449f44c624..5c5c7de942 100644 --- a/nodes/src/nodes/tool_exa_search/IInstance.py +++ b/nodes/src/nodes/tool_exa_search/IInstance.py @@ -26,23 +26,253 @@ """ Exa Search tool node instance. -Delegates tool invoke operations to the ExaSearchDriver. +Exposes ``exa_search`` as a @tool_function for semantic web search via the Exa API. """ from __future__ import annotations -from typing import Any +import json +import time +from typing import Any, Dict -from rocketlib import IInstanceBase +import requests + +from rocketlib import IInstanceBase, tool_function, warning, debug from .IGlobal import IGlobal +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +EXA_SEARCH_URL = 'https://api.exa.ai/search' + +VALID_SEARCH_TYPES = {'auto', 'neural', 'keyword'} + class IInstance(IInstanceBase): IGlobal: IGlobal - def invoke(self, param: Any) -> Any: # noqa: ANN401 - driver = getattr(self.IGlobal, 'driver', None) - if driver is None: - raise RuntimeError('tool_exa_search: driver not initialized') - return driver.handle_invoke(param) + @tool_function( + input_schema={ + 'type': 'object', + 'required': ['query'], + 'properties': { + 'query': { + 'type': 'string', + 'description': 'The search query. Can be a natural language question or keyword phrase.', + }, + 'num_results': { + 'type': 'integer', + 'description': 'Number of results to return (1-50). Defaults to the node config value.', + }, + 'type': { + 'type': 'string', + 'enum': sorted(VALID_SEARCH_TYPES), + 'description': 'Search type: "auto" (default), "neural" (semantic), or "keyword" (traditional).', + }, + 'use_autoprompt': { + 'type': 'boolean', + 'description': 'Whether to let Exa optimize the query for better results.', + }, + 'include_domains': { + 'type': 'array', + 'items': {'type': 'string'}, + 'description': 'Only return results from these domains (e.g. ["arxiv.org", "github.com"]).', + }, + 'exclude_domains': { + 'type': 'array', + 'items': {'type': 'string'}, + 'description': 'Exclude results from these domains.', + }, + 'start_published_date': { + 'type': 'string', + 'description': 'Only return results published after this date (ISO 8601, e.g. "2024-01-01").', + }, + 'end_published_date': { + 'type': 'string', + 'description': 'Only return results published before this date (ISO 8601, e.g. "2025-12-31").', + }, + 'include_text': { + 'type': 'boolean', + 'description': 'Whether to include full text content in results. Defaults to node config value.', + }, + }, + }, + output_schema={ + 'type': 'object', + 'properties': { + 'success': {'type': 'boolean'}, + 'query': {'type': 'string'}, + 'num_results': {'type': 'integer'}, + 'results': {'type': 'array', 'items': {'type': 'object'}}, + 'error': {'type': 'string'}, + }, + }, + description='Search the web using Exa semantic search. Provide a natural language query to find relevant web pages. Returns structured results with title, URL, text content, relevance score, and published date.', + summary='Searches the web using Exa semantic search API', + ) + def exa_search(self, args): + """Search the web using Exa semantic search.""" + args = _normalize_tool_input(args) + + query = (args.get('query') or '').strip() + if not query: + return {'success': False, 'query': '', 'num_results': 0, 'results': [], 'error': 'query is required and must be a non-empty string'} + + cfg = self.IGlobal + num_results = args.get('num_results', cfg.num_results) + search_type = args.get('type', cfg.search_type) + use_autoprompt = args.get('use_autoprompt', cfg.use_autoprompt) + include_text = args.get('include_text', cfg.include_text) + + # Build the search request payload + payload: Dict[str, Any] = { + 'query': query, + 'numResults': max(1, min(50, num_results)), + 'useAutoprompt': use_autoprompt, + 'type': search_type if search_type in VALID_SEARCH_TYPES else 'auto', + } + + # Optional domain filters + include_domains = args.get('include_domains') + if include_domains and isinstance(include_domains, list): + payload['includeDomains'] = include_domains + + exclude_domains = args.get('exclude_domains') + if exclude_domains and isinstance(exclude_domains, list): + payload['excludeDomains'] = exclude_domains + + # Optional date filters + start_date = args.get('start_published_date') + if start_date: + payload['startPublishedDate'] = str(start_date) + + end_date = args.get('end_published_date') + if end_date: + payload['endPublishedDate'] = str(end_date) + + # If we want text content, request it inline via the contents field + if include_text: + payload['contents'] = {'text': True} + + headers = { + 'accept': 'application/json', + 'content-type': 'application/json', + 'x-api-key': cfg.apikey, + } + + try: + response = _request_with_retry(url=EXA_SEARCH_URL, headers=headers, payload=payload) + except RuntimeError as exc: + return {'success': False, 'query': query, 'num_results': 0, 'results': [], 'error': str(exc)} + + # Parse and structure the results + results = [] + for item in response.get('results', []): + result_entry: Dict[str, Any] = { + 'title': item.get('title', ''), + 'url': item.get('url', ''), + 'score': item.get('score'), + 'published_date': item.get('publishedDate'), + 'author': item.get('author'), + } + text = item.get('text') + if text: + result_entry['text'] = text + results.append(result_entry) + + return { + 'success': True, + 'query': query, + 'num_results': len(results), + 'results': results, + } + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _request_with_retry( + *, + url: str, + headers: Dict[str, str], + payload: Dict[str, Any], + max_retries: int = 3, + base_delay: float = 2.0, +) -> Dict[str, Any]: + """Execute an HTTP POST to the Exa API with retry logic for transient errors.""" + for attempt in range(max_retries + 1): + try: + resp = requests.post(url, headers=headers, json=payload, timeout=30) + + if resp.status_code == 429: + if attempt < max_retries: + delay = base_delay * (2**attempt) + debug(f'Exa rate limit hit (429), retrying in {delay}s (attempt {attempt + 1}/{max_retries})') + time.sleep(delay) + continue + resp.raise_for_status() + + if 500 <= resp.status_code < 600: + if attempt < max_retries: + delay = base_delay * (2**attempt) + debug(f'Exa server error ({resp.status_code}), retrying in {delay}s (attempt {attempt + 1}/{max_retries})') + time.sleep(delay) + continue + resp.raise_for_status() + + resp.raise_for_status() + return resp.json() + + except requests.exceptions.Timeout: + if attempt < max_retries: + delay = base_delay * (2**attempt) + debug(f'Exa request timeout, retrying in {delay}s (attempt {attempt + 1}/{max_retries})') + time.sleep(delay) + continue + raise RuntimeError('Exa search: request timed out after all retries') from None + + except requests.RequestException as exc: + status = getattr(getattr(exc, 'response', None), 'status_code', None) + detail = f' (HTTP {status})' if status else '' + raise RuntimeError(f'Exa search request failed{detail}: {type(exc).__name__}') from None + + raise RuntimeError('Exa search: max retries exceeded') + + +def _normalize_tool_input(input_obj: Any) -> Dict[str, Any]: + """Normalize tool input into a plain dict. + + Handles: None, dict, Pydantic model, JSON string, and nested ``input`` wrappers + that some framework paths produce. + """ + if input_obj is None: + return {} + + if hasattr(input_obj, 'model_dump') and callable(getattr(input_obj, 'model_dump')): + input_obj = input_obj.model_dump() + elif hasattr(input_obj, 'dict') and callable(getattr(input_obj, 'dict')): + input_obj = input_obj.dict() + + if isinstance(input_obj, str): + try: + parsed = json.loads(input_obj) + if isinstance(parsed, dict): + input_obj = parsed + except (json.JSONDecodeError, TypeError): + warning('exa_search: failed to parse input as JSON') + + if not isinstance(input_obj, dict): + warning(f'exa_search: unexpected input type {type(input_obj).__name__}') + return {} + + if 'input' in input_obj and isinstance(input_obj['input'], dict): + inner = input_obj['input'] + extras = {k: v for k, v in input_obj.items() if k != 'input'} + input_obj = {**inner, **extras} + + input_obj.pop('security_context', None) + return input_obj diff --git a/nodes/src/nodes/tool_exa_search/exa_driver.py b/nodes/src/nodes/tool_exa_search/exa_driver.py deleted file mode 100644 index 6f5b7ea1b5..0000000000 --- a/nodes/src/nodes/tool_exa_search/exa_driver.py +++ /dev/null @@ -1,372 +0,0 @@ -# ============================================================================= -# RocketRide Engine -# ============================================================================= -# MIT License -# Copyright (c) 2026 Aparavi Software AG -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# ============================================================================= - -""" -Exa Search tool-provider driver. - -Implements ``tool.query``, ``tool.validate``, and ``tool.invoke`` for the Exa -semantic web search API. Exposes a single ``exa_search`` tool that agents can -invoke with a natural-language query to retrieve real-time web results. -""" - -from __future__ import annotations - -import json -import time -from typing import Any, Dict, List - -import requests - -from rocketlib import debug, warning - -from ai.common.tools import ToolsBase - -# --------------------------------------------------------------------------- -# Constants -# --------------------------------------------------------------------------- - -EXA_SEARCH_URL = 'https://api.exa.ai/search' - -VALID_SEARCH_TYPES = {'auto', 'neural', 'keyword'} - -INPUT_SCHEMA: Dict[str, Any] = { - 'type': 'object', - 'required': ['query'], - 'properties': { - 'query': { - 'type': 'string', - 'description': 'The search query. Can be a natural language question or keyword phrase.', - }, - 'num_results': { - 'type': 'integer', - 'description': 'Number of results to return (1-50). Defaults to the node config value.', - }, - 'type': { - 'type': 'string', - 'enum': sorted(VALID_SEARCH_TYPES), - 'description': 'Search type: "auto" (default), "neural" (semantic), or "keyword" (traditional).', - }, - 'use_autoprompt': { - 'type': 'boolean', - 'description': 'Whether to let Exa optimize the query for better results.', - }, - 'include_domains': { - 'type': 'array', - 'items': {'type': 'string'}, - 'description': 'Only return results from these domains (e.g. ["arxiv.org", "github.com"]).', - }, - 'exclude_domains': { - 'type': 'array', - 'items': {'type': 'string'}, - 'description': 'Exclude results from these domains.', - }, - 'start_published_date': { - 'type': 'string', - 'description': 'Only return results published after this date (ISO 8601, e.g. "2024-01-01").', - }, - 'end_published_date': { - 'type': 'string', - 'description': 'Only return results published before this date (ISO 8601, e.g. "2025-12-31").', - }, - 'include_text': { - 'type': 'boolean', - 'description': 'Whether to include full text content in results. Defaults to node config value.', - }, - }, -} - - -class ExaSearchDriver(ToolsBase): - """Tool provider for Exa semantic web search.""" - - def __init__( - self, - *, - server_name: str, - apikey: str, - num_results: int = 10, - use_autoprompt: bool = True, - search_type: str = 'auto', - include_text: bool = True, - ) -> None: - """Initialize the Exa search driver with API key and default search parameters.""" - self._server_name = (server_name or '').strip() or 'exa' - self._apikey = apikey - self._num_results = max(1, min(50, num_results)) - self._use_autoprompt = use_autoprompt - self._search_type = search_type if search_type in VALID_SEARCH_TYPES else 'auto' - self._include_text = include_text - - def _bare_name(self, tool_name: str) -> str: - """Strip server prefix, accepting both bare and namespaced tool names.""" - prefix = f'{self._server_name}.' - return tool_name[len(prefix) :] if tool_name.startswith(prefix) else tool_name - - # ------------------------------------------------------------------ - # ToolsBase hooks - # ------------------------------------------------------------------ - - def _tool_query(self) -> List[ToolsBase.ToolDescriptor]: - return [ - { - 'name': f'{self._server_name}.exa_search', - 'description': ( - 'Search the web using Exa semantic search. ' - 'Provide a natural language "query" to find relevant web pages. ' - 'Returns structured results with title, URL, text content, relevance score, and published date. ' - 'Optional: "num_results", "type" (auto/neural/keyword), "use_autoprompt", ' - '"include_domains", "exclude_domains", "start_published_date", "end_published_date", "include_text".' - ), - 'inputSchema': INPUT_SCHEMA, - } - ] - - def _tool_validate(self, *, tool_name: str, input_obj: Any) -> None: # noqa: ANN401 - bare = self._bare_name(tool_name) - if bare != 'exa_search': - raise ValueError(f'Unknown tool {tool_name!r} (expected exa_search)') - - # Normalize input so validation works for JSON strings, Pydantic models, etc. - input_obj = _normalize_tool_input(input_obj) - - if not isinstance(input_obj, dict): - raise ValueError('Tool input must be a JSON object') - - query = input_obj.get('query') - if not query or not isinstance(query, str) or not query.strip(): - raise ValueError('query is required and must be a non-empty string') - - search_type = input_obj.get('type') - if search_type is not None and search_type not in VALID_SEARCH_TYPES: - raise ValueError(f'type must be one of {sorted(VALID_SEARCH_TYPES)}; got {search_type!r}') - - num_results = input_obj.get('num_results') - if num_results is not None: - if not isinstance(num_results, int) or num_results < 1 or num_results > 50: - raise ValueError('num_results must be an integer between 1 and 50') - - use_autoprompt = input_obj.get('use_autoprompt') - if use_autoprompt is not None and not isinstance(use_autoprompt, bool): - raise ValueError('use_autoprompt must be a boolean') - - include_text = input_obj.get('include_text') - if include_text is not None and not isinstance(include_text, bool): - raise ValueError('include_text must be a boolean') - - include_domains = input_obj.get('include_domains') - if include_domains is not None: - if not isinstance(include_domains, list) or not all(isinstance(d, str) for d in include_domains): - raise ValueError('include_domains must be an array of strings') - - exclude_domains = input_obj.get('exclude_domains') - if exclude_domains is not None: - if not isinstance(exclude_domains, list) or not all(isinstance(d, str) for d in exclude_domains): - raise ValueError('exclude_domains must be an array of strings') - - start_published_date = input_obj.get('start_published_date') - if start_published_date is not None and not isinstance(start_published_date, str): - raise ValueError('start_published_date must be a string in ISO 8601 format') - - end_published_date = input_obj.get('end_published_date') - if end_published_date is not None and not isinstance(end_published_date, str): - raise ValueError('end_published_date must be a string in ISO 8601 format') - - def _tool_invoke(self, *, tool_name: str, input_obj: Any) -> Any: # noqa: ANN401 - input_obj = _normalize_tool_input(input_obj) - self._tool_validate(tool_name=tool_name, input_obj=input_obj) - return self._invoke_search(input_obj) - - # ------------------------------------------------------------------ - # Search implementation - # ------------------------------------------------------------------ - - def _invoke_search(self, args: Dict[str, Any]) -> Dict[str, Any]: - query = args['query'].strip() - num_results = args.get('num_results', self._num_results) - search_type = args.get('type', self._search_type) - use_autoprompt = args.get('use_autoprompt', self._use_autoprompt) - include_text = args.get('include_text', self._include_text) - - # Build the search request payload - payload: Dict[str, Any] = { - 'query': query, - 'numResults': max(1, min(50, num_results)), - 'useAutoprompt': use_autoprompt, - 'type': search_type, - } - - # Optional domain filters - include_domains = args.get('include_domains') - if include_domains and isinstance(include_domains, list): - payload['includeDomains'] = include_domains - - exclude_domains = args.get('exclude_domains') - if exclude_domains and isinstance(exclude_domains, list): - payload['excludeDomains'] = exclude_domains - - # Optional date filters - start_date = args.get('start_published_date') - if start_date: - payload['startPublishedDate'] = str(start_date) - - end_date = args.get('end_published_date') - if end_date: - payload['endPublishedDate'] = str(end_date) - - # If we want text content, request it inline via the contents field - if include_text: - payload['contents'] = { - 'text': True, - } - - headers = { - 'accept': 'application/json', - 'content-type': 'application/json', - 'x-api-key': self._apikey, - } - - response = _request_with_retry( - url=EXA_SEARCH_URL, - headers=headers, - payload=payload, - ) - - # Parse and structure the results - results = [] - for item in response.get('results', []): - result_entry: Dict[str, Any] = { - 'title': item.get('title', ''), - 'url': item.get('url', ''), - 'score': item.get('score'), - 'published_date': item.get('publishedDate'), - 'author': item.get('author'), - } - # Text content is returned inline when contents.text is requested - text = item.get('text') - if text: - result_entry['text'] = text - results.append(result_entry) - - return { - 'success': True, - 'query': query, - 'num_results': len(results), - 'results': results, - } - - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - - -def _request_with_retry( - *, - url: str, - headers: Dict[str, str], - payload: Dict[str, Any], - max_retries: int = 3, - base_delay: float = 2.0, -) -> Dict[str, Any]: - """Execute an HTTP POST to the Exa API with retry logic for transient errors.""" - for attempt in range(max_retries + 1): - try: - resp = requests.post(url, headers=headers, json=payload, timeout=30) - - if resp.status_code == 429: - if attempt < max_retries: - delay = base_delay * (2**attempt) - debug(f'Exa rate limit hit (429), retrying in {delay}s (attempt {attempt + 1}/{max_retries})') - time.sleep(delay) - continue - resp.raise_for_status() - - if 500 <= resp.status_code < 600: - if attempt < max_retries: - delay = base_delay * (2**attempt) - debug(f'Exa server error ({resp.status_code}), retrying in {delay}s (attempt {attempt + 1}/{max_retries})') - time.sleep(delay) - continue - resp.raise_for_status() - - resp.raise_for_status() - return resp.json() - - except requests.exceptions.Timeout: - if attempt < max_retries: - delay = base_delay * (2**attempt) - debug(f'Exa request timeout, retrying in {delay}s (attempt {attempt + 1}/{max_retries})') - time.sleep(delay) - continue - raise RuntimeError('Exa search: request timed out after all retries') from None - - except requests.RequestException as exc: - # Re-raise with a sanitized message so the API key in headers is never leaked. - status = getattr(getattr(exc, 'response', None), 'status_code', None) - detail = f' (HTTP {status})' if status else '' - raise RuntimeError(f'Exa search request failed{detail}: {type(exc).__name__}') from None - - # Should not reach here, but just in case - raise RuntimeError('Exa search: max retries exceeded') - - -def _normalize_tool_input(input_obj: Any) -> Dict[str, Any]: - """Normalize whatever the engine/framework passes as tool input into a plain dict. - - Handles: None, dict, Pydantic model, JSON string, and nested ``input`` wrappers - that some framework paths produce. - """ - if input_obj is None: - return {} - - # Pydantic model -> dict - if hasattr(input_obj, 'model_dump') and callable(getattr(input_obj, 'model_dump')): - input_obj = input_obj.model_dump() - elif hasattr(input_obj, 'dict') and callable(getattr(input_obj, 'dict')): - input_obj = input_obj.dict() - - # JSON string -> dict - if isinstance(input_obj, str): - try: - parsed = json.loads(input_obj) - if isinstance(parsed, dict): - input_obj = parsed - except Exception: - pass - - if not isinstance(input_obj, dict): - warning(f'exa_search: unexpected input type {type(input_obj).__name__}') - return {} - - # Unwrap ``{"input": {...}}`` wrappers that some framework paths leave behind - if 'input' in input_obj and isinstance(input_obj['input'], dict): - inner = input_obj['input'] - extras = {k: v for k, v in input_obj.items() if k != 'input'} - input_obj = {**inner, **extras} - - # Drop framework-injected keys that aren't tool args - input_obj.pop('security_context', None) - - return input_obj diff --git a/nodes/src/nodes/tool_exa_search/services.json b/nodes/src/nodes/tool_exa_search/services.json index 7e1b66854e..3e27154c32 100644 --- a/nodes/src/nodes/tool_exa_search/services.json +++ b/nodes/src/nodes/tool_exa_search/services.json @@ -78,6 +78,19 @@ ] } }, + "test": { + "profiles": { + "default": { + "title": "Exa Search Test", + "apikey": "test-key", + "numResults": 5, + "useAutoprompt": false, + "searchType": "auto", + "includeText": true + } + }, + "outputs": ["results"] + }, "shape": [ { "section": "Pipe", From 392b3ad4db265aeee3c2756a227881479b88e0e2 Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Mon, 13 Apr 2026 21:11:01 -0700 Subject: [PATCH 7/9] fix(nodes): clamp Exa numResults=0 instead of widening to default `cfg.get('numResults') or 10` silently turned an explicit `0` into the default of 10 before clamping. A direct config bypassing the UI schema could therefore widen an out-of-range low value instead of clamping it to 1. Distinguish "not set" from "set to 0" so the clamp takes effect. --- nodes/src/nodes/tool_exa_search/IGlobal.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/nodes/src/nodes/tool_exa_search/IGlobal.py b/nodes/src/nodes/tool_exa_search/IGlobal.py index c92a8fbcad..f03a8f4e6b 100644 --- a/nodes/src/nodes/tool_exa_search/IGlobal.py +++ b/nodes/src/nodes/tool_exa_search/IGlobal.py @@ -60,7 +60,10 @@ def beginGlobal(self) -> None: raise ValueError('tool_exa_search: apikey is required') self.apikey = apikey - self.num_results = max(1, min(50, int(cfg.get('numResults') or 10))) + raw_num_results = cfg.get('numResults', 10) + if raw_num_results is None: + raw_num_results = 10 + self.num_results = max(1, min(50, int(raw_num_results))) self.use_autoprompt = bool(cfg.get('useAutoprompt', True)) self.search_type = str(cfg.get('searchType') or 'auto').strip() self.include_text = bool(cfg.get('includeText', True)) From 9ead2ecdbab3b7bee51c932988789f0431c25c43 Mon Sep 17 00:00:00 2001 From: Charlie Gillet Date: Mon, 13 Apr 2026 21:11:08 -0700 Subject: [PATCH 8/9] fix(nodes): reject boolean num_results and add IInstance docstring `bool` is a subclass of `int` in Python, so `{'num_results': true}` was silently accepted and clamped to 1 instead of being treated as malformed. Explicitly reject non-int (including bool) and fall back to the configured default. Also adds a PEP 257 class docstring to match sibling tool nodes. --- nodes/src/nodes/tool_exa_search/IInstance.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/nodes/src/nodes/tool_exa_search/IInstance.py b/nodes/src/nodes/tool_exa_search/IInstance.py index 5c5c7de942..71f990838f 100644 --- a/nodes/src/nodes/tool_exa_search/IInstance.py +++ b/nodes/src/nodes/tool_exa_search/IInstance.py @@ -51,6 +51,8 @@ class IInstance(IInstanceBase): + """Node instance exposing Exa semantic web search as an agent tool.""" + IGlobal: IGlobal @tool_function( @@ -122,6 +124,10 @@ def exa_search(self, args): cfg = self.IGlobal num_results = args.get('num_results', cfg.num_results) + # bool is a subclass of int in Python — reject it explicitly so that + # {'num_results': true} doesn't silently become 1. + if isinstance(num_results, bool) or not isinstance(num_results, int): + num_results = cfg.num_results search_type = args.get('type', cfg.search_type) use_autoprompt = args.get('use_autoprompt', cfg.use_autoprompt) include_text = args.get('include_text', cfg.include_text) From fa79160005acd8db00130c70e888eecd4a081aae Mon Sep 17 00:00:00 2001 From: Alexandru Sclearuc Date: Wed, 15 Apr 2026 19:24:58 +0300 Subject: [PATCH 9/9] fix: documentation, marking node as experimental --- nodes/src/nodes/tool_exa_search/services.json | 76 +++++++++++++++---- 1 file changed, 63 insertions(+), 13 deletions(-) diff --git a/nodes/src/nodes/tool_exa_search/services.json b/nodes/src/nodes/tool_exa_search/services.json index 3e27154c32..0fde515409 100644 --- a/nodes/src/nodes/tool_exa_search/services.json +++ b/nodes/src/nodes/tool_exa_search/services.json @@ -1,19 +1,62 @@ { + // + // Required: + // The displayable name of this node + // "title": "Exa Search", + // + // Required: + // The protocol is the endpoint protocol + // "protocol": "tool_exa_search://", + // + // Required: + // Class type of the node - what it does + // "classType": ["tool"], - "capabilities": ["invoke"], + // + // Required: + // Capabilities are flags that change the behavior of the underlying engine. + // "experimental" marks this node as not yet production-ready. + // + "capabilities": ["invoke", "experimental"], + // + // Optional: + // Register is either filter, endpoint or ignored if not specified. + // "register": "filter", + // + // Optional: + // The node is the actual physical node to instantiate. + // "node": "python", + // + // Optional: + // The path is the executable/script code. + // "path": "nodes.tool_exa_search", + // + // Required: + // The prefix map when converting URLs <=> paths. + // "prefix": "exa", + // + // Optional: + // The icon to display in the UI for this node. + // "icon": "exa.svg", - "description": [ - "Exposes Exa semantic web search as an agent tool.", - "Performs real-time web searches via the Exa API and returns structured results with titles, URLs, text content, relevance scores, and dates." - ], + // + // Optional: + // Description of this node shown in the pipeline builder. + // + "description": ["Exposes Exa semantic web search as an agent tool.", "Performs real-time web searches via the Exa API and returns structured results with titles, URLs, text content, relevance scores, and dates."], "tile": [], "lanes": {}, + // + // Optional: + // Profile section - configuration options used by the driver itself. + // The default profile is applied when the node is first added to a pipeline. + // "preconfig": { "default": "default", "profiles": { @@ -27,6 +70,11 @@ } } }, + // + // Optional: + // Local field definitions. These define the config fields exposed in the UI. + // "secure: true" fields are encrypted at rest and masked in the UI. + // "fields": { "tool_exa_search.apikey": { "type": "string", @@ -78,6 +126,11 @@ ] } }, + // + // Test configuration for automated node testing. + // "apikey" is intentionally set to a placeholder — config validation is + // tested here, not live API calls. + // "test": { "profiles": { "default": { @@ -91,18 +144,15 @@ }, "outputs": ["results"] }, + // + // Required: + // Defines the fields (shape) shown in the pipeline builder side panel. + // "shape": [ { "section": "Pipe", "title": "Exa Search", - "properties": [ - "type", - "tool_exa_search.apikey", - "tool_exa_search.numResults", - "tool_exa_search.useAutoprompt", - "tool_exa_search.searchType", - "tool_exa_search.includeText" - ] + "properties": ["type", "tool_exa_search.apikey", "tool_exa_search.numResults", "tool_exa_search.useAutoprompt", "tool_exa_search.searchType", "tool_exa_search.includeText"] } ] }