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
Move 'timeout' to common folder (#10983)
Jin Hai1e4513728425
diff --git a/agent/component/agent_with_tools.py b/agent/component/agent_with_tools.pyindex b3e2df6f51..53c2ed9ad7 100644--- a/agent/component/agent_with_tools.py+++ b/agent/component/agent_with_tools.py@@ -27,7 +27,7 @@ from agent.tools.base import LLMToolPluginCallSession, ToolParamBase, ToolBase,from api.db.services.llm_service import LLMBundlefrom api.db.services.tenant_llm_service import TenantLLMServicefrom api.db.services.mcp_server_service import MCPServerService-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.prompts.generator import next_step, COMPLETE_TASK, analyze_task, \citation_prompt, reflect, rank_memories, kb_prompt, citation_plus, full_question, message_fit_infrom rag.utils.mcp_tool_call_conn import MCPToolCallSession, mcp_tool_metadata_to_openai_tooldiff --git a/agent/component/base.py b/agent/component/base.pyindex 73f11ba95a..db9a8f29dd 100644--- a/agent/component/base.py+++ b/agent/component/base.py@@ -25,7 +25,7 @@ from typing import Any, List, Unionimport pandas as pdimport triofrom agent import settings-from api.utils.api_utils import timeout+from common.connection_utils import timeout_FEEDED_DEPRECATED_PARAMS = "_feeded_deprecated_params"diff --git a/agent/component/categorize.py b/agent/component/categorize.pyindex af2666fcbf..1c611daf7f 100644--- a/agent/component/categorize.py+++ b/agent/component/categorize.py@@ -21,7 +21,7 @@ from abc import ABCfrom api.db import LLMTypefrom api.db.services.llm_service import LLMBundlefrom agent.component.llm import LLMParam, LLM-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.llm.chat_model import ERROR_PREFIXdiff --git a/agent/component/invoke.py b/agent/component/invoke.pyindex d31c7ed250..00a39b905c 100644--- a/agent/component/invoke.py+++ b/agent/component/invoke.py@@ -23,7 +23,7 @@ from abc import ABCimport requestsfrom agent.component.base import ComponentBase, ComponentParamBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom deepdoc.parser import HtmlParserdiff --git a/agent/component/llm.py b/agent/component/llm.pyindex 61e52b6fa3..123124765b 100644--- a/agent/component/llm.py+++ b/agent/component/llm.py@@ -25,7 +25,7 @@ from api.db import LLMTypefrom api.db.services.llm_service import LLMBundlefrom api.db.services.tenant_llm_service import TenantLLMServicefrom agent.component.base import ComponentBase, ComponentParamBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.prompts.generator import tool_call_summary, message_fit_in, citation_prompt, structured_output_promptdiff --git a/agent/component/message.py b/agent/component/message.pyindex 3569065e56..a91c2522e6 100644--- a/agent/component/message.py+++ b/agent/component/message.py@@ -23,7 +23,7 @@ from typing import Anyfrom agent.component.base import ComponentBase, ComponentParamBasefrom jinja2 import Template as Jinja2Template-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass MessageParam(ComponentParamBase):diff --git a/agent/component/string_transform.py b/agent/component/string_transform.pyindex fe812c0a81..7802075d1a 100644--- a/agent/component/string_transform.py+++ b/agent/component/string_transform.py@@ -18,7 +18,7 @@ import refrom abc import ABCfrom jinja2 import Template as Jinja2Templatefrom agent.component.base import ComponentParamBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom .message import Messagediff --git a/agent/component/switch.py b/agent/component/switch.pyindex 8cbbde6596..41c25c32f3 100644--- a/agent/component/switch.py+++ b/agent/component/switch.py@@ -19,7 +19,7 @@ from abc import ABCfrom typing import Anyfrom agent.component.base import ComponentBase, ComponentParamBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass SwitchParam(ComponentParamBase):diff --git a/agent/tools/arxiv.py b/agent/tools/arxiv.pyindex 616afa31a4..74a810c745 100644--- a/agent/tools/arxiv.py+++ b/agent/tools/arxiv.py@@ -19,7 +19,7 @@ import timefrom abc import ABCimport arxivfrom agent.tools.base import ToolParamBase, ToolMeta, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass ArXivParam(ToolParamBase):diff --git a/agent/tools/code_exec.py b/agent/tools/code_exec.pyindex 6bd1af34ee..e1fef7fbea 100644--- a/agent/tools/code_exec.py+++ b/agent/tools/code_exec.py@@ -22,7 +22,7 @@ from typing import Optionalfrom pydantic import BaseModel, Field, field_validatorfrom agent.tools.base import ToolParamBase, ToolBase, ToolMetafrom api import settings-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass Language(StrEnum):diff --git a/agent/tools/duckduckgo.py b/agent/tools/duckduckgo.pyindex 0315d69713..fcf5ee0772 100644--- a/agent/tools/duckduckgo.py+++ b/agent/tools/duckduckgo.py@@ -19,7 +19,7 @@ import timefrom abc import ABCfrom duckduckgo_search import DDGSfrom agent.tools.base import ToolMeta, ToolParamBase, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass DuckDuckGoParam(ToolParamBase):diff --git a/agent/tools/email.py b/agent/tools/email.pyindex ab6cc6ea63..42d3e28789 100644--- a/agent/tools/email.py+++ b/agent/tools/email.py@@ -25,7 +25,7 @@ from email.header import Headerfrom email.utils import formataddrfrom agent.tools.base import ToolParamBase, ToolBase, ToolMeta-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass EmailParam(ToolParamBase):diff --git a/agent/tools/exesql.py b/agent/tools/exesql.pyindex d937453237..b5917e7301 100644--- a/agent/tools/exesql.py+++ b/agent/tools/exesql.py@@ -22,7 +22,7 @@ import pymysqlimport psycopg2import pyodbcfrom agent.tools.base import ToolParamBase, ToolBase, ToolMeta-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass ExeSQLParam(ToolParamBase):diff --git a/agent/tools/github.py b/agent/tools/github.pyindex 27cb1e3463..7b53f0b0b9 100644--- a/agent/tools/github.py+++ b/agent/tools/github.py@@ -19,7 +19,7 @@ import timefrom abc import ABCimport requestsfrom agent.tools.base import ToolParamBase, ToolMeta, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass GitHubParam(ToolParamBase):diff --git a/agent/tools/google.py b/agent/tools/google.pyindex 455038abed..3184aaaebb 100644--- a/agent/tools/google.py+++ b/agent/tools/google.py@@ -19,7 +19,7 @@ import timefrom abc import ABCfrom serpapi import GoogleSearchfrom agent.tools.base import ToolParamBase, ToolMeta, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass GoogleParam(ToolParamBase):diff --git a/agent/tools/googlescholar.py b/agent/tools/googlescholar.pyindex bf906da4b9..da7f6ef695 100644--- a/agent/tools/googlescholar.py+++ b/agent/tools/googlescholar.py@@ -19,7 +19,7 @@ import timefrom abc import ABCfrom scholarly import scholarlyfrom agent.tools.base import ToolMeta, ToolParamBase, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass GoogleScholarParam(ToolParamBase):diff --git a/agent/tools/pubmed.py b/agent/tools/pubmed.pyindex 0920b3e236..afa1717683 100644--- a/agent/tools/pubmed.py+++ b/agent/tools/pubmed.py@@ -21,7 +21,7 @@ from Bio import Entrezimport reimport xml.etree.ElementTree as ETfrom agent.tools.base import ToolParamBase, ToolMeta, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass PubMedParam(ToolParamBase):diff --git a/agent/tools/retrieval.py b/agent/tools/retrieval.pyindex bb44b124ad..99ed04e2f9 100644--- a/agent/tools/retrieval.py+++ b/agent/tools/retrieval.py@@ -25,7 +25,7 @@ from api.db.services.dialog_service import meta_filterfrom api.db.services.knowledgebase_service import KnowledgebaseServicefrom api.db.services.llm_service import LLMBundlefrom api import settings-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.app.tag import label_questionfrom rag.prompts.generator import cross_languages, kb_prompt, gen_meta_filterdiff --git a/agent/tools/searxng.py b/agent/tools/searxng.pyindex 32e8075851..44ad18bae6 100644--- a/agent/tools/searxng.py+++ b/agent/tools/searxng.py@@ -19,7 +19,7 @@ import timefrom abc import ABCimport requestsfrom agent.tools.base import ToolMeta, ToolParamBase, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass SearXNGParam(ToolParamBase):diff --git a/agent/tools/tavily.py b/agent/tools/tavily.pyindex 80203feec4..6912c3695c 100644--- a/agent/tools/tavily.py+++ b/agent/tools/tavily.py@@ -19,7 +19,7 @@ import timefrom abc import ABCfrom tavily import TavilyClientfrom agent.tools.base import ToolParamBase, ToolBase, ToolMeta-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass TavilySearchParam(ToolParamBase):diff --git a/agent/tools/wencai.py b/agent/tools/wencai.pyindex e2f8adefcc..7ddf27ac33 100644--- a/agent/tools/wencai.py+++ b/agent/tools/wencai.py@@ -21,7 +21,7 @@ import pandas as pdimport pywencaifrom agent.tools.base import ToolParamBase, ToolMeta, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass WenCaiParam(ToolParamBase):diff --git a/agent/tools/wikipedia.py b/agent/tools/wikipedia.pyindex 83e3b13a8c..8dcddc9b97 100644--- a/agent/tools/wikipedia.py+++ b/agent/tools/wikipedia.py@@ -19,7 +19,7 @@ import timefrom abc import ABCimport wikipediafrom agent.tools.base import ToolMeta, ToolParamBase, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass WikipediaParam(ToolParamBase):diff --git a/agent/tools/yahoofinance.py b/agent/tools/yahoofinance.pyindex 9feea20af8..3cca93f3df 100644--- a/agent/tools/yahoofinance.py+++ b/agent/tools/yahoofinance.py@@ -20,7 +20,7 @@ from abc import ABCimport pandas as pdimport yfinance as yffrom agent.tools.base import ToolMeta, ToolParamBase, ToolBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass YahooFinanceParam(ToolParamBase):diff --git a/api/utils/api_utils.py b/api/utils/api_utils.pyindex 3e4acc37c0..5847858ac5 100644--- a/api/utils/api_utils.py+++ b/api/utils/api_utils.py@@ -13,17 +13,14 @@# See the License for the specific language governing permissions and# limitations under the License.#-import asyncio+import functoolsimport jsonimport loggingimport os-import queue-import threadingimport timefrom copy import deepcopyfrom functools import wraps-from typing import Any, Callable, Coroutine, Optional, Type, Unionimport requestsimport trio@@ -43,6 +40,7 @@ from api.db import ActiveEnumfrom api.db.db_models import APITokenfrom api.utils.json_encode import CustomJSONEncoderfrom rag.utils.mcp_tool_call_conn import MCPToolCallSession, close_multiple_mcp_toolcall_sessions+from common.connection_utils import timeoutrequests.models.complexjson.dumps = functools.partial(json.dumps, cls=CustomJSONEncoder)@@ -604,82 +602,6 @@ def get_mcp_tools(mcp_servers: list, timeout: float | int = 10) -> tuple[dict, sreturn {}, str(e)-TimeoutException = Union[Type[BaseException], BaseException]-OnTimeoutCallback = Union[Callable[..., Any], Coroutine[Any, Any, Any]]---def timeout(seconds: float | int | str = None, attempts: int = 2, *, exception: Optional[TimeoutException] = None, on_timeout: Optional[OnTimeoutCallback] = None):- if isinstance(seconds, str):- seconds = float(seconds)- def decorator(func):- @wraps(func)- def wrapper(*args, **kwargs):- result_queue = queue.Queue(maxsize=1)-- def target():- try:- result = func(*args, **kwargs)- result_queue.put(result)- except Exception as e:- result_queue.put(e)-- thread = threading.Thread(target=target)- thread.daemon = True- thread.start()-- for a in range(attempts):- try:- if os.environ.get("ENABLE_TIMEOUT_ASSERTION"):- result = result_queue.get(timeout=seconds)- else:- result = result_queue.get()- if isinstance(result, Exception):- raise result- return result- except queue.Empty:- pass- raise TimeoutError(f"Function '{func.__name__}' timed out after {seconds} seconds and {attempts} attempts.")-- @wraps(func)- async def async_wrapper(*args, **kwargs) -> Any:- if seconds is None:- return await func(*args, **kwargs)-- for a in range(attempts):- try:- if os.environ.get("ENABLE_TIMEOUT_ASSERTION"):- with trio.fail_after(seconds):- return await func(*args, **kwargs)- else:- return await func(*args, **kwargs)- except trio.TooSlowError:- if a < attempts - 1:- continue- if on_timeout is not None:- if callable(on_timeout):- result = on_timeout()- if isinstance(result, Coroutine):- return await result- return result- return on_timeout-- if exception is None:- raise TimeoutError(f"Operation timed out after {seconds} seconds and {attempts} attempts.")-- if isinstance(exception, BaseException):- raise exception-- if isinstance(exception, type) and issubclass(exception, BaseException):- raise exception(f"Operation timed out after {seconds} seconds and {attempts} attempts.")-- raise RuntimeError("Invalid exception type provided")-- if asyncio.iscoroutinefunction(func):- return async_wrapper- return wrapper-- return decorator-async def is_strong_enough(chat_model, embedding_model):count = settings.STRONG_TEST_COUNTdiff --git a/common/connection_utils.py b/common/connection_utils.pynew file mode 100644index 0000000000..bebef0f4c9--- /dev/null+++ b/common/connection_utils.py@@ -0,0 +1,101 @@+#+# Copyright 2025 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 os+import queue+import threading+from typing import Any, Callable, Coroutine, Optional, Type, Union+import asyncio+import trio+from functools import wraps++TimeoutException = Union[Type[BaseException], BaseException]+OnTimeoutCallback = Union[Callable[..., Any], Coroutine[Any, Any, Any]]+++def timeout(seconds: float | int | str = None, attempts: int = 2, *, exception: Optional[TimeoutException] = None,+ on_timeout: Optional[OnTimeoutCallback] = None):+ if isinstance(seconds, str):+ seconds = float(seconds)++ def decorator(func):+ @wraps(func)+ def wrapper(*args, **kwargs):+ result_queue = queue.Queue(maxsize=1)++ def target():+ try:+ result = func(*args, **kwargs)+ result_queue.put(result)+ except Exception as e:+ result_queue.put(e)++ thread = threading.Thread(target=target)+ thread.daemon = True+ thread.start()++ for a in range(attempts):+ try:+ if os.environ.get("ENABLE_TIMEOUT_ASSERTION"):+ result = result_queue.get(timeout=seconds)+ else:+ result = result_queue.get()+ if isinstance(result, Exception):+ raise result+ return result+ except queue.Empty:+ pass+ raise TimeoutError(f"Function '{func.__name__}' timed out after {seconds} seconds and {attempts} attempts.")++ @wraps(func)+ async def async_wrapper(*args, **kwargs) -> Any:+ if seconds is None:+ return await func(*args, **kwargs)++ for a in range(attempts):+ try:+ if os.environ.get("ENABLE_TIMEOUT_ASSERTION"):+ with trio.fail_after(seconds):+ return await func(*args, **kwargs)+ else:+ return await func(*args, **kwargs)+ except trio.TooSlowError:+ if a < attempts - 1:+ continue+ if on_timeout is not None:+ if callable(on_timeout):+ result = on_timeout()+ if isinstance(result, Coroutine):+ return await result+ return result+ return on_timeout++ if exception is None:+ raise TimeoutError(f"Operation timed out after {seconds} seconds and {attempts} attempts.")++ if isinstance(exception, BaseException):+ raise exception++ if isinstance(exception, type) and issubclass(exception, BaseException):+ raise exception(f"Operation timed out after {seconds} seconds and {attempts} attempts.")++ raise RuntimeError("Invalid exception type provided")++ if asyncio.iscoroutinefunction(func):+ return async_wrapper+ return wrapper++ return decoratordiff --git a/deepdoc/parser/figure_parser.py b/deepdoc/parser/figure_parser.pyindex 98c1d3349d..b71ece1211 100644--- a/deepdoc/parser/figure_parser.py+++ b/deepdoc/parser/figure_parser.py@@ -19,7 +19,7 @@ from PIL import Imagefrom api.db import LLMTypefrom api.db.services.llm_service import LLMBundle-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.app.picture import vision_llm_chunk as picture_vision_llm_chunkfrom rag.prompts.generator import vision_llm_figure_describe_promptdiff --git a/graphrag/general/community_reports_extractor.py b/graphrag/general/community_reports_extractor.pyindex fe611dedfa..6c49c0a73e 100644--- a/graphrag/general/community_reports_extractor.py+++ b/graphrag/general/community_reports_extractor.py@@ -14,7 +14,7 @@ from dataclasses import dataclassimport networkx as nximport pandas as pd-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom graphrag.general import leidenfrom graphrag.general.community_report_prompt import COMMUNITY_REPORT_PROMPTfrom graphrag.general.extractor import Extractordiff --git a/graphrag/general/extractor.py b/graphrag/general/extractor.pyindex a41ffd6a22..9b18d694f4 100644--- a/graphrag/general/extractor.py+++ b/graphrag/general/extractor.py@@ -23,7 +23,7 @@ from typing import Callableimport networkx as nximport trio-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom graphrag.general.graph_prompt import SUMMARIZE_DESCRIPTIONS_PROMPTfrom graphrag.utils import (GraphChange,diff --git a/graphrag/general/index.py b/graphrag/general/index.pyindex 52b298e328..51f79f57f6 100644--- a/graphrag/general/index.py+++ b/graphrag/general/index.py@@ -23,7 +23,7 @@ import triofrom api import settingsfrom api.db.services.document_service import DocumentServicefrom common.misc_utils import get_uuid-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom graphrag.entity_resolution import EntityResolutionfrom graphrag.general.community_reports_extractor import CommunityReportsExtractorfrom graphrag.general.extractor import Extractordiff --git a/graphrag/utils.py b/graphrag/utils.pyindex 8250dea8cd..b64a12265c 100644--- a/graphrag/utils.py+++ b/graphrag/utils.py@@ -25,7 +25,7 @@ from networkx.readwrite import json_graphfrom api import settingsfrom common.misc_utils import get_uuid-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.nlp import rag_tokenizer, searchfrom rag.utils.doc_store_conn import OrderByExprfrom rag.utils.redis_conn import REDIS_CONNdiff --git a/rag/flow/base.py b/rag/flow/base.pyindex 5edc280f82..4b256e78fe 100644--- a/rag/flow/base.py+++ b/rag/flow/base.py@@ -20,7 +20,7 @@ from functools import partialfrom typing import Anyimport triofrom agent.component.base import ComponentBase, ComponentParamBase-from api.utils.api_utils import timeout+from common.connection_utils import timeoutclass ProcessParamBase(ComponentParamBase):diff --git a/rag/flow/tokenizer/tokenizer.py b/rag/flow/tokenizer/tokenizer.pyindex 686a0bb7ed..ee4b277fcc 100644--- a/rag/flow/tokenizer/tokenizer.py+++ b/rag/flow/tokenizer/tokenizer.py@@ -23,7 +23,7 @@ from api.db import LLMTypefrom api.db.services.knowledgebase_service import KnowledgebaseServicefrom api.db.services.llm_service import LLMBundlefrom api.db.services.user_service import TenantService-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom rag.flow.base import ProcessBase, ProcessParamBasefrom rag.flow.tokenizer.schema import TokenizerFromUpstreamfrom rag.nlp import rag_tokenizerdiff --git a/rag/raptor.py b/rag/raptor.pyindex a3d369189f..22f8ce397b 100644--- a/rag/raptor.py+++ b/rag/raptor.py@@ -20,7 +20,7 @@ import numpy as npfrom sklearn.mixture import GaussianMixtureimport trio-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom graphrag.utils import (get_llm_cache,get_embed_cache,diff --git a/rag/svr/task_executor.py b/rag/svr/task_executor.pyindex f425234929..5bc267ecdd 100644--- a/rag/svr/task_executor.py+++ b/rag/svr/task_executor.py@@ -26,7 +26,7 @@ import json_repairfrom api.db.services.canvas_service import UserCanvasServicefrom api.db.services.knowledgebase_service import KnowledgebaseServicefrom api.db.services.pipeline_operation_log_service import PipelineOperationLogService-from api.utils.api_utils import timeout+from common.connection_utils import timeoutfrom common.base64_image import image2idfrom common.log_utils import init_root_loggerfrom common.file_utils import get_project_base_directory