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): port QWeather to ToolBase so it works as an Agent tool (#16692)
boskodev79080a7a874271a
diff --git a/agent/tools/qweather.py b/agent/tools/qweather.pyindex 49f97f9d6a..fe7d2a7dde 100644--- a/agent/tools/qweather.py+++ b/agent/tools/qweather.py@@ -13,19 +13,36 @@# See the License for the specific language governing permissions and# limitations under the License.#+import logging+import os+import timefrom abc import ABC-import pandas as pd+import requests-from agent.component.base import ComponentBase, ComponentParamBase++from agent.tools.base import ToolMeta, ToolParamBase, ToolBase+from common.connection_utils import timeoutfrom common.http_client import DEFAULT_TIMEOUT-class QWeatherParam(ComponentParamBase):+class QWeatherParam(ToolParamBase):"""Define the QWeather component parameters."""def __init__(self):+ self.meta: ToolMeta = {+ "name": "qweather",+ "description": "QWeather (和风天气) looks up the current weather, a multi-day forecast, life indices, or air quality for a location using the QWeather API.",+ "parameters": {+ "query": {+ "type": "string",+ "description": "The location to look up weather for, e.g. a city name like 'Beijing' or '北京'.",+ "default": "{sys.query}",+ "required": True,+ }+ },+ }super().__init__()self.web_apikey = "xxx"self.lang = "zh"@@ -45,7 +62,7 @@ class QWeatherParam(ComponentParamBase):self.time_period = "now"def check(self):- self.check_empty(self.web_apikey, "BaiduFanyi APPID")+ self.check_empty(self.web_apikey, "QWeather API key")self.check_valid_value(self.type, "Type", ["weather", "indices", "airquality"])self.check_valid_value(self.user_type, "Free subscription or paid subscription", ["free", "paid"])self.check_valid_value(@@ -87,76 +104,91 @@ class QWeatherParam(ComponentParamBase):)self.check_valid_value(self.time_period, "Time period", ["now", "3d", "7d", "10d", "15d", "30d"])+ def get_input_form(self) -> dict[str, dict]:+ return {"query": {"name": "Location", "type": "line"}}-class QWeather(ComponentBase, ABC):++class QWeather(ToolBase, ABC):component_name = "QWeather"- def _run(self, history, **kwargs):- if self.check_if_canceled("Qweather processing"):+ @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12)))+ def _invoke(self, **kwargs):+ if self.check_if_canceled("QWeather processing"):return- ans = self.get_input()- ans = "".join(ans["content"]) if "content" in ans else ""- if not ans:- return QWeather.be_output("")+ location = kwargs.get("query")+ if not location:+ self.set_output("formalized_content", "")+ return ""- try:- if self.check_if_canceled("Qweather processing"):+ last_e = None+ for _ in range(self._param.max_retries + 1):+ if self.check_if_canceled("QWeather processing"):return- response = requests.get(url="https://geoapi.qweather.com/v2/city/lookup?location=" + ans + "&key=" + self._param.web_apikey, timeout=DEFAULT_TIMEOUT).json()- if response["code"] == "200":- location_id = response["location"][0]["id"]- else:- return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])+ try:+ lookup = requests.get(+ url="https://geoapi.qweather.com/v2/city/lookup?location=" + location + "&key=" + self._param.web_apikey,+ timeout=DEFAULT_TIMEOUT,+ ).json()- if self.check_if_canceled("Qweather processing"):- return+ if self.check_if_canceled("QWeather processing"):+ return- base_url = "https://api.qweather.com/v7/" if self._param.user_type == "paid" else "https://devapi.qweather.com/v7/"+ if lookup["code"] != "200":+ return self._finish(self._error_message(lookup["code"]))- if self._param.type == "weather":- url = base_url + "weather/" + self._param.time_period + "?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang- response = requests.get(url=url, timeout=DEFAULT_TIMEOUT).json()- if self.check_if_canceled("Qweather processing"):- return- if response["code"] == "200":+ location_id = lookup["location"][0]["id"]+ base_url = "https://api.qweather.com/v7/" if self._param.user_type == "paid" else "https://devapi.qweather.com/v7/"++ if self._param.type == "weather":+ url = base_url + "weather/" + self._param.time_period + "?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang+ response = requests.get(url=url, timeout=DEFAULT_TIMEOUT).json()+ if self.check_if_canceled("QWeather processing"):+ return+ if response["code"] != "200":+ return self._finish(self._error_message(response["code"]))if self._param.time_period == "now":- return QWeather.be_output(str(response["now"]))- else:- qweather_res = [{"content": str(i) + "\n"} for i in response["daily"]]- if self.check_if_canceled("Qweather processing"):- return- if not qweather_res:- return QWeather.be_output("")-- df = pd.DataFrame(qweather_res)- return df- else:- return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])-- elif self._param.type == "indices":- url = base_url + "indices/1d?type=0&location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang+ return self._finish(str(response["now"]))+ return self._finish("\n".join(str(i) for i in response["daily"]))++ if self._param.type == "indices":+ url = base_url + "indices/1d?type=0&location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang+ response = requests.get(url=url, timeout=DEFAULT_TIMEOUT).json()+ if self.check_if_canceled("QWeather processing"):+ return+ if response["code"] != "200":+ return self._finish(self._error_message(response["code"]))+ indices_res = response["daily"][0]["date"] + "\n" + "\n".join(i["name"] + ": " + i["category"] + ", " + i["text"] for i in response["daily"])+ return self._finish(indices_res)++ # airquality+ url = base_url + "air/now?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.langresponse = requests.get(url=url, timeout=DEFAULT_TIMEOUT).json()- if self.check_if_canceled("Qweather processing"):+ if self.check_if_canceled("QWeather processing"):+ return+ if response["code"] != "200":+ return self._finish(self._error_message(response["code"]))+ return self._finish(str(response["now"]))+ except Exception as e:+ if self.check_if_canceled("QWeather processing"):return- if response["code"] == "200":- indices_res = response["daily"][0]["date"] + "\n" + "\n".join([i["name"] + ": " + i["category"] + ", " + i["text"] for i in response["daily"]])- return QWeather.be_output(indices_res)+ last_e = e+ logging.exception(f"QWeather error: {e}")+ time.sleep(self._param.delay_after_error)- else:- return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])+ if last_e:+ self.set_output("_ERROR", str(last_e))+ return f"QWeather error: {last_e}"- elif self._param.type == "airquality":- url = base_url + "air/now?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang- response = requests.get(url=url, timeout=DEFAULT_TIMEOUT).json()- if self.check_if_canceled("Qweather processing"):- return- if response["code"] == "200":- return QWeather.be_output(str(response["now"]))- else:- return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])- except Exception as e:- if self.check_if_canceled("Qweather processing"):- return- return QWeather.be_output("**Error**" + str(e))+ assert False, self.output()++ def _error_message(self, code) -> str:+ return "**Error** " + self._param.error_code.get(str(code), f"QWeather API returned code {code}.")++ def _finish(self, content: str) -> str:+ self.set_output("formalized_content", content)+ return content++ def thoughts(self) -> str:+ return "Looking up the weather for: {}".format(self.get_input().get("query", "-_-!"))diff --git a/test/unit_test/agent/component/test_qweather.py b/test/unit_test/agent/component/test_qweather.pynew file mode 100644index 0000000000..14b9ebdb6e--- /dev/null+++ b/test/unit_test/agent/component/test_qweather.py@@ -0,0 +1,115 @@+#+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest++from agent.tools import qweather as qweather_mod+from agent.tools.qweather import QWeather, QWeatherParam+++def _make_tool(**overrides):+ # Bypass the canvas-bound __init__ (mirrors test_pubmed_unit.py) and stub the+ # canvas-touching helpers so we can exercise _invoke's execution path.+ tool = QWeather.__new__(QWeather)+ param = QWeatherParam()+ param.web_apikey = "test-key"+ for k, v in overrides.items():+ setattr(param, k, v)+ tool._param = param+ 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+++class _FakeResp:+ def __init__(self, payload):+ self._payload = payload++ def json(self):+ return self._payload+++def _patch_requests(monkeypatch, payloads):+ """Return each payload in order for successive requests.get(...) calls."""+ calls = iter(payloads)++ def fake_get(*args, **kwargs):+ return _FakeResp(next(calls))++ monkeypatch.setattr(qweather_mod.requests, "get", fake_get)+++def test_param_instantiates():+ QWeatherParam()+++def test_check_passes_with_defaults():+ param = QWeatherParam()+ param.web_apikey = "test-key"+ param.check()+++def test_meta_exposes_query_parameter():+ # Regression: QWeather extended ComponentBase and defined no `meta`, so it+ # had no get_meta() and crashed the Agent when added as a tool.+ meta = QWeatherParam().get_meta()+ params = meta["function"]["parameters"]+ assert "query" in params["properties"]+ assert "query" in params["required"]+++def test_check_rejects_empty_apikey():+ param = QWeatherParam()+ param.web_apikey = ""+ with pytest.raises(ValueError):+ param.check()+++def test_invoke_weather_now_returns_content(monkeypatch):+ # Regression for the restored runtime path: _invoke(query=...) resolves the+ # location, fetches current weather, returns the content, and mirrors it to+ # formalized_content.+ _patch_requests(+ monkeypatch,+ [+ {"code": "200", "location": [{"id": "101010100"}]},+ {"code": "200", "now": {"temp": "25", "text": "Sunny"}},+ ],+ )+ tool, out = _make_tool(type="weather", time_period="now")+ res = tool._invoke(query="Beijing")+ assert "Sunny" in res+ assert out["formalized_content"] == res+++def test_invoke_empty_query_returns_empty():+ # Empty query short-circuits without any HTTP call.+ tool, out = _make_tool()+ assert tool._invoke(query="") == ""+ assert out.get("formalized_content") == ""+++def test_invoke_location_lookup_error_returns_message(monkeypatch):+ # A non-200 from the geo lookup is a final, human-readable message (not a+ # retry) and is written to formalized_content.+ _patch_requests(monkeypatch, [{"code": "404"}])+ tool, out = _make_tool()+ res = tool._invoke(query="Nowhere")+ assert res.startswith("**Error**")+ assert "does not exist" in res+ assert out["formalized_content"] == res