RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent/tools): port DeepL to ToolBase so it works as an Agent tool (#18395)
Muhammad Furqanc3153ba29471
diff --git a/agent/tools/deepl.py b/agent/tools/deepl.pyindex 037648a5ff..3ec774b9df 100644--- a/agent/tools/deepl.py+++ b/agent/tools/deepl.py@@ -13,20 +13,34 @@# See the License for the specific language governing permissions and# limitations under the License.#+import logging+import osfrom abc import ABC-from agent.component.base import ComponentBase, ComponentParamBase+from agent.tools.base import ToolMeta, ToolParamBase, ToolBase+from common.connection_utils import timeoutimport deepl-class DeepLParam(ComponentParamBase):+class DeepLParam(ToolParamBase):"""Define the DeepL component parameters."""def __init__(self):+ self.meta: ToolMeta = {+ "name": "deepl_translate",+ "description": "DeepL translates text into a target language using the DeepL translation service.",+ "parameters": {+ "query": {+ "type": "string",+ "description": "The text to translate.",+ "default": "{sys.query}",+ "required": True,+ }+ },+ }super().__init__()self.auth_key = "xxx"- self.parameters = []self.source_lang = "ZH"self.target_lang = "EN-GB"@@ -75,27 +89,41 @@ class DeepLParam(ComponentParamBase):],)+ def get_input_form(self) -> dict[str, dict]:+ return {"query": {"name": "Text", "type": "line"}}-class DeepL(ComponentBase, ABC):++class DeepL(ToolBase, ABC):component_name = "DeepL"- def _run(self, history, **kwargs):+ @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12)))+ def _invoke(self, **kwargs):if self.check_if_canceled("DeepL processing"):return- ans = self.get_input()- ans = " - ".join(ans["content"]) if "content" in ans else ""- if not ans:- return DeepL.be_output("")- if self.check_if_canceled("DeepL processing"):- return+ text = kwargs.get("query")+ if not text:+ self.set_output("formalized_content", "")+ return ""try:translator = deepl.Translator(self._param.auth_key)- result = translator.translate_text(ans, source_lang=self._param.source_lang, target_lang=self._param.target_lang)+ result = translator.translate_text(text, source_lang=self._param.source_lang, target_lang=self._param.target_lang)++ if self.check_if_canceled("DeepL processing"):+ return- return DeepL.be_output(result.text)+ res = result.text+ self.set_output("formalized_content", res)+ return resexcept Exception as e:if self.check_if_canceled("DeepL processing"):return- return DeepL.be_output("**Error**:" + str(e))++ logging.exception(f"DeepL error: {e}")+ msg = f"DeepL error: {e}"+ self.set_output("_ERROR", msg)+ return msg++ def thoughts(self) -> str:+ return "Translating into {}: {}".format(self._param.target_lang, self.get_input().get("query", "-_-!"))diff --git a/test/unit_test/agent/component/test_deepl.py b/test/unit_test/agent/component/test_deepl.pyindex 0ec8c24914..a2df26b6ae 100644--- a/test/unit_test/agent/component/test_deepl.py+++ b/test/unit_test/agent/component/test_deepl.py@@ -24,16 +24,20 @@ pytest.importorskip("deepl")from agent.tools.deepl import DeepL, DeepLParam # noqa: E402-class _Canvas:- def is_canceled(self):- return False+def _make_tool(param=None):+ # Bypass the canvas-bound __init__ (mirrors test_akshare.py) and stub the+ # canvas-touching helpers so we can exercise _invoke's execution path.+ tool = DeepL.__new__(DeepL)+ tool._param = param or DeepLParam()+ tool.check_if_canceled = lambda *a, **k: False+ out = {}+ tool.set_output = lambda k, v: out.__setitem__(k, v)+ tool.output = lambda k=None: out.get(k) if k else out+ return tool, out-def _deepl(param=None):- cpn = DeepL.__new__(DeepL)- cpn._canvas = _Canvas()- cpn._param = param or DeepLParam()- return cpn+def test_param_instantiates():+ DeepLParam()def test_check_passes_with_defaults():@@ -56,14 +60,58 @@ def test_check_rejects_invalid_target_lang():param.check()+def test_meta_exposes_query_parameter():+ # Regression: DeepL extended ComponentBase and defined no `meta`, so it had+ # no get_meta() and crashed agent_with_tools when added to an Agent.+ meta = DeepLParam().get_meta()+ params = meta["function"]["parameters"]+ assert "query" in params["properties"]+ assert "query" in params["required"]+++def test_invoke_returns_translation_and_sets_formalized_content():+ # Regression for the restored runtime path: DeepL only implemented the+ # legacy _run, so _invoke fell through to ComponentBase._invoke and raised+ # NotImplementedError.+ tool, out = _make_tool()++ with patch("agent.tools.deepl.deepl.Translator") as translator_cls:+ translator_cls.return_value.translate_text.return_value.text = "hello"+ res = tool._invoke(query="你好")++ assert res == "hello"+ assert out["formalized_content"] == "hello"+++def test_invoke_passes_configured_languages():+ param = DeepLParam()+ param.source_lang = "ZH"+ param.target_lang = "EN-US"+ tool, _ = _make_tool(param)++ with patch("agent.tools.deepl.deepl.Translator") as translator_cls:+ translate_text = translator_cls.return_value.translate_text+ translate_text.return_value.text = "hello"+ tool._invoke(query="你好")++ translate_text.assert_called_once_with("你好", source_lang="ZH", target_lang="EN-US")+++def test_invoke_empty_query_returns_empty():+ # Empty query short-circuits without calling the DeepL SDK.+ tool, out = _make_tool()+ assert tool._invoke(query="") == ""+ assert out.get("formalized_content") == ""++@pytest.mark.p1-def test_run_returns_error_on_translation_failure():- cpn = _deepl()- cpn._param.inputs = {"content": {"value": ["hello"]}}+def test_invoke_surfaces_error_on_translation_failure():+ tool, out = _make_tool()- with patch.object(DeepL, "get_input", return_value={"content": ["hello"]}):- with patch("agent.tools.deepl.deepl.Translator") as translator_cls:- translator_cls.return_value.translate_text.side_effect = RuntimeError("boom")- result = cpn._run([])+ with patch("agent.tools.deepl.deepl.Translator") as translator_cls:+ translator_cls.return_value.translate_text.side_effect = RuntimeError("boom")+ res = tool._invoke(query="你好")- assert "**Error**:boom" in result.iloc[0]["content"]+ assert "boom" in res+ assert "boom" in out["_ERROR"]