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
feat(agent): add You.com search tool (#18583)
Brian Sparkerc6b292338722
diff --git a/agent/tools/youcom.py b/agent/tools/youcom.pynew file mode 100644index 0000000000..9da316f611--- /dev/null+++ b/agent/tools/youcom.py@@ -0,0 +1,223 @@+#+# 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 logging+import os+import time+from abc import ABC++import requests++from agent.tools.base import ToolBase, ToolMeta, ToolParamBase+from common.connection_utils import timeout++# You.com serves the same response shape from two endpoints. The keyless one is+# rate-limited but needs no credentials; the keyed one lifts those limits. The+# keyless endpoint rejects an X-API-Key header, so the endpoint and the headers+# are always chosen together.+YOUCOM_SEARCH_URL = "https://api.you.com/v1/search"+YOUCOM_KEYLESS_SEARCH_URL = "https://api.you.com/v1/agents/search"+# Identifies RAGFlow to You.com. On the keyless endpoint there is no key to+# attribute traffic to, so this is the only signal available.+YOUCOM_USER_AGENT = "RAGFlow youdotcom-integration/infiniflow-ragflow"+# You.com clamps `count` to 1-100.+YOUCOM_MAX_COUNT = 100+# You.com accepts a fixed set of recency windows. `any` is the no-restriction+# default and is never forwarded; the rest go straight into the request.+YOUCOM_FRESHNESS_ANY = "any"+YOUCOM_FRESHNESS_VALUES = [YOUCOM_FRESHNESS_ANY, "day", "week", "month", "year"]+++def _search(api_key: str, params: dict, timeout_s: int = 30) -> dict:+ """GET the keyed endpoint when a key is set, else the keyless one."""+ api_key = (api_key or "").strip()+ headers = {"Accept": "application/json", "User-Agent": YOUCOM_USER_AGENT}+ if api_key:+ url = YOUCOM_SEARCH_URL+ headers["X-API-Key"] = api_key+ else:+ url = YOUCOM_KEYLESS_SEARCH_URL++ response = requests.get(url, headers=headers, params=params, timeout=timeout_s)+ response.raise_for_status()+ return response.json()+++def _freshness(value) -> str:+ """Normalize a freshness value to a You.com window, or "" for no limit.++ Blank and `any` both mean no restriction. Anything else has to be one of the+ published windows, because the value is forwarded to You.com as-is.+ """+ freshness = str(value or "").strip().lower()+ if not freshness or freshness == YOUCOM_FRESHNESS_ANY:+ return ""+ if freshness not in YOUCOM_FRESHNESS_VALUES:+ raise ValueError("Freshness {} is not supported, it should be in {}".format(freshness, YOUCOM_FRESHNESS_VALUES))+ return freshness+++def _result_content(result: dict) -> str:+ """Prefer the extracted page passages, falling back to the description.++ Web hits carry several `snippets` taken from the page body; news hits carry+ only a `description`.+ """+ snippets = result.get("snippets")+ if isinstance(snippets, list):+ joined = " ".join(" ".join(str(s).split()) for s in snippets if str(s).strip())+ if joined:+ return joined+ return " ".join(str(result.get("description") or "").split())+++def _merge_sections(results: dict, top_n: int) -> list[dict]:+ """Web results lead, then news.++ `count` applies per section, so the two together can exceed it; the merged+ list is trimmed back to what the caller asked for.+ """+ if not isinstance(results, dict):+ return []+ merged = []+ for section in ("web", "news"):+ section_results = results.get(section)+ if isinstance(section_results, list):+ merged.extend(r for r in section_results if isinstance(r, dict))+ return merged[:top_n]+++class YouComSearchParam(ToolParamBase):+ """+ Define the You.com search component parameters.+ """++ def __init__(self):+ self.meta: ToolMeta = {+ "name": "youcom_search",+ "description": """+You.com runs its own web index and returns several extracted passages per result+rather than a single snippet, so results carry usable context without a separate+fetch. It works without an API key by default (keyless free tier).+When searching:+ - Use a focused query of the most important terms (and synonyms).+ - Optionally restrict results by how recently they were published.+ """,+ "parameters": {+ "query": {+ "type": "string",+ "description": "The search keywords to execute with You.com. The keywords should be the most important words/terms(includes synonyms) from the original request.",+ "default": "{sys.query}",+ "required": True,+ },+ "freshness": {+ "type": "string",+ "description": "default:'any'. Restrict results by recency. One of 'day', 'week', 'month', 'year', or 'any' for no limit.",+ "enum": YOUCOM_FRESHNESS_VALUES,+ "default": YOUCOM_FRESHNESS_ANY,+ "required": False,+ },+ },+ }+ super().__init__()+ # A key is optional: blank uses the keyless endpoint (free tier);+ # setting one lifts rate limits.+ self.api_key = ""+ self.top_n = 10++ def check(self):+ self.check_positive_integer(self.top_n, "Top N")++ def get_input_form(self) -> dict[str, dict]:+ return {+ "query": {+ "name": "Query",+ "type": "line",+ },+ "freshness": {+ "name": "Freshness",+ "type": "options",+ "value": YOUCOM_FRESHNESS_ANY,+ "options": YOUCOM_FRESHNESS_VALUES,+ },+ }+++class YouComSearch(ToolBase, ABC):+ component_name = "YouComSearch"++ @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12)))+ def _invoke(self, **kwargs):+ if self.check_if_canceled("YouComSearch processing"):+ return++ if not kwargs.get("query"):+ self.set_output("formalized_content", "")+ return ""++ keyed = bool((self._param.api_key or "").strip())+ params = {+ "query": kwargs["query"],+ "count": min(max(1, int(self._param.top_n)), YOUCOM_MAX_COUNT),+ }+ freshness = _freshness(kwargs.get("freshness"))+ if freshness:+ params["freshness"] = freshness++ logging.info(f"YouComSearch: starting search (keyed={keyed})")+ last_e = None+ attempts = self._param.max_retries + 1+ for attempt in range(attempts):+ if self.check_if_canceled("YouComSearch processing"):+ logging.info("YouComSearch: cancelled before request")+ return++ try:+ data = _search(self._param.api_key, params)+ if self.check_if_canceled("YouComSearch processing"):+ logging.info("YouComSearch: cancelled after request")+ return++ results = _merge_sections(data.get("results") or {}, self._param.top_n)+ self._retrieve_chunks(+ results,+ get_title=lambda r: r.get("title"),+ get_url=lambda r: r.get("url"),+ get_content=_result_content,+ )+ self.set_output("json", results)+ logging.info(f"YouComSearch: returned {len(results)} results")+ return self.output("formalized_content")+ except Exception as e:+ if self.check_if_canceled("YouComSearch processing"):+ return++ # Only the exception type is recorded: the query is a URL+ # parameter here, so the requests error message contains it.+ last_e = e+ logging.error(f"You.com error: {type(e).__name__}")+ if attempt < attempts - 1:+ time.sleep(self._param.delay_after_error)++ if last_e:+ return f"You.com error: {type(last_e).__name__}"++ assert False, self.output()++ def thoughts(self) -> str:+ return """+Keywords: {}+Looking for the most relevant articles.+ """.format(self.get_input().get("query", "-_-!"))diff --git a/test/unit_test/agent/tools/test_youcom_unit.py b/test/unit_test/agent/tools/test_youcom_unit.pynew file mode 100644index 0000000000..9133ea9b11--- /dev/null+++ b/test/unit_test/agent/tools/test_youcom_unit.py@@ -0,0 +1,264 @@+#+# 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 agent.tools.youcom as youcom_module+from agent.tools.youcom import YouComSearch, YouComSearchParam++KEYLESS_URL = "https://api.you.com/v1/agents/search"+KEYED_URL = "https://api.you.com/v1/search"+++class _FakeResponse:+ def __init__(self, payload, status_code=200):+ self._payload = payload+ self.status_code = status_code+ self.url = f"{KEYLESS_URL}?query=my%20private%20query&count=10"++ def json(self):+ return self._payload++ def raise_for_status(self):+ if self.status_code >= 400:+ raise youcom_module.requests.HTTPError(+ f"{self.status_code} Client Error for url: {self.url}",+ response=self,+ )+++def _make_tool(api_key=""):+ tool = YouComSearch.__new__(YouComSearch)+ param = YouComSearchParam()+ param.api_key = api_key+ param.delay_after_error = 0+ param.max_retries = 0+ tool._param = param+ tool.check_if_canceled = lambda *args, **kwargs: False++ captured = {}+ outputs = {}++ def fake_retrieve(results, get_title, get_url, get_content):+ captured["references"] = [{"title": get_title(item), "url": get_url(item), "content": get_content(item)} for item in results]+ outputs["formalized_content"] = "FORMALIZED"++ tool._retrieve_chunks = fake_retrieve+ tool.set_output = lambda key, value: outputs.__setitem__(key, value)+ tool.output = lambda key=None: outputs.get(key) if key else outputs+ return tool, captured, outputs+++def _payload():+ return {+ "results": {+ "web": [+ {+ "url": "https://example.com/a",+ "title": "A",+ "description": "Meta description.",+ "snippets": ["First passage.", "Second passage."],+ }+ ],+ "news": [+ {+ "url": "https://news.example.com/b",+ "title": "B",+ "description": "News description only.",+ }+ ],+ }+ }+++def _capture_get(monkeypatch, response=None):+ calls = []++ def fake_get(url, headers=None, params=None, timeout=None):+ calls.append({"url": url, "headers": headers, "params": params})+ return response if response is not None else _FakeResponse(_payload())++ monkeypatch.setattr(youcom_module.requests, "get", fake_get)+ return calls+++def test_keyless_search_uses_the_public_endpoint_without_an_auth_header(monkeypatch):+ calls = _capture_get(monkeypatch)+ tool, _captured, outputs = _make_tool(api_key="")++ tool._invoke(query="What is RAGFlow?")++ assert calls[0]["url"] == KEYLESS_URL+ # The keyless endpoint rejects an auth header, so none may be sent.+ assert "X-API-Key" not in calls[0]["headers"]+ assert calls[0]["params"]["query"] == "What is RAGFlow?"+ assert outputs["formalized_content"] == "FORMALIZED"+++def test_keyed_search_uses_the_authenticated_endpoint(monkeypatch):+ calls = _capture_get(monkeypatch)+ tool, _captured, _outputs = _make_tool(api_key=" ydc-test ")++ tool._invoke(query="What is RAGFlow?")++ assert calls[0]["url"] == KEYED_URL+ assert calls[0]["headers"]["X-API-Key"] == "ydc-test"+++def test_requests_identify_ragflow(monkeypatch):+ calls = _capture_get(monkeypatch)+ tool, _captured, _outputs = _make_tool()++ tool._invoke(query="What is RAGFlow?")++ assert calls[0]["headers"]["User-Agent"] == "RAGFlow youdotcom-integration/infiniflow-ragflow"+++def test_web_and_news_are_merged_with_passages_preferred(monkeypatch):+ _capture_get(monkeypatch)+ tool, captured, outputs = _make_tool()++ tool._invoke(query="What is RAGFlow?")++ assert captured["references"] == [+ {"title": "A", "url": "https://example.com/a", "content": "First passage. Second passage."},+ {"title": "B", "url": "https://news.example.com/b", "content": "News description only."},+ ]+ assert len(outputs["json"]) == 2+++def test_top_n_caps_the_merged_sections(monkeypatch):+ payload = {+ "results": {+ "web": [{"url": f"https://example.com/w{i}", "title": f"W{i}", "description": "d"} for i in range(6)],+ "news": [{"url": f"https://example.com/n{i}", "title": f"N{i}", "description": "d"} for i in range(6)],+ }+ }+ calls = _capture_get(monkeypatch, _FakeResponse(payload))+ tool, captured, _outputs = _make_tool()+ tool._param.top_n = 4++ tool._invoke(query="q")++ assert calls[0]["params"]["count"] == 4+ # `count` applies per section, so the merged list is trimmed on our side.+ assert [r["title"] for r in captured["references"]] == ["W0", "W1", "W2", "W3"]+++def test_freshness_is_forwarded_only_when_a_window_is_set(monkeypatch):+ calls = _capture_get(monkeypatch)+ tool, _captured, _outputs = _make_tool()++ tool._invoke(query="q", freshness="week")+ assert calls[0]["params"]["freshness"] == "week"++ # Blank and `any` both mean no restriction.+ tool._invoke(query="q", freshness="")+ assert "freshness" not in calls[1]["params"]++ tool._invoke(query="q", freshness="any")+ assert "freshness" not in calls[2]["params"]+++def test_an_unsupported_freshness_is_rejected_before_the_request(monkeypatch):+ calls = _capture_get(monkeypatch)+ tool, _captured, _outputs = _make_tool()++ try:+ tool._invoke(query="q", freshness="decade")+ except ValueError as e:+ assert "decade" in str(e)+ assert calls == []+ return+ raise AssertionError("expected an unsupported freshness to raise")+++def test_the_published_schema_restricts_freshness():+ freshness = YouComSearchParam().get_meta()["function"]["parameters"]["properties"]["freshness"]++ assert freshness["enum"] == ["any", "day", "week", "month", "year"]+++def test_blank_query_short_circuits(monkeypatch):+ calls = _capture_get(monkeypatch)+ tool, _captured, outputs = _make_tool()++ assert tool._invoke(query="") == ""+ assert calls == []+ assert outputs["formalized_content"] == ""+++def test_failures_never_log_the_query_or_the_key(monkeypatch, caplog):+ """The query is a URL parameter, so the requests error message contains it."""+ _capture_get(monkeypatch, _FakeResponse({}, status_code=402))+ tool, _captured, _outputs = _make_tool(api_key="ydc-secret")++ with caplog.at_level("ERROR"):+ result = tool._invoke(query="my private query")++ assert "my%20private%20query" not in caplog.text+ assert "ydc-secret" not in caplog.text+ assert "my%20private%20query" not in str(result)+ assert "HTTPError" in str(result)+++def _capture_sleep(monkeypatch):+ """Record the retry delays without patching the stdlib for other threads."""+ slept = []++ class _Clock:+ @staticmethod+ def sleep(seconds):+ slept.append(seconds)++ monkeypatch.setattr(youcom_module, "time", _Clock)+ return slept+++def test_a_failed_final_attempt_does_not_sleep(monkeypatch):+ """The delay only buys something when another attempt follows it."""+ _capture_get(monkeypatch, _FakeResponse({}, status_code=402))+ slept = _capture_sleep(monkeypatch)+ tool, _captured, _outputs = _make_tool()+ tool._param.max_retries = 0+ tool._param.delay_after_error = 5++ tool._invoke(query="q")++ assert slept == []+++def test_retries_sleep_between_attempts(monkeypatch):+ calls = _capture_get(monkeypatch, _FakeResponse({}, status_code=402))+ slept = _capture_sleep(monkeypatch)+ tool, _captured, _outputs = _make_tool()+ tool._param.max_retries = 2+ tool._param.delay_after_error = 5++ tool._invoke(query="q")++ assert len(calls) == 3+ # Two gaps between three attempts, and nothing after the last one.+ assert slept == [5, 5]+++def test_param_check_rejects_a_non_positive_top_n():+ param = YouComSearchParam()+ param.top_n = 0++ try:+ param.check()+ except Exception:+ return+ raise AssertionError("expected check() to reject top_n=0")diff --git a/web/src/components/operator-icon.tsx b/web/src/components/operator-icon.tsxindex 9e8528c37e..021d28d228 100644--- a/web/src/components/operator-icon.tsx+++ b/web/src/components/operator-icon.tsx@@ -72,6 +72,7 @@ export const SVGIconMap = {[Operator.BGPT]: 'bgpt',[Operator.SearXNG]: 'searxng',[Operator.KeenableSearch]: 'keenable',+ [Operator.YouComSearch]: 'youcom',[Operator.TavilyExtract]: 'tavily',[Operator.TavilySearch]: 'tavily',[Operator.QueritContents]: 'querit',diff --git a/web/src/constants/agent.tsx b/web/src/constants/agent.tsxindex 69052061eb..4adccf304f 100644--- a/web/src/constants/agent.tsx+++ b/web/src/constants/agent.tsx@@ -118,6 +118,7 @@ export enum Operator {SearXNG = 'SearXNG',BGPT = 'BGPT',KeenableSearch = 'KeenableSearch',+ YouComSearch = 'YouComSearch',DocGenerator = 'DocGenerator',Browser = 'Browser',Placeholder = 'Placeholder',diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 433b89d446..f1d3f6abd8 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -2712,6 +2712,17 @@ Best for: Documents with flowing, contextually connected content — such as bookeenableMode: 'Search mode',keenableSite: 'Site',keenableApiKeyTip: 'Optional. Leave blank to use the keyless free tier.',+ youComSearch: 'You.com',+ youComSearchDescription:+ "A web search component powered by You.com's own index. Each result carries extracted passages from the page rather than a single snippet. Works without an API Key by default (keyless free tier); add a key to lift rate limits.",+ youComFreshness: 'Freshness',+ youComFreshnessTip: 'Restrict results by how recently they were published.',+ youComFreshnessAny: 'Any time',+ youComFreshnessDay: 'Past day',+ youComFreshnessWeek: 'Past week',+ youComFreshnessMonth: 'Past month',+ youComFreshnessYear: 'Past year',+ youComApiKeyTip: 'Optional. Leave blank to use the keyless free tier.',docGenerator: 'Doc Generator',docGeneratorDescription: `Generate a file from Markdown content.`,browser: 'Browser',diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex 37e096a364..e2cdc3d89b 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -2356,6 +2356,17 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RsearXNG: 'SearXNG',searXNGDescription:'该组件通过您提供的 SearXNG 实例地址进行搜索。请设置 Top N 和实例 URL。',+ youComSearch: 'You.com',+ youComSearchDescription:+ '基于 You.com 自有索引的网络搜索组件。每条结果附带从页面提取的多段文本,而不只是一段摘要。默认无需 API Key 即可使用(免密钥免费额度);配置 Key 可解除限速。',+ youComFreshness: '时间范围',+ youComFreshnessTip: '按发布时间的新旧程度筛选结果。',+ youComFreshnessAny: '不限时间',+ youComFreshnessDay: '一天内',+ youComFreshnessWeek: '一周内',+ youComFreshnessMonth: '一个月内',+ youComFreshnessYear: '一年内',+ youComApiKeyTip: '可选。留空则使用免密钥的免费额度。',docGenerator: '文档生成器',docGeneratorDescription: `从 Markdown 内容生成文件。`,browser: 'Browser',diff --git a/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx b/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsxindex feb419d487..3e44bc01da 100644--- a/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx+++ b/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx@@ -126,6 +126,7 @@ export function AccordionOperators({Operator.WenCai,Operator.SearXNG,Operator.KeenableSearch,+ Operator.YouComSearch,Operator.DocGenerator,Operator.Browser,]}diff --git a/web/src/pages/agent/constant/index.tsx b/web/src/pages/agent/constant/index.tsxindex 1d9da46689..b0c1a863c0 100644--- a/web/src/pages/agent/constant/index.tsx+++ b/web/src/pages/agent/constant/index.tsx@@ -197,6 +197,31 @@ export enum KeenableMode {Realtime = 'realtime',}+export enum YouComFreshness {+ Any = 'any',+ Day = 'day',+ Week = 'week',+ Month = 'month',+ Year = 'year',+}++export const initialYouComValues = {+ api_key: '',+ query: AgentGlobals.SysQuery,+ freshness: YouComFreshness.Any,+ top_n: 10,+ outputs: {+ formalized_content: {+ value: '',+ type: 'string',+ },+ json: {+ value: [],+ type: 'Array<Object>',+ },+ },+};+export const initialKeenableValues = {api_key: '',query: AgentGlobals.SysQuery,@@ -749,6 +774,7 @@ export const RestrictedUpstreamMap = {[Operator.GitHub]: [Operator.Begin, Operator.Retrieval],[Operator.SearXNG]: [Operator.Begin, Operator.Retrieval],[Operator.KeenableSearch]: [Operator.Begin, Operator.Retrieval],+ [Operator.YouComSearch]: [Operator.Begin, Operator.Retrieval],[Operator.ExeSQL]: [Operator.Begin],[Operator.Switch]: [Operator.Begin],[Operator.WenCai]: [Operator.Begin],@@ -805,6 +831,7 @@ export const NodeMap = {[Operator.GitHub]: 'ragNode',[Operator.SearXNG]: 'ragNode',[Operator.KeenableSearch]: 'ragNode',+ [Operator.YouComSearch]: 'ragNode',[Operator.ExeSQL]: 'ragNode',[Operator.Switch]: 'switchNode',[Operator.WenCai]: 'ragNode',diff --git a/web/src/pages/agent/form-sheet/form-config-map.tsx b/web/src/pages/agent/form-sheet/form-config-map.tsxindex a8fb6af7b4..d3072dd82a 100644--- a/web/src/pages/agent/form-sheet/form-config-map.tsx+++ b/web/src/pages/agent/form-sheet/form-config-map.tsx@@ -21,6 +21,7 @@ import InvokeForm from '../form/invoke-form';import IterationForm from '../form/iteration-form';import IterationStartForm from '../form/iteration-start-from';import KeenableForm from '../form/keenable-form';+import YouComForm from '../form/youcom-form';import ListOperationsForm from '../form/list-operations-form';import LoopForm from '../form/loop-form';import MessageForm from '../form/message-form';@@ -78,6 +79,9 @@ export const FormConfigMap = {[Operator.KeenableSearch]: {component: KeenableForm,},+ [Operator.YouComSearch]: {+ component: YouComForm,+ },[Operator.Wikipedia]: {component: WikipediaForm,},diff --git a/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx b/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsxindex a10b33b293..1624562d03 100644--- a/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx+++ b/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx@@ -31,6 +31,7 @@ const Menus = [Operator.Wikipedia,Operator.SearXNG,Operator.KeenableSearch,+ Operator.YouComSearch,Operator.YahooFinance,Operator.PubMed,Operator.BGPT,diff --git a/web/src/pages/agent/form/tool-form/constant.tsx b/web/src/pages/agent/form/tool-form/constant.tsxindex e6b369429d..8be86f58b2 100644--- a/web/src/pages/agent/form/tool-form/constant.tsx+++ b/web/src/pages/agent/form/tool-form/constant.tsx@@ -9,6 +9,7 @@ import GithubForm from './github-form';import GoogleForm from './google-form';import GoogleScholarForm from './google-scholar-form';import KeenableForm from './keenable-form';+import YouComForm from './youcom-form';import PubMedForm from './pubmed-form';import QueritForm from './querit-form';import BGPTForm from './bgpt-form';@@ -42,4 +43,5 @@ export const ToolFormConfigMap = {[Operator.WenCai]: WenCaiForm,[Operator.SearXNG]: SearXNGForm,[Operator.KeenableSearch]: KeenableForm,+ [Operator.YouComSearch]: YouComForm,};diff --git a/web/src/pages/agent/form/tool-form/youcom-form/index.tsx b/web/src/pages/agent/form/tool-form/youcom-form/index.tsxnew file mode 100644index 0000000000..7c5ecf7f88--- /dev/null+++ b/web/src/pages/agent/form/tool-form/youcom-form/index.tsx@@ -0,0 +1,35 @@+import { FormContainer } from '@/components/form-container';+import { Form } from '@/components/ui/form';+import { zodResolver } from '@hookform/resolvers/zod';+import { memo } from 'react';+import { useForm } from 'react-hook-form';+import { z } from 'zod';+import { FormWrapper } from '../../components/form-wrapper';+import { YouComFormPartialSchema, YouComWidgets } from '../../youcom-form';+import { useValues } from '../use-values';+import { useWatchFormChange } from '../use-watch-change';++function YouComForm() {+ const values = useValues();++ const FormSchema = z.object(YouComFormPartialSchema);++ const form = useForm<z.infer<typeof FormSchema>>({+ defaultValues: values,+ resolver: zodResolver(FormSchema),+ });++ useWatchFormChange(form);++ return (+ <Form {...form}>+ <FormWrapper>+ <FormContainer>+ <YouComWidgets></YouComWidgets>+ </FormContainer>+ </FormWrapper>+ </Form>+ );+}++export default memo(YouComForm);diff --git a/web/src/pages/agent/form/youcom-form/index.tsx b/web/src/pages/agent/form/youcom-form/index.tsxnew file mode 100644index 0000000000..a9e809b42f--- /dev/null+++ b/web/src/pages/agent/form/youcom-form/index.tsx@@ -0,0 +1,111 @@+import { FormContainer } from '@/components/form-container';+import { TopNFormField } from '@/components/top-n-item';+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { RAGFlowSelect } from '@/components/ui/select';+import { useTranslate } from '@/hooks/common-hooks';+import { zodResolver } from '@hookform/resolvers/zod';+import { memo, useMemo } from 'react';+import { useForm, useFormContext } from 'react-hook-form';+import { z } from 'zod';+import { YouComFreshness, initialYouComValues } from '../../constant';+import { useFormValues } from '../../hooks/use-form-values';+import { useWatchFormChange } from '../../hooks/use-watch-form-change';+import { INextOperatorForm } from '../../interface';+import { buildOutputList } from '../../utils/build-output-list';+import { ApiKeyField } from '../components/api-key-field';+import { FormWrapper } from '../components/form-wrapper';+import { Output } from '../components/output';+import { QueryVariable } from '../components/query-variable';++// Freshness is a user-facing word, so each option carries its own key rather+// than deriving an English label from the enum value.+const YouComFreshnessLabelKeys: Record<YouComFreshness, string> = {+ [YouComFreshness.Any]: 'youComFreshnessAny',+ [YouComFreshness.Day]: 'youComFreshnessDay',+ [YouComFreshness.Week]: 'youComFreshnessWeek',+ [YouComFreshness.Month]: 'youComFreshnessMonth',+ [YouComFreshness.Year]: 'youComFreshnessYear',+};++export const YouComFormPartialSchema = {+ api_key: z.string().optional(),+ freshness: z.string().optional(),+ top_n: z.coerce.number(),+};++const FormSchema = z.object({+ query: z.string(),+ ...YouComFormPartialSchema,+});++export function YouComWidgets() {+ const { t } = useTranslate('flow');+ const form = useFormContext();++ const freshnessOptions = useMemo(+ () =>+ Object.values(YouComFreshness).map((x) => ({+ value: x,+ label: t(YouComFreshnessLabelKeys[x]),+ })),+ [t],+ );++ return (+ <>+ <ApiKeyField placeholder={t('youComApiKeyTip')}></ApiKeyField>+ <FormField+ control={form.control}+ name={'freshness'}+ render={({ field }) => (+ <FormItem>+ <FormLabel tooltip={t('youComFreshnessTip')}>+ {t('youComFreshness')}+ </FormLabel>+ <FormControl>+ <RAGFlowSelect {...field} options={freshnessOptions} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <TopNFormField></TopNFormField>+ </>+ );+}++const YouComOutputList = buildOutputList(initialYouComValues.outputs);++function YouComForm({ node }: INextOperatorForm) {+ const defaultValues = useFormValues(initialYouComValues, node);++ const form = useForm<z.infer<typeof FormSchema>>({+ defaultValues,+ resolver: zodResolver(FormSchema),+ });++ useWatchFormChange(node?.id, form);++ return (+ <Form {...form}>+ <FormWrapper>+ <FormContainer>+ <QueryVariable></QueryVariable>+ <YouComWidgets></YouComWidgets>+ </FormContainer>+ </FormWrapper>+ <div className="p-5">+ <Output list={YouComOutputList}></Output>+ </div>+ </Form>+ );+}++export default memo(YouComForm);diff --git a/web/src/pages/agent/hooks/use-add-node.ts b/web/src/pages/agent/hooks/use-add-node.tsindex 6207b5f9dd..d30aad25ff 100644--- a/web/src/pages/agent/hooks/use-add-node.ts+++ b/web/src/pages/agent/hooks/use-add-node.ts@@ -32,6 +32,7 @@ import {initialIterationStartValues,initialIterationValues,initialKeenableValues,+ initialYouComValues,initialListOperationsValues,initialLoopValues,initialMessageValues,@@ -173,6 +174,7 @@ export const useInitializeOperatorParams = () => {[Operator.QueritContents]: initialQueritContentsValues,[Operator.QueritSearch]: initialQueritValues,[Operator.KeenableSearch]: initialKeenableValues,+ [Operator.YouComSearch]: initialYouComValues,[Operator.UserFillUp]: initialUserFillUpValues,[Operator.StringTransform]: initialStringTransformValues,[Operator.TavilyExtract]: initialTavilyExtractValues,diff --git a/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts b/web/src/pages/agent/hooks/use-agent-tool-initial-values.tsindex 814afc3d72..91fbd8ea08 100644--- a/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts+++ b/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts@@ -68,6 +68,8 @@ export function useAgentToolInitialValues() {return pick(initialValues, 'searxng_url', 'top_n');case Operator.KeenableSearch:return pick(initialValues, 'api_key', 'mode', 'site', 'top_n');+ case Operator.YouComSearch:+ return pick(initialValues, 'api_key', 'freshness', 'top_n');default:return initialValues;diff --git a/web/src/pages/agent/log-sheet/tool-timeline-item.tsx b/web/src/pages/agent/log-sheet/tool-timeline-item.tsxindex 6666f641c5..234c0a6c73 100644--- a/web/src/pages/agent/log-sheet/tool-timeline-item.tsx+++ b/web/src/pages/agent/log-sheet/tool-timeline-item.tsx@@ -32,6 +32,7 @@ type IToolIcon =| Operator.QueritContents| Operator.QueritSearch| Operator.KeenableSearch+ | Operator.YouComSearch| Operator.Wikipedia| Operator.YahooFinance| Operator.WenCaidiff --git a/web/src/pages/agent/utils/clear-sensitive-fields.test.ts b/web/src/pages/agent/utils/clear-sensitive-fields.test.tsindex f19b77469c..67b7e1293a 100644--- a/web/src/pages/agent/utils/clear-sensitive-fields.test.ts+++ b/web/src/pages/agent/utils/clear-sensitive-fields.test.ts@@ -4,6 +4,7 @@ jest.mock('@/constants/agent', () => ({TavilyExtract: 'TavilyExtract',Google: 'Google',KeenableSearch: 'KeenableSearch',+ YouComSearch: 'YouComSearch',BGPT: 'Bing',QueritContents: 'QueritContents',QueritSearch: 'QueritSearch',@@ -109,6 +110,42 @@ describe('clearSensitiveFields', () => {expect(dsl.components.querit.obj.params.api_key).toBe('component-secret');});+ it('clears a You.com key from a canvas node and from a tool record', () => {+ const dsl = {+ graph: {+ nodes: [+ {+ data: {+ label: Operator.YouComSearch,+ form: {+ api_key: 'ydc-graph-secret',+ freshness: 'week',+ },+ },+ },+ ],+ },+ tools: [+ {+ component_name: Operator.YouComSearch,+ params: {+ api_key: 'ydc-tool-secret',+ top_n: 10,+ },+ },+ ],+ };++ const sanitized = clearSensitiveFields(dsl);++ expect(sanitized.graph.nodes[0].data.form.api_key).toBe('');+ expect(sanitized.graph.nodes[0].data.form.freshness).toBe('week');+ expect(sanitized.tools[0].params.api_key).toBe('');+ expect(sanitized.tools[0].params.top_n).toBe(10);+ expect(dsl.graph.nodes[0].data.form.api_key).toBe('ydc-graph-secret');+ expect(dsl.tools[0].params.api_key).toBe('ydc-tool-secret');+ });+it('does not change standalone graph export behavior for other tools', () => {const dsl = {graph: {diff --git a/web/src/pages/agent/utils/clear-sensitive-fields.ts b/web/src/pages/agent/utils/clear-sensitive-fields.tsindex d7d6c59d1b..8fc8f10ec4 100644--- a/web/src/pages/agent/utils/clear-sensitive-fields.ts+++ b/web/src/pages/agent/utils/clear-sensitive-fields.ts@@ -6,11 +6,17 @@ const apiKeyOperators = [Operator.TavilyExtract,Operator.Google,Operator.KeenableSearch,+ Operator.YouComSearch,Operator.BGPT,Operator.QueritContents,Operator.QueritSearch,];+// Canvas nodes carry the operator under `data.label` and the key under+// `data.form.api_key`, so a graph export has to be sanitized separately from the+// agent-tool records above.+const nodeLabelApiKeyOperators: string[] = [Operator.YouComSearch];+function isQueritOperator(value: unknown) {if (typeof value !== 'string') {return false;@@ -21,6 +27,14 @@ function isQueritOperator(value: unknown) {);}+function isNodeLabelApiKeyOperator(value: unknown) {+ if (typeof value !== 'string') {+ return false;+ }++ return isQueritOperator(value) || nodeLabelApiKeyOperators.includes(value);+}+export function clearSensitiveFields<T>(obj: T): T {return cloneDeepWith(obj, (value) => {if (!isPlainObject(value)) {@@ -36,7 +50,7 @@ export function clearSensitiveFields<T>(obj: T): T {}if (- isQueritOperator(get(value, 'data.label')) &&+ isNodeLabelApiKeyOperator(get(value, 'data.label')) &&get(value, 'data.form.api_key')) {return {