repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sandbox/executor_manager/core/logger.py
sandbox/executor_manager/core/logger.py
# # 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 logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("sandbox")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sandbox/executor_manager/core/container.py
sandbox/executor_manager/core/container.py
# # 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 asyncio import contextlib import os from queue import Empty, Queue from models.enums import SupportLanguage from util import env_setting_enabled, is_valid_memory_limit from utils.common import async_run_command from core.logger import logger _CONTAINER_QUEUES: dict[SupportLanguage, Queue] = {} _CONTAINER_LOCK: asyncio.Lock = asyncio.Lock() _CONTAINER_EXECUTION_SEMAPHORES: dict[SupportLanguage, asyncio.Semaphore] = {} async def init_containers(size: int) -> tuple[int, int]: global _CONTAINER_QUEUES _CONTAINER_QUEUES = {SupportLanguage.PYTHON: Queue(), SupportLanguage.NODEJS: Queue()} async with _CONTAINER_LOCK: while not _CONTAINER_QUEUES[SupportLanguage.PYTHON].empty(): _CONTAINER_QUEUES[SupportLanguage.PYTHON].get_nowait() while not _CONTAINER_QUEUES[SupportLanguage.NODEJS].empty(): _CONTAINER_QUEUES[SupportLanguage.NODEJS].get_nowait() for language in SupportLanguage: _CONTAINER_EXECUTION_SEMAPHORES[language] = asyncio.Semaphore(size) create_tasks = [] for i in range(size): name = f"sandbox_python_{i}" logger.info(f"๐Ÿ› ๏ธ Creating Python container {i + 1}/{size}") create_tasks.append(_prepare_container(name, SupportLanguage.PYTHON)) name = f"sandbox_nodejs_{i}" logger.info(f"๐Ÿ› ๏ธ Creating Node.js container {i + 1}/{size}") create_tasks.append(_prepare_container(name, SupportLanguage.NODEJS)) results = await asyncio.gather(*create_tasks, return_exceptions=True) success_count = sum(1 for r in results if r is True) total_task_count = len(create_tasks) return success_count, total_task_count async def teardown_containers(): async with _CONTAINER_LOCK: while not _CONTAINER_QUEUES[SupportLanguage.PYTHON].empty(): name = _CONTAINER_QUEUES[SupportLanguage.PYTHON].get_nowait() await async_run_command("docker", "rm", "-f", name, timeout=5) while not _CONTAINER_QUEUES[SupportLanguage.NODEJS].empty(): name = _CONTAINER_QUEUES[SupportLanguage.NODEJS].get_nowait() await async_run_command("docker", "rm", "-f", name, timeout=5) async def _prepare_container(name: str, language: SupportLanguage) -> bool: """Prepare a single container""" with contextlib.suppress(Exception): await async_run_command("docker", "rm", "-f", name, timeout=5) if await create_container(name, language): _CONTAINER_QUEUES[language].put(name) return True return False async def create_container(name: str, language: SupportLanguage) -> bool: """Asynchronously create a container""" create_args = [ "docker", "run", "-d", "--runtime=runsc", "--name", name, "--read-only", "--tmpfs", "/workspace:rw,exec,size=100M,uid=65534,gid=65534", "--tmpfs", "/tmp:rw,exec,size=50M", "--user", "nobody", "--workdir", "/workspace", ] if os.getenv("SANDBOX_MAX_MEMORY"): memory_limit = os.getenv("SANDBOX_MAX_MEMORY") or "256m" if is_valid_memory_limit(memory_limit): logger.info(f"SANDBOX_MAX_MEMORY: {os.getenv('SANDBOX_MAX_MEMORY')}") else: logger.info("Invalid SANDBOX_MAX_MEMORY, using default value: 256m") memory_limit = "256m" create_args.extend(["--memory", memory_limit]) else: logger.info("Set default SANDBOX_MAX_MEMORY: 256m") create_args.extend(["--memory", "256m"]) if env_setting_enabled("SANDBOX_ENABLE_SECCOMP", "false"): logger.info(f"SANDBOX_ENABLE_SECCOMP: {os.getenv('SANDBOX_ENABLE_SECCOMP')}") create_args.extend(["--security-opt", "seccomp=/app/seccomp-profile-default.json"]) if language == SupportLanguage.PYTHON: create_args.append(os.getenv("SANDBOX_BASE_PYTHON_IMAGE", "sandbox-base-python:latest")) elif language == SupportLanguage.NODEJS: create_args.append(os.getenv("SANDBOX_BASE_NODEJS_IMAGE", "sandbox-base-nodejs:latest")) logger.info(f"Sandbox config:\n\t {create_args}") try: return_code, _, stderr = await async_run_command(*create_args, timeout=10) if return_code != 0: logger.error(f"โŒ Container creation failed {name}: {stderr}") return False if language == SupportLanguage.NODEJS: copy_cmd = ["docker", "exec", name, "bash", "-c", "cp -a /app/node_modules /workspace/"] return_code, _, stderr = await async_run_command(*copy_cmd, timeout=10) if return_code != 0: logger.error(f"โŒ Failed to prepare dependencies for {name}: {stderr}") return False return await container_is_running(name) except Exception as e: logger.error(f"โŒ Container creation exception {name}: {str(e)}") return False async def recreate_container(name: str, language: SupportLanguage) -> bool: """Asynchronously recreate a container""" logger.info(f"๐Ÿ› ๏ธ Recreating container: {name}") try: await async_run_command("docker", "rm", "-f", name, timeout=5) return await create_container(name, language) except Exception as e: logger.error(f"โŒ Container {name} recreation failed: {str(e)}") return False async def release_container(name: str, language: SupportLanguage): """Asynchronously release a container""" async with _CONTAINER_LOCK: if await container_is_running(name): _CONTAINER_QUEUES[language].put(name) logger.info(f"๐ŸŸข Released container: {name} (remaining available: {_CONTAINER_QUEUES[language].qsize()})") else: logger.warning(f"โš ๏ธ Container {name} has crashed, attempting to recreate...") if await recreate_container(name, language): _CONTAINER_QUEUES[language].put(name) logger.info(f"โœ… Container {name} successfully recreated and returned to queue") async def allocate_container_blocking(language: SupportLanguage, timeout=10) -> str: """Asynchronously allocate an available container""" start_time = asyncio.get_running_loop().time() while asyncio.get_running_loop().time() - start_time < timeout: try: name = _CONTAINER_QUEUES[language].get_nowait() async with _CONTAINER_LOCK: if not await container_is_running(name) and not await recreate_container(name, language): continue return name except Empty: await asyncio.sleep(0.1) return "" async def container_is_running(name: str) -> bool: """Asynchronously check the container status""" try: return_code, stdout, _ = await async_run_command("docker", "inspect", "-f", "{{.State.Running}}", name, timeout=2) return return_code == 0 and stdout.strip() == "true" except Exception: return False
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sandbox/executor_manager/core/config.py
sandbox/executor_manager/core/config.py
# # 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 from contextlib import asynccontextmanager from fastapi import FastAPI from util import format_timeout_duration, parse_timeout_duration from core.container import init_containers, teardown_containers from core.logger import logger TIMEOUT = parse_timeout_duration(os.getenv("SANDBOX_TIMEOUT", "10s")) @asynccontextmanager async def _lifespan(app: FastAPI): """Asynchronous lifecycle management""" size = int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", 1)) success_count, total_task_count = await init_containers(size) logger.info(f"\n๐Ÿ“Š Container pool initialization complete: {success_count}/{total_task_count} available") yield await teardown_containers() def init(): logger.info(f"Global timeout: {format_timeout_duration(TIMEOUT)}") return _lifespan
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sandbox/executor_manager/core/__init__.py
sandbox/executor_manager/core/__init__.py
# # 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. #
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/settings.py
agent/settings.py
# # 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. # FLOAT_ZERO = 1e-8 PARAM_MAXDEPTH = 5
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/__init__.py
agent/__init__.py
# # 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. #
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/canvas.py
agent/canvas.py
# # Copyright 2024 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 asyncio import base64 import inspect import binascii import json import logging import re import time from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from functools import partial from typing import Any, Union, Tuple from agent.component import component_class from agent.component.base import ComponentBase from api.db.services.file_service import FileService from api.db.services.llm_service import LLMBundle from api.db.services.task_service import has_canceled from common.constants import LLMType from common.misc_utils import get_uuid, hash_str2int from common.exceptions import TaskCanceledException from rag.prompts.generator import chunks_format from rag.utils.redis_conn import REDIS_CONN class Graph: """ dsl = { "components": { "begin": { "obj":{ "component_name": "Begin", "params": {}, }, "downstream": ["answer_0"], "upstream": [], }, "retrieval_0": { "obj": { "component_name": "Retrieval", "params": {} }, "downstream": ["generate_0"], "upstream": ["answer_0"], }, "generate_0": { "obj": { "component_name": "Generate", "params": {} }, "downstream": ["answer_0"], "upstream": ["retrieval_0"], } }, "history": [], "path": ["begin"], "retrieval": {"chunks": [], "doc_aggs": []}, "globals": { "sys.query": "", "sys.user_id": tenant_id, "sys.conversation_turns": 0, "sys.files": [] } } """ def __init__(self, dsl: str, tenant_id=None, task_id=None): self.path = [] self.components = {} self.error = "" self.dsl = json.loads(dsl) self._tenant_id = tenant_id self.task_id = task_id if task_id else get_uuid() self._thread_pool = ThreadPoolExecutor(max_workers=5) self.load() def load(self): self.components = self.dsl["components"] cpn_nms = set([]) for k, cpn in self.components.items(): cpn_nms.add(cpn["obj"]["component_name"]) param = component_class(cpn["obj"]["component_name"] + "Param")() param.update(cpn["obj"]["params"]) try: param.check() except Exception as e: raise ValueError(self.get_component_name(k) + f": {e}") cpn["obj"] = component_class(cpn["obj"]["component_name"])(self, k, param) self.path = self.dsl["path"] def __str__(self): self.dsl["path"] = self.path self.dsl["task_id"] = self.task_id dsl = { "components": {} } for k in self.dsl.keys(): if k in ["components"]: continue dsl[k] = deepcopy(self.dsl[k]) for k, cpn in self.components.items(): if k not in dsl["components"]: dsl["components"][k] = {} for c in cpn.keys(): if c == "obj": dsl["components"][k][c] = json.loads(str(cpn["obj"])) continue dsl["components"][k][c] = deepcopy(cpn[c]) return json.dumps(dsl, ensure_ascii=False) def reset(self): self.path = [] for k, cpn in self.components.items(): self.components[k]["obj"].reset() try: REDIS_CONN.delete(f"{self.task_id}-logs") REDIS_CONN.delete(f"{self.task_id}-cancel") except Exception as e: logging.exception(e) def get_component_name(self, cid): for n in self.dsl.get("graph", {}).get("nodes", []): if cid == n["id"]: return n["data"]["name"] return "" def run(self, **kwargs): raise NotImplementedError() def get_component(self, cpn_id) -> Union[None, dict[str, Any]]: return self.components.get(cpn_id) def get_component_obj(self, cpn_id) -> ComponentBase: return self.components.get(cpn_id)["obj"] def get_component_type(self, cpn_id) -> str: return self.components.get(cpn_id)["obj"].component_name def get_component_input_form(self, cpn_id) -> dict: return self.components.get(cpn_id)["obj"].get_input_form() def get_tenant_id(self): return self._tenant_id def get_value_with_variable(self,value: str) -> Any: pat = re.compile(r"\{* *\{([a-zA-Z:0-9]+@[A-Za-z0-9_.-]+|sys\.[A-Za-z0-9_.]+|env\.[A-Za-z0-9_.]+)\} *\}*") out_parts = [] last = 0 for m in pat.finditer(value): out_parts.append(value[last:m.start()]) key = m.group(1) v = self.get_variable_value(key) if v is None: rep = "" elif isinstance(v, partial): buf = [] for chunk in v(): buf.append(chunk) rep = "".join(buf) elif isinstance(v, str): rep = v else: rep = json.dumps(v, ensure_ascii=False) out_parts.append(rep) last = m.end() out_parts.append(value[last:]) return("".join(out_parts)) def get_variable_value(self, exp: str) -> Any: exp = exp.strip("{").strip("}").strip(" ").strip("{").strip("}") if exp.find("@") < 0: return self.globals[exp] cpn_id, var_nm = exp.split("@") cpn = self.get_component(cpn_id) if not cpn: raise Exception(f"Can't find variable: '{cpn_id}@{var_nm}'") parts = var_nm.split(".", 1) root_key = parts[0] rest = parts[1] if len(parts) > 1 else "" root_val = cpn["obj"].output(root_key) if not rest: return root_val return self.get_variable_param_value(root_val,rest) def get_variable_param_value(self, obj: Any, path: str) -> Any: cur = obj if not path: return cur for key in path.split('.'): if cur is None: return None if isinstance(cur, str): try: cur = json.loads(cur) except Exception: return None if isinstance(cur, dict): cur = cur.get(key) continue if isinstance(cur, (list, tuple)): try: idx = int(key) cur = cur[idx] except Exception: return None continue cur = getattr(cur, key, None) return cur def set_variable_value(self, exp: str,value): exp = exp.strip("{").strip("}").strip(" ").strip("{").strip("}") if exp.find("@") < 0: self.globals[exp] = value return cpn_id, var_nm = exp.split("@") cpn = self.get_component(cpn_id) if not cpn: raise Exception(f"Can't find variable: '{cpn_id}@{var_nm}'") parts = var_nm.split(".", 1) root_key = parts[0] rest = parts[1] if len(parts) > 1 else "" if not rest: cpn["obj"].set_output(root_key, value) return root_val = cpn["obj"].output(root_key) if not root_val: root_val = {} cpn["obj"].set_output(root_key, self.set_variable_param_value(root_val,rest,value)) def set_variable_param_value(self, obj: Any, path: str, value) -> Any: cur = obj keys = path.split('.') if not path: return value for key in keys: if key not in cur or not isinstance(cur[key], dict): cur[key] = {} cur = cur[key] cur[keys[-1]] = value return obj def is_canceled(self) -> bool: return has_canceled(self.task_id) def cancel_task(self) -> bool: try: REDIS_CONN.set(f"{self.task_id}-cancel", "x") except Exception as e: logging.exception(e) return False return True class Canvas(Graph): def __init__(self, dsl: str, tenant_id=None, task_id=None, canvas_id=None): self.globals = { "sys.query": "", "sys.user_id": tenant_id, "sys.conversation_turns": 0, "sys.files": [] } self.variables = {} super().__init__(dsl, tenant_id, task_id) self._id = canvas_id def load(self): super().load() self.history = self.dsl["history"] if "globals" in self.dsl: self.globals = self.dsl["globals"] else: self.globals = { "sys.query": "", "sys.user_id": "", "sys.conversation_turns": 0, "sys.files": [] } if "variables" in self.dsl: self.variables = self.dsl["variables"] else: self.variables = {} self.retrieval = self.dsl["retrieval"] self.memory = self.dsl.get("memory", []) def __str__(self): self.dsl["history"] = self.history self.dsl["retrieval"] = self.retrieval self.dsl["memory"] = self.memory return super().__str__() def reset(self, mem=False): super().reset() if not mem: self.history = [] self.retrieval = [] self.memory = [] print(self.variables) for k in self.globals.keys(): if k.startswith("sys."): if isinstance(self.globals[k], str): self.globals[k] = "" elif isinstance(self.globals[k], int): self.globals[k] = 0 elif isinstance(self.globals[k], float): self.globals[k] = 0 elif isinstance(self.globals[k], list): self.globals[k] = [] elif isinstance(self.globals[k], dict): self.globals[k] = {} else: self.globals[k] = None if k.startswith("env."): key = k[4:] if key in self.variables: variable = self.variables[key] if variable["value"]: self.globals[k] = variable["value"] else: if variable["type"] == "string": self.globals[k] = "" elif variable["type"] == "number": self.globals[k] = 0 elif variable["type"] == "boolean": self.globals[k] = False elif variable["type"] == "object": self.globals[k] = {} elif variable["type"].startswith("array"): self.globals[k] = [] else: self.globals[k] = "" else: self.globals[k] = "" async def run(self, **kwargs): st = time.perf_counter() self._loop = asyncio.get_running_loop() self.message_id = get_uuid() created_at = int(time.time()) self.add_user_input(kwargs.get("query")) for k, cpn in self.components.items(): self.components[k]["obj"].reset(True) if kwargs.get("webhook_payload"): for k, cpn in self.components.items(): if self.components[k]["obj"].component_name.lower() == "begin" and self.components[k]["obj"]._param.mode == "Webhook": payload = kwargs.get("webhook_payload", {}) if "input" in payload: self.components[k]["obj"].set_input_value("request", payload["input"]) for kk, vv in payload.items(): if kk == "input": continue self.components[k]["obj"].set_output(kk, vv) for k in kwargs.keys(): if k in ["query", "user_id", "files"] and kwargs[k]: if k == "files": self.globals[f"sys.{k}"] = await self.get_files_async(kwargs[k]) else: self.globals[f"sys.{k}"] = kwargs[k] if not self.globals["sys.conversation_turns"] : self.globals["sys.conversation_turns"] = 0 self.globals["sys.conversation_turns"] += 1 def decorate(event, dt): nonlocal created_at return { "event": event, #"conversation_id": "f3cc152b-24b0-4258-a1a1-7d5e9fc8a115", "message_id": self.message_id, "created_at": created_at, "task_id": self.task_id, "data": dt } if not self.path or self.path[-1].lower().find("userfillup") < 0: self.path.append("begin") self.retrieval.append({"chunks": [], "doc_aggs": []}) if self.is_canceled(): msg = f"Task {self.task_id} has been canceled before starting." logging.info(msg) raise TaskCanceledException(msg) yield decorate("workflow_started", {"inputs": kwargs.get("inputs")}) self.retrieval.append({"chunks": {}, "doc_aggs": {}}) async def _run_batch(f, t): if self.is_canceled(): msg = f"Task {self.task_id} has been canceled during batch execution." logging.info(msg) raise TaskCanceledException(msg) loop = asyncio.get_running_loop() tasks = [] def _run_async_in_thread(coro_func, **call_kwargs): return asyncio.run(coro_func(**call_kwargs)) i = f while i < t: cpn = self.get_component_obj(self.path[i]) task_fn = None call_kwargs = None if cpn.component_name.lower() in ["begin", "userfillup"]: call_kwargs = {"inputs": kwargs.get("inputs", {})} task_fn = cpn.invoke i += 1 else: for _, ele in cpn.get_input_elements().items(): if isinstance(ele, dict) and ele.get("_cpn_id") and ele.get("_cpn_id") not in self.path[:i] and self.path[0].lower().find("userfillup") < 0: self.path.pop(i) t -= 1 break else: call_kwargs = cpn.get_input() task_fn = cpn.invoke i += 1 if task_fn is None: continue invoke_async = getattr(cpn, "invoke_async", None) if invoke_async and asyncio.iscoroutinefunction(invoke_async): tasks.append(loop.run_in_executor(self._thread_pool, partial(_run_async_in_thread, invoke_async, **(call_kwargs or {})))) else: tasks.append(loop.run_in_executor(self._thread_pool, partial(task_fn, **(call_kwargs or {})))) if tasks: await asyncio.gather(*tasks) def _node_finished(cpn_obj): return decorate("node_finished",{ "inputs": cpn_obj.get_input_values(), "outputs": cpn_obj.output(), "component_id": cpn_obj._id, "component_name": self.get_component_name(cpn_obj._id), "component_type": self.get_component_type(cpn_obj._id), "error": cpn_obj.error(), "elapsed_time": time.perf_counter() - cpn_obj.output("_created_time"), "created_at": cpn_obj.output("_created_time"), }) self.error = "" idx = len(self.path) - 1 partials = [] tts_mdl = None while idx < len(self.path): to = len(self.path) for i in range(idx, to): yield decorate("node_started", { "inputs": None, "created_at": int(time.time()), "component_id": self.path[i], "component_name": self.get_component_name(self.path[i]), "component_type": self.get_component_type(self.path[i]), "thoughts": self.get_component_thoughts(self.path[i]) }) await _run_batch(idx, to) to = len(self.path) # post-processing of components invocation for i in range(idx, to): cpn = self.get_component(self.path[i]) cpn_obj = self.get_component_obj(self.path[i]) if cpn_obj.component_name.lower() == "message": if cpn_obj.get_param("auto_play"): tts_mdl = LLMBundle(self._tenant_id, LLMType.TTS) if isinstance(cpn_obj.output("content"), partial): _m = "" buff_m = "" stream = cpn_obj.output("content")() async def _process_stream(m): nonlocal buff_m, _m, tts_mdl if not m: return if m == "<think>": return decorate("message", {"content": "", "start_to_think": True}) elif m == "</think>": return decorate("message", {"content": "", "end_to_think": True}) buff_m += m _m += m if len(buff_m) > 16: ev = decorate( "message", { "content": m, "audio_binary": self.tts(tts_mdl, buff_m) } ) buff_m = "" return ev return decorate("message", {"content": m}) if inspect.isasyncgen(stream): async for m in stream: ev= await _process_stream(m) if ev: yield ev else: for m in stream: ev= await _process_stream(m) if ev: yield ev if buff_m: yield decorate("message", {"content": "", "audio_binary": self.tts(tts_mdl, buff_m)}) buff_m = "" cpn_obj.set_output("content", _m) cite = re.search(r"\[ID:[ 0-9]+\]", _m) else: yield decorate("message", {"content": cpn_obj.output("content")}) cite = re.search(r"\[ID:[ 0-9]+\]", cpn_obj.output("content")) message_end = {} if cpn_obj.get_param("status"): message_end["status"] = cpn_obj.get_param("status") if isinstance(cpn_obj.output("attachment"), dict): message_end["attachment"] = cpn_obj.output("attachment") if cite: message_end["reference"] = self.get_reference() yield decorate("message_end", message_end) while partials: _cpn_obj = self.get_component_obj(partials[0]) if isinstance(_cpn_obj.output("content"), partial): break yield _node_finished(_cpn_obj) partials.pop(0) other_branch = False if cpn_obj.error(): ex = cpn_obj.exception_handler() if ex and ex["goto"]: self.path.extend(ex["goto"]) other_branch = True elif ex and ex["default_value"]: yield decorate("message", {"content": ex["default_value"]}) yield decorate("message_end", {}) else: self.error = cpn_obj.error() if cpn_obj.component_name.lower() not in ("iteration","loop"): if isinstance(cpn_obj.output("content"), partial): if self.error: cpn_obj.set_output("content", None) yield _node_finished(cpn_obj) else: partials.append(self.path[i]) else: yield _node_finished(cpn_obj) def _append_path(cpn_id): nonlocal other_branch if other_branch: return if self.path[-1] == cpn_id: return self.path.append(cpn_id) def _extend_path(cpn_ids): nonlocal other_branch if other_branch: return for cpn_id in cpn_ids: _append_path(cpn_id) if cpn_obj.component_name.lower() in ("iterationitem","loopitem") and cpn_obj.end(): iter = cpn_obj.get_parent() yield _node_finished(iter) _extend_path(self.get_component(cpn["parent_id"])["downstream"]) elif cpn_obj.component_name.lower() in ["categorize", "switch"]: _extend_path(cpn_obj.output("_next")) elif cpn_obj.component_name.lower() in ("iteration", "loop"): _append_path(cpn_obj.get_start()) elif cpn_obj.component_name.lower() == "exitloop" and cpn_obj.get_parent().component_name.lower() == "loop": _extend_path(self.get_component(cpn["parent_id"])["downstream"]) elif not cpn["downstream"] and cpn_obj.get_parent(): _append_path(cpn_obj.get_parent().get_start()) else: _extend_path(cpn["downstream"]) if self.error: logging.error(f"Runtime Error: {self.error}") break idx = to if any([self.get_component_obj(c).component_name.lower() == "userfillup" for c in self.path[idx:]]): path = [c for c in self.path[idx:] if self.get_component(c)["obj"].component_name.lower() == "userfillup"] path.extend([c for c in self.path[idx:] if self.get_component(c)["obj"].component_name.lower() != "userfillup"]) another_inputs = {} tips = "" for c in path: o = self.get_component_obj(c) if o.component_name.lower() == "userfillup": o.invoke() another_inputs.update(o.get_input_elements()) if o.get_param("enable_tips"): tips = o.output("tips") self.path = path yield decorate("user_inputs", {"inputs": another_inputs, "tips": tips}) return self.path = self.path[:idx] if not self.error: yield decorate("workflow_finished", { "inputs": kwargs.get("inputs"), "outputs": self.get_component_obj(self.path[-1]).output(), "elapsed_time": time.perf_counter() - st, "created_at": st, }) self.history.append(("assistant", self.get_component_obj(self.path[-1]).output())) elif "Task has been canceled" in self.error: yield decorate("workflow_finished", { "inputs": kwargs.get("inputs"), "outputs": "Task has been canceled", "elapsed_time": time.perf_counter() - st, "created_at": st, }) def is_reff(self, exp: str) -> bool: exp = exp.strip("{").strip("}") if exp.find("@") < 0: return exp in self.globals arr = exp.split("@") if len(arr) != 2: return False if self.get_component(arr[0]) is None: return False return True def tts(self,tts_mdl, text): def clean_tts_text(text: str) -> str: if not text: return "" text = text.encode("utf-8", "ignore").decode("utf-8", "ignore") text = re.sub(r"[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]", "", text) emoji_pattern = re.compile( "[\U0001F600-\U0001F64F" "\U0001F300-\U0001F5FF" "\U0001F680-\U0001F6FF" "\U0001F1E0-\U0001F1FF" "\U00002700-\U000027BF" "\U0001F900-\U0001F9FF" "\U0001FA70-\U0001FAFF" "\U0001FAD0-\U0001FAFF]+", flags=re.UNICODE ) text = emoji_pattern.sub("", text) text = re.sub(r"\s+", " ", text).strip() MAX_LEN = 500 if len(text) > MAX_LEN: text = text[:MAX_LEN] return text if not tts_mdl or not text: return None text = clean_tts_text(text) if not text: return None bin = b"" try: for chunk in tts_mdl.tts(text): bin += chunk except Exception as e: logging.error(f"TTS failed: {e}, text={text!r}") return None return binascii.hexlify(bin).decode("utf-8") def get_history(self, window_size): convs = [] if window_size <= 0: return convs for role, obj in self.history[window_size * -2:]: if isinstance(obj, dict): convs.append({"role": role, "content": obj.get("content", "")}) else: convs.append({"role": role, "content": str(obj)}) return convs def add_user_input(self, question): self.history.append(("user", question)) def get_prologue(self): return self.components["begin"]["obj"]._param.prologue def get_mode(self): return self.components["begin"]["obj"]._param.mode def get_sys_query(self): return self.globals.get("sys.query", "") def set_global_param(self, **kwargs): self.globals.update(kwargs) def get_preset_param(self): return self.components["begin"]["obj"]._param.inputs def get_component_input_elements(self, cpnnm): return self.components[cpnnm]["obj"].get_input_elements() async def get_files_async(self, files: Union[None, list[dict]]) -> list[str]: if not files: return [] def image_to_base64(file): return "data:{};base64,{}".format(file["mime_type"], base64.b64encode(FileService.get_blob(file["created_by"], file["id"])).decode("utf-8")) loop = asyncio.get_running_loop() tasks = [] for file in files: if file["mime_type"].find("image") >=0: tasks.append(loop.run_in_executor(self._thread_pool, image_to_base64, file)) continue tasks.append(loop.run_in_executor(self._thread_pool, FileService.parse, file["name"], FileService.get_blob(file["created_by"], file["id"]), True, file["created_by"])) return await asyncio.gather(*tasks) def get_files(self, files: Union[None, list[dict]]) -> list[str]: """ Synchronous wrapper for get_files_async, used by sync component invoke paths. """ loop = getattr(self, "_loop", None) if loop and loop.is_running(): return asyncio.run_coroutine_threadsafe(self.get_files_async(files), loop).result() return asyncio.run(self.get_files_async(files)) def tool_use_callback(self, agent_id: str, func_name: str, params: dict, result: Any, elapsed_time=None): agent_ids = agent_id.split("-->") agent_name = self.get_component_name(agent_ids[0]) path = agent_name if len(agent_ids) < 2 else agent_name+"-->"+"-->".join(agent_ids[1:]) try: bin = REDIS_CONN.get(f"{self.task_id}-{self.message_id}-logs") if bin: obj = json.loads(bin.encode("utf-8")) if obj[-1]["component_id"] == agent_ids[0]: obj[-1]["trace"].append({"path": path, "tool_name": func_name, "arguments": params, "result": result, "elapsed_time": elapsed_time}) else: obj.append({ "component_id": agent_ids[0], "trace": [{"path": path, "tool_name": func_name, "arguments": params, "result": result, "elapsed_time": elapsed_time}] }) else: obj = [{ "component_id": agent_ids[0], "trace": [{"path": path, "tool_name": func_name, "arguments": params, "result": result, "elapsed_time": elapsed_time}] }] REDIS_CONN.set_obj(f"{self.task_id}-{self.message_id}-logs", obj, 60*10) except Exception as e: logging.exception(e) def add_reference(self, chunks: list[object], doc_infos: list[object]): if not self.retrieval: self.retrieval = [{"chunks": {}, "doc_aggs": {}}] r = self.retrieval[-1] for ck in chunks_format({"chunks": chunks}): cid = hash_str2int(ck["id"], 500) # cid = uuid.uuid5(uuid.NAMESPACE_DNS, ck["id"]) if cid not in r: r["chunks"][cid] = ck for doc in doc_infos: if doc["doc_name"] not in r: r["doc_aggs"][doc["doc_name"]] = doc def get_reference(self): if not self.retrieval: return {"chunks": {}, "doc_aggs": {}} return self.retrieval[-1] def add_memory(self, user:str, assist:str, summ: str): self.memory.append((user, assist, summ)) def get_memory(self) -> list[Tuple]: return self.memory def get_component_thoughts(self, cpn_id) -> str: return self.components.get(cpn_id)["obj"].thoughts()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/wencai.py
agent/tools/wencai.py
# # Copyright 2024 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 pandas as pd import pywencai from agent.tools.base import ToolParamBase, ToolMeta, ToolBase from common.connection_utils import timeout class WenCaiParam(ToolParamBase): """ Define the WenCai component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "iwencai", "description": """ iwencai search: search platform is committed to providing hundreds of millions of investors with the most timely, accurate and comprehensive information, covering news, announcements, research reports, blogs, forums, Weibo, characters, etc. robo-advisor intelligent stock selection platform: through AI technology, is committed to providing investors with intelligent stock selection, quantitative investment, main force tracking, value investment, technical analysis and other types of stock selection technologies. fund selection platform: through AI technology, is committed to providing excellent fund, value investment, quantitative analysis and other fund selection technologies for foundation citizens. """, "parameters": { "query": { "type": "string", "description": "The question/conditions to select stocks.", "default": "{sys.query}", "required": True } } } super().__init__() self.top_n = 10 self.query_type = "stock" def check(self): self.check_positive_integer(self.top_n, "Top N") self.check_valid_value(self.query_type, "Query type", ['stock', 'zhishu', 'fund', 'hkstock', 'usstock', 'threeboard', 'conbond', 'insurance', 'futures', 'lccp', 'foreign_exchange']) def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" } } class WenCai(ToolBase, ABC): component_name = "WenCai" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("WenCai processing"): return if not kwargs.get("query"): self.set_output("report", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("WenCai processing"): return try: wencai_res = [] res = pywencai.get(query=kwargs["query"], query_type=self._param.query_type, perpage=self._param.top_n) if self.check_if_canceled("WenCai processing"): return if isinstance(res, pd.DataFrame): wencai_res.append(res.to_markdown()) elif isinstance(res, dict): for item in res.items(): if self.check_if_canceled("WenCai processing"): return if isinstance(item[1], list): wencai_res.append(item[0] + "\n" + pd.DataFrame(item[1]).to_markdown()) elif isinstance(item[1], str): wencai_res.append(item[0] + "\n" + item[1]) elif isinstance(item[1], dict): if "meta" in item[1].keys(): continue wencai_res.append(pd.DataFrame.from_dict(item[1], orient='index').to_markdown()) elif isinstance(item[1], pd.DataFrame): if "image_url" in item[1].columns: continue wencai_res.append(item[1].to_markdown()) else: wencai_res.append(item[0] + "\n" + str(item[1])) self.set_output("report", "\n\n".join(wencai_res)) return self.output("report") except Exception as e: if self.check_if_canceled("WenCai processing"): return last_e = e logging.exception(f"WenCai error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"WenCai error: {last_e}" assert False, self.output() def thoughts(self) -> str: return "Pulling live financial data for `{}`.".format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/pubmed.py
agent/tools/pubmed.py
# # Copyright 2024 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 from Bio import Entrez import re import xml.etree.ElementTree as ET from agent.tools.base import ToolParamBase, ToolMeta, ToolBase from common.connection_utils import timeout class PubMedParam(ToolParamBase): """ Define the PubMed component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "pubmed_search", "description": """ PubMed is an openly accessible, free database which includes primarily the MEDLINE database of references and abstracts on life sciences and biomedical topics. In addition to MEDLINE, PubMed provides access to: - older references from the print version of Index Medicus, back to 1951 and earlier - references to some journals before they were indexed in Index Medicus and MEDLINE, for instance Science, BMJ, and Annals of Surgery - very recent entries to records for an article before it is indexed with Medical Subject Headings (MeSH) and added to MEDLINE - a collection of books available full-text and other subsets of NLM records[4] - PMC citations - NCBI Bookshelf """, "parameters": { "query": { "type": "string", "description": "The search keywords to execute with PubMed. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True } } } super().__init__() self.top_n = 12 self.email = "A.N.Other@example.com" 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" } } class PubMed(ToolBase, ABC): component_name = "PubMed" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("PubMed processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("PubMed processing"): return try: Entrez.email = self._param.email pubmedids = Entrez.read(Entrez.esearch(db='pubmed', retmax=self._param.top_n, term=kwargs["query"]))['IdList'] if self.check_if_canceled("PubMed processing"): return pubmedcnt = ET.fromstring(re.sub(r'<(/?)b>|<(/?)i>', '', Entrez.efetch(db='pubmed', id=",".join(pubmedids), retmode="xml").read().decode("utf-8"))) if self.check_if_canceled("PubMed processing"): return self._retrieve_chunks(pubmedcnt.findall("PubmedArticle"), get_title=lambda child: child.find("MedlineCitation").find("Article").find("ArticleTitle").text, get_url=lambda child: "https://pubmed.ncbi.nlm.nih.gov/" + child.find("MedlineCitation").find("PMID").text, get_content=lambda child: self._format_pubmed_content(child),) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("PubMed processing"): return last_e = e logging.exception(f"PubMed error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"PubMed error: {last_e}" assert False, self.output() def _format_pubmed_content(self, child): """Extract structured reference info from PubMed XML""" def safe_find(path): node = child for p in path.split("/"): if node is None: return None node = node.find(p) return node.text if node is not None and node.text else None title = safe_find("MedlineCitation/Article/ArticleTitle") or "No title" abstract = safe_find("MedlineCitation/Article/Abstract/AbstractText") or "No abstract available" journal = safe_find("MedlineCitation/Article/Journal/Title") or "Unknown Journal" volume = safe_find("MedlineCitation/Article/Journal/JournalIssue/Volume") or "-" issue = safe_find("MedlineCitation/Article/Journal/JournalIssue/Issue") or "-" pages = safe_find("MedlineCitation/Article/Pagination/MedlinePgn") or "-" # Authors authors = [] for author in child.findall(".//AuthorList/Author"): lastname = safe_find("LastName") or "" forename = safe_find("ForeName") or "" fullname = f"{forename} {lastname}".strip() if fullname: authors.append(fullname) authors_str = ", ".join(authors) if authors else "Unknown Authors" # DOI doi = None for eid in child.findall(".//ArticleId"): if eid.attrib.get("IdType") == "doi": doi = eid.text break return ( f"Title: {title}\n" f"Authors: {authors_str}\n" f"Journal: {journal}\n" f"Volume: {volume}\n" f"Issue: {issue}\n" f"Pages: {pages}\n" f"DOI: {doi or '-'}\n" f"Abstract: {abstract.strip()}" ) def thoughts(self) -> str: return "Looking for scholarly papers on `{}`,โ€ prioritising reputable sources.".format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/wikipedia.py
agent/tools/wikipedia.py
# # Copyright 2024 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 wikipedia from agent.tools.base import ToolMeta, ToolParamBase, ToolBase from common.connection_utils import timeout class WikipediaParam(ToolParamBase): """ Define the Wikipedia component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "wikipedia_search", "description": """A wide range of how-to and information pages are made available in wikipedia. Since 2001, it has grown rapidly to become the world's largest reference website. From Wikipedia, the free encyclopedia.""", "parameters": { "query": { "type": "string", "description": "The search keyword to execute with wikipedia. The keyword MUST be a specific subject that can match the title.", "default": "{sys.query}", "required": True } } } super().__init__() self.top_n = 10 self.language = "en" def check(self): self.check_positive_integer(self.top_n, "Top N") self.check_valid_value(self.language, "Wikipedia languages", ['af', 'pl', 'ar', 'ast', 'az', 'bg', 'nan', 'bn', 'be', 'ca', 'cs', 'cy', 'da', 'de', 'et', 'el', 'en', 'es', 'eo', 'eu', 'fa', 'fr', 'gl', 'ko', 'hy', 'hi', 'hr', 'id', 'it', 'he', 'ka', 'lld', 'la', 'lv', 'lt', 'hu', 'mk', 'arz', 'ms', 'min', 'my', 'nl', 'ja', 'nb', 'nn', 'ce', 'uz', 'pt', 'kk', 'ro', 'ru', 'ceb', 'sk', 'sl', 'sr', 'sh', 'fi', 'sv', 'ta', 'tt', 'th', 'tg', 'azb', 'tr', 'uk', 'ur', 'vi', 'war', 'zh', 'yue']) def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" } } class Wikipedia(ToolBase, ABC): component_name = "Wikipedia" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 60))) def _invoke(self, **kwargs): if self.check_if_canceled("Wikipedia processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("Wikipedia processing"): return try: wikipedia.set_lang(self._param.language) wiki_engine = wikipedia pages = [] for p in wiki_engine.search(kwargs["query"], results=self._param.top_n): if self.check_if_canceled("Wikipedia processing"): return try: pages.append(wikipedia.page(p)) except Exception: pass self._retrieve_chunks(pages, get_title=lambda r: r.title, get_url=lambda r: r.url, get_content=lambda r: r.summary) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("Wikipedia processing"): return last_e = e logging.exception(f"Wikipedia error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"Wikipedia error: {last_e}" assert False, self.output() def thoughts(self) -> str: return """ Keywords: {} Looking for the most relevant articles. """.format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/tavily.py
agent/tools/tavily.py
# # Copyright 2024 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 from tavily import TavilyClient from agent.tools.base import ToolParamBase, ToolBase, ToolMeta from common.connection_utils import timeout class TavilySearchParam(ToolParamBase): """ Define the Retrieval component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "tavily_search", "description": """ Tavily is a search engine optimized for LLMs, aimed at efficient, quick and persistent search results. When searching: - Start with specific query which should focus on just a single aspect. - Number of keywords in query should be less than 5. - Broaden search terms if needed - Cross-reference information from multiple sources """, "parameters": { "query": { "type": "string", "description": "The search keywords to execute with Tavily. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True }, "topic": { "type": "string", "description": "default:general. The category of the search.news is useful for retrieving real-time updates, particularly about politics, sports, and major current events covered by mainstream media sources. general is for broader, more general-purpose searches that may include a wide range of sources.", "enum": ["general", "news"], "default": "general", "required": False, }, "include_domains": { "type": "array", "description": "default:[]. A list of domains only from which the search results can be included.", "default": [], "items": { "type": "string", "description": "Domain name that must be included, e.g. www.yahoo.com" }, "required": False }, "exclude_domains": { "type": "array", "description": "default:[]. A list of domains from which the search results can not be included", "default": [], "items": { "type": "string", "description": "Domain name that must be excluded, e.g. www.yahoo.com" }, "required": False }, } } super().__init__() self.api_key = "" self.search_depth = "basic" # basic/advanced self.max_results = 6 self.days = 14 self.include_answer = False self.include_raw_content = False self.include_images = False self.include_image_descriptions = False def check(self): self.check_valid_value(self.topic, "Tavily topic: should be in 'general/news'", ["general", "news"]) self.check_valid_value(self.search_depth, "Tavily search depth should be in 'basic/advanced'", ["basic", "advanced"]) self.check_positive_integer(self.max_results, "Tavily max result number should be within [1๏ผŒ 20]") self.check_positive_integer(self.days, "Tavily days should be greater than 1") def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" } } class TavilySearch(ToolBase, ABC): component_name = "TavilySearch" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("TavilySearch processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" self.tavily_client = TavilyClient(api_key=self._param.api_key) last_e = None for fld in ["search_depth", "topic", "max_results", "days", "include_answer", "include_raw_content", "include_images", "include_image_descriptions", "include_domains", "exclude_domains"]: if fld not in kwargs: kwargs[fld] = getattr(self._param, fld) for _ in range(self._param.max_retries+1): if self.check_if_canceled("TavilySearch processing"): return try: kwargs["include_images"] = False kwargs["include_raw_content"] = False res = self.tavily_client.search(**kwargs) if self.check_if_canceled("TavilySearch processing"): return self._retrieve_chunks(res["results"], get_title=lambda r: r["title"], get_url=lambda r: r["url"], get_content=lambda r: r["raw_content"] if r["raw_content"] else r["content"], get_score=lambda r: r["score"]) self.set_output("json", res["results"]) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("TavilySearch processing"): return last_e = e logging.exception(f"Tavily error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"Tavily error: {last_e}" assert False, self.output() def thoughts(self) -> str: return """ Keywords: {} Looking for the most relevant articles. """.format(self.get_input().get("query", "-_-!")) class TavilyExtractParam(ToolParamBase): """ Define the Retrieval component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "tavily_extract", "description": "Extract web page content from one or more specified URLs using Tavily Extract.", "parameters": { "urls": { "type": "array", "description": "The URLs to extract content from.", "default": "", "items": { "type": "string", "description": "The URL to extract content from, e.g. www.yahoo.com" }, "required": True }, "extract_depth": { "type": "string", "description": "The depth of the extraction process. advanced extraction retrieves more data, including tables and embedded content, with higher success but may increase latency.basic extraction costs 1 credit per 5 successful URL extractions, while advanced extraction costs 2 credits per 5 successful URL extractions.", "enum": ["basic", "advanced"], "default": "basic", "required": False, }, "format": { "type": "string", "description": "The format of the extracted web page content. markdown returns content in markdown format. text returns plain text and may increase latency.", "enum": ["markdown", "text"], "default": "markdown", "required": False, } } } super().__init__() self.api_key = "" self.extract_depth = "basic" # basic/advanced self.urls = [] self.format = "markdown" self.include_images = False def check(self): self.check_valid_value(self.extract_depth, "Tavily extract depth should be in 'basic/advanced'", ["basic", "advanced"]) self.check_valid_value(self.format, "Tavily extract format should be in 'markdown/text'", ["markdown", "text"]) def get_input_form(self) -> dict[str, dict]: return { "urls": { "name": "URLs", "type": "line" } } class TavilyExtract(ToolBase, ABC): component_name = "TavilyExtract" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): if self.check_if_canceled("TavilyExtract processing"): return self.tavily_client = TavilyClient(api_key=self._param.api_key) last_e = None for fld in ["urls", "extract_depth", "format"]: if fld not in kwargs: kwargs[fld] = getattr(self._param, fld) if kwargs.get("urls") and isinstance(kwargs["urls"], str): kwargs["urls"] = kwargs["urls"].split(",") for _ in range(self._param.max_retries+1): if self.check_if_canceled("TavilyExtract processing"): return try: kwargs["include_images"] = False res = self.tavily_client.extract(**kwargs) if self.check_if_canceled("TavilyExtract processing"): return self.set_output("json", res["results"]) return self.output("json") except Exception as e: if self.check_if_canceled("TavilyExtract processing"): return last_e = e logging.exception(f"Tavily error: {e}") if last_e: self.set_output("_ERROR", str(last_e)) return f"Tavily error: {last_e}" assert False, self.output() def thoughts(self) -> str: return "Opened {}โ€”pulling out the main textโ€ฆ".format(self.get_input().get("urls", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/exesql.py
agent/tools/exesql.py
# # Copyright 2024 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 json import os import re from abc import ABC import pandas as pd import pymysql import psycopg2 import pyodbc from agent.tools.base import ToolParamBase, ToolBase, ToolMeta from common.connection_utils import timeout class ExeSQLParam(ToolParamBase): """ Define the ExeSQL component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "execute_sql", "description": "This is a tool that can execute SQL.", "parameters": { "sql": { "type": "string", "description": "The SQL needs to be executed.", "default": "{sys.query}", "required": True } } } super().__init__() self.db_type = "mysql" self.database = "" self.username = "" self.host = "" self.port = 3306 self.password = "" self.max_records = 1024 def check(self): self.check_valid_value(self.db_type, "Choose DB type", ['mysql', 'postgres', 'mariadb', 'mssql', 'IBM DB2', 'trino']) self.check_empty(self.database, "Database name") self.check_empty(self.username, "database username") self.check_empty(self.host, "IP Address") self.check_positive_integer(self.port, "IP Port") if self.db_type != "trino": self.check_empty(self.password, "Database password") self.check_positive_integer(self.max_records, "Maximum number of records") if self.database == "rag_flow": if self.host == "ragflow-mysql": raise ValueError("For the security reason, it dose not support database named rag_flow.") if self.password == "infini_rag_flow": raise ValueError("For the security reason, it dose not support database named rag_flow.") def get_input_form(self) -> dict[str, dict]: return { "sql": { "name": "SQL", "type": "line" } } class ExeSQL(ToolBase, ABC): component_name = "ExeSQL" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 60))) def _invoke(self, **kwargs): if self.check_if_canceled("ExeSQL processing"): return def convert_decimals(obj): from decimal import Decimal if isinstance(obj, Decimal): return float(obj) # ๆˆ– str(obj) elif isinstance(obj, dict): return {k: convert_decimals(v) for k, v in obj.items()} elif isinstance(obj, list): return [convert_decimals(item) for item in obj] return obj sql = kwargs.get("sql") if not sql: raise Exception("SQL for `ExeSQL` MUST not be empty.") if self.check_if_canceled("ExeSQL processing"): return vars = self.get_input_elements_from_text(sql) args = {} for k, o in vars.items(): args[k] = o["value"] if not isinstance(args[k], str): try: args[k] = json.dumps(args[k], ensure_ascii=False) except Exception: args[k] = str(args[k]) self.set_input_value(k, args[k]) sql = self.string_format(sql, args) if self.check_if_canceled("ExeSQL processing"): return sqls = sql.split(";") if self._param.db_type in ["mysql", "mariadb"]: db = pymysql.connect(db=self._param.database, user=self._param.username, host=self._param.host, port=self._param.port, password=self._param.password) elif self._param.db_type == 'postgres': db = psycopg2.connect(dbname=self._param.database, user=self._param.username, host=self._param.host, port=self._param.port, password=self._param.password) elif self._param.db_type == 'mssql': conn_str = ( r'DRIVER={ODBC Driver 17 for SQL Server};' r'SERVER=' + self._param.host + ',' + str(self._param.port) + ';' r'DATABASE=' + self._param.database + ';' r'UID=' + self._param.username + ';' r'PWD=' + self._param.password ) db = pyodbc.connect(conn_str) elif self._param.db_type == 'trino': try: import trino from trino.auth import BasicAuthentication except Exception: raise Exception("Missing dependency 'trino'. Please install: pip install trino") def _parse_catalog_schema(db: str): if not db: return None, None if "." in db: c, s = db.split(".", 1) elif "/" in db: c, s = db.split("/", 1) else: c, s = db, "default" return c, s catalog, schema = _parse_catalog_schema(self._param.database) if not catalog: raise Exception("For Trino, `database` must be 'catalog.schema' or at least 'catalog'.") http_scheme = "https" if os.environ.get("TRINO_USE_TLS", "0") == "1" else "http" auth = None if http_scheme == "https" and self._param.password: auth = BasicAuthentication(self._param.username, self._param.password) try: db = trino.dbapi.connect( host=self._param.host, port=int(self._param.port or 8080), user=self._param.username or "ragflow", catalog=catalog, schema=schema or "default", http_scheme=http_scheme, auth=auth ) except Exception as e: raise Exception("Database Connection Failed! \n" + str(e)) elif self._param.db_type == 'IBM DB2': import ibm_db conn_str = ( f"DATABASE={self._param.database};" f"HOSTNAME={self._param.host};" f"PORT={self._param.port};" f"PROTOCOL=TCPIP;" f"UID={self._param.username};" f"PWD={self._param.password};" ) try: conn = ibm_db.connect(conn_str, "", "") except Exception as e: raise Exception("Database Connection Failed! \n" + str(e)) sql_res = [] formalized_content = [] for single_sql in sqls: if self.check_if_canceled("ExeSQL processing"): ibm_db.close(conn) return single_sql = single_sql.replace("```", "").strip() if not single_sql: continue single_sql = re.sub(r"\[ID:[0-9]+\]", "", single_sql) stmt = ibm_db.exec_immediate(conn, single_sql) rows = [] row = ibm_db.fetch_assoc(stmt) while row and len(rows) < self._param.max_records: if self.check_if_canceled("ExeSQL processing"): ibm_db.close(conn) return rows.append(row) row = ibm_db.fetch_assoc(stmt) if not rows: sql_res.append({"content": "No record in the database!"}) continue df = pd.DataFrame(rows) for col in df.columns: if pd.api.types.is_datetime64_any_dtype(df[col]): df[col] = df[col].dt.strftime("%Y-%m-%d") df = df.where(pd.notnull(df), None) sql_res.append(convert_decimals(df.to_dict(orient="records"))) formalized_content.append(df.to_markdown(index=False, floatfmt=".6f")) ibm_db.close(conn) self.set_output("json", sql_res) self.set_output("formalized_content", "\n\n".join(formalized_content)) return self.output("formalized_content") try: cursor = db.cursor() except Exception as e: raise Exception("Database Connection Failed! \n" + str(e)) sql_res = [] formalized_content = [] for single_sql in sqls: if self.check_if_canceled("ExeSQL processing"): cursor.close() db.close() return single_sql = single_sql.replace('```','') if not single_sql: continue single_sql = re.sub(r"\[ID:[0-9]+\]", "", single_sql) cursor.execute(single_sql) if cursor.rowcount == 0: sql_res.append({"content": "No record in the database!"}) break if self._param.db_type == 'mssql': single_res = pd.DataFrame.from_records(cursor.fetchmany(self._param.max_records), columns=[desc[0] for desc in cursor.description]) else: single_res = pd.DataFrame([i for i in cursor.fetchmany(self._param.max_records)]) single_res.columns = [i[0] for i in cursor.description] for col in single_res.columns: if pd.api.types.is_datetime64_any_dtype(single_res[col]): single_res[col] = single_res[col].dt.strftime('%Y-%m-%d') single_res = single_res.where(pd.notnull(single_res), None) sql_res.append(convert_decimals(single_res.to_dict(orient='records'))) formalized_content.append(single_res.to_markdown(index=False, floatfmt=".6f")) cursor.close() db.close() self.set_output("json", sql_res) self.set_output("formalized_content", "\n\n".join(formalized_content)) return self.output("formalized_content") def thoughts(self) -> str: return "Query sentโ€”waiting for the data."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/code_exec.py
agent/tools/code_exec.py
# # 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 ast import base64 import json import logging import os from abc import ABC from typing import Optional from pydantic import BaseModel, Field, field_validator from strenum import StrEnum from agent.tools.base import ToolBase, ToolMeta, ToolParamBase from common import settings from common.connection_utils import timeout class Language(StrEnum): PYTHON = "python" NODEJS = "nodejs" class CodeExecutionRequest(BaseModel): code_b64: str = Field(..., description="Base64 encoded code string") language: str = Field(default=Language.PYTHON.value, description="Programming language") arguments: Optional[dict] = Field(default={}, description="Arguments") @field_validator("code_b64") @classmethod def validate_base64(cls, v: str) -> str: try: base64.b64decode(v, validate=True) return v except Exception as e: raise ValueError(f"Invalid base64 encoding: {str(e)}") @field_validator("language", mode="before") @classmethod def normalize_language(cls, v) -> str: if isinstance(v, str): low = v.lower() if low in ("python", "python3"): return "python" elif low in ("javascript", "nodejs"): return "nodejs" raise ValueError(f"Unsupported language: {v}") class CodeExecParam(ToolParamBase): """ Define the code sandbox component parameters. """ def __init__(self): self.meta: ToolMeta = { "name": "execute_code", "description": """ This tool has a sandbox that can execute code written in 'Python'/'Javascript'. It receives a piece of code and return a Json string. Here's a code example for Python(`main` function MUST be included): def main() -> dict: \"\"\" Generate Fibonacci numbers within 100. \"\"\" def fibonacci_recursive(n): if n <= 1: return n else: return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) return { "result": fibonacci_recursive(100), } Here's a code example for Javascript(`main` function MUST be included and exported): const axios = require('axios'); async function main(args) { try { const response = await axios.get('https://github.com/infiniflow/ragflow'); console.log('Body:', response.data); } catch (error) { console.error('Error:', error.message); } } module.exports = { main }; """, "parameters": { "lang": { "type": "string", "description": "The programming language of this piece of code.", "enum": ["python", "javascript"], "required": True, }, "script": {"type": "string", "description": "A piece of code in right format. There MUST be main function.", "required": True}, }, } super().__init__() self.lang = Language.PYTHON.value self.script = 'def main(arg1: str, arg2: str) -> dict: return {"result": arg1 + arg2}' self.arguments = {} self.outputs = {"result": {"value": "", "type": "string"}} def check(self): self.check_valid_value(self.lang, "Support languages", ["python", "python3", "nodejs", "javascript"]) self.check_empty(self.script, "Script") def get_input_form(self) -> dict[str, dict]: res = {} for k, v in self.arguments.items(): res[k] = {"type": "line", "name": k} return res class CodeExec(ToolBase, ABC): component_name = "CodeExec" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10 * 60))) def _invoke(self, **kwargs): if self.check_if_canceled("CodeExec processing"): return lang = kwargs.get("lang", self._param.lang) script = kwargs.get("script", self._param.script) arguments = {} for k, v in self._param.arguments.items(): if kwargs.get(k): arguments[k] = kwargs[k] continue arguments[k] = self._canvas.get_variable_value(v) if v else None self._execute_code(language=lang, code=script, arguments=arguments) def _execute_code(self, language: str, code: str, arguments: dict): import requests if self.check_if_canceled("CodeExec execution"): return try: code_b64 = self._encode_code(code) code_req = CodeExecutionRequest(code_b64=code_b64, language=language, arguments=arguments).model_dump() except Exception as e: if self.check_if_canceled("CodeExec execution"): return self.set_output("_ERROR", "construct code request error: " + str(e)) try: if self.check_if_canceled("CodeExec execution"): return "Task has been canceled" resp = requests.post(url=f"http://{settings.SANDBOX_HOST}:9385/run", json=code_req, timeout=int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10 * 60))) logging.info(f"http://{settings.SANDBOX_HOST}:9385/run, code_req: {code_req}, resp.status_code {resp.status_code}:") if self.check_if_canceled("CodeExec execution"): return "Task has been canceled" if resp.status_code != 200: resp.raise_for_status() body = resp.json() if body: stderr = body.get("stderr") if stderr: self.set_output("_ERROR", stderr) return raw_stdout = body.get("stdout", "") parsed_stdout = self._deserialize_stdout(raw_stdout) logging.info(f"[CodeExec]: http://{settings.SANDBOX_HOST}:9385/run -> {parsed_stdout}") self._populate_outputs(parsed_stdout, raw_stdout) else: self.set_output("_ERROR", "There is no response from sandbox") except Exception as e: if self.check_if_canceled("CodeExec execution"): return self.set_output("_ERROR", "Exception executing code: " + str(e)) return self.output() def _encode_code(self, code: str) -> str: return base64.b64encode(code.encode("utf-8")).decode("utf-8") def thoughts(self) -> str: return "Running a short script to process data." def _deserialize_stdout(self, stdout: str): text = str(stdout).strip() if not text: return "" for loader in (json.loads, ast.literal_eval): try: return loader(text) except Exception: continue return text def _coerce_output_value(self, value, expected_type: Optional[str]): if expected_type is None: return value etype = expected_type.strip().lower() inner_type = None if etype.startswith("array<") and etype.endswith(">"): inner_type = etype[6:-1].strip() etype = "array" try: if etype == "string": return "" if value is None else str(value) if etype == "number": if value is None or value == "": return None if isinstance(value, (int, float)): return value if isinstance(value, str): try: return float(value) except Exception: return value return float(value) if etype == "boolean": if isinstance(value, bool): return value if isinstance(value, str): lv = value.lower() if lv in ("true", "1", "yes", "y", "on"): return True if lv in ("false", "0", "no", "n", "off"): return False return bool(value) if etype == "array": candidate = value if isinstance(candidate, str): parsed = self._deserialize_stdout(candidate) candidate = parsed if isinstance(candidate, tuple): candidate = list(candidate) if not isinstance(candidate, list): candidate = [] if candidate is None else [candidate] if inner_type == "string": return ["" if v is None else str(v) for v in candidate] if inner_type == "number": coerced = [] for v in candidate: try: if v is None or v == "": coerced.append(None) elif isinstance(v, (int, float)): coerced.append(v) else: coerced.append(float(v)) except Exception: coerced.append(v) return coerced return candidate if etype == "object": if isinstance(value, dict): return value if isinstance(value, str): parsed = self._deserialize_stdout(value) if isinstance(parsed, dict): return parsed return value except Exception: return value return value def _populate_outputs(self, parsed_stdout, raw_stdout: str): outputs_items = list(self._param.outputs.items()) logging.info(f"[CodeExec]: outputs schema keys: {[k for k, _ in outputs_items]}") if not outputs_items: return if isinstance(parsed_stdout, dict): for key, meta in outputs_items: if key.startswith("_"): continue val = self._get_by_path(parsed_stdout, key) coerced = self._coerce_output_value(val, meta.get("type")) logging.info(f"[CodeExec]: populate dict key='{key}' raw='{val}' coerced='{coerced}'") self.set_output(key, coerced) return if isinstance(parsed_stdout, (list, tuple)): for idx, (key, meta) in enumerate(outputs_items): if key.startswith("_"): continue val = parsed_stdout[idx] if idx < len(parsed_stdout) else None coerced = self._coerce_output_value(val, meta.get("type")) logging.info(f"[CodeExec]: populate list key='{key}' raw='{val}' coerced='{coerced}'") self.set_output(key, coerced) return default_val = parsed_stdout if parsed_stdout is not None else raw_stdout for idx, (key, meta) in enumerate(outputs_items): if key.startswith("_"): continue val = default_val if idx == 0 else None coerced = self._coerce_output_value(val, meta.get("type")) logging.info(f"[CodeExec]: populate scalar key='{key}' raw='{val}' coerced='{coerced}'") self.set_output(key, coerced) def _get_by_path(self, data, path: str): if not path: return None cur = data for part in path.split("."): part = part.strip() if not part: return None if isinstance(cur, dict): cur = cur.get(part) elif isinstance(cur, list): try: idx = int(part) cur = cur[idx] except Exception: return None else: return None if cur is None: return None logging.info(f"[CodeExec]: resolve path '{path}' -> {cur}") return cur
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/akshare.py
agent/tools/akshare.py
# # Copyright 2024 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. # from abc import ABC import pandas as pd from agent.component.base import ComponentBase, ComponentParamBase class AkShareParam(ComponentParamBase): """ Define the AkShare component parameters. """ def __init__(self): super().__init__() self.top_n = 10 def check(self): self.check_positive_integer(self.top_n, "Top N") class AkShare(ComponentBase, ABC): component_name = "AkShare" def _run(self, history, **kwargs): import akshare as ak ans = self.get_input() ans = ",".join(ans["content"]) if "content" in ans else "" if not ans: return AkShare.be_output("") try: ak_res = [] stock_news_em_df = ak.stock_news_em(symbol=ans) stock_news_em_df = stock_news_em_df.head(self._param.top_n) ak_res = [{"content": '<a href="' + i["ๆ–ฐ้—ป้“พๆŽฅ"] + '">' + i["ๆ–ฐ้—ปๆ ‡้ข˜"] + '</a>\n ๆ–ฐ้—ปๅ†…ๅฎน: ' + i[ "ๆ–ฐ้—ปๅ†…ๅฎน"] + " \nๅ‘ๅธƒๆ—ถ้—ด:" + i["ๅ‘ๅธƒๆ—ถ้—ด"] + " \nๆ–‡็ซ ๆฅๆบ: " + i["ๆ–‡็ซ ๆฅๆบ"]} for index, i in stock_news_em_df.iterrows()] except Exception as e: return AkShare.be_output("**ERROR**: " + str(e)) if not ak_res: return AkShare.be_output("") return pd.DataFrame(ak_res)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/deepl.py
agent/tools/deepl.py
# # Copyright 2024 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. # from abc import ABC from agent.component.base import ComponentBase, ComponentParamBase import deepl class DeepLParam(ComponentParamBase): """ Define the DeepL component parameters. """ def __init__(self): super().__init__() self.auth_key = "xxx" self.parameters = [] self.source_lang = 'ZH' self.target_lang = 'EN-GB' def check(self): self.check_positive_integer(self.top_n, "Top N") self.check_valid_value(self.source_lang, "Source language", ['AR', 'BG', 'CS', 'DA', 'DE', 'EL', 'EN', 'ES', 'ET', 'FI', 'FR', 'HU', 'ID', 'IT', 'JA', 'KO', 'LT', 'LV', 'NB', 'NL', 'PL', 'PT', 'RO', 'RU', 'SK', 'SL', 'SV', 'TR', 'UK', 'ZH']) self.check_valid_value(self.target_lang, "Target language", ['AR', 'BG', 'CS', 'DA', 'DE', 'EL', 'EN-GB', 'EN-US', 'ES', 'ET', 'FI', 'FR', 'HU', 'ID', 'IT', 'JA', 'KO', 'LT', 'LV', 'NB', 'NL', 'PL', 'PT-BR', 'PT-PT', 'RO', 'RU', 'SK', 'SL', 'SV', 'TR', 'UK', 'ZH']) class DeepL(ComponentBase, ABC): component_name = "DeepL" def _run(self, history, **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 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) return DeepL.be_output(result.text) except Exception as e: if self.check_if_canceled("DeepL processing"): return DeepL.be_output("**Error**:" + str(e))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/googlescholar.py
agent/tools/googlescholar.py
# # Copyright 2024 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 from scholarly import scholarly from agent.tools.base import ToolMeta, ToolParamBase, ToolBase from common.connection_utils import timeout class GoogleScholarParam(ToolParamBase): """ Define the GoogleScholar component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "google_scholar_search", "description": """Google Scholar provides a simple way to broadly search for scholarly literature. From one place, you can search across many disciplines and sources: articles, theses, books, abstracts and court opinions, from academic publishers, professional societies, online repositories, universities and other web sites. Google Scholar helps you find relevant work across the world of scholarly research.""", "parameters": { "query": { "type": "string", "description": "The search keyword to execute with Google Scholar. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True } } } super().__init__() self.top_n = 12 self.sort_by = 'relevance' self.year_low = None self.year_high = None self.patents = True def check(self): self.check_positive_integer(self.top_n, "Top N") self.check_valid_value(self.sort_by, "GoogleScholar Sort_by", ['date', 'relevance']) self.check_boolean(self.patents, "Whether or not to include patents, defaults to True") def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" } } class GoogleScholar(ToolBase, ABC): component_name = "GoogleScholar" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("GoogleScholar processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("GoogleScholar processing"): return try: scholar_client = scholarly.search_pubs(kwargs["query"], patents=self._param.patents, year_low=self._param.year_low, year_high=self._param.year_high, sort_by=self._param.sort_by) if self.check_if_canceled("GoogleScholar processing"): return self._retrieve_chunks(scholar_client, get_title=lambda r: r['bib']['title'], get_url=lambda r: r["pub_url"], get_content=lambda r: "\n author: " + ",".join(r['bib']['author']) + '\n Abstract: ' + r['bib'].get('abstract', 'no abstract') ) self.set_output("json", list(scholar_client)) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("GoogleScholar processing"): return last_e = e logging.exception(f"GoogleScholar error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"GoogleScholar error: {last_e}" assert False, self.output() def thoughts(self) -> str: return "Looking for scholarly papers on `{}`,โ€ prioritising reputable sources.".format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/retrieval.py
agent/tools/retrieval.py
# # Copyright 2024 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 asyncio from functools import partial import json import os import re from abc import ABC from agent.tools.base import ToolParamBase, ToolBase, ToolMeta from common.constants import LLMType from api.db.services.document_service import DocumentService from common.metadata_utils import apply_meta_data_filter from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.llm_service import LLMBundle from api.db.services.memory_service import MemoryService from api.db.joint_services import memory_message_service from common import settings from common.connection_utils import timeout from rag.app.tag import label_question from rag.prompts.generator import cross_languages, kb_prompt, memory_prompt class RetrievalParam(ToolParamBase): """ Define the Retrieval component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "search_my_dateset", "description": "This tool can be utilized for relevant content searching in the datasets.", "parameters": { "query": { "type": "string", "description": "The keywords to search the dataset. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "", "required": True } } } super().__init__() self.function_name = "search_my_dateset" self.description = "This tool can be utilized for relevant content searching in the datasets." self.similarity_threshold = 0.2 self.keywords_similarity_weight = 0.5 self.top_n = 8 self.top_k = 1024 self.kb_ids = [] self.memory_ids = [] self.kb_vars = [] self.rerank_id = "" self.empty_response = "" self.use_kg = False self.cross_languages = [] self.toc_enhance = False self.meta_data_filter={} def check(self): self.check_decimal_float(self.similarity_threshold, "[Retrieval] Similarity threshold") self.check_decimal_float(self.keywords_similarity_weight, "[Retrieval] Keyword similarity weight") self.check_positive_number(self.top_n, "[Retrieval] Top N") def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" } } class Retrieval(ToolBase, ABC): component_name = "Retrieval" async def _retrieve_kb(self, query_text: str): kb_ids: list[str] = [] for id in self._param.kb_ids: if id.find("@") < 0: kb_ids.append(id) continue kb_nm = self._canvas.get_variable_value(id) # if kb_nm is a list kb_nm_list = kb_nm if isinstance(kb_nm, list) else [kb_nm] for nm_or_id in kb_nm_list: e, kb = KnowledgebaseService.get_by_name(nm_or_id, self._canvas._tenant_id) if not e: e, kb = KnowledgebaseService.get_by_id(nm_or_id) if not e: raise Exception(f"Dataset({nm_or_id}) does not exist.") kb_ids.append(kb.id) filtered_kb_ids: list[str] = list(set([kb_id for kb_id in kb_ids if kb_id])) kbs = KnowledgebaseService.get_by_ids(filtered_kb_ids) if not kbs: raise Exception("No dataset is selected.") embd_nms = list(set([kb.embd_id for kb in kbs])) assert len(embd_nms) == 1, "Knowledge bases use different embedding models." embd_mdl = None if embd_nms: embd_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING, embd_nms[0]) rerank_mdl = None if self._param.rerank_id: rerank_mdl = LLMBundle(kbs[0].tenant_id, LLMType.RERANK, self._param.rerank_id) vars = self.get_input_elements_from_text(query_text) vars = {k: o["value"] for k, o in vars.items()} query = self.string_format(query_text, vars) doc_ids = [] if self._param.meta_data_filter != {}: metas = DocumentService.get_meta_by_kbs(kb_ids) def _resolve_manual_filter(flt: dict) -> dict: pat = re.compile(self.variable_ref_patt) s = flt.get("value", "") out_parts = [] last = 0 for m in pat.finditer(s): out_parts.append(s[last:m.start()]) key = m.group(1) v = self._canvas.get_variable_value(key) if v is None: rep = "" elif isinstance(v, partial): buf = [] for chunk in v(): buf.append(chunk) rep = "".join(buf) elif isinstance(v, str): rep = v else: rep = json.dumps(v, ensure_ascii=False) out_parts.append(rep) last = m.end() out_parts.append(s[last:]) flt["value"] = "".join(out_parts) return flt chat_mdl = None if self._param.meta_data_filter.get("method") in ["auto", "semi_auto"]: chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT) doc_ids = await apply_meta_data_filter( self._param.meta_data_filter, metas, query, chat_mdl, doc_ids, _resolve_manual_filter if self._param.meta_data_filter.get("method") == "manual" else None, ) if self._param.cross_languages: query = await cross_languages(kbs[0].tenant_id, None, query, self._param.cross_languages) if kbs: query = re.sub(r"^user[:๏ผš\s]*", "", query, flags=re.IGNORECASE) kbinfos = settings.retriever.retrieval( query, embd_mdl, [kb.tenant_id for kb in kbs], filtered_kb_ids, 1, self._param.top_n, self._param.similarity_threshold, 1 - self._param.keywords_similarity_weight, doc_ids=doc_ids, aggs=False, rerank_mdl=rerank_mdl, rank_feature=label_question(query, kbs), ) if self.check_if_canceled("Retrieval processing"): return if self._param.toc_enhance: chat_mdl = LLMBundle(self._canvas._tenant_id, LLMType.CHAT) cks = settings.retriever.retrieval_by_toc(query, kbinfos["chunks"], [kb.tenant_id for kb in kbs], chat_mdl, self._param.top_n) if self.check_if_canceled("Retrieval processing"): return if cks: kbinfos["chunks"] = cks kbinfos["chunks"] = settings.retriever.retrieval_by_children(kbinfos["chunks"], [kb.tenant_id for kb in kbs]) if self._param.use_kg: ck = await settings.kg_retriever.retrieval(query, [kb.tenant_id for kb in kbs], kb_ids, embd_mdl, LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT)) if self.check_if_canceled("Retrieval processing"): return if ck["content_with_weight"]: kbinfos["chunks"].insert(0, ck) else: kbinfos = {"chunks": [], "doc_aggs": []} if self._param.use_kg and kbs: ck = await settings.kg_retriever.retrieval(query, [kb.tenant_id for kb in kbs], filtered_kb_ids, embd_mdl, LLMBundle(kbs[0].tenant_id, LLMType.CHAT)) if self.check_if_canceled("Retrieval processing"): return if ck["content_with_weight"]: ck["content"] = ck["content_with_weight"] del ck["content_with_weight"] kbinfos["chunks"].insert(0, ck) for ck in kbinfos["chunks"]: if "vector" in ck: del ck["vector"] if "content_ltks" in ck: del ck["content_ltks"] if not kbinfos["chunks"]: self.set_output("formalized_content", self._param.empty_response) return # Format the chunks for JSON output (similar to how other tools do it) json_output = kbinfos["chunks"].copy() self._canvas.add_reference(kbinfos["chunks"], kbinfos["doc_aggs"]) form_cnt = "\n".join(kb_prompt(kbinfos, 200000, True)) # Set both formalized content and JSON output self.set_output("formalized_content", form_cnt) self.set_output("json", json_output) return form_cnt async def _retrieve_memory(self, query_text: str): memory_ids: list[str] = [memory_id for memory_id in self._param.memory_ids] memory_list = MemoryService.get_by_ids(memory_ids) if not memory_list: raise Exception("No memory is selected.") embd_names = list({memory.embd_id for memory in memory_list}) assert len(embd_names) == 1, "Memory use different embedding models." vars = self.get_input_elements_from_text(query_text) vars = {k: o["value"] for k, o in vars.items()} query = self.string_format(query_text, vars) # query message message_list = memory_message_service.query_message({"memory_id": memory_ids}, { "query": query, "similarity_threshold": self._param.similarity_threshold, "keywords_similarity_weight": self._param.keywords_similarity_weight, "top_n": self._param.top_n }) if not message_list: self.set_output("formalized_content", self._param.empty_response) return "" formated_content = "\n".join(memory_prompt(message_list, 200000)) # set formalized_content output self.set_output("formalized_content", formated_content) return formated_content @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) async def _invoke_async(self, **kwargs): if self.check_if_canceled("Retrieval processing"): return if not kwargs.get("query"): self.set_output("formalized_content", self._param.empty_response) return if hasattr(self._param, "retrieval_from") and self._param.retrieval_from == "dataset": return await self._retrieve_kb(kwargs["query"]) elif hasattr(self._param, "retrieval_from") and self._param.retrieval_from == "memory": return await self._retrieve_memory(kwargs["query"]) elif self._param.kb_ids: return await self._retrieve_kb(kwargs["query"]) elif hasattr(self._param, "memory_ids") and self._param.memory_ids: return await self._retrieve_memory(kwargs["query"]) else: self.set_output("formalized_content", self._param.empty_response) return @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): return asyncio.run(self._invoke_async(**kwargs)) def thoughts(self) -> str: return """ Keywords: {} Looking for the most relevant articles. """.format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/tushare.py
agent/tools/tushare.py
# # Copyright 2024 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 json from abc import ABC import pandas as pd import time import requests from agent.component.base import ComponentBase, ComponentParamBase class TuShareParam(ComponentParamBase): """ Define the TuShare component parameters. """ def __init__(self): super().__init__() self.token = "xxx" self.src = "eastmoney" self.start_date = "2024-01-01 09:00:00" self.end_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.keyword = "" def check(self): self.check_valid_value(self.src, "Quick News Source", ["sina", "wallstreetcn", "10jqka", "eastmoney", "yuncaijing", "fenghuang", "jinrongjie"]) class TuShare(ComponentBase, ABC): component_name = "TuShare" def _run(self, history, **kwargs): if self.check_if_canceled("TuShare processing"): return ans = self.get_input() ans = ",".join(ans["content"]) if "content" in ans else "" if not ans: return TuShare.be_output("") try: if self.check_if_canceled("TuShare processing"): return tus_res = [] params = { "api_name": "news", "token": self._param.token, "params": {"src": self._param.src, "start_date": self._param.start_date, "end_date": self._param.end_date} } response = requests.post(url="http://api.tushare.pro", data=json.dumps(params).encode('utf-8')) response = response.json() if self.check_if_canceled("TuShare processing"): return if response['code'] != 0: return TuShare.be_output(response['msg']) df = pd.DataFrame(response['data']['items']) df.columns = response['data']['fields'] if self.check_if_canceled("TuShare processing"): return tus_res.append({"content": (df[df['content'].str.contains(self._param.keyword, case=False)]).to_markdown()}) except Exception as e: if self.check_if_canceled("TuShare processing"): return return TuShare.be_output("**ERROR**: " + str(e)) if not tus_res: return TuShare.be_output("") return pd.DataFrame(tus_res)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/google.py
agent/tools/google.py
# # Copyright 2024 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 from serpapi import GoogleSearch from agent.tools.base import ToolParamBase, ToolMeta, ToolBase from common.connection_utils import timeout class GoogleParam(ToolParamBase): """ Define the Google component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "google_search", "description": """Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking ...""", "parameters": { "q": { "type": "string", "description": "The search keywords to execute with Google. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True }, "start": { "type": "integer", "description": "Parameter defines the result offset. It skips the given number of results. It's used for pagination. (e.g., 0 (default) is the first page of results, 10 is the 2nd page of results, 20 is the 3rd page of results, etc.). Google Local Results only accepts multiples of 20(e.g. 20 for the second page results, 40 for the third page results, etc.) as the `start` value.", "default": "0", "required": False, }, "num": { "type": "integer", "description": "Parameter defines the maximum number of results to return. (e.g., 10 (default) returns 10 results, 40 returns 40 results, and 100 returns 100 results). The use of num may introduce latency, and/or prevent the inclusion of specialized result types. It is better to omit this parameter unless it is strictly necessary to increase the number of results per page. Results are not guaranteed to have the number of results specified in num.", "default": "6", "required": False, } } } super().__init__() self.start = 0 self.num = 6 self.api_key = "" self.country = "cn" self.language = "en" def check(self): self.check_empty(self.api_key, "SerpApi API key") self.check_valid_value(self.country, "Google Country", ['af', 'al', 'dz', 'as', 'ad', 'ao', 'ai', 'aq', 'ag', 'ar', 'am', 'aw', 'au', 'at', 'az', 'bs', 'bh', 'bd', 'bb', 'by', 'be', 'bz', 'bj', 'bm', 'bt', 'bo', 'ba', 'bw', 'bv', 'br', 'io', 'bn', 'bg', 'bf', 'bi', 'kh', 'cm', 'ca', 'cv', 'ky', 'cf', 'td', 'cl', 'cn', 'cx', 'cc', 'co', 'km', 'cg', 'cd', 'ck', 'cr', 'ci', 'hr', 'cu', 'cy', 'cz', 'dk', 'dj', 'dm', 'do', 'ec', 'eg', 'sv', 'gq', 'er', 'ee', 'et', 'fk', 'fo', 'fj', 'fi', 'fr', 'gf', 'pf', 'tf', 'ga', 'gm', 'ge', 'de', 'gh', 'gi', 'gr', 'gl', 'gd', 'gp', 'gu', 'gt', 'gn', 'gw', 'gy', 'ht', 'hm', 'va', 'hn', 'hk', 'hu', 'is', 'in', 'id', 'ir', 'iq', 'ie', 'il', 'it', 'jm', 'jp', 'jo', 'kz', 'ke', 'ki', 'kp', 'kr', 'kw', 'kg', 'la', 'lv', 'lb', 'ls', 'lr', 'ly', 'li', 'lt', 'lu', 'mo', 'mk', 'mg', 'mw', 'my', 'mv', 'ml', 'mt', 'mh', 'mq', 'mr', 'mu', 'yt', 'mx', 'fm', 'md', 'mc', 'mn', 'ms', 'ma', 'mz', 'mm', 'na', 'nr', 'np', 'nl', 'an', 'nc', 'nz', 'ni', 'ne', 'ng', 'nu', 'nf', 'mp', 'no', 'om', 'pk', 'pw', 'ps', 'pa', 'pg', 'py', 'pe', 'ph', 'pn', 'pl', 'pt', 'pr', 'qa', 're', 'ro', 'ru', 'rw', 'sh', 'kn', 'lc', 'pm', 'vc', 'ws', 'sm', 'st', 'sa', 'sn', 'rs', 'sc', 'sl', 'sg', 'sk', 'si', 'sb', 'so', 'za', 'gs', 'es', 'lk', 'sd', 'sr', 'sj', 'sz', 'se', 'ch', 'sy', 'tw', 'tj', 'tz', 'th', 'tl', 'tg', 'tk', 'to', 'tt', 'tn', 'tr', 'tm', 'tc', 'tv', 'ug', 'ua', 'ae', 'uk', 'gb', 'us', 'um', 'uy', 'uz', 'vu', 've', 'vn', 'vg', 'vi', 'wf', 'eh', 'ye', 'zm', 'zw']) self.check_valid_value(self.language, "Google languages", ['af', 'ak', 'sq', 'ws', 'am', 'ar', 'hy', 'az', 'eu', 'be', 'bem', 'bn', 'bh', 'xx-bork', 'bs', 'br', 'bg', 'bt', 'km', 'ca', 'chr', 'ny', 'zh-cn', 'zh-tw', 'co', 'hr', 'cs', 'da', 'nl', 'xx-elmer', 'en', 'eo', 'et', 'ee', 'fo', 'tl', 'fi', 'fr', 'fy', 'gaa', 'gl', 'ka', 'de', 'el', 'kl', 'gn', 'gu', 'xx-hacker', 'ht', 'ha', 'haw', 'iw', 'hi', 'hu', 'is', 'ig', 'id', 'ia', 'ga', 'it', 'ja', 'jw', 'kn', 'kk', 'rw', 'rn', 'xx-klingon', 'kg', 'ko', 'kri', 'ku', 'ckb', 'ky', 'lo', 'la', 'lv', 'ln', 'lt', 'loz', 'lg', 'ach', 'mk', 'mg', 'ms', 'ml', 'mt', 'mv', 'mi', 'mr', 'mfe', 'mo', 'mn', 'sr-me', 'my', 'ne', 'pcm', 'nso', 'no', 'nn', 'oc', 'or', 'om', 'ps', 'fa', 'xx-pirate', 'pl', 'pt', 'pt-br', 'pt-pt', 'pa', 'qu', 'ro', 'rm', 'nyn', 'ru', 'gd', 'sr', 'sh', 'st', 'tn', 'crs', 'sn', 'sd', 'si', 'sk', 'sl', 'so', 'es', 'es-419', 'su', 'sw', 'sv', 'tg', 'ta', 'tt', 'te', 'th', 'ti', 'to', 'lua', 'tum', 'tr', 'tk', 'tw', 'ug', 'uk', 'ur', 'uz', 'vu', 'vi', 'cy', 'wo', 'xh', 'yi', 'yo', 'zu'] ) def get_input_form(self) -> dict[str, dict]: return { "q": { "name": "Query", "type": "line" }, "start": { "name": "From", "type": "integer", "value": 0 }, "num": { "name": "Limit", "type": "integer", "value": 12 } } class Google(ToolBase, ABC): component_name = "Google" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("Google processing"): return if not kwargs.get("q"): self.set_output("formalized_content", "") return "" params = { "api_key": self._param.api_key, "engine": "google", "q": kwargs["q"], "google_domain": "google.com", "gl": self._param.country, "hl": self._param.language } last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("Google processing"): return try: search = GoogleSearch(params).get_dict() if self.check_if_canceled("Google processing"): return self._retrieve_chunks(search["organic_results"], get_title=lambda r: r["title"], get_url=lambda r: r["link"], get_content=lambda r: r.get("about_this_result", {}).get("source", {}).get("description", r["snippet"]) ) self.set_output("json", search["organic_results"]) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("Google processing"): return last_e = e logging.exception(f"Google error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"Google error: {last_e}" assert False, self.output() def thoughts(self) -> str: return """ Keywords: {} Looking for the most relevant articles. """.format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/searxng.py
agent/tools/searxng.py
# # Copyright 2024 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 ToolMeta, ToolParamBase, ToolBase from common.connection_utils import timeout class SearXNGParam(ToolParamBase): """ Define the SearXNG component parameters. """ def __init__(self): self.meta: ToolMeta = { "name": "searxng_search", "description": "SearXNG is a privacy-focused metasearch engine that aggregates results from multiple search engines without tracking users. It provides comprehensive web search capabilities.", "parameters": { "query": { "type": "string", "description": "The search keywords to execute with SearXNG. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True }, "searxng_url": { "type": "string", "description": "The base URL of your SearXNG instance (e.g., http://localhost:4000). This is required to connect to your SearXNG server.", "required": False, "default": "" } } } super().__init__() self.top_n = 10 self.searxng_url = "" def check(self): # Keep validation lenient so opening try-run panel won't fail without URL. # Coerce top_n to int if it comes as string from UI. try: if isinstance(self.top_n, str): self.top_n = int(self.top_n.strip()) except Exception: pass self.check_positive_integer(self.top_n, "Top N") def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" }, "searxng_url": { "name": "SearXNG URL", "type": "line", "placeholder": "http://localhost:4000" } } class SearXNG(ToolBase, ABC): component_name = "SearXNG" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("SearXNG processing"): return # Gracefully handle try-run without inputs query = kwargs.get("query") if not query or not isinstance(query, str) or not query.strip(): self.set_output("formalized_content", "") return "" searxng_url = (getattr(self._param, "searxng_url", "") or kwargs.get("searxng_url") or "").strip() # In try-run, if no URL configured, just return empty instead of raising if not searxng_url: self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("SearXNG processing"): return try: search_params = { 'q': query, 'format': 'json', 'categories': 'general', 'language': 'auto', 'safesearch': 1, 'pageno': 1 } response = requests.get( f"{searxng_url}/search", params=search_params, timeout=10 ) response.raise_for_status() if self.check_if_canceled("SearXNG processing"): return data = response.json() if not data or not isinstance(data, dict): raise ValueError("Invalid response from SearXNG") results = data.get("results", []) if not isinstance(results, list): raise ValueError("Invalid results format from SearXNG") results = results[:self._param.top_n] if self.check_if_canceled("SearXNG processing"): return self._retrieve_chunks(results, get_title=lambda r: r.get("title", ""), get_url=lambda r: r.get("url", ""), get_content=lambda r: r.get("content", "")) self.set_output("json", results) return self.output("formalized_content") except requests.RequestException as e: if self.check_if_canceled("SearXNG processing"): return last_e = f"Network error: {e}" logging.exception(f"SearXNG network error: {e}") time.sleep(self._param.delay_after_error) except Exception as e: if self.check_if_canceled("SearXNG processing"): return last_e = str(e) logging.exception(f"SearXNG error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", last_e) return f"SearXNG error: {last_e}" assert False, self.output() def thoughts(self) -> str: return """ Keywords: {} Searching with SearXNG for relevant results... """.format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/yahoofinance.py
agent/tools/yahoofinance.py
# # Copyright 2024 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 pandas as pd import yfinance as yf from agent.tools.base import ToolMeta, ToolParamBase, ToolBase from common.connection_utils import timeout class YahooFinanceParam(ToolParamBase): """ Define the YahooFinance component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "yahoo_finance", "description": "The Yahoo Finance is a service that provides access to real-time and historical stock market data. It enables users to fetch various types of stock information, such as price quotes, historical prices, company profiles, and financial news. The API offers structured data, allowing developers to integrate market data into their applications and analysis tools.", "parameters": { "stock_code": { "type": "string", "description": "The stock code or company name.", "default": "{sys.query}", "required": True } } } super().__init__() self.info = True self.history = False self.count = False self.financials = False self.income_stmt = False self.balance_sheet = False self.cash_flow_statement = False self.news = True def check(self): self.check_boolean(self.info, "get all stock info") self.check_boolean(self.history, "get historical market data") self.check_boolean(self.count, "show share count") self.check_boolean(self.financials, "show financials") self.check_boolean(self.income_stmt, "income statement") self.check_boolean(self.balance_sheet, "balance sheet") self.check_boolean(self.cash_flow_statement, "cash flow statement") self.check_boolean(self.news, "show news") def get_input_form(self) -> dict[str, dict]: return { "stock_code": { "name": "Stock code/Company name", "type": "line" } } class YahooFinance(ToolBase, ABC): component_name = "YahooFinance" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 60))) def _invoke(self, **kwargs): if self.check_if_canceled("YahooFinance processing"): return None if not kwargs.get("stock_code"): self.set_output("report", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("YahooFinance processing"): return None yahoo_res = [] try: msft = yf.Ticker(kwargs["stock_code"]) if self.check_if_canceled("YahooFinance processing"): return None if self._param.info: yahoo_res.append("# Information:\n" + pd.Series(msft.info).to_markdown() + "\n") if self._param.history: yahoo_res.append("# History:\n" + msft.history().to_markdown() + "\n") if self._param.financials: yahoo_res.append("# Calendar:\n" + pd.DataFrame(msft.calendar).to_markdown() + "\n") if self._param.balance_sheet: yahoo_res.append("# Balance sheet:\n" + msft.balance_sheet.to_markdown() + "\n") yahoo_res.append("# Quarterly balance sheet:\n" + msft.quarterly_balance_sheet.to_markdown() + "\n") if self._param.cash_flow_statement: yahoo_res.append("# Cash flow statement:\n" + msft.cashflow.to_markdown() + "\n") yahoo_res.append("# Quarterly cash flow statement:\n" + msft.quarterly_cashflow.to_markdown() + "\n") if self._param.news: yahoo_res.append("# News:\n" + pd.DataFrame(msft.news).to_markdown() + "\n") self.set_output("report", "\n\n".join(yahoo_res)) return self.output("report") except Exception as e: if self.check_if_canceled("YahooFinance processing"): return None last_e = e logging.exception(f"YahooFinance error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"YahooFinance error: {last_e}" assert False, self.output() def thoughts(self) -> str: return "Pulling live financial data for `{}`.".format(self.get_input().get("stock_code", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/jin10.py
agent/tools/jin10.py
# # Copyright 2024 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 json from abc import ABC import pandas as pd import requests from agent.component.base import ComponentBase, ComponentParamBase class Jin10Param(ComponentParamBase): """ Define the Jin10 component parameters. """ def __init__(self): super().__init__() self.type = "flash" self.secret_key = "xxx" self.flash_type = '1' self.calendar_type = 'cj' self.calendar_datatype = 'data' self.symbols_type = 'GOODS' self.symbols_datatype = 'symbols' self.contain = "" self.filter = "" def check(self): self.check_valid_value(self.type, "Type", ['flash', 'calendar', 'symbols', 'news']) self.check_valid_value(self.flash_type, "Flash Type", ['1', '2', '3', '4', '5']) self.check_valid_value(self.calendar_type, "Calendar Type", ['cj', 'qh', 'hk', 'us']) self.check_valid_value(self.calendar_datatype, "Calendar DataType", ['data', 'event', 'holiday']) self.check_valid_value(self.symbols_type, "Symbols Type", ['GOODS', 'FOREX', 'FUTURE', 'CRYPTO']) self.check_valid_value(self.symbols_datatype, 'Symbols DataType', ['symbols', 'quotes']) class Jin10(ComponentBase, ABC): component_name = "Jin10" def _run(self, history, **kwargs): if self.check_if_canceled("Jin10 processing"): return ans = self.get_input() ans = " - ".join(ans["content"]) if "content" in ans else "" if not ans: return Jin10.be_output("") jin10_res = [] headers = {'secret-key': self._param.secret_key} try: if self.check_if_canceled("Jin10 processing"): return if self._param.type == "flash": params = { 'category': self._param.flash_type, 'contain': self._param.contain, 'filter': self._param.filter } response = requests.get( url='https://open-data-api.jin10.com/data-api/flash?category=' + self._param.flash_type, headers=headers, data=json.dumps(params)) response = response.json() for i in response['data']: if self.check_if_canceled("Jin10 processing"): return jin10_res.append({"content": i['data']['content']}) if self._param.type == "calendar": params = { 'category': self._param.calendar_type } response = requests.get( url='https://open-data-api.jin10.com/data-api/calendar/' + self._param.calendar_datatype + '?category=' + self._param.calendar_type, headers=headers, data=json.dumps(params)) response = response.json() if self.check_if_canceled("Jin10 processing"): return jin10_res.append({"content": pd.DataFrame(response['data']).to_markdown()}) if self._param.type == "symbols": params = { 'type': self._param.symbols_type } if self._param.symbols_datatype == "quotes": params['codes'] = 'BTCUSD' response = requests.get( url='https://open-data-api.jin10.com/data-api/' + self._param.symbols_datatype + '?type=' + self._param.symbols_type, headers=headers, data=json.dumps(params)) response = response.json() if self.check_if_canceled("Jin10 processing"): return if self._param.symbols_datatype == "symbols": for i in response['data']: if self.check_if_canceled("Jin10 processing"): return i['Commodity Code'] = i['c'] i['Stock Exchange'] = i['e'] i['Commodity Name'] = i['n'] i['Commodity Type'] = i['t'] del i['c'], i['e'], i['n'], i['t'] if self._param.symbols_datatype == "quotes": for i in response['data']: if self.check_if_canceled("Jin10 processing"): return i['Selling Price'] = i['a'] i['Buying Price'] = i['b'] i['Commodity Code'] = i['c'] i['Stock Exchange'] = i['e'] i['Highest Price'] = i['h'] i['Yesterdayโ€™s Closing Price'] = i['hc'] i['Lowest Price'] = i['l'] i['Opening Price'] = i['o'] i['Latest Price'] = i['p'] i['Market Quote Time'] = i['t'] del i['a'], i['b'], i['c'], i['e'], i['h'], i['hc'], i['l'], i['o'], i['p'], i['t'] jin10_res.append({"content": pd.DataFrame(response['data']).to_markdown()}) if self._param.type == "news": params = { 'contain': self._param.contain, 'filter': self._param.filter } response = requests.get( url='https://open-data-api.jin10.com/data-api/news', headers=headers, data=json.dumps(params)) response = response.json() if self.check_if_canceled("Jin10 processing"): return jin10_res.append({"content": pd.DataFrame(response['data']).to_markdown()}) except Exception as e: if self.check_if_canceled("Jin10 processing"): return return Jin10.be_output("**ERROR**: " + str(e)) if not jin10_res: return Jin10.be_output("") return pd.DataFrame(jin10_res)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/__init__.py
agent/tools/__init__.py
# # 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 importlib import inspect from types import ModuleType from typing import Dict, Type _package_path = os.path.dirname(__file__) __all_classes: Dict[str, Type] = {} def _import_submodules() -> None: for filename in os.listdir(_package_path): # noqa: F821 if filename.startswith("__") or not filename.endswith(".py") or filename.startswith("base"): continue module_name = filename[:-3] try: module = importlib.import_module(f".{module_name}", package=__name__) _extract_classes_from_module(module) # noqa: F821 except ImportError as e: print(f"Warning: Failed to import module {module_name}: {str(e)}") def _extract_classes_from_module(module: ModuleType) -> None: for name, obj in inspect.getmembers(module): if (inspect.isclass(obj) and obj.__module__ == module.__name__ and not name.startswith("_")): __all_classes[name] = obj globals()[name] = obj _import_submodules() __all__ = list(__all_classes.keys()) + ["__all_classes"] del _package_path, _import_submodules, _extract_classes_from_module
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/email.py
agent/tools/email.py
# # Copyright 2024 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 time from abc import ABC import json import smtplib import logging from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from email.utils import formataddr from agent.tools.base import ToolParamBase, ToolBase, ToolMeta from common.connection_utils import timeout class EmailParam(ToolParamBase): """ Define the Email component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "email", "description": "The email is a method of electronic communication for sending and receiving information through the Internet. This tool helps users to send emails to one person or to multiple recipients with support for CC, BCC, file attachments, and markdown-to-HTML conversion.", "parameters": { "to_email": { "type": "string", "description": "The target email address.", "default": "{sys.query}", "required": True }, "cc_email": { "type": "string", "description": "The other email addresses needs to be send to. Comma splited.", "default": "", "required": False }, "content": { "type": "string", "description": "The content of the email.", "default": "", "required": False }, "subject": { "type": "string", "description": "The subject/title of the email.", "default": "", "required": False } } } super().__init__() # Fixed configuration parameters self.smtp_server = "" # SMTP server address self.smtp_port = 465 # SMTP port self.email = "" # Sender email self.password = "" # Email authorization code self.sender_name = "" # Sender name def check(self): # Check required parameters self.check_empty(self.smtp_server, "SMTP Server") self.check_empty(self.email, "Email") self.check_empty(self.password, "Password") self.check_empty(self.sender_name, "Sender Name") def get_input_form(self) -> dict[str, dict]: return { "to_email": { "name": "To ", "type": "line" }, "subject": { "name": "Subject", "type": "line", "optional": True }, "cc_email": { "name": "CC To", "type": "line", "optional": True }, } class Email(ToolBase, ABC): component_name = "Email" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 60))) def _invoke(self, **kwargs): if self.check_if_canceled("Email processing"): return if not kwargs.get("to_email"): self.set_output("success", False) return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("Email processing"): return try: # Parse JSON string passed from upstream email_data = kwargs # Validate required fields if "to_email" not in email_data: self.set_output("_ERROR", "Missing required field: to_email") self.set_output("success", False) return False # Create email object msg = MIMEMultipart('alternative') # Properly handle sender name encoding msg['From'] = formataddr((str(Header(self._param.sender_name,'utf-8')), self._param.email)) msg['To'] = email_data["to_email"] if email_data.get("cc_email"): msg['Cc'] = email_data["cc_email"] msg['Subject'] = Header(email_data.get("subject", "No Subject"), 'utf-8').encode() # Use content from email_data or default content email_content = email_data.get("content", "No content provided") # msg.attach(MIMEText(email_content, 'plain', 'utf-8')) msg.attach(MIMEText(email_content, 'html', 'utf-8')) # Connect to SMTP server and send logging.info(f"Connecting to SMTP server {self._param.smtp_server}:{self._param.smtp_port}") if self.check_if_canceled("Email processing"): return context = smtplib.ssl.create_default_context() with smtplib.SMTP(self._param.smtp_server, self._param.smtp_port) as server: server.ehlo() server.starttls(context=context) server.ehlo() # Login logging.info(f"Attempting to login with email: {self._param.email}") server.login(self._param.email, self._param.password) # Get all recipient list recipients = [email_data["to_email"]] if email_data.get("cc_email"): recipients.extend(email_data["cc_email"].split(',')) # Send email logging.info(f"Sending email to recipients: {recipients}") if self.check_if_canceled("Email processing"): return try: server.send_message(msg, self._param.email, recipients) success = True except Exception as e: logging.error(f"Error during send_message: {str(e)}") # Try alternative method server.sendmail(self._param.email, recipients, msg.as_string()) success = True try: server.quit() except Exception as e: # Ignore errors when closing connection logging.warning(f"Non-fatal error during connection close: {str(e)}") self.set_output("success", success) return success except json.JSONDecodeError: error_msg = "Invalid JSON format in input" logging.error(error_msg) self.set_output("_ERROR", error_msg) self.set_output("success", False) return False except smtplib.SMTPAuthenticationError: error_msg = "SMTP Authentication failed. Please check your email and authorization code." logging.error(error_msg) self.set_output("_ERROR", error_msg) self.set_output("success", False) return False except smtplib.SMTPConnectError: error_msg = f"Failed to connect to SMTP server {self._param.smtp_server}:{self._param.smtp_port}" logging.error(error_msg) last_e = error_msg time.sleep(self._param.delay_after_error) except smtplib.SMTPException as e: error_msg = f"SMTP error occurred: {str(e)}" logging.error(error_msg) last_e = error_msg time.sleep(self._param.delay_after_error) except Exception as e: error_msg = f"Unexpected error: {str(e)}" logging.error(error_msg) self.set_output("_ERROR", error_msg) self.set_output("success", False) return False if last_e: self.set_output("_ERROR", str(last_e)) return False assert False, self.output() def thoughts(self) -> str: inputs = self.get_input() return """ To: {} Subject: {} Your email is on its wayโ€”sit tight! """.format(inputs.get("to_email", "-_-!"), inputs.get("subject", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/arxiv.py
agent/tools/arxiv.py
# # Copyright 2024 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 arxiv from agent.tools.base import ToolParamBase, ToolMeta, ToolBase from common.connection_utils import timeout class ArXivParam(ToolParamBase): """ Define the ArXiv component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "arxiv_search", "description": """arXiv is a free distribution service and an open-access archive for nearly 2.4 million scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics. Materials on this site are not peer-reviewed by arXiv.""", "parameters": { "query": { "type": "string", "description": "The search keywords to execute with arXiv. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True } } } super().__init__() self.top_n = 12 self.sort_by = 'submittedDate' def check(self): self.check_positive_integer(self.top_n, "Top N") self.check_valid_value(self.sort_by, "ArXiv Search Sort_by", ['submittedDate', 'lastUpdatedDate', 'relevance']) def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" } } class ArXiv(ToolBase, ABC): component_name = "ArXiv" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("ArXiv processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("ArXiv processing"): return try: sort_choices = {"relevance": arxiv.SortCriterion.Relevance, "lastUpdatedDate": arxiv.SortCriterion.LastUpdatedDate, 'submittedDate': arxiv.SortCriterion.SubmittedDate} arxiv_client = arxiv.Client() search = arxiv.Search( query=kwargs["query"], max_results=self._param.top_n, sort_by=sort_choices[self._param.sort_by] ) results = list(arxiv_client.results(search)) if self.check_if_canceled("ArXiv processing"): return self._retrieve_chunks(results, get_title=lambda r: r.title, get_url=lambda r: r.pdf_url, get_content=lambda r: r.summary) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("ArXiv processing"): return last_e = e logging.exception(f"ArXiv error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"ArXiv error: {last_e}" assert False, self.output() def thoughts(self) -> str: return """ Keywords: {} Looking for the most relevant articles. """.format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/base.py
agent/tools/base.py
# # Copyright 2024 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 re import time from copy import deepcopy import asyncio from functools import partial from typing import TypedDict, List, Any from agent.component.base import ComponentParamBase, ComponentBase from common.misc_utils import hash_str2int from rag.prompts.generator import kb_prompt from common.mcp_tool_call_conn import MCPToolCallSession, ToolCallSession from timeit import default_timer as timer class ToolParameter(TypedDict): type: str description: str displayDescription: str enum: List[str] required: bool class ToolMeta(TypedDict): name: str displayName: str description: str displayDescription: str parameters: dict[str, ToolParameter] class LLMToolPluginCallSession(ToolCallSession): def __init__(self, tools_map: dict[str, object], callback: partial): self.tools_map = tools_map self.callback = callback def tool_call(self, name: str, arguments: dict[str, Any]) -> Any: return asyncio.run(self.tool_call_async(name, arguments)) async def tool_call_async(self, name: str, arguments: dict[str, Any]) -> Any: assert name in self.tools_map, f"LLM tool {name} does not exist" st = timer() tool_obj = self.tools_map[name] if isinstance(tool_obj, MCPToolCallSession): resp = await asyncio.to_thread(tool_obj.tool_call, name, arguments, 60) else: if hasattr(tool_obj, "invoke_async") and asyncio.iscoroutinefunction(tool_obj.invoke_async): resp = await tool_obj.invoke_async(**arguments) else: resp = await asyncio.to_thread(tool_obj.invoke, **arguments) self.callback(name, arguments, resp, elapsed_time=timer()-st) return resp def get_tool_obj(self, name): return self.tools_map[name] class ToolParamBase(ComponentParamBase): def __init__(self): #self.meta:ToolMeta = None super().__init__() self._init_inputs() self._init_attr_by_meta() def _init_inputs(self): self.inputs = {} for k,p in self.meta["parameters"].items(): self.inputs[k] = deepcopy(p) def _init_attr_by_meta(self): for k,p in self.meta["parameters"].items(): if not hasattr(self, k): setattr(self, k, p.get("default")) def get_meta(self): params = {} for k, p in self.meta["parameters"].items(): params[k] = { "type": p["type"], "description": p["description"] } if "enum" in p: params[k]["enum"] = p["enum"] desc = self.meta["description"] if hasattr(self, "description"): desc = self.description function_name = self.meta["name"] if hasattr(self, "function_name"): function_name = self.function_name return { "type": "function", "function": { "name": function_name, "description": desc, "parameters": { "type": "object", "properties": params, "required": [k for k, p in self.meta["parameters"].items() if p["required"]] } } } class ToolBase(ComponentBase): def __init__(self, canvas, id, param: ComponentParamBase): from agent.canvas import Canvas # Local import to avoid cyclic dependency assert isinstance(canvas, Canvas), "canvas must be an instance of Canvas" self._canvas = canvas self._id = id self._param = param self._param.check() def get_meta(self) -> dict[str, Any]: return self._param.get_meta() def invoke(self, **kwargs): if self.check_if_canceled("Tool processing"): return self.set_output("_created_time", time.perf_counter()) try: res = self._invoke(**kwargs) except Exception as e: self._param.outputs["_ERROR"] = {"value": str(e)} logging.exception(e) res = str(e) self._param.debug_inputs = [] self.set_output("_elapsed_time", time.perf_counter() - self.output("_created_time")) return res async def invoke_async(self, **kwargs): """ Async wrapper for tool invocation. If `_invoke` is a coroutine, await it directly; otherwise run in a thread to avoid blocking. Mirrors the exception handling of `invoke`. """ if self.check_if_canceled("Tool processing"): return self.set_output("_created_time", time.perf_counter()) try: fn_async = getattr(self, "_invoke_async", None) if fn_async and asyncio.iscoroutinefunction(fn_async): res = await fn_async(**kwargs) elif asyncio.iscoroutinefunction(self._invoke): res = await self._invoke(**kwargs) else: res = await asyncio.to_thread(self._invoke, **kwargs) except Exception as e: self._param.outputs["_ERROR"] = {"value": str(e)} logging.exception(e) res = str(e) self._param.debug_inputs = [] self.set_output("_elapsed_time", time.perf_counter() - self.output("_created_time")) return res def _retrieve_chunks(self, res_list: list, get_title, get_url, get_content, get_score=None): chunks = [] aggs = [] for r in res_list: content = get_content(r) if not content: continue content = re.sub(r"!?\[[a-z]+\]\(data:image/png;base64,[ 0-9A-Za-z/_=+-]+\)", "", content) content = content[:10000] if not content: continue id = str(hash_str2int(content)) title = get_title(r) url = get_url(r) score = get_score(r) if get_score else 1 chunks.append({ "chunk_id": id, "content": content, "doc_id": id, "docnm_kwd": title, "similarity": score, "url": url }) aggs.append({ "doc_name": title, "doc_id": id, "count": 1, "url": url }) self._canvas.add_reference(chunks, aggs) self.set_output("formalized_content", "\n".join(kb_prompt({"chunks": chunks, "doc_aggs": aggs}, 200000, True))) def thoughts(self) -> str: return self._canvas.get_component_name(self._id) + " is running..."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/duckduckgo.py
agent/tools/duckduckgo.py
# # Copyright 2024 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 from duckduckgo_search import DDGS from agent.tools.base import ToolMeta, ToolParamBase, ToolBase from common.connection_utils import timeout class DuckDuckGoParam(ToolParamBase): """ Define the DuckDuckGo component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "duckduckgo_search", "description": "DuckDuckGo is a search engine focused on privacy. It offers search capabilities for web pages, images, and provides translation services. DuckDuckGo also features a private AI chat interface, providing users with an AI assistant that prioritizes data protection.", "parameters": { "query": { "type": "string", "description": "The search keywords to execute with DuckDuckGo. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True }, "channel": { "type": "string", "description": "default:general. The category of the search. `news` is useful for retrieving real-time updates, particularly about politics, sports, and major current events covered by mainstream media sources. `general` is for broader, more general-purpose searches that may include a wide range of sources.", "enum": ["general", "news"], "default": "general", "required": False, }, } } super().__init__() self.top_n = 10 self.channel = "text" def check(self): self.check_positive_integer(self.top_n, "Top N") self.check_valid_value(self.channel, "Web Search or News", ["text", "news"]) def get_input_form(self) -> dict[str, dict]: return { "query": { "name": "Query", "type": "line" }, "channel": { "name": "Channel", "type": "options", "value": "general", "options": ["general", "news"] } } class DuckDuckGo(ToolBase, ABC): component_name = "DuckDuckGo" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("DuckDuckGo processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("DuckDuckGo processing"): return try: if kwargs.get("topic", "general") == "general": with DDGS() as ddgs: if self.check_if_canceled("DuckDuckGo processing"): return # {'title': '', 'href': '', 'body': ''} duck_res = ddgs.text(kwargs["query"], max_results=self._param.top_n) if self.check_if_canceled("DuckDuckGo processing"): return self._retrieve_chunks(duck_res, get_title=lambda r: r["title"], get_url=lambda r: r.get("href", r.get("url")), get_content=lambda r: r["body"]) self.set_output("json", duck_res) return self.output("formalized_content") else: with DDGS() as ddgs: if self.check_if_canceled("DuckDuckGo processing"): return # {'date': '', 'title': '', 'body': '', 'url': '', 'image': '', 'source': ''} duck_res = ddgs.news(kwargs["query"], max_results=self._param.top_n) if self.check_if_canceled("DuckDuckGo processing"): return self._retrieve_chunks(duck_res, get_title=lambda r: r["title"], get_url=lambda r: r.get("href", r.get("url")), get_content=lambda r: r["body"]) self.set_output("json", duck_res) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("DuckDuckGo processing"): return last_e = e logging.exception(f"DuckDuckGo error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"DuckDuckGo error: {last_e}" assert False, self.output() def thoughts(self) -> str: return """ Keywords: {} Looking for the most relevant articles. """.format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/qweather.py
agent/tools/qweather.py
# # Copyright 2024 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. # from abc import ABC import pandas as pd import requests from agent.component.base import ComponentBase, ComponentParamBase class QWeatherParam(ComponentParamBase): """ Define the QWeather component parameters. """ def __init__(self): super().__init__() self.web_apikey = "xxx" self.lang = "zh" self.type = "weather" self.user_type = 'free' self.error_code = { "204": "The request was successful, but the region you are querying does not have the data you need at this time.", "400": "Request error, may contain incorrect request parameters or missing mandatory request parameters.", "401": "Authentication fails, possibly using the wrong KEY, wrong digital signature, wrong type of KEY (e.g. using the SDK's KEY to access the Web API).", "402": "Exceeded the number of accesses or the balance is not enough to support continued access to the service, you can recharge, upgrade the accesses or wait for the accesses to be reset.", "403": "No access, may be the binding PackageName, BundleID, domain IP address is inconsistent, or the data that requires additional payment.", "404": "The queried data or region does not exist.", "429": "Exceeded the limited QPM (number of accesses per minute), please refer to the QPM description", "500": "No response or timeout, interface service abnormality please contact us" } # Weather self.time_period = 'now' def check(self): self.check_empty(self.web_apikey, "BaiduFanyi APPID") 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(self.lang, "Use language", ['zh', 'zh-hant', 'en', 'de', 'es', 'fr', 'it', 'ja', 'ko', 'ru', 'hi', 'th', 'ar', 'pt', 'bn', 'ms', 'nl', 'el', 'la', 'sv', 'id', 'pl', 'tr', 'cs', 'et', 'vi', 'fil', 'fi', 'he', 'is', 'nb']) self.check_valid_value(self.time_period, "Time period", ['now', '3d', '7d', '10d', '15d', '30d']) class QWeather(ComponentBase, ABC): component_name = "QWeather" def _run(self, history, **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("") try: 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).json() if response["code"] == "200": location_id = response["location"][0]["id"] else: return QWeather.be_output("**Error**" + self._param.error_code[response["code"]]) 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 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).json() if self.check_if_canceled("Qweather processing"): return if response["code"] == "200": 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 response = requests.get(url=url).json() 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) else: return QWeather.be_output("**Error**" + self._param.error_code[response["code"]]) 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).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))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/github.py
agent/tools/github.py
# # Copyright 2024 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 ToolParamBase, ToolMeta, ToolBase from common.connection_utils import timeout class GitHubParam(ToolParamBase): """ Define the GitHub component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "github_search", "description": """GitHub repository search is a feature that enables users to find specific repositories on the GitHub platform. This search functionality allows users to locate projects, codebases, and other content hosted on GitHub based on various criteria.""", "parameters": { "query": { "type": "string", "description": "The search keywords to execute with GitHub. The keywords should be the most important words/terms(includes synonyms) from the original request.", "default": "{sys.query}", "required": True } } } super().__init__() 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" } } class GitHub(ToolBase, ABC): component_name = "GitHub" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) def _invoke(self, **kwargs): if self.check_if_canceled("GitHub processing"): return if not kwargs.get("query"): self.set_output("formalized_content", "") return "" last_e = "" for _ in range(self._param.max_retries+1): if self.check_if_canceled("GitHub processing"): return try: url = 'https://api.github.com/search/repositories?q=' + kwargs["query"] + '&sort=stars&order=desc&per_page=' + str( self._param.top_n) headers = {"Content-Type": "application/vnd.github+json", "X-GitHub-Api-Version": '2022-11-28'} response = requests.get(url=url, headers=headers).json() if self.check_if_canceled("GitHub processing"): return self._retrieve_chunks(response['items'], get_title=lambda r: r["name"], get_url=lambda r: r["html_url"], get_content=lambda r: str(r["description"]) + '\n stars:' + str(r['watchers'])) self.set_output("json", response['items']) return self.output("formalized_content") except Exception as e: if self.check_if_canceled("GitHub processing"): return last_e = e logging.exception(f"GitHub error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"GitHub error: {last_e}" assert False, self.output() def thoughts(self) -> str: return "Scanning GitHub repos related to `{}`.".format(self.get_input().get("query", "-_-!"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/tools/crawler.py
agent/tools/crawler.py
# # Copyright 2024 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. # from abc import ABC import asyncio from crawl4ai import AsyncWebCrawler from agent.tools.base import ToolParamBase, ToolBase class CrawlerParam(ToolParamBase): """ Define the Crawler component parameters. """ def __init__(self): super().__init__() self.proxy = None self.extract_type = "markdown" def check(self): self.check_valid_value(self.extract_type, "Type of content from the crawler", ['html', 'markdown', 'content']) class Crawler(ToolBase, ABC): component_name = "Crawler" def _run(self, history, **kwargs): from api.utils.web_utils import is_valid_url ans = self.get_input() ans = " - ".join(ans["content"]) if "content" in ans else "" if not is_valid_url(ans): return Crawler.be_output("URL not valid") try: result = asyncio.run(self.get_web(ans)) return Crawler.be_output(result) except Exception as e: return Crawler.be_output(f"An unexpected error occurred: {str(e)}") async def get_web(self, url): if self.check_if_canceled("Crawler async operation"): return proxy = self._param.proxy if self._param.proxy else None async with AsyncWebCrawler(verbose=True, proxy=proxy) as crawler: result = await crawler.arun( url=url, bypass_cache=True ) if self.check_if_canceled("Crawler async operation"): return if self._param.extract_type == 'html': return result.cleaned_html elif self._param.extract_type == 'markdown': return result.markdown elif self._param.extract_type == 'content': return result.extracted_content return result.markdown
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/test/client.py
agent/test/client.py
# # Copyright 2024 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 argparse import os from agent.canvas import Canvas from common import settings if __name__ == '__main__': parser = argparse.ArgumentParser() dsl_default_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "dsl_examples", "retrieval_and_generate.json", ) parser.add_argument('-s', '--dsl', default=dsl_default_path, help="input dsl", action='store', required=True) parser.add_argument('-t', '--tenant_id', default=False, help="Tenant ID", action='store', required=True) parser.add_argument('-m', '--stream', default=False, help="Stream output", action='store_true', required=False) args = parser.parse_args() settings.init_settings() canvas = Canvas(open(args.dsl, "r").read(), args.tenant_id) if canvas.get_prologue(): print(f"==================== Bot =====================\n> {canvas.get_prologue()}", end='') query = "" while True: canvas.reset(True) query = input("\n==================== User =====================\n> ") ans = canvas.run(query=query) print("==================== Bot =====================\n> ", end='') for ans in canvas.run(query=query): print(ans, end='\n', flush=True) print(canvas.path)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/varaiable_aggregator.py
agent/component/varaiable_aggregator.py
# # Copyright 2024 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. from typing import Any import os from common.connection_utils import timeout from agent.component.base import ComponentBase, ComponentParamBase class VariableAggregatorParam(ComponentParamBase): """ Parameters for VariableAggregator - groups: list of dicts {"group_name": str, "variables": [variable selectors]} """ def __init__(self): super().__init__() # each group expects: {"group_name": str, "variables": List[str]} self.groups = [] def check(self): self.check_empty(self.groups, "[VariableAggregator] groups") for g in self.groups: if not g.get("group_name"): raise ValueError("[VariableAggregator] group_name can not be empty!") if not g.get("variables"): raise ValueError( f"[VariableAggregator] variables of group `{g.get('group_name')}` can not be empty" ) if not isinstance(g.get("variables"), list): raise ValueError( f"[VariableAggregator] variables of group `{g.get('group_name')}` should be a list of strings" ) def get_input_form(self) -> dict[str, dict]: return { "variables": { "name": "Variables", "type": "list", } } class VariableAggregator(ComponentBase): component_name = "VariableAggregator" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 3))) def _invoke(self, **kwargs): # Group mode: for each group, pick the first available variable for group in self._param.groups: gname = group.get("group_name") # record candidate selectors within this group self.set_input_value(f"{gname}.variables", list(group.get("variables", []))) for selector in group.get("variables", []): val = self._canvas.get_variable_value(selector['value']) if val: self.set_output(gname, val) break @staticmethod def _to_object(value: Any) -> Any: # Try to convert value to serializable object if it has to_object() try: return value.to_object() # type: ignore[attr-defined] except Exception: return value def thoughts(self) -> str: return "Aggregating variables from canvas and grouping as configured."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/invoke.py
agent/component/invoke.py
# # Copyright 2024 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 json import logging import os import re import time from abc import ABC import requests from agent.component.base import ComponentBase, ComponentParamBase from common.connection_utils import timeout from deepdoc.parser import HtmlParser class InvokeParam(ComponentParamBase): """ Define the Crawler component parameters. """ def __init__(self): super().__init__() self.proxy = None self.headers = "" self.method = "get" self.variables = [] self.url = "" self.timeout = 60 self.clean_html = False self.datatype = "json" # New parameter to determine data posting type def check(self): self.check_valid_value(self.method.lower(), "Type of content from the crawler", ["get", "post", "put"]) self.check_empty(self.url, "End point URL") self.check_positive_integer(self.timeout, "Timeout time in second") self.check_boolean(self.clean_html, "Clean HTML") self.check_valid_value(self.datatype.lower(), "Data post type", ["json", "formdata"]) # Check for valid datapost value class Invoke(ComponentBase, ABC): component_name = "Invoke" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 3))) def _invoke(self, **kwargs): if self.check_if_canceled("Invoke processing"): return args = {} for para in self._param.variables: if para.get("value"): args[para["key"]] = para["value"] else: args[para["key"]] = self._canvas.get_variable_value(para["ref"]) url = self._param.url.strip() def replace_variable(match): var_name = match.group(1) try: value = self._canvas.get_variable_value(var_name) return str(value or "") except Exception: return "" # {base_url} or {component_id@variable_name} url = re.sub(r"\{([a-zA-Z_][a-zA-Z0-9_.@-]*)\}", replace_variable, url) if url.find("http") != 0: url = "http://" + url method = self._param.method.lower() headers = {} if self._param.headers: headers = json.loads(self._param.headers) proxies = None if re.sub(r"https?:?/?/?", "", self._param.proxy): proxies = {"http": self._param.proxy, "https": self._param.proxy} last_e = "" for _ in range(self._param.max_retries + 1): if self.check_if_canceled("Invoke processing"): return try: if method == "get": response = requests.get(url=url, params=args, headers=headers, proxies=proxies, timeout=self._param.timeout) if self._param.clean_html: sections = HtmlParser()(None, response.content) self.set_output("result", "\n".join(sections)) else: self.set_output("result", response.text) if method == "put": if self._param.datatype.lower() == "json": response = requests.put(url=url, json=args, headers=headers, proxies=proxies, timeout=self._param.timeout) else: response = requests.put(url=url, data=args, headers=headers, proxies=proxies, timeout=self._param.timeout) if self._param.clean_html: sections = HtmlParser()(None, response.content) self.set_output("result", "\n".join(sections)) else: self.set_output("result", response.text) if method == "post": if self._param.datatype.lower() == "json": response = requests.post(url=url, json=args, headers=headers, proxies=proxies, timeout=self._param.timeout) else: response = requests.post(url=url, data=args, headers=headers, proxies=proxies, timeout=self._param.timeout) if self._param.clean_html: self.set_output("result", "\n".join(sections)) else: self.set_output("result", response.text) return self.output("result") except Exception as e: if self.check_if_canceled("Invoke processing"): return last_e = e logging.exception(f"Http request error: {e}") time.sleep(self._param.delay_after_error) if last_e: self.set_output("_ERROR", str(last_e)) return f"Http request error: {last_e}" assert False, self.output() def thoughts(self) -> str: return "Waiting for the server respond..."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/data_operations.py
agent/component/data_operations.py
# # Copyright 2024 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. # from abc import ABC import ast import os from agent.component.base import ComponentBase, ComponentParamBase from api.utils.api_utils import timeout class DataOperationsParam(ComponentParamBase): """ Define the Data Operations component parameters. """ def __init__(self): super().__init__() self.query = [] self.operations = "literal_eval" self.select_keys = [] self.filter_values=[] self.updates=[] self.remove_keys=[] self.rename_keys=[] self.outputs = { "result": { "value": [], "type": "Array of Object" } } def check(self): self.check_valid_value(self.operations, "Support operations", ["select_keys", "literal_eval","combine","filter_values","append_or_update","remove_keys","rename_keys"]) class DataOperations(ComponentBase,ABC): component_name = "DataOperations" def get_input_form(self) -> dict[str, dict]: return { k: {"name": o.get("name", ""), "type": "line"} for input_item in (self._param.query or []) for k, o in self.get_input_elements_from_text(input_item).items() } @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): self.input_objects=[] inputs = getattr(self._param, "query", None) if not isinstance(inputs, (list, tuple)): inputs = [inputs] for input_ref in inputs: input_object=self._canvas.get_variable_value(input_ref) self.set_input_value(input_ref, input_object) if input_object is None: continue if isinstance(input_object,dict): self.input_objects.append(input_object) elif isinstance(input_object,list): self.input_objects.extend(x for x in input_object if isinstance(x, dict)) else: continue if self._param.operations == "select_keys": self._select_keys() elif self._param.operations == "recursive_eval": self._literal_eval() elif self._param.operations == "combine": self._combine() elif self._param.operations == "filter_values": self._filter_values() elif self._param.operations == "append_or_update": self._append_or_update() elif self._param.operations == "remove_keys": self._remove_keys() else: self._rename_keys() def _select_keys(self): filter_criteria: list[str] = self._param.select_keys results = [{key: value for key, value in data_dict.items() if key in filter_criteria} for data_dict in self.input_objects] self.set_output("result", results) def _recursive_eval(self, data): if isinstance(data, dict): return {k: self.recursive_eval(v) for k, v in data.items()} if isinstance(data, list): return [self.recursive_eval(item) for item in data] if isinstance(data, str): try: if ( data.strip().startswith(("{", "[", "(", "'", '"')) or data.strip().lower() in ("true", "false", "none") or data.strip().replace(".", "").isdigit() ): return ast.literal_eval(data) except (ValueError, SyntaxError, TypeError, MemoryError): return data else: return data return data def _literal_eval(self): self.set_output("result", self._recursive_eval(self.input_objects)) def _combine(self): result={} for obj in self.input_objects: for key, value in obj.items(): if key not in result: result[key] = value elif isinstance(result[key], list): if isinstance(value, list): result[key].extend(value) else: result[key].append(value) else: result[key] = ( [result[key], value] if not isinstance(value, list) else [result[key], *value] ) self.set_output("result", result) def norm(self,v): s = "" if v is None else str(v) return s def match_rule(self, obj, rule): key = rule.get("key") op = (rule.get("operator") or "equals").lower() target = self.norm(rule.get("value")) target = self._canvas.get_value_with_variable(target) or target if key not in obj: return False val = obj.get(key, None) v = self.norm(val) if op == "=": return v == target if op == "โ‰ ": return v != target if op == "contains": return target in v if op == "start with": return v.startswith(target) if op == "end with": return v.endswith(target) return False def _filter_values(self): results=[] rules = (getattr(self._param, "filter_values", None) or []) for obj in self.input_objects: if not rules: results.append(obj) continue if all(self.match_rule(obj, r) for r in rules): results.append(obj) self.set_output("result", results) def _append_or_update(self): results=[] updates = getattr(self._param, "updates", []) or [] for obj in self.input_objects: new_obj = dict(obj) for item in updates: if not isinstance(item, dict): continue k = (item.get("key") or "").strip() if not k: continue new_obj[k] = self._canvas.get_value_with_variable(item.get("value")) or item.get("value") results.append(new_obj) self.set_output("result", results) def _remove_keys(self): results = [] remove_keys = getattr(self._param, "remove_keys", []) or [] for obj in (self.input_objects or []): new_obj = dict(obj) for k in remove_keys: if not isinstance(k, str): continue new_obj.pop(k, None) results.append(new_obj) self.set_output("result", results) def _rename_keys(self): results = [] rename_pairs = getattr(self._param, "rename_keys", []) or [] for obj in (self.input_objects or []): new_obj = dict(obj) for pair in rename_pairs: if not isinstance(pair, dict): continue old = (pair.get("old_key") or "").strip() new = (pair.get("new_key") or "").strip() if not old or not new or old == new: continue if old in new_obj: new_obj[new] = new_obj.pop(old) results.append(new_obj) self.set_output("result", results) def thoughts(self) -> str: return "DataOperation in progress"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/fillup.py
agent/component/fillup.py
# # Copyright 2024 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 json import re from functools import partial from agent.component.base import ComponentParamBase, ComponentBase from api.db.services.file_service import FileService class UserFillUpParam(ComponentParamBase): def __init__(self): super().__init__() self.enable_tips = True self.tips = "Please fill up the form" def check(self) -> bool: return True class UserFillUp(ComponentBase): component_name = "UserFillUp" def _invoke(self, **kwargs): if self.check_if_canceled("UserFillUp processing"): return if self._param.enable_tips: content = self._param.tips for k, v in self.get_input_elements_from_text(self._param.tips).items(): v = v["value"] ans = "" if isinstance(v, partial): for t in v(): ans += t elif isinstance(v, list): ans = ",".join([str(vv) for vv in v]) elif not isinstance(v, str): try: ans = json.dumps(v, ensure_ascii=False) except Exception: pass else: ans = v if not ans: ans = "" content = re.sub(r"\{%s\}"%k, ans, content) self.set_output("tips", content) for k, v in kwargs.get("inputs", {}).items(): if self.check_if_canceled("UserFillUp processing"): return if isinstance(v, dict) and v.get("type", "").lower().find("file") >=0: if v.get("optional") and v.get("value", None) is None: v = None else: v = FileService.get_files([v["value"]]) else: v = v.get("value") self.set_output(k, v) def thoughts(self) -> str: return "Waiting for your input..."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/exit_loop.py
agent/component/exit_loop.py
# # Copyright 2024 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. # from abc import ABC from agent.component.base import ComponentBase, ComponentParamBase class ExitLoopParam(ComponentParamBase, ABC): def check(self): return True class ExitLoop(ComponentBase, ABC): component_name = "ExitLoop" def _invoke(self, **kwargs): pass def thoughts(self) -> str: return ""
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/llm.py
agent/component/llm.py
# # Copyright 2024 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 asyncio import json import logging import os import re from copy import deepcopy from typing import Any, AsyncGenerator import json_repair from functools import partial from common.constants import LLMType from api.db.services.llm_service import LLMBundle from api.db.services.tenant_llm_service import TenantLLMService from agent.component.base import ComponentBase, ComponentParamBase from common.connection_utils import timeout from rag.prompts.generator import tool_call_summary, message_fit_in, citation_prompt, structured_output_prompt class LLMParam(ComponentParamBase): """ Define the LLM component parameters. """ def __init__(self): super().__init__() self.llm_id = "" self.sys_prompt = "" self.prompts = [{"role": "user", "content": "{sys.query}"}] self.max_tokens = 0 self.temperature = 0 self.top_p = 0 self.presence_penalty = 0 self.frequency_penalty = 0 self.output_structure = None self.cite = True self.visual_files_var = None def check(self): self.check_decimal_float(float(self.temperature), "[Agent] Temperature") self.check_decimal_float(float(self.presence_penalty), "[Agent] Presence penalty") self.check_decimal_float(float(self.frequency_penalty), "[Agent] Frequency penalty") self.check_nonnegative_number(int(self.max_tokens), "[Agent] Max tokens") self.check_decimal_float(float(self.top_p), "[Agent] Top P") self.check_empty(self.llm_id, "[Agent] LLM") self.check_empty(self.prompts, "[Agent] User prompt") def gen_conf(self): conf = {} def get_attr(nm): try: return getattr(self, nm) except Exception: pass if int(self.max_tokens) > 0 and get_attr("maxTokensEnabled"): conf["max_tokens"] = int(self.max_tokens) if float(self.temperature) > 0 and get_attr("temperatureEnabled"): conf["temperature"] = float(self.temperature) if float(self.top_p) > 0 and get_attr("topPEnabled"): conf["top_p"] = float(self.top_p) if float(self.presence_penalty) > 0 and get_attr("presencePenaltyEnabled"): conf["presence_penalty"] = float(self.presence_penalty) if float(self.frequency_penalty) > 0 and get_attr("frequencyPenaltyEnabled"): conf["frequency_penalty"] = float(self.frequency_penalty) return conf class LLM(ComponentBase): component_name = "LLM" def __init__(self, canvas, component_id, param: ComponentParamBase): super().__init__(canvas, component_id, param) self.chat_mdl = LLMBundle(self._canvas.get_tenant_id(), TenantLLMService.llm_id2llm_type(self._param.llm_id), self._param.llm_id, max_retries=self._param.max_retries, retry_interval=self._param.delay_after_error ) self.imgs = [] def get_input_form(self) -> dict[str, dict]: res = {} for k, v in self.get_input_elements().items(): res[k] = { "type": "line", "name": v["name"] } return res def get_input_elements(self) -> dict[str, Any]: res = self.get_input_elements_from_text(self._param.sys_prompt) if isinstance(self._param.prompts, str): self._param.prompts = [{"role": "user", "content": self._param.prompts}] for prompt in self._param.prompts: d = self.get_input_elements_from_text(prompt["content"]) res.update(d) return res def set_debug_inputs(self, inputs: dict[str, dict]): self._param.debug_inputs = inputs def add2system_prompt(self, txt): self._param.sys_prompt += txt def _sys_prompt_and_msg(self, msg, args): if isinstance(self._param.prompts, str): self._param.prompts = [{"role": "user", "content": self._param.prompts}] for p in self._param.prompts: if msg and msg[-1]["role"] == p["role"]: continue p = deepcopy(p) p["content"] = self.string_format(p["content"], args) msg.append(p) return msg, self.string_format(self._param.sys_prompt, args) def _prepare_prompt_variables(self): if self._param.visual_files_var: self.imgs = self._canvas.get_variable_value(self._param.visual_files_var) if not self.imgs: self.imgs = [] self.imgs = [img for img in self.imgs if img[:len("data:image/")] == "data:image/"] if self.imgs and TenantLLMService.llm_id2llm_type(self._param.llm_id) == LLMType.CHAT.value: self.chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.IMAGE2TEXT.value, self._param.llm_id, max_retries=self._param.max_retries, retry_interval=self._param.delay_after_error ) args = {} vars = self.get_input_elements() if not self._param.debug_inputs else self._param.debug_inputs for k, o in vars.items(): args[k] = o["value"] if not isinstance(args[k], str): try: args[k] = json.dumps(args[k], ensure_ascii=False) except Exception: args[k] = str(args[k]) self.set_input_value(k, args[k]) msg, sys_prompt = self._sys_prompt_and_msg(self._canvas.get_history(self._param.message_history_window_size)[:-1], args) user_defined_prompt, sys_prompt = self._extract_prompts(sys_prompt) if self._param.cite and self._canvas.get_reference()["chunks"]: sys_prompt += citation_prompt(user_defined_prompt) return sys_prompt, msg, user_defined_prompt def _extract_prompts(self, sys_prompt): pts = {} for tag in ["TASK_ANALYSIS", "PLAN_GENERATION", "REFLECTION", "CONTEXT_SUMMARY", "CONTEXT_RANKING", "CITATION_GUIDELINES"]: r = re.search(rf"<{tag}>(.*?)</{tag}>", sys_prompt, flags=re.DOTALL|re.IGNORECASE) if not r: continue pts[tag.lower()] = r.group(1) sys_prompt = re.sub(rf"<{tag}>(.*?)</{tag}>", "", sys_prompt, flags=re.DOTALL|re.IGNORECASE) return pts, sys_prompt async def _generate_async(self, msg: list[dict], **kwargs) -> str: if not self.imgs: return await self.chat_mdl.async_chat(msg[0]["content"], msg[1:], self._param.gen_conf(), **kwargs) return await self.chat_mdl.async_chat(msg[0]["content"], msg[1:], self._param.gen_conf(), images=self.imgs, **kwargs) async def _generate_streamly(self, msg: list[dict], **kwargs) -> AsyncGenerator[str, None]: async def delta_wrapper(txt_iter): ans = "" last_idx = 0 endswith_think = False def delta(txt): nonlocal ans, last_idx, endswith_think delta_ans = txt[last_idx:] ans = txt if delta_ans.find("<think>") == 0: last_idx += len("<think>") return "<think>" elif delta_ans.find("<think>") > 0: delta_ans = txt[last_idx:last_idx + delta_ans.find("<think>")] last_idx += delta_ans.find("<think>") return delta_ans elif delta_ans.endswith("</think>"): endswith_think = True elif endswith_think: endswith_think = False return "</think>" last_idx = len(ans) if ans.endswith("</think>"): last_idx -= len("</think>") return re.sub(r"(<think>|</think>)", "", delta_ans) async for t in txt_iter: yield delta(t) if not self.imgs: async for t in delta_wrapper(self.chat_mdl.async_chat_streamly(msg[0]["content"], msg[1:], self._param.gen_conf(), **kwargs)): yield t return async for t in delta_wrapper(self.chat_mdl.async_chat_streamly(msg[0]["content"], msg[1:], self._param.gen_conf(), images=self.imgs, **kwargs)): yield t async def _stream_output_async(self, prompt, msg): _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(self.chat_mdl.max_length * 0.97)) answer = "" last_idx = 0 endswith_think = False def delta(txt): nonlocal answer, last_idx, endswith_think delta_ans = txt[last_idx:] answer = txt if delta_ans.find("<think>") == 0: last_idx += len("<think>") return "<think>" elif delta_ans.find("<think>") > 0: delta_ans = txt[last_idx:last_idx + delta_ans.find("<think>")] last_idx += delta_ans.find("<think>") return delta_ans elif delta_ans.endswith("</think>"): endswith_think = True elif endswith_think: endswith_think = False return "</think>" last_idx = len(answer) if answer.endswith("</think>"): last_idx -= len("</think>") return re.sub(r"(<think>|</think>)", "", delta_ans) stream_kwargs = {"images": self.imgs} if self.imgs else {} async for ans in self.chat_mdl.async_chat_streamly(msg[0]["content"], msg[1:], self._param.gen_conf(), **stream_kwargs): if self.check_if_canceled("LLM streaming"): return if isinstance(ans, int): continue if ans.find("**ERROR**") >= 0: if self.get_exception_default_value(): self.set_output("content", self.get_exception_default_value()) yield self.get_exception_default_value() else: self.set_output("_ERROR", ans) return yield delta(ans) self.set_output("content", answer) @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) async def _invoke_async(self, **kwargs): if self.check_if_canceled("LLM processing"): return def clean_formated_answer(ans: str) -> str: ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL) ans = re.sub(r"^.*```json", "", ans, flags=re.DOTALL) return re.sub(r"```\n*$", "", ans, flags=re.DOTALL) prompt, msg, _ = self._prepare_prompt_variables() error: str = "" output_structure = None try: output_structure = self._param.outputs["structured"] except Exception: pass if output_structure and isinstance(output_structure, dict) and output_structure.get("properties") and len(output_structure["properties"]) > 0: schema = json.dumps(output_structure, ensure_ascii=False, indent=2) prompt_with_schema = prompt + structured_output_prompt(schema) for _ in range(self._param.max_retries + 1): if self.check_if_canceled("LLM processing"): return _, msg_fit = message_fit_in( [{"role": "system", "content": prompt_with_schema}, *deepcopy(msg)], int(self.chat_mdl.max_length * 0.97), ) error = "" ans = await self._generate_async(msg_fit) msg_fit.pop(0) if ans.find("**ERROR**") >= 0: logging.error(f"LLM response error: {ans}") error = ans continue try: self.set_output("structured", json_repair.loads(clean_formated_answer(ans))) return except Exception: msg_fit.append({"role": "user", "content": "The answer can't not be parsed as JSON"}) error = "The answer can't not be parsed as JSON" if error: self.set_output("_ERROR", error) return downstreams = self._canvas.get_component(self._id)["downstream"] if self._canvas.get_component(self._id) else [] ex = self.exception_handler() if any([self._canvas.get_component_obj(cid).component_name.lower() == "message" for cid in downstreams]) and not ( ex and ex["goto"] ): self.set_output("content", partial(self._stream_output_async, prompt, deepcopy(msg))) return error = "" for _ in range(self._param.max_retries + 1): if self.check_if_canceled("LLM processing"): return _, msg_fit = message_fit_in( [{"role": "system", "content": prompt}, *deepcopy(msg)], int(self.chat_mdl.max_length * 0.97) ) error = "" ans = await self._generate_async(msg_fit) msg_fit.pop(0) if ans.find("**ERROR**") >= 0: logging.error(f"LLM response error: {ans}") error = ans continue self.set_output("content", ans) break if error: if self.get_exception_default_value(): self.set_output("content", self.get_exception_default_value()) else: self.set_output("_ERROR", error) @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): return asyncio.run(self._invoke_async(**kwargs)) async def add_memory(self, user:str, assist:str, func_name: str, params: dict, results: str, user_defined_prompt:dict={}): summ = await tool_call_summary(self.chat_mdl, func_name, params, results, user_defined_prompt) logging.info(f"[MEMORY]: {summ}") self._canvas.add_memory(user, assist, summ) def thoughts(self) -> str: _, msg,_ = self._prepare_prompt_variables() return "โŒ›Give me a momentโ€”starting from: \n\n" + re.sub(r"(User's query:|[\\]+)", '', msg[-1]['content'], flags=re.DOTALL) + "\n\nIโ€™ll figure out our best next move."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/switch.py
agent/component/switch.py
# # Copyright 2024 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 numbers import os from abc import ABC from typing import Any from agent.component.base import ComponentBase, ComponentParamBase from common.connection_utils import timeout class SwitchParam(ComponentParamBase): """ Define the Switch component parameters. """ def __init__(self): super().__init__() """ { "logical_operator" : "and | or" "items" : [ {"cpn_id": "categorize:0", "operator": "contains", "value": ""}, {"cpn_id": "categorize:0", "operator": "contains", "value": ""},...], "to": "" } """ self.conditions = [] self.end_cpn_ids = [] self.operators = ['contains', 'not contains', 'start with', 'end with', 'empty', 'not empty', '=', 'โ‰ ', '>', '<', 'โ‰ฅ', 'โ‰ค'] def check(self): self.check_empty(self.conditions, "[Switch] conditions") for cond in self.conditions: if not cond["to"]: raise ValueError("[Switch] 'To' can not be empty!") self.check_empty(self.end_cpn_ids, "[Switch] the ELSE/Other destination can not be empty.") def get_input_form(self) -> dict[str, dict]: return { "urls": { "name": "URLs", "type": "line" } } class Switch(ComponentBase, ABC): component_name = "Switch" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 3))) def _invoke(self, **kwargs): if self.check_if_canceled("Switch processing"): return for cond in self._param.conditions: if self.check_if_canceled("Switch processing"): return res = [] for item in cond["items"]: if self.check_if_canceled("Switch processing"): return if not item["cpn_id"]: continue cpn_v = self._canvas.get_variable_value(item["cpn_id"]) self.set_input_value(item["cpn_id"], cpn_v) operatee = item.get("value", "") if isinstance(cpn_v, numbers.Number): operatee = float(operatee) res.append(self.process_operator(cpn_v, item["operator"], operatee)) if cond["logical_operator"] != "and" and any(res): self.set_output("next", [self._canvas.get_component_name(cpn_id) for cpn_id in cond["to"]]) self.set_output("_next", cond["to"]) return if all(res): self.set_output("next", [self._canvas.get_component_name(cpn_id) for cpn_id in cond["to"]]) self.set_output("_next", cond["to"]) return self.set_output("next", [self._canvas.get_component_name(cpn_id) for cpn_id in self._param.end_cpn_ids]) self.set_output("_next", self._param.end_cpn_ids) def process_operator(self, input: Any, operator: str, value: Any) -> bool: if operator == "contains": return True if value.lower() in input.lower() else False elif operator == "not contains": return True if value.lower() not in input.lower() else False elif operator == "start with": return True if input.lower().startswith(value.lower()) else False elif operator == "end with": return True if input.lower().endswith(value.lower()) else False elif operator == "empty": return True if not input else False elif operator == "not empty": return True if input else False elif operator == "=": return True if input == value else False elif operator == "โ‰ ": return True if input != value else False elif operator == ">": try: return True if float(input) > float(value) else False except Exception: return True if input > value else False elif operator == "<": try: return True if float(input) < float(value) else False except Exception: return True if input < value else False elif operator == "โ‰ฅ": try: return True if float(input) >= float(value) else False except Exception: return True if input >= value else False elif operator == "โ‰ค": try: return True if float(input) <= float(value) else False except Exception: return True if input <= value else False raise ValueError('Not supported operator' + operator) def thoughts(self) -> str: return "Iโ€™m weighing a few options and will pick the next step shortly."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/docs_generator.py
agent/component/docs_generator.py
import json import os import re import base64 from datetime import datetime from abc import ABC from io import BytesIO from typing import Optional from functools import partial from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, TableStyle, LongTable from reportlab.lib import colors from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.cidfonts import UnicodeCIDFont from agent.component.base import ComponentParamBase from api.utils.api_utils import timeout from .message import Message class PDFGeneratorParam(ComponentParamBase): """ Define the PDF Generator component parameters. """ def __init__(self): super().__init__() # Output format self.output_format = "pdf" # pdf, docx, txt # Content inputs self.content = "" self.title = "" self.subtitle = "" self.header_text = "" self.footer_text = "" # Images self.logo_image = "" # base64 or file path self.logo_position = "left" # left, center, right self.logo_width = 2.0 # inches self.logo_height = 1.0 # inches # Styling self.font_family = "Helvetica" # Helvetica, Times-Roman, Courier self.font_size = 12 self.title_font_size = 24 self.heading1_font_size = 18 self.heading2_font_size = 16 self.heading3_font_size = 14 self.text_color = "#000000" self.title_color = "#000000" # Page settings self.page_size = "A4" self.orientation = "portrait" # portrait, landscape self.margin_top = 1.0 # inches self.margin_bottom = 1.0 self.margin_left = 1.0 self.margin_right = 1.0 self.line_spacing = 1.2 # Output settings self.filename = "" self.output_directory = "/tmp/pdf_outputs" self.add_page_numbers = True self.add_timestamp = True # Advanced features self.watermark_text = "" self.enable_toc = False self.outputs = { "file_path": {"value": "", "type": "string"}, "pdf_base64": {"value": "", "type": "string"}, "download": {"value": "", "type": "string"}, "success": {"value": False, "type": "boolean"} } def check(self): self.check_empty(self.content, "[PDFGenerator] Content") self.check_valid_value(self.output_format, "[PDFGenerator] Output format", ["pdf", "docx", "txt"]) self.check_valid_value(self.logo_position, "[PDFGenerator] Logo position", ["left", "center", "right"]) self.check_valid_value(self.font_family, "[PDFGenerator] Font family", ["Helvetica", "Times-Roman", "Courier", "Helvetica-Bold", "Times-Bold"]) self.check_valid_value(self.page_size, "[PDFGenerator] Page size", ["A4", "Letter"]) self.check_valid_value(self.orientation, "[PDFGenerator] Orientation", ["portrait", "landscape"]) self.check_positive_number(self.font_size, "[PDFGenerator] Font size") self.check_positive_number(self.margin_top, "[PDFGenerator] Margin top") class PDFGenerator(Message, ABC): component_name = "PDFGenerator" # Track if Unicode fonts have been registered _unicode_fonts_registered = False _unicode_font_name = None _unicode_font_bold_name = None @classmethod def _reset_font_cache(cls): """Reset font registration cache - useful for testing""" cls._unicode_fonts_registered = False cls._unicode_font_name = None cls._unicode_font_bold_name = None @classmethod def _register_unicode_fonts(cls): """Register Unicode-compatible fonts for multi-language support. Uses CID fonts (STSong-Light) for reliable CJK rendering as TTF fonts have issues with glyph mapping in some ReportLab versions. """ # If already registered successfully, return True if cls._unicode_fonts_registered and cls._unicode_font_name is not None: return True # Reset and try again if previous registration failed cls._unicode_fonts_registered = True cls._unicode_font_name = None cls._unicode_font_bold_name = None # Use CID fonts for reliable CJK support # These are built into ReportLab and work reliably across all platforms cid_fonts = [ 'STSong-Light', # Simplified Chinese 'HeiseiMin-W3', # Japanese 'HYSMyeongJo-Medium', # Korean ] for cid_font in cid_fonts: try: pdfmetrics.registerFont(UnicodeCIDFont(cid_font)) cls._unicode_font_name = cid_font cls._unicode_font_bold_name = cid_font # CID fonts don't have bold variants print(f"Registered CID font: {cid_font}") break except Exception as e: print(f"Failed to register CID font {cid_font}: {e}") continue # If CID fonts fail, try TTF fonts as fallback if not cls._unicode_font_name: font_paths = [ '/usr/share/fonts/truetype/freefont/FreeSans.ttf', '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', ] for font_path in font_paths: if os.path.exists(font_path): try: pdfmetrics.registerFont(TTFont('UnicodeFont', font_path)) cls._unicode_font_name = 'UnicodeFont' cls._unicode_font_bold_name = 'UnicodeFont' print(f"Registered TTF font from: {font_path}") # Register font family from reportlab.pdfbase.pdfmetrics import registerFontFamily registerFontFamily('UnicodeFont', normal='UnicodeFont', bold='UnicodeFont') break except Exception as e: print(f"Failed to register TTF font {font_path}: {e}") continue return cls._unicode_font_name is not None @staticmethod def _needs_unicode_font(text: str) -> bool: """Check if text contains CJK or other complex scripts that need special fonts. Standard PDF fonts (Helvetica, Times, Courier) support: - Basic Latin, Extended Latin, Cyrillic, Greek CID fonts are needed for: - CJK (Chinese, Japanese, Korean) - Arabic, Hebrew (RTL scripts) - Thai, Hindi, and other Indic scripts """ if not text: return False for char in text: code = ord(char) # CJK Unified Ideographs and related ranges if 0x4E00 <= code <= 0x9FFF: # CJK Unified Ideographs return True if 0x3400 <= code <= 0x4DBF: # CJK Extension A return True if 0x3000 <= code <= 0x303F: # CJK Symbols and Punctuation return True if 0x3040 <= code <= 0x309F: # Hiragana return True if 0x30A0 <= code <= 0x30FF: # Katakana return True if 0xAC00 <= code <= 0xD7AF: # Hangul Syllables return True if 0x1100 <= code <= 0x11FF: # Hangul Jamo return True # Arabic and Hebrew (RTL scripts) if 0x0600 <= code <= 0x06FF: # Arabic return True if 0x0590 <= code <= 0x05FF: # Hebrew return True # Indic scripts if 0x0900 <= code <= 0x097F: # Devanagari (Hindi) return True if 0x0E00 <= code <= 0x0E7F: # Thai return True return False def _get_font_for_content(self, content: str) -> tuple: """Get appropriate font based on content, returns (regular_font, bold_font)""" if self._needs_unicode_font(content): if self._register_unicode_fonts() and self._unicode_font_name: return (self._unicode_font_name, self._unicode_font_bold_name or self._unicode_font_name) else: print("Warning: Content contains non-Latin characters but no Unicode font available") # Fall back to configured font return (self._param.font_family, self._get_bold_font_name()) def _get_active_font(self) -> str: """Get the currently active font (Unicode or configured)""" return getattr(self, '_active_font', self._param.font_family) def _get_active_bold_font(self) -> str: """Get the currently active bold font (Unicode or configured)""" return getattr(self, '_active_bold_font', self._get_bold_font_name()) def _get_bold_font_name(self) -> str: """Get the correct bold variant of the current font family""" font_map = { 'Helvetica': 'Helvetica-Bold', 'Times-Roman': 'Times-Bold', 'Courier': 'Courier-Bold', } font_family = getattr(self._param, 'font_family', 'Helvetica') if 'Bold' in font_family: return font_family return font_map.get(font_family, 'Helvetica-Bold') def get_input_form(self) -> dict[str, dict]: return { "content": { "name": "Content", "type": "text" }, "title": { "name": "Title", "type": "line" }, "subtitle": { "name": "Subtitle", "type": "line" } } @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): import traceback try: # Get content from parameters (which may contain variable references) content = self._param.content or "" title = self._param.title or "" subtitle = self._param.subtitle or "" # Log PDF generation start print(f"Starting PDF generation for title: {title}, content length: {len(content)} chars") # Resolve variable references in content using canvas if content and self._canvas.is_reff(content): # Extract the variable reference and get its value import re matches = re.findall(self.variable_ref_patt, content, flags=re.DOTALL) for match in matches: try: var_value = self._canvas.get_variable_value(match) if var_value: # Handle partial (streaming) content if isinstance(var_value, partial): resolved_content = "" for chunk in var_value(): resolved_content += chunk content = content.replace("{" + match + "}", resolved_content) else: content = content.replace("{" + match + "}", str(var_value)) except Exception as e: print(f"Error resolving variable {match}: {str(e)}") content = content.replace("{" + match + "}", f"[ERROR: {str(e)}]") # Also process with get_kwargs for any remaining variables if content: try: content, _ = self.get_kwargs(content, kwargs) except Exception as e: print(f"Error processing content with get_kwargs: {str(e)}") # Process template variables in title if title and self._canvas.is_reff(title): try: matches = re.findall(self.variable_ref_patt, title, flags=re.DOTALL) for match in matches: var_value = self._canvas.get_variable_value(match) if var_value: title = title.replace("{" + match + "}", str(var_value)) except Exception as e: print(f"Error processing title variables: {str(e)}") if title: try: title, _ = self.get_kwargs(title, kwargs) except Exception: pass # Process template variables in subtitle if subtitle and self._canvas.is_reff(subtitle): try: matches = re.findall(self.variable_ref_patt, subtitle, flags=re.DOTALL) for match in matches: var_value = self._canvas.get_variable_value(match) if var_value: subtitle = subtitle.replace("{" + match + "}", str(var_value)) except Exception as e: print(f"Error processing subtitle variables: {str(e)}") if subtitle: try: subtitle, _ = self.get_kwargs(subtitle, kwargs) except Exception: pass # If content is still empty, check if it was passed directly if not content: content = kwargs.get("content", "") # Generate document based on format try: output_format = self._param.output_format or "pdf" if output_format == "pdf": file_path, doc_base64 = self._generate_pdf(content, title, subtitle) mime_type = "application/pdf" elif output_format == "docx": file_path, doc_base64 = self._generate_docx(content, title, subtitle) mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" elif output_format == "txt": file_path, doc_base64 = self._generate_txt(content, title, subtitle) mime_type = "text/plain" else: raise Exception(f"Unsupported output format: {output_format}") filename = os.path.basename(file_path) # Verify the file was created and has content if not os.path.exists(file_path): raise Exception(f"Document file was not created: {file_path}") file_size = os.path.getsize(file_path) if file_size == 0: raise Exception(f"Document file is empty: {file_path}") print(f"Successfully generated {output_format.upper()}: {file_path} (Size: {file_size} bytes)") # Set outputs self.set_output("file_path", file_path) self.set_output("pdf_base64", doc_base64) # Keep same output name for compatibility self.set_output("success", True) # Create download info object download_info = { "filename": filename, "path": file_path, "base64": doc_base64, "mime_type": mime_type, "size": file_size } # Output download info as JSON string so it can be used in Message block download_json = json.dumps(download_info) self.set_output("download", download_json) return download_info except Exception as e: error_msg = f"Error in _generate_pdf: {str(e)}\n{traceback.format_exc()}" print(error_msg) self.set_output("success", False) self.set_output("_ERROR", f"PDF generation failed: {str(e)}") raise except Exception as e: error_msg = f"Error in PDFGenerator._invoke: {str(e)}\n{traceback.format_exc()}" print(error_msg) self.set_output("success", False) self.set_output("_ERROR", f"PDF generation failed: {str(e)}") raise def _generate_pdf(self, content: str, title: str = "", subtitle: str = "") -> tuple[str, str]: """Generate PDF from markdown-style content with improved error handling and concurrency support""" import uuid import traceback # Create output directory if it doesn't exist os.makedirs(self._param.output_directory, exist_ok=True) # Initialize variables that need cleanup buffer = None temp_file_path = None file_path = None try: # Generate a unique filename to prevent conflicts if self._param.filename: base_name = os.path.splitext(self._param.filename)[0] filename = f"{base_name}_{uuid.uuid4().hex[:8]}.pdf" else: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"document_{timestamp}_{uuid.uuid4().hex[:8]}.pdf" file_path = os.path.join(self._param.output_directory, filename) temp_file_path = f"{file_path}.tmp" # Setup page size page_size = A4 if self._param.orientation == "landscape": page_size = (A4[1], A4[0]) # Create PDF buffer and document buffer = BytesIO() doc = SimpleDocTemplate( buffer, pagesize=page_size, topMargin=self._param.margin_top * inch, bottomMargin=self._param.margin_bottom * inch, leftMargin=self._param.margin_left * inch, rightMargin=self._param.margin_right * inch ) # Build story (content elements) story = [] # Combine all text content for Unicode font detection all_text = f"{title} {subtitle} {content}" # IMPORTANT: Register Unicode fonts BEFORE creating any styles or Paragraphs # This ensures the font family is available for ReportLab's HTML parser if self._needs_unicode_font(all_text): self._register_unicode_fonts() styles = self._create_styles(all_text) # Add logo if provided if self._param.logo_image: logo = self._add_logo() if logo: story.append(logo) story.append(Spacer(1, 0.3 * inch)) # Add title if title: title_para = Paragraph(self._escape_html(title), styles['PDFTitle']) story.append(title_para) story.append(Spacer(1, 0.2 * inch)) # Add subtitle if subtitle: subtitle_para = Paragraph(self._escape_html(subtitle), styles['PDFSubtitle']) story.append(subtitle_para) story.append(Spacer(1, 0.3 * inch)) # Add timestamp if enabled if self._param.add_timestamp: timestamp_text = f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" timestamp_para = Paragraph(timestamp_text, styles['Italic']) story.append(timestamp_para) story.append(Spacer(1, 0.2 * inch)) # Parse and add content content_elements = self._parse_markdown_content(content, styles) story.extend(content_elements) # Build PDF doc.build(story, onFirstPage=self._add_page_decorations, onLaterPages=self._add_page_decorations) # Get PDF bytes pdf_bytes = buffer.getvalue() # Write to temporary file first with open(temp_file_path, 'wb') as f: f.write(pdf_bytes) # Atomic rename to final filename (works across different filesystems) if os.path.exists(file_path): os.remove(file_path) os.rename(temp_file_path, file_path) # Verify the file was created and has content if not os.path.exists(file_path): raise Exception(f"Failed to create output file: {file_path}") file_size = os.path.getsize(file_path) if file_size == 0: raise Exception(f"Generated PDF is empty: {file_path}") # Convert to base64 pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8') return file_path, pdf_base64 except Exception as e: # Clean up any temporary files on error if temp_file_path and os.path.exists(temp_file_path): try: os.remove(temp_file_path) except Exception as cleanup_error: print(f"Error cleaning up temporary file: {cleanup_error}") error_msg = f"Error generating PDF: {str(e)}\n{traceback.format_exc()}" print(error_msg) raise Exception(f"PDF generation failed: {str(e)}") finally: # Ensure buffer is always closed if buffer is not None: try: buffer.close() except Exception as close_error: print(f"Error closing buffer: {close_error}") def _create_styles(self, content: str = ""): """Create custom paragraph styles with Unicode font support if needed""" # Check if content contains CJK characters that need special fonts needs_cjk = self._needs_unicode_font(content) if needs_cjk: # Use CID fonts for CJK content if self._register_unicode_fonts() and self._unicode_font_name: regular_font = self._unicode_font_name bold_font = self._unicode_font_bold_name or self._unicode_font_name print(f"Using CID font for CJK content: {regular_font}") else: # Fall back to configured font if CID fonts unavailable regular_font = self._param.font_family bold_font = self._get_bold_font_name() print(f"Warning: CJK content detected but no CID font available, using {regular_font}") else: # Use user-selected font for Latin-only content regular_font = self._param.font_family bold_font = self._get_bold_font_name() print(f"Using configured font: {regular_font}") # Store active fonts as instance variables for use in other methods self._active_font = regular_font self._active_bold_font = bold_font # Get fresh style sheet styles = getSampleStyleSheet() # Helper function to get the correct bold font name def get_bold_font(font_family): """Get the correct bold variant of a font family""" # If using Unicode font, return the Unicode bold if font_family in ('UnicodeFont', self._unicode_font_name): return bold_font font_map = { 'Helvetica': 'Helvetica-Bold', 'Times-Roman': 'Times-Bold', 'Courier': 'Courier-Bold', } if 'Bold' in font_family: return font_family return font_map.get(font_family, 'Helvetica-Bold') # Use detected font instead of configured font for non-Latin content active_font = regular_font active_bold_font = bold_font # Helper function to add or update style def add_or_update_style(name, **kwargs): if name in styles: # Update existing style style = styles[name] for key, value in kwargs.items(): setattr(style, key, value) else: # Add new style styles.add(ParagraphStyle(name=name, **kwargs)) # IMPORTANT: Update base styles to use Unicode font for non-Latin content # This ensures ALL text uses the correct font, not just our custom styles add_or_update_style('Normal', fontName=active_font) add_or_update_style('BodyText', fontName=active_font) add_or_update_style('Bullet', fontName=active_font) add_or_update_style('Heading1', fontName=active_bold_font) add_or_update_style('Heading2', fontName=active_bold_font) add_or_update_style('Heading3', fontName=active_bold_font) add_or_update_style('Title', fontName=active_bold_font) # Title style add_or_update_style( 'PDFTitle', parent=styles['Heading1'], fontSize=self._param.title_font_size, textColor=colors.HexColor(self._param.title_color), fontName=active_bold_font, alignment=TA_CENTER, spaceAfter=12 ) # Subtitle style add_or_update_style( 'PDFSubtitle', parent=styles['Heading2'], fontSize=self._param.heading2_font_size, textColor=colors.HexColor(self._param.text_color), fontName=active_font, alignment=TA_CENTER, spaceAfter=12 ) # Custom heading styles add_or_update_style( 'CustomHeading1', parent=styles['Heading1'], fontSize=self._param.heading1_font_size, fontName=active_bold_font, textColor=colors.HexColor(self._param.text_color), spaceAfter=12, spaceBefore=12 ) add_or_update_style( 'CustomHeading2', parent=styles['Heading2'], fontSize=self._param.heading2_font_size, fontName=active_bold_font, textColor=colors.HexColor(self._param.text_color), spaceAfter=10, spaceBefore=10 ) add_or_update_style( 'CustomHeading3', parent=styles['Heading3'], fontSize=self._param.heading3_font_size, fontName=active_bold_font, textColor=colors.HexColor(self._param.text_color), spaceAfter=8, spaceBefore=8 ) # Body text style add_or_update_style( 'CustomBody', parent=styles['BodyText'], fontSize=self._param.font_size, fontName=active_font, textColor=colors.HexColor(self._param.text_color), leading=self._param.font_size * self._param.line_spacing, alignment=TA_JUSTIFY ) # Bullet style add_or_update_style( 'CustomBullet', parent=styles['BodyText'], fontSize=self._param.font_size, fontName=active_font, textColor=colors.HexColor(self._param.text_color), leftIndent=20, bulletIndent=10 ) # Code style (keep Courier for code blocks) add_or_update_style( 'PDFCode', parent=styles.get('Code', styles['Normal']), fontSize=self._param.font_size - 1, fontName='Courier', textColor=colors.HexColor('#333333'), backColor=colors.HexColor('#f5f5f5'), leftIndent=20, rightIndent=20 ) # Italic style add_or_update_style( 'Italic', parent=styles['Normal'], fontSize=self._param.font_size, fontName=active_font, textColor=colors.HexColor(self._param.text_color) ) return styles def _parse_markdown_content(self, content: str, styles): """Parse markdown-style content and convert to PDF elements""" elements = [] lines = content.split('\n') i = 0 while i < len(lines): line = lines[i].strip() # Skip empty lines if not line: elements.append(Spacer(1, 0.1 * inch)) i += 1 continue # Horizontal rule if line == '---' or line == '___': elements.append(Spacer(1, 0.1 * inch)) elements.append(self._create_horizontal_line()) elements.append(Spacer(1, 0.1 * inch)) i += 1 continue # Heading 1 if line.startswith('# ') and not line.startswith('## '): text = line[2:].strip() elements.append(Paragraph(self._format_inline(text), styles['CustomHeading1'])) i += 1 continue # Heading 2 if line.startswith('## ') and not line.startswith('### '): text = line[3:].strip() elements.append(Paragraph(self._format_inline(text), styles['CustomHeading2'])) i += 1 continue # Heading 3 if line.startswith('### '): text = line[4:].strip() elements.append(Paragraph(self._format_inline(text), styles['CustomHeading3'])) i += 1 continue # Bullet list if line.startswith('- ') or line.startswith('* '): bullet_items = [] while i < len(lines) and (lines[i].strip().startswith('- ') or lines[i].strip().startswith('* ')): item_text = lines[i].strip()[2:].strip() formatted = self._format_inline(item_text) bullet_items.append(f"โ€ข {formatted}") i += 1 for item in bullet_items: elements.append(Paragraph(item, styles['CustomBullet'])) continue # Numbered list if re.match(r'^\d+\.\s', line): numbered_items = [] counter = 1 while i < len(lines) and re.match(r'^\d+\.\s', lines[i].strip()): item_text = re.sub(r'^\d+\.\s', '', lines[i].strip()) numbered_items.append(f"{counter}. {self._format_inline(item_text)}") counter += 1 i += 1 for item in numbered_items: elements.append(Paragraph(item, styles['CustomBullet'])) continue # Table detection (markdown table must start with |) if line.startswith('|') and '|' in line: table_lines = [] # Collect all consecutive lines that look like table rows while i < len(lines) and lines[i].strip() and '|' in lines[i]: table_lines.append(lines[i].strip()) i += 1 # Only process if we have at least 2 lines (header + separator or header + data) if len(table_lines) >= 2: table_elements = self._create_table(table_lines) if table_elements: # _create_table now returns a list of elements elements.extend(table_elements) elements.append(Spacer(1, 0.2 * inch)) continue else: # Not a valid table, treat as regular text i -= len(table_lines) # Reset position # Code block if line.startswith('```'): code_lines = [] i += 1 while i < len(lines) and not lines[i].strip().startswith('```'):
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/list_operations.py
agent/component/list_operations.py
from abc import ABC import os from agent.component.base import ComponentBase, ComponentParamBase from api.utils.api_utils import timeout class ListOperationsParam(ComponentParamBase): """ Define the List Operations component parameters. """ def __init__(self): super().__init__() self.query = "" self.operations = "topN" self.n=0 self.sort_method = "asc" self.filter = { "operator": "=", "value": "" } self.outputs = { "result": { "value": [], "type": "Array of ?" }, "first": { "value": "", "type": "?" }, "last": { "value": "", "type": "?" } } def check(self): self.check_empty(self.query, "query") self.check_valid_value(self.operations, "Support operations", ["topN","head","tail","filter","sort","drop_duplicates"]) def get_input_form(self) -> dict[str, dict]: return {} class ListOperations(ComponentBase,ABC): component_name = "ListOperations" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): self.input_objects=[] inputs = getattr(self._param, "query", None) self.inputs = self._canvas.get_variable_value(inputs) if not isinstance(self.inputs, list): raise TypeError("The input of List Operations should be an array.") self.set_input_value(inputs, self.inputs) if self._param.operations == "topN": self._topN() elif self._param.operations == "head": self._head() elif self._param.operations == "tail": self._tail() elif self._param.operations == "filter": self._filter() elif self._param.operations == "sort": self._sort() elif self._param.operations == "drop_duplicates": self._drop_duplicates() def _coerce_n(self): try: return int(getattr(self._param, "n", 0)) except Exception: return 0 def _set_outputs(self, outputs): self._param.outputs["result"]["value"] = outputs self._param.outputs["first"]["value"] = outputs[0] if outputs else None self._param.outputs["last"]["value"] = outputs[-1] if outputs else None def _topN(self): n = self._coerce_n() if n < 1: outputs = [] else: n = min(n, len(self.inputs)) outputs = self.inputs[:n] self._set_outputs(outputs) def _head(self): n = self._coerce_n() if 1 <= n <= len(self.inputs): outputs = [self.inputs[n - 1]] else: outputs = [] self._set_outputs(outputs) def _tail(self): n = self._coerce_n() if 1 <= n <= len(self.inputs): outputs = [self.inputs[-n]] else: outputs = [] self._set_outputs(outputs) def _filter(self): self._set_outputs([i for i in self.inputs if self._eval(self._norm(i),self._param.filter["operator"],self._param.filter["value"])]) def _norm(self,v): s = "" if v is None else str(v) return s def _eval(self, v, operator, value): if operator == "=": return v == value elif operator == "โ‰ ": return v != value elif operator == "contains": return value in v elif operator == "start with": return v.startswith(value) elif operator == "end with": return v.endswith(value) else: return False def _sort(self): items = self.inputs or [] method = getattr(self._param, "sort_method", "asc") or "asc" reverse = method == "desc" if not items: self._set_outputs([]) return first = items[0] if isinstance(first, dict): outputs = sorted( items, key=lambda x: self._hashable(x), reverse=reverse, ) else: outputs = sorted(items, reverse=reverse) self._set_outputs(outputs) def _drop_duplicates(self): seen = set() outs = [] for item in self.inputs: k = self._hashable(item) if k in seen: continue seen.add(k) outs.append(item) self._set_outputs(outs) def _hashable(self,x): if isinstance(x, dict): return tuple(sorted((k, self._hashable(v)) for k, v in x.items())) if isinstance(x, (list, tuple)): return tuple(self._hashable(v) for v in x) if isinstance(x, set): return tuple(sorted(self._hashable(v) for v in x)) return x def thoughts(self) -> str: return "ListOperation in progress"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/excel_processor.py
agent/component/excel_processor.py
# # 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. # """ ExcelProcessor Component A component for reading, processing, and generating Excel files in RAGFlow agents. Supports multiple Excel file inputs, data transformation, and Excel output generation. """ import logging import os from abc import ABC from io import BytesIO import pandas as pd from agent.component.base import ComponentBase, ComponentParamBase from api.db.services.file_service import FileService from api.utils.api_utils import timeout from common import settings from common.misc_utils import get_uuid class ExcelProcessorParam(ComponentParamBase): """ Define the ExcelProcessor component parameters. """ def __init__(self): super().__init__() # Input configuration self.input_files = [] # Variable references to uploaded files self.operation = "read" # read, merge, transform, output # Processing options self.sheet_selection = "all" # all, first, or comma-separated sheet names self.merge_strategy = "concat" # concat, join self.join_on = "" # Column name for join operations # Transform options (for LLM-guided transformations) self.transform_instructions = "" self.transform_data = "" # Variable reference to transformation data # Output options self.output_format = "xlsx" # xlsx, csv self.output_filename = "output" # Component outputs self.outputs = { "data": { "type": "object", "value": {} }, "summary": { "type": "str", "value": "" }, "markdown": { "type": "str", "value": "" } } def check(self): self.check_valid_value( self.operation, "[ExcelProcessor] Operation", ["read", "merge", "transform", "output"] ) self.check_valid_value( self.output_format, "[ExcelProcessor] Output format", ["xlsx", "csv"] ) return True class ExcelProcessor(ComponentBase, ABC): """ Excel processing component for RAGFlow agents. Operations: - read: Parse Excel files into structured data - merge: Combine multiple Excel files - transform: Apply data transformations based on instructions - output: Generate Excel file output """ component_name = "ExcelProcessor" def get_input_form(self) -> dict[str, dict]: """Define input form for the component.""" res = {} for ref in (self._param.input_files or []): for k, o in self.get_input_elements_from_text(ref).items(): res[k] = {"name": o.get("name", ""), "type": "file"} if self._param.transform_data: for k, o in self.get_input_elements_from_text(self._param.transform_data).items(): res[k] = {"name": o.get("name", ""), "type": "object"} return res @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): if self.check_if_canceled("ExcelProcessor processing"): return operation = self._param.operation.lower() if operation == "read": self._read_excels() elif operation == "merge": self._merge_excels() elif operation == "transform": self._transform_data() elif operation == "output": self._output_excel() else: self.set_output("summary", f"Unknown operation: {operation}") def _get_file_content(self, file_ref: str) -> tuple[bytes, str]: """ Get file content from a variable reference. Returns (content_bytes, filename). """ value = self._canvas.get_variable_value(file_ref) if value is None: return None, None # Handle different value formats if isinstance(value, dict): # File reference from Begin/UserFillUp component file_id = value.get("id") or value.get("file_id") created_by = value.get("created_by") or self._canvas.get_tenant_id() filename = value.get("name") or value.get("filename", "unknown.xlsx") if file_id: content = FileService.get_blob(created_by, file_id) return content, filename elif isinstance(value, list) and len(value) > 0: # List of file references - return first return self._get_file_content_from_list(value[0]) elif isinstance(value, str): # Could be base64 encoded or a path if value.startswith("data:"): import base64 # Extract base64 content _, encoded = value.split(",", 1) return base64.b64decode(encoded), "uploaded.xlsx" return None, None def _get_file_content_from_list(self, item) -> tuple[bytes, str]: """Extract file content from a list item.""" if isinstance(item, dict): return self._get_file_content(item) return None, None def _parse_excel_to_dataframes(self, content: bytes, filename: str) -> dict[str, pd.DataFrame]: """Parse Excel content into a dictionary of DataFrames (one per sheet).""" try: excel_file = BytesIO(content) if filename.lower().endswith(".csv"): df = pd.read_csv(excel_file) return {"Sheet1": df} else: # Read all sheets xlsx = pd.ExcelFile(excel_file, engine='openpyxl') sheet_selection = self._param.sheet_selection if sheet_selection == "all": sheets_to_read = xlsx.sheet_names elif sheet_selection == "first": sheets_to_read = [xlsx.sheet_names[0]] if xlsx.sheet_names else [] else: # Comma-separated sheet names requested = [s.strip() for s in sheet_selection.split(",")] sheets_to_read = [s for s in requested if s in xlsx.sheet_names] dfs = {} for sheet in sheets_to_read: dfs[sheet] = pd.read_excel(xlsx, sheet_name=sheet) return dfs except Exception as e: logging.error(f"Error parsing Excel file {filename}: {e}") return {} def _read_excels(self): """Read and parse Excel files into structured data.""" all_data = {} summaries = [] markdown_parts = [] for file_ref in (self._param.input_files or []): if self.check_if_canceled("ExcelProcessor reading"): return # Get variable value value = self._canvas.get_variable_value(file_ref) self.set_input_value(file_ref, str(value)[:200] if value else "") if value is None: continue # Handle file content content, filename = self._get_file_content(file_ref) if content is None: continue # Parse Excel dfs = self._parse_excel_to_dataframes(content, filename) for sheet_name, df in dfs.items(): key = f"{filename}_{sheet_name}" if len(dfs) > 1 else filename all_data[key] = df.to_dict(orient="records") # Build summary summaries.append(f"**{key}**: {len(df)} rows, {len(df.columns)} columns ({', '.join(df.columns.tolist()[:5])}{'...' if len(df.columns) > 5 else ''})") # Build markdown table markdown_parts.append(f"### {key}\n\n{df.head(10).to_markdown(index=False)}\n") # Set outputs self.set_output("data", all_data) self.set_output("summary", "\n".join(summaries) if summaries else "No Excel files found") self.set_output("markdown", "\n\n".join(markdown_parts) if markdown_parts else "No data") def _merge_excels(self): """Merge multiple Excel files/sheets into one.""" all_dfs = [] for file_ref in (self._param.input_files or []): if self.check_if_canceled("ExcelProcessor merging"): return value = self._canvas.get_variable_value(file_ref) self.set_input_value(file_ref, str(value)[:200] if value else "") if value is None: continue content, filename = self._get_file_content(file_ref) if content is None: continue dfs = self._parse_excel_to_dataframes(content, filename) all_dfs.extend(dfs.values()) if not all_dfs: self.set_output("data", {}) self.set_output("summary", "No data to merge") return # Merge strategy if self._param.merge_strategy == "concat": merged_df = pd.concat(all_dfs, ignore_index=True) elif self._param.merge_strategy == "join" and self._param.join_on: # Join on specified column merged_df = all_dfs[0] for df in all_dfs[1:]: merged_df = merged_df.merge(df, on=self._param.join_on, how="outer") else: merged_df = pd.concat(all_dfs, ignore_index=True) self.set_output("data", {"merged": merged_df.to_dict(orient="records")}) self.set_output("summary", f"Merged {len(all_dfs)} sources into {len(merged_df)} rows, {len(merged_df.columns)} columns") self.set_output("markdown", merged_df.head(20).to_markdown(index=False)) def _transform_data(self): """Apply transformations to data based on instructions or input data.""" # Get the data to transform transform_ref = self._param.transform_data if not transform_ref: self.set_output("summary", "No transform data reference provided") return data = self._canvas.get_variable_value(transform_ref) self.set_input_value(transform_ref, str(data)[:300] if data else "") if data is None: self.set_output("summary", "Transform data is empty") return # Convert to DataFrame if isinstance(data, dict): # Could be {"sheet": [rows]} format if all(isinstance(v, list) for v in data.values()): # Multiple sheets all_markdown = [] for sheet_name, rows in data.items(): df = pd.DataFrame(rows) all_markdown.append(f"### {sheet_name}\n\n{df.to_markdown(index=False)}") self.set_output("data", data) self.set_output("markdown", "\n\n".join(all_markdown)) else: df = pd.DataFrame([data]) self.set_output("data", df.to_dict(orient="records")) self.set_output("markdown", df.to_markdown(index=False)) elif isinstance(data, list): df = pd.DataFrame(data) self.set_output("data", df.to_dict(orient="records")) self.set_output("markdown", df.to_markdown(index=False)) else: self.set_output("data", {"raw": str(data)}) self.set_output("markdown", str(data)) self.set_output("summary", "Transformed data ready for processing") def _output_excel(self): """Generate Excel file output from data.""" # Get data from transform_data reference transform_ref = self._param.transform_data if not transform_ref: self.set_output("summary", "No data reference for output") return data = self._canvas.get_variable_value(transform_ref) self.set_input_value(transform_ref, str(data)[:300] if data else "") if data is None: self.set_output("summary", "No data to output") return try: # Prepare DataFrames if isinstance(data, dict): if all(isinstance(v, list) for v in data.values()): # Multi-sheet format dfs = {k: pd.DataFrame(v) for k, v in data.items()} else: dfs = {"Sheet1": pd.DataFrame([data])} elif isinstance(data, list): dfs = {"Sheet1": pd.DataFrame(data)} else: self.set_output("summary", "Invalid data format for Excel output") return # Generate output doc_id = get_uuid() if self._param.output_format == "csv": # For CSV, only output first sheet first_df = list(dfs.values())[0] binary_content = first_df.to_csv(index=False).encode("utf-8") filename = f"{self._param.output_filename}.csv" else: # Excel output excel_io = BytesIO() with pd.ExcelWriter(excel_io, engine='openpyxl') as writer: for sheet_name, df in dfs.items(): # Sanitize sheet name (max 31 chars, no special chars) safe_name = sheet_name[:31].replace("/", "_").replace("\\", "_") df.to_excel(writer, sheet_name=safe_name, index=False) excel_io.seek(0) binary_content = excel_io.read() filename = f"{self._param.output_filename}.xlsx" # Store file settings.STORAGE_IMPL.put(self._canvas._tenant_id, doc_id, binary_content) # Set attachment output self.set_output("attachment", { "doc_id": doc_id, "format": self._param.output_format, "file_name": filename }) total_rows = sum(len(df) for df in dfs.values()) self.set_output("summary", f"Generated {filename} with {len(dfs)} sheet(s), {total_rows} total rows") self.set_output("data", {k: v.to_dict(orient="records") for k, v in dfs.items()}) logging.info(f"ExcelProcessor: Generated {filename} as {doc_id}") except Exception as e: logging.error(f"ExcelProcessor output error: {e}") self.set_output("summary", f"Error generating output: {str(e)}") def thoughts(self) -> str: """Return component thoughts for UI display.""" op = self._param.operation if op == "read": return "Reading Excel files..." elif op == "merge": return "Merging Excel data..." elif op == "transform": return "Transforming data..." elif op == "output": return "Generating Excel output..." return "Processing Excel..."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/message.py
agent/component/message.py
# # Copyright 2024 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 asyncio import nest_asyncio nest_asyncio.apply() import inspect import json import os import random import re import logging import tempfile from functools import partial from typing import Any from agent.component.base import ComponentBase, ComponentParamBase from jinja2 import Template as Jinja2Template from common.connection_utils import timeout from common.misc_utils import get_uuid from common import settings from api.db.joint_services.memory_message_service import queue_save_to_memory_task class MessageParam(ComponentParamBase): """ Define the Message component parameters. """ def __init__(self): super().__init__() self.content = [] self.stream = True self.output_format = None # default output format self.auto_play = False self.outputs = { "content": { "type": "str" } } def check(self): self.check_empty(self.content, "[Message] Content") self.check_boolean(self.stream, "[Message] stream") return True class Message(ComponentBase): component_name = "Message" def get_input_elements(self) -> dict[str, Any]: return self.get_input_elements_from_text("".join(self._param.content)) def get_kwargs(self, script:str, kwargs:dict = {}, delimiter:str=None) -> tuple[str, dict[str, str | list | Any]]: for k,v in self.get_input_elements_from_text(script).items(): if k in kwargs: continue v = v["value"] if not v: v = "" ans = "" if isinstance(v, partial): iter_obj = v() if inspect.isasyncgen(iter_obj): ans = asyncio.run(self._consume_async_gen(iter_obj)) else: for t in iter_obj: ans += t elif isinstance(v, list) and delimiter: ans = delimiter.join([str(vv) for vv in v]) elif not isinstance(v, str): try: ans = json.dumps(v, ensure_ascii=False) except Exception: pass else: ans = v if not ans: ans = "" kwargs[k] = ans self.set_input_value(k, ans) _kwargs = {} for n, v in kwargs.items(): _n = re.sub("[@:.]", "_", n) script = re.sub(r"\{%s\}" % re.escape(n), _n, script) _kwargs[_n] = v return script, _kwargs async def _consume_async_gen(self, agen): buf = "" async for t in agen: buf += t return buf async def _stream(self, rand_cnt:str): s = 0 all_content = "" cache = {} for r in re.finditer(self.variable_ref_patt, rand_cnt, flags=re.DOTALL): if self.check_if_canceled("Message streaming"): return all_content += rand_cnt[s: r.start()] yield rand_cnt[s: r.start()] s = r.end() exp = r.group(1) if exp in cache: yield cache[exp] all_content += cache[exp] continue v = self._canvas.get_variable_value(exp) if v is None: v = "" if isinstance(v, partial): cnt = "" iter_obj = v() if inspect.isasyncgen(iter_obj): async for t in iter_obj: if self.check_if_canceled("Message streaming"): return all_content += t cnt += t yield t else: for t in iter_obj: if self.check_if_canceled("Message streaming"): return all_content += t cnt += t yield t self.set_input_value(exp, cnt) continue elif inspect.isawaitable(v): v = await v elif not isinstance(v, str): try: v = json.dumps(v, ensure_ascii=False) except Exception: v = str(v) yield v self.set_input_value(exp, v) all_content += v cache[exp] = v if s < len(rand_cnt): if self.check_if_canceled("Message streaming"): return all_content += rand_cnt[s: ] yield rand_cnt[s: ] self.set_output("content", all_content) self._convert_content(all_content) await self._save_to_memory(all_content) def _is_jinjia2(self, content:str) -> bool: patt = [ r"\{%.*%\}", "{{", "}}" ] return any([re.search(p, content) for p in patt]) @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): if self.check_if_canceled("Message processing"): return rand_cnt = random.choice(self._param.content) if self._param.stream and not self._is_jinjia2(rand_cnt): self.set_output("content", partial(self._stream, rand_cnt)) return rand_cnt, kwargs = self.get_kwargs(rand_cnt, kwargs) template = Jinja2Template(rand_cnt) try: content = template.render(kwargs) except Exception: pass if self.check_if_canceled("Message processing"): return for n, v in kwargs.items(): content = re.sub(n, v, content) self.set_output("content", content) self._convert_content(content) self._save_to_memory(content) def thoughts(self) -> str: return "" def _parse_markdown_table_lines(self, table_lines: list): """ Parse a list of Markdown table lines into a pandas DataFrame. Args: table_lines: List of strings, each representing a row in the Markdown table (excluding separator lines like |---|---|) Returns: pandas DataFrame with the table data, or None if parsing fails """ import pandas as pd if not table_lines: return None rows = [] headers = None for line in table_lines: # Split by | and clean up cells = [cell.strip() for cell in line.split('|')] # Remove empty first and last elements from split (caused by leading/trailing |) cells = [c for c in cells if c] if headers is None: headers = cells else: rows.append(cells) if headers and rows: # Ensure all rows have same number of columns as headers normalized_rows = [] for row in rows: while len(row) < len(headers): row.append('') normalized_rows.append(row[:len(headers)]) return pd.DataFrame(normalized_rows, columns=headers) return None def _convert_content(self, content): if not self._param.output_format: return import pypandoc doc_id = get_uuid() if self._param.output_format.lower() not in {"markdown", "html", "pdf", "docx", "xlsx"}: self._param.output_format = "markdown" try: if self._param.output_format in {"markdown", "html"}: if isinstance(content, str): converted = pypandoc.convert_text( content, to=self._param.output_format, format="markdown", ) else: converted = pypandoc.convert_file( content, to=self._param.output_format, format="markdown", ) binary_content = converted.encode("utf-8") elif self._param.output_format == "xlsx": import pandas as pd from io import BytesIO # Debug: log the content being parsed logging.info(f"XLSX Parser: Content length={len(content) if content else 0}, first 500 chars: {content[:500] if content else 'None'}") # Try to parse ALL Markdown tables from the content # Each table will be written to a separate sheet tables = [] # List of (sheet_name, dataframe) if isinstance(content, str): lines = content.strip().split('\n') logging.info(f"XLSX Parser: Total lines={len(lines)}, lines starting with '|': {sum(1 for line in lines if line.strip().startswith('|'))}") current_table_lines = [] current_table_title = None pending_title = None in_table = False table_count = 0 for i, line in enumerate(lines): stripped = line.strip() # Check for potential table title (lines before a table) # Look for patterns like "Table 1:", "## Table", or markdown headers if not in_table and stripped and not stripped.startswith('|'): # Check if this could be a table title lower_stripped = stripped.lower() if (lower_stripped.startswith('table') or stripped.startswith('#') or ':' in stripped): pending_title = stripped.lstrip('#').strip() if stripped.startswith('|') and '|' in stripped[1:]: # Check if this is a separator line (|---|---|) cleaned = stripped.replace(' ', '').replace('|', '').replace('-', '').replace(':', '') if cleaned == '': continue # Skip separator line if not in_table: # Starting a new table in_table = True current_table_lines = [] current_table_title = pending_title pending_title = None current_table_lines.append(stripped) elif in_table and not stripped.startswith('|'): # End of current table - save it if current_table_lines: df = self._parse_markdown_table_lines(current_table_lines) if df is not None and not df.empty: table_count += 1 # Generate sheet name if current_table_title: # Clean and truncate title for sheet name sheet_name = current_table_title[:31] sheet_name = sheet_name.replace('/', '_').replace('\\', '_').replace('*', '').replace('?', '').replace('[', '').replace(']', '').replace(':', '') else: sheet_name = f"Table_{table_count}" tables.append((sheet_name, df)) # Reset for next table in_table = False current_table_lines = [] current_table_title = None # Check if this line could be a title for the next table if stripped: lower_stripped = stripped.lower() if (lower_stripped.startswith('table') or stripped.startswith('#') or ':' in stripped): pending_title = stripped.lstrip('#').strip() # Don't forget the last table if content ends with a table if in_table and current_table_lines: df = self._parse_markdown_table_lines(current_table_lines) if df is not None and not df.empty: table_count += 1 if current_table_title: sheet_name = current_table_title[:31] sheet_name = sheet_name.replace('/', '_').replace('\\', '_').replace('*', '').replace('?', '').replace('[', '').replace(']', '').replace(':', '') else: sheet_name = f"Table_{table_count}" tables.append((sheet_name, df)) # Fallback: if no tables found, create single sheet with content if not tables: df = pd.DataFrame({"Content": [content if content else ""]}) tables = [("Data", df)] # Write all tables to Excel, each in a separate sheet excel_io = BytesIO() with pd.ExcelWriter(excel_io, engine='openpyxl') as writer: used_names = set() for sheet_name, df in tables: # Ensure unique sheet names original_name = sheet_name counter = 1 while sheet_name in used_names: suffix = f"_{counter}" sheet_name = original_name[:31-len(suffix)] + suffix counter += 1 used_names.add(sheet_name) df.to_excel(writer, sheet_name=sheet_name, index=False) excel_io.seek(0) binary_content = excel_io.read() logging.info(f"Generated Excel with {len(tables)} sheet(s): {[t[0] for t in tables]}") else: # pdf, docx with tempfile.NamedTemporaryFile(suffix=f".{self._param.output_format}", delete=False) as tmp: tmp_name = tmp.name try: if isinstance(content, str): pypandoc.convert_text( content, to=self._param.output_format, format="markdown", outputfile=tmp_name, ) else: pypandoc.convert_file( content, to=self._param.output_format, format="markdown", outputfile=tmp_name, ) with open(tmp_name, "rb") as f: binary_content = f.read() finally: if os.path.exists(tmp_name): os.remove(tmp_name) settings.STORAGE_IMPL.put(self._canvas._tenant_id, doc_id, binary_content) self.set_output("attachment", { "doc_id":doc_id, "format":self._param.output_format, "file_name":f"{doc_id[:8]}.{self._param.output_format}"}) logging.info(f"Converted content uploaded as {doc_id} (format={self._param.output_format})") except Exception as e: logging.error(f"Error converting content to {self._param.output_format}: {e}") async def _save_to_memory(self, content): if not hasattr(self._param, "memory_ids") or not self._param.memory_ids: return True, "No memory selected." message_dict = { "user_id": self._canvas._tenant_id, "agent_id": self._canvas._id, "session_id": self._canvas.task_id, "user_input": self._canvas.get_sys_query(), "agent_response": content } return await queue_save_to_memory_task(self._param.memory_ids, message_dict)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/iterationitem.py
agent/component/iterationitem.py
# # Copyright 2024 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. # from abc import ABC from agent.component.base import ComponentBase, ComponentParamBase class IterationItemParam(ComponentParamBase): """ Define the IterationItem component parameters. """ def check(self): return True class IterationItem(ComponentBase, ABC): component_name = "IterationItem" def __init__(self, canvas, id, param: ComponentParamBase): super().__init__(canvas, id, param) self._idx = 0 def _invoke(self, **kwargs): if self.check_if_canceled("IterationItem processing"): return parent = self.get_parent() arr = self._canvas.get_variable_value(parent._param.items_ref) if not isinstance(arr, list): self._idx = -1 raise Exception(parent._param.items_ref + " must be an array, but its type is "+str(type(arr))) if self._idx > 0: if self.check_if_canceled("IterationItem processing"): return self.output_collation() if self._idx >= len(arr): self._idx = -1 return if self.check_if_canceled("IterationItem processing"): return self.set_output("item", arr[self._idx]) self.set_output("index", self._idx) self._idx += 1 def output_collation(self): pid = self.get_parent()._id for cid in self._canvas.components.keys(): obj = self._canvas.get_component_obj(cid) p = obj.get_parent() if not p: continue if p._id != pid: continue if p.component_name.lower() in ["categorize", "message", "switch", "userfillup", "interationitem"]: continue for k, o in p._param.outputs.items(): if "ref" not in o: continue _cid, var = o["ref"].split("@") if _cid != cid: continue res = p.output(k) if not res: res = [] res.append(obj.output(var)) p.set_output(k, res) def end(self): return self._idx == -1 def thoughts(self) -> str: return "Next turn..."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/string_transform.py
agent/component/string_transform.py
# # 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 re from abc import ABC from typing import Any from jinja2 import Template as Jinja2Template from agent.component.base import ComponentParamBase from common.connection_utils import timeout from .message import Message class StringTransformParam(ComponentParamBase): """ Define the code sandbox component parameters. """ def __init__(self): super().__init__() self.method = "split" self.script = "" self.split_ref = "" self.delimiters = [","] self.outputs = {"result": {"value": "", "type": "string"}} def check(self): self.check_valid_value(self.method, "Support method", ["split", "merge"]) self.check_empty(self.delimiters, "delimiters") class StringTransform(Message, ABC): component_name = "StringTransform" def get_input_elements(self) -> dict[str, Any]: return self.get_input_elements_from_text(self._param.script) def get_input_form(self) -> dict[str, dict]: if self._param.method == "split": return { "line": { "name": "String", "type": "line" } } return {k: { "name": o["name"], "type": "line" } for k, o in self.get_input_elements_from_text(self._param.script).items()} @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): if self.check_if_canceled("StringTransform processing"): return if self._param.method == "split": self._split(kwargs.get("line")) else: self._merge(kwargs) def _split(self, line:str|None = None): if self.check_if_canceled("StringTransform split processing"): return var = self._canvas.get_variable_value(self._param.split_ref) if not line else line if not var: var = "" assert isinstance(var, str), "The input variable is not a string: {}".format(type(var)) self.set_input_value(self._param.split_ref, var) res = [] for i,s in enumerate(re.split(r"(%s)"%("|".join([re.escape(d) for d in self._param.delimiters])), var, flags=re.DOTALL)): if i % 2 == 1: continue res.append(s) self.set_output("result", res) def _merge(self, kwargs:dict[str, str] = {}): if self.check_if_canceled("StringTransform merge processing"): return script = self._param.script script, kwargs = self.get_kwargs(script, kwargs, self._param.delimiters[0]) if self._is_jinjia2(script): template = Jinja2Template(script) try: script = template.render(kwargs) except Exception: pass for k,v in kwargs.items(): if not v: v = "" script = re.sub(k, lambda match: v, script) self.set_output("result", script) def thoughts(self) -> str: return f"It's {self._param.method}ing."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/__init__.py
agent/component/__init__.py
# # 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 importlib import inspect from types import ModuleType from typing import Dict, Type _package_path = os.path.dirname(__file__) __all_classes: Dict[str, Type] = {} def _import_submodules() -> None: for filename in os.listdir(_package_path): # noqa: F821 if filename.startswith("__") or not filename.endswith(".py") or filename.startswith("base"): continue module_name = filename[:-3] try: module = importlib.import_module(f".{module_name}", package=__name__) _extract_classes_from_module(module) # noqa: F821 except ImportError as e: print(f"Warning: Failed to import module {module_name}: {str(e)}") def _extract_classes_from_module(module: ModuleType) -> None: for name, obj in inspect.getmembers(module): if (inspect.isclass(obj) and obj.__module__ == module.__name__ and not name.startswith("_")): __all_classes[name] = obj globals()[name] = obj _import_submodules() __all__ = list(__all_classes.keys()) + ["__all_classes"] del _package_path, _import_submodules, _extract_classes_from_module def component_class(class_name): for module_name in ["agent.component", "agent.tools", "rag.flow"]: try: return getattr(importlib.import_module(module_name), class_name) except Exception: # logging.warning(f"Can't import module: {module_name}, error: {e}") pass assert False, f"Can't import {class_name}"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/variable_assigner.py
agent/component/variable_assigner.py
# # Copyright 2024 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. # from abc import ABC import os import numbers from agent.component.base import ComponentBase, ComponentParamBase from api.utils.api_utils import timeout class VariableAssignerParam(ComponentParamBase): """ Define the Variable Assigner component parameters. """ def __init__(self): super().__init__() self.variables=[] def check(self): return True def get_input_form(self) -> dict[str, dict]: return { "items": { "type": "json", "name": "Items" } } class VariableAssigner(ComponentBase,ABC): component_name = "VariableAssigner" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): if not isinstance(self._param.variables,list): return else: for item in self._param.variables: if any([not item.get("variable"), not item.get("operator"), not item.get("parameter")]): assert "Variable is not complete." variable=item["variable"] operator=item["operator"] parameter=item["parameter"] variable_value=self._canvas.get_variable_value(variable) new_variable=self._operate(variable_value,operator,parameter) self._canvas.set_variable_value(variable, new_variable) def _operate(self,variable,operator,parameter): if operator == "overwrite": return self._overwrite(parameter) elif operator == "clear": return self._clear(variable) elif operator == "set": return self._set(variable,parameter) elif operator == "append": return self._append(variable,parameter) elif operator == "extend": return self._extend(variable,parameter) elif operator == "remove_first": return self._remove_first(variable) elif operator == "remove_last": return self._remove_last(variable) elif operator == "+=": return self._add(variable,parameter) elif operator == "-=": return self._subtract(variable,parameter) elif operator == "*=": return self._multiply(variable,parameter) elif operator == "/=": return self._divide(variable,parameter) else: return def _overwrite(self,parameter): return self._canvas.get_variable_value(parameter) def _clear(self,variable): if isinstance(variable,list): return [] elif isinstance(variable,str): return "" elif isinstance(variable,dict): return {} elif isinstance(variable,int): return 0 elif isinstance(variable,float): return 0.0 elif isinstance(variable,bool): return False else: return None def _set(self,variable,parameter): if variable is None: return self._canvas.get_value_with_variable(parameter) elif isinstance(variable,str): return self._canvas.get_value_with_variable(parameter) elif isinstance(variable,bool): return parameter elif isinstance(variable,int): return parameter elif isinstance(variable,float): return parameter else: return parameter def _append(self,variable,parameter): parameter=self._canvas.get_variable_value(parameter) if variable is None: variable=[] if not isinstance(variable,list): return "ERROR:VARIABLE_NOT_LIST" elif len(variable)!=0 and not isinstance(parameter,type(variable[0])): return "ERROR:PARAMETER_NOT_LIST_ELEMENT_TYPE" else: variable.append(parameter) return variable def _extend(self,variable,parameter): parameter=self._canvas.get_variable_value(parameter) if variable is None: variable=[] if not isinstance(variable,list): return "ERROR:VARIABLE_NOT_LIST" elif not isinstance(parameter,list): return "ERROR:PARAMETER_NOT_LIST" elif len(variable)!=0 and len(parameter)!=0 and not isinstance(parameter[0],type(variable[0])): return "ERROR:PARAMETER_NOT_LIST_ELEMENT_TYPE" else: return variable + parameter def _remove_first(self,variable): if len(variable)==0: return variable if not isinstance(variable,list): return "ERROR:VARIABLE_NOT_LIST" else: return variable[1:] def _remove_last(self,variable): if len(variable)==0: return variable if not isinstance(variable,list): return "ERROR:VARIABLE_NOT_LIST" else: return variable[:-1] def is_number(self, value): if isinstance(value, bool): return False return isinstance(value, numbers.Number) def _add(self,variable,parameter): if self.is_number(variable) and self.is_number(parameter): return variable + parameter else: return "ERROR:VARIABLE_NOT_NUMBER or PARAMETER_NOT_NUMBER" def _subtract(self,variable,parameter): if self.is_number(variable) and self.is_number(parameter): return variable - parameter else: return "ERROR:VARIABLE_NOT_NUMBER or PARAMETER_NOT_NUMBER" def _multiply(self,variable,parameter): if self.is_number(variable) and self.is_number(parameter): return variable * parameter else: return "ERROR:VARIABLE_NOT_NUMBER or PARAMETER_NOT_NUMBER" def _divide(self,variable,parameter): if self.is_number(variable) and self.is_number(parameter): if parameter==0: return "ERROR:DIVIDE_BY_ZERO" else: return variable/parameter else: return "ERROR:VARIABLE_NOT_NUMBER or PARAMETER_NOT_NUMBER" def thoughts(self) -> str: return "Assign variables from canvas."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/iteration.py
agent/component/iteration.py
# # Copyright 2024 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. # from abc import ABC from agent.component.base import ComponentBase, ComponentParamBase """ class VariableModel(BaseModel): data_type: Annotated[Literal["string", "number", "Object", "Boolean", "Array<string>", "Array<number>", "Array<object>", "Array<boolean>"], Field(default="Array<string>")] input_mode: Annotated[Literal["constant", "variable"], Field(default="constant")] value: Annotated[Any, Field(default=None)] model_config = ConfigDict(extra="forbid") """ class IterationParam(ComponentParamBase): """ Define the Iteration component parameters. """ def __init__(self): super().__init__() self.items_ref = "" self.variable={} def get_input_form(self) -> dict[str, dict]: return { "items": { "type": "json", "name": "Items" } } def check(self): return True class Iteration(ComponentBase, ABC): component_name = "Iteration" def get_start(self): for cid in self._canvas.components.keys(): if self._canvas.get_component(cid)["obj"].component_name.lower() != "iterationitem": continue if self._canvas.get_component(cid)["parent_id"] == self._id: return cid def _invoke(self, **kwargs): if self.check_if_canceled("Iteration processing"): return arr = self._canvas.get_variable_value(self._param.items_ref) if not isinstance(arr, list): self.set_output("_ERROR", self._param.items_ref + " must be an array, but its type is "+str(type(arr))) def thoughts(self) -> str: return "Need to process {} items.".format(len(self._canvas.get_variable_value(self._param.items_ref)))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/begin.py
agent/component/begin.py
# # Copyright 2024 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. # from agent.component.fillup import UserFillUpParam, UserFillUp from api.db.services.file_service import FileService class BeginParam(UserFillUpParam): """ Define the Begin component parameters. """ def __init__(self): super().__init__() self.mode = "conversational" self.prologue = "Hi! I'm your smart assistant. What can I do for you?" def check(self): self.check_valid_value(self.mode, "The 'mode' should be either `conversational` or `task`", ["conversational", "task","Webhook"]) def get_input_form(self) -> dict[str, dict]: return getattr(self, "inputs") class Begin(UserFillUp): component_name = "Begin" def _invoke(self, **kwargs): if self.check_if_canceled("Begin processing"): return for k, v in kwargs.get("inputs", {}).items(): if self.check_if_canceled("Begin processing"): return if isinstance(v, dict) and v.get("type", "").lower().find("file") >=0: if v.get("optional") and v.get("value", None) is None: v = None else: v = FileService.get_files([v["value"]]) else: v = v.get("value") self.set_output(k, v) self.set_input_value(k, v) def thoughts(self) -> str: return ""
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/base.py
agent/component/base.py
# # Copyright 2024 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 asyncio import re import time from abc import ABC import builtins import json import os import logging from typing import Any, List, Union import pandas as pd from agent import settings from common.connection_utils import timeout _FEEDED_DEPRECATED_PARAMS = "_feeded_deprecated_params" _DEPRECATED_PARAMS = "_deprecated_params" _USER_FEEDED_PARAMS = "_user_feeded_params" _IS_RAW_CONF = "_is_raw_conf" class ComponentParamBase(ABC): def __init__(self): self.message_history_window_size = 13 self.inputs = {} self.outputs = {} self.description = "" self.max_retries = 0 self.delay_after_error = 2.0 self.exception_method = None self.exception_default_value = None self.exception_goto = None self.debug_inputs = {} def set_name(self, name: str): self._name = name return self def check(self): raise NotImplementedError("Parameter Object should be checked.") @classmethod def _get_or_init_deprecated_params_set(cls): if not hasattr(cls, _DEPRECATED_PARAMS): setattr(cls, _DEPRECATED_PARAMS, set()) return getattr(cls, _DEPRECATED_PARAMS) def _get_or_init_feeded_deprecated_params_set(self, conf=None): if not hasattr(self, _FEEDED_DEPRECATED_PARAMS): if conf is None: setattr(self, _FEEDED_DEPRECATED_PARAMS, set()) else: setattr( self, _FEEDED_DEPRECATED_PARAMS, set(conf[_FEEDED_DEPRECATED_PARAMS]), ) return getattr(self, _FEEDED_DEPRECATED_PARAMS) def _get_or_init_user_feeded_params_set(self, conf=None): if not hasattr(self, _USER_FEEDED_PARAMS): if conf is None: setattr(self, _USER_FEEDED_PARAMS, set()) else: setattr(self, _USER_FEEDED_PARAMS, set(conf[_USER_FEEDED_PARAMS])) return getattr(self, _USER_FEEDED_PARAMS) def get_user_feeded(self): return self._get_or_init_user_feeded_params_set() def get_feeded_deprecated_params(self): return self._get_or_init_feeded_deprecated_params_set() @property def _deprecated_params_set(self): return {name: True for name in self.get_feeded_deprecated_params()} def __str__(self): return json.dumps(self.as_dict(), ensure_ascii=False) def as_dict(self): def _recursive_convert_obj_to_dict(obj): ret_dict = {} if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, dict) or (v and type(v).__name__ not in dir(builtins)): ret_dict[k] = _recursive_convert_obj_to_dict(v) else: ret_dict[k] = v return ret_dict for attr_name in list(obj.__dict__): if attr_name in [_FEEDED_DEPRECATED_PARAMS, _DEPRECATED_PARAMS, _USER_FEEDED_PARAMS, _IS_RAW_CONF]: continue # get attr attr = getattr(obj, attr_name) if isinstance(attr, pd.DataFrame): ret_dict[attr_name] = attr.to_dict() continue if isinstance(attr, dict) or (attr and type(attr).__name__ not in dir(builtins)): ret_dict[attr_name] = _recursive_convert_obj_to_dict(attr) else: ret_dict[attr_name] = attr return ret_dict return _recursive_convert_obj_to_dict(self) def update(self, conf, allow_redundant=False): update_from_raw_conf = conf.get(_IS_RAW_CONF, True) if update_from_raw_conf: deprecated_params_set = self._get_or_init_deprecated_params_set() feeded_deprecated_params_set = ( self._get_or_init_feeded_deprecated_params_set() ) user_feeded_params_set = self._get_or_init_user_feeded_params_set() setattr(self, _IS_RAW_CONF, False) else: feeded_deprecated_params_set = ( self._get_or_init_feeded_deprecated_params_set(conf) ) user_feeded_params_set = self._get_or_init_user_feeded_params_set(conf) def _recursive_update_param(param, config, depth, prefix): if depth > settings.PARAM_MAXDEPTH: raise ValueError("Param define nesting too deep!!!, can not parse it") inst_variables = param.__dict__ redundant_attrs = [] for config_key, config_value in config.items(): # redundant attr if config_key not in inst_variables: if not update_from_raw_conf and config_key.startswith("_"): setattr(param, config_key, config_value) else: setattr(param, config_key, config_value) # redundant_attrs.append(config_key) continue full_config_key = f"{prefix}{config_key}" if update_from_raw_conf: # add user feeded params user_feeded_params_set.add(full_config_key) # update user feeded deprecated param set if full_config_key in deprecated_params_set: feeded_deprecated_params_set.add(full_config_key) # supported attr attr = getattr(param, config_key) if type(attr).__name__ in dir(builtins) or attr is None: setattr(param, config_key, config_value) else: # recursive set obj attr sub_params = _recursive_update_param( attr, config_value, depth + 1, prefix=f"{prefix}{config_key}." ) setattr(param, config_key, sub_params) if not allow_redundant and redundant_attrs: raise ValueError( f"cpn `{getattr(self, '_name', type(self))}` has redundant parameters: `{[redundant_attrs]}`" ) return param return _recursive_update_param(param=self, config=conf, depth=0, prefix="") def extract_not_builtin(self): def _get_not_builtin_types(obj): ret_dict = {} for variable in obj.__dict__: attr = getattr(obj, variable) if attr and type(attr).__name__ not in dir(builtins): ret_dict[variable] = _get_not_builtin_types(attr) return ret_dict return _get_not_builtin_types(self) def validate(self): self.builtin_types = dir(builtins) self.func = { "ge": self._greater_equal_than, "le": self._less_equal_than, "in": self._in, "not_in": self._not_in, "range": self._range, } home_dir = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) param_validation_path_prefix = home_dir + "/param_validation/" param_name = type(self).__name__ param_validation_path = "/".join( [param_validation_path_prefix, param_name + ".json"] ) validation_json = None try: with open(param_validation_path, "r") as fin: validation_json = json.loads(fin.read()) except BaseException: return self._validate_param(self, validation_json) def _validate_param(self, param_obj, validation_json): default_section = type(param_obj).__name__ var_list = param_obj.__dict__ for variable in var_list: attr = getattr(param_obj, variable) if type(attr).__name__ in self.builtin_types or attr is None: if variable not in validation_json: continue validation_dict = validation_json[default_section][variable] value = getattr(param_obj, variable) value_legal = False for op_type in validation_dict: if self.func[op_type](value, validation_dict[op_type]): value_legal = True break if not value_legal: raise ValueError( "Please check runtime conf, {} = {} does not match user-parameter restriction".format( variable, value ) ) elif variable in validation_json: self._validate_param(attr, validation_json) @staticmethod def check_string(param, description): if type(param).__name__ not in ["str"]: raise ValueError(description + " {} not supported, should be string type".format(param)) @staticmethod def check_empty(param, description): if not param: raise ValueError(description + " does not support empty value.") @staticmethod def check_positive_integer(param, description): if type(param).__name__ not in ["int", "long"] or param <= 0: raise ValueError(description + " {} not supported, should be positive integer".format(param)) @staticmethod def check_positive_number(param, description): if type(param).__name__ not in ["float", "int", "long"] or param <= 0: raise ValueError(description + " {} not supported, should be positive numeric".format(param)) @staticmethod def check_nonnegative_number(param, description): if type(param).__name__ not in ["float", "int", "long"] or param < 0: raise ValueError(description + " {} not supported, should be non-negative numeric".format(param)) @staticmethod def check_decimal_float(param, description): if type(param).__name__ not in ["float", "int"] or param < 0 or param > 1: raise ValueError(description + " {} not supported, should be a float number in range [0, 1]".format(param)) @staticmethod def check_boolean(param, description): if type(param).__name__ != "bool": raise ValueError(description + " {} not supported, should be bool type".format(param)) @staticmethod def check_open_unit_interval(param, description): if type(param).__name__ not in ["float"] or param <= 0 or param >= 1: raise ValueError(description + " should be a numeric number between 0 and 1 exclusively") @staticmethod def check_valid_value(param, description, valid_values): if param not in valid_values: raise ValueError(description + " {} is not supported, it should be in {}".format(param, valid_values)) @staticmethod def check_defined_type(param, description, types): if type(param).__name__ not in types: raise ValueError(description + " {} not supported, should be one of {}".format(param, types)) @staticmethod def check_and_change_lower(param, valid_list, description=""): if type(param).__name__ != "str": raise ValueError(description + " {} not supported, should be one of {}".format(param, valid_list)) lower_param = param.lower() if lower_param in valid_list: return lower_param else: raise ValueError(description + " {} not supported, should be one of {}".format(param, valid_list)) @staticmethod def _greater_equal_than(value, limit): return value >= limit - settings.FLOAT_ZERO @staticmethod def _less_equal_than(value, limit): return value <= limit + settings.FLOAT_ZERO @staticmethod def _range(value, ranges): in_range = False for left_limit, right_limit in ranges: if ( left_limit - settings.FLOAT_ZERO <= value <= right_limit + settings.FLOAT_ZERO ): in_range = True break return in_range @staticmethod def _in(value, right_value_list): return value in right_value_list @staticmethod def _not_in(value, wrong_value_list): return value not in wrong_value_list def _warn_deprecated_param(self, param_name, description): if self._deprecated_params_set.get(param_name): logging.warning( f"{description} {param_name} is deprecated and ignored in this version." ) def _warn_to_deprecate_param(self, param_name, description, new_param): if self._deprecated_params_set.get(param_name): logging.warning( f"{description} {param_name} will be deprecated in future release; " f"please use {new_param} instead." ) return True return False class ComponentBase(ABC): component_name: str thread_limiter = asyncio.Semaphore(int(os.environ.get("MAX_CONCURRENT_CHATS", 10))) variable_ref_patt = r"\{* *\{([a-zA-Z:0-9]+@[A-Za-z0-9_.-]+|sys\.[A-Za-z0-9_.]+|env\.[A-Za-z0-9_.]+)\} *\}*" def __str__(self): """ { "component_name": "Begin", "params": {} } """ return """{{ "component_name": "{}", "params": {} }}""".format(self.component_name, self._param ) def __init__(self, canvas, id, param: ComponentParamBase): from agent.canvas import Graph # Local import to avoid cyclic dependency assert isinstance(canvas, Graph), "canvas must be an instance of Canvas" self._canvas = canvas self._id = id self._param = param self._param.check() def is_canceled(self) -> bool: return self._canvas.is_canceled() def check_if_canceled(self, message: str = "") -> bool: if self.is_canceled(): task_id = getattr(self._canvas, 'task_id', 'unknown') log_message = f"Task {task_id} has been canceled" if message: log_message += f" during {message}" logging.info(log_message) self.set_output("_ERROR", "Task has been canceled") return True return False def invoke(self, **kwargs) -> dict[str, Any]: self.set_output("_created_time", time.perf_counter()) try: self._invoke(**kwargs) except Exception as e: if self.get_exception_default_value(): self.set_exception_default_value() else: self.set_output("_ERROR", str(e)) logging.exception(e) self._param.debug_inputs = {} self.set_output("_elapsed_time", time.perf_counter() - self.output("_created_time")) return self.output() async def invoke_async(self, **kwargs) -> dict[str, Any]: """ Async wrapper for component invocation. Prefers coroutine `_invoke_async` if present; otherwise falls back to `_invoke`. Handles timing and error recording consistently with `invoke`. """ self.set_output("_created_time", time.perf_counter()) try: if self.check_if_canceled("Component processing"): return fn_async = getattr(self, "_invoke_async", None) if fn_async and asyncio.iscoroutinefunction(fn_async): await fn_async(**kwargs) elif asyncio.iscoroutinefunction(self._invoke): await self._invoke(**kwargs) else: await asyncio.to_thread(self._invoke, **kwargs) except Exception as e: if self.get_exception_default_value(): self.set_exception_default_value() else: self.set_output("_ERROR", str(e)) logging.exception(e) self._param.debug_inputs = {} self.set_output("_elapsed_time", time.perf_counter() - self.output("_created_time")) return self.output() @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10 * 60))) def _invoke(self, **kwargs): raise NotImplementedError() def output(self, var_nm: str = None) -> Union[dict[str, Any], Any]: if var_nm: return self._param.outputs.get(var_nm, {}).get("value", "") return {k: o.get("value") for k, o in self._param.outputs.items()} def set_output(self, key: str, value: Any): if key not in self._param.outputs: self._param.outputs[key] = {"value": None, "type": str(type(value))} self._param.outputs[key]["value"] = value def error(self): return self._param.outputs.get("_ERROR", {}).get("value") def reset(self, only_output=False): outputs: dict = self._param.outputs # for better performance for k in outputs.keys(): outputs[k]["value"] = None if only_output: return inputs: dict = self._param.inputs # for better performance for k in inputs.keys(): inputs[k]["value"] = None self._param.debug_inputs = {} def get_input(self, key: str = None) -> Union[Any, dict[str, Any]]: if key: return self._param.inputs.get(key, {}).get("value") res = {} for var, o in self.get_input_elements().items(): v = self.get_param(var) if v is None: continue if isinstance(v, str) and self._canvas.is_reff(v): self.set_input_value(var, self._canvas.get_variable_value(v)) else: self.set_input_value(var, v) res[var] = self.get_input_value(var) return res def get_input_values(self) -> Union[Any, dict[str, Any]]: if self._param.debug_inputs: return self._param.debug_inputs return {var: self.get_input_value(var) for var, o in self.get_input_elements().items()} def get_input_elements_from_text(self, txt: str) -> dict[str, dict[str, str]]: res = {} for r in re.finditer(self.variable_ref_patt, txt, flags=re.IGNORECASE | re.DOTALL): exp = r.group(1) cpn_id, var_nm = exp.split("@") if exp.find("@") > 0 else ("", exp) res[exp] = { "name": (self._canvas.get_component_name(cpn_id) + f"@{var_nm}") if cpn_id else exp, "value": self._canvas.get_variable_value(exp), "_retrieval": self._canvas.get_variable_value(f"{cpn_id}@_references") if cpn_id else None, "_cpn_id": cpn_id } return res def get_input_elements(self) -> dict[str, Any]: return self._param.inputs def get_input_form(self) -> dict[str, dict]: return self._param.get_input_form() def set_input_value(self, key: str, value: Any) -> None: if key not in self._param.inputs: self._param.inputs[key] = {"value": None} self._param.inputs[key]["value"] = value def get_input_value(self, key: str) -> Any: if key not in self._param.inputs: return None return self._param.inputs[key].get("value") def get_component_name(self, cpn_id) -> str: return self._canvas.get_component(cpn_id)["obj"].component_name.lower() def get_param(self, name): if hasattr(self._param, name): return getattr(self._param, name) return None def debug(self, **kwargs): return self._invoke(**kwargs) def get_parent(self) -> Union[object, None]: pid = self._canvas.get_component(self._id).get("parent_id") if not pid: return None return self._canvas.get_component(pid)["obj"] def get_upstream(self) -> List[str]: cpn_nms = self._canvas.get_component(self._id)['upstream'] return cpn_nms def get_downstream(self) -> List[str]: cpn_nms = self._canvas.get_component(self._id)['downstream'] return cpn_nms @staticmethod def string_format(content: str, kv: dict[str, str]) -> str: for n, v in kv.items(): def repl(_match, val=v): return str(val) if val is not None else "" content = re.sub( r"\{%s\}" % re.escape(n), repl, content ) return content def exception_handler(self): if not self._param.exception_method: return None return { "goto": self._param.exception_goto, "default_value": self._param.exception_default_value } def get_exception_default_value(self): if self._param.exception_method != "comment": return "" return self._param.exception_default_value def set_exception_default_value(self): self.set_output("result", self.get_exception_default_value()) def thoughts(self) -> str: raise NotImplementedError()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/categorize.py
agent/component/categorize.py
# # Copyright 2024 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 asyncio import logging import os import re from abc import ABC from common.constants import LLMType from api.db.services.llm_service import LLMBundle from agent.component.llm import LLMParam, LLM from common.connection_utils import timeout from rag.llm.chat_model import ERROR_PREFIX class CategorizeParam(LLMParam): """ Define the categorize component parameters. """ def __init__(self): super().__init__() self.category_description = {} self.query = "sys.query" self.message_history_window_size = 1 self.update_prompt() def check(self): self.check_positive_integer(self.message_history_window_size, "[Categorize] Message window size > 0") self.check_empty(self.category_description, "[Categorize] Category examples") for k, v in self.category_description.items(): if not k: raise ValueError("[Categorize] Category name can not be empty!") if not v.get("to"): raise ValueError(f"[Categorize] 'To' of category {k} can not be empty!") def get_input_form(self) -> dict[str, dict]: return { "query": { "type": "line", "name": "Query" } } def update_prompt(self): cate_lines = [] for c, desc in self.category_description.items(): for line in desc.get("examples", []): if not line: continue cate_lines.append("USER: \"" + re.sub(r"\n", " ", line, flags=re.DOTALL) + "\" โ†’ "+c) descriptions = [] for c, desc in self.category_description.items(): if desc.get("description"): descriptions.append( "\n------\nCategory: {}\nDescription: {}".format(c, desc["description"])) self.sys_prompt = """ You are an advanced classification system that categorizes user questions into specific types. Analyze the input question and classify it into ONE of the following categories: {} Here's description of each category: - {} ---- Instructions ---- - Consider both explicit mentions and implied context - Prioritize the most specific applicable category - Return only the category name without explanations - Use "Other" only when no other category fits """.format( "\n - ".join(list(self.category_description.keys())), "\n".join(descriptions) ) if cate_lines: self.sys_prompt += """ ---- Examples ---- {} """.format("\n".join(cate_lines)) class Categorize(LLM, ABC): component_name = "Categorize" @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) async def _invoke_async(self, **kwargs): if self.check_if_canceled("Categorize processing"): return msg = self._canvas.get_history(self._param.message_history_window_size) if not msg: msg = [{"role": "user", "content": ""}] if kwargs.get("sys.query"): msg[-1]["content"] = kwargs["sys.query"] self.set_input_value("sys.query", kwargs["sys.query"]) else: msg[-1]["content"] = self._canvas.get_variable_value(self._param.query) self.set_input_value(self._param.query, msg[-1]["content"]) self._param.update_prompt() chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id) user_prompt = """ ---- Real Data ---- {} โ†’ """.format(" | ".join(["{}: \"{}\"".format(c["role"].upper(), re.sub(r"\n", "", c["content"], flags=re.DOTALL)) for c in msg])) if self.check_if_canceled("Categorize processing"): return ans = await chat_mdl.async_chat(self._param.sys_prompt, [{"role": "user", "content": user_prompt}], self._param.gen_conf()) logging.info(f"input: {user_prompt}, answer: {str(ans)}") if ERROR_PREFIX in ans: raise Exception(ans) if self.check_if_canceled("Categorize processing"): return # Count the number of times each category appears in the answer. category_counts = {} for c in self._param.category_description.keys(): count = ans.lower().count(c.lower()) category_counts[c] = count cpn_ids = list(self._param.category_description.items())[-1][1]["to"] max_category = list(self._param.category_description.keys())[0] if any(category_counts.values()): max_category = max(category_counts.items(), key=lambda x: x[1])[0] cpn_ids = self._param.category_description[max_category]["to"] self.set_output("category_name", max_category) self.set_output("_next", cpn_ids) @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10*60))) def _invoke(self, **kwargs): return asyncio.run(self._invoke_async(**kwargs)) def thoughts(self) -> str: return "Which should it falls into {}? ...".format(",".join([f"`{c}`" for c, _ in self._param.category_description.items()]))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/loopitem.py
agent/component/loopitem.py
# # Copyright 2024 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. # from abc import ABC from agent.component.base import ComponentBase, ComponentParamBase class LoopItemParam(ComponentParamBase): """ Define the LoopItem component parameters. """ def check(self): return True class LoopItem(ComponentBase, ABC): component_name = "LoopItem" def __init__(self, canvas, id, param: ComponentParamBase): super().__init__(canvas, id, param) self._idx = 0 def _invoke(self, **kwargs): if self.check_if_canceled("LoopItem processing"): return parent = self.get_parent() maximum_loop_count = parent._param.maximum_loop_count if self._idx >= maximum_loop_count: self._idx = -1 return if self._idx > 0: if self.check_if_canceled("LoopItem processing"): return self._idx += 1 def evaluate_condition(self,var, operator, value): if isinstance(var, str): if operator == "contains": return value in var elif operator == "not contains": return value not in var elif operator == "start with": return var.startswith(value) elif operator == "end with": return var.endswith(value) elif operator == "is": return var == value elif operator == "is not": return var != value elif operator == "empty": return var == "" elif operator == "not empty": return var != "" elif isinstance(var, (int, float)): if operator == "=": return var == value elif operator == "โ‰ ": return var != value elif operator == ">": return var > value elif operator == "<": return var < value elif operator == "โ‰ฅ": return var >= value elif operator == "โ‰ค": return var <= value elif operator == "empty": return var is None elif operator == "not empty": return var is not None elif isinstance(var, bool): if operator == "is": return var is value elif operator == "is not": return var is not value elif operator == "empty": return var is None elif operator == "not empty": return var is not None elif isinstance(var, dict): if operator == "empty": return len(var) == 0 elif operator == "not empty": return len(var) > 0 elif isinstance(var, list): if operator == "contains": return value in var elif operator == "not contains": return value not in var elif operator == "is": return var == value elif operator == "is not": return var != value elif operator == "empty": return len(var) == 0 elif operator == "not empty": return len(var) > 0 elif var is None: if operator == "empty": return True return False raise Exception(f"Invalid operator: {operator}") def end(self): if self._idx == -1: return True parent = self.get_parent() logical_operator = parent._param.logical_operator if hasattr(parent._param, "logical_operator") else "and" conditions = [] for item in parent._param.loop_termination_condition: if not item.get("variable") or not item.get("operator"): raise ValueError("Loop condition is incomplete.") var = self._canvas.get_variable_value(item["variable"]) operator = item["operator"] input_mode = item.get("input_mode", "constant") if input_mode == "variable": value = self._canvas.get_variable_value(item.get("value", "")) elif input_mode == "constant": value = item.get("value", "") else: raise ValueError("Invalid input mode.") conditions.append(self.evaluate_condition(var, operator, value)) should_end = ( all(conditions) if logical_operator == "and" else any(conditions) if logical_operator == "or" else None ) if should_end is None: raise ValueError("Invalid logical operator,should be 'and' or 'or'.") if should_end: self._idx = -1 return True return False def next(self): if self._idx == -1: self._idx = 0 else: self._idx += 1 if self._idx >= len(self._items): self._idx = -1 return False def thoughts(self) -> str: return "Next turn..."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/agent_with_tools.py
agent/component/agent_with_tools.py
# # Copyright 2024 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 asyncio import json import logging import os import re from copy import deepcopy from functools import partial from typing import Any import json_repair from timeit import default_timer as timer from agent.tools.base import LLMToolPluginCallSession, ToolParamBase, ToolBase, ToolMeta from api.db.services.llm_service import LLMBundle from api.db.services.tenant_llm_service import TenantLLMService from api.db.services.mcp_server_service import MCPServerService from common.connection_utils import timeout from rag.prompts.generator import next_step_async, COMPLETE_TASK, \ citation_prompt, kb_prompt, citation_plus, full_question, message_fit_in, structured_output_prompt from common.mcp_tool_call_conn import MCPToolCallSession, mcp_tool_metadata_to_openai_tool from agent.component.llm import LLMParam, LLM class AgentParam(LLMParam, ToolParamBase): """ Define the Agent component parameters. """ def __init__(self): self.meta:ToolMeta = { "name": "agent", "description": "This is an agent for a specific task.", "parameters": { "user_prompt": { "type": "string", "description": "This is the order you need to send to the agent.", "default": "", "required": True }, "reasoning": { "type": "string", "description": ( "Supervisor's reasoning for choosing the this agent. " "Explain why this agent is being invoked and what is expected of it." ), "required": True }, "context": { "type": "string", "description": ( "All relevant background information, prior facts, decisions, " "and state needed by the agent to solve the current query. " "Should be as detailed and self-contained as possible." ), "required": True }, } } super().__init__() self.function_name = "agent" self.tools = [] self.mcp = [] self.max_rounds = 5 self.description = "" class Agent(LLM, ToolBase): component_name = "Agent" def __init__(self, canvas, id, param: LLMParam): LLM.__init__(self, canvas, id, param) self.tools = {} for idx, cpn in enumerate(self._param.tools): cpn = self._load_tool_obj(cpn) original_name = cpn.get_meta()["function"]["name"] indexed_name = f"{original_name}_{idx}" self.tools[indexed_name] = cpn self.chat_mdl = LLMBundle(self._canvas.get_tenant_id(), TenantLLMService.llm_id2llm_type(self._param.llm_id), self._param.llm_id, max_retries=self._param.max_retries, retry_interval=self._param.delay_after_error, max_rounds=self._param.max_rounds, verbose_tool_use=True ) self.tool_meta = [] for indexed_name, tool_obj in self.tools.items(): original_meta = tool_obj.get_meta() indexed_meta = deepcopy(original_meta) indexed_meta["function"]["name"] = indexed_name self.tool_meta.append(indexed_meta) for mcp in self._param.mcp: _, mcp_server = MCPServerService.get_by_id(mcp["mcp_id"]) tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables) for tnm, meta in mcp["tools"].items(): self.tool_meta.append(mcp_tool_metadata_to_openai_tool(meta)) self.tools[tnm] = tool_call_session self.callback = partial(self._canvas.tool_use_callback, id) self.toolcall_session = LLMToolPluginCallSession(self.tools, self.callback) #self.chat_mdl.bind_tools(self.toolcall_session, self.tool_metas) def _load_tool_obj(self, cpn: dict) -> object: from agent.component import component_class tool_name = cpn["component_name"] param = component_class(tool_name + "Param")() param.update(cpn["params"]) try: param.check() except Exception as e: self.set_output("_ERROR", cpn["component_name"] + f" configuration error: {e}") raise cpn_id = f"{self._id}-->" + cpn.get("name", "").replace(" ", "_") return component_class(cpn["component_name"])(self._canvas, cpn_id, param) def get_meta(self) -> dict[str, Any]: self._param.function_name= self._id.split("-->")[-1] m = super().get_meta() if hasattr(self._param, "user_prompt") and self._param.user_prompt: m["function"]["parameters"]["properties"]["user_prompt"] = self._param.user_prompt return m def get_input_form(self) -> dict[str, dict]: res = {} for k, v in self.get_input_elements().items(): res[k] = { "type": "line", "name": v["name"] } for cpn in self._param.tools: if not isinstance(cpn, LLM): continue res.update(cpn.get_input_form()) return res def _get_output_schema(self): try: cand = self._param.outputs.get("structured") except Exception: return None if isinstance(cand, dict): if isinstance(cand.get("properties"), dict) and len(cand["properties"]) > 0: return cand for k in ("schema", "structured"): if isinstance(cand.get(k), dict) and isinstance(cand[k].get("properties"), dict) and len(cand[k]["properties"]) > 0: return cand[k] return None async def _force_format_to_schema_async(self, text: str, schema_prompt: str) -> str: fmt_msgs = [ {"role": "system", "content": schema_prompt + "\nIMPORTANT: Output ONLY valid JSON. No markdown, no extra text."}, {"role": "user", "content": text}, ] _, fmt_msgs = message_fit_in(fmt_msgs, int(self.chat_mdl.max_length * 0.97)) return await self._generate_async(fmt_msgs) def _invoke(self, **kwargs): return asyncio.run(self._invoke_async(**kwargs)) @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 20*60))) async def _invoke_async(self, **kwargs): if self.check_if_canceled("Agent processing"): return if kwargs.get("user_prompt"): usr_pmt = "" if kwargs.get("reasoning"): usr_pmt += "\nREASONING:\n{}\n".format(kwargs["reasoning"]) if kwargs.get("context"): usr_pmt += "\nCONTEXT:\n{}\n".format(kwargs["context"]) if usr_pmt: usr_pmt += "\nQUERY:\n{}\n".format(str(kwargs["user_prompt"])) else: usr_pmt = str(kwargs["user_prompt"]) self._param.prompts = [{"role": "user", "content": usr_pmt}] if not self.tools: if self.check_if_canceled("Agent processing"): return return await LLM._invoke_async(self, **kwargs) prompt, msg, user_defined_prompt = self._prepare_prompt_variables() output_schema = self._get_output_schema() schema_prompt = "" if output_schema: schema = json.dumps(output_schema, ensure_ascii=False, indent=2) schema_prompt = structured_output_prompt(schema) downstreams = self._canvas.get_component(self._id)["downstream"] if self._canvas.get_component(self._id) else [] ex = self.exception_handler() if any([self._canvas.get_component_obj(cid).component_name.lower()=="message" for cid in downstreams]) and not (ex and ex["goto"]) and not output_schema: self.set_output("content", partial(self.stream_output_with_tools_async, prompt, deepcopy(msg), user_defined_prompt)) return _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(self.chat_mdl.max_length * 0.97)) use_tools = [] ans = "" async for delta_ans, _tk in self._react_with_tools_streamly_async_simple(prompt, msg, use_tools, user_defined_prompt,schema_prompt=schema_prompt): if self.check_if_canceled("Agent processing"): return ans += delta_ans if ans.find("**ERROR**") >= 0: logging.error(f"Agent._chat got error. response: {ans}") if self.get_exception_default_value(): self.set_output("content", self.get_exception_default_value()) else: self.set_output("_ERROR", ans) return if output_schema: error = "" for _ in range(self._param.max_retries + 1): try: def clean_formated_answer(ans: str) -> str: ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL) ans = re.sub(r"^.*```json", "", ans, flags=re.DOTALL) return re.sub(r"```\n*$", "", ans, flags=re.DOTALL) obj = json_repair.loads(clean_formated_answer(ans)) self.set_output("structured", obj) if use_tools: self.set_output("use_tools", use_tools) return obj except Exception: error = "The answer cannot be parsed as JSON" ans = await self._force_format_to_schema_async(ans, schema_prompt) if ans.find("**ERROR**") >= 0: continue self.set_output("_ERROR", error) return self.set_output("content", ans) if use_tools: self.set_output("use_tools", use_tools) return ans async def stream_output_with_tools_async(self, prompt, msg, user_defined_prompt={}): _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(self.chat_mdl.max_length * 0.97)) answer_without_toolcall = "" use_tools = [] async for delta_ans, _ in self._react_with_tools_streamly_async_simple(prompt, msg, use_tools, user_defined_prompt): if self.check_if_canceled("Agent streaming"): return if delta_ans.find("**ERROR**") >= 0: if self.get_exception_default_value(): self.set_output("content", self.get_exception_default_value()) yield self.get_exception_default_value() else: self.set_output("_ERROR", delta_ans) return answer_without_toolcall += delta_ans yield delta_ans self.set_output("content", answer_without_toolcall) if use_tools: self.set_output("use_tools", use_tools) async def _react_with_tools_streamly_async_simple(self, prompt, history: list[dict], use_tools, user_defined_prompt={}, schema_prompt: str = ""): token_count = 0 tool_metas = self.tool_meta hist = deepcopy(history) last_calling = "" if len(hist) > 3: st = timer() user_request = await full_question(messages=history, chat_mdl=self.chat_mdl) self.callback("Multi-turn conversation optimization", {}, user_request, elapsed_time=timer()-st) else: user_request = history[-1]["content"] def build_task_desc(prompt: str, user_request: str, user_defined_prompt: dict | None = None) -> str: """Build a minimal task_desc by concatenating prompt, query, and tool schemas.""" user_defined_prompt = user_defined_prompt or {} task_desc = ( "### Agent Prompt\n" f"{prompt}\n\n" "### User Request\n" f"{user_request}\n\n" ) if user_defined_prompt: udp_json = json.dumps(user_defined_prompt, ensure_ascii=False, indent=2) task_desc += "\n### User Defined Prompts\n" + udp_json + "\n" return task_desc async def use_tool_async(name, args): nonlocal hist, use_tools, last_calling logging.info(f"{last_calling=} == {name=}") last_calling = name tool_response = await self.toolcall_session.tool_call_async(name, args) use_tools.append({ "name": name, "arguments": args, "results": tool_response }) return name, tool_response async def complete(): nonlocal hist need2cite = self._param.cite and self._canvas.get_reference()["chunks"] and self._id.find("-->") < 0 if schema_prompt: need2cite = False cited = False if hist and hist[0]["role"] == "system": if schema_prompt: hist[0]["content"] += "\n" + schema_prompt if need2cite and len(hist) < 7: hist[0]["content"] += citation_prompt() cited = True yield "", token_count _hist = hist if len(hist) > 12: _hist = [hist[0], hist[1], *hist[-10:]] entire_txt = "" async for delta_ans in self._generate_streamly(_hist): if not need2cite or cited: yield delta_ans, 0 entire_txt += delta_ans if not need2cite or cited: return st = timer() txt = "" async for delta_ans in self._gen_citations_async(entire_txt): if self.check_if_canceled("Agent streaming"): return yield delta_ans, 0 txt += delta_ans self.callback("gen_citations", {}, txt, elapsed_time=timer()-st) def build_observation(tool_call_res: list[tuple]) -> str: """ Build a Observation from tool call results. No LLM involved. """ if not tool_call_res: return "" lines = ["Observation:"] for name, result in tool_call_res: lines.append(f"[{name} result]") lines.append(str(result)) return "\n".join(lines) def append_user_content(hist, content): if hist[-1]["role"] == "user": hist[-1]["content"] += content else: hist.append({"role": "user", "content": content}) st = timer() task_desc = build_task_desc(prompt, user_request, user_defined_prompt) self.callback("analyze_task", {}, task_desc, elapsed_time=timer()-st) for _ in range(self._param.max_rounds + 1): if self.check_if_canceled("Agent streaming"): return response, tk = await next_step_async(self.chat_mdl, hist, tool_metas, task_desc, user_defined_prompt) # self.callback("next_step", {}, str(response)[:256]+"...") token_count += tk or 0 hist.append({"role": "assistant", "content": response}) try: functions = json_repair.loads(re.sub(r"```.*", "", response)) if not isinstance(functions, list): raise TypeError(f"List should be returned, but `{functions}`") for f in functions: if not isinstance(f, dict): raise TypeError(f"An object type should be returned, but `{f}`") tool_tasks = [] for func in functions: name = func["name"] args = func["arguments"] if name == COMPLETE_TASK: append_user_content(hist, f"Respond with a formal answer. FORGET(DO NOT mention) about `{COMPLETE_TASK}`. The language for the response MUST be as the same as the first user request.\n") async for txt, tkcnt in complete(): yield txt, tkcnt return tool_tasks.append(asyncio.create_task(use_tool_async(name, args))) results = await asyncio.gather(*tool_tasks) if tool_tasks else [] st = timer() reflection = build_observation(results) append_user_content(hist, reflection) self.callback("reflection", {}, str(reflection), elapsed_time=timer()-st) except Exception as e: logging.exception(msg=f"Wrong JSON argument format in LLM ReAct response: {e}") e = f"\nTool call error, please correct the input parameter of response format and call it again.\n *** Exception ***\n{e}" append_user_content(hist, str(e)) logging.warning( f"Exceed max rounds: {self._param.max_rounds}") final_instruction = f""" {user_request} IMPORTANT: You have reached the conversation limit. Based on ALL the information and research you have gathered so far, please provide a DIRECT and COMPREHENSIVE final answer to the original request. Instructions: 1. SYNTHESIZE all information collected during this conversation 2. Provide a COMPLETE response using existing data - do not suggest additional research 3. Structure your response as a FINAL DELIVERABLE, not a plan 4. If information is incomplete, state what you found and provide the best analysis possible with available data 5. DO NOT mention conversation limits or suggest further steps 6. Focus on delivering VALUE with the information already gathered Respond immediately with your final comprehensive answer. """ if self.check_if_canceled("Agent final instruction"): return append_user_content(hist, final_instruction) async for txt, tkcnt in complete(): yield txt, tkcnt # async def _react_with_tools_streamly_async(self, prompt, history: list[dict], use_tools, user_defined_prompt={}, schema_prompt: str = ""): # token_count = 0 # tool_metas = self.tool_meta # hist = deepcopy(history) # last_calling = "" # if len(hist) > 3: # st = timer() # user_request = await full_question(messages=history, chat_mdl=self.chat_mdl) # self.callback("Multi-turn conversation optimization", {}, user_request, elapsed_time=timer()-st) # else: # user_request = history[-1]["content"] # async def use_tool_async(name, args): # nonlocal hist, use_tools, last_calling # logging.info(f"{last_calling=} == {name=}") # last_calling = name # tool_response = await self.toolcall_session.tool_call_async(name, args) # use_tools.append({ # "name": name, # "arguments": args, # "results": tool_response # }) # # self.callback("add_memory", {}, "...") # #self.add_memory(hist[-2]["content"], hist[-1]["content"], name, args, str(tool_response), user_defined_prompt) # return name, tool_response # async def complete(): # nonlocal hist # need2cite = self._param.cite and self._canvas.get_reference()["chunks"] and self._id.find("-->") < 0 # if schema_prompt: # need2cite = False # cited = False # if hist and hist[0]["role"] == "system": # if schema_prompt: # hist[0]["content"] += "\n" + schema_prompt # if need2cite and len(hist) < 7: # hist[0]["content"] += citation_prompt() # cited = True # yield "", token_count # _hist = hist # if len(hist) > 12: # _hist = [hist[0], hist[1], *hist[-10:]] # entire_txt = "" # async for delta_ans in self._generate_streamly(_hist): # if not need2cite or cited: # yield delta_ans, 0 # entire_txt += delta_ans # if not need2cite or cited: # return # st = timer() # txt = "" # async for delta_ans in self._gen_citations_async(entire_txt): # if self.check_if_canceled("Agent streaming"): # return # yield delta_ans, 0 # txt += delta_ans # self.callback("gen_citations", {}, txt, elapsed_time=timer()-st) # def append_user_content(hist, content): # if hist[-1]["role"] == "user": # hist[-1]["content"] += content # else: # hist.append({"role": "user", "content": content}) # st = timer() # task_desc = await analyze_task_async(self.chat_mdl, prompt, user_request, tool_metas, user_defined_prompt) # self.callback("analyze_task", {}, task_desc, elapsed_time=timer()-st) # for _ in range(self._param.max_rounds + 1): # if self.check_if_canceled("Agent streaming"): # return # response, tk = await next_step_async(self.chat_mdl, hist, tool_metas, task_desc, user_defined_prompt) # # self.callback("next_step", {}, str(response)[:256]+"...") # token_count += tk or 0 # hist.append({"role": "assistant", "content": response}) # try: # functions = json_repair.loads(re.sub(r"```.*", "", response)) # if not isinstance(functions, list): # raise TypeError(f"List should be returned, but `{functions}`") # for f in functions: # if not isinstance(f, dict): # raise TypeError(f"An object type should be returned, but `{f}`") # tool_tasks = [] # for func in functions: # name = func["name"] # args = func["arguments"] # if name == COMPLETE_TASK: # append_user_content(hist, f"Respond with a formal answer. FORGET(DO NOT mention) about `{COMPLETE_TASK}`. The language for the response MUST be as the same as the first user request.\n") # async for txt, tkcnt in complete(): # yield txt, tkcnt # return # tool_tasks.append(asyncio.create_task(use_tool_async(name, args))) # results = await asyncio.gather(*tool_tasks) if tool_tasks else [] # st = timer() # reflection = await reflect_async(self.chat_mdl, hist, results, user_defined_prompt) # append_user_content(hist, reflection) # self.callback("reflection", {}, str(reflection), elapsed_time=timer()-st) # except Exception as e: # logging.exception(msg=f"Wrong JSON argument format in LLM ReAct response: {e}") # e = f"\nTool call error, please correct the input parameter of response format and call it again.\n *** Exception ***\n{e}" # append_user_content(hist, str(e)) # logging.warning( f"Exceed max rounds: {self._param.max_rounds}") # final_instruction = f""" # {user_request} # IMPORTANT: You have reached the conversation limit. Based on ALL the information and research you have gathered so far, please provide a DIRECT and COMPREHENSIVE final answer to the original request. # Instructions: # 1. SYNTHESIZE all information collected during this conversation # 2. Provide a COMPLETE response using existing data - do not suggest additional research # 3. Structure your response as a FINAL DELIVERABLE, not a plan # 4. If information is incomplete, state what you found and provide the best analysis possible with available data # 5. DO NOT mention conversation limits or suggest further steps # 6. Focus on delivering VALUE with the information already gathered # Respond immediately with your final comprehensive answer. # """ # if self.check_if_canceled("Agent final instruction"): # return # append_user_content(hist, final_instruction) # async for txt, tkcnt in complete(): # yield txt, tkcnt async def _gen_citations_async(self, text): retrievals = self._canvas.get_reference() retrievals = {"chunks": list(retrievals["chunks"].values()), "doc_aggs": list(retrievals["doc_aggs"].values())} formated_refer = kb_prompt(retrievals, self.chat_mdl.max_length, True) async for delta_ans in self._generate_streamly([{"role": "system", "content": citation_plus("\n\n".join(formated_refer))}, {"role": "user", "content": text} ]): yield delta_ans def reset(self, only_output=False): """ Reset all tools if they have a reset method. This avoids errors for tools like MCPToolCallSession. """ for k in self._param.outputs.keys(): self._param.outputs[k]["value"] = None for k, cpn in self.tools.items(): if hasattr(cpn, "reset") and callable(cpn.reset): cpn.reset() if only_output: return for k in self._param.inputs.keys(): self._param.inputs[k]["value"] = None self._param.debug_inputs = {}
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/agent/component/loop.py
agent/component/loop.py
# # Copyright 2024 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. # from abc import ABC from agent.component.base import ComponentBase, ComponentParamBase class LoopParam(ComponentParamBase): """ Define the Loop component parameters. """ def __init__(self): super().__init__() self.loop_variables = [] self.loop_termination_condition=[] self.maximum_loop_count = 0 def get_input_form(self) -> dict[str, dict]: return { "items": { "type": "json", "name": "Items" } } def check(self): return True class Loop(ComponentBase, ABC): component_name = "Loop" def get_start(self): for cid in self._canvas.components.keys(): if self._canvas.get_component(cid)["obj"].component_name.lower() != "loopitem": continue if self._canvas.get_component(cid)["parent_id"] == self._id: return cid def _invoke(self, **kwargs): if self.check_if_canceled("Loop processing"): return for item in self._param.loop_variables: if any([not item.get("variable"), not item.get("input_mode"), not item.get("value"),not item.get("type")]): assert "Loop Variable is not complete." if item["input_mode"]=="variable": self.set_output(item["variable"],self._canvas.get_variable_value(item["value"])) elif item["input_mode"]=="constant": self.set_output(item["variable"],item["value"]) else: if item["type"] == "number": self.set_output(item["variable"], 0) elif item["type"] == "string": self.set_output(item["variable"], "") elif item["type"] == "boolean": self.set_output(item["variable"], False) elif item["type"].startswith("object"): self.set_output(item["variable"], {}) elif item["type"].startswith("array"): self.set_output(item["variable"], []) else: self.set_output(item["variable"], "") def thoughts(self) -> str: return "Loop from canvas."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/hello_ragflow.py
sdk/python/hello_ragflow.py
# # 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 ragflow_sdk print(ragflow_sdk.__version__)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/__init__.py
sdk/python/ragflow_sdk/__init__.py
# # 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. # from beartype.claw import beartype_this_package beartype_this_package() import importlib.metadata from .ragflow import RAGFlow from .modules.dataset import DataSet from .modules.chat import Chat from .modules.session import Session from .modules.document import Document from .modules.chunk import Chunk from .modules.agent import Agent __version__ = importlib.metadata.version("ragflow_sdk") __all__ = [ "RAGFlow", "DataSet", "Chat", "Session", "Document", "Chunk", "Agent" ]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/ragflow.py
sdk/python/ragflow_sdk/ragflow.py
# # Copyright 2024 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. from typing import Optional import requests from .modules.agent import Agent from .modules.chat import Chat from .modules.chunk import Chunk from .modules.dataset import DataSet class RAGFlow: def __init__(self, api_key, base_url, version="v1"): """ api_url: http://<host_address>/api/v1 """ self.user_key = api_key self.api_url = f"{base_url}/api/{version}" self.authorization_header = {"Authorization": "{} {}".format("Bearer", self.user_key)} def post(self, path, json=None, stream=False, files=None): res = requests.post(url=self.api_url + path, json=json, headers=self.authorization_header, stream=stream, files=files) return res def get(self, path, params=None, json=None): res = requests.get(url=self.api_url + path, params=params, headers=self.authorization_header, json=json) return res def delete(self, path, json): res = requests.delete(url=self.api_url + path, json=json, headers=self.authorization_header) return res def put(self, path, json): res = requests.put(url=self.api_url + path, json=json, headers=self.authorization_header) return res def create_dataset( self, name: str, avatar: Optional[str] = None, description: Optional[str] = None, embedding_model: Optional[str] = None, permission: str = "me", chunk_method: str = "naive", parser_config: Optional[DataSet.ParserConfig] = None, ) -> DataSet: payload = { "name": name, "avatar": avatar, "description": description, "embedding_model": embedding_model, "permission": permission, "chunk_method": chunk_method, } if parser_config is not None: payload["parser_config"] = parser_config.to_json() res = self.post("/datasets", payload) res = res.json() if res.get("code") == 0: return DataSet(self, res["data"]) raise Exception(res["message"]) def delete_datasets(self, ids: list[str] | None = None): res = self.delete("/datasets", {"ids": ids}) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) def get_dataset(self, name: str): _list = self.list_datasets(name=name) if len(_list) > 0: return _list[0] raise Exception("Dataset %s not found" % name) def list_datasets(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, id: str | None = None, name: str | None = None) -> list[DataSet]: res = self.get( "/datasets", { "page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name, }, ) res = res.json() result_list = [] if res.get("code") == 0: for data in res["data"]: result_list.append(DataSet(self, data)) return result_list raise Exception(res["message"]) def create_chat(self, name: str, avatar: str = "", dataset_ids=None, llm: Chat.LLM | None = None, prompt: Chat.Prompt | None = None) -> Chat: if dataset_ids is None: dataset_ids = [] dataset_list = [] for id in dataset_ids: dataset_list.append(id) if llm is None: llm = Chat.LLM( self, { "model_name": None, "temperature": 0.1, "top_p": 0.3, "presence_penalty": 0.4, "frequency_penalty": 0.7, "max_tokens": 512, }, ) if prompt is None: prompt = Chat.Prompt( self, { "similarity_threshold": 0.2, "keywords_similarity_weight": 0.7, "top_n": 8, "top_k": 1024, "variables": [{"key": "knowledge", "optional": True}], "rerank_model": "", "empty_response": None, "opener": None, "show_quote": True, "prompt": None, }, ) if prompt.opener is None: prompt.opener = "Hi! I'm your assistant. What can I do for you?" if prompt.prompt is None: prompt.prompt = ( "You are an intelligent assistant. Your primary function is to answer questions based strictly on the provided knowledge base." "**Essential Rules:**" "- Your answer must be derived **solely** from this knowledge base: `{knowledge}`." "- **When information is available**: Summarize the content to give a detailed answer." "- **When information is unavailable**: Your response must contain this exact sentence: 'The answer you are looking for is not found in the knowledge base!' " "- **Always consider** the entire conversation history." ) temp_dict = {"name": name, "avatar": avatar, "dataset_ids": dataset_list if dataset_list else [], "llm": llm.to_json(), "prompt": prompt.to_json()} res = self.post("/chats", temp_dict) res = res.json() if res.get("code") == 0: return Chat(self, res["data"]) raise Exception(res["message"]) def delete_chats(self, ids: list[str] | None = None): res = self.delete("/chats", {"ids": ids}) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) def list_chats(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, id: str | None = None, name: str | None = None) -> list[Chat]: res = self.get( "/chats", { "page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name, }, ) res = res.json() result_list = [] if res.get("code") == 0: for data in res["data"]: result_list.append(Chat(self, data)) return result_list raise Exception(res["message"]) def retrieve( self, dataset_ids, document_ids=None, question="", page=1, page_size=30, similarity_threshold=0.2, vector_similarity_weight=0.3, top_k=1024, rerank_id: str | None = None, keyword: bool = False, cross_languages: list[str]|None = None, metadata_condition: dict | None = None, use_kg: bool = False, toc_enhance: bool = False, ): if document_ids is None: document_ids = [] data_json = { "page": page, "page_size": page_size, "similarity_threshold": similarity_threshold, "vector_similarity_weight": vector_similarity_weight, "top_k": top_k, "rerank_id": rerank_id, "keyword": keyword, "question": question, "dataset_ids": dataset_ids, "document_ids": document_ids, "cross_languages": cross_languages, "metadata_condition": metadata_condition, "use_kg": use_kg, "toc_enhance": toc_enhance } # Send a POST request to the backend service (using requests library as an example, actual implementation may vary) res = self.post("/retrieval", json=data_json) res = res.json() if res.get("code") == 0: chunks = [] for chunk_data in res["data"].get("chunks"): chunk = Chunk(self, chunk_data) chunks.append(chunk) return chunks raise Exception(res.get("message")) def list_agents(self, page: int = 1, page_size: int = 30, orderby: str = "update_time", desc: bool = True, id: str | None = None, title: str | None = None) -> list[Agent]: res = self.get( "/agents", { "page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "title": title, }, ) res = res.json() result_list = [] if res.get("code") == 0: for data in res["data"]: result_list.append(Agent(self, data)) return result_list raise Exception(res["message"]) def create_agent(self, title: str, dsl: dict, description: str | None = None) -> None: req = {"title": title, "dsl": dsl} if description is not None: req["description"] = description res = self.post("/agents", req) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) def update_agent(self, agent_id: str, title: str | None = None, description: str | None = None, dsl: dict | None = None) -> None: req = {} if title is not None: req["title"] = title if description is not None: req["description"] = description if dsl is not None: req["dsl"] = dsl res = self.put(f"/agents/{agent_id}", req) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) def delete_agent(self, agent_id: str) -> None: res = self.delete(f"/agents/{agent_id}", {}) res = res.json() if res.get("code") != 0: raise Exception(res["message"])
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/chat.py
sdk/python/ragflow_sdk/modules/chat.py
# # 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. # from .base import Base from .session import Session class Chat(Base): def __init__(self, rag, res_dict): self.id = "" self.name = "assistant" self.avatar = "path/to/avatar" self.llm = Chat.LLM(rag, {}) self.prompt = Chat.Prompt(rag, {}) super().__init__(rag, res_dict) class LLM(Base): def __init__(self, rag, res_dict): self.model_name = None self.temperature = 0.1 self.top_p = 0.3 self.presence_penalty = 0.4 self.frequency_penalty = 0.7 self.max_tokens = 512 super().__init__(rag, res_dict) class Prompt(Base): def __init__(self, rag, res_dict): self.similarity_threshold = 0.2 self.keywords_similarity_weight = 0.7 self.top_n = 8 self.top_k = 1024 self.variables = [{"key": "knowledge", "optional": True}] self.rerank_model = "" self.empty_response = None self.opener = "Hi! I'm your assistant. What can I do for you?" self.show_quote = True self.prompt = ( "You are an intelligent assistant. Your primary function is to answer questions based strictly on the provided knowledge base." "**Essential Rules:**" "- Your answer must be derived **solely** from this knowledge base: `{knowledge}`." "- **When information is available**: Summarize the content to give a detailed answer." "- **When information is unavailable**: Your response must contain this exact sentence: 'The answer you are looking for is not found in the knowledge base!' " "- **Always consider** the entire conversation history." ) super().__init__(rag, res_dict) def update(self, update_message: dict): res = self.put(f"/chats/{self.id}", update_message) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) def create_session(self, name: str = "New session") -> Session: res = self.post(f"/chats/{self.id}/sessions", {"name": name}) res = res.json() if res.get("code") == 0: return Session(self.rag, res["data"]) raise Exception(res["message"]) def list_sessions(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, id: str = None, name: str = None) -> list[Session]: res = self.get(f"/chats/{self.id}/sessions", {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name}) res = res.json() if res.get("code") == 0: result_list = [] for data in res["data"]: result_list.append(Session(self.rag, data)) return result_list raise Exception(res["message"]) def delete_sessions(self, ids: list[str] | None = None): res = self.rm(f"/chats/{self.id}/sessions", {"ids": ids}) res = res.json() if res.get("code") != 0: raise Exception(res.get("message"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/document.py
sdk/python/ragflow_sdk/modules/document.py
# # 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 json from .base import Base from .chunk import Chunk class Document(Base): class ParserConfig(Base): def __init__(self, rag, res_dict): super().__init__(rag, res_dict) def __init__(self, rag, res_dict): self.id = "" self.name = "" self.thumbnail = None self.dataset_id = None self.chunk_method = "naive" self.parser_config = {"pages": [[1, 1000000]]} self.source_type = "local" self.type = "" self.created_by = "" self.size = 0 self.token_count = 0 self.chunk_count = 0 self.progress = 0.0 self.progress_msg = "" self.process_begin_at = None self.process_duration = 0.0 self.run = "0" self.status = "1" self.meta_fields = {} for k in list(res_dict.keys()): if k not in self.__dict__: res_dict.pop(k) super().__init__(rag, res_dict) def update(self, update_message: dict): if "meta_fields" in update_message: if not isinstance(update_message["meta_fields"], dict): raise Exception("meta_fields must be a dictionary") res = self.put(f"/datasets/{self.dataset_id}/documents/{self.id}", update_message) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) self._update_from_dict(self.rag, res.get("data", {})) return self def download(self): res = self.get(f"/datasets/{self.dataset_id}/documents/{self.id}") error_keys = set(["code", "message"]) try: response = res.json() actual_keys = set(response.keys()) if actual_keys == error_keys: raise Exception(response.get("message")) else: return res.content except json.JSONDecodeError: return res.content def list_chunks(self, page=1, page_size=30, keywords="", id=""): data = {"keywords": keywords, "page": page, "page_size": page_size, "id": id} res = self.get(f"/datasets/{self.dataset_id}/documents/{self.id}/chunks", data) res = res.json() if res.get("code") == 0: chunks = [] for data in res["data"].get("chunks"): chunk = Chunk(self.rag, data) chunks.append(chunk) return chunks raise Exception(res.get("message")) def add_chunk(self, content: str, important_keywords: list[str] = [], questions: list[str] = []): res = self.post(f"/datasets/{self.dataset_id}/documents/{self.id}/chunks", {"content": content, "important_keywords": important_keywords, "questions": questions}) res = res.json() if res.get("code") == 0: return Chunk(self.rag, res["data"].get("chunk")) raise Exception(res.get("message")) def delete_chunks(self, ids: list[str] | None = None): res = self.rm(f"/datasets/{self.dataset_id}/documents/{self.id}/chunks", {"chunk_ids": ids}) res = res.json() if res.get("code") != 0: raise Exception(res.get("message"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/chunk.py
sdk/python/ragflow_sdk/modules/chunk.py
# # 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. # from .base import Base class ChunkUpdateError(Exception): def __init__(self, code=None, message=None, details=None): self.code = code self.message = message self.details = details super().__init__(message) class Chunk(Base): def __init__(self, rag, res_dict): self.id = "" self.content = "" self.important_keywords = [] self.questions = [] self.create_time = "" self.create_timestamp = 0.0 self.dataset_id = None self.document_name = "" self.documnet_keyword = "" self.document_id = "" self.available = True # Additional fields for retrieval results self.similarity = 0.0 self.vector_similarity = 0.0 self.term_similarity = 0.0 self.positions = [] self.doc_type = "" for k in list(res_dict.keys()): if k not in self.__dict__: res_dict.pop(k) super().__init__(rag, res_dict) #for backward compatibility if not self.document_name: self.document_name = self.documnet_keyword def update(self, update_message: dict): res = self.put(f"/datasets/{self.dataset_id}/documents/{self.document_id}/chunks/{self.id}", update_message) res = res.json() if res.get("code") != 0: raise ChunkUpdateError( code=res.get("code"), message=res.get("message"), details=res.get("details") )
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/dataset.py
sdk/python/ragflow_sdk/modules/dataset.py
# # 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. # from .base import Base from .document import Document class DataSet(Base): class ParserConfig(Base): def __init__(self, rag, res_dict): super().__init__(rag, res_dict) def __init__(self, rag, res_dict): self.id = "" self.name = "" self.avatar = "" self.tenant_id = None self.description = "" self.embedding_model = "" self.permission = "me" self.document_count = 0 self.chunk_count = 0 self.chunk_method = "naive" self.parser_config = None self.pagerank = 0 for k in list(res_dict.keys()): if k not in self.__dict__: res_dict.pop(k) super().__init__(rag, res_dict) def update(self, update_message: dict): res = self.put(f"/datasets/{self.id}", update_message) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) self._update_from_dict(self.rag, res.get("data", {})) return self def upload_documents(self, document_list: list[dict]): url = f"/datasets/{self.id}/documents" files = [("file", (ele["display_name"], ele["blob"])) for ele in document_list] res = self.post(path=url, json=None, files=files) res = res.json() if res.get("code") == 0: doc_list = [] for doc in res["data"]: document = Document(self.rag, doc) doc_list.append(document) return doc_list raise Exception(res.get("message")) def list_documents( self, id: str | None = None, name: str | None = None, keywords: str | None = None, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, create_time_from: int = 0, create_time_to: int = 0, ): params = { "id": id, "name": name, "keywords": keywords, "page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "create_time_from": create_time_from, "create_time_to": create_time_to, } res = self.get(f"/datasets/{self.id}/documents", params=params) res = res.json() documents = [] if res.get("code") == 0: for document in res["data"].get("docs"): documents.append(Document(self.rag, document)) return documents raise Exception(res["message"]) def delete_documents(self, ids: list[str] | None = None): res = self.rm(f"/datasets/{self.id}/documents", {"ids": ids}) res = res.json() if res.get("code") != 0: raise Exception(res["message"]) def _get_documents_status(self, document_ids): import time terminal_states = {"DONE", "FAIL", "CANCEL"} interval_sec = 1 pending = set(document_ids) finished = [] while pending: for doc_id in list(pending): def fetch_doc(doc_id: str) -> Document | None: try: docs = self.list_documents(id=doc_id) return docs[0] if docs else None except Exception: return None doc = fetch_doc(doc_id) if doc is None: continue if isinstance(doc.run, str) and doc.run.upper() in terminal_states: finished.append((doc_id, doc.run, doc.chunk_count, doc.token_count)) pending.discard(doc_id) elif float(doc.progress or 0.0) >= 1.0: finished.append((doc_id, "DONE", doc.chunk_count, doc.token_count)) pending.discard(doc_id) if pending: time.sleep(interval_sec) return finished def async_parse_documents(self, document_ids): res = self.post(f"/datasets/{self.id}/chunks", {"document_ids": document_ids}) res = res.json() if res.get("code") != 0: raise Exception(res.get("message")) def parse_documents(self, document_ids): try: self.async_parse_documents(document_ids) self._get_documents_status(document_ids) except KeyboardInterrupt: self.async_cancel_parse_documents(document_ids) return self._get_documents_status(document_ids) def async_cancel_parse_documents(self, document_ids): res = self.rm(f"/datasets/{self.id}/chunks", {"document_ids": document_ids}) res = res.json() if res.get("code") != 0: raise Exception(res.get("message"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/__init__.py
sdk/python/ragflow_sdk/modules/__init__.py
# # 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. #
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/session.py
sdk/python/ragflow_sdk/modules/session.py
# # 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 json from .base import Base class Session(Base): def __init__(self, rag, res_dict): self.id = None self.name = "New session" self.messages = [{"role": "assistant", "content": "Hi! I am your assistant, can I help you?"}] for key, value in res_dict.items(): if key == "chat_id" and value is not None: self.chat_id = None self.__session_type = "chat" if key == "agent_id" and value is not None: self.agent_id = None self.__session_type = "agent" super().__init__(rag, res_dict) def ask(self, question="", stream=False, **kwargs): """ Ask a question to the session. If stream=True, yields Message objects as they arrive (SSE streaming). If stream=False, returns a single Message object for the final answer. """ if self.__session_type == "agent": res = self._ask_agent(question, stream, **kwargs) elif self.__session_type == "chat": res = self._ask_chat(question, stream, **kwargs) else: raise Exception(f"Unknown session type: {self.__session_type}") if stream: for line in res.iter_lines(decode_unicode=True): if not line: continue # Skip empty lines line = line.strip() if line.startswith("data:"): content = line[len("data:"):].strip() if content == "[DONE]": break # End of stream else: content = line try: json_data = json.loads(content) except json.JSONDecodeError: continue # Skip lines that are not valid JSON if ( (self.__session_type == "agent" and json_data.get("event") == "message_end") or (self.__session_type == "chat" and json_data.get("data") is True) ): return if self.__session_type == "agent": yield self._structure_answer(json_data) else: yield self._structure_answer(json_data["data"]) else: try: json_data = res.json() except ValueError: raise Exception(f"Invalid response {res}") yield self._structure_answer(json_data["data"]) def _structure_answer(self, json_data): answer = "" if self.__session_type == "agent": answer = json_data["data"]["content"] elif self.__session_type == "chat": answer = json_data["answer"] reference = json_data.get("reference", {}) temp_dict = { "content": answer, "role": "assistant" } if reference and "chunks" in reference: chunks = reference["chunks"] temp_dict["reference"] = chunks message = Message(self.rag, temp_dict) return message def _ask_chat(self, question: str, stream: bool, **kwargs): json_data = {"question": question, "stream": stream, "session_id": self.id} json_data.update(kwargs) res = self.post(f"/chats/{self.chat_id}/completions", json_data, stream=stream) return res def _ask_agent(self, question: str, stream: bool, **kwargs): json_data = {"question": question, "stream": stream, "session_id": self.id} json_data.update(kwargs) res = self.post(f"/agents/{self.agent_id}/completions", json_data, stream=stream) return res def update(self, update_message): res = self.put(f"/chats/{self.chat_id}/sessions/{self.id}", update_message) res = res.json() if res.get("code") != 0: raise Exception(res.get("message")) class Message(Base): def __init__(self, rag, res_dict): self.content = "Hi! I am your assistant, can I help you?" self.reference = None self.role = "assistant" self.prompt = None self.id = None super().__init__(rag, res_dict)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/base.py
sdk/python/ragflow_sdk/modules/base.py
# # 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. # class Base: def __init__(self, rag, res_dict): self.rag = rag self._update_from_dict(rag, res_dict) def _update_from_dict(self, rag, res_dict): for k, v in res_dict.items(): if isinstance(v, dict): self.__dict__[k] = Base(rag, v) else: self.__dict__[k] = v def to_json(self): pr = {} for name in dir(self): value = getattr(self, name) if not name.startswith("__") and not callable(value) and name != "rag": if isinstance(value, Base): pr[name] = value.to_json() else: pr[name] = value return pr def post(self, path, json=None, stream=False, files=None): res = self.rag.post(path, json, stream=stream, files=files) return res def get(self, path, params=None): res = self.rag.get(path, params) return res def rm(self, path, json): res = self.rag.delete(path, json) return res def put(self, path, json): res = self.rag.put(path, json) return res def __str__(self): return str(self.to_json())
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/ragflow_sdk/modules/agent.py
sdk/python/ragflow_sdk/modules/agent.py
# # 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. # from .base import Base from .session import Session class Agent(Base): def __init__(self, rag, res_dict): self.id = None self.avatar = None self.canvas_type = None self.description = None self.dsl = None super().__init__(rag, res_dict) class Dsl(Base): def __init__(self, rag, res_dict): self.answer = [] self.components = { "begin": { "downstream": ["Answer:China"], "obj": { "component_name": "Begin", "params": {} }, "upstream": [] } } self.graph = { "edges": [], "nodes": [ { "data": { "label": "Begin", "name": "begin" }, "id": "begin", "position": { "x": 50, "y": 200 }, "sourcePosition": "left", "targetPosition": "right", "type": "beginNode" } ] } self.history = [] self.messages = [] self.path = [] self.reference = [] super().__init__(rag, res_dict) def create_session(self, **kwargs) -> Session: res = self.post(f"/agents/{self.id}/sessions", json=kwargs) res = res.json() if res.get("code") == 0: return Session(self.rag, res.get("data")) raise Exception(res.get("message")) def list_sessions(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True, id: str = None) -> list[Session]: res = self.get(f"/agents/{self.id}/sessions", {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id}) res = res.json() if res.get("code") == 0: result_list = [] for data in res.get("data"): temp_agent = Session(self.rag, data) result_list.append(temp_agent) return result_list raise Exception(res.get("message")) def delete_sessions(self, ids: list[str] | None = None): res = self.rm(f"/agents/{self.id}/sessions", {"ids": ids}) res = res.json() if res.get("code") != 0: raise Exception(res.get("message"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/conftest.py
sdk/python/test/conftest.py
# # 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 pytest import requests HOST_ADDRESS = os.getenv("HOST_ADDRESS", "http://127.0.0.1:9380") ZHIPU_AI_API_KEY = os.getenv("ZHIPU_AI_API_KEY") if ZHIPU_AI_API_KEY is None: pytest.exit("Error: Environment variable ZHIPU_AI_API_KEY must be set") # def generate_random_email(): # return 'user_' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))+'@1.com' def generate_email(): return "user_123@1.com" EMAIL = generate_email() # password is "123" PASSWORD = """ctAseGvejiaSWWZ88T/m4FQVOpQyUvP+x7sXtdv3feqZACiQleuewkUi35E16wSd5C5QcnkkcV9cYc8TKPTRZlxappDuirxghxoOvFcJxFU4ixLsD fN33jCHRoDUW81IH9zjij/vaw8IbVyb6vuwg6MX6inOEBRRzVbRYxXOu1wkWY6SsI8X70oF9aeLFp/PzQpjoe/YbSqpTq8qqrmHzn9vO+yvyYyvmDsphXe X8f7fp9c7vUsfOCkM+gHY3PadG+QHa7KI7mzTKgUTZImK6BZtfRBATDTthEUbbaTewY4H0MnWiCeeDhcbeQao6cFy1To8pE3RpmxnGnS8BsBn8w==""" def register(): url = HOST_ADDRESS + "/v1/user/register" name = "user" register_data = {"email": EMAIL, "nickname": name, "password": PASSWORD} res = requests.post(url=url, json=register_data) res = res.json() if res.get("code") != 0: raise Exception(res.get("message")) def login(): url = HOST_ADDRESS + "/v1/user/login" login_data = {"email": EMAIL, "password": PASSWORD} response = requests.post(url=url, json=login_data) res = response.json() if res.get("code") != 0: raise Exception(res.get("message")) auth = response.headers["Authorization"] return auth @pytest.fixture(scope="session") def get_api_key_fixture(): try: register() except Exception as e: print(e) auth = login() url = HOST_ADDRESS + "/v1/system/new_token" auth = {"Authorization": auth} response = requests.post(url=url, headers=auth) res = response.json() if res.get("code") != 0: raise Exception(res.get("message")) return res["data"].get("token") @pytest.fixture(scope="session") def get_auth(): try: register() except Exception as e: print(e) auth = login() return auth @pytest.fixture(scope="session") def get_email(): return EMAIL def get_my_llms(auth, name): url = HOST_ADDRESS + "/v1/llm/my_llms" authorization = {"Authorization": auth} response = requests.get(url=url, headers=authorization) res = response.json() if res.get("code") != 0: raise Exception(res.get("message")) if name in res.get("data"): return True return False def add_models(auth): url = HOST_ADDRESS + "/v1/llm/set_api_key" authorization = {"Authorization": auth} models_info = { "ZHIPU-AI": {"llm_factory": "ZHIPU-AI", "api_key": ZHIPU_AI_API_KEY}, } for name, model_info in models_info.items(): if not get_my_llms(auth, name): response = requests.post(url=url, headers=authorization, json=model_info) res = response.json() if res.get("code") != 0: pytest.exit(f"Critical error in add_models: {res.get('message')}") def get_tenant_info(auth): url = HOST_ADDRESS + "/v1/user/tenant_info" authorization = {"Authorization": auth} response = requests.get(url=url, headers=authorization) res = response.json() if res.get("code") != 0: raise Exception(res.get("message")) return res["data"].get("tenant_id") @pytest.fixture(scope="session", autouse=True) def set_tenant_info(get_auth): auth = get_auth try: add_models(auth) tenant_id = get_tenant_info(auth) except Exception as e: pytest.exit(f"Error in set_tenant_info: {str(e)}") url = HOST_ADDRESS + "/v1/user/set_tenant_info" authorization = {"Authorization": get_auth} tenant_info = { "tenant_id": tenant_id, "llm_id": "glm-4-flash@ZHIPU-AI", "embd_id": "BAAI/bge-small-en-v1.5@Builtin", "img2txt_id": "glm-4v@ZHIPU-AI", "asr_id": "", "tts_id": None, } response = requests.post(url=url, headers=authorization, json=tenant_info) res = response.json() if res.get("code") != 0: raise Exception(res.get("message"))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/t_agent.py
sdk/python/test/test_sdk_api/t_agent.py
# # 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. # from ragflow_sdk import RAGFlow, Agent from common import HOST_ADDRESS import pytest @pytest.mark.skip(reason="") def test_list_agents_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) rag.list_agents() @pytest.mark.skip(reason="") def test_converse_with_agent_with_success(get_api_key_fixture): API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm" agent_id = "ebfada2eb2bc11ef968a0242ac120006" rag = RAGFlow(API_KEY, HOST_ADDRESS) lang = "Chinese" file = "How is the weather tomorrow?" Agent.ask(agent_id=agent_id, rag=rag, lang=lang, file=file)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/common.py
sdk/python/test/test_sdk_api/common.py
# # 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 HOST_ADDRESS = os.getenv('HOST_ADDRESS', 'http://127.0.0.1:9380')
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/t_session.py
sdk/python/test/test_sdk_api/t_session.py
# # 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. # from ragflow_sdk import RAGFlow from common import HOST_ADDRESS import pytest def test_create_session_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_create_session") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") assistant = rag.create_chat("test_create_session", dataset_ids=[kb.id]) assistant.create_session() def test_create_conversation_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_create_conversation") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") assistant = rag.create_chat("test_create_conversation", dataset_ids=[kb.id]) session = assistant.create_session() question = "What is AI" for ans in session.ask(question): pass # assert not ans.content.startswith("**ERROR**"), "Please check this error." def test_delete_sessions_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_delete_session") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") assistant = rag.create_chat("test_delete_session", dataset_ids=[kb.id]) session = assistant.create_session() assistant.delete_sessions(ids=[session.id]) def test_update_session_with_name(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_update_session") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") assistant = rag.create_chat("test_update_session", dataset_ids=[kb.id]) session = assistant.create_session(name="old session") session.update({"name": "new session"}) def test_list_sessions_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_list_session") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") assistant = rag.create_chat("test_list_session", dataset_ids=[kb.id]) assistant.create_session("test_1") assistant.create_session("test_2") assistant.list_sessions() @pytest.mark.skip(reason="") def test_create_agent_session_with_success(get_api_key_fixture): API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm" rag = RAGFlow(API_KEY, HOST_ADDRESS) agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0] agent.create_session() @pytest.mark.skip(reason="") def test_create_agent_conversation_with_success(get_api_key_fixture): API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm" rag = RAGFlow(API_KEY, HOST_ADDRESS) agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0] session = agent.create_session() session.ask("What is this job") @pytest.mark.skip(reason="") def test_list_agent_sessions_with_success(get_api_key_fixture): API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm" rag = RAGFlow(API_KEY, HOST_ADDRESS) agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0] agent.list_sessions() @pytest.mark.skip(reason="") def test_delete_session_of_agent_with_success(get_api_key_fixture): API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm" rag = RAGFlow(API_KEY, HOST_ADDRESS) agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0] agent.delete_sessions(ids=["test_1"])
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/t_document.py
sdk/python/test/test_sdk_api/t_document.py
# # 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. # from ragflow_sdk import RAGFlow from common import HOST_ADDRESS import pytest def test_upload_document_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_upload_document") blob = b"Sample document content for test." with open("test_data/ragflow.txt", "rb") as file: blob_2 = file.read() document_infos = [] document_infos.append({"display_name": "test_1.txt", "blob": blob}) document_infos.append({"display_name": "test_2.txt", "blob": blob_2}) ds.upload_documents(document_infos) def test_update_document_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_update_document") blob = b"Sample document content for test." document_infos = [{"display_name": "test.txt", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] doc.update({"chunk_method": "manual", "name": "manual.txt"}) def test_download_document_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_download_document") blob = b"Sample document content for test." document_infos = [{"display_name": "test_1.txt", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] with open("test_download.txt", "wb+") as file: file.write(doc.download()) def test_list_documents_in_dataset_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_list_documents") blob = b"Sample document content for test." document_infos = [{"display_name": "test.txt", "blob": blob}] ds.upload_documents(document_infos) ds.list_documents(keywords="test", page=1, page_size=12) def test_delete_documents_in_dataset_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_delete_documents") name = "test_delete_documents.txt" blob = b"Sample document content for test." document_infos = [{"display_name": name, "blob": blob}] docs = ds.upload_documents(document_infos) ds.delete_documents([docs[0].id]) # upload and parse the document with different in different parse method. def test_upload_and_parse_pdf_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_pdf_document") with open("test_data/test.pdf", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.pdf", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_docx_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_docx_document") with open("test_data/test.docx", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.docx", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_excel_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_excel_document") with open("test_data/test.xlsx", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.xlsx", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_ppt_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_ppt_document") with open("test_data/test.ppt", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.ppt", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_image_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_image_document") with open("test_data/test.jpg", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.jpg", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_txt_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_txt_document") with open("test_data/test.txt", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.txt", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_md_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_md_document") with open("test_data/test.md", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.md", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_json_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_json_document") with open("test_data/test.json", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.json", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) @pytest.mark.skip(reason="") def test_upload_and_parse_eml_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_eml_document") with open("test_data/test.eml", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.eml", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id]) def test_upload_and_parse_html_documents_with_general_parse_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_html_document") with open("test_data/test.html", "rb") as file: blob = file.read() document_infos = [{"display_name": "test.html", "blob": blob}] docs = ds.upload_documents(document_infos) doc = docs[0] ds.async_parse_documents([doc.id])
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/t_dataset.py
sdk/python/test/test_sdk_api/t_dataset.py
# # 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 random import pytest from common import HOST_ADDRESS from ragflow_sdk import RAGFlow def test_create_dataset_with_name(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) rag.create_dataset("test_create_dataset_with_name") def test_create_dataset_with_duplicated_name(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) rag.create_dataset("test_create_dataset_with_duplicated_name") with pytest.raises(Exception) as exc_info: rag.create_dataset("test_create_dataset_with_duplicated_name") assert str(exc_info.value) == "Dataset name 'test_create_dataset_with_duplicated_name' already exists" def test_create_dataset_with_random_chunk_method(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) valid_chunk_methods = ["naive", "manual", "qa", "table", "paper", "book", "laws", "presentation", "picture", "one", "email"] random_chunk_method = random.choice(valid_chunk_methods) rag.create_dataset("test_create_dataset_with_random_chunk_method", chunk_method=random_chunk_method) def test_create_dataset_with_invalid_parameter(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) chunk_method = "invalid_chunk_method" with pytest.raises(Exception) as exc_info: rag.create_dataset("test_create_dataset_with_invalid_chunk_method", chunk_method=chunk_method) assert ( str(exc_info.value) == f"Field: <chunk_method> - Message: <Input should be 'naive', 'book', 'email', 'laws', 'manual', 'one', 'paper', 'picture', 'presentation', 'qa', 'table' or 'tag'> - Value: <{chunk_method}>" ) def test_update_dataset_with_name(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset("test_update_dataset") ds.update({"name": "updated_dataset"}) def test_delete_datasets_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset("test_delete_dataset") rag.delete_datasets(ids=[ds.id]) def test_list_datasets_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) rag.create_dataset("test_list_datasets") rag.list_datasets()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/get_email.py
sdk/python/test/test_sdk_api/get_email.py
# # 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. # def test_get_email(get_email): print("\nEmail account:", flush=True) print(f"{get_email}\n", flush=True)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/t_chat.py
sdk/python/test/test_sdk_api/t_chat.py
# # 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. # from common import HOST_ADDRESS from ragflow_sdk import RAGFlow from ragflow_sdk.modules.chat import Chat def test_create_chat_with_name(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_create_chat") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") llm = Chat.LLM( rag, { "model_name": "glm-4-flash@ZHIPU-AI", "temperature": 0.1, "top_p": 0.3, "presence_penalty": 0.4, "frequency_penalty": 0.7, "max_tokens": 512, }, ) rag.create_chat("test_create_chat", dataset_ids=[kb.id], llm=llm) def test_update_chat_with_name(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_update_chat") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") llm = Chat.LLM( rag, { "model_name": "glm-4-flash@ZHIPU-AI", "temperature": 0.1, "top_p": 0.3, "presence_penalty": 0.4, "frequency_penalty": 0.7, "max_tokens": 512, }, ) chat = rag.create_chat("test_update_chat", dataset_ids=[kb.id], llm=llm) chat.update({"name": "new_chat"}) def test_delete_chats_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_delete_chat") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") llm = Chat.LLM( rag, { "model_name": "glm-4-flash@ZHIPU-AI", "temperature": 0.1, "top_p": 0.3, "presence_penalty": 0.4, "frequency_penalty": 0.7, "max_tokens": 512, }, ) chat = rag.create_chat("test_delete_chat", dataset_ids=[kb.id], llm=llm) rag.delete_chats(ids=[chat.id]) def test_list_chats_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) kb = rag.create_dataset(name="test_list_chats") display_name = "ragflow.txt" with open("test_data/ragflow.txt", "rb") as file: blob = file.read() document = {"display_name": display_name, "blob": blob} documents = [] documents.append(document) docs = kb.upload_documents(documents) for doc in docs: doc.add_chunk("This is a test to add chunk") llm = Chat.LLM( rag, { "model_name": "glm-4-flash@ZHIPU-AI", "temperature": 0.1, "top_p": 0.3, "presence_penalty": 0.4, "frequency_penalty": 0.7, "max_tokens": 512, }, ) rag.create_chat("test_list_1", dataset_ids=[kb.id], llm=llm) rag.create_chat("test_list_2", dataset_ids=[kb.id], llm=llm) rag.list_chats()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_sdk_api/t_chunk.py
sdk/python/test/test_sdk_api/t_chunk.py
# # 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. # from ragflow_sdk import RAGFlow from common import HOST_ADDRESS from time import sleep def test_parse_document_with_txt(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_parse_document") name = 'ragflow_test.txt' with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() docs = ds.upload_documents([{"display_name": name, "blob": blob}]) doc = docs[0] ds.async_parse_documents(document_ids=[doc.id]) ''' for n in range(100): if doc.progress == 1: break sleep(1) else: raise Exception("Run time ERROR: Document parsing did not complete in time.") ''' def test_parse_and_cancel_document(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_parse_and_cancel_document") name = 'ragflow_test.txt' with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() docs = ds.upload_documents([{"display_name": name, "blob": blob}]) doc = docs[0] ds.async_parse_documents(document_ids=[doc.id]) sleep(1) if 0 < doc.progress < 1: ds.async_cancel_parse_documents(document_ids=[doc.id]) def test_bulk_parse_documents(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_bulk_parse_and_cancel_documents") with open("test_data/ragflow.txt", "rb") as file: blob = file.read() documents = [ {'display_name': 'test1.txt', 'blob': blob}, {'display_name': 'test2.txt', 'blob': blob}, {'display_name': 'test3.txt', 'blob': blob} ] docs = ds.upload_documents(documents) ids = [doc.id for doc in docs] ds.async_parse_documents(ids) ''' for n in range(100): all_completed = all(doc.progress == 1 for doc in docs) if all_completed: break sleep(1) else: raise Exception("Run time ERROR: Bulk document parsing did not complete in time.") ''' def test_list_chunks_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_list_chunks_with_success") with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() ''' # chunk_size = 1024 * 1024 # chunks = [blob[i:i + chunk_size] for i in range(0, len(blob), chunk_size)] documents = [ {'display_name': f'chunk_{i}.txt', 'blob': chunk} for i, chunk in enumerate(chunks) ] ''' documents = [{"display_name": "test_list_chunks_with_success.txt", "blob": blob}] docs = ds.upload_documents(documents) ids = [doc.id for doc in docs] ds.async_parse_documents(ids) ''' for n in range(100): all_completed = all(doc.progress == 1 for doc in docs) if all_completed: break sleep(1) else: raise Exception("Run time ERROR: Chunk document parsing did not complete in time.") ''' doc = docs[0] doc.list_chunks() def test_add_chunk_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_add_chunk_with_success") with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() ''' # chunk_size = 1024 * 1024 # chunks = [blob[i:i + chunk_size] for i in range(0, len(blob), chunk_size)] documents = [ {'display_name': f'chunk_{i}.txt', 'blob': chunk} for i, chunk in enumerate(chunks) ] ''' documents = [{"display_name": "test_list_chunks_with_success.txt", "blob": blob}] docs = ds.upload_documents(documents) doc = docs[0] doc.add_chunk(content="This is a chunk addition test") def test_delete_chunk_with_success(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_delete_chunk_with_success") with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() ''' # chunk_size = 1024 * 1024 # chunks = [blob[i:i + chunk_size] for i in range(0, len(blob), chunk_size)] documents = [ {'display_name': f'chunk_{i}.txt', 'blob': chunk} for i, chunk in enumerate(chunks) ] ''' documents = [{"display_name": "test_delete_chunk_with_success.txt", "blob": blob}] docs = ds.upload_documents(documents) doc = docs[0] chunk = doc.add_chunk(content="This is a chunk addition test") sleep(5) doc.delete_chunks([chunk.id]) def test_update_chunk_content(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_update_chunk_content_with_success") with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() ''' # chunk_size = 1024 * 1024 # chunks = [blob[i:i + chunk_size] for i in range(0, len(blob), chunk_size)] documents = [ {'display_name': f'chunk_{i}.txt', 'blob': chunk} for i, chunk in enumerate(chunks) ] ''' documents = [{"display_name": "test_update_chunk_content_with_success.txt", "blob": blob}] docs = ds.upload_documents(documents) doc = docs[0] chunk = doc.add_chunk(content="This is a chunk addition test") # For Elasticsearch, the chunk is not searchable in shot time (~2s). sleep(3) chunk.update({"content": "This is a updated content"}) def test_update_chunk_available(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="test_update_chunk_available_with_success") with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() ''' # chunk_size = 1024 * 1024 # chunks = [blob[i:i + chunk_size] for i in range(0, len(blob), chunk_size)] documents = [ {'display_name': f'chunk_{i}.txt', 'blob': chunk} for i, chunk in enumerate(chunks) ] ''' documents = [{"display_name": "test_update_chunk_available_with_success.txt", "blob": blob}] docs = ds.upload_documents(documents) doc = docs[0] chunk = doc.add_chunk(content="This is a chunk addition test") # For Elasticsearch, the chunk is not searchable in shot time (~2s). sleep(3) chunk.update({"available": 0}) def test_retrieve_chunks(get_api_key_fixture): API_KEY = get_api_key_fixture rag = RAGFlow(API_KEY, HOST_ADDRESS) ds = rag.create_dataset(name="retrieval") with open("test_data/ragflow_test.txt", "rb") as file: blob = file.read() ''' # chunk_size = 1024 * 1024 # chunks = [blob[i:i + chunk_size] for i in range(0, len(blob), chunk_size)] documents = [ {'display_name': f'chunk_{i}.txt', 'blob': chunk} for i, chunk in enumerate(chunks) ] ''' documents = [{"display_name": "test_retrieve_chunks.txt", "blob": blob}] docs = ds.upload_documents(documents) doc = docs[0] doc.add_chunk(content="This is a chunk addition test") rag.retrieve(dataset_ids=[ds.id], document_ids=[doc.id]) rag.delete_datasets(ids=[ds.id]) # test different parameters for the retrieval
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_frontend_api/common.py
sdk/python/test/test_frontend_api/common.py
# # 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 requests HOST_ADDRESS = os.getenv("HOST_ADDRESS", "http://127.0.0.1:9380") DATASET_NAME_LIMIT = 128 def create_dataset(auth, dataset_name): authorization = {"Authorization": auth} url = f"{HOST_ADDRESS}/v1/kb/create" json = {"name": dataset_name} res = requests.post(url=url, headers=authorization, json=json) return res.json() def list_dataset(auth, page_number, page_size=30): authorization = {"Authorization": auth} url = f"{HOST_ADDRESS}/v1/kb/list?page={page_number}&page_size={page_size}" json = {} res = requests.post(url=url, headers=authorization, json=json) return res.json() def rm_dataset(auth, dataset_id): authorization = {"Authorization": auth} url = f"{HOST_ADDRESS}/v1/kb/rm" json = {"kb_id": dataset_id} res = requests.post(url=url, headers=authorization, json=json) return res.json() def update_dataset(auth, json_req): authorization = {"Authorization": auth} url = f"{HOST_ADDRESS}/v1/kb/update" res = requests.post(url=url, headers=authorization, json=json_req) return res.json() def upload_file(auth, dataset_id, path): authorization = {"Authorization": auth} url = f"{HOST_ADDRESS}/v1/document/upload" json_req = { "kb_id": dataset_id, } file = {"file": open(f"{path}", "rb")} res = requests.post(url=url, headers=authorization, files=file, data=json_req) return res.json() def list_document(auth, dataset_id): authorization = {"Authorization": auth} url = f"{HOST_ADDRESS}/v1/document/list?kb_id={dataset_id}" json = {} res = requests.post(url=url, headers=authorization, json=json) return res.json() def get_docs_info(auth, doc_ids): authorization = {"Authorization": auth} json_req = {"doc_ids": doc_ids} url = f"{HOST_ADDRESS}/v1/document/infos" res = requests.post(url=url, headers=authorization, json=json_req) return res.json() def parse_docs(auth, doc_ids): authorization = {"Authorization": auth} json_req = {"doc_ids": doc_ids, "run": 1} url = f"{HOST_ADDRESS}/v1/document/run" res = requests.post(url=url, headers=authorization, json=json_req) return res.json() def parse_file(auth, document_id): pass
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_frontend_api/get_email.py
sdk/python/test/test_frontend_api/get_email.py
# # 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. # def test_get_email(get_email): print("\nEmail account:",flush=True) print(f"{get_email}\n",flush=True)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_frontend_api/test_chunk.py
sdk/python/test/test_frontend_api/test_chunk.py
# # Copyright 2024 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. from common import create_dataset, list_dataset, rm_dataset, upload_file from common import list_document, get_docs_info, parse_docs from time import sleep from timeit import default_timer as timer def test_parse_txt_document(get_auth): # create dataset res = create_dataset(get_auth, "test_parse_txt_document") assert res.get("code") == 0, f"{res.get('message')}" # list dataset page_number = 1 dataset_list = [] dataset_id = None while True: res = list_dataset(get_auth, page_number) data = res.get("data").get("kbs") for item in data: dataset_id = item.get("id") dataset_list.append(dataset_id) if len(dataset_list) < page_number * 150: break page_number += 1 filename = 'ragflow_test.txt' res = upload_file(get_auth, dataset_id, f"../test_sdk_api/test_data/{filename}") assert res.get("code") == 0, f"{res.get('message')}" res = list_document(get_auth, dataset_id) doc_id_list = [] for doc in res['data']['docs']: doc_id_list.append(doc['id']) res = get_docs_info(get_auth, doc_id_list) print(doc_id_list) doc_count = len(doc_id_list) res = parse_docs(get_auth, doc_id_list) start_ts = timer() while True: res = get_docs_info(get_auth, doc_id_list) finished_count = 0 for doc_info in res['data']: if doc_info['progress'] == 1: finished_count += 1 if finished_count == doc_count: break sleep(1) print('time cost {:.1f}s'.format(timer() - start_ts)) # delete dataset for dataset_id in dataset_list: res = rm_dataset(get_auth, dataset_id) assert res.get("code") == 0, f"{res.get('message')}" print(f"{len(dataset_list)} datasets are deleted")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_frontend_api/test_dataset.py
sdk/python/test/test_frontend_api/test_dataset.py
# # 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. # from common import create_dataset, list_dataset, rm_dataset, update_dataset, DATASET_NAME_LIMIT import re import random import string def test_dataset(get_auth): # create dataset res = create_dataset(get_auth, "test_create_dataset") assert res.get("code") == 0, f"{res.get('message')}" # list dataset page_number = 1 dataset_list = [] while True: res = list_dataset(get_auth, page_number) data = res.get("data").get("kbs") for item in data: dataset_id = item.get("id") dataset_list.append(dataset_id) if len(dataset_list) < page_number * 150: break page_number += 1 print(f"found {len(dataset_list)} datasets") # delete dataset for dataset_id in dataset_list: res = rm_dataset(get_auth, dataset_id) assert res.get("code") == 0, f"{res.get('message')}" print(f"{len(dataset_list)} datasets are deleted") def test_dataset_1k_dataset(get_auth): # create dataset for i in range(1000): res = create_dataset(get_auth, f"test_create_dataset_{i}") assert res.get("code") == 0, f"{res.get('message')}" # list dataset page_number = 1 dataset_list = [] while True: res = list_dataset(get_auth, page_number) data = res.get("data").get("kbs") for item in data: dataset_id = item.get("id") dataset_list.append(dataset_id) if len(dataset_list) < page_number * 150: break page_number += 1 print(f"found {len(dataset_list)} datasets") # delete dataset for dataset_id in dataset_list: res = rm_dataset(get_auth, dataset_id) assert res.get("code") == 0, f"{res.get('message')}" print(f"{len(dataset_list)} datasets are deleted") def test_duplicated_name_dataset(get_auth): # create dataset for i in range(20): res = create_dataset(get_auth, "test_create_dataset") assert res.get("code") == 0, f"{res.get('message')}" # list dataset res = list_dataset(get_auth, 1) data = res.get("data").get("kbs") dataset_list = [] pattern = r'^test_create_dataset.*' for item in data: dataset_name = item.get("name") dataset_id = item.get("id") dataset_list.append(dataset_id) match = re.match(pattern, dataset_name) assert match is not None for dataset_id in dataset_list: res = rm_dataset(get_auth, dataset_id) assert res.get("code") == 0, f"{res.get('message')}" print(f"{len(dataset_list)} datasets are deleted") def test_invalid_name_dataset(get_auth): # create dataset # with pytest.raises(Exception) as e: res = create_dataset(get_auth, 0) assert res['code'] != 0 res = create_dataset(get_auth, "") assert res['code'] != 0 long_string = "" while len(long_string.encode("utf-8")) <= DATASET_NAME_LIMIT: long_string += random.choice(string.ascii_letters + string.digits) res = create_dataset(get_auth, long_string) assert res['code'] != 0 print(res) def test_update_different_params_dataset_success(get_auth): # create dataset res = create_dataset(get_auth, "test_create_dataset") assert res.get("code") == 0, f"{res.get('message')}" # list dataset page_number = 1 dataset_list = [] while True: res = list_dataset(get_auth, page_number) data = res.get("data").get("kbs") for item in data: dataset_id = item.get("id") dataset_list.append(dataset_id) if len(dataset_list) < page_number * 150: break page_number += 1 print(f"found {len(dataset_list)} datasets") dataset_id = dataset_list[0] json_req = {"kb_id": dataset_id, "name": "test_update_dataset", "description": "test", "permission": "me", "parser_id": "presentation", "language": "spanish"} res = update_dataset(get_auth, json_req) assert res.get("code") == 0, f"{res.get('message')}" # delete dataset for dataset_id in dataset_list: res = rm_dataset(get_auth, dataset_id) assert res.get("code") == 0, f"{res.get('message')}" print(f"{len(dataset_list)} datasets are deleted") # update dataset with different parameters def test_update_different_params_dataset_fail(get_auth): # create dataset res = create_dataset(get_auth, "test_create_dataset") assert res.get("code") == 0, f"{res.get('message')}" # list dataset page_number = 1 dataset_list = [] while True: res = list_dataset(get_auth, page_number) data = res.get("data").get("kbs") for item in data: dataset_id = item.get("id") dataset_list.append(dataset_id) if len(dataset_list) < page_number * 150: break page_number += 1 print(f"found {len(dataset_list)} datasets") dataset_id = dataset_list[0] json_req = {"kb_id": dataset_id, "id": "xxx"} res = update_dataset(get_auth, json_req) assert res.get("code") == 101 # delete dataset for dataset_id in dataset_list: res = rm_dataset(get_auth, dataset_id) assert res.get("code") == 0, f"{res.get('message')}" print(f"{len(dataset_list)} datasets are deleted")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/common.py
sdk/python/test/test_http_api/common.py
# # 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 from pathlib import Path import requests from libs.utils.file_utils import create_txt_file from requests_toolbelt import MultipartEncoder HEADERS = {"Content-Type": "application/json"} HOST_ADDRESS = os.getenv("HOST_ADDRESS", "http://127.0.0.1:9380") DATASETS_API_URL = "/api/v1/datasets" FILE_API_URL = "/api/v1/datasets/{dataset_id}/documents" FILE_CHUNK_API_URL = "/api/v1/datasets/{dataset_id}/chunks" CHUNK_API_URL = "/api/v1/datasets/{dataset_id}/documents/{document_id}/chunks" CHAT_ASSISTANT_API_URL = "/api/v1/chats" SESSION_WITH_CHAT_ASSISTANT_API_URL = "/api/v1/chats/{chat_id}/sessions" SESSION_WITH_AGENT_API_URL = "/api/v1/agents/{agent_id}/sessions" INVALID_API_TOKEN = "invalid_key_123" DATASET_NAME_LIMIT = 128 DOCUMENT_NAME_LIMIT = 128 CHAT_ASSISTANT_NAME_LIMIT = 255 SESSION_WITH_CHAT_NAME_LIMIT = 255 # DATASET MANAGEMENT def create_dataset(auth, payload=None, *, headers=HEADERS, data=None): res = requests.post(url=f"{HOST_ADDRESS}{DATASETS_API_URL}", headers=headers, auth=auth, json=payload, data=data) return res.json() def list_datasets(auth, params=None, *, headers=HEADERS): res = requests.get(url=f"{HOST_ADDRESS}{DATASETS_API_URL}", headers=headers, auth=auth, params=params) return res.json() def update_dataset(auth, dataset_id, payload=None, *, headers=HEADERS, data=None): res = requests.put(url=f"{HOST_ADDRESS}{DATASETS_API_URL}/{dataset_id}", headers=headers, auth=auth, json=payload, data=data) return res.json() def delete_datasets(auth, payload=None, *, headers=HEADERS, data=None): res = requests.delete(url=f"{HOST_ADDRESS}{DATASETS_API_URL}", headers=headers, auth=auth, json=payload, data=data) return res.json() def batch_create_datasets(auth, num): ids = [] for i in range(num): res = create_dataset(auth, {"name": f"dataset_{i}"}) ids.append(res["data"]["id"]) return ids # FILE MANAGEMENT WITHIN DATASET def upload_documnets(auth, dataset_id, files_path=None): url = f"{HOST_ADDRESS}{FILE_API_URL}".format(dataset_id=dataset_id) if files_path is None: files_path = [] fields = [] file_objects = [] try: for fp in files_path: p = Path(fp) f = p.open("rb") fields.append(("file", (p.name, f))) file_objects.append(f) m = MultipartEncoder(fields=fields) res = requests.post( url=url, headers={"Content-Type": m.content_type}, auth=auth, data=m, ) return res.json() finally: for f in file_objects: f.close() def download_document(auth, dataset_id, document_id, save_path): url = f"{HOST_ADDRESS}{FILE_API_URL}/{document_id}".format(dataset_id=dataset_id) res = requests.get(url=url, auth=auth, stream=True) try: if res.status_code == 200: with open(save_path, "wb") as f: for chunk in res.iter_content(chunk_size=8192): f.write(chunk) finally: res.close() return res def list_documnets(auth, dataset_id, params=None): url = f"{HOST_ADDRESS}{FILE_API_URL}".format(dataset_id=dataset_id) res = requests.get(url=url, headers=HEADERS, auth=auth, params=params) return res.json() def update_documnet(auth, dataset_id, document_id, payload=None): url = f"{HOST_ADDRESS}{FILE_API_URL}/{document_id}".format(dataset_id=dataset_id) res = requests.put(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def delete_documnets(auth, dataset_id, payload=None): url = f"{HOST_ADDRESS}{FILE_API_URL}".format(dataset_id=dataset_id) res = requests.delete(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def parse_documnets(auth, dataset_id, payload=None): url = f"{HOST_ADDRESS}{FILE_CHUNK_API_URL}".format(dataset_id=dataset_id) res = requests.post(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def stop_parse_documnets(auth, dataset_id, payload=None): url = f"{HOST_ADDRESS}{FILE_CHUNK_API_URL}".format(dataset_id=dataset_id) res = requests.delete(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def bulk_upload_documents(auth, dataset_id, num, tmp_path): fps = [] for i in range(num): fp = create_txt_file(tmp_path / f"ragflow_test_upload_{i}.txt") fps.append(fp) res = upload_documnets(auth, dataset_id, fps) document_ids = [] for document in res["data"]: document_ids.append(document["id"]) return document_ids # CHUNK MANAGEMENT WITHIN DATASET def add_chunk(auth, dataset_id, document_id, payload=None): url = f"{HOST_ADDRESS}{CHUNK_API_URL}".format(dataset_id=dataset_id, document_id=document_id) res = requests.post(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def list_chunks(auth, dataset_id, document_id, params=None): url = f"{HOST_ADDRESS}{CHUNK_API_URL}".format(dataset_id=dataset_id, document_id=document_id) res = requests.get(url=url, headers=HEADERS, auth=auth, params=params) return res.json() def update_chunk(auth, dataset_id, document_id, chunk_id, payload=None): url = f"{HOST_ADDRESS}{CHUNK_API_URL}/{chunk_id}".format(dataset_id=dataset_id, document_id=document_id) res = requests.put(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def delete_chunks(auth, dataset_id, document_id, payload=None): url = f"{HOST_ADDRESS}{CHUNK_API_URL}".format(dataset_id=dataset_id, document_id=document_id) res = requests.delete(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def retrieval_chunks(auth, payload=None): url = f"{HOST_ADDRESS}/api/v1/retrieval" res = requests.post(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def batch_add_chunks(auth, dataset_id, document_id, num): chunk_ids = [] for i in range(num): res = add_chunk(auth, dataset_id, document_id, {"content": f"chunk test {i}"}) chunk_ids.append(res["data"]["chunk"]["id"]) return chunk_ids # CHAT ASSISTANT MANAGEMENT def create_chat_assistant(auth, payload=None): url = f"{HOST_ADDRESS}{CHAT_ASSISTANT_API_URL}" res = requests.post(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def list_chat_assistants(auth, params=None): url = f"{HOST_ADDRESS}{CHAT_ASSISTANT_API_URL}" res = requests.get(url=url, headers=HEADERS, auth=auth, params=params) return res.json() def update_chat_assistant(auth, chat_assistant_id, payload=None): url = f"{HOST_ADDRESS}{CHAT_ASSISTANT_API_URL}/{chat_assistant_id}" res = requests.put(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def delete_chat_assistants(auth, payload=None): url = f"{HOST_ADDRESS}{CHAT_ASSISTANT_API_URL}" res = requests.delete(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def batch_create_chat_assistants(auth, num): chat_assistant_ids = [] for i in range(num): res = create_chat_assistant(auth, {"name": f"test_chat_assistant_{i}", "dataset_ids": []}) chat_assistant_ids.append(res["data"]["id"]) return chat_assistant_ids # SESSION MANAGEMENT def create_session_with_chat_assistant(auth, chat_assistant_id, payload=None): url = f"{HOST_ADDRESS}{SESSION_WITH_CHAT_ASSISTANT_API_URL}".format(chat_id=chat_assistant_id) res = requests.post(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def list_session_with_chat_assistants(auth, chat_assistant_id, params=None): url = f"{HOST_ADDRESS}{SESSION_WITH_CHAT_ASSISTANT_API_URL}".format(chat_id=chat_assistant_id) res = requests.get(url=url, headers=HEADERS, auth=auth, params=params) return res.json() def update_session_with_chat_assistant(auth, chat_assistant_id, session_id, payload=None): url = f"{HOST_ADDRESS}{SESSION_WITH_CHAT_ASSISTANT_API_URL}/{session_id}".format(chat_id=chat_assistant_id) res = requests.put(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def delete_session_with_chat_assistants(auth, chat_assistant_id, payload=None): url = f"{HOST_ADDRESS}{SESSION_WITH_CHAT_ASSISTANT_API_URL}".format(chat_id=chat_assistant_id) res = requests.delete(url=url, headers=HEADERS, auth=auth, json=payload) return res.json() def batch_add_sessions_with_chat_assistant(auth, chat_assistant_id, num): session_ids = [] for i in range(num): res = create_session_with_chat_assistant(auth, chat_assistant_id, {"name": f"session_with_chat_assistant_{i}"}) session_ids.append(res["data"]["id"]) return session_ids
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/conftest.py
sdk/python/test/test_http_api/conftest.py
# # 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 pytest from common import ( add_chunk, batch_create_datasets, bulk_upload_documents, create_chat_assistant, delete_chat_assistants, delete_datasets, delete_session_with_chat_assistants, list_documnets, parse_documnets, ) from libs.auth import RAGFlowHttpApiAuth from libs.utils import wait_for from libs.utils.file_utils import ( create_docx_file, create_eml_file, create_excel_file, create_html_file, create_image_file, create_json_file, create_md_file, create_pdf_file, create_ppt_file, create_txt_file, ) MARKER_EXPRESSIONS = { "p1": "p1", "p2": "p1 or p2", "p3": "p1 or p2 or p3", } HOST_ADDRESS = os.getenv("HOST_ADDRESS", "http://127.0.0.1:9380") def pytest_addoption(parser: pytest.Parser) -> None: parser.addoption( "--level", action="store", default="p2", choices=list(MARKER_EXPRESSIONS.keys()), help=f"Test level ({'/'.join(MARKER_EXPRESSIONS)}): p1=smoke, p2=core, p3=full", ) def pytest_configure(config: pytest.Config) -> None: level = config.getoption("--level") config.option.markexpr = MARKER_EXPRESSIONS[level] if config.option.verbose > 0: print(f"\n[CONFIG] Active test level: {level}") @wait_for(30, 1, "Document parsing timeout") def condition(_auth, _dataset_id): res = list_documnets(_auth, _dataset_id) for doc in res["data"]["docs"]: if doc["run"] != "DONE": return False return True @pytest.fixture(scope="session") def get_http_api_auth(get_api_key_fixture): return RAGFlowHttpApiAuth(get_api_key_fixture) @pytest.fixture(scope="function") def clear_datasets(request, get_http_api_auth): def cleanup(): delete_datasets(get_http_api_auth, {"ids": None}) request.addfinalizer(cleanup) @pytest.fixture(scope="function") def clear_chat_assistants(request, get_http_api_auth): def cleanup(): delete_chat_assistants(get_http_api_auth) request.addfinalizer(cleanup) @pytest.fixture(scope="function") def clear_session_with_chat_assistants(request, get_http_api_auth, add_chat_assistants): _, _, chat_assistant_ids = add_chat_assistants def cleanup(): for chat_assistant_id in chat_assistant_ids: delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) request.addfinalizer(cleanup) @pytest.fixture def generate_test_files(request, tmp_path): file_creators = { "docx": (tmp_path / "ragflow_test.docx", create_docx_file), "excel": (tmp_path / "ragflow_test.xlsx", create_excel_file), "ppt": (tmp_path / "ragflow_test.pptx", create_ppt_file), "image": (tmp_path / "ragflow_test.png", create_image_file), "pdf": (tmp_path / "ragflow_test.pdf", create_pdf_file), "txt": (tmp_path / "ragflow_test.txt", create_txt_file), "md": (tmp_path / "ragflow_test.md", create_md_file), "json": (tmp_path / "ragflow_test.json", create_json_file), "eml": (tmp_path / "ragflow_test.eml", create_eml_file), "html": (tmp_path / "ragflow_test.html", create_html_file), } files = {} for file_type, (file_path, creator_func) in file_creators.items(): if request.param in ["", file_type]: creator_func(file_path) files[file_type] = file_path return files @pytest.fixture(scope="class") def ragflow_tmp_dir(request, tmp_path_factory): class_name = request.cls.__name__ return tmp_path_factory.mktemp(class_name) @pytest.fixture(scope="class") def add_dataset(request, get_http_api_auth): def cleanup(): delete_datasets(get_http_api_auth, {"ids": None}) request.addfinalizer(cleanup) dataset_ids = batch_create_datasets(get_http_api_auth, 1) return dataset_ids[0] @pytest.fixture(scope="function") def add_dataset_func(request, get_http_api_auth): def cleanup(): delete_datasets(get_http_api_auth, {"ids": None}) request.addfinalizer(cleanup) return batch_create_datasets(get_http_api_auth, 1)[0] @pytest.fixture(scope="class") def add_document(get_http_api_auth, add_dataset, ragflow_tmp_dir): dataset_id = add_dataset document_ids = bulk_upload_documents(get_http_api_auth, dataset_id, 1, ragflow_tmp_dir) return dataset_id, document_ids[0] @pytest.fixture(scope="class") def add_chunks(get_http_api_auth, add_document): dataset_id, document_id = add_document parse_documnets(get_http_api_auth, dataset_id, {"document_ids": [document_id]}) condition(get_http_api_auth, dataset_id) chunk_ids = [] for i in range(4): res = add_chunk(get_http_api_auth, dataset_id, document_id, {"content": f"chunk test {i}"}) chunk_ids.append(res["data"]["chunk"]["id"]) # issues/6487 from time import sleep sleep(1) return dataset_id, document_id, chunk_ids @pytest.fixture(scope="class") def add_chat_assistants(request, get_http_api_auth, add_document): def cleanup(): delete_chat_assistants(get_http_api_auth) request.addfinalizer(cleanup) dataset_id, document_id = add_document parse_documnets(get_http_api_auth, dataset_id, {"document_ids": [document_id]}) condition(get_http_api_auth, dataset_id) chat_assistant_ids = [] for i in range(5): res = create_chat_assistant(get_http_api_auth, {"name": f"test_chat_assistant_{i}", "dataset_ids": [dataset_id]}) chat_assistant_ids.append(res["data"]["id"]) return dataset_id, document_id, chat_assistant_ids
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chat_assistant_management/test_delete_chat_assistants.py
sdk/python/test/test_http_api/test_chat_assistant_management/test_delete_chat_assistants.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, batch_create_chat_assistants, delete_chat_assistants, list_chat_assistants from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = delete_chat_assistants(auth) assert res["code"] == expected_code assert res["message"] == expected_message class TestChatAssistantsDelete: @pytest.mark.parametrize( "payload, expected_code, expected_message, remaining", [ pytest.param(None, 0, "", 0, marks=pytest.mark.p3), pytest.param({"ids": []}, 0, "", 0, marks=pytest.mark.p3), pytest.param({"ids": ["invalid_id"]}, 102, "Assistant(invalid_id) not found.", 5, marks=pytest.mark.p3), pytest.param({"ids": ["\n!?ใ€‚๏ผ›๏ผ๏ผŸ\"'"]}, 102, """Assistant(\n!?ใ€‚๏ผ›๏ผ๏ผŸ"\') not found.""", 5, marks=pytest.mark.p3), pytest.param("not json", 100, "AttributeError(\"'str' object has no attribute 'get'\")", 5, marks=pytest.mark.p3), pytest.param(lambda r: {"ids": r[:1]}, 0, "", 4, marks=pytest.mark.p3), pytest.param(lambda r: {"ids": r}, 0, "", 0, marks=pytest.mark.p1), ], ) def test_basic_scenarios(self, get_http_api_auth, add_chat_assistants_func, payload, expected_code, expected_message, remaining): _, _, chat_assistant_ids = add_chat_assistants_func if callable(payload): payload = payload(chat_assistant_ids) res = delete_chat_assistants(get_http_api_auth, payload) assert res["code"] == expected_code if res["code"] != 0: assert res["message"] == expected_message res = list_chat_assistants(get_http_api_auth) assert len(res["data"]) == remaining @pytest.mark.parametrize( "payload", [ pytest.param(lambda r: {"ids": ["invalid_id"] + r}, marks=pytest.mark.p3), pytest.param(lambda r: {"ids": r[:1] + ["invalid_id"] + r[1:5]}, marks=pytest.mark.p1), pytest.param(lambda r: {"ids": r + ["invalid_id"]}, marks=pytest.mark.p3), ], ) def test_delete_partial_invalid_id(self, get_http_api_auth, add_chat_assistants_func, payload): _, _, chat_assistant_ids = add_chat_assistants_func if callable(payload): payload = payload(chat_assistant_ids) res = delete_chat_assistants(get_http_api_auth, payload) assert res["code"] == 0 assert res["data"]["errors"][0] == "Assistant(invalid_id) not found." assert res["data"]["success_count"] == 5 res = list_chat_assistants(get_http_api_auth) assert len(res["data"]) == 0 @pytest.mark.p3 def test_repeated_deletion(self, get_http_api_auth, add_chat_assistants_func): _, _, chat_assistant_ids = add_chat_assistants_func res = delete_chat_assistants(get_http_api_auth, {"ids": chat_assistant_ids}) assert res["code"] == 0 res = delete_chat_assistants(get_http_api_auth, {"ids": chat_assistant_ids}) assert res["code"] == 102 assert "not found" in res["message"] @pytest.mark.p3 def test_duplicate_deletion(self, get_http_api_auth, add_chat_assistants_func): _, _, chat_assistant_ids = add_chat_assistants_func res = delete_chat_assistants(get_http_api_auth, {"ids": chat_assistant_ids + chat_assistant_ids}) assert res["code"] == 0 assert "Duplicate assistant ids" in res["data"]["errors"][0] assert res["data"]["success_count"] == 5 res = list_chat_assistants(get_http_api_auth) assert res["code"] == 0 @pytest.mark.p3 def test_concurrent_deletion(self, get_http_api_auth): ids = batch_create_chat_assistants(get_http_api_auth, 100) with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(delete_chat_assistants, get_http_api_auth, {"ids": ids[i : i + 1]}) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_delete_10k(self, get_http_api_auth): ids = batch_create_chat_assistants(get_http_api_auth, 10_000) res = delete_chat_assistants(get_http_api_auth, {"ids": ids}) assert res["code"] == 0 res = list_chat_assistants(get_http_api_auth) assert len(res["data"]) == 0
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chat_assistant_management/conftest.py
sdk/python/test/test_http_api/test_chat_assistant_management/conftest.py
# # 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 pytest from common import create_chat_assistant, delete_chat_assistants, list_documnets, parse_documnets from libs.utils import wait_for @wait_for(30, 1, "Document parsing timeout") def condition(_auth, _dataset_id): res = list_documnets(_auth, _dataset_id) for doc in res["data"]["docs"]: if doc["run"] != "DONE": return False return True @pytest.fixture(scope="function") def add_chat_assistants_func(request, get_http_api_auth, add_document): def cleanup(): delete_chat_assistants(get_http_api_auth) request.addfinalizer(cleanup) dataset_id, document_id = add_document parse_documnets(get_http_api_auth, dataset_id, {"document_ids": [document_id]}) condition(get_http_api_auth, dataset_id) chat_assistant_ids = [] for i in range(5): res = create_chat_assistant(get_http_api_auth, {"name": f"test_chat_assistant_{i}", "dataset_ids": [dataset_id]}) chat_assistant_ids.append(res["data"]["id"]) return dataset_id, document_id, chat_assistant_ids
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chat_assistant_management/test_create_chat_assistant.py
sdk/python/test/test_http_api/test_chat_assistant_management/test_create_chat_assistant.py
# # 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 pytest from common import CHAT_ASSISTANT_NAME_LIMIT, INVALID_API_TOKEN, create_chat_assistant from libs.auth import RAGFlowHttpApiAuth from libs.utils import encode_avatar from libs.utils.file_utils import create_image_file @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = create_chat_assistant(auth) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.usefixtures("clear_chat_assistants") class TestChatAssistantCreate: @pytest.mark.p1 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"name": "valid_name"}, 0, ""), pytest.param({"name": "a" * (CHAT_ASSISTANT_NAME_LIMIT + 1)}, 102, "", marks=pytest.mark.skip(reason="issues/")), pytest.param({"name": 1}, 100, "", marks=pytest.mark.skip(reason="issues/")), ({"name": ""}, 102, "`name` is required."), ({"name": "duplicated_name"}, 102, "Duplicated chat name in creating chat."), ({"name": "case insensitive"}, 102, "Duplicated chat name in creating chat."), ], ) def test_name(self, get_http_api_auth, add_chunks, payload, expected_code, expected_message): payload["dataset_ids"] = [] # issues/ if payload["name"] == "duplicated_name": create_chat_assistant(get_http_api_auth, payload) elif payload["name"] == "case insensitive": create_chat_assistant(get_http_api_auth, {"name": payload["name"].upper()}) res = create_chat_assistant(get_http_api_auth, payload) assert res["code"] == expected_code, res if expected_code == 0: assert res["data"]["name"] == payload["name"] else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "dataset_ids, expected_code, expected_message", [ ([], 0, ""), (lambda r: [r], 0, ""), (["invalid_dataset_id"], 102, "You don't own the dataset invalid_dataset_id"), ("invalid_dataset_id", 102, "You don't own the dataset i"), ], ) def test_dataset_ids(self, get_http_api_auth, add_chunks, dataset_ids, expected_code, expected_message): dataset_id, _, _ = add_chunks payload = {"name": "ragflow test"} if callable(dataset_ids): payload["dataset_ids"] = dataset_ids(dataset_id) else: payload["dataset_ids"] = dataset_ids res = create_chat_assistant(get_http_api_auth, payload) assert res["code"] == expected_code, res if expected_code == 0: assert res["data"]["name"] == payload["name"] else: assert res["message"] == expected_message @pytest.mark.p3 def test_avatar(self, get_http_api_auth, tmp_path): fn = create_image_file(tmp_path / "ragflow_test.png") payload = {"name": "avatar_test", "avatar": encode_avatar(fn), "dataset_ids": []} res = create_chat_assistant(get_http_api_auth, payload) assert res["code"] == 0 @pytest.mark.p2 @pytest.mark.parametrize( "llm, expected_code, expected_message", [ ({}, 0, ""), ({"model_name": "glm-4"}, 0, ""), ({"model_name": "unknown"}, 102, "`model_name` unknown doesn't exist"), ({"temperature": 0}, 0, ""), ({"temperature": 1}, 0, ""), pytest.param({"temperature": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"temperature": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"temperature": "a"}, 0, "", marks=pytest.mark.skip), ({"top_p": 0}, 0, ""), ({"top_p": 1}, 0, ""), pytest.param({"top_p": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"top_p": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"top_p": "a"}, 0, "", marks=pytest.mark.skip), ({"presence_penalty": 0}, 0, ""), ({"presence_penalty": 1}, 0, ""), pytest.param({"presence_penalty": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"presence_penalty": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"presence_penalty": "a"}, 0, "", marks=pytest.mark.skip), ({"frequency_penalty": 0}, 0, ""), ({"frequency_penalty": 1}, 0, ""), pytest.param({"frequency_penalty": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"frequency_penalty": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"frequency_penalty": "a"}, 0, "", marks=pytest.mark.skip), ({"max_token": 0}, 0, ""), ({"max_token": 1024}, 0, ""), pytest.param({"max_token": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"max_token": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"max_token": "a"}, 0, "", marks=pytest.mark.skip), pytest.param({"unknown": "unknown"}, 0, "", marks=pytest.mark.skip), ], ) def test_llm(self, get_http_api_auth, add_chunks, llm, expected_code, expected_message): dataset_id, _, _ = add_chunks payload = {"name": "llm_test", "dataset_ids": [dataset_id], "llm": llm} res = create_chat_assistant(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: if llm: for k, v in llm.items(): assert res["data"]["llm"][k] == v else: assert res["data"]["llm"]["model_name"] == "glm-4-flash@ZHIPU-AI" assert res["data"]["llm"]["temperature"] == 0.1 assert res["data"]["llm"]["top_p"] == 0.3 assert res["data"]["llm"]["presence_penalty"] == 0.4 assert res["data"]["llm"]["frequency_penalty"] == 0.7 assert res["data"]["llm"]["max_tokens"] == 512 else: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "prompt, expected_code, expected_message", [ ({}, 0, ""), ({"similarity_threshold": 0}, 0, ""), ({"similarity_threshold": 1}, 0, ""), pytest.param({"similarity_threshold": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"similarity_threshold": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"similarity_threshold": "a"}, 0, "", marks=pytest.mark.skip), ({"keywords_similarity_weight": 0}, 0, ""), ({"keywords_similarity_weight": 1}, 0, ""), pytest.param({"keywords_similarity_weight": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"keywords_similarity_weight": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"keywords_similarity_weight": "a"}, 0, "", marks=pytest.mark.skip), ({"variables": []}, 0, ""), ({"top_n": 0}, 0, ""), ({"top_n": 1}, 0, ""), pytest.param({"top_n": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"top_n": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"top_n": "a"}, 0, "", marks=pytest.mark.skip), ({"empty_response": "Hello World"}, 0, ""), ({"empty_response": ""}, 0, ""), ({"empty_response": "!@#$%^&*()"}, 0, ""), ({"empty_response": "ไธญๆ–‡ๆต‹่ฏ•"}, 0, ""), pytest.param({"empty_response": 123}, 0, "", marks=pytest.mark.skip), pytest.param({"empty_response": True}, 0, "", marks=pytest.mark.skip), pytest.param({"empty_response": " "}, 0, "", marks=pytest.mark.skip), ({"opener": "Hello World"}, 0, ""), ({"opener": ""}, 0, ""), ({"opener": "!@#$%^&*()"}, 0, ""), ({"opener": "ไธญๆ–‡ๆต‹่ฏ•"}, 0, ""), pytest.param({"opener": 123}, 0, "", marks=pytest.mark.skip), pytest.param({"opener": True}, 0, "", marks=pytest.mark.skip), pytest.param({"opener": " "}, 0, "", marks=pytest.mark.skip), ({"show_quote": True}, 0, ""), ({"show_quote": False}, 0, ""), ({"prompt": "Hello World {knowledge}"}, 0, ""), ({"prompt": "{knowledge}"}, 0, ""), ({"prompt": "!@#$%^&*() {knowledge}"}, 0, ""), ({"prompt": "ไธญๆ–‡ๆต‹่ฏ• {knowledge}"}, 0, ""), ({"prompt": "Hello World"}, 102, "Parameter 'knowledge' is not used"), ({"prompt": "Hello World", "variables": []}, 0, ""), pytest.param({"prompt": 123}, 100, """AttributeError("\'int\' object has no attribute \'find\'")""", marks=pytest.mark.skip), pytest.param({"prompt": True}, 100, """AttributeError("\'int\' object has no attribute \'find\'")""", marks=pytest.mark.skip), pytest.param({"unknown": "unknown"}, 0, "", marks=pytest.mark.skip), ], ) def test_prompt(self, get_http_api_auth, add_chunks, prompt, expected_code, expected_message): dataset_id, _, _ = add_chunks payload = {"name": "prompt_test", "dataset_ids": [dataset_id], "prompt": prompt} res = create_chat_assistant(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: if prompt: for k, v in prompt.items(): if k == "keywords_similarity_weight": assert res["data"]["prompt"][k] == 1 - v else: assert res["data"]["prompt"][k] == v else: assert res["data"]["prompt"]["similarity_threshold"] == 0.2 assert res["data"]["prompt"]["keywords_similarity_weight"] == 0.7 assert res["data"]["prompt"]["top_n"] == 6 assert res["data"]["prompt"]["variables"] == [{"key": "knowledge", "optional": False}] assert res["data"]["prompt"]["rerank_model"] == "" assert res["data"]["prompt"]["empty_response"] == "Sorry! No relevant content was found in the knowledge base!" assert res["data"]["prompt"]["opener"] == "Hi! I'm your assistant. What can I do for you?" assert res["data"]["prompt"]["show_quote"] is True assert ( res["data"]["prompt"]["prompt"] == 'You are an intelligent assistant. Please summarize the content of the dataset to answer the question. Please list the data in the dataset and answer in detail. When all dataset content is irrelevant to the question, your answer must include the sentence "The answer you are looking for is not found in the dataset!" Answers need to consider chat history.\n Here is the knowledge base:\n {knowledge}\n The above is the knowledge base.' ) else: assert res["message"] == expected_message class TestChatAssistantCreate2: @pytest.mark.p2 def test_unparsed_document(self, get_http_api_auth, add_document): dataset_id, _ = add_document payload = {"name": "prompt_test", "dataset_ids": [dataset_id]} res = create_chat_assistant(get_http_api_auth, payload) assert res["code"] == 102 assert "doesn't own parsed file" in res["message"]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py
sdk/python/test/test_http_api/test_chat_assistant_management/test_update_chat_assistant.py
# # 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 pytest from common import CHAT_ASSISTANT_NAME_LIMIT, INVALID_API_TOKEN, list_chat_assistants, update_chat_assistant from libs.auth import RAGFlowHttpApiAuth from libs.utils import encode_avatar from libs.utils.file_utils import create_image_file @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = update_chat_assistant(auth, "chat_assistant_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestChatAssistantUpdate: @pytest.mark.parametrize( "payload, expected_code, expected_message", [ pytest.param({"name": "valid_name"}, 0, "", marks=pytest.mark.p1), pytest.param({"name": "a" * (CHAT_ASSISTANT_NAME_LIMIT + 1)}, 102, "", marks=pytest.mark.skip(reason="issues/")), pytest.param({"name": 1}, 100, "", marks=pytest.mark.skip(reason="issues/")), pytest.param({"name": ""}, 102, "`name` cannot be empty.", marks=pytest.mark.p3), pytest.param({"name": "test_chat_assistant_1"}, 102, "Duplicated chat name in updating chat.", marks=pytest.mark.p3), pytest.param({"name": "TEST_CHAT_ASSISTANT_1"}, 102, "Duplicated chat name in updating chat.", marks=pytest.mark.p3), ], ) def test_name(self, get_http_api_auth, add_chat_assistants_func, payload, expected_code, expected_message): _, _, chat_assistant_ids = add_chat_assistants_func res = update_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) assert res["code"] == expected_code, res if expected_code == 0: res = list_chat_assistants(get_http_api_auth, {"id": chat_assistant_ids[0]}) assert res["data"][0]["name"] == payload.get("name") else: assert res["message"] == expected_message @pytest.mark.parametrize( "dataset_ids, expected_code, expected_message", [ pytest.param([], 0, "", marks=pytest.mark.skip(reason="issues/")), pytest.param(lambda r: [r], 0, "", marks=pytest.mark.p1), pytest.param(["invalid_dataset_id"], 102, "You don't own the dataset invalid_dataset_id", marks=pytest.mark.p3), pytest.param("invalid_dataset_id", 102, "You don't own the dataset i", marks=pytest.mark.p3), ], ) def test_dataset_ids(self, get_http_api_auth, add_chat_assistants_func, dataset_ids, expected_code, expected_message): dataset_id, _, chat_assistant_ids = add_chat_assistants_func payload = {"name": "ragflow test"} if callable(dataset_ids): payload["dataset_ids"] = dataset_ids(dataset_id) else: payload["dataset_ids"] = dataset_ids res = update_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) assert res["code"] == expected_code, res if expected_code == 0: res = list_chat_assistants(get_http_api_auth, {"id": chat_assistant_ids[0]}) assert res["data"][0]["name"] == payload.get("name") else: assert res["message"] == expected_message @pytest.mark.p3 def test_avatar(self, get_http_api_auth, add_chat_assistants_func, tmp_path): dataset_id, _, chat_assistant_ids = add_chat_assistants_func fn = create_image_file(tmp_path / "ragflow_test.png") payload = {"name": "avatar_test", "avatar": encode_avatar(fn), "dataset_ids": [dataset_id]} res = update_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) assert res["code"] == 0 @pytest.mark.p3 @pytest.mark.parametrize( "llm, expected_code, expected_message", [ ({}, 100, "ValueError"), ({"model_name": "glm-4"}, 0, ""), ({"model_name": "unknown"}, 102, "`model_name` unknown doesn't exist"), ({"temperature": 0}, 0, ""), ({"temperature": 1}, 0, ""), pytest.param({"temperature": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"temperature": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"temperature": "a"}, 0, "", marks=pytest.mark.skip), ({"top_p": 0}, 0, ""), ({"top_p": 1}, 0, ""), pytest.param({"top_p": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"top_p": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"top_p": "a"}, 0, "", marks=pytest.mark.skip), ({"presence_penalty": 0}, 0, ""), ({"presence_penalty": 1}, 0, ""), pytest.param({"presence_penalty": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"presence_penalty": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"presence_penalty": "a"}, 0, "", marks=pytest.mark.skip), ({"frequency_penalty": 0}, 0, ""), ({"frequency_penalty": 1}, 0, ""), pytest.param({"frequency_penalty": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"frequency_penalty": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"frequency_penalty": "a"}, 0, "", marks=pytest.mark.skip), ({"max_token": 0}, 0, ""), ({"max_token": 1024}, 0, ""), pytest.param({"max_token": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"max_token": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"max_token": "a"}, 0, "", marks=pytest.mark.skip), pytest.param({"unknown": "unknown"}, 0, "", marks=pytest.mark.skip), ], ) def test_llm(self, get_http_api_auth, add_chat_assistants_func, llm, expected_code, expected_message): dataset_id, _, chat_assistant_ids = add_chat_assistants_func payload = {"name": "llm_test", "dataset_ids": [dataset_id], "llm": llm} res = update_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) assert res["code"] == expected_code if expected_code == 0: res = list_chat_assistants(get_http_api_auth, {"id": chat_assistant_ids[0]}) if llm: for k, v in llm.items(): assert res["data"][0]["llm"][k] == v else: assert res["data"][0]["llm"]["model_name"] == "glm-4-flash@ZHIPU-AI" assert res["data"][0]["llm"]["temperature"] == 0.1 assert res["data"][0]["llm"]["top_p"] == 0.3 assert res["data"][0]["llm"]["presence_penalty"] == 0.4 assert res["data"][0]["llm"]["frequency_penalty"] == 0.7 assert res["data"][0]["llm"]["max_tokens"] == 512 else: assert expected_message in res["message"] @pytest.mark.p3 @pytest.mark.parametrize( "prompt, expected_code, expected_message", [ ({}, 100, "ValueError"), ({"similarity_threshold": 0}, 0, ""), ({"similarity_threshold": 1}, 0, ""), pytest.param({"similarity_threshold": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"similarity_threshold": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"similarity_threshold": "a"}, 0, "", marks=pytest.mark.skip), ({"keywords_similarity_weight": 0}, 0, ""), ({"keywords_similarity_weight": 1}, 0, ""), pytest.param({"keywords_similarity_weight": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"keywords_similarity_weight": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"keywords_similarity_weight": "a"}, 0, "", marks=pytest.mark.skip), ({"variables": []}, 0, ""), ({"top_n": 0}, 0, ""), ({"top_n": 1}, 0, ""), pytest.param({"top_n": -1}, 0, "", marks=pytest.mark.skip), pytest.param({"top_n": 10}, 0, "", marks=pytest.mark.skip), pytest.param({"top_n": "a"}, 0, "", marks=pytest.mark.skip), ({"empty_response": "Hello World"}, 0, ""), ({"empty_response": ""}, 0, ""), ({"empty_response": "!@#$%^&*()"}, 0, ""), ({"empty_response": "ไธญๆ–‡ๆต‹่ฏ•"}, 0, ""), pytest.param({"empty_response": 123}, 0, "", marks=pytest.mark.skip), pytest.param({"empty_response": True}, 0, "", marks=pytest.mark.skip), pytest.param({"empty_response": " "}, 0, "", marks=pytest.mark.skip), ({"opener": "Hello World"}, 0, ""), ({"opener": ""}, 0, ""), ({"opener": "!@#$%^&*()"}, 0, ""), ({"opener": "ไธญๆ–‡ๆต‹่ฏ•"}, 0, ""), pytest.param({"opener": 123}, 0, "", marks=pytest.mark.skip), pytest.param({"opener": True}, 0, "", marks=pytest.mark.skip), pytest.param({"opener": " "}, 0, "", marks=pytest.mark.skip), ({"show_quote": True}, 0, ""), ({"show_quote": False}, 0, ""), ({"prompt": "Hello World {knowledge}"}, 0, ""), ({"prompt": "{knowledge}"}, 0, ""), ({"prompt": "!@#$%^&*() {knowledge}"}, 0, ""), ({"prompt": "ไธญๆ–‡ๆต‹่ฏ• {knowledge}"}, 0, ""), ({"prompt": "Hello World"}, 102, "Parameter 'knowledge' is not used"), ({"prompt": "Hello World", "variables": []}, 0, ""), pytest.param({"prompt": 123}, 100, """AttributeError("\'int\' object has no attribute \'find\'")""", marks=pytest.mark.skip), pytest.param({"prompt": True}, 100, """AttributeError("\'int\' object has no attribute \'find\'")""", marks=pytest.mark.skip), pytest.param({"unknown": "unknown"}, 0, "", marks=pytest.mark.skip), ], ) def test_prompt(self, get_http_api_auth, add_chat_assistants_func, prompt, expected_code, expected_message): dataset_id, _, chat_assistant_ids = add_chat_assistants_func payload = {"name": "prompt_test", "dataset_ids": [dataset_id], "prompt": prompt} res = update_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) assert res["code"] == expected_code if expected_code == 0: res = list_chat_assistants(get_http_api_auth, {"id": chat_assistant_ids[0]}) if prompt: for k, v in prompt.items(): if k == "keywords_similarity_weight": assert res["data"][0]["prompt"][k] == 1 - v else: assert res["data"][0]["prompt"][k] == v else: assert res["data"]["prompt"][0]["similarity_threshold"] == 0.2 assert res["data"]["prompt"][0]["keywords_similarity_weight"] == 0.7 assert res["data"]["prompt"][0]["top_n"] == 6 assert res["data"]["prompt"][0]["variables"] == [{"key": "knowledge", "optional": False}] assert res["data"]["prompt"][0]["rerank_model"] == "" assert res["data"]["prompt"][0]["empty_response"] == "Sorry! No relevant content was found in the knowledge base!" assert res["data"]["prompt"][0]["opener"] == "Hi! I'm your assistant. What can I do for you?" assert res["data"]["prompt"][0]["show_quote"] is True assert ( res["data"]["prompt"][0]["prompt"] == 'You are an intelligent assistant. Please summarize the content of the dataset to answer the question. Please list the data in the dataset and answer in detail. When all dataset content is irrelevant to the question, your answer must include the sentence "The answer you are looking for is not found in the dataset!" Answers need to consider chat history.\n Here is the knowledge base:\n {knowledge}\n The above is the knowledge base.' ) else: assert expected_message in res["message"]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py
sdk/python/test/test_http_api/test_chat_assistant_management/test_list_chat_assistants.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, delete_datasets, list_chat_assistants from libs.auth import RAGFlowHttpApiAuth from libs.utils import is_sorted @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = list_chat_assistants(auth) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.usefixtures("add_chat_assistants") class TestChatAssistantsList: @pytest.mark.p1 def test_default(self, get_http_api_auth): res = list_chat_assistants(get_http_api_auth) assert res["code"] == 0 assert len(res["data"]) == 5 @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_page_size, expected_message", [ ({"page": None, "page_size": 2}, 0, 2, ""), ({"page": 0, "page_size": 2}, 0, 2, ""), ({"page": 2, "page_size": 2}, 0, 2, ""), ({"page": 3, "page_size": 2}, 0, 1, ""), ({"page": "3", "page_size": 2}, 0, 1, ""), pytest.param( {"page": -1, "page_size": 2}, 100, 0, "1064", marks=pytest.mark.skip(reason="issues/5851"), ), pytest.param( {"page": "a", "page_size": 2}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip(reason="issues/5851"), ), ], ) def test_page(self, get_http_api_auth, params, expected_code, expected_page_size, expected_message): res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_page_size, expected_message", [ ({"page_size": None}, 0, 5, ""), ({"page_size": 0}, 0, 0, ""), ({"page_size": 1}, 0, 1, ""), ({"page_size": 6}, 0, 5, ""), ({"page_size": "1"}, 0, 1, ""), pytest.param( {"page_size": -1}, 100, 0, "1064", marks=pytest.mark.skip(reason="issues/5851"), ), pytest.param( {"page_size": "a"}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip(reason="issues/5851"), ), ], ) def test_page_size( self, get_http_api_auth, params, expected_code, expected_page_size, expected_message, ): res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "params, expected_code, assertions, expected_message", [ ({"orderby": None}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"orderby": "create_time"}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"orderby": "update_time"}, 0, lambda r: (is_sorted(r["data"], "update_time", True)), ""), pytest.param( {"orderby": "name", "desc": "False"}, 0, lambda r: (is_sorted(r["data"], "name", False)), "", marks=pytest.mark.skip(reason="issues/5851"), ), pytest.param( {"orderby": "unknown"}, 102, 0, "orderby should be create_time or update_time", marks=pytest.mark.skip(reason="issues/5851"), ), ], ) def test_orderby( self, get_http_api_auth, params, expected_code, assertions, expected_message, ): res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: if callable(assertions): assert assertions(res) else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "params, expected_code, assertions, expected_message", [ ({"desc": None}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": "true"}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": "True"}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": True}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": "false"}, 0, lambda r: (is_sorted(r["data"], "create_time", False)), ""), ({"desc": "False"}, 0, lambda r: (is_sorted(r["data"], "create_time", False)), ""), ({"desc": False}, 0, lambda r: (is_sorted(r["data"], "create_time", False)), ""), ({"desc": "False", "orderby": "update_time"}, 0, lambda r: (is_sorted(r["data"], "update_time", False)), ""), pytest.param( {"desc": "unknown"}, 102, 0, "desc should be true or false", marks=pytest.mark.skip(reason="issues/5851"), ), ], ) def test_desc( self, get_http_api_auth, params, expected_code, assertions, expected_message, ): res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: if callable(assertions): assert assertions(res) else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_num, expected_message", [ ({"name": None}, 0, 5, ""), ({"name": ""}, 0, 5, ""), ({"name": "test_chat_assistant_1"}, 0, 1, ""), ({"name": "unknown"}, 102, 0, "The chat doesn't exist"), ], ) def test_name(self, get_http_api_auth, params, expected_code, expected_num, expected_message): res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: if params["name"] in [None, ""]: assert len(res["data"]) == expected_num else: assert res["data"][0]["name"] == params["name"] else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "chat_assistant_id, expected_code, expected_num, expected_message", [ (None, 0, 5, ""), ("", 0, 5, ""), (lambda r: r[0], 0, 1, ""), ("unknown", 102, 0, "The chat doesn't exist"), ], ) def test_id( self, get_http_api_auth, add_chat_assistants, chat_assistant_id, expected_code, expected_num, expected_message, ): _, _, chat_assistant_ids = add_chat_assistants if callable(chat_assistant_id): params = {"id": chat_assistant_id(chat_assistant_ids)} else: params = {"id": chat_assistant_id} res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: if params["id"] in [None, ""]: assert len(res["data"]) == expected_num else: assert res["data"][0]["id"] == params["id"] else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "chat_assistant_id, name, expected_code, expected_num, expected_message", [ (lambda r: r[0], "test_chat_assistant_0", 0, 1, ""), (lambda r: r[0], "test_chat_assistant_1", 102, 0, "The chat doesn't exist"), (lambda r: r[0], "unknown", 102, 0, "The chat doesn't exist"), ("id", "chat_assistant_0", 102, 0, "The chat doesn't exist"), ], ) def test_name_and_id( self, get_http_api_auth, add_chat_assistants, chat_assistant_id, name, expected_code, expected_num, expected_message, ): _, _, chat_assistant_ids = add_chat_assistants if callable(chat_assistant_id): params = {"id": chat_assistant_id(chat_assistant_ids), "name": name} else: params = {"id": chat_assistant_id, "name": name} res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]) == expected_num else: assert res["message"] == expected_message @pytest.mark.p3 def test_concurrent_list(self, get_http_api_auth): with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(list_chat_assistants, get_http_api_auth) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_invalid_params(self, get_http_api_auth): params = {"a": "b"} res = list_chat_assistants(get_http_api_auth, params=params) assert res["code"] == 0 assert len(res["data"]) == 5 @pytest.mark.p2 def test_list_chats_after_deleting_associated_dataset(self, get_http_api_auth, add_chat_assistants): dataset_id, _, _ = add_chat_assistants res = delete_datasets(get_http_api_auth, {"ids": [dataset_id]}) assert res["code"] == 0 res = list_chat_assistants(get_http_api_auth) assert res["code"] == 0 assert len(res["data"]) == 5
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_dataset_mangement/test_list_datasets.py
sdk/python/test/test_http_api/test_dataset_mangement/test_list_datasets.py
# # 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 uuid from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, list_datasets from libs.auth import RAGFlowHttpApiAuth from libs.utils import is_sorted class TestAuthorization: @pytest.mark.p1 @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_auth_invalid(self, auth, expected_code, expected_message): res = list_datasets(auth) assert res["code"] == expected_code, res assert res["message"] == expected_message, res class TestCapability: @pytest.mark.p3 def test_concurrent_list(self, get_http_api_auth): with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(list_datasets, get_http_api_auth) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses), responses @pytest.mark.usefixtures("add_datasets") class TestDatasetsList: @pytest.mark.p1 def test_params_unset(self, get_http_api_auth): res = list_datasets(get_http_api_auth, None) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p2 def test_params_empty(self, get_http_api_auth): res = list_datasets(get_http_api_auth, {}) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_page_size", [ ({"page": 2, "page_size": 2}, 2), ({"page": 3, "page_size": 2}, 1), ({"page": 4, "page_size": 2}, 0), ({"page": "2", "page_size": 2}, 2), ({"page": 1, "page_size": 10}, 5), ], ids=["normal_middle_page", "normal_last_partial_page", "beyond_max_page", "string_page_number", "full_data_single_page"], ) def test_page(self, get_http_api_auth, params, expected_page_size): res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == expected_page_size, res @pytest.mark.p2 @pytest.mark.parametrize( "params, expected_code, expected_message", [ ({"page": 0}, 101, "Input should be greater than or equal to 1"), ({"page": "a"}, 101, "Input should be a valid integer, unable to parse string as an integer"), ], ids=["page_0", "page_a"], ) def test_page_invalid(self, get_http_api_auth, params, expected_code, expected_message): res = list_datasets(get_http_api_auth, params=params) assert res["code"] == expected_code, res assert expected_message in res["message"], res @pytest.mark.p2 def test_page_none(self, get_http_api_auth): params = {"page": None} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_page_size", [ ({"page_size": 1}, 1), ({"page_size": 3}, 3), ({"page_size": 5}, 5), ({"page_size": 6}, 5), ({"page_size": "1"}, 1), ], ids=["min_valid_page_size", "medium_page_size", "page_size_equals_total", "page_size_exceeds_total", "string_type_page_size"], ) def test_page_size(self, get_http_api_auth, params, expected_page_size): res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == expected_page_size, res @pytest.mark.p2 @pytest.mark.parametrize( "params, expected_code, expected_message", [ ({"page_size": 0}, 101, "Input should be greater than or equal to 1"), ({"page_size": "a"}, 101, "Input should be a valid integer, unable to parse string as an integer"), ], ) def test_page_size_invalid(self, get_http_api_auth, params, expected_code, expected_message): res = list_datasets(get_http_api_auth, params) assert res["code"] == expected_code, res assert expected_message in res["message"], res @pytest.mark.p2 def test_page_size_none(self, get_http_api_auth): params = {"page_size": None} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p2 @pytest.mark.parametrize( "params, assertions", [ ({"orderby": "create_time"}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"orderby": "update_time"}, lambda r: (is_sorted(r["data"], "update_time", True))), ({"orderby": "CREATE_TIME"}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"orderby": "UPDATE_TIME"}, lambda r: (is_sorted(r["data"], "update_time", True))), ({"orderby": " create_time "}, lambda r: (is_sorted(r["data"], "update_time", True))), ], ids=["orderby_create_time", "orderby_update_time", "orderby_create_time_upper", "orderby_update_time_upper", "whitespace"], ) def test_orderby(self, get_http_api_auth, params, assertions): res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res if callable(assertions): assert assertions(res), res @pytest.mark.p3 @pytest.mark.parametrize( "params", [ {"orderby": ""}, {"orderby": "unknown"}, ], ids=["empty", "unknown"], ) def test_orderby_invalid(self, get_http_api_auth, params): res = list_datasets(get_http_api_auth, params) assert res["code"] == 101, res assert "Input should be 'create_time' or 'update_time'" in res["message"], res @pytest.mark.p3 def test_orderby_none(self, get_http_api_auth): params = {"order_by": None} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert is_sorted(res["data"], "create_time", True), res @pytest.mark.p2 @pytest.mark.parametrize( "params, assertions", [ ({"desc": True}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"desc": False}, lambda r: (is_sorted(r["data"], "create_time", False))), ({"desc": "true"}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"desc": "false"}, lambda r: (is_sorted(r["data"], "create_time", False))), ({"desc": 1}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"desc": 0}, lambda r: (is_sorted(r["data"], "create_time", False))), ({"desc": "yes"}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"desc": "no"}, lambda r: (is_sorted(r["data"], "create_time", False))), ({"desc": "y"}, lambda r: (is_sorted(r["data"], "create_time", True))), ({"desc": "n"}, lambda r: (is_sorted(r["data"], "create_time", False))), ], ids=["desc=True", "desc=False", "desc=true", "desc=false", "desc=1", "desc=0", "desc=yes", "desc=no", "desc=y", "desc=n"], ) def test_desc(self, get_http_api_auth, params, assertions): res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res if callable(assertions): assert assertions(res), res @pytest.mark.p3 @pytest.mark.parametrize( "params", [ {"desc": 3.14}, {"desc": "unknown"}, ], ids=["empty", "unknown"], ) def test_desc_invalid(self, get_http_api_auth, params): res = list_datasets(get_http_api_auth, params) assert res["code"] == 101, res assert "Input should be a valid boolean, unable to interpret input" in res["message"], res @pytest.mark.p3 def test_desc_none(self, get_http_api_auth): params = {"desc": None} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert is_sorted(res["data"], "create_time", True), res @pytest.mark.p1 def test_name(self, get_http_api_auth): params = {"name": "dataset_1"} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == 1, res assert res["data"][0]["name"] == "dataset_1", res @pytest.mark.p2 def test_name_wrong(self, get_http_api_auth): params = {"name": "wrong name"} res = list_datasets(get_http_api_auth, params) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res @pytest.mark.p2 def test_name_empty(self, get_http_api_auth): params = {"name": ""} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p2 def test_name_none(self, get_http_api_auth): params = {"name": None} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p1 def test_id(self, get_http_api_auth, add_datasets): dataset_ids = add_datasets params = {"id": dataset_ids[0]} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0 assert len(res["data"]) == 1 assert res["data"][0]["id"] == dataset_ids[0] @pytest.mark.p2 def test_id_not_uuid(self, get_http_api_auth): params = {"id": "not_uuid"} res = list_datasets(get_http_api_auth, params) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res @pytest.mark.p2 def test_id_not_uuid1(self, get_http_api_auth): params = {"id": uuid.uuid4().hex} res = list_datasets(get_http_api_auth, params) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res @pytest.mark.p2 def test_id_wrong_uuid(self, get_http_api_auth): params = {"id": "d94a8dc02c9711f0930f7fbc369eab6d"} res = list_datasets(get_http_api_auth, params) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res @pytest.mark.p2 def test_id_empty(self, get_http_api_auth): params = {"id": ""} res = list_datasets(get_http_api_auth, params) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res @pytest.mark.p2 def test_id_none(self, get_http_api_auth): params = {"id": None} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == 5, res @pytest.mark.p2 @pytest.mark.parametrize( "func, name, expected_num", [ (lambda r: r[0], "dataset_0", 1), (lambda r: r[0], "dataset_1", 0), ], ids=["name_and_id_match", "name_and_id_mismatch"], ) def test_name_and_id(self, get_http_api_auth, add_datasets, func, name, expected_num): dataset_ids = add_datasets if callable(func): params = {"id": func(dataset_ids), "name": name} res = list_datasets(get_http_api_auth, params) assert res["code"] == 0, res assert len(res["data"]) == expected_num, res @pytest.mark.p3 @pytest.mark.parametrize( "dataset_id, name", [ (lambda r: r[0], "wrong_name"), (uuid.uuid1().hex, "dataset_0"), ], ids=["name", "id"], ) def test_name_and_id_wrong(self, get_http_api_auth, add_datasets, dataset_id, name): dataset_ids = add_datasets if callable(dataset_id): params = {"id": dataset_id(dataset_ids), "name": name} else: params = {"id": dataset_id, "name": name} res = list_datasets(get_http_api_auth, params) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res @pytest.mark.p2 def test_field_unsupported(self, get_http_api_auth): params = {"unknown_field": "unknown_field"} res = list_datasets(get_http_api_auth, params) assert res["code"] == 101, res assert "Extra inputs are not permitted" in res["message"], res
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_dataset_mangement/test_delete_datasets.py
sdk/python/test/test_http_api/test_dataset_mangement/test_delete_datasets.py
# # 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 uuid from concurrent.futures import ThreadPoolExecutor import pytest from common import ( INVALID_API_TOKEN, batch_create_datasets, delete_datasets, list_datasets, ) from libs.auth import RAGFlowHttpApiAuth class TestAuthorization: @pytest.mark.p1 @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_auth_invalid(self, auth, expected_code, expected_message): res = delete_datasets(auth) assert res["code"] == expected_code, res assert res["message"] == expected_message, res class TestRquest: @pytest.mark.p3 def test_content_type_bad(self, get_http_api_auth): BAD_CONTENT_TYPE = "text/xml" res = delete_datasets(get_http_api_auth, headers={"Content-Type": BAD_CONTENT_TYPE}) assert res["code"] == 101, res assert res["message"] == f"Unsupported content type: Expected application/json, got {BAD_CONTENT_TYPE}", res @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_message", [ ("a", "Malformed JSON syntax: Missing commas/brackets or invalid encoding"), ('"a"', "Invalid request payload: expected object, got str"), ], ids=["malformed_json_syntax", "invalid_request_payload_type"], ) def test_payload_bad(self, get_http_api_auth, payload, expected_message): res = delete_datasets(get_http_api_auth, data=payload) assert res["code"] == 101, res assert res["message"] == expected_message, res @pytest.mark.p3 def test_payload_unset(self, get_http_api_auth): res = delete_datasets(get_http_api_auth, None) assert res["code"] == 101, res assert res["message"] == "Malformed JSON syntax: Missing commas/brackets or invalid encoding", res class TestCapability: @pytest.mark.p3 def test_delete_dataset_1k(self, get_http_api_auth): ids = batch_create_datasets(get_http_api_auth, 1_000) res = delete_datasets(get_http_api_auth, {"ids": ids}) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 0, res @pytest.mark.p3 def test_concurrent_deletion(self, get_http_api_auth): dataset_num = 1_000 ids = batch_create_datasets(get_http_api_auth, dataset_num) with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(delete_datasets, get_http_api_auth, {"ids": ids[i : i + 1]}) for i in range(dataset_num)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses), responses class TestDatasetsDelete: @pytest.mark.p1 @pytest.mark.parametrize( "func, expected_code, expected_message, remaining", [ (lambda r: {"ids": r[:1]}, 0, "", 2), (lambda r: {"ids": r}, 0, "", 0), ], ids=["single_dataset", "multiple_datasets"], ) def test_ids(self, get_http_api_auth, add_datasets_func, func, expected_code, expected_message, remaining): dataset_ids = add_datasets_func if callable(func): payload = func(dataset_ids) res = delete_datasets(get_http_api_auth, payload) assert res["code"] == expected_code, res res = list_datasets(get_http_api_auth) assert len(res["data"]) == remaining, res @pytest.mark.p1 @pytest.mark.usefixtures("add_dataset_func") def test_ids_empty(self, get_http_api_auth): payload = {"ids": []} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 1, res @pytest.mark.p1 @pytest.mark.usefixtures("add_datasets_func") def test_ids_none(self, get_http_api_auth): payload = {"ids": None} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 0, res @pytest.mark.p2 @pytest.mark.usefixtures("add_dataset_func") def test_id_not_uuid(self, get_http_api_auth): payload = {"ids": ["not_uuid"]} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 1, res @pytest.mark.p3 @pytest.mark.usefixtures("add_dataset_func") def test_id_not_uuid1(self, get_http_api_auth): payload = {"ids": [uuid.uuid4().hex]} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res @pytest.mark.p2 @pytest.mark.usefixtures("add_dataset_func") def test_id_wrong_uuid(self, get_http_api_auth): payload = {"ids": ["d94a8dc02c9711f0930f7fbc369eab6d"]} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 1, res @pytest.mark.p2 @pytest.mark.parametrize( "func", [ lambda r: {"ids": ["d94a8dc02c9711f0930f7fbc369eab6d"] + r}, lambda r: {"ids": r[:1] + ["d94a8dc02c9711f0930f7fbc369eab6d"] + r[1:3]}, lambda r: {"ids": r + ["d94a8dc02c9711f0930f7fbc369eab6d"]}, ], ) def test_ids_partial_invalid(self, get_http_api_auth, add_datasets_func, func): dataset_ids = add_datasets_func if callable(func): payload = func(dataset_ids) res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 3, res @pytest.mark.p2 def test_ids_duplicate(self, get_http_api_auth, add_datasets_func): dataset_ids = add_datasets_func payload = {"ids": dataset_ids + dataset_ids} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 101, res assert "Duplicate ids:" in res["message"], res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 3, res @pytest.mark.p2 def test_repeated_delete(self, get_http_api_auth, add_datasets_func): dataset_ids = add_datasets_func payload = {"ids": dataset_ids} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 0, res res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res @pytest.mark.p2 @pytest.mark.usefixtures("add_dataset_func") def test_field_unsupported(self, get_http_api_auth): payload = {"unknown_field": "unknown_field"} res = delete_datasets(get_http_api_auth, payload) assert res["code"] == 101, res assert "Extra inputs are not permitted" in res["message"], res res = list_datasets(get_http_api_auth) assert len(res["data"]) == 1, res
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_dataset_mangement/test_create_dataset.py
sdk/python/test/test_http_api/test_dataset_mangement/test_create_dataset.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import DATASET_NAME_LIMIT, INVALID_API_TOKEN, create_dataset from hypothesis import example, given, settings from libs.auth import RAGFlowHttpApiAuth from libs.utils import encode_avatar from libs.utils.file_utils import create_image_file from libs.utils.hypothesis_utils import valid_names @pytest.mark.usefixtures("clear_datasets") class TestAuthorization: @pytest.mark.p1 @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ids=["empty_auth", "invalid_api_token"], ) def test_auth_invalid(self, auth, expected_code, expected_message): res = create_dataset(auth, {"name": "auth_test"}) assert res["code"] == expected_code, res assert res["message"] == expected_message, res class TestRquest: @pytest.mark.p3 def test_content_type_bad(self, get_http_api_auth): BAD_CONTENT_TYPE = "text/xml" res = create_dataset(get_http_api_auth, {"name": "bad_content_type"}, headers={"Content-Type": BAD_CONTENT_TYPE}) assert res["code"] == 101, res assert res["message"] == f"Unsupported content type: Expected application/json, got {BAD_CONTENT_TYPE}", res @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_message", [ ("a", "Malformed JSON syntax: Missing commas/brackets or invalid encoding"), ('"a"', "Invalid request payload: expected object, got str"), ], ids=["malformed_json_syntax", "invalid_request_payload_type"], ) def test_payload_bad(self, get_http_api_auth, payload, expected_message): res = create_dataset(get_http_api_auth, data=payload) assert res["code"] == 101, res assert res["message"] == expected_message, res @pytest.mark.usefixtures("clear_datasets") class TestCapability: @pytest.mark.p3 def test_create_dataset_1k(self, get_http_api_auth): for i in range(1_000): payload = {"name": f"dataset_{i}"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, f"Failed to create dataset {i}" @pytest.mark.p3 def test_create_dataset_concurrent(self, get_http_api_auth): with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(create_dataset, get_http_api_auth, {"name": f"dataset_{i}"}) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses), responses @pytest.mark.usefixtures("clear_datasets") class TestDatasetCreate: @pytest.mark.p1 @given(name=valid_names()) @example("a" * 128) @settings(max_examples=20) def test_name(self, get_http_api_auth, name): res = create_dataset(get_http_api_auth, {"name": name}) assert res["code"] == 0, res assert res["data"]["name"] == name, res @pytest.mark.p2 @pytest.mark.parametrize( "name, expected_message", [ ("", "String should have at least 1 character"), (" ", "String should have at least 1 character"), ("a" * (DATASET_NAME_LIMIT + 1), "String should have at most 128 characters"), (0, "Input should be a valid string"), (None, "Input should be a valid string"), ], ids=["empty_name", "space_name", "too_long_name", "invalid_name", "None_name"], ) def test_name_invalid(self, get_http_api_auth, name, expected_message): payload = {"name": name} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p3 def test_name_duplicated(self, get_http_api_auth): name = "duplicated_name" payload = {"name": name} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res res = create_dataset(get_http_api_auth, payload) assert res["code"] == 103, res assert res["message"] == f"Dataset name '{name}' already exists", res @pytest.mark.p3 def test_name_case_insensitive(self, get_http_api_auth): name = "CaseInsensitive" payload = {"name": name.upper()} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res payload = {"name": name.lower()} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 103, res assert res["message"] == f"Dataset name '{name.lower()}' already exists", res @pytest.mark.p2 def test_avatar(self, get_http_api_auth, tmp_path): fn = create_image_file(tmp_path / "ragflow_test.png") payload = { "name": "avatar", "avatar": f"data:image/png;base64,{encode_avatar(fn)}", } res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res @pytest.mark.p2 def test_avatar_exceeds_limit_length(self, get_http_api_auth): payload = {"name": "avatar_exceeds_limit_length", "avatar": "a" * 65536} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "String should have at most 65535 characters" in res["message"], res @pytest.mark.p3 @pytest.mark.parametrize( "name, prefix, expected_message", [ ("empty_prefix", "", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"), ("missing_comma", "data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"), ("unsupported_mine_type", "invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"), ("invalid_mine_type", "data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"), ], ids=["empty_prefix", "missing_comma", "unsupported_mine_type", "invalid_mine_type"], ) def test_avatar_invalid_prefix(self, get_http_api_auth, tmp_path, name, prefix, expected_message): fn = create_image_file(tmp_path / "ragflow_test.png") payload = { "name": name, "avatar": f"{prefix}{encode_avatar(fn)}", } res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p3 def test_avatar_unset(self, get_http_api_auth): payload = {"name": "avatar_unset"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["avatar"] is None, res @pytest.mark.p3 def test_avatar_none(self, get_http_api_auth): payload = {"name": "avatar_none", "avatar": None} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["avatar"] is None, res @pytest.mark.p2 def test_description(self, get_http_api_auth): payload = {"name": "description", "description": "description"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["description"] == "description", res @pytest.mark.p2 def test_description_exceeds_limit_length(self, get_http_api_auth): payload = {"name": "description_exceeds_limit_length", "description": "a" * 65536} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "String should have at most 65535 characters" in res["message"], res @pytest.mark.p3 def test_description_unset(self, get_http_api_auth): payload = {"name": "description_unset"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["description"] is None, res @pytest.mark.p3 def test_description_none(self, get_http_api_auth): payload = {"name": "description_none", "description": None} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["description"] is None, res @pytest.mark.p1 @pytest.mark.parametrize( "name, embedding_model", [ ("BAAI/bge-small-en-v1.5@Builtin", "BAAI/bge-small-en-v1.5@Builtin"), ("embedding-3@ZHIPU-AI", "embedding-3@ZHIPU-AI"), ], ids=["builtin_baai", "tenant_zhipu"], ) def test_embedding_model(self, get_http_api_auth, name, embedding_model): payload = {"name": name, "embedding_model": embedding_model} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["embedding_model"] == embedding_model, res @pytest.mark.p2 @pytest.mark.parametrize( "name, embedding_model", [ ("unknown_llm_name", "unknown@ZHIPU-AI"), ("unknown_llm_factory", "embedding-3@unknown"), ("tenant_no_auth_default_tenant_llm", "text-embedding-v3@Tongyi-Qianwen"), ("tenant_no_auth", "text-embedding-3-small@OpenAI"), ], ids=["unknown_llm_name", "unknown_llm_factory", "tenant_no_auth_default_tenant_llm", "tenant_no_auth"], ) def test_embedding_model_invalid(self, get_http_api_auth, name, embedding_model): payload = {"name": name, "embedding_model": embedding_model} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res if "tenant_no_auth" in name: assert res["message"] == f"Unauthorized model: <{embedding_model}>", res else: assert res["message"] == f"Unsupported model: <{embedding_model}>", res @pytest.mark.p2 @pytest.mark.parametrize( "name, embedding_model", [ ("missing_at", "BAAI/bge-small-en-v1.5Builtin"), ("missing_model_name", "@Builtin"), ("missing_provider", "BAAI/bge-small-en-v1.5@"), ("whitespace_only_model_name", " @Builtin"), ("whitespace_only_provider", "BAAI/bge-small-en-v1.5@ "), ], ids=["missing_at", "empty_model_name", "empty_provider", "whitespace_only_model_name", "whitespace_only_provider"], ) def test_embedding_model_format(self, get_http_api_auth, name, embedding_model): payload = {"name": name, "embedding_model": embedding_model} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res if name == "missing_at": assert "Embedding model identifier must follow <model_name>@<provider> format" in res["message"], res else: assert "Both model_name and provider must be non-empty strings" in res["message"], res @pytest.mark.p2 def test_embedding_model_unset(self, get_http_api_auth): payload = {"name": "embedding_model_unset"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["embedding_model"] == "BAAI/bge-small-en-v1.5@Builtin", res @pytest.mark.p2 def test_embedding_model_none(self, get_http_api_auth): payload = {"name": "embedding_model_none", "embedding_model": None} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "Input should be a valid string" in res["message"], res @pytest.mark.p1 @pytest.mark.parametrize( "name, permission", [ ("me", "me"), ("team", "team"), ("me_upercase", "ME"), ("team_upercase", "TEAM"), ("whitespace", " ME "), ], ids=["me", "team", "me_upercase", "team_upercase", "whitespace"], ) def test_permission(self, get_http_api_auth, name, permission): payload = {"name": name, "permission": permission} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["permission"] == permission.lower().strip(), res @pytest.mark.p2 @pytest.mark.parametrize( "name, permission", [ ("empty", ""), ("unknown", "unknown"), ("type_error", list()), ], ids=["empty", "unknown", "type_error"], ) def test_permission_invalid(self, get_http_api_auth, name, permission): payload = {"name": name, "permission": permission} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101 assert "Input should be 'me' or 'team'" in res["message"] @pytest.mark.p2 def test_permission_unset(self, get_http_api_auth): payload = {"name": "permission_unset"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["permission"] == "me", res @pytest.mark.p3 def test_permission_none(self, get_http_api_auth): payload = {"name": "permission_none", "permission": None} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "Input should be 'me' or 'team'" in res["message"], res @pytest.mark.p1 @pytest.mark.parametrize( "name, chunk_method", [ ("naive", "naive"), ("book", "book"), ("email", "email"), ("laws", "laws"), ("manual", "manual"), ("one", "one"), ("paper", "paper"), ("picture", "picture"), ("presentation", "presentation"), ("qa", "qa"), ("table", "table"), ("tag", "tag"), ], ids=["naive", "book", "email", "laws", "manual", "one", "paper", "picture", "presentation", "qa", "table", "tag"], ) def test_chunk_method(self, get_http_api_auth, name, chunk_method): payload = {"name": name, "chunk_method": chunk_method} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["chunk_method"] == chunk_method, res @pytest.mark.p2 @pytest.mark.parametrize( "name, chunk_method", [ ("empty", ""), ("unknown", "unknown"), ("type_error", list()), ], ids=["empty", "unknown", "type_error"], ) def test_chunk_method_invalid(self, get_http_api_auth, name, chunk_method): payload = {"name": name, "chunk_method": chunk_method} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "Input should be 'naive', 'book', 'email', 'laws', 'manual', 'one', 'paper', 'picture', 'presentation', 'qa', 'table' or 'tag'" in res["message"], res @pytest.mark.p2 def test_chunk_method_unset(self, get_http_api_auth): payload = {"name": "chunk_method_unset"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["chunk_method"] == "naive", res @pytest.mark.p3 def test_chunk_method_none(self, get_http_api_auth): payload = {"name": "chunk_method_none", "chunk_method": None} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "Input should be 'naive', 'book', 'email', 'laws', 'manual', 'one', 'paper', 'picture', 'presentation', 'qa', 'table' or 'tag'" in res["message"], res @pytest.mark.p2 @pytest.mark.parametrize( "name, pagerank", [ ("pagerank_min", 0), ("pagerank_mid", 50), ("pagerank_max", 100), ], ids=["min", "mid", "max"], ) def test_pagerank(self, get_http_api_auth, name, pagerank): payload = {"name": name, "pagerank": pagerank} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["pagerank"] == pagerank, res @pytest.mark.p3 @pytest.mark.parametrize( "name, pagerank, expected_message", [ ("pagerank_min_limit", -1, "Input should be greater than or equal to 0"), ("pagerank_max_limit", 101, "Input should be less than or equal to 100"), ], ids=["min_limit", "max_limit"], ) def test_pagerank_invalid(self, get_http_api_auth, name, pagerank, expected_message): payload = {"name": name, "pagerank": pagerank} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p3 def test_pagerank_unset(self, get_http_api_auth): payload = {"name": "pagerank_unset"} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res assert res["data"]["pagerank"] == 0, res @pytest.mark.p3 def test_pagerank_none(self, get_http_api_auth): payload = {"name": "pagerank_unset", "pagerank": None} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 101, res assert "Input should be a valid integer" in res["message"], res @pytest.mark.p1 @pytest.mark.parametrize( "name, parser_config", [ ("auto_keywords_min", {"auto_keywords": 0}), ("auto_keywords_mid", {"auto_keywords": 16}), ("auto_keywords_max", {"auto_keywords": 32}), ("auto_questions_min", {"auto_questions": 0}), ("auto_questions_mid", {"auto_questions": 5}), ("auto_questions_max", {"auto_questions": 10}), ("chunk_token_num_min", {"chunk_token_num": 1}), ("chunk_token_num_mid", {"chunk_token_num": 1024}), ("chunk_token_num_max", {"chunk_token_num": 2048}), ("delimiter", {"delimiter": "\n"}), ("delimiter_space", {"delimiter": " "}), ("html4excel_true", {"html4excel": True}), ("html4excel_false", {"html4excel": False}), ("layout_recognize_DeepDOC", {"layout_recognize": "DeepDOC"}), ("layout_recognize_navie", {"layout_recognize": "Plain Text"}), ("tag_kb_ids", {"tag_kb_ids": ["1", "2"]}), ("topn_tags_min", {"topn_tags": 1}), ("topn_tags_mid", {"topn_tags": 5}), ("topn_tags_max", {"topn_tags": 10}), ("filename_embd_weight_min", {"filename_embd_weight": 0.1}), ("filename_embd_weight_mid", {"filename_embd_weight": 0.5}), ("filename_embd_weight_max", {"filename_embd_weight": 1.0}), ("task_page_size_min", {"task_page_size": 1}), ("task_page_size_None", {"task_page_size": None}), ("pages", {"pages": [[1, 100]]}), ("pages_none", {"pages": None}), ("graphrag_true", {"graphrag": {"use_graphrag": True}}), ("graphrag_false", {"graphrag": {"use_graphrag": False}}), ("graphrag_entity_types", {"graphrag": {"entity_types": ["age", "sex", "height", "weight"]}}), ("graphrag_method_general", {"graphrag": {"method": "general"}}), ("graphrag_method_light", {"graphrag": {"method": "light"}}), ("graphrag_community_true", {"graphrag": {"community": True}}), ("graphrag_community_false", {"graphrag": {"community": False}}), ("graphrag_resolution_true", {"graphrag": {"resolution": True}}), ("graphrag_resolution_false", {"graphrag": {"resolution": False}}), ("raptor_true", {"raptor": {"use_raptor": True}}), ("raptor_false", {"raptor": {"use_raptor": False}}), ("raptor_prompt", {"raptor": {"prompt": "Who are you?"}}), ("raptor_max_token_min", {"raptor": {"max_token": 1}}), ("raptor_max_token_mid", {"raptor": {"max_token": 1024}}), ("raptor_max_token_max", {"raptor": {"max_token": 2048}}), ("raptor_threshold_min", {"raptor": {"threshold": 0.0}}), ("raptor_threshold_mid", {"raptor": {"threshold": 0.5}}), ("raptor_threshold_max", {"raptor": {"threshold": 1.0}}), ("raptor_max_cluster_min", {"raptor": {"max_cluster": 1}}), ("raptor_max_cluster_mid", {"raptor": {"max_cluster": 512}}), ("raptor_max_cluster_max", {"raptor": {"max_cluster": 1024}}), ("raptor_random_seed_min", {"raptor": {"random_seed": 0}}), ], ids=[ "auto_keywords_min", "auto_keywords_mid", "auto_keywords_max", "auto_questions_min", "auto_questions_mid", "auto_questions_max", "chunk_token_num_min", "chunk_token_num_mid", "chunk_token_num_max", "delimiter", "delimiter_space", "html4excel_true", "html4excel_false", "layout_recognize_DeepDOC", "layout_recognize_navie", "tag_kb_ids", "topn_tags_min", "topn_tags_mid", "topn_tags_max", "filename_embd_weight_min", "filename_embd_weight_mid", "filename_embd_weight_max", "task_page_size_min", "task_page_size_None", "pages", "pages_none", "graphrag_true", "graphrag_false", "graphrag_entity_types", "graphrag_method_general", "graphrag_method_light", "graphrag_community_true", "graphrag_community_false", "graphrag_resolution_true", "graphrag_resolution_false", "raptor_true", "raptor_false", "raptor_prompt", "raptor_max_token_min", "raptor_max_token_mid", "raptor_max_token_max", "raptor_threshold_min", "raptor_threshold_mid", "raptor_threshold_max", "raptor_max_cluster_min", "raptor_max_cluster_mid", "raptor_max_cluster_max", "raptor_random_seed_min", ], ) def test_parser_config(self, get_http_api_auth, name, parser_config): payload = {"name": name, "parser_config": parser_config} res = create_dataset(get_http_api_auth, payload) assert res["code"] == 0, res for k, v in parser_config.items(): if isinstance(v, dict): for kk, vv in v.items(): assert res["data"]["parser_config"][k][kk] == vv, res else: assert res["data"]["parser_config"][k] == v, res @pytest.mark.p2 @pytest.mark.parametrize( "name, parser_config, expected_message", [ ("auto_keywords_min_limit", {"auto_keywords": -1}, "Input should be greater than or equal to 0"), ("auto_keywords_max_limit", {"auto_keywords": 33}, "Input should be less than or equal to 32"), ("auto_keywords_float_not_allowed", {"auto_keywords": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ("auto_keywords_type_invalid", {"auto_keywords": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ("auto_questions_min_limit", {"auto_questions": -1}, "Input should be greater than or equal to 0"), ("auto_questions_max_limit", {"auto_questions": 11}, "Input should be less than or equal to 10"), ("auto_questions_float_not_allowed", {"auto_questions": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ("auto_questions_type_invalid", {"auto_questions": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ("chunk_token_num_min_limit", {"chunk_token_num": 0}, "Input should be greater than or equal to 1"), ("chunk_token_num_max_limit", {"chunk_token_num": 2049}, "Input should be less than or equal to 2048"), ("chunk_token_num_float_not_allowed", {"chunk_token_num": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ("chunk_token_num_type_invalid", {"chunk_token_num": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ("delimiter_empty", {"delimiter": ""}, "String should have at least 1 character"), ("html4excel_type_invalid", {"html4excel": "string"}, "Input should be a valid boolean, unable to interpret input"), ("tag_kb_ids_not_list", {"tag_kb_ids": "1,2"}, "Input should be a valid list"), ("tag_kb_ids_int_in_list", {"tag_kb_ids": [1, 2]}, "Input should be a valid string"), ("topn_tags_min_limit", {"topn_tags": 0}, "Input should be greater than or equal to 1"), ("topn_tags_max_limit", {"topn_tags": 11}, "Input should be less than or equal to 10"), ("topn_tags_float_not_allowed", {"topn_tags": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ("topn_tags_type_invalid", {"topn_tags": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ("filename_embd_weight_min_limit", {"filename_embd_weight": -1}, "Input should be greater than or equal to 0"), ("filename_embd_weight_max_limit", {"filename_embd_weight": 1.1}, "Input should be less than or equal to 1"), ("filename_embd_weight_type_invalid", {"filename_embd_weight": "string"}, "Input should be a valid number, unable to parse string as a number"), ("task_page_size_min_limit", {"task_page_size": 0}, "Input should be greater than or equal to 1"), ("task_page_size_float_not_allowed", {"task_page_size": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ("task_page_size_type_invalid", {"task_page_size": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ("pages_not_list", {"pages": "1,2"}, "Input should be a valid list"), ("pages_not_list_in_list", {"pages": ["1,2"]}, "Input should be a valid list"), ("pages_not_int_list", {"pages": [["string1", "string2"]]}, "Input should be a valid integer, unable to parse string as an integer"), ("graphrag_type_invalid", {"graphrag": {"use_graphrag": "string"}}, "Input should be a valid boolean, unable to interpret input"), ("graphrag_entity_types_not_list", {"graphrag": {"entity_types": "1,2"}}, "Input should be a valid list"), ("graphrag_entity_types_not_str_in_list", {"graphrag": {"entity_types": [1, 2]}}, "nput should be a valid string"), ("graphrag_method_unknown", {"graphrag": {"method": "unknown"}}, "Input should be 'light' or 'general'"), ("graphrag_method_none", {"graphrag": {"method": None}}, "Input should be 'light' or 'general'"), ("graphrag_community_type_invalid", {"graphrag": {"community": "string"}}, "Input should be a valid boolean, unable to interpret input"), ("graphrag_resolution_type_invalid", {"graphrag": {"resolution": "string"}}, "Input should be a valid boolean, unable to interpret input"), ("raptor_type_invalid", {"raptor": {"use_raptor": "string"}}, "Input should be a valid boolean, unable to interpret input"), ("raptor_prompt_empty", {"raptor": {"prompt": ""}}, "String should have at least 1 character"), ("raptor_prompt_space", {"raptor": {"prompt": " "}}, "String should have at least 1 character"), ("raptor_max_token_min_limit", {"raptor": {"max_token": 0}}, "Input should be greater than or equal to 1"), ("raptor_max_token_max_limit", {"raptor": {"max_token": 2049}}, "Input should be less than or equal to 2048"), ("raptor_max_token_float_not_allowed", {"raptor": {"max_token": 3.14}}, "Input should be a valid integer, got a number with a fractional part"), ("raptor_max_token_type_invalid", {"raptor": {"max_token": "string"}}, "Input should be a valid integer, unable to parse string as an integer"), ("raptor_threshold_min_limit", {"raptor": {"threshold": -0.1}}, "Input should be greater than or equal to 0"), ("raptor_threshold_max_limit", {"raptor": {"threshold": 1.1}}, "Input should be less than or equal to 1"), ("raptor_threshold_type_invalid", {"raptor": {"threshold": "string"}}, "Input should be a valid number, unable to parse string as a number"), ("raptor_max_cluster_min_limit", {"raptor": {"max_cluster": 0}}, "Input should be greater than or equal to 1"), ("raptor_max_cluster_max_limit", {"raptor": {"max_cluster": 1025}}, "Input should be less than or equal to 1024"), ("raptor_max_cluster_float_not_allowed", {"raptor": {"max_cluster": 3.14}}, "Input should be a valid integer, got a number with a fractional par"), ("raptor_max_cluster_type_invalid", {"raptor": {"max_cluster": "string"}}, "Input should be a valid integer, unable to parse string as an integer"), ("raptor_random_seed_min_limit", {"raptor": {"random_seed": -1}}, "Input should be greater than or equal to 0"), ("raptor_random_seed_float_not_allowed", {"raptor": {"random_seed": 3.14}}, "Input should be a valid integer, got a number with a fractional part"), ("raptor_random_seed_type_invalid", {"raptor": {"random_seed": "string"}}, "Input should be a valid integer, unable to parse string as an integer"), ("parser_config_type_invalid", {"delimiter": "a" * 65536}, "Parser config exceeds size limit (max 65,535 characters)"), ], ids=[ "auto_keywords_min_limit", "auto_keywords_max_limit", "auto_keywords_float_not_allowed", "auto_keywords_type_invalid", "auto_questions_min_limit", "auto_questions_max_limit", "auto_questions_float_not_allowed", "auto_questions_type_invalid", "chunk_token_num_min_limit", "chunk_token_num_max_limit", "chunk_token_num_float_not_allowed", "chunk_token_num_type_invalid", "delimiter_empty", "html4excel_type_invalid", "tag_kb_ids_not_list", "tag_kb_ids_int_in_list", "topn_tags_min_limit", "topn_tags_max_limit", "topn_tags_float_not_allowed", "topn_tags_type_invalid", "filename_embd_weight_min_limit", "filename_embd_weight_max_limit", "filename_embd_weight_type_invalid", "task_page_size_min_limit", "task_page_size_float_not_allowed", "task_page_size_type_invalid", "pages_not_list", "pages_not_list_in_list", "pages_not_int_list", "graphrag_type_invalid", "graphrag_entity_types_not_list", "graphrag_entity_types_not_str_in_list", "graphrag_method_unknown", "graphrag_method_none", "graphrag_community_type_invalid", "graphrag_resolution_type_invalid", "raptor_type_invalid", "raptor_prompt_empty", "raptor_prompt_space", "raptor_max_token_min_limit", "raptor_max_token_max_limit", "raptor_max_token_float_not_allowed", "raptor_max_token_type_invalid", "raptor_threshold_min_limit", "raptor_threshold_max_limit", "raptor_threshold_type_invalid", "raptor_max_cluster_min_limit", "raptor_max_cluster_max_limit", "raptor_max_cluster_float_not_allowed", "raptor_max_cluster_type_invalid", "raptor_random_seed_min_limit",
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_dataset_mangement/conftest.py
sdk/python/test/test_http_api/test_dataset_mangement/conftest.py
# # 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 pytest from common import batch_create_datasets, delete_datasets @pytest.fixture(scope="class") def add_datasets(get_http_api_auth, request): def cleanup(): delete_datasets(get_http_api_auth, {"ids": None}) request.addfinalizer(cleanup) return batch_create_datasets(get_http_api_auth, 5) @pytest.fixture(scope="function") def add_datasets_func(get_http_api_auth, request): def cleanup(): delete_datasets(get_http_api_auth, {"ids": None}) request.addfinalizer(cleanup) return batch_create_datasets(get_http_api_auth, 3)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_dataset_mangement/test_update_dataset.py
sdk/python/test/test_http_api/test_dataset_mangement/test_update_dataset.py
# # 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 uuid from concurrent.futures import ThreadPoolExecutor import pytest from common import DATASET_NAME_LIMIT, INVALID_API_TOKEN, list_datasets, update_dataset from hypothesis import HealthCheck, example, given, settings from libs.auth import RAGFlowHttpApiAuth from libs.utils import encode_avatar from libs.utils.file_utils import create_image_file from libs.utils.hypothesis_utils import valid_names # TODO: Missing scenario for updating embedding_model with chunk_count != 0 class TestAuthorization: @pytest.mark.p1 @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ids=["empty_auth", "invalid_api_token"], ) def test_auth_invalid(self, auth, expected_code, expected_message): res = update_dataset(auth, "dataset_id") assert res["code"] == expected_code, res assert res["message"] == expected_message, res class TestRquest: @pytest.mark.p3 def test_bad_content_type(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func BAD_CONTENT_TYPE = "text/xml" res = update_dataset(get_http_api_auth, dataset_id, {"name": "bad_content_type"}, headers={"Content-Type": BAD_CONTENT_TYPE}) assert res["code"] == 101, res assert res["message"] == f"Unsupported content type: Expected application/json, got {BAD_CONTENT_TYPE}", res @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_message", [ ("a", "Malformed JSON syntax: Missing commas/brackets or invalid encoding"), ('"a"', "Invalid request payload: expected object, got str"), ], ids=["malformed_json_syntax", "invalid_request_payload_type"], ) def test_payload_bad(self, get_http_api_auth, add_dataset_func, payload, expected_message): dataset_id = add_dataset_func res = update_dataset(get_http_api_auth, dataset_id, data=payload) assert res["code"] == 101, res assert res["message"] == expected_message, res @pytest.mark.p2 def test_payload_empty(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func res = update_dataset(get_http_api_auth, dataset_id, {}) assert res["code"] == 101, res assert res["message"] == "No properties were modified", res @pytest.mark.p3 def test_payload_unset(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func res = update_dataset(get_http_api_auth, dataset_id, None) assert res["code"] == 101, res assert res["message"] == "Malformed JSON syntax: Missing commas/brackets or invalid encoding", res class TestCapability: @pytest.mark.p3 def test_update_dateset_concurrent(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(update_dataset, get_http_api_auth, dataset_id, {"name": f"dataset_{i}"}) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses), responses class TestDatasetUpdate: @pytest.mark.p3 def test_dataset_id_not_uuid(self, get_http_api_auth): payload = {"name": "not uuid"} res = update_dataset(get_http_api_auth, "not_uuid", payload) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res @pytest.mark.p3 def test_dataset_id_not_uuid1(self, get_http_api_auth): payload = {"name": "not uuid1"} res = update_dataset(get_http_api_auth, uuid.uuid4().hex, payload) assert res["code"] == 101, res assert "Invalid UUID1 format" in res["message"], res @pytest.mark.p3 def test_dataset_id_wrong_uuid(self, get_http_api_auth): payload = {"name": "wrong uuid"} res = update_dataset(get_http_api_auth, "d94a8dc02c9711f0930f7fbc369eab6d", payload) assert res["code"] == 108, res assert "lacks permission for dataset" in res["message"], res @pytest.mark.p1 @given(name=valid_names()) @example("a" * 128) @settings(max_examples=20, suppress_health_check=[HealthCheck.function_scoped_fixture]) def test_name(self, get_http_api_auth, add_dataset_func, name): dataset_id = add_dataset_func payload = {"name": name} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["name"] == name, res @pytest.mark.p2 @pytest.mark.parametrize( "name, expected_message", [ ("", "String should have at least 1 character"), (" ", "String should have at least 1 character"), ("a" * (DATASET_NAME_LIMIT + 1), "String should have at most 128 characters"), (0, "Input should be a valid string"), (None, "Input should be a valid string"), ], ids=["empty_name", "space_name", "too_long_name", "invalid_name", "None_name"], ) def test_name_invalid(self, get_http_api_auth, add_dataset_func, name, expected_message): dataset_id = add_dataset_func payload = {"name": name} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p3 def test_name_duplicated(self, get_http_api_auth, add_datasets_func): dataset_ids = add_datasets_func[0] name = "dataset_1" payload = {"name": name} res = update_dataset(get_http_api_auth, dataset_ids, payload) assert res["code"] == 102, res assert res["message"] == f"Dataset name '{name}' already exists", res @pytest.mark.p3 def test_name_case_insensitive(self, get_http_api_auth, add_datasets_func): dataset_id = add_datasets_func[0] name = "DATASET_1" payload = {"name": name} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 102, res assert res["message"] == f"Dataset name '{name}' already exists", res @pytest.mark.p2 def test_avatar(self, get_http_api_auth, add_dataset_func, tmp_path): dataset_id = add_dataset_func fn = create_image_file(tmp_path / "ragflow_test.png") payload = { "avatar": f"data:image/png;base64,{encode_avatar(fn)}", } res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["avatar"] == f"data:image/png;base64,{encode_avatar(fn)}", res @pytest.mark.p2 def test_avatar_exceeds_limit_length(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"avatar": "a" * 65536} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "String should have at most 65535 characters" in res["message"], res @pytest.mark.p3 @pytest.mark.parametrize( "avatar_prefix, expected_message", [ ("", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"), ("data:image/png;base64", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>"), ("invalid_mine_prefix:image/png;base64,", "Invalid MIME prefix format. Must start with 'data:'"), ("data:unsupported_mine_type;base64,", "Unsupported MIME type. Allowed: ['image/jpeg', 'image/png']"), ], ids=["empty_prefix", "missing_comma", "unsupported_mine_type", "invalid_mine_type"], ) def test_avatar_invalid_prefix(self, get_http_api_auth, add_dataset_func, tmp_path, avatar_prefix, expected_message): dataset_id = add_dataset_func fn = create_image_file(tmp_path / "ragflow_test.png") payload = {"avatar": f"{avatar_prefix}{encode_avatar(fn)}"} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p3 def test_avatar_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"avatar": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["avatar"] is None, res @pytest.mark.p2 def test_description(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"description": "description"} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0 res = list_datasets(get_http_api_auth, {"id": dataset_id}) assert res["code"] == 0, res assert res["data"][0]["description"] == "description" @pytest.mark.p2 def test_description_exceeds_limit_length(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"description": "a" * 65536} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "String should have at most 65535 characters" in res["message"], res @pytest.mark.p3 def test_description_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"description": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth, {"id": dataset_id}) assert res["code"] == 0, res assert res["data"][0]["description"] is None @pytest.mark.p1 @pytest.mark.parametrize( "embedding_model", [ "BAAI/bge-small-en-v1.5@Builtin", "embedding-3@ZHIPU-AI", ], ids=["builtin_baai", "tenant_zhipu"], ) def test_embedding_model(self, get_http_api_auth, add_dataset_func, embedding_model): dataset_id = add_dataset_func payload = {"embedding_model": embedding_model} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["embedding_model"] == embedding_model, res @pytest.mark.p2 @pytest.mark.parametrize( "name, embedding_model", [ ("unknown_llm_name", "unknown@ZHIPU-AI"), ("unknown_llm_factory", "embedding-3@unknown"), ("tenant_no_auth_default_tenant_llm", "text-embedding-v3@Tongyi-Qianwen"), ("tenant_no_auth", "text-embedding-3-small@OpenAI"), ], ids=["unknown_llm_name", "unknown_llm_factory", "tenant_no_auth_default_tenant_llm", "tenant_no_auth"], ) def test_embedding_model_invalid(self, get_http_api_auth, add_dataset_func, name, embedding_model): dataset_id = add_dataset_func payload = {"name": name, "embedding_model": embedding_model} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res if "tenant_no_auth" in name: assert res["message"] == f"Unauthorized model: <{embedding_model}>", res else: assert res["message"] == f"Unsupported model: <{embedding_model}>", res @pytest.mark.p2 @pytest.mark.parametrize( "name, embedding_model", [ ("missing_at", "BAAI/bge-small-en-v1.5Builtin"), ("missing_model_name", "@Builtin"), ("missing_provider", "BAAI/bge-small-en-v1.5@"), ("whitespace_only_model_name", " @Builtin"), ("whitespace_only_provider", "BAAI/bge-small-en-v1.5@ "), ], ids=["missing_at", "empty_model_name", "empty_provider", "whitespace_only_model_name", "whitespace_only_provider"], ) def test_embedding_model_format(self, get_http_api_auth, add_dataset_func, name, embedding_model): dataset_id = add_dataset_func payload = {"name": name, "embedding_model": embedding_model} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res if name == "missing_at": assert "Embedding model identifier must follow <model_name>@<provider> format" in res["message"], res else: assert "Both model_name and provider must be non-empty strings" in res["message"], res @pytest.mark.p2 def test_embedding_model_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"embedding_model": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "Input should be a valid string" in res["message"], res @pytest.mark.p1 @pytest.mark.parametrize( "permission", [ "me", "team", "ME", "TEAM", " ME ", ], ids=["me", "team", "me_upercase", "team_upercase", "whitespace"], ) def test_permission(self, get_http_api_auth, add_dataset_func, permission): dataset_id = add_dataset_func payload = {"permission": permission} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["permission"] == permission.lower().strip(), res @pytest.mark.p2 @pytest.mark.parametrize( "permission", [ "", "unknown", list(), ], ids=["empty", "unknown", "type_error"], ) def test_permission_invalid(self, get_http_api_auth, add_dataset_func, permission): dataset_id = add_dataset_func payload = {"permission": permission} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101 assert "Input should be 'me' or 'team'" in res["message"] @pytest.mark.p3 def test_permission_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"permission": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "Input should be 'me' or 'team'" in res["message"], res @pytest.mark.p1 @pytest.mark.parametrize( "chunk_method", [ "naive", "book", "email", "laws", "manual", "one", "paper", "picture", "presentation", "qa", "table", "tag", ], ids=["naive", "book", "email", "laws", "manual", "one", "paper", "picture", "presentation", "qa", "table", "tag"], ) def test_chunk_method(self, get_http_api_auth, add_dataset_func, chunk_method): dataset_id = add_dataset_func payload = {"chunk_method": chunk_method} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["chunk_method"] == chunk_method, res @pytest.mark.p2 @pytest.mark.parametrize( "chunk_method", [ "", "unknown", list(), ], ids=["empty", "unknown", "type_error"], ) def test_chunk_method_invalid(self, get_http_api_auth, add_dataset_func, chunk_method): dataset_id = add_dataset_func payload = {"chunk_method": chunk_method} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "Input should be 'naive', 'book', 'email', 'laws', 'manual', 'one', 'paper', 'picture', 'presentation', 'qa', 'table' or 'tag'" in res["message"], res @pytest.mark.p3 def test_chunk_method_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"chunk_method": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "Input should be 'naive', 'book', 'email', 'laws', 'manual', 'one', 'paper', 'picture', 'presentation', 'qa', 'table' or 'tag'" in res["message"], res @pytest.mark.p2 @pytest.mark.parametrize("pagerank", [0, 50, 100], ids=["min", "mid", "max"]) def test_pagerank(self, get_http_api_auth, add_dataset_func, pagerank): dataset_id = add_dataset_func payload = {"pagerank": pagerank} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0 res = list_datasets(get_http_api_auth, {"id": dataset_id}) assert res["code"] == 0, res assert res["data"][0]["pagerank"] == pagerank @pytest.mark.p2 @pytest.mark.parametrize( "pagerank, expected_message", [ (-1, "Input should be greater than or equal to 0"), (101, "Input should be less than or equal to 100"), ], ids=["min_limit", "max_limit"], ) def test_pagerank_invalid(self, get_http_api_auth, add_dataset_func, pagerank, expected_message): dataset_id = add_dataset_func payload = {"pagerank": pagerank} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p3 def test_pagerank_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"pagerank": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert "Input should be a valid integer" in res["message"], res @pytest.mark.p1 @pytest.mark.parametrize( "parser_config", [ {"auto_keywords": 0}, {"auto_keywords": 16}, {"auto_keywords": 32}, {"auto_questions": 0}, {"auto_questions": 5}, {"auto_questions": 10}, {"chunk_token_num": 1}, {"chunk_token_num": 1024}, {"chunk_token_num": 2048}, {"delimiter": "\n"}, {"delimiter": " "}, {"html4excel": True}, {"html4excel": False}, {"layout_recognize": "DeepDOC"}, {"layout_recognize": "Plain Text"}, {"tag_kb_ids": ["1", "2"]}, {"topn_tags": 1}, {"topn_tags": 5}, {"topn_tags": 10}, {"filename_embd_weight": 0.1}, {"filename_embd_weight": 0.5}, {"filename_embd_weight": 1.0}, {"task_page_size": 1}, {"task_page_size": None}, {"pages": [[1, 100]]}, {"pages": None}, {"graphrag": {"use_graphrag": True}}, {"graphrag": {"use_graphrag": False}}, {"graphrag": {"entity_types": ["age", "sex", "height", "weight"]}}, {"graphrag": {"method": "general"}}, {"graphrag": {"method": "light"}}, {"graphrag": {"community": True}}, {"graphrag": {"community": False}}, {"graphrag": {"resolution": True}}, {"graphrag": {"resolution": False}}, {"raptor": {"use_raptor": True}}, {"raptor": {"use_raptor": False}}, {"raptor": {"prompt": "Who are you?"}}, {"raptor": {"max_token": 1}}, {"raptor": {"max_token": 1024}}, {"raptor": {"max_token": 2048}}, {"raptor": {"threshold": 0.0}}, {"raptor": {"threshold": 0.5}}, {"raptor": {"threshold": 1.0}}, {"raptor": {"max_cluster": 1}}, {"raptor": {"max_cluster": 512}}, {"raptor": {"max_cluster": 1024}}, {"raptor": {"random_seed": 0}}, ], ids=[ "auto_keywords_min", "auto_keywords_mid", "auto_keywords_max", "auto_questions_min", "auto_questions_mid", "auto_questions_max", "chunk_token_num_min", "chunk_token_num_mid", "chunk_token_num_max", "delimiter", "delimiter_space", "html4excel_true", "html4excel_false", "layout_recognize_DeepDOC", "layout_recognize_navie", "tag_kb_ids", "topn_tags_min", "topn_tags_mid", "topn_tags_max", "filename_embd_weight_min", "filename_embd_weight_mid", "filename_embd_weight_max", "task_page_size_min", "task_page_size_None", "pages", "pages_none", "graphrag_true", "graphrag_false", "graphrag_entity_types", "graphrag_method_general", "graphrag_method_light", "graphrag_community_true", "graphrag_community_false", "graphrag_resolution_true", "graphrag_resolution_false", "raptor_true", "raptor_false", "raptor_prompt", "raptor_max_token_min", "raptor_max_token_mid", "raptor_max_token_max", "raptor_threshold_min", "raptor_threshold_mid", "raptor_threshold_max", "raptor_max_cluster_min", "raptor_max_cluster_mid", "raptor_max_cluster_max", "raptor_random_seed_min", ], ) def test_parser_config(self, get_http_api_auth, add_dataset_func, parser_config): dataset_id = add_dataset_func payload = {"parser_config": parser_config} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res for k, v in parser_config.items(): if isinstance(v, dict): for kk, vv in v.items(): assert res["data"][0]["parser_config"][k][kk] == vv, res else: assert res["data"][0]["parser_config"][k] == v, res @pytest.mark.p2 @pytest.mark.parametrize( "parser_config, expected_message", [ ({"auto_keywords": -1}, "Input should be greater than or equal to 0"), ({"auto_keywords": 33}, "Input should be less than or equal to 32"), ({"auto_keywords": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ({"auto_keywords": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ({"auto_questions": -1}, "Input should be greater than or equal to 0"), ({"auto_questions": 11}, "Input should be less than or equal to 10"), ({"auto_questions": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ({"auto_questions": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ({"chunk_token_num": 0}, "Input should be greater than or equal to 1"), ({"chunk_token_num": 2049}, "Input should be less than or equal to 2048"), ({"chunk_token_num": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ({"chunk_token_num": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ({"delimiter": ""}, "String should have at least 1 character"), ({"html4excel": "string"}, "Input should be a valid boolean, unable to interpret input"), ({"tag_kb_ids": "1,2"}, "Input should be a valid list"), ({"tag_kb_ids": [1, 2]}, "Input should be a valid string"), ({"topn_tags": 0}, "Input should be greater than or equal to 1"), ({"topn_tags": 11}, "Input should be less than or equal to 10"), ({"topn_tags": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ({"topn_tags": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ({"filename_embd_weight": -1}, "Input should be greater than or equal to 0"), ({"filename_embd_weight": 1.1}, "Input should be less than or equal to 1"), ({"filename_embd_weight": "string"}, "Input should be a valid number, unable to parse string as a number"), ({"task_page_size": 0}, "Input should be greater than or equal to 1"), ({"task_page_size": 3.14}, "Input should be a valid integer, got a number with a fractional part"), ({"task_page_size": "string"}, "Input should be a valid integer, unable to parse string as an integer"), ({"pages": "1,2"}, "Input should be a valid list"), ({"pages": ["1,2"]}, "Input should be a valid list"), ({"pages": [["string1", "string2"]]}, "Input should be a valid integer, unable to parse string as an integer"), ({"graphrag": {"use_graphrag": "string"}}, "Input should be a valid boolean, unable to interpret input"), ({"graphrag": {"entity_types": "1,2"}}, "Input should be a valid list"), ({"graphrag": {"entity_types": [1, 2]}}, "nput should be a valid string"), ({"graphrag": {"method": "unknown"}}, "Input should be 'light' or 'general'"), ({"graphrag": {"method": None}}, "Input should be 'light' or 'general'"), ({"graphrag": {"community": "string"}}, "Input should be a valid boolean, unable to interpret input"), ({"graphrag": {"resolution": "string"}}, "Input should be a valid boolean, unable to interpret input"), ({"raptor": {"use_raptor": "string"}}, "Input should be a valid boolean, unable to interpret input"), ({"raptor": {"prompt": ""}}, "String should have at least 1 character"), ({"raptor": {"prompt": " "}}, "String should have at least 1 character"), ({"raptor": {"max_token": 0}}, "Input should be greater than or equal to 1"), ({"raptor": {"max_token": 2049}}, "Input should be less than or equal to 2048"), ({"raptor": {"max_token": 3.14}}, "Input should be a valid integer, got a number with a fractional part"), ({"raptor": {"max_token": "string"}}, "Input should be a valid integer, unable to parse string as an integer"), ({"raptor": {"threshold": -0.1}}, "Input should be greater than or equal to 0"), ({"raptor": {"threshold": 1.1}}, "Input should be less than or equal to 1"), ({"raptor": {"threshold": "string"}}, "Input should be a valid number, unable to parse string as a number"), ({"raptor": {"max_cluster": 0}}, "Input should be greater than or equal to 1"), ({"raptor": {"max_cluster": 1025}}, "Input should be less than or equal to 1024"), ({"raptor": {"max_cluster": 3.14}}, "Input should be a valid integer, got a number with a fractional par"), ({"raptor": {"max_cluster": "string"}}, "Input should be a valid integer, unable to parse string as an integer"), ({"raptor": {"random_seed": -1}}, "Input should be greater than or equal to 0"), ({"raptor": {"random_seed": 3.14}}, "Input should be a valid integer, got a number with a fractional part"), ({"raptor": {"random_seed": "string"}}, "Input should be a valid integer, unable to parse string as an integer"), ({"delimiter": "a" * 65536}, "Parser config exceeds size limit (max 65,535 characters)"), ], ids=[ "auto_keywords_min_limit", "auto_keywords_max_limit", "auto_keywords_float_not_allowed", "auto_keywords_type_invalid", "auto_questions_min_limit", "auto_questions_max_limit", "auto_questions_float_not_allowed", "auto_questions_type_invalid", "chunk_token_num_min_limit", "chunk_token_num_max_limit", "chunk_token_num_float_not_allowed", "chunk_token_num_type_invalid", "delimiter_empty", "html4excel_type_invalid", "tag_kb_ids_not_list", "tag_kb_ids_int_in_list", "topn_tags_min_limit", "topn_tags_max_limit", "topn_tags_float_not_allowed", "topn_tags_type_invalid", "filename_embd_weight_min_limit", "filename_embd_weight_max_limit", "filename_embd_weight_type_invalid", "task_page_size_min_limit", "task_page_size_float_not_allowed", "task_page_size_type_invalid", "pages_not_list", "pages_not_list_in_list", "pages_not_int_list", "graphrag_type_invalid", "graphrag_entity_types_not_list", "graphrag_entity_types_not_str_in_list", "graphrag_method_unknown", "graphrag_method_none", "graphrag_community_type_invalid", "graphrag_resolution_type_invalid", "raptor_type_invalid", "raptor_prompt_empty", "raptor_prompt_space", "raptor_max_token_min_limit", "raptor_max_token_max_limit", "raptor_max_token_float_not_allowed", "raptor_max_token_type_invalid", "raptor_threshold_min_limit", "raptor_threshold_max_limit", "raptor_threshold_type_invalid", "raptor_max_cluster_min_limit", "raptor_max_cluster_max_limit", "raptor_max_cluster_float_not_allowed", "raptor_max_cluster_type_invalid", "raptor_random_seed_min_limit", "raptor_random_seed_float_not_allowed", "raptor_random_seed_type_invalid", "parser_config_type_invalid", ], ) def test_parser_config_invalid(self, get_http_api_auth, add_dataset_func, parser_config, expected_message): dataset_id = add_dataset_func payload = {"parser_config": parser_config} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 101, res assert expected_message in res["message"], res @pytest.mark.p2 def test_parser_config_empty(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"parser_config": {}} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth) assert res["code"] == 0, res assert res["data"][0]["parser_config"] == { "chunk_token_num": 128, "delimiter": r"\n", "html4excel": False, "layout_recognize": "DeepDOC", "raptor": {"use_raptor": False}, }, res @pytest.mark.p3 def test_parser_config_none(self, get_http_api_auth, add_dataset_func): dataset_id = add_dataset_func payload = {"parser_config": None} res = update_dataset(get_http_api_auth, dataset_id, payload) assert res["code"] == 0, res res = list_datasets(get_http_api_auth, {"id": dataset_id}) assert res["code"] == 0, res assert res["data"][0]["parser_config"] == { "chunk_token_num": 128,
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py
sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, add_chunk, delete_documnets, list_chunks from libs.auth import RAGFlowHttpApiAuth def validate_chunk_details(dataset_id, document_id, payload, res): chunk = res["data"]["chunk"] assert chunk["dataset_id"] == dataset_id assert chunk["document_id"] == document_id assert chunk["content"] == payload["content"] if "important_keywords" in payload: assert chunk["important_keywords"] == payload["important_keywords"] if "questions" in payload: assert chunk["questions"] == [str(q).strip() for q in payload.get("questions", []) if str(q).strip()] @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = add_chunk(auth, "dataset_id", "document_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestAddChunk: @pytest.mark.p1 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"content": None}, 100, """TypeError("unsupported operand type(s) for +: \'NoneType\' and \'str\'")"""), ({"content": ""}, 102, "`content` is required"), pytest.param( {"content": 1}, 100, """TypeError("unsupported operand type(s) for +: \'int\' and \'str\'")""", marks=pytest.mark.skip, ), ({"content": "a"}, 0, ""), ({"content": " "}, 102, "`content` is required"), ({"content": "\n!?ใ€‚๏ผ›๏ผ๏ผŸ\"'"}, 0, ""), ], ) def test_content(self, get_http_api_auth, add_document, payload, expected_code, expected_message): dataset_id, document_id = add_document res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res chunks_count = res["data"]["doc"]["chunk_count"] res = add_chunk(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == expected_code if expected_code == 0: validate_chunk_details(dataset_id, document_id, payload, res) res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert res["data"]["doc"]["chunk_count"] == chunks_count + 1 else: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"content": "chunk test", "important_keywords": ["a", "b", "c"]}, 0, ""), ({"content": "chunk test", "important_keywords": [""]}, 0, ""), ( {"content": "chunk test", "important_keywords": [1]}, 100, "TypeError('sequence item 0: expected str instance, int found')", ), ({"content": "chunk test", "important_keywords": ["a", "a"]}, 0, ""), ({"content": "chunk test", "important_keywords": "abc"}, 102, "`important_keywords` is required to be a list"), ({"content": "chunk test", "important_keywords": 123}, 102, "`important_keywords` is required to be a list"), ], ) def test_important_keywords(self, get_http_api_auth, add_document, payload, expected_code, expected_message): dataset_id, document_id = add_document res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res chunks_count = res["data"]["doc"]["chunk_count"] res = add_chunk(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == expected_code if expected_code == 0: validate_chunk_details(dataset_id, document_id, payload, res) res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert res["data"]["doc"]["chunk_count"] == chunks_count + 1 else: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"content": "chunk test", "questions": ["a", "b", "c"]}, 0, ""), ({"content": "chunk test", "questions": [""]}, 0, ""), ({"content": "chunk test", "questions": [1]}, 100, "TypeError('sequence item 0: expected str instance, int found')"), ({"content": "chunk test", "questions": ["a", "a"]}, 0, ""), ({"content": "chunk test", "questions": "abc"}, 102, "`questions` is required to be a list"), ({"content": "chunk test", "questions": 123}, 102, "`questions` is required to be a list"), ], ) def test_questions(self, get_http_api_auth, add_document, payload, expected_code, expected_message): dataset_id, document_id = add_document res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res chunks_count = res["data"]["doc"]["chunk_count"] res = add_chunk(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == expected_code if expected_code == 0: validate_chunk_details(dataset_id, document_id, payload, res) if res["code"] != 0: assert False, res res = list_chunks(get_http_api_auth, dataset_id, document_id) assert res["data"]["doc"]["chunk_count"] == chunks_count + 1 else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "dataset_id, expected_code, expected_message", [ ("", 100, "<NotFound '404: Not Found'>"), ( "invalid_dataset_id", 102, "You don't own the dataset invalid_dataset_id.", ), ], ) def test_invalid_dataset_id( self, get_http_api_auth, add_document, dataset_id, expected_code, expected_message, ): _, document_id = add_document res = add_chunk(get_http_api_auth, dataset_id, document_id, {"content": "a"}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "document_id, expected_code, expected_message", [ ("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"), ( "invalid_document_id", 102, "You don't own the document invalid_document_id.", ), ], ) def test_invalid_document_id(self, get_http_api_auth, add_document, document_id, expected_code, expected_message): dataset_id, _ = add_document res = add_chunk(get_http_api_auth, dataset_id, document_id, {"content": "chunk test"}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 def test_repeated_add_chunk(self, get_http_api_auth, add_document): payload = {"content": "chunk test"} dataset_id, document_id = add_document res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res chunks_count = res["data"]["doc"]["chunk_count"] res = add_chunk(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == 0 validate_chunk_details(dataset_id, document_id, payload, res) res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert res["data"]["doc"]["chunk_count"] == chunks_count + 1 res = add_chunk(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == 0 validate_chunk_details(dataset_id, document_id, payload, res) res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert res["data"]["doc"]["chunk_count"] == chunks_count + 2 @pytest.mark.p2 def test_add_chunk_to_deleted_document(self, get_http_api_auth, add_document): dataset_id, document_id = add_document delete_documnets(get_http_api_auth, dataset_id, {"ids": [document_id]}) res = add_chunk(get_http_api_auth, dataset_id, document_id, {"content": "chunk test"}) assert res["code"] == 102 assert res["message"] == f"You don't own the document {document_id}." @pytest.mark.skip(reason="issues/6411") def test_concurrent_add_chunk(self, get_http_api_auth, add_document): chunk_num = 50 dataset_id, document_id = add_document res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res chunks_count = res["data"]["doc"]["chunk_count"] with ThreadPoolExecutor(max_workers=5) as executor: futures = [ executor.submit( add_chunk, get_http_api_auth, dataset_id, document_id, {"content": f"chunk test {i}"}, ) for i in range(chunk_num) ] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert res["data"]["doc"]["chunk_count"] == chunks_count + chunk_num
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_retrieval_chunks.py
sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_retrieval_chunks.py
# # 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 pytest from common import ( INVALID_API_TOKEN, retrieval_chunks, ) from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = retrieval_chunks(auth) assert res["code"] == expected_code assert res["message"] == expected_message class TestChunksRetrieval: @pytest.mark.p1 @pytest.mark.parametrize( "payload, expected_code, expected_page_size, expected_message", [ ({"question": "chunk", "dataset_ids": None}, 0, 4, ""), ({"question": "chunk", "document_ids": None}, 102, 0, "`dataset_ids` is required."), ({"question": "chunk", "dataset_ids": None, "document_ids": None}, 0, 4, ""), ({"question": "chunk"}, 102, 0, "`dataset_ids` is required."), ], ) def test_basic_scenarios(self, get_http_api_auth, add_chunks, payload, expected_code, expected_page_size, expected_message): dataset_id, document_id, _ = add_chunks if "dataset_ids" in payload: payload["dataset_ids"] = [dataset_id] if "document_ids" in payload: payload["document_ids"] = [document_id] res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_page_size, expected_message", [ pytest.param( {"page": None, "page_size": 2}, 100, 2, """TypeError("int() argument must be a string, a bytes-like object or a real number, not \'NoneType\'")""", marks=pytest.mark.skip, ), pytest.param( {"page": 0, "page_size": 2}, 100, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip, ), pytest.param({"page": 2, "page_size": 2}, 0, 2, "", marks=pytest.mark.skip(reason="issues/6646")), ({"page": 3, "page_size": 2}, 0, 0, ""), ({"page": "3", "page_size": 2}, 0, 0, ""), pytest.param( {"page": -1, "page_size": 2}, 100, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip, ), pytest.param( {"page": "a", "page_size": 2}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip, ), ], ) def test_page(self, get_http_api_auth, add_chunks, payload, expected_code, expected_page_size, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_code, expected_page_size, expected_message", [ pytest.param( {"page_size": None}, 100, 0, """TypeError("int() argument must be a string, a bytes-like object or a real number, not \'NoneType\'")""", marks=pytest.mark.skip, ), # ({"page_size": 0}, 0, 0, ""), ({"page_size": 1}, 0, 1, ""), ({"page_size": 5}, 0, 4, ""), ({"page_size": "1"}, 0, 1, ""), # ({"page_size": -1}, 0, 0, ""), pytest.param( {"page_size": "a"}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip, ), ], ) def test_page_size(self, get_http_api_auth, add_chunks, payload, expected_code, expected_page_size, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_code, expected_page_size, expected_message", [ ({"vector_similarity_weight": 0}, 0, 4, ""), ({"vector_similarity_weight": 0.5}, 0, 4, ""), ({"vector_similarity_weight": 10}, 0, 4, ""), pytest.param( {"vector_similarity_weight": "a"}, 100, 0, """ValueError("could not convert string to float: \'a\'")""", marks=pytest.mark.skip, ), ], ) def test_vector_similarity_weight(self, get_http_api_auth, add_chunks, payload, expected_code, expected_page_size, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_page_size, expected_message", [ ({"top_k": 10}, 0, 4, ""), pytest.param( {"top_k": 1}, 0, 4, "", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") in ["infinity", "opensearch"], reason="Infinity"), ), pytest.param( {"top_k": 1}, 0, 1, "", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") in [None, "opensearch", "elasticsearch"], reason="elasticsearch"), ), pytest.param( {"top_k": -1}, 100, 4, "must be greater than 0", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") in ["infinity", "opensearch"], reason="Infinity"), ), pytest.param( {"top_k": -1}, 100, 4, "3014", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") in [None, "opensearch", "elasticsearch"], reason="elasticsearch"), ), pytest.param( {"top_k": "a"}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip, ), ], ) def test_top_k(self, get_http_api_auth, add_chunks, payload, expected_code, expected_page_size, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert expected_message in res["message"] @pytest.mark.skip @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"rerank_id": "BAAI/bge-reranker-v2-m3"}, 0, ""), pytest.param({"rerank_id": "unknown"}, 100, "LookupError('Model(unknown) not authorized')", marks=pytest.mark.skip), ], ) def test_rerank_id(self, get_http_api_auth, add_chunks, payload, expected_code, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) > 0 else: assert expected_message in res["message"] @pytest.mark.skip @pytest.mark.parametrize( "payload, expected_code, expected_page_size, expected_message", [ ({"keyword": True}, 0, 5, ""), ({"keyword": "True"}, 0, 5, ""), ({"keyword": False}, 0, 5, ""), ({"keyword": "False"}, 0, 5, ""), ({"keyword": None}, 0, 5, ""), ], ) def test_keyword(self, get_http_api_auth, add_chunks, payload, expected_code, expected_page_size, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk test", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_code, expected_highlight, expected_message", [ ({"highlight": True}, 0, True, ""), ({"highlight": "True"}, 0, True, ""), pytest.param({"highlight": False}, 0, False, "", marks=pytest.mark.skip(reason="issues/6648")), ({"highlight": "False"}, 0, False, ""), pytest.param({"highlight": None}, 0, False, "", marks=pytest.mark.skip(reason="issues/6648")), ], ) def test_highlight(self, get_http_api_auth, add_chunks, payload, expected_code, expected_highlight, expected_message): dataset_id, _, _ = add_chunks payload.update({"question": "chunk", "dataset_ids": [dataset_id]}) res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == expected_code if expected_highlight: for chunk in res["data"]["chunks"]: assert "highlight" in chunk else: for chunk in res["data"]["chunks"]: assert "highlight" not in chunk if expected_code != 0: assert res["message"] == expected_message @pytest.mark.p3 def test_invalid_params(self, get_http_api_auth, add_chunks): dataset_id, _, _ = add_chunks payload = {"question": "chunk", "dataset_ids": [dataset_id], "a": "b"} res = retrieval_chunks(get_http_api_auth, payload) assert res["code"] == 0 assert len(res["data"]["chunks"]) == 4 @pytest.mark.p3 def test_concurrent_retrieval(self, get_http_api_auth, add_chunks): from concurrent.futures import ThreadPoolExecutor dataset_id, _, _ = add_chunks payload = {"question": "chunk", "dataset_ids": [dataset_id]} with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(retrieval_chunks, get_http_api_auth, payload) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_update_chunk.py
sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_update_chunk.py
# # 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 from concurrent.futures import ThreadPoolExecutor from random import randint import pytest from common import INVALID_API_TOKEN, delete_documnets, update_chunk from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = update_chunk(auth, "dataset_id", "document_id", "chunk_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestUpdatedChunk: @pytest.mark.p1 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"content": None}, 100, "TypeError('expected string or bytes-like object')"), pytest.param( {"content": ""}, 100, """APIRequestFailedError(\'Error code: 400, with error text {"error":{"code":"1213","message":"ๆœชๆญฃๅธธๆŽฅๆ”ถๅˆฐpromptๅ‚ๆ•ฐใ€‚"}}\')""", marks=pytest.mark.skip(reason="issues/6541"), ), pytest.param( {"content": 1}, 100, "TypeError('expected string or bytes-like object')", marks=pytest.mark.skip, ), ({"content": "update chunk"}, 0, ""), pytest.param( {"content": " "}, 100, """APIRequestFailedError(\'Error code: 400, with error text {"error":{"code":"1213","message":"ๆœชๆญฃๅธธๆŽฅๆ”ถๅˆฐpromptๅ‚ๆ•ฐใ€‚"}}\')""", marks=pytest.mark.skip(reason="issues/6541"), ), ({"content": "\n!?ใ€‚๏ผ›๏ผ๏ผŸ\"'"}, 0, ""), ], ) def test_content(self, get_http_api_auth, add_chunks, payload, expected_code, expected_message): dataset_id, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], payload) assert res["code"] == expected_code if expected_code != 0: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"important_keywords": ["a", "b", "c"]}, 0, ""), ({"important_keywords": [""]}, 0, ""), ({"important_keywords": [1]}, 100, "TypeError('sequence item 0: expected str instance, int found')"), ({"important_keywords": ["a", "a"]}, 0, ""), ({"important_keywords": "abc"}, 102, "`important_keywords` should be a list"), ({"important_keywords": 123}, 102, "`important_keywords` should be a list"), ], ) def test_important_keywords(self, get_http_api_auth, add_chunks, payload, expected_code, expected_message): dataset_id, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], payload) assert res["code"] == expected_code if expected_code != 0: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"questions": ["a", "b", "c"]}, 0, ""), ({"questions": [""]}, 0, ""), ({"questions": [1]}, 100, "TypeError('sequence item 0: expected str instance, int found')"), ({"questions": ["a", "a"]}, 0, ""), ({"questions": "abc"}, 102, "`questions` should be a list"), ({"questions": 123}, 102, "`questions` should be a list"), ], ) def test_questions(self, get_http_api_auth, add_chunks, payload, expected_code, expected_message): dataset_id, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], payload) assert res["code"] == expected_code if expected_code != 0: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"available": True}, 0, ""), pytest.param({"available": "True"}, 100, """ValueError("invalid literal for int() with base 10: \'True\'")""", marks=pytest.mark.skip), ({"available": 1}, 0, ""), ({"available": False}, 0, ""), pytest.param({"available": "False"}, 100, """ValueError("invalid literal for int() with base 10: \'False\'")""", marks=pytest.mark.skip), ({"available": 0}, 0, ""), ], ) def test_available( self, get_http_api_auth, add_chunks, payload, expected_code, expected_message, ): dataset_id, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], payload) assert res["code"] == expected_code if expected_code != 0: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "dataset_id, expected_code, expected_message", [ ("", 100, "<NotFound '404: Not Found'>"), pytest.param("invalid_dataset_id", 102, "You don't own the dataset invalid_dataset_id.", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") == "infinity", reason="infinity")), pytest.param("invalid_dataset_id", 102, "Can't find this chunk", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") in [None, "opensearch","elasticsearch"], reason="elasticsearch")), ], ) def test_invalid_dataset_id(self, get_http_api_auth, add_chunks, dataset_id, expected_code, expected_message): _, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0]) assert res["code"] == expected_code assert expected_message in res["message"] @pytest.mark.p3 @pytest.mark.parametrize( "document_id, expected_code, expected_message", [ ("", 100, "<NotFound '404: Not Found'>"), ( "invalid_document_id", 102, "You don't own the document invalid_document_id.", ), ], ) def test_invalid_document_id(self, get_http_api_auth, add_chunks, document_id, expected_code, expected_message): dataset_id, _, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0]) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "chunk_id, expected_code, expected_message", [ ("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"), ( "invalid_document_id", 102, "Can't find this chunk invalid_document_id", ), ], ) def test_invalid_chunk_id(self, get_http_api_auth, add_chunks, chunk_id, expected_code, expected_message): dataset_id, document_id, _ = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_id) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 def test_repeated_update_chunk(self, get_http_api_auth, add_chunks): dataset_id, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], {"content": "chunk test 1"}) assert res["code"] == 0 res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], {"content": "chunk test 2"}) assert res["code"] == 0 @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"unknown_key": "unknown_value"}, 0, ""), ({}, 0, ""), pytest.param(None, 100, """TypeError("argument of type \'NoneType\' is not iterable")""", marks=pytest.mark.skip), ], ) def test_invalid_params(self, get_http_api_auth, add_chunks, payload, expected_code, expected_message): dataset_id, document_id, chunk_ids = add_chunks res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0], payload) assert res["code"] == expected_code if expected_code != 0: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.skipif(os.getenv("DOC_ENGINE") == "infinity", reason="issues/6554") def test_concurrent_update_chunk(self, get_http_api_auth, add_chunks): chunk_num = 50 dataset_id, document_id, chunk_ids = add_chunks with ThreadPoolExecutor(max_workers=5) as executor: futures = [ executor.submit( update_chunk, get_http_api_auth, dataset_id, document_id, chunk_ids[randint(0, 3)], {"content": f"update chunk test {i}"}, ) for i in range(chunk_num) ] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_update_chunk_to_deleted_document(self, get_http_api_auth, add_chunks): dataset_id, document_id, chunk_ids = add_chunks delete_documnets(get_http_api_auth, dataset_id, {"ids": [document_id]}) res = update_chunk(get_http_api_auth, dataset_id, document_id, chunk_ids[0]) assert res["code"] == 102 assert res["message"] == f"Can't find this chunk {chunk_ids[0]}"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chunk_management_within_dataset/conftest.py
sdk/python/test/test_http_api/test_chunk_management_within_dataset/conftest.py
# # 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 pytest from common import add_chunk, delete_chunks, list_documnets, parse_documnets from libs.utils import wait_for @wait_for(30, 1, "Document parsing timeout") def condition(_auth, _dataset_id): res = list_documnets(_auth, _dataset_id) for doc in res["data"]["docs"]: if doc["run"] != "DONE": return False return True @pytest.fixture(scope="function") def add_chunks_func(request, get_http_api_auth, add_document): dataset_id, document_id = add_document parse_documnets(get_http_api_auth, dataset_id, {"document_ids": [document_id]}) condition(get_http_api_auth, dataset_id) chunk_ids = [] for i in range(4): res = add_chunk(get_http_api_auth, dataset_id, document_id, {"content": f"chunk test {i}"}) chunk_ids.append(res["data"]["chunk"]["id"]) # issues/6487 from time import sleep sleep(1) def cleanup(): delete_chunks(get_http_api_auth, dataset_id, document_id, {"chunk_ids": chunk_ids}) request.addfinalizer(cleanup) return dataset_id, document_id, chunk_ids
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_delete_chunks.py
sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_delete_chunks.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, batch_add_chunks, delete_chunks, list_chunks from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = delete_chunks(auth, "dataset_id", "document_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestChunksDeletion: @pytest.mark.p3 @pytest.mark.parametrize( "dataset_id, expected_code, expected_message", [ ("", 100, "<NotFound '404: Not Found'>"), ( "invalid_dataset_id", 102, "You don't own the dataset invalid_dataset_id.", ), ], ) def test_invalid_dataset_id(self, get_http_api_auth, add_chunks_func, dataset_id, expected_code, expected_message): _, document_id, chunk_ids = add_chunks_func res = delete_chunks(get_http_api_auth, dataset_id, document_id, {"chunk_ids": chunk_ids}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "document_id, expected_code, expected_message", [ ("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"), ("invalid_document_id", 100, """LookupError("Can't find the document with ID invalid_document_id!")"""), ], ) def test_invalid_document_id(self, get_http_api_auth, add_chunks_func, document_id, expected_code, expected_message): dataset_id, _, chunk_ids = add_chunks_func res = delete_chunks(get_http_api_auth, dataset_id, document_id, {"chunk_ids": chunk_ids}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.parametrize( "payload", [ pytest.param(lambda r: {"chunk_ids": ["invalid_id"] + r}, marks=pytest.mark.p3), pytest.param(lambda r: {"chunk_ids": r[:1] + ["invalid_id"] + r[1:4]}, marks=pytest.mark.p1), pytest.param(lambda r: {"chunk_ids": r + ["invalid_id"]}, marks=pytest.mark.p3), ], ) def test_delete_partial_invalid_id(self, get_http_api_auth, add_chunks_func, payload): dataset_id, document_id, chunk_ids = add_chunks_func if callable(payload): payload = payload(chunk_ids) res = delete_chunks(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == 102 assert res["message"] == "rm_chunk deleted chunks 4, expect 5" res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert len(res["data"]["chunks"]) == 1 assert res["data"]["total"] == 1 @pytest.mark.p3 def test_repeated_deletion(self, get_http_api_auth, add_chunks_func): dataset_id, document_id, chunk_ids = add_chunks_func payload = {"chunk_ids": chunk_ids} res = delete_chunks(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == 0 res = delete_chunks(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == 102 assert res["message"] == "rm_chunk deleted chunks 0, expect 4" @pytest.mark.p3 def test_duplicate_deletion(self, get_http_api_auth, add_chunks_func): dataset_id, document_id, chunk_ids = add_chunks_func res = delete_chunks(get_http_api_auth, dataset_id, document_id, {"chunk_ids": chunk_ids * 2}) assert res["code"] == 0 assert "Duplicate chunk ids" in res["data"]["errors"][0] assert res["data"]["success_count"] == 4 res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert len(res["data"]["chunks"]) == 1 assert res["data"]["total"] == 1 @pytest.mark.p3 def test_concurrent_deletion(self, get_http_api_auth, add_document): chunks_num = 100 dataset_id, document_id = add_document chunk_ids = batch_add_chunks(get_http_api_auth, dataset_id, document_id, chunks_num) with ThreadPoolExecutor(max_workers=5) as executor: futures = [ executor.submit( delete_chunks, get_http_api_auth, dataset_id, document_id, {"chunk_ids": chunk_ids[i : i + 1]}, ) for i in range(chunks_num) ] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_delete_1k(self, get_http_api_auth, add_document): chunks_num = 1_000 dataset_id, document_id = add_document chunk_ids = batch_add_chunks(get_http_api_auth, dataset_id, document_id, chunks_num) # issues/6487 from time import sleep sleep(1) res = delete_chunks(get_http_api_auth, dataset_id, document_id, {"chunk_ids": chunk_ids}) assert res["code"] == 0 res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert len(res["data"]["chunks"]) == 1 assert res["data"]["total"] == 1 @pytest.mark.parametrize( "payload, expected_code, expected_message, remaining", [ pytest.param(None, 100, """TypeError("argument of type \'NoneType\' is not iterable")""", 5, marks=pytest.mark.skip), pytest.param({"chunk_ids": ["invalid_id"]}, 102, "rm_chunk deleted chunks 0, expect 1", 5, marks=pytest.mark.p3), pytest.param("not json", 100, """UnboundLocalError("local variable \'duplicate_messages\' referenced before assignment")""", 5, marks=pytest.mark.skip(reason="pull/6376")), pytest.param(lambda r: {"chunk_ids": r[:1]}, 0, "", 4, marks=pytest.mark.p3), pytest.param(lambda r: {"chunk_ids": r}, 0, "", 1, marks=pytest.mark.p1), pytest.param({"chunk_ids": []}, 0, "", 0, marks=pytest.mark.p3), ], ) def test_basic_scenarios( self, get_http_api_auth, add_chunks_func, payload, expected_code, expected_message, remaining, ): dataset_id, document_id, chunk_ids = add_chunks_func if callable(payload): payload = payload(chunk_ids) res = delete_chunks(get_http_api_auth, dataset_id, document_id, payload) assert res["code"] == expected_code if res["code"] != 0: assert res["message"] == expected_message res = list_chunks(get_http_api_auth, dataset_id, document_id) if res["code"] != 0: assert False, res assert len(res["data"]["chunks"]) == remaining assert res["data"]["total"] == remaining
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py
sdk/python/test/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py
# # 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 from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, batch_add_chunks, list_chunks from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = list_chunks(auth, "dataset_id", "document_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestChunksList: @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_page_size, expected_message", [ ({"page": None, "page_size": 2}, 0, 2, ""), pytest.param({"page": 0, "page_size": 2}, 100, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip), ({"page": 2, "page_size": 2}, 0, 2, ""), ({"page": 3, "page_size": 2}, 0, 1, ""), ({"page": "3", "page_size": 2}, 0, 1, ""), pytest.param({"page": -1, "page_size": 2}, 100, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip), pytest.param({"page": "a", "page_size": 2}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip), ], ) def test_page(self, get_http_api_auth, add_chunks, params, expected_code, expected_page_size, expected_message): dataset_id, document_id, _ = add_chunks res = list_chunks(get_http_api_auth, dataset_id, document_id, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_page_size, expected_message", [ ({"page_size": None}, 0, 5, ""), pytest.param({"page_size": 0}, 0, 5, ""), pytest.param({"page_size": 0}, 100, 0, ""), ({"page_size": 1}, 0, 1, ""), ({"page_size": 6}, 0, 5, ""), ({"page_size": "1"}, 0, 1, ""), pytest.param({"page_size": -1}, 0, 5, "", marks=pytest.mark.skip), pytest.param({"page_size": "a"}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip), ], ) def test_page_size(self, get_http_api_auth, add_chunks, params, expected_code, expected_page_size, expected_message): dataset_id, document_id, _ = add_chunks res = list_chunks(get_http_api_auth, dataset_id, document_id, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p2 @pytest.mark.parametrize( "params, expected_page_size", [ ({"keywords": None}, 5), ({"keywords": ""}, 5), ({"keywords": "1"}, 1), pytest.param({"keywords": "chunk"}, 4, marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") == "infinity", reason="issues/6509")), ({"keywords": "ragflow"}, 1), ({"keywords": "unknown"}, 0), ], ) def test_keywords(self, get_http_api_auth, add_chunks, params, expected_page_size): dataset_id, document_id, _ = add_chunks res = list_chunks(get_http_api_auth, dataset_id, document_id, params=params) assert res["code"] == 0 assert len(res["data"]["chunks"]) == expected_page_size @pytest.mark.p1 @pytest.mark.parametrize( "chunk_id, expected_code, expected_page_size, expected_message", [ (None, 0, 5, ""), ("", 0, 5, ""), pytest.param(lambda r: r[0], 0, 1, "", marks=pytest.mark.skipif(os.getenv("DOC_ENGINE") == "infinity", reason="issues/6499")), pytest.param("unknown", 100, 0, """AttributeError("\'NoneType\' object has no attribute \'keys\'")""", marks=pytest.mark.skip), ], ) def test_id( self, get_http_api_auth, add_chunks, chunk_id, expected_code, expected_page_size, expected_message, ): dataset_id, document_id, chunk_ids = add_chunks if callable(chunk_id): params = {"id": chunk_id(chunk_ids)} else: params = {"id": chunk_id} res = list_chunks(get_http_api_auth, dataset_id, document_id, params=params) assert res["code"] == expected_code if expected_code == 0: if params["id"] in [None, ""]: assert len(res["data"]["chunks"]) == expected_page_size else: assert res["data"]["chunks"][0]["id"] == params["id"] else: assert res["message"] == expected_message @pytest.mark.p3 def test_invalid_params(self, get_http_api_auth, add_chunks): dataset_id, document_id, _ = add_chunks params = {"a": "b"} res = list_chunks(get_http_api_auth, dataset_id, document_id, params=params) assert res["code"] == 0 assert len(res["data"]["chunks"]) == 5 @pytest.mark.p3 def test_concurrent_list(self, get_http_api_auth, add_chunks): dataset_id, document_id, _ = add_chunks with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(list_chunks, get_http_api_auth, dataset_id, document_id) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) assert all(len(r["data"]["chunks"]) == 5 for r in responses) @pytest.mark.p1 def test_default(self, get_http_api_auth, add_document): dataset_id, document_id = add_document res = list_chunks(get_http_api_auth, dataset_id, document_id) chunks_count = res["data"]["doc"]["chunk_count"] batch_add_chunks(get_http_api_auth, dataset_id, document_id, 31) # issues/6487 from time import sleep sleep(3) res = list_chunks(get_http_api_auth, dataset_id, document_id) assert res["code"] == 0 assert len(res["data"]["chunks"]) == 30 assert res["data"]["doc"]["chunk_count"] == chunks_count + 31 @pytest.mark.p3 @pytest.mark.parametrize( "dataset_id, expected_code, expected_message", [ ("", 100, "<NotFound '404: Not Found'>"), ( "invalid_dataset_id", 102, "You don't own the dataset invalid_dataset_id.", ), ], ) def test_invalid_dataset_id(self, get_http_api_auth, add_chunks, dataset_id, expected_code, expected_message): _, document_id, _ = add_chunks res = list_chunks(get_http_api_auth, dataset_id, document_id) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "document_id, expected_code, expected_message", [ ("", 102, "The dataset not own the document chunks."), ( "invalid_document_id", 102, "You don't own the document invalid_document_id.", ), ], ) def test_invalid_document_id(self, get_http_api_auth, add_chunks, document_id, expected_code, expected_message): dataset_id, _, _ = add_chunks res = list_chunks(get_http_api_auth, dataset_id, document_id) assert res["code"] == expected_code assert res["message"] == expected_message
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py
sdk/python/test/test_http_api/test_session_management/test_list_sessions_with_chat_assistant.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, delete_chat_assistants, list_session_with_chat_assistants from libs.auth import RAGFlowHttpApiAuth from libs.utils import is_sorted @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = list_session_with_chat_assistants(auth, "chat_assistant_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestSessionsWithChatAssistantList: @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_page_size, expected_message", [ ({"page": None, "page_size": 2}, 0, 2, ""), pytest.param({"page": 0, "page_size": 2}, 100, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip), ({"page": 2, "page_size": 2}, 0, 2, ""), ({"page": 3, "page_size": 2}, 0, 1, ""), ({"page": "3", "page_size": 2}, 0, 1, ""), pytest.param({"page": -1, "page_size": 2}, 100, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip), pytest.param({"page": "a", "page_size": 2}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip), ], ) def test_page(self, get_http_api_auth, add_sessions_with_chat_assistant, params, expected_code, expected_page_size, expected_message): chat_assistant_id, _ = add_sessions_with_chat_assistant res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_page_size, expected_message", [ ({"page_size": None}, 0, 5, ""), ({"page_size": 0}, 0, 0, ""), ({"page_size": 1}, 0, 1, ""), ({"page_size": 6}, 0, 5, ""), ({"page_size": "1"}, 0, 1, ""), pytest.param({"page_size": -1}, 0, 5, "", marks=pytest.mark.skip), pytest.param({"page_size": "a"}, 100, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip), ], ) def test_page_size(self, get_http_api_auth, add_sessions_with_chat_assistant, params, expected_code, expected_page_size, expected_message): chat_assistant_id, _ = add_sessions_with_chat_assistant res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]) == expected_page_size else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "params, expected_code, assertions, expected_message", [ ({"orderby": None}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"orderby": "create_time"}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"orderby": "update_time"}, 0, lambda r: (is_sorted(r["data"], "update_time", True)), ""), ({"orderby": "name", "desc": "False"}, 0, lambda r: (is_sorted(r["data"], "name", False)), ""), pytest.param({"orderby": "unknown"}, 102, 0, "orderby should be create_time or update_time", marks=pytest.mark.skip(reason="issues/")), ], ) def test_orderby( self, get_http_api_auth, add_sessions_with_chat_assistant, params, expected_code, assertions, expected_message, ): chat_assistant_id, _ = add_sessions_with_chat_assistant res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: if callable(assertions): assert assertions(res) else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "params, expected_code, assertions, expected_message", [ ({"desc": None}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": "true"}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": "True"}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": True}, 0, lambda r: (is_sorted(r["data"], "create_time", True)), ""), ({"desc": "false"}, 0, lambda r: (is_sorted(r["data"], "create_time", False)), ""), ({"desc": "False"}, 0, lambda r: (is_sorted(r["data"], "create_time", False)), ""), ({"desc": False}, 0, lambda r: (is_sorted(r["data"], "create_time", False)), ""), ({"desc": "False", "orderby": "update_time"}, 0, lambda r: (is_sorted(r["data"], "update_time", False)), ""), pytest.param({"desc": "unknown"}, 102, 0, "desc should be true or false", marks=pytest.mark.skip(reason="issues/")), ], ) def test_desc( self, get_http_api_auth, add_sessions_with_chat_assistant, params, expected_code, assertions, expected_message, ): chat_assistant_id, _ = add_sessions_with_chat_assistant res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: if callable(assertions): assert assertions(res) else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "params, expected_code, expected_num, expected_message", [ ({"name": None}, 0, 5, ""), ({"name": ""}, 0, 5, ""), ({"name": "session_with_chat_assistant_1"}, 0, 1, ""), ({"name": "unknown"}, 0, 0, ""), ], ) def test_name(self, get_http_api_auth, add_sessions_with_chat_assistant, params, expected_code, expected_num, expected_message): chat_assistant_id, _ = add_sessions_with_chat_assistant res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: if params["name"] == "session_with_chat_assistant_1": assert res["data"][0]["name"] == params["name"] else: assert len(res["data"]) == expected_num else: assert res["message"] == expected_message @pytest.mark.p1 @pytest.mark.parametrize( "session_id, expected_code, expected_num, expected_message", [ (None, 0, 5, ""), ("", 0, 5, ""), (lambda r: r[0], 0, 1, ""), ("unknown", 0, 0, "The chat doesn't exist"), ], ) def test_id(self, get_http_api_auth, add_sessions_with_chat_assistant, session_id, expected_code, expected_num, expected_message): chat_assistant_id, session_ids = add_sessions_with_chat_assistant if callable(session_id): params = {"id": session_id(session_ids)} else: params = {"id": session_id} res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: if params["id"] == session_ids[0]: assert res["data"][0]["id"] == params["id"] else: assert len(res["data"]) == expected_num else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "session_id, name, expected_code, expected_num, expected_message", [ (lambda r: r[0], "session_with_chat_assistant_0", 0, 1, ""), (lambda r: r[0], "session_with_chat_assistant_100", 0, 0, ""), (lambda r: r[0], "unknown", 0, 0, ""), ("id", "session_with_chat_assistant_0", 0, 0, ""), ], ) def test_name_and_id(self, get_http_api_auth, add_sessions_with_chat_assistant, session_id, name, expected_code, expected_num, expected_message): chat_assistant_id, session_ids = add_sessions_with_chat_assistant if callable(session_id): params = {"id": session_id(session_ids), "name": name} else: params = {"id": session_id, "name": name} res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == expected_code if expected_code == 0: assert len(res["data"]) == expected_num else: assert res["message"] == expected_message @pytest.mark.p3 def test_concurrent_list(self, get_http_api_auth, add_sessions_with_chat_assistant): chat_assistant_id, _ = add_sessions_with_chat_assistant with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(list_session_with_chat_assistants, get_http_api_auth, chat_assistant_id) for i in range(100)] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_invalid_params(self, get_http_api_auth, add_sessions_with_chat_assistant): chat_assistant_id, _ = add_sessions_with_chat_assistant params = {"a": "b"} res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, params=params) assert res["code"] == 0 assert len(res["data"]) == 5 @pytest.mark.p3 def test_list_chats_after_deleting_associated_chat_assistant(self, get_http_api_auth, add_sessions_with_chat_assistant): chat_assistant_id, _ = add_sessions_with_chat_assistant res = delete_chat_assistants(get_http_api_auth, {"ids": [chat_assistant_id]}) assert res["code"] == 0 res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) assert res["code"] == 102 assert "You don't own the assistant" in res["message"]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py
sdk/python/test/test_http_api/test_session_management/test_delete_sessions_with_chat_assistant.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, batch_add_sessions_with_chat_assistant, delete_session_with_chat_assistants, list_session_with_chat_assistants from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = delete_session_with_chat_assistants(auth, "chat_assistant_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestSessionWithChatAssistantDelete: @pytest.mark.p3 @pytest.mark.parametrize( "chat_assistant_id, expected_code, expected_message", [ ("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"), ( "invalid_chat_assistant_id", 102, "You don't own the chat", ), ], ) def test_invalid_chat_assistant_id(self, get_http_api_auth, add_sessions_with_chat_assistant_func, chat_assistant_id, expected_code, expected_message): _, session_ids = add_sessions_with_chat_assistant_func res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, {"ids": session_ids}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.parametrize( "payload", [ pytest.param(lambda r: {"ids": ["invalid_id"] + r}, marks=pytest.mark.p3), pytest.param(lambda r: {"ids": r[:1] + ["invalid_id"] + r[1:5]}, marks=pytest.mark.p1), pytest.param(lambda r: {"ids": r + ["invalid_id"]}, marks=pytest.mark.p3), ], ) def test_delete_partial_invalid_id(self, get_http_api_auth, add_sessions_with_chat_assistant_func, payload): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func if callable(payload): payload = payload(session_ids) res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, payload) assert res["code"] == 0 assert res["data"]["errors"][0] == "The chat doesn't own the session invalid_id" res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) if res["code"] != 0: assert False, res assert len(res["data"]) == 0 @pytest.mark.p3 def test_repeated_deletion(self, get_http_api_auth, add_sessions_with_chat_assistant_func): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func payload = {"ids": session_ids} res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, payload) assert res["code"] == 0 res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, payload) assert res["code"] == 102 assert "The chat doesn't own the session" in res["message"] @pytest.mark.p3 def test_duplicate_deletion(self, get_http_api_auth, add_sessions_with_chat_assistant_func): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, {"ids": session_ids * 2}) assert res["code"] == 0 assert "Duplicate session ids" in res["data"]["errors"][0] assert res["data"]["success_count"] == 5 res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) if res["code"] != 0: assert False, res assert len(res["data"]) == 0 @pytest.mark.p3 def test_concurrent_deletion(self, get_http_api_auth, add_chat_assistants): sessions_num = 100 _, _, chat_assistant_ids = add_chat_assistants session_ids = batch_add_sessions_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], sessions_num) with ThreadPoolExecutor(max_workers=5) as executor: futures = [ executor.submit( delete_session_with_chat_assistants, get_http_api_auth, chat_assistant_ids[0], {"ids": session_ids[i : i + 1]}, ) for i in range(sessions_num) ] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_delete_1k(self, get_http_api_auth, add_chat_assistants): sessions_num = 1_000 _, _, chat_assistant_ids = add_chat_assistants session_ids = batch_add_sessions_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], sessions_num) res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_ids[0], {"ids": session_ids}) assert res["code"] == 0 res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_ids[0]) if res["code"] != 0: assert False, res assert len(res["data"]) == 0 @pytest.mark.parametrize( "payload, expected_code, expected_message, remaining", [ pytest.param(None, 0, """TypeError("argument of type \'NoneType\' is not iterable")""", 0, marks=pytest.mark.skip), pytest.param({"ids": ["invalid_id"]}, 102, "The chat doesn't own the session invalid_id", 5, marks=pytest.mark.p3), pytest.param("not json", 100, """AttributeError("\'str\' object has no attribute \'get\'")""", 5, marks=pytest.mark.skip), pytest.param(lambda r: {"ids": r[:1]}, 0, "", 4, marks=pytest.mark.p3), pytest.param(lambda r: {"ids": r}, 0, "", 0, marks=pytest.mark.p1), pytest.param({"ids": []}, 0, "", 0, marks=pytest.mark.p3), ], ) def test_basic_scenarios( self, get_http_api_auth, add_sessions_with_chat_assistant_func, payload, expected_code, expected_message, remaining, ): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func if callable(payload): payload = payload(session_ids) res = delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, payload) assert res["code"] == expected_code if res["code"] != 0: assert res["message"] == expected_message res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) if res["code"] != 0: assert False, res assert len(res["data"]) == remaining
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_session_management/conftest.py
sdk/python/test/test_http_api/test_session_management/conftest.py
# # 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 pytest from common import create_session_with_chat_assistant, delete_session_with_chat_assistants @pytest.fixture(scope="class") def add_sessions_with_chat_assistant(request, get_http_api_auth, add_chat_assistants): _, _, chat_assistant_ids = add_chat_assistants def cleanup(): for chat_assistant_id in chat_assistant_ids: delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) request.addfinalizer(cleanup) session_ids = [] for i in range(5): res = create_session_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], {"name": f"session_with_chat_assistant_{i}"}) session_ids.append(res["data"]["id"]) return chat_assistant_ids[0], session_ids @pytest.fixture(scope="function") def add_sessions_with_chat_assistant_func(request, get_http_api_auth, add_chat_assistants): _, _, chat_assistant_ids = add_chat_assistants def cleanup(): for chat_assistant_id in chat_assistant_ids: delete_session_with_chat_assistants(get_http_api_auth, chat_assistant_id) request.addfinalizer(cleanup) session_ids = [] for i in range(5): res = create_session_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], {"name": f"session_with_chat_assistant_{i}"}) session_ids.append(res["data"]["id"]) return chat_assistant_ids[0], session_ids
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_session_management/test_create_session_with_chat_assistant.py
sdk/python/test/test_http_api/test_session_management/test_create_session_with_chat_assistant.py
# # 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. # from concurrent.futures import ThreadPoolExecutor import pytest from common import INVALID_API_TOKEN, SESSION_WITH_CHAT_NAME_LIMIT, create_session_with_chat_assistant, delete_chat_assistants, list_session_with_chat_assistants from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = create_session_with_chat_assistant(auth, "chat_assistant_id") assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.usefixtures("clear_session_with_chat_assistants") class TestSessionWithChatAssistantCreate: @pytest.mark.p1 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ ({"name": "valid_name"}, 0, ""), pytest.param({"name": "a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1)}, 102, "", marks=pytest.mark.skip(reason="issues/")), pytest.param({"name": 1}, 100, "", marks=pytest.mark.skip(reason="issues/")), ({"name": ""}, 102, "`name` can not be empty."), ({"name": "duplicated_name"}, 0, ""), ({"name": "case insensitive"}, 0, ""), ], ) def test_name(self, get_http_api_auth, add_chat_assistants, payload, expected_code, expected_message): _, _, chat_assistant_ids = add_chat_assistants if payload["name"] == "duplicated_name": create_session_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) elif payload["name"] == "case insensitive": create_session_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], {"name": payload["name"].upper()}) res = create_session_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], payload) assert res["code"] == expected_code, res if expected_code == 0: assert res["data"]["name"] == payload["name"] assert res["data"]["chat_id"] == chat_assistant_ids[0] else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "chat_assistant_id, expected_code, expected_message", [ ("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"), ("invalid_chat_assistant_id", 102, "You do not own the assistant."), ], ) def test_invalid_chat_assistant_id(self, get_http_api_auth, chat_assistant_id, expected_code, expected_message): res = create_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, {"name": "valid_name"}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 def test_concurrent_create_session(self, get_http_api_auth, add_chat_assistants): chunk_num = 1000 _, _, chat_assistant_ids = add_chat_assistants res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_ids[0]) if res["code"] != 0: assert False, res chunks_count = len(res["data"]) with ThreadPoolExecutor(max_workers=5) as executor: futures = [ executor.submit( create_session_with_chat_assistant, get_http_api_auth, chat_assistant_ids[0], {"name": f"session with chat assistant test {i}"}, ) for i in range(chunk_num) ] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_ids[0], {"page_size": chunk_num}) if res["code"] != 0: assert False, res assert len(res["data"]) == chunks_count + chunk_num @pytest.mark.p3 def test_add_session_to_deleted_chat_assistant(self, get_http_api_auth, add_chat_assistants): _, _, chat_assistant_ids = add_chat_assistants res = delete_chat_assistants(get_http_api_auth, {"ids": [chat_assistant_ids[0]]}) assert res["code"] == 0 res = create_session_with_chat_assistant(get_http_api_auth, chat_assistant_ids[0], {"name": "valid_name"}) assert res["code"] == 102 assert res["message"] == "You do not own the assistant."
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/sdk/python/test/test_http_api/test_session_management/test_update_session_with_chat_assistant.py
sdk/python/test/test_http_api/test_session_management/test_update_session_with_chat_assistant.py
# # 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. # from concurrent.futures import ThreadPoolExecutor from random import randint import pytest from common import INVALID_API_TOKEN, SESSION_WITH_CHAT_NAME_LIMIT, delete_chat_assistants, list_session_with_chat_assistants, update_session_with_chat_assistant from libs.auth import RAGFlowHttpApiAuth @pytest.mark.p1 class TestAuthorization: @pytest.mark.parametrize( "auth, expected_code, expected_message", [ (None, 0, "`Authorization` can't be empty"), ( RAGFlowHttpApiAuth(INVALID_API_TOKEN), 109, "Authentication error: API key is invalid!", ), ], ) def test_invalid_auth(self, auth, expected_code, expected_message): res = update_session_with_chat_assistant(auth, "chat_assistant_id", "session_id") assert res["code"] == expected_code assert res["message"] == expected_message class TestSessionWithChatAssistantUpdate: @pytest.mark.parametrize( "payload, expected_code, expected_message", [ pytest.param({"name": "valid_name"}, 0, "", marks=pytest.mark.p1), pytest.param({"name": "a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1)}, 102, "", marks=pytest.mark.skip(reason="issues/")), pytest.param({"name": 1}, 100, "", marks=pytest.mark.skip(reason="issues/")), pytest.param({"name": ""}, 102, "`name` can not be empty.", marks=pytest.mark.p3), pytest.param({"name": "duplicated_name"}, 0, "", marks=pytest.mark.p3), pytest.param({"name": "case insensitive"}, 0, "", marks=pytest.mark.p3), ], ) def test_name(self, get_http_api_auth, add_sessions_with_chat_assistant_func, payload, expected_code, expected_message): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func if payload["name"] == "duplicated_name": update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], payload) elif payload["name"] == "case insensitive": update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], {"name": payload["name"].upper()}) res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], payload) assert res["code"] == expected_code, res if expected_code == 0: res = list_session_with_chat_assistants(get_http_api_auth, chat_assistant_id, {"id": session_ids[0]}) assert res["data"][0]["name"] == payload["name"] else: assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "chat_assistant_id, expected_code, expected_message", [ ("", 100, "<NotFound '404: Not Found'>"), pytest.param("invalid_chat_assistant_id", 102, "Session does not exist", marks=pytest.mark.skip(reason="issues/")), ], ) def test_invalid_chat_assistant_id(self, get_http_api_auth, add_sessions_with_chat_assistant_func, chat_assistant_id, expected_code, expected_message): _, session_ids = add_sessions_with_chat_assistant_func res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], {"name": "valid_name"}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 @pytest.mark.parametrize( "session_id, expected_code, expected_message", [ ("", 100, "<MethodNotAllowed '405: Method Not Allowed'>"), ("invalid_session_id", 102, "Session does not exist"), ], ) def test_invalid_session_id(self, get_http_api_auth, add_sessions_with_chat_assistant_func, session_id, expected_code, expected_message): chat_assistant_id, _ = add_sessions_with_chat_assistant_func res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_id, {"name": "valid_name"}) assert res["code"] == expected_code assert res["message"] == expected_message @pytest.mark.p3 def test_repeated_update_session(self, get_http_api_auth, add_sessions_with_chat_assistant_func): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], {"name": "valid_name_1"}) assert res["code"] == 0 res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], {"name": "valid_name_2"}) assert res["code"] == 0 @pytest.mark.p3 @pytest.mark.parametrize( "payload, expected_code, expected_message", [ pytest.param({"unknown_key": "unknown_value"}, 100, "ValueError", marks=pytest.mark.skip), ({}, 0, ""), pytest.param(None, 100, "TypeError", marks=pytest.mark.skip), ], ) def test_invalid_params(self, get_http_api_auth, add_sessions_with_chat_assistant_func, payload, expected_code, expected_message): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], payload) assert res["code"] == expected_code if expected_code != 0: assert expected_message in res["message"] @pytest.mark.p3 def test_concurrent_update_session(self, get_http_api_auth, add_sessions_with_chat_assistant_func): chunk_num = 50 chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func with ThreadPoolExecutor(max_workers=5) as executor: futures = [ executor.submit( update_session_with_chat_assistant, get_http_api_auth, chat_assistant_id, session_ids[randint(0, 4)], {"name": f"update session test {i}"}, ) for i in range(chunk_num) ] responses = [f.result() for f in futures] assert all(r["code"] == 0 for r in responses) @pytest.mark.p3 def test_update_session_to_deleted_chat_assistant(self, get_http_api_auth, add_sessions_with_chat_assistant_func): chat_assistant_id, session_ids = add_sessions_with_chat_assistant_func delete_chat_assistants(get_http_api_auth, {"ids": [chat_assistant_id]}) res = update_session_with_chat_assistant(get_http_api_auth, chat_assistant_id, session_ids[0], {"name": "valid_name"}) assert res["code"] == 102 assert res["message"] == "You do not own the session"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false