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/api/apps/tenant_app.py
api/apps/tenant_app.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 asyncio from api.db import UserTenantRole from api.db.db_models import UserTenant from api.db.services.user_service import UserTenantService, UserService from common.constants import RetCode, StatusEnum from common.misc_utils import get_uuid from common.time_utils import delta_seconds from api.utils.api_utils import get_data_error_result, get_json_result, get_request_json, server_error_response, validate_request from api.utils.web_utils import send_invite_email from common import settings from api.apps import login_required, current_user @manager.route("/<tenant_id>/user/list", methods=["GET"]) # noqa: F821 @login_required def user_list(tenant_id): if current_user.id != tenant_id: return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR) try: users = UserTenantService.get_by_tenant_id(tenant_id) for u in users: u["delta_seconds"] = delta_seconds(str(u["update_date"])) return get_json_result(data=users) except Exception as e: return server_error_response(e) @manager.route('/<tenant_id>/user', methods=['POST']) # noqa: F821 @login_required @validate_request("email") async def create(tenant_id): if current_user.id != tenant_id: return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR) req = await get_request_json() invite_user_email = req["email"] invite_users = UserService.query(email=invite_user_email) if not invite_users: return get_data_error_result(message="User not found.") user_id_to_invite = invite_users[0].id user_tenants = UserTenantService.query(user_id=user_id_to_invite, tenant_id=tenant_id) if user_tenants: user_tenant_role = user_tenants[0].role if user_tenant_role == UserTenantRole.NORMAL: return get_data_error_result(message=f"{invite_user_email} is already in the team.") if user_tenant_role == UserTenantRole.OWNER: return get_data_error_result(message=f"{invite_user_email} is the owner of the team.") return get_data_error_result( message=f"{invite_user_email} is in the team, but the role: {user_tenant_role} is invalid.") UserTenantService.save( id=get_uuid(), user_id=user_id_to_invite, tenant_id=tenant_id, invited_by=current_user.id, role=UserTenantRole.INVITE, status=StatusEnum.VALID.value) try: user_name = "" _, user = UserService.get_by_id(current_user.id) if user: user_name = user.nickname asyncio.create_task( send_invite_email( to_email=invite_user_email, invite_url=settings.MAIL_FRONTEND_URL, tenant_id=tenant_id, inviter=user_name or current_user.email ) ) except Exception as e: logging.exception(f"Failed to send invite email to {invite_user_email}: {e}") return get_json_result(data=False, message="Failed to send invite email.", code=RetCode.SERVER_ERROR) usr = invite_users[0].to_dict() usr = {k: v for k, v in usr.items() if k in ["id", "avatar", "email", "nickname"]} return get_json_result(data=usr) @manager.route('/<tenant_id>/user/<user_id>', methods=['DELETE']) # noqa: F821 @login_required def rm(tenant_id, user_id): if current_user.id != tenant_id and current_user.id != user_id: return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR) try: UserTenantService.filter_delete([UserTenant.tenant_id == tenant_id, UserTenant.user_id == user_id]) return get_json_result(data=True) except Exception as e: return server_error_response(e) @manager.route("/list", methods=["GET"]) # noqa: F821 @login_required def tenant_list(): try: users = UserTenantService.get_tenants_by_user_id(current_user.id) for u in users: u["delta_seconds"] = delta_seconds(str(u["update_date"])) return get_json_result(data=users) except Exception as e: return server_error_response(e) @manager.route("/agree/<tenant_id>", methods=["PUT"]) # noqa: F821 @login_required def agree(tenant_id): try: UserTenantService.filter_update([UserTenant.tenant_id == tenant_id, UserTenant.user_id == current_user.id], {"role": UserTenantRole.NORMAL}) return get_json_result(data=True) except Exception as e: return server_error_response(e)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/search_app.py
api/apps/search_app.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 quart import request from api.apps import current_user, login_required from api.constants import DATASET_NAME_LIMIT from api.db.db_models import DB from api.db.services import duplicate_name from api.db.services.search_service import SearchService from api.db.services.user_service import TenantService, UserTenantService from common.misc_utils import get_uuid from common.constants import RetCode, StatusEnum from api.utils.api_utils import get_data_error_result, get_json_result, not_allowed_parameters, get_request_json, server_error_response, validate_request @manager.route("/create", methods=["post"]) # noqa: F821 @login_required @validate_request("name") async def create(): req = await get_request_json() search_name = req["name"] description = req.get("description", "") if not isinstance(search_name, str): return get_data_error_result(message="Search name must be string.") if search_name.strip() == "": return get_data_error_result(message="Search name can't be empty.") if len(search_name.encode("utf-8")) > 255: return get_data_error_result(message=f"Search name length is {len(search_name)} which is large than 255.") e, _ = TenantService.get_by_id(current_user.id) if not e: return get_data_error_result(message="Authorized identity.") search_name = search_name.strip() search_name = duplicate_name(SearchService.query, name=search_name, tenant_id=current_user.id, status=StatusEnum.VALID.value) req["id"] = get_uuid() req["name"] = search_name req["description"] = description req["tenant_id"] = current_user.id req["created_by"] = current_user.id with DB.atomic(): try: if not SearchService.save(**req): return get_data_error_result() return get_json_result(data={"search_id": req["id"]}) except Exception as e: return server_error_response(e) @manager.route("/update", methods=["post"]) # noqa: F821 @login_required @validate_request("search_id", "name", "search_config", "tenant_id") @not_allowed_parameters("id", "created_by", "create_time", "update_time", "create_date", "update_date", "created_by") async def update(): req = await get_request_json() if not isinstance(req["name"], str): return get_data_error_result(message="Search name must be string.") if req["name"].strip() == "": return get_data_error_result(message="Search name can't be empty.") if len(req["name"].encode("utf-8")) > DATASET_NAME_LIMIT: return get_data_error_result(message=f"Search name length is {len(req['name'])} which is large than {DATASET_NAME_LIMIT}") req["name"] = req["name"].strip() tenant_id = req["tenant_id"] e, _ = TenantService.get_by_id(tenant_id) if not e: return get_data_error_result(message="Authorized identity.") search_id = req["search_id"] if not SearchService.accessible4deletion(search_id, current_user.id): return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR) try: search_app = SearchService.query(tenant_id=tenant_id, id=search_id)[0] if not search_app: return get_json_result(data=False, message=f"Cannot find search {search_id}", code=RetCode.DATA_ERROR) if req["name"].lower() != search_app.name.lower() and len(SearchService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value)) >= 1: return get_data_error_result(message="Duplicated search name.") if "search_config" in req: current_config = search_app.search_config or {} new_config = req["search_config"] if not isinstance(new_config, dict): return get_data_error_result(message="search_config must be a JSON object") updated_config = {**current_config, **new_config} req["search_config"] = updated_config req.pop("search_id", None) req.pop("tenant_id", None) updated = SearchService.update_by_id(search_id, req) if not updated: return get_data_error_result(message="Failed to update search") e, updated_search = SearchService.get_by_id(search_id) if not e: return get_data_error_result(message="Failed to fetch updated search") return get_json_result(data=updated_search.to_dict()) except Exception as e: return server_error_response(e) @manager.route("/detail", methods=["GET"]) # noqa: F821 @login_required def detail(): search_id = request.args["search_id"] try: tenants = UserTenantService.query(user_id=current_user.id) for tenant in tenants: if SearchService.query(tenant_id=tenant.tenant_id, id=search_id): break else: return get_json_result(data=False, message="Has no permission for this operation.", code=RetCode.OPERATING_ERROR) search = SearchService.get_detail(search_id) if not search: return get_data_error_result(message="Can't find this Search App!") return get_json_result(data=search) except Exception as e: return server_error_response(e) @manager.route("/list", methods=["POST"]) # noqa: F821 @login_required async def list_search_app(): keywords = request.args.get("keywords", "") page_number = int(request.args.get("page", 0)) items_per_page = int(request.args.get("page_size", 0)) orderby = request.args.get("orderby", "create_time") if request.args.get("desc", "true").lower() == "false": desc = False else: desc = True req = await get_request_json() owner_ids = req.get("owner_ids", []) try: if not owner_ids: # tenants = TenantService.get_joined_tenants_by_user_id(current_user.id) # tenants = [m["tenant_id"] for m in tenants] tenants = [] search_apps, total = SearchService.get_by_tenant_ids(tenants, current_user.id, page_number, items_per_page, orderby, desc, keywords) else: tenants = owner_ids search_apps, total = SearchService.get_by_tenant_ids(tenants, current_user.id, 0, 0, orderby, desc, keywords) search_apps = [search_app for search_app in search_apps if search_app["tenant_id"] in tenants] total = len(search_apps) if page_number and items_per_page: search_apps = search_apps[(page_number - 1) * items_per_page : page_number * items_per_page] return get_json_result(data={"search_apps": search_apps, "total": total}) except Exception as e: return server_error_response(e) @manager.route("/rm", methods=["post"]) # noqa: F821 @login_required @validate_request("search_id") async def rm(): req = await get_request_json() search_id = req["search_id"] if not SearchService.accessible4deletion(search_id, current_user.id): return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR) try: if not SearchService.delete_by_id(search_id): return get_data_error_result(message=f"Failed to delete search App {search_id}") return get_json_result(data=True) except Exception as e: return server_error_response(e)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/__init__.py
api/apps/__init__.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 sys from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path from quart import Blueprint, Quart, request, g, current_app, session from flasgger import Swagger from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer from quart_cors import cors from common.constants import StatusEnum from api.db.db_models import close_connection, APIToken from api.db.services import UserService from api.utils.json_encode import CustomJSONEncoder from api.utils import commands from quart_auth import Unauthorized from common import settings from api.utils.api_utils import server_error_response from api.constants import API_VERSION from common.misc_utils import get_uuid settings.init_settings() __all__ = ["app"] app = Quart(__name__) app = cors(app, allow_origin="*") # Add this at the beginning of your file to configure Swagger UI swagger_config = { "headers": [], "specs": [ { "endpoint": "apispec", "route": "/apispec.json", "rule_filter": lambda rule: True, # Include all endpoints "model_filter": lambda tag: True, # Include all models } ], "static_url_path": "/flasgger_static", "swagger_ui": True, "specs_route": "/apidocs/", } swagger = Swagger( app, config=swagger_config, template={ "swagger": "2.0", "info": { "title": "RAGFlow API", "description": "", "version": "1.0.0", }, "securityDefinitions": { "ApiKeyAuth": {"type": "apiKey", "name": "Authorization", "in": "header"} }, }, ) app.url_map.strict_slashes = False app.json_encoder = CustomJSONEncoder app.errorhandler(Exception)(server_error_response) # Configure Quart timeouts for slow LLM responses (e.g., local Ollama on CPU) # Default Quart timeouts are 60 seconds which is too short for many LLM backends app.config["RESPONSE_TIMEOUT"] = int(os.environ.get("QUART_RESPONSE_TIMEOUT", 600)) app.config["BODY_TIMEOUT"] = int(os.environ.get("QUART_BODY_TIMEOUT", 600)) ## convince for dev and debug # app.config["LOGIN_DISABLED"] = True app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "redis" app.config["SESSION_REDIS"] = settings.decrypt_database_config(name="redis") app.config["MAX_CONTENT_LENGTH"] = int( os.environ.get("MAX_CONTENT_LENGTH", 1024 * 1024 * 1024) ) app.config['SECRET_KEY'] = settings.SECRET_KEY app.secret_key = settings.SECRET_KEY commands.register_commands(app) from functools import wraps from typing import ParamSpec, TypeVar from collections.abc import Awaitable, Callable from werkzeug.local import LocalProxy T = TypeVar("T") P = ParamSpec("P") def _load_user(): jwt = Serializer(secret_key=settings.SECRET_KEY) authorization = request.headers.get("Authorization") g.user = None if not authorization: return None try: access_token = str(jwt.loads(authorization)) if not access_token or not access_token.strip(): logging.warning("Authentication attempt with empty access token") return None # Access tokens should be UUIDs (32 hex characters) if len(access_token.strip()) < 32: logging.warning(f"Authentication attempt with invalid token format: {len(access_token)} chars") return None user = UserService.query( access_token=access_token, status=StatusEnum.VALID.value ) if not user and len(authorization.split()) == 2: objs = APIToken.query(token=authorization.split()[1]) if objs: user = UserService.query(id=objs[0].tenant_id, status=StatusEnum.VALID.value) if user: if not user[0].access_token or not user[0].access_token.strip(): logging.warning(f"User {user[0].email} has empty access_token in database") return None g.user = user[0] return user[0] except Exception as e: logging.warning(f"load_user got exception {e}") current_user = LocalProxy(_load_user) def login_required(func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]: """A decorator to restrict route access to authenticated users. This should be used to wrap a route handler (or view function) to enforce that only authenticated requests can access it. Note that it is important that this decorator be wrapped by the route decorator and not vice, versa, as below. .. code-block:: python @app.route('/') @login_required async def index(): ... If the request is not authenticated a `quart.exceptions.Unauthorized` exception will be raised. """ @wraps(func) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: if not current_user: # or not session.get("_user_id"): raise Unauthorized() else: return await current_app.ensure_async(func)(*args, **kwargs) return wrapper def login_user(user, remember=False, duration=None, force=False, fresh=True): """ Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the login attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: bool """ if not force and not user.is_active: return False session["_user_id"] = user.id session["_fresh"] = fresh session["_id"] = get_uuid() return True def logout_user(): """ Logs a user out. (You do not need to pass the actual user.) This will also clean up the remember me cookie if it exists. """ if "_user_id" in session: session.pop("_user_id") if "_fresh" in session: session.pop("_fresh") if "_id" in session: session.pop("_id") COOKIE_NAME = "remember_token" cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME) if cookie_name in request.cookies: session["_remember"] = "clear" if "_remember_seconds" in session: session.pop("_remember_seconds") return True def search_pages_path(page_path): app_path_list = [ path for path in page_path.glob("*_app.py") if not path.name.startswith(".") ] api_path_list = [ path for path in page_path.glob("*sdk/*.py") if not path.name.startswith(".") ] app_path_list.extend(api_path_list) return app_path_list def register_page(page_path): path = f"{page_path}" page_name = page_path.stem.removesuffix("_app") module_name = ".".join( page_path.parts[page_path.parts.index("api"): -1] + (page_name,) ) spec = spec_from_file_location(module_name, page_path) page = module_from_spec(spec) page.app = app page.manager = Blueprint(page_name, module_name) sys.modules[module_name] = page spec.loader.exec_module(page) page_name = getattr(page, "page_name", page_name) sdk_path = "\\sdk\\" if sys.platform.startswith("win") else "/sdk/" url_prefix = ( f"/api/{API_VERSION}" if sdk_path in path else f"/{API_VERSION}/{page_name}" ) app.register_blueprint(page.manager, url_prefix=url_prefix) return url_prefix pages_dir = [ Path(__file__).parent, Path(__file__).parent.parent / "api" / "apps", Path(__file__).parent.parent / "api" / "apps" / "sdk", ] client_urls_prefix = [ register_page(path) for directory in pages_dir for path in search_pages_path(directory) ] @app.errorhandler(404) async def not_found(error): error_msg: str = f"The requested URL {request.path} was not found" logging.error(error_msg) return { "error": "Not Found", "message": error_msg, }, 404 @app.teardown_request def _db_close(exception): if exception: logging.exception(f"Request failed: {exception}") close_connection()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/langfuse_app.py
api/apps/langfuse_app.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 api.apps import current_user, login_required from langfuse import Langfuse from api.db.db_models import DB from api.db.services.langfuse_service import TenantLangfuseService from api.utils.api_utils import get_error_data_result, get_json_result, get_request_json, server_error_response, validate_request @manager.route("/api_key", methods=["POST", "PUT"]) # noqa: F821 @login_required @validate_request("secret_key", "public_key", "host") async def set_api_key(): req = await get_request_json() secret_key = req.get("secret_key", "") public_key = req.get("public_key", "") host = req.get("host", "") if not all([secret_key, public_key, host]): return get_error_data_result(message="Missing required fields") current_user_id = current_user.id langfuse_keys = dict( tenant_id=current_user_id, secret_key=secret_key, public_key=public_key, host=host, ) langfuse = Langfuse(public_key=langfuse_keys["public_key"], secret_key=langfuse_keys["secret_key"], host=langfuse_keys["host"]) if not langfuse.auth_check(): return get_error_data_result(message="Invalid Langfuse keys") langfuse_entry = TenantLangfuseService.filter_by_tenant(tenant_id=current_user_id) with DB.atomic(): try: if not langfuse_entry: TenantLangfuseService.save(**langfuse_keys) else: TenantLangfuseService.update_by_tenant(tenant_id=current_user_id, langfuse_keys=langfuse_keys) return get_json_result(data=langfuse_keys) except Exception as e: return server_error_response(e) @manager.route("/api_key", methods=["GET"]) # noqa: F821 @login_required @validate_request() def get_api_key(): current_user_id = current_user.id langfuse_entry = TenantLangfuseService.filter_by_tenant_with_info(tenant_id=current_user_id) if not langfuse_entry: return get_json_result(message="Have not record any Langfuse keys.") langfuse = Langfuse(public_key=langfuse_entry["public_key"], secret_key=langfuse_entry["secret_key"], host=langfuse_entry["host"]) try: if not langfuse.auth_check(): return get_error_data_result(message="Invalid Langfuse keys loaded") except langfuse.api.core.api_error.ApiError as api_err: return get_json_result(message=f"Error from Langfuse: {api_err}") except Exception as e: return server_error_response(e) langfuse_entry["project_id"] = langfuse.api.projects.get().dict()["data"][0]["id"] langfuse_entry["project_name"] = langfuse.api.projects.get().dict()["data"][0]["name"] return get_json_result(data=langfuse_entry) @manager.route("/api_key", methods=["DELETE"]) # noqa: F821 @login_required @validate_request() def delete_api_key(): current_user_id = current_user.id langfuse_entry = TenantLangfuseService.filter_by_tenant(tenant_id=current_user_id) if not langfuse_entry: return get_json_result(message="Have not record any Langfuse keys.") with DB.atomic(): try: TenantLangfuseService.delete_model(langfuse_entry) return get_json_result(data=True) except Exception as e: return server_error_response(e)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/memories_app.py
api/apps/memories_app.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 from quart import request from api.apps import login_required, current_user from api.db import TenantPermission from api.db.services.memory_service import MemoryService from api.db.services.user_service import UserTenantService from api.db.services.canvas_service import UserCanvasService from api.db.joint_services.memory_message_service import get_memory_size_cache, judge_system_prompt_is_default from api.utils.api_utils import validate_request, get_request_json, get_error_argument_result, get_json_result from api.utils.memory_utils import format_ret_data_from_memory, get_memory_type_human from api.constants import MEMORY_NAME_LIMIT, MEMORY_SIZE_LIMIT from memory.services.messages import MessageService from memory.utils.prompt_util import PromptAssembler from common.constants import MemoryType, RetCode, ForgettingPolicy @manager.route("", methods=["POST"]) # noqa: F821 @login_required @validate_request("name", "memory_type", "embd_id", "llm_id") async def create_memory(): req = await get_request_json() # check name length name = req["name"] memory_name = name.strip() if len(memory_name) == 0: return get_error_argument_result("Memory name cannot be empty or whitespace.") if len(memory_name) > MEMORY_NAME_LIMIT: return get_error_argument_result(f"Memory name '{memory_name}' exceeds limit of {MEMORY_NAME_LIMIT}.") # check memory_type valid memory_type = set(req["memory_type"]) invalid_type = memory_type - {e.name.lower() for e in MemoryType} if invalid_type: return get_error_argument_result(f"Memory type '{invalid_type}' is not supported.") memory_type = list(memory_type) try: res, memory = MemoryService.create_memory( tenant_id=current_user.id, name=memory_name, memory_type=memory_type, embd_id=req["embd_id"], llm_id=req["llm_id"] ) if res: return get_json_result(message=True, data=format_ret_data_from_memory(memory)) else: return get_json_result(message=memory, code=RetCode.SERVER_ERROR) except Exception as e: return get_json_result(message=str(e), code=RetCode.SERVER_ERROR) @manager.route("/<memory_id>", methods=["PUT"]) # noqa: F821 @login_required async def update_memory(memory_id): req = await get_request_json() update_dict = {} # check name length if "name" in req: name = req["name"] memory_name = name.strip() if len(memory_name) == 0: return get_error_argument_result("Memory name cannot be empty or whitespace.") if len(memory_name) > MEMORY_NAME_LIMIT: return get_error_argument_result(f"Memory name '{memory_name}' exceeds limit of {MEMORY_NAME_LIMIT}.") update_dict["name"] = memory_name # check permissions valid if req.get("permissions"): if req["permissions"] not in [e.value for e in TenantPermission]: return get_error_argument_result(f"Unknown permission '{req['permissions']}'.") update_dict["permissions"] = req["permissions"] if req.get("llm_id"): update_dict["llm_id"] = req["llm_id"] if req.get("embd_id"): update_dict["embd_id"] = req["embd_id"] if req.get("memory_type"): memory_type = set(req["memory_type"]) invalid_type = memory_type - {e.name.lower() for e in MemoryType} if invalid_type: return get_error_argument_result(f"Memory type '{invalid_type}' is not supported.") update_dict["memory_type"] = list(memory_type) # check memory_size valid if req.get("memory_size"): if not 0 < int(req["memory_size"]) <= MEMORY_SIZE_LIMIT: return get_error_argument_result(f"Memory size should be in range (0, {MEMORY_SIZE_LIMIT}] Bytes.") update_dict["memory_size"] = req["memory_size"] # check forgetting_policy valid if req.get("forgetting_policy"): if req["forgetting_policy"] not in [e.value for e in ForgettingPolicy]: return get_error_argument_result(f"Forgetting policy '{req['forgetting_policy']}' is not supported.") update_dict["forgetting_policy"] = req["forgetting_policy"] # check temperature valid if "temperature" in req: temperature = float(req["temperature"]) if not 0 <= temperature <= 1: return get_error_argument_result("Temperature should be in range [0, 1].") update_dict["temperature"] = temperature # allow update to empty fields for field in ["avatar", "description", "system_prompt", "user_prompt"]: if field in req: update_dict[field] = req[field] current_memory = MemoryService.get_by_memory_id(memory_id) if not current_memory: return get_json_result(code=RetCode.NOT_FOUND, message=f"Memory '{memory_id}' not found.") memory_dict = current_memory.to_dict() memory_dict.update({"memory_type": get_memory_type_human(current_memory.memory_type)}) to_update = {} for k, v in update_dict.items(): if isinstance(v, list) and set(memory_dict[k]) != set(v): to_update[k] = v elif memory_dict[k] != v: to_update[k] = v if not to_update: return get_json_result(message=True, data=memory_dict) # check memory empty when update embd_id, memory_type memory_size = get_memory_size_cache(memory_id, current_memory.tenant_id) not_allowed_update = [f for f in ["embd_id", "memory_type"] if f in to_update and memory_size > 0] if not_allowed_update: return get_error_argument_result(f"Can't update {not_allowed_update} when memory isn't empty.") if "memory_type" in to_update: if "system_prompt" not in to_update and judge_system_prompt_is_default(current_memory.system_prompt, current_memory.memory_type): # update old default prompt, assemble a new one to_update["system_prompt"] = PromptAssembler.assemble_system_prompt({"memory_type": to_update["memory_type"]}) try: MemoryService.update_memory(current_memory.tenant_id, memory_id, to_update) updated_memory = MemoryService.get_by_memory_id(memory_id) return get_json_result(message=True, data=format_ret_data_from_memory(updated_memory)) except Exception as e: logging.error(e) return get_json_result(message=str(e), code=RetCode.SERVER_ERROR) @manager.route("/<memory_id>", methods=["DELETE"]) # noqa: F821 @login_required async def delete_memory(memory_id): memory = MemoryService.get_by_memory_id(memory_id) if not memory: return get_json_result(message=True, code=RetCode.NOT_FOUND) try: MemoryService.delete_memory(memory_id) if MessageService.has_index(memory.tenant_id, memory_id): MessageService.delete_message({"memory_id": memory_id}, memory.tenant_id, memory_id) return get_json_result(message=True) except Exception as e: logging.error(e) return get_json_result(message=str(e), code=RetCode.SERVER_ERROR) @manager.route("", methods=["GET"]) # noqa: F821 @login_required async def list_memory(): args = request.args try: tenant_ids = args.getlist("tenant_id") memory_types = args.getlist("memory_type") storage_type = args.get("storage_type") keywords = args.get("keywords", "") page = int(args.get("page", 1)) page_size = int(args.get("page_size", 50)) # make filter dict filter_dict = {"memory_type": memory_types, "storage_type": storage_type} if not tenant_ids: # restrict to current user's tenants user_tenants = UserTenantService.get_user_tenant_relation_by_user_id(current_user.id) filter_dict["tenant_id"] = [tenant["tenant_id"] for tenant in user_tenants] else: filter_dict["tenant_id"] = tenant_ids memory_list, count = MemoryService.get_by_filter(filter_dict, keywords, page, page_size) [memory.update({"memory_type": get_memory_type_human(memory["memory_type"])}) for memory in memory_list] return get_json_result(message=True, data={"memory_list": memory_list, "total_count": count}) except Exception as e: logging.error(e) return get_json_result(message=str(e), code=RetCode.SERVER_ERROR) @manager.route("/<memory_id>/config", methods=["GET"]) # noqa: F821 @login_required async def get_memory_config(memory_id): memory = MemoryService.get_with_owner_name_by_id(memory_id) if not memory: return get_json_result(code=RetCode.NOT_FOUND, message=f"Memory '{memory_id}' not found.") return get_json_result(message=True, data=format_ret_data_from_memory(memory)) @manager.route("/<memory_id>", methods=["GET"]) # noqa: F821 @login_required async def get_memory_detail(memory_id): args = request.args agent_ids = args.getlist("agent_id") keywords = args.get("keywords", "") keywords = keywords.strip() page = int(args.get("page", 1)) page_size = int(args.get("page_size", 50)) memory = MemoryService.get_by_memory_id(memory_id) if not memory: return get_json_result(code=RetCode.NOT_FOUND, message=f"Memory '{memory_id}' not found.") messages = MessageService.list_message( memory.tenant_id, memory_id, agent_ids, keywords, page, page_size) agent_name_mapping = {} if messages["message_list"]: agent_list = UserCanvasService.get_basic_info_by_canvas_ids([message["agent_id"] for message in messages["message_list"]]) agent_name_mapping = {agent["id"]: agent["title"] for agent in agent_list} for message in messages["message_list"]: message["agent_name"] = agent_name_mapping.get(message["agent_id"], "Unknown") return get_json_result(data={"messages": messages, "storage_type": memory.storage_type}, message=True)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/messages_app.py
api/apps/messages_app.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 quart import request from api.apps import login_required from api.db.services.memory_service import MemoryService from common.time_utils import current_timestamp, timestamp_to_date from memory.services.messages import MessageService from api.db.joint_services import memory_message_service from api.utils.api_utils import validate_request, get_request_json, get_error_argument_result, get_json_result from common.constants import RetCode @manager.route("", methods=["POST"]) # noqa: F821 @login_required @validate_request("memory_id", "agent_id", "session_id", "user_input", "agent_response") async def add_message(): req = await get_request_json() memory_ids = req["memory_id"] agent_id = req["agent_id"] session_id = req["session_id"] user_id = req["user_id"] if req.get("user_id") else "" user_input = req["user_input"] agent_response = req["agent_response"] res = [] for memory_id in memory_ids: success, msg = await memory_message_service.save_to_memory( memory_id, { "user_id": user_id, "agent_id": agent_id, "session_id": session_id, "user_input": user_input, "agent_response": agent_response } ) res.append({ "memory_id": memory_id, "success": success, "message": msg }) if all([r["success"] for r in res]): return get_json_result(message="Successfully added to memories.") return get_json_result(code=RetCode.SERVER_ERROR, message="Some messages failed to add.", data=res) @manager.route("/<memory_id>:<message_id>", methods=["DELETE"]) # noqa: F821 @login_required async def forget_message(memory_id: str, message_id: int): memory = MemoryService.get_by_memory_id(memory_id) if not memory: return get_json_result(code=RetCode.NOT_FOUND, message=f"Memory '{memory_id}' not found.") forget_time = timestamp_to_date(current_timestamp()) update_succeed = MessageService.update_message( {"memory_id": memory_id, "message_id": int(message_id)}, {"forget_at": forget_time}, memory.tenant_id, memory_id) if update_succeed: return get_json_result(message=update_succeed) else: return get_json_result(code=RetCode.SERVER_ERROR, message=f"Failed to forget message '{message_id}' in memory '{memory_id}'.") @manager.route("/<memory_id>:<message_id>", methods=["PUT"]) # noqa: F821 @login_required @validate_request("status") async def update_message(memory_id: str, message_id: int): req = await get_request_json() status = req["status"] if not isinstance(status, bool): return get_error_argument_result("Status must be a boolean.") memory = MemoryService.get_by_memory_id(memory_id) if not memory: return get_json_result(code=RetCode.NOT_FOUND, message=f"Memory '{memory_id}' not found.") update_succeed = MessageService.update_message({"memory_id": memory_id, "message_id": int(message_id)}, {"status": status}, memory.tenant_id, memory_id) if update_succeed: return get_json_result(message=update_succeed) else: return get_json_result(code=RetCode.SERVER_ERROR, message=f"Failed to set status for message '{message_id}' in memory '{memory_id}'.") @manager.route("/search", methods=["GET"]) # noqa: F821 @login_required async def search_message(): args = request.args print(args, flush=True) empty_fields = [f for f in ["memory_id", "query"] if not args.get(f)] if empty_fields: return get_error_argument_result(f"{', '.join(empty_fields)} can't be empty.") memory_ids = args.getlist("memory_id") query = args.get("query") similarity_threshold = float(args.get("similarity_threshold", 0.2)) keywords_similarity_weight = float(args.get("keywords_similarity_weight", 0.7)) top_n = int(args.get("top_n", 5)) agent_id = args.get("agent_id", "") session_id = args.get("session_id", "") filter_dict = { "memory_id": memory_ids, "agent_id": agent_id, "session_id": session_id } params = { "query": query, "similarity_threshold": similarity_threshold, "keywords_similarity_weight": keywords_similarity_weight, "top_n": top_n } res = memory_message_service.query_message(filter_dict, params) return get_json_result(message=True, data=res) @manager.route("", methods=["GET"]) # noqa: F821 @login_required async def get_messages(): args = request.args memory_ids = args.getlist("memory_id") agent_id = args.get("agent_id", "") session_id = args.get("session_id", "") limit = int(args.get("limit", 10)) if not memory_ids: return get_error_argument_result("memory_ids is required.") memory_list = MemoryService.get_by_ids(memory_ids) uids = [memory.tenant_id for memory in memory_list] res = MessageService.get_recent_messages( uids, memory_ids, agent_id, session_id, limit ) return get_json_result(message=True, data=res) @manager.route("/<memory_id>:<message_id>/content", methods=["GET"]) # noqa: F821 @login_required async def get_message_content(memory_id:str, message_id: int): memory = MemoryService.get_by_memory_id(memory_id) if not memory: return get_json_result(code=RetCode.NOT_FOUND, message=f"Memory '{memory_id}' not found.") res = MessageService.get_by_message_id(memory_id, message_id, memory.tenant_id) if res: return get_json_result(message=True, data=res) else: return get_json_result(code=RetCode.NOT_FOUND, message=f"Message '{message_id}' in memory '{memory_id}' not found.")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/kb_app.py
api/apps/kb_app.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 random import re import asyncio from quart import request import numpy as np from api.db.services.connector_service import Connector2KbService from api.db.services.llm_service import LLMBundle from api.db.services.document_service import DocumentService, queue_raptor_o_graphrag_tasks from api.db.services.file2document_service import File2DocumentService from api.db.services.file_service import FileService from api.db.services.pipeline_operation_log_service import PipelineOperationLogService from api.db.services.task_service import TaskService, GRAPH_RAPTOR_FAKE_DOC_ID from api.db.services.user_service import TenantService, UserTenantService from api.utils.api_utils import get_error_data_result, server_error_response, get_data_error_result, validate_request, not_allowed_parameters, \ get_request_json from api.db import VALID_FILE_TYPES from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.db_models import File from api.utils.api_utils import get_json_result from rag.nlp import search from api.constants import DATASET_NAME_LIMIT from rag.utils.redis_conn import REDIS_CONN from common.constants import RetCode, PipelineTaskType, StatusEnum, VALID_TASK_STATUS, FileSource, LLMType, PAGERANK_FLD from common import settings from common.doc_store.doc_store_base import OrderByExpr from api.apps import login_required, current_user @manager.route('/create', methods=['post']) # noqa: F821 @login_required @validate_request("name") async def create(): req = await get_request_json() e, res = KnowledgebaseService.create_with_name( name = req.pop("name", None), tenant_id = current_user.id, parser_id = req.pop("parser_id", None), **req ) if not e: return res try: if not KnowledgebaseService.save(**res): return get_data_error_result() return get_json_result(data={"kb_id":res["id"]}) except Exception as e: return server_error_response(e) @manager.route('/update', methods=['post']) # noqa: F821 @login_required @validate_request("kb_id", "name", "description", "parser_id") @not_allowed_parameters("id", "tenant_id", "created_by", "create_time", "update_time", "create_date", "update_date", "created_by") async def update(): req = await get_request_json() if not isinstance(req["name"], str): return get_data_error_result(message="Dataset name must be string.") if req["name"].strip() == "": return get_data_error_result(message="Dataset name can't be empty.") if len(req["name"].encode("utf-8")) > DATASET_NAME_LIMIT: return get_data_error_result( message=f"Dataset name length is {len(req['name'])} which is large than {DATASET_NAME_LIMIT}") req["name"] = req["name"].strip() if not KnowledgebaseService.accessible4deletion(req["kb_id"], current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) try: if not KnowledgebaseService.query( created_by=current_user.id, id=req["kb_id"]): return get_json_result( data=False, message='Only owner of dataset authorized for this operation.', code=RetCode.OPERATING_ERROR) e, kb = KnowledgebaseService.get_by_id(req["kb_id"]) # Rename folder in FileService if e and req["name"].lower() != kb.name.lower(): FileService.filter_update( [ File.tenant_id == kb.tenant_id, File.source_type == FileSource.KNOWLEDGEBASE, File.type == "folder", File.name == kb.name, ], {"name": req["name"]}, ) if not e: return get_data_error_result( message="Can't find this dataset!") if req["name"].lower() != kb.name.lower() \ and len( KnowledgebaseService.query(name=req["name"], tenant_id=current_user.id, status=StatusEnum.VALID.value)) >= 1: return get_data_error_result( message="Duplicated dataset name.") del req["kb_id"] connectors = [] if "connectors" in req: connectors = req["connectors"] del req["connectors"] if not KnowledgebaseService.update_by_id(kb.id, req): return get_data_error_result() if kb.pagerank != req.get("pagerank", 0): if req.get("pagerank", 0) > 0: await asyncio.to_thread( settings.docStoreConn.update, {"kb_id": kb.id}, {PAGERANK_FLD: req["pagerank"]}, search.index_name(kb.tenant_id), kb.id, ) else: # Elasticsearch requires PAGERANK_FLD be non-zero! await asyncio.to_thread( settings.docStoreConn.update, {"exists": PAGERANK_FLD}, {"remove": PAGERANK_FLD}, search.index_name(kb.tenant_id), kb.id, ) e, kb = KnowledgebaseService.get_by_id(kb.id) if not e: return get_data_error_result( message="Database error (Knowledgebase rename)!") errors = Connector2KbService.link_connectors(kb.id, [conn for conn in connectors], current_user.id) if errors: logging.error("Link KB errors: ", errors) kb = kb.to_dict() kb.update(req) kb["connectors"] = connectors return get_json_result(data=kb) except Exception as e: return server_error_response(e) @manager.route('/update_metadata_setting', methods=['post']) # noqa: F821 @login_required @validate_request("kb_id", "metadata") async def update_metadata_setting(): req = await get_request_json() e, kb = KnowledgebaseService.get_by_id(req["kb_id"]) if not e: return get_data_error_result( message="Database error (Knowledgebase rename)!") kb = kb.to_dict() kb["parser_config"]["metadata"] = req["metadata"] KnowledgebaseService.update_by_id(kb["id"], kb) return get_json_result(data=kb) @manager.route('/detail', methods=['GET']) # noqa: F821 @login_required def detail(): kb_id = request.args["kb_id"] try: tenants = UserTenantService.query(user_id=current_user.id) for tenant in tenants: if KnowledgebaseService.query( tenant_id=tenant.tenant_id, id=kb_id): break else: return get_json_result( data=False, message='Only owner of dataset authorized for this operation.', code=RetCode.OPERATING_ERROR) kb = KnowledgebaseService.get_detail(kb_id) if not kb: return get_data_error_result( message="Can't find this dataset!") kb["size"] = DocumentService.get_total_size_by_kb_id(kb_id=kb["id"],keywords="", run_status=[], types=[]) kb["connectors"] = Connector2KbService.list_connectors(kb_id) for key in ["graphrag_task_finish_at", "raptor_task_finish_at", "mindmap_task_finish_at"]: if finish_at := kb.get(key): kb[key] = finish_at.strftime("%Y-%m-%d %H:%M:%S") return get_json_result(data=kb) except Exception as e: return server_error_response(e) @manager.route('/list', methods=['POST']) # noqa: F821 @login_required async def list_kbs(): args = request.args keywords = args.get("keywords", "") page_number = int(args.get("page", 0)) items_per_page = int(args.get("page_size", 0)) parser_id = args.get("parser_id") orderby = args.get("orderby", "create_time") if args.get("desc", "true").lower() == "false": desc = False else: desc = True req = await get_request_json() owner_ids = req.get("owner_ids", []) try: if not owner_ids: tenants = TenantService.get_joined_tenants_by_user_id(current_user.id) tenants = [m["tenant_id"] for m in tenants] kbs, total = KnowledgebaseService.get_by_tenant_ids( tenants, current_user.id, page_number, items_per_page, orderby, desc, keywords, parser_id) else: tenants = owner_ids kbs, total = KnowledgebaseService.get_by_tenant_ids( tenants, current_user.id, 0, 0, orderby, desc, keywords, parser_id) kbs = [kb for kb in kbs if kb["tenant_id"] in tenants] total = len(kbs) if page_number and items_per_page: kbs = kbs[(page_number-1)*items_per_page:page_number*items_per_page] return get_json_result(data={"kbs": kbs, "total": total}) except Exception as e: return server_error_response(e) @manager.route('/rm', methods=['post']) # noqa: F821 @login_required @validate_request("kb_id") async def rm(): req = await get_request_json() if not KnowledgebaseService.accessible4deletion(req["kb_id"], current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) try: kbs = KnowledgebaseService.query( created_by=current_user.id, id=req["kb_id"]) if not kbs: return get_json_result( data=False, message='Only owner of dataset authorized for this operation.', code=RetCode.OPERATING_ERROR) def _rm_sync(): for doc in DocumentService.query(kb_id=req["kb_id"]): if not DocumentService.remove_document(doc, kbs[0].tenant_id): return get_data_error_result( message="Database error (Document removal)!") f2d = File2DocumentService.get_by_document_id(doc.id) if f2d: FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id]) File2DocumentService.delete_by_document_id(doc.id) FileService.filter_delete( [ File.tenant_id == kbs[0].tenant_id, File.source_type == FileSource.KNOWLEDGEBASE, File.type == "folder", File.name == kbs[0].name, ] ) if not KnowledgebaseService.delete_by_id(req["kb_id"]): return get_data_error_result( message="Database error (Knowledgebase removal)!") for kb in kbs: settings.docStoreConn.delete({"kb_id": kb.id}, search.index_name(kb.tenant_id), kb.id) settings.docStoreConn.delete_idx(search.index_name(kb.tenant_id), kb.id) if hasattr(settings.STORAGE_IMPL, 'remove_bucket'): settings.STORAGE_IMPL.remove_bucket(kb.id) return get_json_result(data=True) return await asyncio.to_thread(_rm_sync) except Exception as e: return server_error_response(e) @manager.route('/<kb_id>/tags', methods=['GET']) # noqa: F821 @login_required def list_tags(kb_id): if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) tenants = UserTenantService.get_tenants_by_user_id(current_user.id) tags = [] for tenant in tenants: tags += settings.retriever.all_tags(tenant["tenant_id"], [kb_id]) return get_json_result(data=tags) @manager.route('/tags', methods=['GET']) # noqa: F821 @login_required def list_tags_from_kbs(): kb_ids = request.args.get("kb_ids", "").split(",") for kb_id in kb_ids: if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) tenants = UserTenantService.get_tenants_by_user_id(current_user.id) tags = [] for tenant in tenants: tags += settings.retriever.all_tags(tenant["tenant_id"], kb_ids) return get_json_result(data=tags) @manager.route('/<kb_id>/rm_tags', methods=['POST']) # noqa: F821 @login_required async def rm_tags(kb_id): req = await get_request_json() if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) e, kb = KnowledgebaseService.get_by_id(kb_id) for t in req["tags"]: settings.docStoreConn.update({"tag_kwd": t, "kb_id": [kb_id]}, {"remove": {"tag_kwd": t}}, search.index_name(kb.tenant_id), kb_id) return get_json_result(data=True) @manager.route('/<kb_id>/rename_tag', methods=['POST']) # noqa: F821 @login_required async def rename_tags(kb_id): req = await get_request_json() if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) e, kb = KnowledgebaseService.get_by_id(kb_id) settings.docStoreConn.update({"tag_kwd": req["from_tag"], "kb_id": [kb_id]}, {"remove": {"tag_kwd": req["from_tag"].strip()}, "add": {"tag_kwd": req["to_tag"]}}, search.index_name(kb.tenant_id), kb_id) return get_json_result(data=True) @manager.route('/<kb_id>/knowledge_graph', methods=['GET']) # noqa: F821 @login_required def knowledge_graph(kb_id): if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) _, kb = KnowledgebaseService.get_by_id(kb_id) req = { "kb_id": [kb_id], "knowledge_graph_kwd": ["graph"] } obj = {"graph": {}, "mind_map": {}} if not settings.docStoreConn.index_exist(search.index_name(kb.tenant_id), kb_id): return get_json_result(data=obj) sres = settings.retriever.search(req, search.index_name(kb.tenant_id), [kb_id]) if not len(sres.ids): return get_json_result(data=obj) for id in sres.ids[:1]: ty = sres.field[id]["knowledge_graph_kwd"] try: content_json = json.loads(sres.field[id]["content_with_weight"]) except Exception: continue obj[ty] = content_json if "nodes" in obj["graph"]: obj["graph"]["nodes"] = sorted(obj["graph"]["nodes"], key=lambda x: x.get("pagerank", 0), reverse=True)[:256] if "edges" in obj["graph"]: node_id_set = { o["id"] for o in obj["graph"]["nodes"] } filtered_edges = [o for o in obj["graph"]["edges"] if o["source"] != o["target"] and o["source"] in node_id_set and o["target"] in node_id_set] obj["graph"]["edges"] = sorted(filtered_edges, key=lambda x: x.get("weight", 0), reverse=True)[:128] return get_json_result(data=obj) @manager.route('/<kb_id>/knowledge_graph', methods=['DELETE']) # noqa: F821 @login_required def delete_knowledge_graph(kb_id): if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) _, kb = KnowledgebaseService.get_by_id(kb_id) settings.docStoreConn.delete({"knowledge_graph_kwd": ["graph", "subgraph", "entity", "relation"]}, search.index_name(kb.tenant_id), kb_id) return get_json_result(data=True) @manager.route("/get_meta", methods=["GET"]) # noqa: F821 @login_required def get_meta(): kb_ids = request.args.get("kb_ids", "").split(",") for kb_id in kb_ids: if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) return get_json_result(data=DocumentService.get_meta_by_kbs(kb_ids)) @manager.route("/basic_info", methods=["GET"]) # noqa: F821 @login_required def get_basic_info(): kb_id = request.args.get("kb_id", "") if not KnowledgebaseService.accessible(kb_id, current_user.id): return get_json_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) basic_info = DocumentService.knowledgebase_basic_info(kb_id) return get_json_result(data=basic_info) @manager.route("/list_pipeline_logs", methods=["POST"]) # noqa: F821 @login_required async def list_pipeline_logs(): kb_id = request.args.get("kb_id") if not kb_id: return get_json_result(data=False, message='Lack of "KB ID"', code=RetCode.ARGUMENT_ERROR) keywords = request.args.get("keywords", "") page_number = int(request.args.get("page", 0)) items_per_page = int(request.args.get("page_size", 0)) orderby = request.args.get("orderby", "create_time") if request.args.get("desc", "true").lower() == "false": desc = False else: desc = True create_date_from = request.args.get("create_date_from", "") create_date_to = request.args.get("create_date_to", "") if create_date_to > create_date_from: return get_data_error_result(message="Create data filter is abnormal.") req = await get_request_json() operation_status = req.get("operation_status", []) if operation_status: invalid_status = {s for s in operation_status if s not in VALID_TASK_STATUS} if invalid_status: return get_data_error_result(message=f"Invalid filter operation_status status conditions: {', '.join(invalid_status)}") types = req.get("types", []) if types: invalid_types = {t for t in types if t not in VALID_FILE_TYPES} if invalid_types: return get_data_error_result(message=f"Invalid filter conditions: {', '.join(invalid_types)} type{'s' if len(invalid_types) > 1 else ''}") suffix = req.get("suffix", []) try: logs, tol = PipelineOperationLogService.get_file_logs_by_kb_id(kb_id, page_number, items_per_page, orderby, desc, keywords, operation_status, types, suffix, create_date_from, create_date_to) return get_json_result(data={"total": tol, "logs": logs}) except Exception as e: return server_error_response(e) @manager.route("/list_pipeline_dataset_logs", methods=["POST"]) # noqa: F821 @login_required async def list_pipeline_dataset_logs(): kb_id = request.args.get("kb_id") if not kb_id: return get_json_result(data=False, message='Lack of "KB ID"', code=RetCode.ARGUMENT_ERROR) page_number = int(request.args.get("page", 0)) items_per_page = int(request.args.get("page_size", 0)) orderby = request.args.get("orderby", "create_time") if request.args.get("desc", "true").lower() == "false": desc = False else: desc = True create_date_from = request.args.get("create_date_from", "") create_date_to = request.args.get("create_date_to", "") if create_date_to > create_date_from: return get_data_error_result(message="Create data filter is abnormal.") req = await get_request_json() operation_status = req.get("operation_status", []) if operation_status: invalid_status = {s for s in operation_status if s not in VALID_TASK_STATUS} if invalid_status: return get_data_error_result(message=f"Invalid filter operation_status status conditions: {', '.join(invalid_status)}") try: logs, tol = PipelineOperationLogService.get_dataset_logs_by_kb_id(kb_id, page_number, items_per_page, orderby, desc, operation_status, create_date_from, create_date_to) return get_json_result(data={"total": tol, "logs": logs}) except Exception as e: return server_error_response(e) @manager.route("/delete_pipeline_logs", methods=["POST"]) # noqa: F821 @login_required async def delete_pipeline_logs(): kb_id = request.args.get("kb_id") if not kb_id: return get_json_result(data=False, message='Lack of "KB ID"', code=RetCode.ARGUMENT_ERROR) req = await get_request_json() log_ids = req.get("log_ids", []) PipelineOperationLogService.delete_by_ids(log_ids) return get_json_result(data=True) @manager.route("/pipeline_log_detail", methods=["GET"]) # noqa: F821 @login_required def pipeline_log_detail(): log_id = request.args.get("log_id") if not log_id: return get_json_result(data=False, message='Lack of "Pipeline log ID"', code=RetCode.ARGUMENT_ERROR) ok, log = PipelineOperationLogService.get_by_id(log_id) if not ok: return get_data_error_result(message="Invalid pipeline log ID") return get_json_result(data=log.to_dict()) @manager.route("/run_graphrag", methods=["POST"]) # noqa: F821 @login_required async def run_graphrag(): req = await get_request_json() kb_id = req.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_error_data_result(message="Invalid Knowledgebase ID") task_id = kb.graphrag_task_id if task_id: ok, task = TaskService.get_by_id(task_id) if not ok: logging.warning(f"A valid GraphRAG task id is expected for kb {kb_id}") if task and task.progress not in [-1, 1]: return get_error_data_result(message=f"Task {task_id} in progress with status {task.progress}. A Graph Task is already running.") documents, _ = DocumentService.get_by_kb_id( kb_id=kb_id, page_number=0, items_per_page=0, orderby="create_time", desc=False, keywords="", run_status=[], types=[], suffix=[], ) if not documents: return get_error_data_result(message=f"No documents in Knowledgebase {kb_id}") sample_document = documents[0] document_ids = [document["id"] for document in documents] task_id = queue_raptor_o_graphrag_tasks(sample_doc_id=sample_document, ty="graphrag", priority=0, fake_doc_id=GRAPH_RAPTOR_FAKE_DOC_ID, doc_ids=list(document_ids)) if not KnowledgebaseService.update_by_id(kb.id, {"graphrag_task_id": task_id}): logging.warning(f"Cannot save graphrag_task_id for kb {kb_id}") return get_json_result(data={"graphrag_task_id": task_id}) @manager.route("/trace_graphrag", methods=["GET"]) # noqa: F821 @login_required def trace_graphrag(): kb_id = request.args.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_error_data_result(message="Invalid Knowledgebase ID") task_id = kb.graphrag_task_id if not task_id: return get_json_result(data={}) ok, task = TaskService.get_by_id(task_id) if not ok: return get_json_result(data={}) return get_json_result(data=task.to_dict()) @manager.route("/run_raptor", methods=["POST"]) # noqa: F821 @login_required async def run_raptor(): req = await get_request_json() kb_id = req.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_error_data_result(message="Invalid Knowledgebase ID") task_id = kb.raptor_task_id if task_id: ok, task = TaskService.get_by_id(task_id) if not ok: logging.warning(f"A valid RAPTOR task id is expected for kb {kb_id}") if task and task.progress not in [-1, 1]: return get_error_data_result(message=f"Task {task_id} in progress with status {task.progress}. A RAPTOR Task is already running.") documents, _ = DocumentService.get_by_kb_id( kb_id=kb_id, page_number=0, items_per_page=0, orderby="create_time", desc=False, keywords="", run_status=[], types=[], suffix=[], ) if not documents: return get_error_data_result(message=f"No documents in Knowledgebase {kb_id}") sample_document = documents[0] document_ids = [document["id"] for document in documents] task_id = queue_raptor_o_graphrag_tasks(sample_doc_id=sample_document, ty="raptor", priority=0, fake_doc_id=GRAPH_RAPTOR_FAKE_DOC_ID, doc_ids=list(document_ids)) if not KnowledgebaseService.update_by_id(kb.id, {"raptor_task_id": task_id}): logging.warning(f"Cannot save raptor_task_id for kb {kb_id}") return get_json_result(data={"raptor_task_id": task_id}) @manager.route("/trace_raptor", methods=["GET"]) # noqa: F821 @login_required def trace_raptor(): kb_id = request.args.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_error_data_result(message="Invalid Knowledgebase ID") task_id = kb.raptor_task_id if not task_id: return get_json_result(data={}) ok, task = TaskService.get_by_id(task_id) if not ok: return get_error_data_result(message="RAPTOR Task Not Found or Error Occurred") return get_json_result(data=task.to_dict()) @manager.route("/run_mindmap", methods=["POST"]) # noqa: F821 @login_required async def run_mindmap(): req = await get_request_json() kb_id = req.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_error_data_result(message="Invalid Knowledgebase ID") task_id = kb.mindmap_task_id if task_id: ok, task = TaskService.get_by_id(task_id) if not ok: logging.warning(f"A valid Mindmap task id is expected for kb {kb_id}") if task and task.progress not in [-1, 1]: return get_error_data_result(message=f"Task {task_id} in progress with status {task.progress}. A Mindmap Task is already running.") documents, _ = DocumentService.get_by_kb_id( kb_id=kb_id, page_number=0, items_per_page=0, orderby="create_time", desc=False, keywords="", run_status=[], types=[], suffix=[], ) if not documents: return get_error_data_result(message=f"No documents in Knowledgebase {kb_id}") sample_document = documents[0] document_ids = [document["id"] for document in documents] task_id = queue_raptor_o_graphrag_tasks(sample_doc_id=sample_document, ty="mindmap", priority=0, fake_doc_id=GRAPH_RAPTOR_FAKE_DOC_ID, doc_ids=list(document_ids)) if not KnowledgebaseService.update_by_id(kb.id, {"mindmap_task_id": task_id}): logging.warning(f"Cannot save mindmap_task_id for kb {kb_id}") return get_json_result(data={"mindmap_task_id": task_id}) @manager.route("/trace_mindmap", methods=["GET"]) # noqa: F821 @login_required def trace_mindmap(): kb_id = request.args.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_error_data_result(message="Invalid Knowledgebase ID") task_id = kb.mindmap_task_id if not task_id: return get_json_result(data={}) ok, task = TaskService.get_by_id(task_id) if not ok: return get_error_data_result(message="Mindmap Task Not Found or Error Occurred") return get_json_result(data=task.to_dict()) @manager.route("/unbind_task", methods=["DELETE"]) # noqa: F821 @login_required def delete_kb_task(): kb_id = request.args.get("kb_id", "") if not kb_id: return get_error_data_result(message='Lack of "KB ID"') ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: return get_json_result(data=True) pipeline_task_type = request.args.get("pipeline_task_type", "") if not pipeline_task_type or pipeline_task_type not in [PipelineTaskType.GRAPH_RAG, PipelineTaskType.RAPTOR, PipelineTaskType.MINDMAP]: return get_error_data_result(message="Invalid task type") def cancel_task(task_id): REDIS_CONN.set(f"{task_id}-cancel", "x") kb_task_id_field: str = "" kb_task_finish_at: str = "" match pipeline_task_type: case PipelineTaskType.GRAPH_RAG: kb_task_id_field = "graphrag_task_id" task_id = kb.graphrag_task_id kb_task_finish_at = "graphrag_task_finish_at" cancel_task(task_id) settings.docStoreConn.delete({"knowledge_graph_kwd": ["graph", "subgraph", "entity", "relation"]}, search.index_name(kb.tenant_id), kb_id) case PipelineTaskType.RAPTOR: kb_task_id_field = "raptor_task_id" task_id = kb.raptor_task_id kb_task_finish_at = "raptor_task_finish_at" cancel_task(task_id) settings.docStoreConn.delete({"raptor_kwd": ["raptor"]}, search.index_name(kb.tenant_id), kb_id) case PipelineTaskType.MINDMAP: kb_task_id_field = "mindmap_task_id" task_id = kb.mindmap_task_id kb_task_finish_at = "mindmap_task_finish_at" cancel_task(task_id) case _: return get_error_data_result(message="Internal Error: Invalid task type") ok = KnowledgebaseService.update_by_id(kb_id, {kb_task_id_field: "", kb_task_finish_at: None}) if not ok: return server_error_response(f"Internal error: cannot delete task {pipeline_task_type}") return get_json_result(data=True) @manager.route("/check_embedding", methods=["post"]) # noqa: F821 @login_required async def check_embedding(): def _guess_vec_field(src: dict) -> str | None: for k in src or {}: if k.endswith("_vec"): return k return None def _as_float_vec(v): if v is None: return [] if isinstance(v, str): return [float(x) for x in v.split("\t") if x != ""] if isinstance(v, (list, tuple, np.ndarray)): return [float(x) for x in v] return [] def _to_1d(x): a = np.asarray(x, dtype=np.float32) return a.reshape(-1) def _cos_sim(a, b, eps=1e-12): a = _to_1d(a) b = _to_1d(b) na = np.linalg.norm(a) nb = np.linalg.norm(b) if na < eps or nb < eps: return 0.0 return float(np.dot(a, b) / (na * nb)) def sample_random_chunks_with_vectors( docStoreConn, tenant_id: str, kb_id: str, n: int = 5, base_fields=("docnm_kwd","doc_id","content_with_weight","page_num_int","position_int","top_int"), ): index_nm = search.index_name(tenant_id) res0 = docStoreConn.search( select_fields=[], highlight_fields=[], condition={"kb_id": kb_id, "available_int": 1}, match_expressions=[], order_by=OrderByExpr(), offset=0, limit=1, index_names=index_nm, knowledgebase_ids=[kb_id] ) total = docStoreConn.get_total(res0) if total <= 0: return [] n = min(n, total) offsets = sorted(random.sample(range(min(total,1000)), n)) out = [] for off in offsets: res1 = docStoreConn.search(
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/mcp_server_app.py
api/apps/mcp_server_app.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 quart import Response, request from api.apps import current_user, login_required from api.db.db_models import MCPServer from api.db.services.mcp_server_service import MCPServerService from api.db.services.user_service import TenantService from common.constants import RetCode, VALID_MCP_SERVER_TYPES from common.misc_utils import get_uuid from api.utils.api_utils import get_data_error_result, get_json_result, get_mcp_tools, get_request_json, server_error_response, validate_request from api.utils.web_utils import get_float, safe_json_parse from common.mcp_tool_call_conn import MCPToolCallSession, close_multiple_mcp_toolcall_sessions @manager.route("/list", methods=["POST"]) # noqa: F821 @login_required async def list_mcp() -> Response: keywords = request.args.get("keywords", "") page_number = int(request.args.get("page", 0)) items_per_page = int(request.args.get("page_size", 0)) orderby = request.args.get("orderby", "create_time") if request.args.get("desc", "true").lower() == "false": desc = False else: desc = True req = await get_request_json() mcp_ids = req.get("mcp_ids", []) try: servers = MCPServerService.get_servers(current_user.id, mcp_ids, 0, 0, orderby, desc, keywords) or [] total = len(servers) if page_number and items_per_page: servers = servers[(page_number - 1) * items_per_page : page_number * items_per_page] return get_json_result(data={"mcp_servers": servers, "total": total}) except Exception as e: return server_error_response(e) @manager.route("/detail", methods=["GET"]) # noqa: F821 @login_required def detail() -> Response: mcp_id = request.args["mcp_id"] try: mcp_server = MCPServerService.get_or_none(id=mcp_id, tenant_id=current_user.id) if mcp_server is None: return get_json_result(code=RetCode.NOT_FOUND, data=None) return get_json_result(data=mcp_server.to_dict()) except Exception as e: return server_error_response(e) @manager.route("/create", methods=["POST"]) # noqa: F821 @login_required @validate_request("name", "url", "server_type") async def create() -> Response: req = await get_request_json() server_type = req.get("server_type", "") if server_type not in VALID_MCP_SERVER_TYPES: return get_data_error_result(message="Unsupported MCP server type.") server_name = req.get("name", "") if not server_name or len(server_name.encode("utf-8")) > 255: return get_data_error_result(message=f"Invalid MCP name or length is {len(server_name)} which is large than 255.") e, _ = MCPServerService.get_by_name_and_tenant(name=server_name, tenant_id=current_user.id) if e: return get_data_error_result(message="Duplicated MCP server name.") url = req.get("url", "") if not url: return get_data_error_result(message="Invalid url.") headers = safe_json_parse(req.get("headers", {})) req["headers"] = headers variables = safe_json_parse(req.get("variables", {})) variables.pop("tools", None) timeout = get_float(req, "timeout", 10) try: req["id"] = get_uuid() req["tenant_id"] = current_user.id e, _ = TenantService.get_by_id(current_user.id) if not e: return get_data_error_result(message="Tenant not found.") mcp_server = MCPServer(id=server_name, name=server_name, url=url, server_type=server_type, variables=variables, headers=headers) server_tools, err_message = await asyncio.to_thread(get_mcp_tools, [mcp_server], timeout) if err_message: return get_data_error_result(err_message) tools = server_tools[server_name] tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool} variables["tools"] = tools req["variables"] = variables if not MCPServerService.insert(**req): return get_data_error_result("Failed to create MCP server.") return get_json_result(data=req) except Exception as e: return server_error_response(e) @manager.route("/update", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcp_id") async def update() -> Response: req = await get_request_json() mcp_id = req.get("mcp_id", "") e, mcp_server = MCPServerService.get_by_id(mcp_id) if not e or mcp_server.tenant_id != current_user.id: return get_data_error_result(message=f"Cannot find MCP server {mcp_id} for user {current_user.id}") server_type = req.get("server_type", mcp_server.server_type) if server_type and server_type not in VALID_MCP_SERVER_TYPES: return get_data_error_result(message="Unsupported MCP server type.") server_name = req.get("name", mcp_server.name) if server_name and len(server_name.encode("utf-8")) > 255: return get_data_error_result(message=f"Invalid MCP name or length is {len(server_name)} which is large than 255.") url = req.get("url", mcp_server.url) if not url: return get_data_error_result(message="Invalid url.") headers = safe_json_parse(req.get("headers", mcp_server.headers)) req["headers"] = headers variables = safe_json_parse(req.get("variables", mcp_server.variables)) variables.pop("tools", None) timeout = get_float(req, "timeout", 10) try: req["tenant_id"] = current_user.id req.pop("mcp_id", None) req["id"] = mcp_id mcp_server = MCPServer(id=server_name, name=server_name, url=url, server_type=server_type, variables=variables, headers=headers) server_tools, err_message = await asyncio.to_thread(get_mcp_tools, [mcp_server], timeout) if err_message: return get_data_error_result(err_message) tools = server_tools[server_name] tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool} variables["tools"] = tools req["variables"] = variables if not MCPServerService.filter_update([MCPServer.id == mcp_id, MCPServer.tenant_id == current_user.id], req): return get_data_error_result(message="Failed to updated MCP server.") e, updated_mcp = MCPServerService.get_by_id(req["id"]) if not e: return get_data_error_result(message="Failed to fetch updated MCP server.") return get_json_result(data=updated_mcp.to_dict()) except Exception as e: return server_error_response(e) @manager.route("/rm", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcp_ids") async def rm() -> Response: req = await get_request_json() mcp_ids = req.get("mcp_ids", []) try: req["tenant_id"] = current_user.id if not MCPServerService.delete_by_ids(mcp_ids): return get_data_error_result(message=f"Failed to delete MCP servers {mcp_ids}") return get_json_result(data=True) except Exception as e: return server_error_response(e) @manager.route("/import", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcpServers") async def import_multiple() -> Response: req = await get_request_json() servers = req.get("mcpServers", {}) if not servers: return get_data_error_result(message="No MCP servers provided.") timeout = get_float(req, "timeout", 10) results = [] try: for server_name, config in servers.items(): if not all(key in config for key in {"type", "url"}): results.append({"server": server_name, "success": False, "message": "Missing required fields (type or url)"}) continue if not server_name or len(server_name.encode("utf-8")) > 255: results.append({"server": server_name, "success": False, "message": f"Invalid MCP name or length is {len(server_name)} which is large than 255."}) continue base_name = server_name new_name = base_name counter = 0 while True: e, _ = MCPServerService.get_by_name_and_tenant(name=new_name, tenant_id=current_user.id) if not e: break new_name = f"{base_name}_{counter}" counter += 1 create_data = { "id": get_uuid(), "tenant_id": current_user.id, "name": new_name, "url": config["url"], "server_type": config["type"], "variables": {"authorization_token": config.get("authorization_token", "")}, } headers = {"authorization_token": config["authorization_token"]} if "authorization_token" in config else {} variables = {k: v for k, v in config.items() if k not in {"type", "url", "headers"}} mcp_server = MCPServer(id=new_name, name=new_name, url=config["url"], server_type=config["type"], variables=variables, headers=headers) server_tools, err_message = await asyncio.to_thread(get_mcp_tools, [mcp_server], timeout) if err_message: results.append({"server": base_name, "success": False, "message": err_message}) continue tools = server_tools[new_name] tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool} create_data["variables"]["tools"] = tools if MCPServerService.insert(**create_data): result = {"server": server_name, "success": True, "action": "created", "id": create_data["id"], "new_name": new_name} if new_name != base_name: result["message"] = f"Renamed from '{base_name}' to '{new_name}' avoid duplication" results.append(result) else: results.append({"server": server_name, "success": False, "message": "Failed to create MCP server."}) return get_json_result(data={"results": results}) except Exception as e: return server_error_response(e) @manager.route("/export", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcp_ids") async def export_multiple() -> Response: req = await get_request_json() mcp_ids = req.get("mcp_ids", []) if not mcp_ids: return get_data_error_result(message="No MCP server IDs provided.") try: exported_servers = {} for mcp_id in mcp_ids: e, mcp_server = MCPServerService.get_by_id(mcp_id) if e and mcp_server.tenant_id == current_user.id: server_key = mcp_server.name exported_servers[server_key] = { "type": mcp_server.server_type, "url": mcp_server.url, "name": mcp_server.name, "authorization_token": mcp_server.variables.get("authorization_token", ""), "tools": mcp_server.variables.get("tools", {}), } return get_json_result(data={"mcpServers": exported_servers}) except Exception as e: return server_error_response(e) @manager.route("/list_tools", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcp_ids") async def list_tools() -> Response: req = await get_request_json() mcp_ids = req.get("mcp_ids", []) if not mcp_ids: return get_data_error_result(message="No MCP server IDs provided.") timeout = get_float(req, "timeout", 10) results = {} tool_call_sessions = [] try: for mcp_id in mcp_ids: e, mcp_server = MCPServerService.get_by_id(mcp_id) if e and mcp_server.tenant_id == current_user.id: server_key = mcp_server.id cached_tools = mcp_server.variables.get("tools", {}) tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables) tool_call_sessions.append(tool_call_session) try: tools = await asyncio.to_thread(tool_call_session.get_tools, timeout) except Exception as e: return get_data_error_result(message=f"MCP list tools error: {e}") results[server_key] = [] for tool in tools: tool_dict = tool.model_dump() cached_tool = cached_tools.get(tool_dict["name"], {}) tool_dict["enabled"] = cached_tool.get("enabled", True) results[server_key].append(tool_dict) return get_json_result(data=results) except Exception as e: return server_error_response(e) finally: # PERF: blocking call to close sessions — consider moving to background thread or task queue await asyncio.to_thread(close_multiple_mcp_toolcall_sessions, tool_call_sessions) @manager.route("/test_tool", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcp_id", "tool_name", "arguments") async def test_tool() -> Response: req = await get_request_json() mcp_id = req.get("mcp_id", "") if not mcp_id: return get_data_error_result(message="No MCP server ID provided.") timeout = get_float(req, "timeout", 10) tool_name = req.get("tool_name", "") arguments = req.get("arguments", {}) if not all([tool_name, arguments]): return get_data_error_result(message="Require provide tool name and arguments.") tool_call_sessions = [] try: e, mcp_server = MCPServerService.get_by_id(mcp_id) if not e or mcp_server.tenant_id != current_user.id: return get_data_error_result(message=f"Cannot find MCP server {mcp_id} for user {current_user.id}") tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables) tool_call_sessions.append(tool_call_session) result = await asyncio.to_thread(tool_call_session.tool_call, tool_name, arguments, timeout) # PERF: blocking call to close sessions — consider moving to background thread or task queue await asyncio.to_thread(close_multiple_mcp_toolcall_sessions, tool_call_sessions) return get_json_result(data=result) except Exception as e: return server_error_response(e) @manager.route("/cache_tools", methods=["POST"]) # noqa: F821 @login_required @validate_request("mcp_id", "tools") async def cache_tool() -> Response: req = await get_request_json() mcp_id = req.get("mcp_id", "") if not mcp_id: return get_data_error_result(message="No MCP server ID provided.") tools = req.get("tools", []) e, mcp_server = MCPServerService.get_by_id(mcp_id) if not e or mcp_server.tenant_id != current_user.id: return get_data_error_result(message=f"Cannot find MCP server {mcp_id} for user {current_user.id}") variables = mcp_server.variables tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool} variables["tools"] = tools if not MCPServerService.filter_update([MCPServer.id == mcp_id, MCPServer.tenant_id == current_user.id], {"variables": variables}): return get_data_error_result(message="Failed to updated MCP server.") return get_json_result(data=tools) @manager.route("/test_mcp", methods=["POST"]) # noqa: F821 @validate_request("url", "server_type") async def test_mcp() -> Response: req = await get_request_json() url = req.get("url", "") if not url: return get_data_error_result(message="Invalid MCP url.") server_type = req.get("server_type", "") if server_type not in VALID_MCP_SERVER_TYPES: return get_data_error_result(message="Unsupported MCP server type.") timeout = get_float(req, "timeout", 10) headers = safe_json_parse(req.get("headers", {})) variables = safe_json_parse(req.get("variables", {})) mcp_server = MCPServer(id=f"{server_type}: {url}", server_type=server_type, url=url, headers=headers, variables=variables) result = [] try: tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables) try: tools = await asyncio.to_thread(tool_call_session.get_tools, timeout) except Exception as e: return get_data_error_result(message=f"Test MCP error: {e}") finally: # PERF: blocking call to close sessions — consider moving to background thread or task queue await asyncio.to_thread(close_multiple_mcp_toolcall_sessions, [tool_call_session]) for tool in tools: tool_dict = tool.model_dump() tool_dict["enabled"] = True result.append(tool_dict) return get_json_result(data=result) except Exception as e: return server_error_response(e)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/plugin_app.py
api/apps/plugin_app.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 quart import Response from api.apps import login_required from api.utils.api_utils import get_json_result from plugin import GlobalPluginManager @manager.route('/llm_tools', methods=['GET']) # noqa: F821 @login_required def llm_tools() -> Response: tools = GlobalPluginManager.get_llm_tools() tools_metadata = [t.get_metadata() for t in tools] return get_json_result(data=tools_metadata)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/auth/oauth.py
api/apps/auth/oauth.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 urllib.parse from common.http_client import async_request, sync_request class UserInfo: def __init__(self, email, username, nickname, avatar_url): self.email = email self.username = username self.nickname = nickname self.avatar_url = avatar_url def to_dict(self): return {key: value for key, value in self.__dict__.items()} class OAuthClient: def __init__(self, config): """ Initialize the OAuthClient with the provider's configuration. """ self.client_id = config["client_id"] self.client_secret = config["client_secret"] self.authorization_url = config["authorization_url"] self.token_url = config["token_url"] self.userinfo_url = config["userinfo_url"] self.redirect_uri = config["redirect_uri"] self.scope = config.get("scope", None) self.http_request_timeout = 7 def get_authorization_url(self, state=None): """ Generate the authorization URL for user login. """ params = { "client_id": self.client_id, "redirect_uri": self.redirect_uri, "response_type": "code", } if self.scope: params["scope"] = self.scope if state: params["state"] = state authorization_url = f"{self.authorization_url}?{urllib.parse.urlencode(params)}" return authorization_url def exchange_code_for_token(self, code): """ Exchange authorization code for access token. """ try: payload = { "client_id": self.client_id, "client_secret": self.client_secret, "code": code, "redirect_uri": self.redirect_uri, "grant_type": "authorization_code" } response = sync_request( "POST", self.token_url, data=payload, headers={"Accept": "application/json"}, timeout=self.http_request_timeout, ) response.raise_for_status() return response.json() except Exception as e: raise ValueError(f"Failed to exchange authorization code for token: {e}") async def async_exchange_code_for_token(self, code): """ Async variant of exchange_code_for_token using httpx. """ payload = { "client_id": self.client_id, "client_secret": self.client_secret, "code": code, "redirect_uri": self.redirect_uri, "grant_type": "authorization_code", } try: response = await async_request( "POST", self.token_url, data=payload, headers={"Accept": "application/json"}, timeout=self.http_request_timeout, ) response.raise_for_status() return response.json() except Exception as e: raise ValueError(f"Failed to exchange authorization code for token: {e}") def fetch_user_info(self, access_token, **kwargs): """ Fetch user information using access token. """ try: headers = {"Authorization": f"Bearer {access_token}"} response = sync_request("GET", self.userinfo_url, headers=headers, timeout=self.http_request_timeout) response.raise_for_status() user_info = response.json() return self.normalize_user_info(user_info) except Exception as e: raise ValueError(f"Failed to fetch user info: {e}") async def async_fetch_user_info(self, access_token, **kwargs): """Async variant of fetch_user_info using httpx.""" headers = {"Authorization": f"Bearer {access_token}"} try: response = await async_request( "GET", self.userinfo_url, headers=headers, timeout=self.http_request_timeout, ) response.raise_for_status() user_info = response.json() return self.normalize_user_info(user_info) except Exception as e: raise ValueError(f"Failed to fetch user info: {e}") def normalize_user_info(self, user_info): email = user_info.get("email") username = user_info.get("username", str(email).split("@")[0]) nickname = user_info.get("nickname", username) avatar_url = user_info.get("avatar_url", None) if avatar_url is None: avatar_url = user_info.get("picture", "") return UserInfo(email=email, username=username, nickname=nickname, avatar_url=avatar_url)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/auth/__init__.py
api/apps/auth/__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 .oauth import OAuthClient from .oidc import OIDCClient from .github import GithubOAuthClient CLIENT_TYPES = { "oauth2": OAuthClient, "oidc": OIDCClient, "github": GithubOAuthClient } def get_auth_client(config)->OAuthClient: channel_type = str(config.get("type", "")).lower() if channel_type == "": if config.get("issuer"): channel_type = "oidc" else: channel_type = "oauth2" client_class = CLIENT_TYPES.get(channel_type) if not client_class: raise ValueError(f"Unsupported type: {channel_type}") return client_class(config)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/auth/oidc.py
api/apps/auth/oidc.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 jwt from common.http_client import sync_request from .oauth import OAuthClient class OIDCClient(OAuthClient): def __init__(self, config): """ Initialize the OIDCClient with the provider's configuration. Use `issuer` as the single source of truth for configuration discovery. """ self.issuer = config.get("issuer") if not self.issuer: raise ValueError("Missing issuer in configuration.") oidc_metadata = self._load_oidc_metadata(self.issuer) config.update({ 'issuer': oidc_metadata['issuer'], 'jwks_uri': oidc_metadata['jwks_uri'], 'authorization_url': oidc_metadata['authorization_endpoint'], 'token_url': oidc_metadata['token_endpoint'], 'userinfo_url': oidc_metadata['userinfo_endpoint'] }) super().__init__(config) self.issuer = config['issuer'] self.jwks_uri = config['jwks_uri'] @staticmethod def _load_oidc_metadata(issuer): """ Load OIDC metadata from `/.well-known/openid-configuration`. """ try: metadata_url = f"{issuer}/.well-known/openid-configuration" response = sync_request("GET", metadata_url, timeout=7) response.raise_for_status() return response.json() except Exception as e: raise ValueError(f"Failed to fetch OIDC metadata: {e}") def parse_id_token(self, id_token): """ Parse and validate OIDC ID Token (JWT format) with signature verification. """ try: # Decode JWT header without verifying signature headers = jwt.get_unverified_header(id_token) # OIDC usually uses `RS256` for signing alg = headers.get("alg", "RS256") # Use PyJWT's PyJWKClient to fetch JWKS and find signing key jwks_cli = jwt.PyJWKClient(self.jwks_uri) signing_key = jwks_cli.get_signing_key_from_jwt(id_token).key # Decode and verify signature decoded_token = jwt.decode( id_token, key=signing_key, algorithms=[alg], audience=str(self.client_id), issuer=self.issuer, ) return decoded_token except Exception as e: raise ValueError(f"Error parsing ID Token: {e}") def fetch_user_info(self, access_token, id_token=None, **kwargs): """ Fetch user info. """ user_info = {} if id_token: user_info = self.parse_id_token(id_token) user_info.update(super().fetch_user_info(access_token).to_dict()) return self.normalize_user_info(user_info) async def async_fetch_user_info(self, access_token, id_token=None, **kwargs): user_info = {} if id_token: user_info = self.parse_id_token(id_token) user_info.update((await super().async_fetch_user_info(access_token)).to_dict()) return self.normalize_user_info(user_info) def normalize_user_info(self, user_info): return super().normalize_user_info(user_info)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/auth/github.py
api/apps/auth/github.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.http_client import async_request, sync_request from .oauth import OAuthClient, UserInfo class GithubOAuthClient(OAuthClient): def __init__(self, config): """ Initialize the GithubOAuthClient with the provider's configuration. """ config.update({ "authorization_url": "https://github.com/login/oauth/authorize", "token_url": "https://github.com/login/oauth/access_token", "userinfo_url": "https://api.github.com/user", "scope": "user:email" }) super().__init__(config) def fetch_user_info(self, access_token, **kwargs): """ Fetch GitHub user info (synchronous). """ user_info = {} try: headers = {"Authorization": f"Bearer {access_token}"} response = sync_request("GET", self.userinfo_url, headers=headers, timeout=self.http_request_timeout) response.raise_for_status() user_info.update(response.json()) email_response = sync_request( "GET", self.userinfo_url + "/emails", headers=headers, timeout=self.http_request_timeout ) email_response.raise_for_status() email_info = email_response.json() user_info["email"] = next((email for email in email_info if email["primary"]), None)["email"] return self.normalize_user_info(user_info) except Exception as e: raise ValueError(f"Failed to fetch github user info: {e}") async def async_fetch_user_info(self, access_token, **kwargs): """Async variant of fetch_user_info using httpx.""" user_info = {} headers = {"Authorization": f"Bearer {access_token}"} try: response = await async_request( "GET", self.userinfo_url, headers=headers, timeout=self.http_request_timeout, ) response.raise_for_status() user_info.update(response.json()) email_response = await async_request( "GET", self.userinfo_url + "/emails", headers=headers, timeout=self.http_request_timeout, ) email_response.raise_for_status() email_info = email_response.json() user_info["email"] = next((email for email in email_info if email["primary"]), None)["email"] return self.normalize_user_info(user_info) except Exception as e: raise ValueError(f"Failed to fetch github user info: {e}") def normalize_user_info(self, user_info): email = user_info.get("email") username = user_info.get("login", str(email).split("@")[0]) nickname = user_info.get("name", username) avatar_url = user_info.get("avatar_url", "") return UserInfo(email=email, username=username, nickname=nickname, avatar_url=avatar_url)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/dify_retrieval.py
api/apps/sdk/dify_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 logging from quart import jsonify from api.db.services.document_service import DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.llm_service import LLMBundle from common.metadata_utils import meta_filter, convert_conditions from api.utils.api_utils import apikey_required, build_error_result, get_request_json, validate_request from rag.app.tag import label_question from common.constants import RetCode, LLMType from common import settings @manager.route('/dify/retrieval', methods=['POST']) # noqa: F821 @apikey_required @validate_request("knowledge_id", "query") async def retrieval(tenant_id): """ Dify-compatible retrieval API --- tags: - SDK security: - ApiKeyAuth: [] parameters: - in: body name: body required: true schema: type: object required: - knowledge_id - query properties: knowledge_id: type: string description: Knowledge base ID query: type: string description: Query text use_kg: type: boolean description: Whether to use knowledge graph default: false retrieval_setting: type: object description: Retrieval configuration properties: score_threshold: type: number description: Similarity threshold default: 0.0 top_k: type: integer description: Number of results to return default: 1024 metadata_condition: type: object description: Metadata filter condition properties: conditions: type: array items: type: object properties: name: type: string description: Field name comparison_operator: type: string description: Comparison operator value: type: string description: Field value responses: 200: description: Retrieval succeeded schema: type: object properties: records: type: array items: type: object properties: content: type: string description: Content text score: type: number description: Similarity score title: type: string description: Document title metadata: type: object description: Metadata info 404: description: Knowledge base or document not found """ req = await get_request_json() question = req["query"] kb_id = req["knowledge_id"] use_kg = req.get("use_kg", False) retrieval_setting = req.get("retrieval_setting", {}) similarity_threshold = float(retrieval_setting.get("score_threshold", 0.0)) top = int(retrieval_setting.get("top_k", 1024)) metadata_condition = req.get("metadata_condition", {}) or {} metas = DocumentService.get_meta_by_kbs([kb_id]) doc_ids = [] try: e, kb = KnowledgebaseService.get_by_id(kb_id) if not e: return build_error_result(message="Knowledgebase not found!", code=RetCode.NOT_FOUND) embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id) if metadata_condition: doc_ids.extend(meta_filter(metas, convert_conditions(metadata_condition), metadata_condition.get("logic", "and"))) if not doc_ids and metadata_condition: doc_ids = ["-999"] ranks = settings.retriever.retrieval( question, embd_mdl, kb.tenant_id, [kb_id], page=1, page_size=top, similarity_threshold=similarity_threshold, vector_similarity_weight=0.3, top=top, doc_ids=doc_ids, rank_feature=label_question(question, [kb]) ) if use_kg: ck = await settings.kg_retriever.retrieval(question, [tenant_id], [kb_id], embd_mdl, LLMBundle(kb.tenant_id, LLMType.CHAT)) if ck["content_with_weight"]: ranks["chunks"].insert(0, ck) records = [] for c in ranks["chunks"]: e, doc = DocumentService.get_by_id(c["doc_id"]) c.pop("vector", None) meta = getattr(doc, 'meta_fields', {}) meta["doc_id"] = c["doc_id"] records.append({ "content": c["content_with_weight"], "score": c["similarity"], "title": c["docnm_kwd"], "metadata": meta }) return jsonify({"records": records}) except Exception as e: if str(e).find("not_found") > 0: return build_error_result( message='No chunk found! Check the chunk status please!', code=RetCode.NOT_FOUND ) logging.exception(e) return build_error_result(message=str(e), code=RetCode.SERVER_ERROR)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/chat.py
api/apps/sdk/chat.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 from quart import request from api.db.services.dialog_service import DialogService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.tenant_llm_service import TenantLLMService from api.db.services.user_service import TenantService from common.misc_utils import get_uuid from common.constants import RetCode, StatusEnum from api.utils.api_utils import check_duplicate_ids, get_error_data_result, get_result, token_required, get_request_json @manager.route("/chats", methods=["POST"]) # noqa: F821 @token_required async def create(tenant_id): req = await get_request_json() ids = [i for i in req.get("dataset_ids", []) if i] for kb_id in ids: kbs = KnowledgebaseService.accessible(kb_id=kb_id, user_id=tenant_id) if not kbs: return get_error_data_result(f"You don't own the dataset {kb_id}") kbs = KnowledgebaseService.query(id=kb_id) kb = kbs[0] if kb.chunk_num == 0: return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file") kbs = KnowledgebaseService.get_by_ids(ids) if ids else [] embd_ids = [TenantLLMService.split_model_name_and_factory(kb.embd_id)[0] for kb in kbs] # remove vendor suffix for comparison embd_count = list(set(embd_ids)) if len(embd_count) > 1: return get_result(message='Datasets use different embedding models."', code=RetCode.AUTHENTICATION_ERROR) req["kb_ids"] = ids # llm llm = req.get("llm") if llm: if "model_name" in llm: req["llm_id"] = llm.pop("model_name") if req.get("llm_id") is not None: llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(req["llm_id"]) if not TenantLLMService.query(tenant_id=tenant_id, llm_name=llm_name, llm_factory=llm_factory, model_type="chat"): return get_error_data_result(f"`model_name` {req.get('llm_id')} doesn't exist") req["llm_setting"] = req.pop("llm") e, tenant = TenantService.get_by_id(tenant_id) if not e: return get_error_data_result(message="Tenant not found!") # prompt prompt = req.get("prompt") key_mapping = {"parameters": "variables", "prologue": "opener", "quote": "show_quote", "system": "prompt", "rerank_id": "rerank_model", "vector_similarity_weight": "keywords_similarity_weight"} key_list = ["similarity_threshold", "vector_similarity_weight", "top_n", "rerank_id", "top_k"] if prompt: for new_key, old_key in key_mapping.items(): if old_key in prompt: prompt[new_key] = prompt.pop(old_key) for key in key_list: if key in prompt: req[key] = prompt.pop(key) req["prompt_config"] = req.pop("prompt") # init req["id"] = get_uuid() req["description"] = req.get("description", "A helpful Assistant") req["icon"] = req.get("avatar", "") req["top_n"] = req.get("top_n", 6) req["top_k"] = req.get("top_k", 1024) req["rerank_id"] = req.get("rerank_id", "") if req.get("rerank_id"): value_rerank_model = ["BAAI/bge-reranker-v2-m3", "maidalun1020/bce-reranker-base_v1"] if req["rerank_id"] not in value_rerank_model and not TenantLLMService.query(tenant_id=tenant_id, llm_name=req.get("rerank_id"), model_type="rerank"): return get_error_data_result(f"`rerank_model` {req.get('rerank_id')} doesn't exist") if not req.get("llm_id"): req["llm_id"] = tenant.llm_id if not req.get("name"): return get_error_data_result(message="`name` is required.") if DialogService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value): return get_error_data_result(message="Duplicated chat name in creating chat.") # tenant_id if req.get("tenant_id"): return get_error_data_result(message="`tenant_id` must not be provided.") req["tenant_id"] = tenant_id # prompt more parameter default_prompt = { "system": """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. Here is the knowledge base: {knowledge} The above is the knowledge base.""", "prologue": "Hi! I'm your assistant. What can I do for you?", "parameters": [{"key": "knowledge", "optional": False}], "empty_response": "Sorry! No relevant content was found in the knowledge base!", "quote": True, "tts": False, "refine_multiturn": True, } key_list_2 = ["system", "prologue", "parameters", "empty_response", "quote", "tts", "refine_multiturn"] if "prompt_config" not in req: req["prompt_config"] = {} for key in key_list_2: temp = req["prompt_config"].get(key) if (not temp and key == "system") or (key not in req["prompt_config"]): req["prompt_config"][key] = default_prompt[key] for p in req["prompt_config"]["parameters"]: if p["optional"]: continue if req["prompt_config"]["system"].find("{%s}" % p["key"]) < 0: return get_error_data_result(message="Parameter '{}' is not used".format(p["key"])) # save if not DialogService.save(**req): return get_error_data_result(message="Fail to new a chat!") # response e, res = DialogService.get_by_id(req["id"]) if not e: return get_error_data_result(message="Fail to new a chat!") res = res.to_json() renamed_dict = {} for key, value in res["prompt_config"].items(): new_key = key_mapping.get(key, key) renamed_dict[new_key] = value res["prompt"] = renamed_dict del res["prompt_config"] new_dict = {"similarity_threshold": res["similarity_threshold"], "keywords_similarity_weight": 1 - res["vector_similarity_weight"], "top_n": res["top_n"], "rerank_model": res["rerank_id"]} res["prompt"].update(new_dict) for key in key_list: del res[key] res["llm"] = res.pop("llm_setting") res["llm"]["model_name"] = res.pop("llm_id") del res["kb_ids"] res["dataset_ids"] = req.get("dataset_ids", []) res["avatar"] = res.pop("icon") return get_result(data=res) @manager.route("/chats/<chat_id>", methods=["PUT"]) # noqa: F821 @token_required async def update(tenant_id, chat_id): if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value): return get_error_data_result(message="You do not own the chat") req = await get_request_json() ids = req.get("dataset_ids", []) if "show_quotation" in req: req["do_refer"] = req.pop("show_quotation") if ids: for kb_id in ids: kbs = KnowledgebaseService.accessible(kb_id=kb_id, user_id=tenant_id) if not kbs: return get_error_data_result(f"You don't own the dataset {kb_id}") kbs = KnowledgebaseService.query(id=kb_id) kb = kbs[0] if kb.chunk_num == 0: return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file") kbs = KnowledgebaseService.get_by_ids(ids) embd_ids = [TenantLLMService.split_model_name_and_factory(kb.embd_id)[0] for kb in kbs] # remove vendor suffix for comparison embd_count = list(set(embd_ids)) if len(embd_count) > 1: return get_result(message='Datasets use different embedding models."', code=RetCode.AUTHENTICATION_ERROR) req["kb_ids"] = ids else: req["kb_ids"] = [] llm = req.get("llm") if llm: if "model_name" in llm: req["llm_id"] = llm.pop("model_name") if req.get("llm_id") is not None: llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(req["llm_id"]) model_type = llm.pop("model_type") model_type = model_type if model_type in ["chat", "image2text"] else "chat" if not TenantLLMService.query(tenant_id=tenant_id, llm_name=llm_name, llm_factory=llm_factory, model_type=model_type): return get_error_data_result(f"`model_name` {req.get('llm_id')} doesn't exist") req["llm_setting"] = req.pop("llm") e, tenant = TenantService.get_by_id(tenant_id) if not e: return get_error_data_result(message="Tenant not found!") # prompt prompt = req.get("prompt") key_mapping = {"parameters": "variables", "prologue": "opener", "quote": "show_quote", "system": "prompt", "rerank_id": "rerank_model", "vector_similarity_weight": "keywords_similarity_weight"} key_list = ["similarity_threshold", "vector_similarity_weight", "top_n", "rerank_id", "top_k"] if prompt: for new_key, old_key in key_mapping.items(): if old_key in prompt: prompt[new_key] = prompt.pop(old_key) for key in key_list: if key in prompt: req[key] = prompt.pop(key) req["prompt_config"] = req.pop("prompt") e, res = DialogService.get_by_id(chat_id) res = res.to_json() if req.get("rerank_id"): value_rerank_model = ["BAAI/bge-reranker-v2-m3", "maidalun1020/bce-reranker-base_v1"] if req["rerank_id"] not in value_rerank_model and not TenantLLMService.query(tenant_id=tenant_id, llm_name=req.get("rerank_id"), model_type="rerank"): return get_error_data_result(f"`rerank_model` {req.get('rerank_id')} doesn't exist") if "name" in req: if not req.get("name"): return get_error_data_result(message="`name` cannot be empty.") if req["name"].lower() != res["name"].lower() and len(DialogService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value)) > 0: return get_error_data_result(message="Duplicated chat name in updating chat.") if "prompt_config" in req: res["prompt_config"].update(req["prompt_config"]) for p in res["prompt_config"]["parameters"]: if p["optional"]: continue if res["prompt_config"]["system"].find("{%s}" % p["key"]) < 0: return get_error_data_result(message="Parameter '{}' is not used".format(p["key"])) if "llm_setting" in req: res["llm_setting"].update(req["llm_setting"]) req["prompt_config"] = res["prompt_config"] req["llm_setting"] = res["llm_setting"] # avatar if "avatar" in req: req["icon"] = req.pop("avatar") if "dataset_ids" in req: req.pop("dataset_ids") if not DialogService.update_by_id(chat_id, req): return get_error_data_result(message="Chat not found!") return get_result() @manager.route("/chats", methods=["DELETE"]) # noqa: F821 @token_required async def delete_chats(tenant_id): errors = [] success_count = 0 req = await get_request_json() if not req: ids = None else: ids = req.get("ids") if not ids: id_list = [] dias = DialogService.query(tenant_id=tenant_id, status=StatusEnum.VALID.value) for dia in dias: id_list.append(dia.id) else: id_list = ids unique_id_list, duplicate_messages = check_duplicate_ids(id_list, "assistant") for id in unique_id_list: if not DialogService.query(tenant_id=tenant_id, id=id, status=StatusEnum.VALID.value): errors.append(f"Assistant({id}) not found.") continue temp_dict = {"status": StatusEnum.INVALID.value} success_count += DialogService.update_by_id(id, temp_dict) if errors: if success_count > 0: return get_result(data={"success_count": success_count, "errors": errors}, message=f"Partially deleted {success_count} chats with {len(errors)} errors") else: return get_error_data_result(message="; ".join(errors)) if duplicate_messages: if success_count > 0: return get_result(message=f"Partially deleted {success_count} chats with {len(duplicate_messages)} errors", data={"success_count": success_count, "errors": duplicate_messages}) else: return get_error_data_result(message=";".join(duplicate_messages)) return get_result() @manager.route("/chats", methods=["GET"]) # noqa: F821 @token_required def list_chat(tenant_id): id = request.args.get("id") name = request.args.get("name") if id or name: chat = DialogService.query(id=id, name=name, status=StatusEnum.VALID.value, tenant_id=tenant_id) if not chat: return get_error_data_result(message="The chat doesn't exist") page_number = int(request.args.get("page", 1)) items_per_page = int(request.args.get("page_size", 30)) orderby = request.args.get("orderby", "create_time") if request.args.get("desc") == "False" or request.args.get("desc") == "false": desc = False else: desc = True chats = DialogService.get_list(tenant_id, page_number, items_per_page, orderby, desc, id, name) if not chats: return get_result(data=[]) list_assistants = [] key_mapping = { "parameters": "variables", "prologue": "opener", "quote": "show_quote", "system": "prompt", "rerank_id": "rerank_model", "vector_similarity_weight": "keywords_similarity_weight", "do_refer": "show_quotation", } key_list = ["similarity_threshold", "vector_similarity_weight", "top_n", "rerank_id"] for res in chats: renamed_dict = {} for key, value in res["prompt_config"].items(): new_key = key_mapping.get(key, key) renamed_dict[new_key] = value res["prompt"] = renamed_dict del res["prompt_config"] new_dict = {"similarity_threshold": res["similarity_threshold"], "keywords_similarity_weight": 1 - res["vector_similarity_weight"], "top_n": res["top_n"], "rerank_model": res["rerank_id"]} res["prompt"].update(new_dict) for key in key_list: del res[key] res["llm"] = res.pop("llm_setting") res["llm"]["model_name"] = res.pop("llm_id") kb_list = [] for kb_id in res["kb_ids"]: kb = KnowledgebaseService.query(id=kb_id) if not kb: logging.warning(f"The kb {kb_id} does not exist.") continue kb_list.append(kb[0].to_json()) del res["kb_ids"] res["datasets"] = kb_list res["avatar"] = res.pop("icon") list_assistants.append(res) return get_result(data=list_assistants)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/doc.py
api/apps/sdk/doc.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 datetime import json import logging import pathlib import re from io import BytesIO import xxhash from quart import request, send_file from peewee import OperationalError from pydantic import BaseModel, Field, validator from api.constants import FILE_NAME_LEN_LIMIT from api.db import FileType from api.db.db_models import File, Task from api.db.services.document_service import DocumentService from api.db.services.file2document_service import File2DocumentService from api.db.services.file_service import FileService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.llm_service import LLMBundle from api.db.services.tenant_llm_service import TenantLLMService from api.db.services.task_service import TaskService, queue_tasks, cancel_all_task_of from common.metadata_utils import meta_filter, convert_conditions from api.utils.api_utils import check_duplicate_ids, construct_json_result, get_error_data_result, get_parser_config, get_result, server_error_response, token_required, \ get_request_json from rag.app.qa import beAdoc, rmPrefix from rag.app.tag import label_question from rag.nlp import rag_tokenizer, search from rag.prompts.generator import cross_languages, keyword_extraction from common.string_utils import remove_redundant_spaces from common.constants import RetCode, LLMType, ParserType, TaskStatus, FileSource from common import settings MAXIMUM_OF_UPLOADING_FILES = 256 class Chunk(BaseModel): id: str = "" content: str = "" document_id: str = "" docnm_kwd: str = "" important_keywords: list = Field(default_factory=list) questions: list = Field(default_factory=list) question_tks: str = "" image_id: str = "" available: bool = True positions: list[list[int]] = Field(default_factory=list) @validator("positions") def validate_positions(cls, value): for sublist in value: if len(sublist) != 5: raise ValueError("Each sublist in positions must have a length of 5") return value @manager.route("/datasets/<dataset_id>/documents", methods=["POST"]) # noqa: F821 @token_required async def upload(dataset_id, tenant_id): """ Upload documents to a dataset. --- tags: - Documents security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: header name: Authorization type: string required: true description: Bearer token for authentication. - in: formData name: file type: file required: true description: Document files to upload. - in: formData name: parent_path type: string description: Optional nested path under the parent folder. Uses '/' separators. responses: 200: description: Successfully uploaded documents. schema: type: object properties: data: type: array items: type: object properties: id: type: string description: Document ID. name: type: string description: Document name. chunk_count: type: integer description: Number of chunks. token_count: type: integer description: Number of tokens. dataset_id: type: string description: ID of the dataset. chunk_method: type: string description: Chunking method used. run: type: string description: Processing status. """ form = await request.form files = await request.files if "file" not in files: return get_error_data_result(message="No file part!", code=RetCode.ARGUMENT_ERROR) file_objs = files.getlist("file") for file_obj in file_objs: if file_obj.filename == "": return get_result(message="No file selected!", code=RetCode.ARGUMENT_ERROR) if len(file_obj.filename.encode("utf-8")) > FILE_NAME_LEN_LIMIT: return get_result(message=f"File name must be {FILE_NAME_LEN_LIMIT} bytes or less.", code=RetCode.ARGUMENT_ERROR) """ # total size total_size = 0 for file_obj in file_objs: file_obj.seek(0, os.SEEK_END) total_size += file_obj.tell() file_obj.seek(0) MAX_TOTAL_FILE_SIZE = 10 * 1024 * 1024 if total_size > MAX_TOTAL_FILE_SIZE: return get_result( message=f"Total file size exceeds 10MB limit! ({total_size / (1024 * 1024):.2f} MB)", code=RetCode.ARGUMENT_ERROR, ) """ e, kb = KnowledgebaseService.get_by_id(dataset_id) if not e: raise LookupError(f"Can't find the dataset with ID {dataset_id}!") err, files = FileService.upload_document(kb, file_objs, tenant_id, parent_path=form.get("parent_path")) if err: return get_result(message="\n".join(err), code=RetCode.SERVER_ERROR) # rename key's name renamed_doc_list = [] for file in files: doc = file[0] key_mapping = { "chunk_num": "chunk_count", "kb_id": "dataset_id", "token_num": "token_count", "parser_id": "chunk_method", } renamed_doc = {} for key, value in doc.items(): new_key = key_mapping.get(key, key) renamed_doc[new_key] = value renamed_doc["run"] = "UNSTART" renamed_doc_list.append(renamed_doc) return get_result(data=renamed_doc_list) @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["PUT"]) # noqa: F821 @token_required async def update_doc(tenant_id, dataset_id, document_id): """ Update a document within a dataset. --- tags: - Documents security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: path name: document_id type: string required: true description: ID of the document to update. - in: header name: Authorization type: string required: true description: Bearer token for authentication. - in: body name: body description: Document update parameters. required: true schema: type: object properties: name: type: string description: New name of the document. parser_config: type: object description: Parser configuration. chunk_method: type: string description: Chunking method. enabled: type: boolean description: Document status. responses: 200: description: Document updated successfully. schema: type: object """ req = await get_request_json() if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id): return get_error_data_result(message="You don't own the dataset.") e, kb = KnowledgebaseService.get_by_id(dataset_id) if not e: return get_error_data_result(message="Can't find this dataset!") doc = DocumentService.query(kb_id=dataset_id, id=document_id) if not doc: return get_error_data_result(message="The dataset doesn't own the document.") doc = doc[0] if "chunk_count" in req: if req["chunk_count"] != doc.chunk_num: return get_error_data_result(message="Can't change `chunk_count`.") if "token_count" in req: if req["token_count"] != doc.token_num: return get_error_data_result(message="Can't change `token_count`.") if "progress" in req: if req["progress"] != doc.progress: return get_error_data_result(message="Can't change `progress`.") if "meta_fields" in req: if not isinstance(req["meta_fields"], dict): return get_error_data_result(message="meta_fields must be a dictionary") DocumentService.update_meta_fields(document_id, req["meta_fields"]) if "name" in req and req["name"] != doc.name: if len(req["name"].encode("utf-8")) > FILE_NAME_LEN_LIMIT: return get_result( message=f"File name must be {FILE_NAME_LEN_LIMIT} bytes or less.", code=RetCode.ARGUMENT_ERROR, ) if pathlib.Path(req["name"].lower()).suffix != pathlib.Path(doc.name.lower()).suffix: return get_result( message="The extension of file can't be changed", code=RetCode.ARGUMENT_ERROR, ) for d in DocumentService.query(name=req["name"], kb_id=doc.kb_id): if d.name == req["name"]: return get_error_data_result(message="Duplicated document name in the same dataset.") if not DocumentService.update_by_id(document_id, {"name": req["name"]}): return get_error_data_result(message="Database error (Document rename)!") informs = File2DocumentService.get_by_document_id(document_id) if informs: e, file = FileService.get_by_id(informs[0].file_id) FileService.update_by_id(file.id, {"name": req["name"]}) if "parser_config" in req: DocumentService.update_parser_config(doc.id, req["parser_config"]) if "chunk_method" in req: valid_chunk_method = {"naive", "manual", "qa", "table", "paper", "book", "laws", "presentation", "picture", "one", "knowledge_graph", "email", "tag"} if req.get("chunk_method") not in valid_chunk_method: return get_error_data_result(f"`chunk_method` {req['chunk_method']} doesn't exist") if doc.type == FileType.VISUAL or re.search(r"\.(ppt|pptx|pages)$", doc.name): return get_error_data_result(message="Not supported yet!") if doc.parser_id.lower() != req["chunk_method"].lower(): e = DocumentService.update_by_id( doc.id, { "parser_id": req["chunk_method"], "progress": 0, "progress_msg": "", "run": TaskStatus.UNSTART.value, }, ) if not e: return get_error_data_result(message="Document not found!") if not req.get("parser_config"): req["parser_config"] = get_parser_config(req["chunk_method"], req.get("parser_config")) DocumentService.update_parser_config(doc.id, req["parser_config"]) if doc.token_num > 0: e = DocumentService.increment_chunk_num( doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1, doc.process_duration * -1, ) if not e: return get_error_data_result(message="Document not found!") settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), dataset_id) if "enabled" in req: status = int(req["enabled"]) if doc.status != req["enabled"]: try: if not DocumentService.update_by_id(doc.id, {"status": str(status)}): return get_error_data_result(message="Database error (Document update)!") settings.docStoreConn.update({"doc_id": doc.id}, {"available_int": status}, search.index_name(kb.tenant_id), doc.kb_id) except Exception as e: return server_error_response(e) try: ok, doc = DocumentService.get_by_id(doc.id) if not ok: return get_error_data_result(message="Dataset created failed") except OperationalError as e: logging.exception(e) return get_error_data_result(message="Database operation failed") key_mapping = { "chunk_num": "chunk_count", "kb_id": "dataset_id", "token_num": "token_count", "parser_id": "chunk_method", } run_mapping = { "0": "UNSTART", "1": "RUNNING", "2": "CANCEL", "3": "DONE", "4": "FAIL", } renamed_doc = {} for key, value in doc.to_dict().items(): new_key = key_mapping.get(key, key) renamed_doc[new_key] = value if key == "run": renamed_doc["run"] = run_mapping.get(str(value)) return get_result(data=renamed_doc) @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["GET"]) # noqa: F821 @token_required async def download(tenant_id, dataset_id, document_id): """ Download a document from a dataset. --- tags: - Documents security: - ApiKeyAuth: [] produces: - application/octet-stream parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: path name: document_id type: string required: true description: ID of the document to download. - in: header name: Authorization type: string required: true description: Bearer token for authentication. responses: 200: description: Document file stream. schema: type: file 400: description: Error message. schema: type: object """ if not document_id: return get_error_data_result(message="Specify document_id please.") if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id): return get_error_data_result(message=f"You do not own the dataset {dataset_id}.") doc = DocumentService.query(kb_id=dataset_id, id=document_id) if not doc: return get_error_data_result(message=f"The dataset not own the document {document_id}.") # The process of downloading doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address file_stream = settings.STORAGE_IMPL.get(doc_id, doc_location) if not file_stream: return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR) file = BytesIO(file_stream) # Use send_file with a proper filename and MIME type return await send_file( file, as_attachment=True, attachment_filename=doc[0].name, mimetype="application/octet-stream", # Set a default MIME type ) @manager.route("/datasets/<dataset_id>/documents", methods=["GET"]) # noqa: F821 @token_required def list_docs(dataset_id, tenant_id): """ List documents in a dataset. --- tags: - Documents security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: query name: id type: string required: false description: Filter by document ID. - in: query name: page type: integer required: false default: 1 description: Page number. - in: query name: page_size type: integer required: false default: 30 description: Number of items per page. - in: query name: orderby type: string required: false default: "create_time" description: Field to order by. - in: query name: desc type: boolean required: false default: true description: Order in descending. - in: query name: create_time_from type: integer required: false default: 0 description: Unix timestamp for filtering documents created after this time. 0 means no filter. - in: query name: create_time_to type: integer required: false default: 0 description: Unix timestamp for filtering documents created before this time. 0 means no filter. - in: query name: suffix type: array items: type: string required: false description: Filter by file suffix (e.g., ["pdf", "txt", "docx"]). - in: query name: run type: array items: type: string required: false description: Filter by document run status. Supports both numeric ("0", "1", "2", "3", "4") and text formats ("UNSTART", "RUNNING", "CANCEL", "DONE", "FAIL"). - in: header name: Authorization type: string required: true description: Bearer token for authentication. responses: 200: description: List of documents. schema: type: object properties: total: type: integer description: Total number of documents. docs: type: array items: type: object properties: id: type: string description: Document ID. name: type: string description: Document name. chunk_count: type: integer description: Number of chunks. token_count: type: integer description: Number of tokens. dataset_id: type: string description: ID of the dataset. chunk_method: type: string description: Chunking method used. run: type: string description: Processing status. """ if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ") q = request.args document_id = q.get("id") name = q.get("name") if document_id and not DocumentService.query(id=document_id, kb_id=dataset_id): return get_error_data_result(message=f"You don't own the document {document_id}.") if name and not DocumentService.query(name=name, kb_id=dataset_id): return get_error_data_result(message=f"You don't own the document {name}.") page = int(q.get("page", 1)) page_size = int(q.get("page_size", 30)) orderby = q.get("orderby", "create_time") desc = str(q.get("desc", "true")).strip().lower() != "false" keywords = q.get("keywords", "") # filters - align with OpenAPI parameter names suffix = q.getlist("suffix") run_status = q.getlist("run") create_time_from = int(q.get("create_time_from", 0)) create_time_to = int(q.get("create_time_to", 0)) metadata_condition_raw = q.get("metadata_condition") metadata_condition = {} if metadata_condition_raw: try: metadata_condition = json.loads(metadata_condition_raw) except Exception: return get_error_data_result(message="metadata_condition must be valid JSON.") if metadata_condition and not isinstance(metadata_condition, dict): return get_error_data_result(message="metadata_condition must be an object.") # map run status (text or numeric) - align with API parameter run_status_text_to_numeric = {"UNSTART": "0", "RUNNING": "1", "CANCEL": "2", "DONE": "3", "FAIL": "4"} run_status_converted = [run_status_text_to_numeric.get(v, v) for v in run_status] doc_ids_filter = None if metadata_condition: metas = DocumentService.get_flatted_meta_by_kbs([dataset_id]) doc_ids_filter = meta_filter(metas, convert_conditions(metadata_condition), metadata_condition.get("logic", "and")) if metadata_condition.get("conditions") and not doc_ids_filter: return get_result(data={"total": 0, "docs": []}) docs, total = DocumentService.get_list( dataset_id, page, page_size, orderby, desc, keywords, document_id, name, suffix, run_status_converted, doc_ids_filter ) # time range filter (0 means no bound) if create_time_from or create_time_to: docs = [ d for d in docs if (create_time_from == 0 or d.get("create_time", 0) >= create_time_from) and (create_time_to == 0 or d.get("create_time", 0) <= create_time_to) ] # rename keys + map run status back to text for output key_mapping = { "chunk_num": "chunk_count", "kb_id": "dataset_id", "token_num": "token_count", "parser_id": "chunk_method", } run_status_numeric_to_text = {"0": "UNSTART", "1": "RUNNING", "2": "CANCEL", "3": "DONE", "4": "FAIL"} output_docs = [] for d in docs: renamed_doc = {key_mapping.get(k, k): v for k, v in d.items()} if "run" in d: renamed_doc["run"] = run_status_numeric_to_text.get(str(d["run"]), d["run"]) output_docs.append(renamed_doc) return get_result(data={"total": total, "docs": output_docs}) @manager.route("/datasets/<dataset_id>/metadata/summary", methods=["GET"]) # noqa: F821 @token_required def metadata_summary(dataset_id, tenant_id): if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ") try: summary = DocumentService.get_metadata_summary(dataset_id) return get_result(data={"summary": summary}) except Exception as e: return server_error_response(e) @manager.route("/datasets/<dataset_id>/metadata/update", methods=["POST"]) # noqa: F821 @token_required async def metadata_batch_update(dataset_id, tenant_id): if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ") req = await get_request_json() selector = req.get("selector", {}) or {} updates = req.get("updates", []) or [] deletes = req.get("deletes", []) or [] if not isinstance(selector, dict): return get_error_data_result(message="selector must be an object.") if not isinstance(updates, list) or not isinstance(deletes, list): return get_error_data_result(message="updates and deletes must be lists.") metadata_condition = selector.get("metadata_condition", {}) or {} if metadata_condition and not isinstance(metadata_condition, dict): return get_error_data_result(message="metadata_condition must be an object.") document_ids = selector.get("document_ids", []) or [] if document_ids and not isinstance(document_ids, list): return get_error_data_result(message="document_ids must be a list.") for upd in updates: if not isinstance(upd, dict) or not upd.get("key") or "value" not in upd: return get_error_data_result(message="Each update requires key and value.") for d in deletes: if not isinstance(d, dict) or not d.get("key"): return get_error_data_result(message="Each delete requires key.") kb_doc_ids = KnowledgebaseService.list_documents_by_ids([dataset_id]) target_doc_ids = set(kb_doc_ids) if document_ids: invalid_ids = set(document_ids) - set(kb_doc_ids) if invalid_ids: return get_error_data_result(message=f"These documents do not belong to dataset {dataset_id}: {', '.join(invalid_ids)}") target_doc_ids = set(document_ids) if metadata_condition: metas = DocumentService.get_flatted_meta_by_kbs([dataset_id]) filtered_ids = set(meta_filter(metas, convert_conditions(metadata_condition), metadata_condition.get("logic", "and"))) target_doc_ids = target_doc_ids & filtered_ids if metadata_condition.get("conditions") and not target_doc_ids: return get_result(data={"updated": 0, "matched_docs": 0}) target_doc_ids = list(target_doc_ids) updated = DocumentService.batch_update_metadata(dataset_id, target_doc_ids, updates, deletes) return get_result(data={"updated": updated, "matched_docs": len(target_doc_ids)}) @manager.route("/datasets/<dataset_id>/documents", methods=["DELETE"]) # noqa: F821 @token_required async def delete(tenant_id, dataset_id): """ Delete documents from a dataset. --- tags: - Documents security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: body name: body description: Document deletion parameters. required: true schema: type: object properties: ids: type: array items: type: string description: List of document IDs to delete. - in: header name: Authorization type: string required: true description: Bearer token for authentication. responses: 200: description: Documents deleted successfully. schema: type: object """ if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ") req = await get_request_json() if not req: doc_ids = None else: doc_ids = req.get("ids") if not doc_ids: doc_list = [] docs = DocumentService.query(kb_id=dataset_id) for doc in docs: doc_list.append(doc.id) else: doc_list = doc_ids unique_doc_ids, duplicate_messages = check_duplicate_ids(doc_list, "document") doc_list = unique_doc_ids root_folder = FileService.get_root_folder(tenant_id) pf_id = root_folder["id"] FileService.init_knowledgebase_docs(pf_id, tenant_id) errors = "" not_found = [] success_count = 0 for doc_id in doc_list: try: e, doc = DocumentService.get_by_id(doc_id) if not e: not_found.append(doc_id) continue tenant_id = DocumentService.get_tenant_id(doc_id) if not tenant_id: return get_error_data_result(message="Tenant not found!") b, n = File2DocumentService.get_storage_address(doc_id=doc_id) if not DocumentService.remove_document(doc, tenant_id): return get_error_data_result(message="Database error (Document removal)!") f2d = File2DocumentService.get_by_document_id(doc_id) FileService.filter_delete( [ File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id, ] ) File2DocumentService.delete_by_document_id(doc_id) settings.STORAGE_IMPL.rm(b, n) success_count += 1 except Exception as e: errors += str(e) if not_found: return get_result(message=f"Documents not found: {not_found}", code=RetCode.DATA_ERROR) if errors: return get_result(message=errors, code=RetCode.SERVER_ERROR) if duplicate_messages: if success_count > 0: return get_result( message=f"Partially deleted {success_count} datasets with {len(duplicate_messages)} errors", data={"success_count": success_count, "errors": duplicate_messages}, ) else: return get_error_data_result(message=";".join(duplicate_messages)) return get_result() @manager.route("/datasets/<dataset_id>/chunks", methods=["POST"]) # noqa: F821 @token_required async def parse(tenant_id, dataset_id): """ Start parsing documents into chunks. --- tags: - Chunks security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: body name: body description: Parsing parameters. required: true schema: type: object properties: document_ids: type: array items: type: string description: List of document IDs to parse. - in: header name: Authorization type: string required: true description: Bearer token for authentication. responses: 200: description: Parsing started successfully. schema: type: object """ if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): return get_error_data_result(message=f"You don't own the dataset {dataset_id}.") req = await get_request_json() if not req.get("document_ids"): return get_error_data_result("`document_ids` is required") doc_list = req.get("document_ids") unique_doc_ids, duplicate_messages = check_duplicate_ids(doc_list, "document") doc_list = unique_doc_ids not_found = [] success_count = 0 for id in doc_list: doc = DocumentService.query(id=id, kb_id=dataset_id) if not doc: not_found.append(id) continue if not doc: return get_error_data_result(message=f"You don't own the document {id}.") if 0.0 < doc[0].progress < 1.0: return get_error_data_result("Can't parse document that is currently being processed") info = {"run": "1", "progress": 0, "progress_msg": "", "chunk_num": 0, "token_num": 0} DocumentService.update_by_id(id, info) settings.docStoreConn.delete({"doc_id": id}, search.index_name(tenant_id), dataset_id) TaskService.filter_delete([Task.doc_id == id]) e, doc = DocumentService.get_by_id(id) doc = doc.to_dict() doc["tenant_id"] = tenant_id bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"]) queue_tasks(doc, bucket, name, 0) success_count += 1 if not_found: return get_result(message=f"Documents not found: {not_found}", code=RetCode.DATA_ERROR) if duplicate_messages: if success_count > 0: return get_result( message=f"Partially parsed {success_count} documents with {len(duplicate_messages)} errors", data={"success_count": success_count, "errors": duplicate_messages}, ) else: return get_error_data_result(message=";".join(duplicate_messages)) return get_result() @manager.route("/datasets/<dataset_id>/chunks", methods=["DELETE"]) # noqa: F821 @token_required async def stop_parsing(tenant_id, dataset_id): """ Stop parsing documents into chunks. --- tags: - Chunks security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset. - in: body name: body description: Stop parsing parameters. required: true schema: type: object properties: document_ids: type: array items: type: string description: List of document IDs to stop parsing. - in: header name: Authorization type: string required: true description: Bearer token for authentication. responses: 200: description: Parsing stopped successfully. schema: type: object """ if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/dataset.py
api/apps/sdk/dataset.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 json from quart import request from peewee import OperationalError from api.db.db_models import File from api.db.services.document_service import DocumentService, queue_raptor_o_graphrag_tasks from api.db.services.file2document_service import File2DocumentService from api.db.services.file_service import FileService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.task_service import GRAPH_RAPTOR_FAKE_DOC_ID, TaskService from api.db.services.user_service import TenantService from common.constants import RetCode, FileSource, StatusEnum from api.utils.api_utils import ( deep_merge, get_error_argument_result, get_error_data_result, get_error_permission_result, get_parser_config, get_result, remap_dictionary_keys, token_required, verify_embedding_availability, ) from api.utils.validation_utils import ( CreateDatasetReq, DeleteDatasetReq, ListDatasetReq, UpdateDatasetReq, validate_and_parse_json_request, validate_and_parse_request_args, ) from rag.nlp import search from common.constants import PAGERANK_FLD from common import settings @manager.route("/datasets", methods=["POST"]) # noqa: F821 @token_required async def create(tenant_id): """ Create a new dataset. --- tags: - Datasets security: - ApiKeyAuth: [] parameters: - in: header name: Authorization type: string required: true description: Bearer token for authentication. - in: body name: body description: Dataset creation parameters. required: true schema: type: object required: - name properties: name: type: string description: Dataset name (required). avatar: type: string description: Optional base64-encoded avatar image. description: type: string description: Optional dataset description. embedding_model: type: string description: Optional embedding model name; if omitted, the tenant's default embedding model is used. permission: type: string enum: ['me', 'team'] description: Visibility of the dataset (private to me or shared with team). chunk_method: type: string enum: ["naive", "book", "email", "laws", "manual", "one", "paper", "picture", "presentation", "qa", "table", "tag"] description: Chunking method; if omitted, defaults to "naive". parser_config: type: object description: Optional parser configuration; server-side defaults will be applied. responses: 200: description: Successful operation. schema: type: object properties: data: type: object """ # Field name transformations during model dump: # | Original | Dump Output | # |----------------|-------------| # | embedding_model| embd_id | # | chunk_method | parser_id | req, err = await validate_and_parse_json_request(request, CreateDatasetReq) if err is not None: return get_error_argument_result(err) e, req = KnowledgebaseService.create_with_name( name = req.pop("name", None), tenant_id = tenant_id, parser_id = req.pop("parser_id", None), **req ) if not e: return req # Insert embedding model(embd id) ok, t = TenantService.get_by_id(tenant_id) if not ok: return get_error_permission_result(message="Tenant not found") if not req.get("embd_id"): req["embd_id"] = t.embd_id else: ok, err = verify_embedding_availability(req["embd_id"], tenant_id) if not ok: return err try: if not KnowledgebaseService.save(**req): return get_error_data_result() ok, k = KnowledgebaseService.get_by_id(req["id"]) if not ok: return get_error_data_result(message="Dataset created failed") response_data = remap_dictionary_keys(k.to_dict()) return get_result(data=response_data) except Exception as e: logging.exception(e) return get_error_data_result(message="Database operation failed") @manager.route("/datasets", methods=["DELETE"]) # noqa: F821 @token_required async def delete(tenant_id): """ Delete datasets. --- tags: - Datasets security: - ApiKeyAuth: [] parameters: - in: header name: Authorization type: string required: true description: Bearer token for authentication. - in: body name: body description: Dataset deletion parameters. required: true schema: type: object required: - ids properties: ids: type: array or null items: type: string description: | Specifies the datasets to delete: - If `null`, all datasets will be deleted. - If an array of IDs, only the specified datasets will be deleted. - If an empty array, no datasets will be deleted. responses: 200: description: Successful operation. schema: type: object """ req, err = await validate_and_parse_json_request(request, DeleteDatasetReq) if err is not None: return get_error_argument_result(err) try: kb_id_instance_pairs = [] if req["ids"] is None: kbs = KnowledgebaseService.query(tenant_id=tenant_id) for kb in kbs: kb_id_instance_pairs.append((kb.id, kb)) else: error_kb_ids = [] for kb_id in req["ids"]: kb = KnowledgebaseService.get_or_none(id=kb_id, tenant_id=tenant_id) if kb is None: error_kb_ids.append(kb_id) continue kb_id_instance_pairs.append((kb_id, kb)) if len(error_kb_ids) > 0: return get_error_permission_result( message=f"""User '{tenant_id}' lacks permission for datasets: '{", ".join(error_kb_ids)}'""") errors = [] success_count = 0 for kb_id, kb in kb_id_instance_pairs: for doc in DocumentService.query(kb_id=kb_id): if not DocumentService.remove_document(doc, tenant_id): errors.append(f"Remove document '{doc.id}' error for dataset '{kb_id}'") continue f2d = File2DocumentService.get_by_document_id(doc.id) FileService.filter_delete( [ File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id, ] ) File2DocumentService.delete_by_document_id(doc.id) FileService.filter_delete( [File.source_type == FileSource.KNOWLEDGEBASE, File.type == "folder", File.name == kb.name]) if not KnowledgebaseService.delete_by_id(kb_id): errors.append(f"Delete dataset error for {kb_id}") continue success_count += 1 if not errors: return get_result() error_message = f"Successfully deleted {success_count} datasets, {len(errors)} failed. Details: {'; '.join(errors)[:128]}..." if success_count == 0: return get_error_data_result(message=error_message) return get_result(data={"success_count": success_count, "errors": errors[:5]}, message=error_message) except OperationalError as e: logging.exception(e) return get_error_data_result(message="Database operation failed") @manager.route("/datasets/<dataset_id>", methods=["PUT"]) # noqa: F821 @token_required async def update(tenant_id, dataset_id): """ Update a dataset. --- tags: - Datasets security: - ApiKeyAuth: [] parameters: - in: path name: dataset_id type: string required: true description: ID of the dataset to update. - in: header name: Authorization type: string required: true description: Bearer token for authentication. - in: body name: body description: Dataset update parameters. required: true schema: type: object properties: name: type: string description: New name of the dataset. avatar: type: string description: Updated base64 encoding of the avatar. description: type: string description: Updated description of the dataset. embedding_model: type: string description: Updated embedding model Name. permission: type: string enum: ['me', 'team'] description: Updated dataset permission. chunk_method: type: string enum: ["naive", "book", "email", "laws", "manual", "one", "paper", "picture", "presentation", "qa", "table", "tag" ] description: Updated chunking method. pagerank: type: integer description: Updated page rank. parser_config: type: object description: Updated parser configuration. responses: 200: description: Successful operation. schema: type: object """ # Field name transformations during model dump: # | Original | Dump Output | # |----------------|-------------| # | embedding_model| embd_id | # | chunk_method | parser_id | extras = {"dataset_id": dataset_id} req, err = await validate_and_parse_json_request(request, UpdateDatasetReq, extras=extras, exclude_unset=True) if err is not None: return get_error_argument_result(err) if not req: return get_error_argument_result(message="No properties were modified") try: kb = KnowledgebaseService.get_or_none(id=dataset_id, tenant_id=tenant_id) if kb is None: return get_error_permission_result( message=f"User '{tenant_id}' lacks permission for dataset '{dataset_id}'") if req.get("parser_config"): req["parser_config"] = deep_merge(kb.parser_config, req["parser_config"]) if (chunk_method := req.get("parser_id")) and chunk_method != kb.parser_id: if not req.get("parser_config"): req["parser_config"] = get_parser_config(chunk_method, None) elif "parser_config" in req and not req["parser_config"]: del req["parser_config"] if "name" in req and req["name"].lower() != kb.name.lower(): exists = KnowledgebaseService.get_or_none(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value) if exists: return get_error_data_result(message=f"Dataset name '{req['name']}' already exists") if "embd_id" in req: if not req["embd_id"]: req["embd_id"] = kb.embd_id if kb.chunk_num != 0 and req["embd_id"] != kb.embd_id: return get_error_data_result( message=f"When chunk_num ({kb.chunk_num}) > 0, embedding_model must remain {kb.embd_id}") ok, err = verify_embedding_availability(req["embd_id"], tenant_id) if not ok: return err if "pagerank" in req and req["pagerank"] != kb.pagerank: if os.environ.get("DOC_ENGINE", "elasticsearch") == "infinity": return get_error_argument_result(message="'pagerank' can only be set when doc_engine is elasticsearch") if req["pagerank"] > 0: settings.docStoreConn.update({"kb_id": kb.id}, {PAGERANK_FLD: req["pagerank"]}, search.index_name(kb.tenant_id), kb.id) else: # Elasticsearch requires PAGERANK_FLD be non-zero! settings.docStoreConn.update({"exists": PAGERANK_FLD}, {"remove": PAGERANK_FLD}, search.index_name(kb.tenant_id), kb.id) if not KnowledgebaseService.update_by_id(kb.id, req): return get_error_data_result(message="Update dataset error.(Database error)") ok, k = KnowledgebaseService.get_by_id(kb.id) if not ok: return get_error_data_result(message="Dataset created failed") response_data = remap_dictionary_keys(k.to_dict()) return get_result(data=response_data) except OperationalError as e: logging.exception(e) return get_error_data_result(message="Database operation failed") @manager.route("/datasets", methods=["GET"]) # noqa: F821 @token_required def list_datasets(tenant_id): """ List datasets. --- tags: - Datasets security: - ApiKeyAuth: [] parameters: - in: query name: id type: string required: false description: Dataset ID to filter. - in: query name: name type: string required: false description: Dataset name to filter. - in: query name: page type: integer required: false default: 1 description: Page number. - in: query name: page_size type: integer required: false default: 30 description: Number of items per page. - in: query name: orderby type: string required: false default: "create_time" description: Field to order by. - in: query name: desc type: boolean required: false default: true description: Order in descending. - in: header name: Authorization type: string required: true description: Bearer token for authentication. responses: 200: description: Successful operation. schema: type: array items: type: object """ args, err = validate_and_parse_request_args(request, ListDatasetReq) if err is not None: return get_error_argument_result(err) try: kb_id = request.args.get("id") name = args.get("name") if kb_id: kbs = KnowledgebaseService.get_kb_by_id(kb_id, tenant_id) if not kbs: return get_error_permission_result(message=f"User '{tenant_id}' lacks permission for dataset '{kb_id}'") if name: kbs = KnowledgebaseService.get_kb_by_name(name, tenant_id) if not kbs: return get_error_permission_result(message=f"User '{tenant_id}' lacks permission for dataset '{name}'") tenants = TenantService.get_joined_tenants_by_user_id(tenant_id) kbs, total = KnowledgebaseService.get_list( [m["tenant_id"] for m in tenants], tenant_id, args["page"], args["page_size"], args["orderby"], args["desc"], kb_id, name, ) response_data_list = [] for kb in kbs: response_data_list.append(remap_dictionary_keys(kb)) return get_result(data=response_data_list, total=total) except OperationalError as e: logging.exception(e) return get_error_data_result(message="Database operation failed") @manager.route('/datasets/<dataset_id>/knowledge_graph', methods=['GET']) # noqa: F821 @token_required def knowledge_graph(tenant_id, dataset_id): if not KnowledgebaseService.accessible(dataset_id, tenant_id): return get_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) _, kb = KnowledgebaseService.get_by_id(dataset_id) req = { "kb_id": [dataset_id], "knowledge_graph_kwd": ["graph"] } obj = {"graph": {}, "mind_map": {}} if not settings.docStoreConn.index_exist(search.index_name(kb.tenant_id), dataset_id): return get_result(data=obj) sres = settings.retriever.search(req, search.index_name(kb.tenant_id), [dataset_id]) if not len(sres.ids): return get_result(data=obj) for id in sres.ids[:1]: ty = sres.field[id]["knowledge_graph_kwd"] try: content_json = json.loads(sres.field[id]["content_with_weight"]) except Exception: continue obj[ty] = content_json if "nodes" in obj["graph"]: obj["graph"]["nodes"] = sorted(obj["graph"]["nodes"], key=lambda x: x.get("pagerank", 0), reverse=True)[:256] if "edges" in obj["graph"]: node_id_set = {o["id"] for o in obj["graph"]["nodes"]} filtered_edges = [o for o in obj["graph"]["edges"] if o["source"] != o["target"] and o["source"] in node_id_set and o["target"] in node_id_set] obj["graph"]["edges"] = sorted(filtered_edges, key=lambda x: x.get("weight", 0), reverse=True)[:128] return get_result(data=obj) @manager.route('/datasets/<dataset_id>/knowledge_graph', methods=['DELETE']) # noqa: F821 @token_required def delete_knowledge_graph(tenant_id, dataset_id): if not KnowledgebaseService.accessible(dataset_id, tenant_id): return get_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) _, kb = KnowledgebaseService.get_by_id(dataset_id) settings.docStoreConn.delete({"knowledge_graph_kwd": ["graph", "subgraph", "entity", "relation"]}, search.index_name(kb.tenant_id), dataset_id) return get_result(data=True) @manager.route("/datasets/<dataset_id>/run_graphrag", methods=["POST"]) # noqa: F821 @token_required def run_graphrag(tenant_id,dataset_id): if not dataset_id: return get_error_data_result(message='Lack of "Dataset ID"') if not KnowledgebaseService.accessible(dataset_id, tenant_id): return get_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) ok, kb = KnowledgebaseService.get_by_id(dataset_id) if not ok: return get_error_data_result(message="Invalid Dataset ID") task_id = kb.graphrag_task_id if task_id: ok, task = TaskService.get_by_id(task_id) if not ok: logging.warning(f"A valid GraphRAG task id is expected for Dataset {dataset_id}") if task and task.progress not in [-1, 1]: return get_error_data_result(message=f"Task {task_id} in progress with status {task.progress}. A Graph Task is already running.") documents, _ = DocumentService.get_by_kb_id( kb_id=dataset_id, page_number=0, items_per_page=0, orderby="create_time", desc=False, keywords="", run_status=[], types=[], suffix=[], ) if not documents: return get_error_data_result(message=f"No documents in Dataset {dataset_id}") sample_document = documents[0] document_ids = [document["id"] for document in documents] task_id = queue_raptor_o_graphrag_tasks(sample_doc_id=sample_document, ty="graphrag", priority=0, fake_doc_id=GRAPH_RAPTOR_FAKE_DOC_ID, doc_ids=list(document_ids)) if not KnowledgebaseService.update_by_id(kb.id, {"graphrag_task_id": task_id}): logging.warning(f"Cannot save graphrag_task_id for Dataset {dataset_id}") return get_result(data={"graphrag_task_id": task_id}) @manager.route("/datasets/<dataset_id>/trace_graphrag", methods=["GET"]) # noqa: F821 @token_required def trace_graphrag(tenant_id,dataset_id): if not dataset_id: return get_error_data_result(message='Lack of "Dataset ID"') if not KnowledgebaseService.accessible(dataset_id, tenant_id): return get_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) ok, kb = KnowledgebaseService.get_by_id(dataset_id) if not ok: return get_error_data_result(message="Invalid Dataset ID") task_id = kb.graphrag_task_id if not task_id: return get_result(data={}) ok, task = TaskService.get_by_id(task_id) if not ok: return get_result(data={}) return get_result(data=task.to_dict()) @manager.route("/datasets/<dataset_id>/run_raptor", methods=["POST"]) # noqa: F821 @token_required def run_raptor(tenant_id,dataset_id): if not dataset_id: return get_error_data_result(message='Lack of "Dataset ID"') if not KnowledgebaseService.accessible(dataset_id, tenant_id): return get_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) ok, kb = KnowledgebaseService.get_by_id(dataset_id) if not ok: return get_error_data_result(message="Invalid Dataset ID") task_id = kb.raptor_task_id if task_id: ok, task = TaskService.get_by_id(task_id) if not ok: logging.warning(f"A valid RAPTOR task id is expected for Dataset {dataset_id}") if task and task.progress not in [-1, 1]: return get_error_data_result(message=f"Task {task_id} in progress with status {task.progress}. A RAPTOR Task is already running.") documents, _ = DocumentService.get_by_kb_id( kb_id=dataset_id, page_number=0, items_per_page=0, orderby="create_time", desc=False, keywords="", run_status=[], types=[], suffix=[], ) if not documents: return get_error_data_result(message=f"No documents in Dataset {dataset_id}") sample_document = documents[0] document_ids = [document["id"] for document in documents] task_id = queue_raptor_o_graphrag_tasks(sample_doc_id=sample_document, ty="raptor", priority=0, fake_doc_id=GRAPH_RAPTOR_FAKE_DOC_ID, doc_ids=list(document_ids)) if not KnowledgebaseService.update_by_id(kb.id, {"raptor_task_id": task_id}): logging.warning(f"Cannot save raptor_task_id for Dataset {dataset_id}") return get_result(data={"raptor_task_id": task_id}) @manager.route("/datasets/<dataset_id>/trace_raptor", methods=["GET"]) # noqa: F821 @token_required def trace_raptor(tenant_id,dataset_id): if not dataset_id: return get_error_data_result(message='Lack of "Dataset ID"') if not KnowledgebaseService.accessible(dataset_id, tenant_id): return get_result( data=False, message='No authorization.', code=RetCode.AUTHENTICATION_ERROR ) ok, kb = KnowledgebaseService.get_by_id(dataset_id) if not ok: return get_error_data_result(message="Invalid Dataset ID") task_id = kb.raptor_task_id if not task_id: return get_result(data={}) ok, task = TaskService.get_by_id(task_id) if not ok: return get_error_data_result(message="RAPTOR Task Not Found or Error Occurred") return get_result(data=task.to_dict())
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/files.py
api/apps/sdk/files.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 pathlib import re from quart import request, make_response from pathlib import Path from api.db.services.document_service import DocumentService from api.db.services.file2document_service import File2DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.utils.api_utils import get_json_result, get_request_json, server_error_response, token_required from common.misc_utils import get_uuid from api.db import FileType from api.db.services import duplicate_name from api.db.services.file_service import FileService from api.utils.file_utils import filename_type from api.utils.web_utils import CONTENT_TYPE_MAP from common import settings from common.constants import RetCode @manager.route('/file/upload', methods=['POST']) # noqa: F821 @token_required async def upload(tenant_id): """ Upload a file to the system. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: formData name: file type: file required: true description: The file to upload - in: formData name: parent_id type: string description: Parent folder ID where the file will be uploaded. Optional. responses: 200: description: Successfully uploaded the file. schema: type: object properties: data: type: array items: type: object properties: id: type: string description: File ID name: type: string description: File name size: type: integer description: File size in bytes type: type: string description: File type (e.g., document, folder) """ form = await request.form files = await request.files pf_id = form.get("parent_id") if not pf_id: root_folder = FileService.get_root_folder(tenant_id) pf_id = root_folder["id"] if 'file' not in files: return get_json_result(data=False, message='No file part!', code=RetCode.BAD_REQUEST) file_objs = files.getlist('file') for file_obj in file_objs: if file_obj.filename == '': return get_json_result(data=False, message='No selected file!', code=RetCode.BAD_REQUEST) file_res = [] try: e, pf_folder = FileService.get_by_id(pf_id) if not e: return get_json_result(data=False, message="Can't find this folder!", code=RetCode.NOT_FOUND) for file_obj in file_objs: # Handle file path full_path = '/' + file_obj.filename file_obj_names = full_path.split('/') file_len = len(file_obj_names) # Get folder path ID file_id_list = FileService.get_id_list_by_id(pf_id, file_obj_names, 1, [pf_id]) len_id_list = len(file_id_list) # Crete file folder if file_len != len_id_list: e, file = FileService.get_by_id(file_id_list[len_id_list - 1]) if not e: return get_json_result(data=False, message="Folder not found!", code=RetCode.NOT_FOUND) last_folder = FileService.create_folder(file, file_id_list[len_id_list - 1], file_obj_names, len_id_list) else: e, file = FileService.get_by_id(file_id_list[len_id_list - 2]) if not e: return get_json_result(data=False, message="Folder not found!", code=RetCode.NOT_FOUND) last_folder = FileService.create_folder(file, file_id_list[len_id_list - 2], file_obj_names, len_id_list) filetype = filename_type(file_obj_names[file_len - 1]) location = file_obj_names[file_len - 1] while settings.STORAGE_IMPL.obj_exist(last_folder.id, location): location += "_" blob = file_obj.read() filename = duplicate_name(FileService.query, name=file_obj_names[file_len - 1], parent_id=last_folder.id) file = { "id": get_uuid(), "parent_id": last_folder.id, "tenant_id": tenant_id, "created_by": tenant_id, "type": filetype, "name": filename, "location": location, "size": len(blob), } file = FileService.insert(file) settings.STORAGE_IMPL.put(last_folder.id, location, blob) file_res.append(file.to_json()) return get_json_result(data=file_res) except Exception as e: return server_error_response(e) @manager.route('/file/create', methods=['POST']) # noqa: F821 @token_required async def create(tenant_id): """ Create a new file or folder. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: body name: body description: File creation parameters required: true schema: type: object properties: name: type: string description: Name of the file/folder parent_id: type: string description: Parent folder ID. Optional. type: type: string enum: ["FOLDER", "VIRTUAL"] description: Type of the file responses: 200: description: File created successfully. schema: type: object properties: data: type: object properties: id: type: string name: type: string type: type: string """ req = await get_request_json() pf_id = req.get("parent_id") input_file_type = req.get("type") if not pf_id: root_folder = FileService.get_root_folder(tenant_id) pf_id = root_folder["id"] try: if not FileService.is_parent_folder_exist(pf_id): return get_json_result(data=False, message="Parent Folder Doesn't Exist!", code=RetCode.BAD_REQUEST) if FileService.query(name=req["name"], parent_id=pf_id): return get_json_result(data=False, message="Duplicated folder name in the same folder.", code=RetCode.CONFLICT) if input_file_type == FileType.FOLDER.value: file_type = FileType.FOLDER.value else: file_type = FileType.VIRTUAL.value file = FileService.insert({ "id": get_uuid(), "parent_id": pf_id, "tenant_id": tenant_id, "created_by": tenant_id, "name": req["name"], "location": "", "size": 0, "type": file_type }) return get_json_result(data=file.to_json()) except Exception as e: return server_error_response(e) @manager.route('/file/list', methods=['GET']) # noqa: F821 @token_required async def list_files(tenant_id): """ List files under a specific folder. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: query name: parent_id type: string description: Folder ID to list files from - in: query name: keywords type: string description: Search keyword filter - in: query name: page type: integer default: 1 description: Page number - in: query name: page_size type: integer default: 15 description: Number of results per page - in: query name: orderby type: string default: "create_time" description: Sort by field - in: query name: desc type: boolean default: true description: Descending order responses: 200: description: Successfully retrieved file list. schema: type: object properties: total: type: integer files: type: array items: type: object properties: id: type: string name: type: string type: type: string size: type: integer create_time: type: string format: date-time """ pf_id = request.args.get("parent_id") keywords = request.args.get("keywords", "") page_number = int(request.args.get("page", 1)) items_per_page = int(request.args.get("page_size", 15)) orderby = request.args.get("orderby", "create_time") desc = request.args.get("desc", True) if not pf_id: root_folder = FileService.get_root_folder(tenant_id) pf_id = root_folder["id"] FileService.init_knowledgebase_docs(pf_id, tenant_id) try: e, file = FileService.get_by_id(pf_id) if not e: return get_json_result(message="Folder not found!", code=RetCode.NOT_FOUND) files, total = FileService.get_by_pf_id(tenant_id, pf_id, page_number, items_per_page, orderby, desc, keywords) parent_folder = FileService.get_parent_folder(pf_id) if not parent_folder: return get_json_result(message="File not found!", code=RetCode.NOT_FOUND) return get_json_result(data={"total": total, "files": files, "parent_folder": parent_folder.to_json()}) except Exception as e: return server_error_response(e) @manager.route('/file/root_folder', methods=['GET']) # noqa: F821 @token_required async def get_root_folder(tenant_id): """ Get user's root folder. --- tags: - File security: - ApiKeyAuth: [] responses: 200: description: Root folder information schema: type: object properties: data: type: object properties: root_folder: type: object properties: id: type: string name: type: string type: type: string """ try: root_folder = FileService.get_root_folder(tenant_id) return get_json_result(data={"root_folder": root_folder}) except Exception as e: return server_error_response(e) @manager.route('/file/parent_folder', methods=['GET']) # noqa: F821 @token_required async def get_parent_folder(): """ Get parent folder info of a file. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: query name: file_id type: string required: true description: Target file ID responses: 200: description: Parent folder information schema: type: object properties: data: type: object properties: parent_folder: type: object properties: id: type: string name: type: string """ file_id = request.args.get("file_id") try: e, file = FileService.get_by_id(file_id) if not e: return get_json_result(message="Folder not found!", code=RetCode.NOT_FOUND) parent_folder = FileService.get_parent_folder(file_id) return get_json_result(data={"parent_folder": parent_folder.to_json()}) except Exception as e: return server_error_response(e) @manager.route('/file/all_parent_folder', methods=['GET']) # noqa: F821 @token_required async def get_all_parent_folders(tenant_id): """ Get all parent folders of a file. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: query name: file_id type: string required: true description: Target file ID responses: 200: description: All parent folders of the file schema: type: object properties: data: type: object properties: parent_folders: type: array items: type: object properties: id: type: string name: type: string """ file_id = request.args.get("file_id") try: e, file = FileService.get_by_id(file_id) if not e: return get_json_result(message="Folder not found!", code=RetCode.NOT_FOUND) parent_folders = FileService.get_all_parent_folders(file_id) parent_folders_res = [folder.to_json() for folder in parent_folders] return get_json_result(data={"parent_folders": parent_folders_res}) except Exception as e: return server_error_response(e) @manager.route('/file/rm', methods=['POST']) # noqa: F821 @token_required async def rm(tenant_id): """ Delete one or multiple files/folders. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: body name: body description: Files to delete required: true schema: type: object properties: file_ids: type: array items: type: string description: List of file IDs to delete responses: 200: description: Successfully deleted files schema: type: object properties: data: type: boolean example: true """ req = await get_request_json() file_ids = req["file_ids"] try: for file_id in file_ids: e, file = FileService.get_by_id(file_id) if not e: return get_json_result(message="File or Folder not found!", code=RetCode.NOT_FOUND) if not file.tenant_id: return get_json_result(message="Tenant not found!", code=RetCode.NOT_FOUND) if file.type == FileType.FOLDER.value: file_id_list = FileService.get_all_innermost_file_ids(file_id, []) for inner_file_id in file_id_list: e, file = FileService.get_by_id(inner_file_id) if not e: return get_json_result(message="File not found!", code=RetCode.NOT_FOUND) settings.STORAGE_IMPL.rm(file.parent_id, file.location) FileService.delete_folder_by_pf_id(tenant_id, file_id) else: settings.STORAGE_IMPL.rm(file.parent_id, file.location) if not FileService.delete(file): return get_json_result(message="Database error (File removal)!", code=RetCode.SERVER_ERROR) informs = File2DocumentService.get_by_file_id(file_id) for inform in informs: doc_id = inform.document_id e, doc = DocumentService.get_by_id(doc_id) if not e: return get_json_result(message="Document not found!", code=RetCode.NOT_FOUND) tenant_id = DocumentService.get_tenant_id(doc_id) if not tenant_id: return get_json_result(message="Tenant not found!", code=RetCode.NOT_FOUND) if not DocumentService.remove_document(doc, tenant_id): return get_json_result(message="Database error (Document removal)!", code=RetCode.SERVER_ERROR) File2DocumentService.delete_by_file_id(file_id) return get_json_result(data=True) except Exception as e: return server_error_response(e) @manager.route('/file/rename', methods=['POST']) # noqa: F821 @token_required async def rename(tenant_id): """ Rename a file. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: body name: body description: Rename file required: true schema: type: object properties: file_id: type: string description: Target file ID name: type: string description: New name for the file responses: 200: description: File renamed successfully schema: type: object properties: data: type: boolean example: true """ req = await get_request_json() try: e, file = FileService.get_by_id(req["file_id"]) if not e: return get_json_result(message="File not found!", code=RetCode.NOT_FOUND) if file.type != FileType.FOLDER.value and pathlib.Path(req["name"].lower()).suffix != pathlib.Path( file.name.lower()).suffix: return get_json_result(data=False, message="The extension of file can't be changed", code=RetCode.BAD_REQUEST) for existing_file in FileService.query(name=req["name"], pf_id=file.parent_id): if existing_file.name == req["name"]: return get_json_result(data=False, message="Duplicated file name in the same folder.", code=RetCode.CONFLICT) if not FileService.update_by_id(req["file_id"], {"name": req["name"]}): return get_json_result(message="Database error (File rename)!", code=RetCode.SERVER_ERROR) informs = File2DocumentService.get_by_file_id(req["file_id"]) if informs: if not DocumentService.update_by_id(informs[0].document_id, {"name": req["name"]}): return get_json_result(message="Database error (Document rename)!", code=RetCode.SERVER_ERROR) return get_json_result(data=True) except Exception as e: return server_error_response(e) @manager.route('/file/get/<file_id>', methods=['GET']) # noqa: F821 @token_required async def get(tenant_id, file_id): """ Download a file. --- tags: - File security: - ApiKeyAuth: [] produces: - application/octet-stream parameters: - in: path name: file_id type: string required: true description: File ID to download responses: 200: description: File stream schema: type: file RetCode.NOT_FOUND: description: File not found """ try: e, file = FileService.get_by_id(file_id) if not e: return get_json_result(message="Document not found!", code=RetCode.NOT_FOUND) blob = settings.STORAGE_IMPL.get(file.parent_id, file.location) if not blob: b, n = File2DocumentService.get_storage_address(file_id=file_id) blob = settings.STORAGE_IMPL.get(b, n) response = await make_response(blob) ext = re.search(r"\.([^.]+)$", file.name) if ext: if file.type == FileType.VISUAL.value: response.headers.set('Content-Type', 'image/%s' % ext.group(1)) else: response.headers.set('Content-Type', 'application/%s' % ext.group(1)) return response except Exception as e: return server_error_response(e) @manager.route("/file/download/<attachment_id>", methods=["GET"]) # noqa: F821 @token_required async def download_attachment(tenant_id, attachment_id): try: ext = request.args.get("ext", "markdown") data = await asyncio.to_thread(settings.STORAGE_IMPL.get, tenant_id, attachment_id) response = await make_response(data) response.headers.set("Content-Type", CONTENT_TYPE_MAP.get(ext, f"application/{ext}")) return response except Exception as e: return server_error_response(e) @manager.route('/file/mv', methods=['POST']) # noqa: F821 @token_required async def move(tenant_id): """ Move one or multiple files to another folder. --- tags: - File security: - ApiKeyAuth: [] parameters: - in: body name: body description: Move operation required: true schema: type: object properties: src_file_ids: type: array items: type: string description: Source file IDs dest_file_id: type: string description: Destination folder ID responses: 200: description: Files moved successfully schema: type: object properties: data: type: boolean example: true """ req = await get_request_json() try: file_ids = req["src_file_ids"] parent_id = req["dest_file_id"] files = FileService.get_by_ids(file_ids) files_dict = {f.id: f for f in files} for file_id in file_ids: file = files_dict[file_id] if not file: return get_json_result(message="File or Folder not found!", code=RetCode.NOT_FOUND) if not file.tenant_id: return get_json_result(message="Tenant not found!", code=RetCode.NOT_FOUND) fe, _ = FileService.get_by_id(parent_id) if not fe: return get_json_result(message="Parent Folder not found!", code=RetCode.NOT_FOUND) FileService.move_file(file_ids, parent_id) return get_json_result(data=True) except Exception as e: return server_error_response(e) @manager.route('/file/convert', methods=['POST']) # noqa: F821 @token_required async def convert(tenant_id): req = await get_request_json() kb_ids = req["kb_ids"] file_ids = req["file_ids"] file2documents = [] try: files = FileService.get_by_ids(file_ids) files_set = dict({file.id: file for file in files}) for file_id in file_ids: file = files_set[file_id] if not file: return get_json_result(message="File not found!", code=RetCode.NOT_FOUND) file_ids_list = [file_id] if file.type == FileType.FOLDER.value: file_ids_list = FileService.get_all_innermost_file_ids(file_id, []) for id in file_ids_list: informs = File2DocumentService.get_by_file_id(id) # delete for inform in informs: doc_id = inform.document_id e, doc = DocumentService.get_by_id(doc_id) if not e: return get_json_result(message="Document not found!", code=RetCode.NOT_FOUND) tenant_id = DocumentService.get_tenant_id(doc_id) if not tenant_id: return get_json_result(message="Tenant not found!", code=RetCode.NOT_FOUND) if not DocumentService.remove_document(doc, tenant_id): return get_json_result( message="Database error (Document removal)!", code=RetCode.NOT_FOUND) File2DocumentService.delete_by_file_id(id) # insert for kb_id in kb_ids: e, kb = KnowledgebaseService.get_by_id(kb_id) if not e: return get_json_result( message="Can't find this dataset!", code=RetCode.NOT_FOUND) e, file = FileService.get_by_id(id) if not e: return get_json_result( message="Can't find this file!", code=RetCode.NOT_FOUND) doc = DocumentService.insert({ "id": get_uuid(), "kb_id": kb.id, "parser_id": FileService.get_parser(file.type, file.name, kb.parser_id), "parser_config": kb.parser_config, "created_by": tenant_id, "type": file.type, "name": file.name, "suffix": Path(file.name).suffix.lstrip("."), "location": file.location, "size": file.size }) file2document = File2DocumentService.insert({ "id": get_uuid(), "file_id": id, "document_id": doc.id, }) file2documents.append(file2document.to_json()) return get_json_result(data=file2documents) except Exception as e: return server_error_response(e)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/session.py
api/apps/sdk/session.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 copy import re import time import tiktoken from quart import Response, jsonify, request from agent.canvas import Canvas from api.db.db_models import APIToken from api.db.services.api_service import API4ConversationService from api.db.services.canvas_service import UserCanvasService, completion_openai from api.db.services.canvas_service import completion as agent_completion from api.db.services.conversation_service import ConversationService from api.db.services.conversation_service import async_iframe_completion as iframe_completion from api.db.services.conversation_service import async_completion as rag_completion from api.db.services.dialog_service import DialogService, async_ask, async_chat, gen_mindmap from api.db.services.document_service import DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.llm_service import LLMBundle from common.metadata_utils import apply_meta_data_filter, convert_conditions, meta_filter from api.db.services.search_service import SearchService from api.db.services.user_service import UserTenantService from common.misc_utils import get_uuid from api.utils.api_utils import check_duplicate_ids, get_data_openai, get_error_data_result, get_json_result, \ get_result, get_request_json, server_error_response, token_required, validate_request from rag.app.tag import label_question from rag.prompts.template import load_prompt from rag.prompts.generator import cross_languages, keyword_extraction, chunks_format from common.constants import RetCode, LLMType, StatusEnum from common import settings @manager.route("/chats/<chat_id>/sessions", methods=["POST"]) # noqa: F821 @token_required async def create(tenant_id, chat_id): req = await get_request_json() req["dialog_id"] = chat_id dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value) if not dia: return get_error_data_result(message="You do not own the assistant.") conv = { "id": get_uuid(), "dialog_id": req["dialog_id"], "name": req.get("name", "New session"), "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}], "user_id": req.get("user_id", ""), "reference": [], } if not conv.get("name"): return get_error_data_result(message="`name` can not be empty.") ConversationService.save(**conv) e, conv = ConversationService.get_by_id(conv["id"]) if not e: return get_error_data_result(message="Fail to create a session!") conv = conv.to_dict() conv["messages"] = conv.pop("message") conv["chat_id"] = conv.pop("dialog_id") del conv["reference"] return get_result(data=conv) @manager.route("/agents/<agent_id>/sessions", methods=["POST"]) # noqa: F821 @token_required async def create_agent_session(tenant_id, agent_id): user_id = request.args.get("user_id", tenant_id) e, cvs = UserCanvasService.get_by_id(agent_id) if not e: return get_error_data_result("Agent not found.") if not UserCanvasService.query(user_id=tenant_id, id=agent_id): return get_error_data_result("You cannot access the agent.") if not isinstance(cvs.dsl, str): cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False) session_id = get_uuid() canvas = Canvas(cvs.dsl, tenant_id, agent_id, canvas_id=cvs.id) canvas.reset() cvs.dsl = json.loads(str(canvas)) conv = {"id": session_id, "dialog_id": cvs.id, "user_id": user_id, "message": [{"role": "assistant", "content": canvas.get_prologue()}], "source": "agent", "dsl": cvs.dsl} API4ConversationService.save(**conv) conv["agent_id"] = conv.pop("dialog_id") return get_result(data=conv) @manager.route("/chats/<chat_id>/sessions/<session_id>", methods=["PUT"]) # noqa: F821 @token_required async def update(tenant_id, chat_id, session_id): req = await get_request_json() req["dialog_id"] = chat_id conv_id = session_id conv = ConversationService.query(id=conv_id, dialog_id=chat_id) if not conv: return get_error_data_result(message="Session does not exist") if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value): return get_error_data_result(message="You do not own the session") if "message" in req or "messages" in req: return get_error_data_result(message="`message` can not be change") if "reference" in req: return get_error_data_result(message="`reference` can not be change") if "name" in req and not req.get("name"): return get_error_data_result(message="`name` can not be empty.") if not ConversationService.update_by_id(conv_id, req): return get_error_data_result(message="Session updates error") return get_result() @manager.route("/chats/<chat_id>/completions", methods=["POST"]) # noqa: F821 @token_required async def chat_completion(tenant_id, chat_id): req = await get_request_json() if not req: req = {"question": ""} if not req.get("session_id"): req["question"] = "" dia = DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value) if not dia: return get_error_data_result(f"You don't own the chat {chat_id}") dia = dia[0] if req.get("session_id"): if not ConversationService.query(id=req["session_id"], dialog_id=chat_id): return get_error_data_result(f"You don't own the session {req['session_id']}") metadata_condition = req.get("metadata_condition") or {} if metadata_condition and not isinstance(metadata_condition, dict): return get_error_data_result(message="metadata_condition must be an object.") if metadata_condition and req.get("question"): metas = DocumentService.get_meta_by_kbs(dia.kb_ids or []) filtered_doc_ids = meta_filter( metas, convert_conditions(metadata_condition), metadata_condition.get("logic", "and"), ) if metadata_condition.get("conditions") and not filtered_doc_ids: filtered_doc_ids = ["-999"] if filtered_doc_ids: req["doc_ids"] = ",".join(filtered_doc_ids) else: req.pop("doc_ids", None) if req.get("stream", True): resp = Response(rag_completion(tenant_id, chat_id, **req), mimetype="text/event-stream") resp.headers.add_header("Cache-control", "no-cache") resp.headers.add_header("Connection", "keep-alive") resp.headers.add_header("X-Accel-Buffering", "no") resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8") return resp else: answer = None async for ans in rag_completion(tenant_id, chat_id, **req): answer = ans break return get_result(data=answer) @manager.route("/chats_openai/<chat_id>/chat/completions", methods=["POST"]) # noqa: F821 @validate_request("model", "messages") # noqa: F821 @token_required async def chat_completion_openai_like(tenant_id, chat_id): """ OpenAI-like chat completion API that simulates the behavior of OpenAI's completions endpoint. This function allows users to interact with a model and receive responses based on a series of historical messages. If `stream` is set to True (by default), the response will be streamed in chunks, mimicking the OpenAI-style API. Set `stream` to False explicitly, the response will be returned in a single complete answer. Reference: - If `stream` is True, the final answer and reference information will appear in the **last chunk** of the stream. - If `stream` is False, the reference will be included in `choices[0].message.reference`. Example usage: curl -X POST https://ragflow_address.com/api/v1/chats_openai/<chat_id>/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $RAGFLOW_API_KEY" \ -d '{ "model": "model", "messages": [{"role": "user", "content": "Say this is a test!"}], "stream": true }' Alternatively, you can use Python's `OpenAI` client: from openai import OpenAI model = "model" client = OpenAI(api_key="ragflow-api-key", base_url=f"http://ragflow_address/api/v1/chats_openai/<chat_id>") stream = True reference = True completion = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who are you?"}, {"role": "assistant", "content": "I am an AI assistant named..."}, {"role": "user", "content": "Can you tell me how to install neovim"}, ], stream=stream, extra_body={ "reference": reference, "metadata_condition": { "logic": "and", "conditions": [ { "name": "author", "comparison_operator": "is", "value": "bob" } ] } } ) if stream: for chunk in completion: print(chunk) if reference and chunk.choices[0].finish_reason == "stop": print(f"Reference:\n{chunk.choices[0].delta.reference}") print(f"Final content:\n{chunk.choices[0].delta.final_content}") else: print(completion.choices[0].message.content) if reference: print(completion.choices[0].message.reference) """ req = await get_request_json() extra_body = req.get("extra_body") or {} if extra_body and not isinstance(extra_body, dict): return get_error_data_result("extra_body must be an object.") need_reference = bool(extra_body.get("reference", False)) messages = req.get("messages", []) # To prevent empty [] input if len(messages) < 1: return get_error_data_result("You have to provide messages.") if messages[-1]["role"] != "user": return get_error_data_result("The last content of this conversation is not from user.") prompt = messages[-1]["content"] # Treat context tokens as reasoning tokens context_token_used = sum(len(message["content"]) for message in messages) dia = DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value) if not dia: return get_error_data_result(f"You don't own the chat {chat_id}") dia = dia[0] metadata_condition = extra_body.get("metadata_condition") or {} if metadata_condition and not isinstance(metadata_condition, dict): return get_error_data_result(message="metadata_condition must be an object.") doc_ids_str = None if metadata_condition: metas = DocumentService.get_meta_by_kbs(dia.kb_ids or []) filtered_doc_ids = meta_filter( metas, convert_conditions(metadata_condition), metadata_condition.get("logic", "and"), ) if metadata_condition.get("conditions") and not filtered_doc_ids: filtered_doc_ids = ["-999"] doc_ids_str = ",".join(filtered_doc_ids) if filtered_doc_ids else None # Filter system and non-sense assistant messages msg = [] for m in messages: if m["role"] == "system": continue if m["role"] == "assistant" and not msg: continue msg.append(m) # tools = get_tools() # toolcall_session = SimpleFunctionCallServer() tools = None toolcall_session = None if req.get("stream", True): # The value for the usage field on all chunks except for the last one will be null. # The usage field on the last chunk contains token usage statistics for the entire request. # The choices field on the last chunk will always be an empty array []. async def streamed_response_generator(chat_id, dia, msg): token_used = 0 answer_cache = "" reasoning_cache = "" last_ans = {} response = { "id": f"chatcmpl-{chat_id}", "choices": [ { "delta": { "content": "", "role": "assistant", "function_call": None, "tool_calls": None, "reasoning_content": "", }, "finish_reason": None, "index": 0, "logprobs": None, } ], "created": int(time.time()), "model": "model", "object": "chat.completion.chunk", "system_fingerprint": "", "usage": None, } try: chat_kwargs = {"toolcall_session": toolcall_session, "tools": tools, "quote": need_reference} if doc_ids_str: chat_kwargs["doc_ids"] = doc_ids_str async for ans in async_chat(dia, msg, True, **chat_kwargs): last_ans = ans answer = ans["answer"] reasoning_match = re.search(r"<think>(.*?)</think>", answer, flags=re.DOTALL) if reasoning_match: reasoning_part = reasoning_match.group(1) content_part = answer[reasoning_match.end() :] else: reasoning_part = "" content_part = answer reasoning_incremental = "" if reasoning_part: if reasoning_part.startswith(reasoning_cache): reasoning_incremental = reasoning_part.replace(reasoning_cache, "", 1) else: reasoning_incremental = reasoning_part reasoning_cache = reasoning_part content_incremental = "" if content_part: if content_part.startswith(answer_cache): content_incremental = content_part.replace(answer_cache, "", 1) else: content_incremental = content_part answer_cache = content_part token_used += len(reasoning_incremental) + len(content_incremental) if not any([reasoning_incremental, content_incremental]): continue if reasoning_incremental: response["choices"][0]["delta"]["reasoning_content"] = reasoning_incremental else: response["choices"][0]["delta"]["reasoning_content"] = None if content_incremental: response["choices"][0]["delta"]["content"] = content_incremental else: response["choices"][0]["delta"]["content"] = None yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n" except Exception as e: response["choices"][0]["delta"]["content"] = "**ERROR**: " + str(e) yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n" # The last chunk response["choices"][0]["delta"]["content"] = None response["choices"][0]["delta"]["reasoning_content"] = None response["choices"][0]["finish_reason"] = "stop" response["usage"] = {"prompt_tokens": len(prompt), "completion_tokens": token_used, "total_tokens": len(prompt) + token_used} if need_reference: response["choices"][0]["delta"]["reference"] = chunks_format(last_ans.get("reference", [])) response["choices"][0]["delta"]["final_content"] = last_ans.get("answer", "") yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n" yield "data:[DONE]\n\n" resp = Response(streamed_response_generator(chat_id, dia, msg), mimetype="text/event-stream") resp.headers.add_header("Cache-control", "no-cache") resp.headers.add_header("Connection", "keep-alive") resp.headers.add_header("X-Accel-Buffering", "no") resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8") return resp else: answer = None chat_kwargs = {"toolcall_session": toolcall_session, "tools": tools, "quote": need_reference} if doc_ids_str: chat_kwargs["doc_ids"] = doc_ids_str async for ans in async_chat(dia, msg, False, **chat_kwargs): # focus answer content only answer = ans break content = answer["answer"] response = { "id": f"chatcmpl-{chat_id}", "object": "chat.completion", "created": int(time.time()), "model": req.get("model", ""), "usage": { "prompt_tokens": len(prompt), "completion_tokens": len(content), "total_tokens": len(prompt) + len(content), "completion_tokens_details": { "reasoning_tokens": context_token_used, "accepted_prediction_tokens": len(content), "rejected_prediction_tokens": 0, # 0 for simplicity }, }, "choices": [ { "message": { "role": "assistant", "content": content, }, "logprobs": None, "finish_reason": "stop", "index": 0, } ], } if need_reference: response["choices"][0]["message"]["reference"] = chunks_format(answer.get("reference", [])) return jsonify(response) @manager.route("/agents_openai/<agent_id>/chat/completions", methods=["POST"]) # noqa: F821 @validate_request("model", "messages") # noqa: F821 @token_required async def agents_completion_openai_compatibility(tenant_id, agent_id): req = await get_request_json() tiktoken_encode = tiktoken.get_encoding("cl100k_base") messages = req.get("messages", []) if not messages: return get_error_data_result("You must provide at least one message.") if not UserCanvasService.query(user_id=tenant_id, id=agent_id): return get_error_data_result(f"You don't own the agent {agent_id}") filtered_messages = [m for m in messages if m["role"] in ["user", "assistant"]] prompt_tokens = sum(len(tiktoken_encode.encode(m["content"])) for m in filtered_messages) if not filtered_messages: return jsonify( get_data_openai( id=agent_id, content="No valid messages found (user or assistant).", finish_reason="stop", model=req.get("model", ""), completion_tokens=len(tiktoken_encode.encode("No valid messages found (user or assistant).")), prompt_tokens=prompt_tokens, ) ) question = next((m["content"] for m in reversed(messages) if m["role"] == "user"), "") stream = req.pop("stream", False) if stream: resp = Response( completion_openai( tenant_id, agent_id, question, session_id=req.pop("session_id", req.get("id", "")) or req.get("metadata", {}).get("id", ""), stream=True, **req, ), mimetype="text/event-stream", ) resp.headers.add_header("Cache-control", "no-cache") resp.headers.add_header("Connection", "keep-alive") resp.headers.add_header("X-Accel-Buffering", "no") resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8") return resp else: # For non-streaming, just return the response directly async for response in completion_openai( tenant_id, agent_id, question, session_id=req.pop("session_id", req.get("id", "")) or req.get("metadata", {}).get("id", ""), stream=False, **req, ): return jsonify(response) return None @manager.route("/agents/<agent_id>/completions", methods=["POST"]) # noqa: F821 @token_required async def agent_completions(tenant_id, agent_id): req = await get_request_json() return_trace = bool(req.get("return_trace", False)) if req.get("stream", True): async def generate(): trace_items = [] async for answer in agent_completion(tenant_id=tenant_id, agent_id=agent_id, **req): if isinstance(answer, str): try: ans = json.loads(answer[5:]) # remove "data:" except Exception: continue event = ans.get("event") if event == "node_finished": if return_trace: data = ans.get("data", {}) trace_items.append( { "component_id": data.get("component_id"), "trace": [copy.deepcopy(data)], } ) ans.setdefault("data", {})["trace"] = trace_items answer = "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n" yield answer if event not in ["message", "message_end"]: continue yield answer yield "data:[DONE]\n\n" resp = Response(generate(), mimetype="text/event-stream") resp.headers.add_header("Cache-control", "no-cache") resp.headers.add_header("Connection", "keep-alive") resp.headers.add_header("X-Accel-Buffering", "no") resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8") return resp full_content = "" reference = {} final_ans = "" trace_items = [] async for answer in agent_completion(tenant_id=tenant_id, agent_id=agent_id, **req): try: ans = json.loads(answer[5:]) if ans["event"] == "message": full_content += ans["data"]["content"] if ans.get("data", {}).get("reference", None): reference.update(ans["data"]["reference"]) if return_trace and ans.get("event") == "node_finished": data = ans.get("data", {}) trace_items.append( { "component_id": data.get("component_id"), "trace": [copy.deepcopy(data)], } ) final_ans = ans except Exception as e: return get_result(data=f"**ERROR**: {str(e)}") final_ans["data"]["content"] = full_content final_ans["data"]["reference"] = reference if return_trace and final_ans: final_ans["data"]["trace"] = trace_items return get_result(data=final_ans) @manager.route("/chats/<chat_id>/sessions", methods=["GET"]) # noqa: F821 @token_required async def list_session(tenant_id, chat_id): if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value): return get_error_data_result(message=f"You don't own the assistant {chat_id}.") id = request.args.get("id") name = request.args.get("name") page_number = int(request.args.get("page", 1)) items_per_page = int(request.args.get("page_size", 30)) orderby = request.args.get("orderby", "create_time") user_id = request.args.get("user_id") if request.args.get("desc") == "False" or request.args.get("desc") == "false": desc = False else: desc = True convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id) if not convs: return get_result(data=[]) for conv in convs: conv["messages"] = conv.pop("message") infos = conv["messages"] for info in infos: if "prompt" in info: info.pop("prompt") conv["chat_id"] = conv.pop("dialog_id") ref_messages = conv["reference"] if ref_messages: messages = conv["messages"] message_num = 0 ref_num = 0 while message_num < len(messages) and ref_num < len(ref_messages): if messages[message_num]["role"] != "user": chunk_list = [] if "chunks" in ref_messages[ref_num]: chunks = ref_messages[ref_num]["chunks"] for chunk in chunks: new_chunk = { "id": chunk.get("chunk_id", chunk.get("id")), "content": chunk.get("content_with_weight", chunk.get("content")), "document_id": chunk.get("doc_id", chunk.get("document_id")), "document_name": chunk.get("docnm_kwd", chunk.get("document_name")), "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")), "image_id": chunk.get("image_id", chunk.get("img_id")), "positions": chunk.get("positions", chunk.get("position_int")), } chunk_list.append(new_chunk) messages[message_num]["reference"] = chunk_list ref_num += 1 message_num += 1 del conv["reference"] return get_result(data=convs) @manager.route("/agents/<agent_id>/sessions", methods=["GET"]) # noqa: F821 @token_required async def list_agent_session(tenant_id, agent_id): if not UserCanvasService.query(user_id=tenant_id, id=agent_id): return get_error_data_result(message=f"You don't own the agent {agent_id}.") id = request.args.get("id") user_id = request.args.get("user_id") page_number = int(request.args.get("page", 1)) items_per_page = int(request.args.get("page_size", 30)) orderby = request.args.get("orderby", "update_time") if request.args.get("desc") == "False" or request.args.get("desc") == "false": desc = False else: desc = True # dsl defaults to True in all cases except for False and false include_dsl = request.args.get("dsl") != "False" and request.args.get("dsl") != "false" total, convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id, user_id, include_dsl) if not convs: return get_result(data=[]) for conv in convs: conv["messages"] = conv.pop("message") infos = conv["messages"] for info in infos: if "prompt" in info: info.pop("prompt") conv["agent_id"] = conv.pop("dialog_id") # Fix for session listing endpoint if conv["reference"]: messages = conv["messages"] message_num = 0 chunk_num = 0 # Ensure reference is a list type to prevent KeyError if not isinstance(conv["reference"], list): conv["reference"] = [] while message_num < len(messages): if message_num != 0 and messages[message_num]["role"] != "user": chunk_list = [] # Add boundary and type checks to prevent KeyError if chunk_num < len(conv["reference"]) and conv["reference"][chunk_num] is not None and isinstance( conv["reference"][chunk_num], dict) and "chunks" in conv["reference"][chunk_num]: chunks = conv["reference"][chunk_num]["chunks"] for chunk in chunks: # Ensure chunk is a dictionary before calling get method if not isinstance(chunk, dict): continue new_chunk = { "id": chunk.get("chunk_id", chunk.get("id")), "content": chunk.get("content_with_weight", chunk.get("content")), "document_id": chunk.get("doc_id", chunk.get("document_id")), "document_name": chunk.get("docnm_kwd", chunk.get("document_name")), "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")), "image_id": chunk.get("image_id", chunk.get("img_id")), "positions": chunk.get("positions", chunk.get("position_int")), } chunk_list.append(new_chunk) chunk_num += 1 messages[message_num]["reference"] = chunk_list message_num += 1 del conv["reference"] return get_result(data=convs) @manager.route("/chats/<chat_id>/sessions", methods=["DELETE"]) # noqa: F821 @token_required async def delete(tenant_id, chat_id): if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value): return get_error_data_result(message="You don't own the chat") errors = [] success_count = 0 req = await get_request_json() convs = ConversationService.query(dialog_id=chat_id) if not req: ids = None else: ids = req.get("ids") if not ids: conv_list = [] for conv in convs: conv_list.append(conv.id) else: conv_list = ids unique_conv_ids, duplicate_messages = check_duplicate_ids(conv_list, "session") conv_list = unique_conv_ids for id in conv_list: conv = ConversationService.query(id=id, dialog_id=chat_id) if not conv: errors.append(f"The chat doesn't own the session {id}") continue ConversationService.delete_by_id(id) success_count += 1 if errors: if success_count > 0: return get_result(data={"success_count": success_count, "errors": errors}, message=f"Partially deleted {success_count} sessions with {len(errors)} errors") else: return get_error_data_result(message="; ".join(errors)) if duplicate_messages: if success_count > 0: return get_result( message=f"Partially deleted {success_count} sessions with {len(duplicate_messages)} errors", data={"success_count": success_count, "errors": duplicate_messages}) else: return get_error_data_result(message=";".join(duplicate_messages)) return get_result() @manager.route("/agents/<agent_id>/sessions", methods=["DELETE"]) # noqa: F821 @token_required async def delete_agent_session(tenant_id, agent_id): errors = [] success_count = 0 req = await get_request_json() cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id) if not cvs: return get_error_data_result(f"You don't own the agent {agent_id}") convs = API4ConversationService.query(dialog_id=agent_id) if not convs: return get_error_data_result(f"Agent {agent_id} has no sessions") if not req: ids = None else: ids = req.get("ids") if not ids: conv_list = [] for conv in convs: conv_list.append(conv.id) else: conv_list = ids unique_conv_ids, duplicate_messages = check_duplicate_ids(conv_list, "session")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/apps/sdk/agents.py
api/apps/sdk/agents.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 hashlib import hmac import ipaddress import json import logging import time from typing import Any, cast import jwt from agent.canvas import Canvas from api.db import CanvasCategory from api.db.services.canvas_service import UserCanvasService from api.db.services.file_service import FileService from api.db.services.user_canvas_version import UserCanvasVersionService from common.constants import RetCode from common.misc_utils import get_uuid from api.utils.api_utils import get_data_error_result, get_error_data_result, get_json_result, get_request_json, token_required from api.utils.api_utils import get_result from quart import request, Response from rag.utils.redis_conn import REDIS_CONN @manager.route('/agents', methods=['GET']) # noqa: F821 @token_required def list_agents(tenant_id): id = request.args.get("id") title = request.args.get("title") if id or title: canvas = UserCanvasService.query(id=id, title=title, user_id=tenant_id) if not canvas: return get_error_data_result("The agent doesn't exist.") page_number = int(request.args.get("page", 1)) items_per_page = int(request.args.get("page_size", 30)) order_by = request.args.get("orderby", "update_time") if request.args.get("desc") == "False" or request.args.get("desc") == "false": desc = False else: desc = True canvas = UserCanvasService.get_list(tenant_id, page_number, items_per_page, order_by, desc, id, title) return get_result(data=canvas) @manager.route("/agents", methods=["POST"]) # noqa: F821 @token_required async def create_agent(tenant_id: str): req: dict[str, Any] = cast(dict[str, Any], await get_request_json()) req["user_id"] = tenant_id if req.get("dsl") is not None: if not isinstance(req["dsl"], str): req["dsl"] = json.dumps(req["dsl"], ensure_ascii=False) req["dsl"] = json.loads(req["dsl"]) else: return get_json_result(data=False, message="No DSL data in request.", code=RetCode.ARGUMENT_ERROR) if req.get("title") is not None: req["title"] = req["title"].strip() else: return get_json_result(data=False, message="No title in request.", code=RetCode.ARGUMENT_ERROR) if UserCanvasService.query(user_id=tenant_id, title=req["title"]): return get_data_error_result(message=f"Agent with title {req['title']} already exists.") agent_id = get_uuid() req["id"] = agent_id if not UserCanvasService.save(**req): return get_data_error_result(message="Fail to create agent.") UserCanvasVersionService.insert( user_canvas_id=agent_id, title="{0}_{1}".format(req["title"], time.strftime("%Y_%m_%d_%H_%M_%S")), dsl=req["dsl"] ) return get_json_result(data=True) @manager.route("/agents/<agent_id>", methods=["PUT"]) # noqa: F821 @token_required async def update_agent(tenant_id: str, agent_id: str): req: dict[str, Any] = {k: v for k, v in cast(dict[str, Any], (await get_request_json())).items() if v is not None} req["user_id"] = tenant_id if req.get("dsl") is not None: if not isinstance(req["dsl"], str): req["dsl"] = json.dumps(req["dsl"], ensure_ascii=False) req["dsl"] = json.loads(req["dsl"]) if req.get("title") is not None: req["title"] = req["title"].strip() if not UserCanvasService.query(user_id=tenant_id, id=agent_id): return get_json_result( data=False, message="Only owner of canvas authorized for this operation.", code=RetCode.OPERATING_ERROR) UserCanvasService.update_by_id(agent_id, req) if req.get("dsl") is not None: UserCanvasVersionService.insert( user_canvas_id=agent_id, title="{0}_{1}".format(req["title"], time.strftime("%Y_%m_%d_%H_%M_%S")), dsl=req["dsl"] ) UserCanvasVersionService.delete_all_versions(agent_id) return get_json_result(data=True) @manager.route("/agents/<agent_id>", methods=["DELETE"]) # noqa: F821 @token_required def delete_agent(tenant_id: str, agent_id: str): if not UserCanvasService.query(user_id=tenant_id, id=agent_id): return get_json_result( data=False, message="Only owner of canvas authorized for this operation.", code=RetCode.OPERATING_ERROR) UserCanvasService.delete_by_id(agent_id) return get_json_result(data=True) @manager.route("/webhook/<agent_id>", methods=["POST", "GET", "PUT", "PATCH", "DELETE", "HEAD"]) # noqa: F821 @manager.route("/webhook_test/<agent_id>",methods=["POST", "GET", "PUT", "PATCH", "DELETE", "HEAD"],) # noqa: F821 async def webhook(agent_id: str): is_test = request.path.startswith("/api/v1/webhook_test") start_ts = time.time() # 1. Fetch canvas by agent_id exists, cvs = UserCanvasService.get_by_id(agent_id) if not exists: return get_data_error_result(code=RetCode.BAD_REQUEST,message="Canvas not found."),RetCode.BAD_REQUEST # 2. Check canvas category if cvs.canvas_category == CanvasCategory.DataFlow: return get_data_error_result(code=RetCode.BAD_REQUEST,message="Dataflow can not be triggered by webhook."),RetCode.BAD_REQUEST # 3. Load DSL from canvas dsl = getattr(cvs, "dsl", None) if not isinstance(dsl, dict): return get_data_error_result(code=RetCode.BAD_REQUEST,message="Invalid DSL format."),RetCode.BAD_REQUEST # 4. Check webhook configuration in DSL webhook_cfg = {} components = dsl.get("components", {}) for k, _ in components.items(): cpn_obj = components[k]["obj"] if cpn_obj["component_name"].lower() == "begin" and cpn_obj["params"]["mode"] == "Webhook": webhook_cfg = cpn_obj["params"] if not webhook_cfg: return get_data_error_result(code=RetCode.BAD_REQUEST,message="Webhook not configured for this agent."),RetCode.BAD_REQUEST # 5. Validate request method against webhook_cfg.methods allowed_methods = webhook_cfg.get("methods", []) request_method = request.method.upper() if allowed_methods and request_method not in allowed_methods: return get_data_error_result( code=RetCode.BAD_REQUEST,message=f"HTTP method '{request_method}' not allowed for this webhook." ),RetCode.BAD_REQUEST # 6. Validate webhook security async def validate_webhook_security(security_cfg: dict): """Validate webhook security rules based on security configuration.""" if not security_cfg: return # No security config → allowed by default # 1. Validate max body size await _validate_max_body_size(security_cfg) # 2. Validate IP whitelist _validate_ip_whitelist(security_cfg) # # 3. Validate rate limiting _validate_rate_limit(security_cfg) # 4. Validate authentication auth_type = security_cfg.get("auth_type", "none") if auth_type == "none": return if auth_type == "token": _validate_token_auth(security_cfg) elif auth_type == "basic": _validate_basic_auth(security_cfg) elif auth_type == "jwt": _validate_jwt_auth(security_cfg) else: raise Exception(f"Unsupported auth_type: {auth_type}") async def _validate_max_body_size(security_cfg): """Check request size does not exceed max_body_size.""" max_size = security_cfg.get("max_body_size") if not max_size: return # Convert "10MB" → bytes units = {"kb": 1024, "mb": 1024**2} size_str = max_size.lower() for suffix, factor in units.items(): if size_str.endswith(suffix): limit = int(size_str.replace(suffix, "")) * factor break else: raise Exception("Invalid max_body_size format") MAX_LIMIT = 10 * 1024 * 1024 # 10MB if limit > MAX_LIMIT: raise Exception("max_body_size exceeds maximum allowed size (10MB)") content_length = request.content_length or 0 if content_length > limit: raise Exception(f"Request body too large: {content_length} > {limit}") def _validate_ip_whitelist(security_cfg): """Allow only IPs listed in ip_whitelist.""" whitelist = security_cfg.get("ip_whitelist", []) if not whitelist: return client_ip = request.remote_addr for rule in whitelist: if "/" in rule: # CIDR notation if ipaddress.ip_address(client_ip) in ipaddress.ip_network(rule, strict=False): return else: # Single IP if client_ip == rule: return raise Exception(f"IP {client_ip} is not allowed by whitelist") def _validate_rate_limit(security_cfg): """Simple in-memory rate limiting.""" rl = security_cfg.get("rate_limit") if not rl: return limit = int(rl.get("limit", 60)) if limit <= 0: raise Exception("rate_limit.limit must be > 0") per = rl.get("per", "minute") window = { "second": 1, "minute": 60, "hour": 3600, "day": 86400, }.get(per) if not window: raise Exception(f"Invalid rate_limit.per: {per}") capacity = limit rate = limit / window cost = 1 key = f"rl:tb:{agent_id}" now = time.time() try: res = REDIS_CONN.lua_token_bucket( keys=[key], args=[capacity, rate, now, cost], client=REDIS_CONN.REDIS, ) allowed = int(res[0]) if allowed != 1: raise Exception("Too many requests (rate limit exceeded)") except Exception as e: raise Exception(f"Rate limit error: {e}") def _validate_token_auth(security_cfg): """Validate header-based token authentication.""" token_cfg = security_cfg.get("token",{}) header = token_cfg.get("token_header") token_value = token_cfg.get("token_value") provided = request.headers.get(header) if provided != token_value: raise Exception("Invalid token authentication") def _validate_basic_auth(security_cfg): """Validate HTTP Basic Auth credentials.""" auth_cfg = security_cfg.get("basic_auth", {}) username = auth_cfg.get("username") password = auth_cfg.get("password") auth = request.authorization if not auth or auth.username != username or auth.password != password: raise Exception("Invalid Basic Auth credentials") def _validate_jwt_auth(security_cfg): """Validate JWT token in Authorization header.""" jwt_cfg = security_cfg.get("jwt", {}) secret = jwt_cfg.get("secret") if not secret: raise Exception("JWT secret not configured") auth_header = request.headers.get("Authorization", "") if not auth_header.startswith("Bearer "): raise Exception("Missing Bearer token") token = auth_header[len("Bearer "):].strip() if not token: raise Exception("Empty Bearer token") alg = (jwt_cfg.get("algorithm") or "HS256").upper() decode_kwargs = { "key": secret, "algorithms": [alg], } options = {} if jwt_cfg.get("audience"): decode_kwargs["audience"] = jwt_cfg["audience"] options["verify_aud"] = True else: options["verify_aud"] = False if jwt_cfg.get("issuer"): decode_kwargs["issuer"] = jwt_cfg["issuer"] options["verify_iss"] = True else: options["verify_iss"] = False try: decoded = jwt.decode( token, options=options, **decode_kwargs, ) except Exception as e: raise Exception(f"Invalid JWT: {str(e)}") raw_required_claims = jwt_cfg.get("required_claims", []) if isinstance(raw_required_claims, str): required_claims = [raw_required_claims] elif isinstance(raw_required_claims, (list, tuple, set)): required_claims = list(raw_required_claims) else: required_claims = [] required_claims = [ c for c in required_claims if isinstance(c, str) and c.strip() ] RESERVED_CLAIMS = {"exp", "sub", "aud", "iss", "nbf", "iat"} for claim in required_claims: if claim in RESERVED_CLAIMS: raise Exception(f"Reserved JWT claim cannot be required: {claim}") for claim in required_claims: if claim not in decoded: raise Exception(f"Missing JWT claim: {claim}") return decoded try: security_config=webhook_cfg.get("security", {}) await validate_webhook_security(security_config) except Exception as e: return get_data_error_result(code=RetCode.BAD_REQUEST,message=str(e)),RetCode.BAD_REQUEST if not isinstance(cvs.dsl, str): dsl = json.dumps(cvs.dsl, ensure_ascii=False) try: canvas = Canvas(dsl, cvs.user_id, agent_id, canvas_id=agent_id) except Exception as e: resp=get_data_error_result(code=RetCode.BAD_REQUEST,message=str(e)) resp.status_code = RetCode.BAD_REQUEST return resp # 7. Parse request body async def parse_webhook_request(content_type): """Parse request based on content-type and return structured data.""" # 1. Query query_data = {k: v for k, v in request.args.items()} # 2. Headers header_data = {k: v for k, v in request.headers.items()} # 3. Body ctype = request.headers.get("Content-Type", "").split(";")[0].strip() if ctype and ctype != content_type: raise ValueError( f"Invalid Content-Type: expect '{content_type}', got '{ctype}'" ) body_data: dict = {} try: if ctype == "application/json": body_data = await request.get_json() or {} elif ctype == "multipart/form-data": nonlocal canvas form = await request.form files = await request.files body_data = {} for key, value in form.items(): body_data[key] = value if len(files) > 10: raise Exception("Too many uploaded files") for key, file in files.items(): desc = FileService.upload_info( cvs.user_id, # user file, # FileStorage None # url (None for webhook) ) file_parsed= await canvas.get_files_async([desc]) body_data[key] = file_parsed elif ctype == "application/x-www-form-urlencoded": form = await request.form body_data = dict(form) else: # text/plain / octet-stream / empty / unknown raw = await request.get_data() if raw: try: body_data = json.loads(raw.decode("utf-8")) except Exception: body_data = {} else: body_data = {} except Exception: body_data = {} return { "query": query_data, "headers": header_data, "body": body_data, "content_type": ctype, } def extract_by_schema(data, schema, name="section"): """ Extract only fields defined in schema. Required fields must exist. Optional fields default to type-based default values. Type validation included. """ props = schema.get("properties", {}) required = schema.get("required", []) extracted = {} for field, field_schema in props.items(): field_type = field_schema.get("type") # 1. Required field missing if field in required and field not in data: raise Exception(f"{name} missing required field: {field}") # 2. Optional → default value if field not in data: extracted[field] = default_for_type(field_type) continue raw_value = data[field] # 3. Auto convert value try: value = auto_cast_value(raw_value, field_type) except Exception as e: raise Exception(f"{name}.{field} auto-cast failed: {str(e)}") # 4. Type validation if not validate_type(value, field_type): raise Exception( f"{name}.{field} type mismatch: expected {field_type}, got {type(value).__name__}" ) extracted[field] = value return extracted def default_for_type(t): """Return default value for the given schema type.""" if t == "file": return [] if t == "object": return {} if t == "boolean": return False if t == "number": return 0 if t == "string": return "" if t and t.startswith("array"): return [] if t == "null": return None return None def auto_cast_value(value, expected_type): """Convert string values into schema type when possible.""" # Non-string values already good if not isinstance(value, str): return value v = value.strip() # Boolean if expected_type == "boolean": if v.lower() in ["true", "1"]: return True if v.lower() in ["false", "0"]: return False raise Exception(f"Cannot convert '{value}' to boolean") # Number if expected_type == "number": # integer if v.isdigit() or (v.startswith("-") and v[1:].isdigit()): return int(v) # float try: return float(v) except Exception: raise Exception(f"Cannot convert '{value}' to number") # Object if expected_type == "object": try: parsed = json.loads(v) if isinstance(parsed, dict): return parsed else: raise Exception("JSON is not an object") except Exception: raise Exception(f"Cannot convert '{value}' to object") # Array <T> if expected_type.startswith("array"): try: parsed = json.loads(v) if isinstance(parsed, list): return parsed else: raise Exception("JSON is not an array") except Exception: raise Exception(f"Cannot convert '{value}' to array") # String (accept original) if expected_type == "string": return value # File if expected_type == "file": return value # Default: do nothing return value def validate_type(value, t): """Validate value type against schema type t.""" if t == "file": return isinstance(value, list) if t == "string": return isinstance(value, str) if t == "number": return isinstance(value, (int, float)) if t == "boolean": return isinstance(value, bool) if t == "object": return isinstance(value, dict) # array<string> / array<number> / array<object> if t.startswith("array"): if not isinstance(value, list): return False if "<" in t and ">" in t: inner = t[t.find("<") + 1 : t.find(">")] # Check each element type for item in value: if not validate_type(item, inner): return False return True return True parsed = await parse_webhook_request(webhook_cfg.get("content_types")) SCHEMA = webhook_cfg.get("schema", {"query": {}, "headers": {}, "body": {}}) # Extract strictly by schema try: query_clean = extract_by_schema(parsed["query"], SCHEMA.get("query", {}), name="query") header_clean = extract_by_schema(parsed["headers"], SCHEMA.get("headers", {}), name="headers") body_clean = extract_by_schema(parsed["body"], SCHEMA.get("body", {}), name="body") except Exception as e: return get_data_error_result(code=RetCode.BAD_REQUEST,message=str(e)),RetCode.BAD_REQUEST clean_request = { "query": query_clean, "headers": header_clean, "body": body_clean, "input": parsed } execution_mode = webhook_cfg.get("execution_mode", "Immediately") response_cfg = webhook_cfg.get("response", {}) def append_webhook_trace(agent_id: str, start_ts: float,event: dict, ttl=600): key = f"webhook-trace-{agent_id}-logs" raw = REDIS_CONN.get(key) obj = json.loads(raw) if raw else {"webhooks": {}} ws = obj["webhooks"].setdefault( str(start_ts), {"start_ts": start_ts, "events": []} ) ws["events"].append({ "ts": time.time(), **event }) REDIS_CONN.set_obj(key, obj, ttl) if execution_mode == "Immediately": status = response_cfg.get("status", 200) try: status = int(status) except (TypeError, ValueError): return get_data_error_result(code=RetCode.BAD_REQUEST,message=str(f"Invalid response status code: {status}")),RetCode.BAD_REQUEST if not (200 <= status <= 399): return get_data_error_result(code=RetCode.BAD_REQUEST,message=str(f"Invalid response status code: {status}, must be between 200 and 399")),RetCode.BAD_REQUEST body_tpl = response_cfg.get("body_template", "") def parse_body(body: str): if not body: return None, "application/json" try: parsed = json.loads(body) return parsed, "application/json" except (json.JSONDecodeError, TypeError): return body, "text/plain" body, content_type = parse_body(body_tpl) resp = Response( json.dumps(body, ensure_ascii=False) if content_type == "application/json" else body, status=status, content_type=content_type, ) async def background_run(): try: async for ans in canvas.run( query="", user_id=cvs.user_id, webhook_payload=clean_request ): if is_test: append_webhook_trace(agent_id, start_ts, ans) if is_test: append_webhook_trace( agent_id, start_ts, { "event": "finished", "elapsed_time": time.time() - start_ts, "success": True, } ) cvs.dsl = json.loads(str(canvas)) UserCanvasService.update_by_id(cvs.user_id, cvs.to_dict()) except Exception as e: logging.exception("Webhook background run failed") if is_test: try: append_webhook_trace( agent_id, start_ts, { "event": "error", "message": str(e), "error_type": type(e).__name__, } ) append_webhook_trace( agent_id, start_ts, { "event": "finished", "elapsed_time": time.time() - start_ts, "success": False, } ) except Exception: logging.exception("Failed to append webhook trace") asyncio.create_task(background_run()) return resp else: async def sse(): nonlocal canvas contents: list[str] = [] status = 200 try: async for ans in canvas.run( query="", user_id=cvs.user_id, webhook_payload=clean_request, ): if ans["event"] == "message": content = ans["data"]["content"] if ans["data"].get("start_to_think", False): content = "<think>" elif ans["data"].get("end_to_think", False): content = "</think>" if content: contents.append(content) if ans["event"] == "message_end": status = int(ans["data"].get("status", status)) if is_test: append_webhook_trace( agent_id, start_ts, ans ) if is_test: append_webhook_trace( agent_id, start_ts, { "event": "finished", "elapsed_time": time.time() - start_ts, "success": True, } ) final_content = "".join(contents) return { "message": final_content, "success": True, "code": status, } except Exception as e: if is_test: append_webhook_trace( agent_id, start_ts, { "event": "error", "message": str(e), "error_type": type(e).__name__, } ) append_webhook_trace( agent_id, start_ts, { "event": "finished", "elapsed_time": time.time() - start_ts, "success": False, } ) return {"code": 400, "message": str(e),"success":False} result = await sse() return Response( json.dumps(result), status=result["code"], mimetype="application/json", ) @manager.route("/webhook_trace/<agent_id>", methods=["GET"]) # noqa: F821 async def webhook_trace(agent_id: str): def encode_webhook_id(start_ts: str) -> str: WEBHOOK_ID_SECRET = "webhook_id_secret" sig = hmac.new( WEBHOOK_ID_SECRET.encode("utf-8"), start_ts.encode("utf-8"), hashlib.sha256, ).digest() return base64.urlsafe_b64encode(sig).decode("utf-8").rstrip("=") def decode_webhook_id(enc_id: str, webhooks: dict) -> str | None: for ts in webhooks.keys(): if encode_webhook_id(ts) == enc_id: return ts return None since_ts = request.args.get("since_ts", type=float) webhook_id = request.args.get("webhook_id") key = f"webhook-trace-{agent_id}-logs" raw = REDIS_CONN.get(key) if since_ts is None: now = time.time() return get_json_result( data={ "webhook_id": None, "events": [], "next_since_ts": now, "finished": False, } ) if not raw: return get_json_result( data={ "webhook_id": None, "events": [], "next_since_ts": since_ts, "finished": False, } ) obj = json.loads(raw) webhooks = obj.get("webhooks", {}) if webhook_id is None: candidates = [ float(k) for k in webhooks.keys() if float(k) > since_ts ] if not candidates: return get_json_result( data={ "webhook_id": None, "events": [], "next_since_ts": since_ts, "finished": False, } ) start_ts = min(candidates) real_id = str(start_ts) webhook_id = encode_webhook_id(real_id) return get_json_result( data={ "webhook_id": webhook_id, "events": [], "next_since_ts": start_ts, "finished": False, } ) real_id = decode_webhook_id(webhook_id, webhooks) if not real_id: return get_json_result( data={ "webhook_id": webhook_id, "events": [], "next_since_ts": since_ts, "finished": True, } ) ws = webhooks.get(str(real_id)) events = ws.get("events", []) new_events = [e for e in events if e.get("ts", 0) > since_ts] next_ts = since_ts for e in new_events: next_ts = max(next_ts, e["ts"]) finished = any(e.get("event") == "finished" for e in new_events) return get_json_result( data={ "webhook_id": webhook_id, "events": new_events, "next_since_ts": next_ts, "finished": finished, } )
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/db_models.py
api/db/db_models.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 hashlib import inspect import logging import operator import os import sys import time import typing from datetime import datetime, timezone from enum import Enum from functools import wraps from quart_auth import AuthUser from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer from peewee import InterfaceError, OperationalError, BigIntegerField, BooleanField, CharField, CompositeKey, DateTimeField, Field, FloatField, IntegerField, Metadata, Model, TextField from playhouse.migrate import MySQLMigrator, PostgresqlMigrator, migrate from playhouse.pool import PooledMySQLDatabase, PooledPostgresqlDatabase from api import utils from api.db import SerializedType from api.utils.json_encode import json_dumps, json_loads from api.utils.configs import deserialize_b64, serialize_b64 from common.time_utils import current_timestamp, timestamp_to_date, date_string_to_timestamp from common.decorator import singleton from common.constants import ParserType from common import settings CONTINUOUS_FIELD_TYPE = {IntegerField, FloatField, DateTimeField} AUTO_DATE_TIMESTAMP_FIELD_PREFIX = {"create", "start", "end", "update", "read_access", "write_access"} class TextFieldType(Enum): MYSQL = "LONGTEXT" POSTGRES = "TEXT" class LongTextField(TextField): field_type = TextFieldType[settings.DATABASE_TYPE.upper()].value class JSONField(LongTextField): default_value = {} def __init__(self, object_hook=None, object_pairs_hook=None, **kwargs): self._object_hook = object_hook self._object_pairs_hook = object_pairs_hook super().__init__(**kwargs) def db_value(self, value): if value is None: value = self.default_value return json_dumps(value) def python_value(self, value): if not value: return self.default_value return json_loads(value, object_hook=self._object_hook, object_pairs_hook=self._object_pairs_hook) class ListField(JSONField): default_value = [] class SerializedField(LongTextField): def __init__(self, serialized_type=SerializedType.PICKLE, object_hook=None, object_pairs_hook=None, **kwargs): self._serialized_type = serialized_type self._object_hook = object_hook self._object_pairs_hook = object_pairs_hook super().__init__(**kwargs) def db_value(self, value): if self._serialized_type == SerializedType.PICKLE: return serialize_b64(value, to_str=True) elif self._serialized_type == SerializedType.JSON: if value is None: return None return json_dumps(value, with_type=True) else: raise ValueError(f"the serialized type {self._serialized_type} is not supported") def python_value(self, value): if self._serialized_type == SerializedType.PICKLE: return deserialize_b64(value) elif self._serialized_type == SerializedType.JSON: if value is None: return {} return json_loads(value, object_hook=self._object_hook, object_pairs_hook=self._object_pairs_hook) else: raise ValueError(f"the serialized type {self._serialized_type} is not supported") def is_continuous_field(cls: typing.Type) -> bool: if cls in CONTINUOUS_FIELD_TYPE: return True for p in cls.__bases__: if p in CONTINUOUS_FIELD_TYPE: return True elif p is not Field and p is not object: if is_continuous_field(p): return True else: return False def auto_date_timestamp_field(): return {f"{f}_time" for f in AUTO_DATE_TIMESTAMP_FIELD_PREFIX} def auto_date_timestamp_db_field(): return {f"f_{f}_time" for f in AUTO_DATE_TIMESTAMP_FIELD_PREFIX} def remove_field_name_prefix(field_name): return field_name[2:] if field_name.startswith("f_") else field_name class BaseModel(Model): create_time = BigIntegerField(null=True, index=True) create_date = DateTimeField(null=True, index=True) update_time = BigIntegerField(null=True, index=True) update_date = DateTimeField(null=True, index=True) def to_json(self): # This function is obsolete return self.to_dict() def to_dict(self): return self.__dict__["__data__"] def to_human_model_dict(self, only_primary_with: list = None): model_dict = self.__dict__["__data__"] if not only_primary_with: return {remove_field_name_prefix(k): v for k, v in model_dict.items()} human_model_dict = {} for k in self._meta.primary_key.field_names: human_model_dict[remove_field_name_prefix(k)] = model_dict[k] for k in only_primary_with: human_model_dict[k] = model_dict[f"f_{k}"] return human_model_dict @property def meta(self) -> Metadata: return self._meta @classmethod def get_primary_keys_name(cls): return cls._meta.primary_key.field_names if isinstance(cls._meta.primary_key, CompositeKey) else [cls._meta.primary_key.name] @classmethod def getter_by(cls, attr): return operator.attrgetter(attr)(cls) @classmethod def query(cls, reverse=None, order_by=None, **kwargs): filters = [] for f_n, f_v in kwargs.items(): attr_name = "%s" % f_n if not hasattr(cls, attr_name) or f_v is None: continue if type(f_v) in {list, set}: f_v = list(f_v) if is_continuous_field(type(getattr(cls, attr_name))): if len(f_v) == 2: for i, v in enumerate(f_v): if isinstance(v, str) and f_n in auto_date_timestamp_field(): # time type: %Y-%m-%d %H:%M:%S f_v[i] = date_string_to_timestamp(v) lt_value = f_v[0] gt_value = f_v[1] if lt_value is not None and gt_value is not None: filters.append(cls.getter_by(attr_name).between(lt_value, gt_value)) elif lt_value is not None: filters.append(operator.attrgetter(attr_name)(cls) >= lt_value) elif gt_value is not None: filters.append(operator.attrgetter(attr_name)(cls) <= gt_value) else: filters.append(operator.attrgetter(attr_name)(cls) << f_v) else: filters.append(operator.attrgetter(attr_name)(cls) == f_v) if filters: query_records = cls.select().where(*filters) if reverse is not None: if not order_by or not hasattr(cls, f"{order_by}"): order_by = "create_time" if reverse is True: query_records = query_records.order_by(cls.getter_by(f"{order_by}").desc()) elif reverse is False: query_records = query_records.order_by(cls.getter_by(f"{order_by}").asc()) return [query_record for query_record in query_records] else: return [] @classmethod def insert(cls, __data=None, **insert): if isinstance(__data, dict) and __data: __data[cls._meta.combined["create_time"]] = current_timestamp() if insert: insert["create_time"] = current_timestamp() return super().insert(__data, **insert) # update and insert will call this method @classmethod def _normalize_data(cls, data, kwargs): normalized = super()._normalize_data(data, kwargs) if not normalized: return {} normalized[cls._meta.combined["update_time"]] = current_timestamp() for f_n in AUTO_DATE_TIMESTAMP_FIELD_PREFIX: if {f"{f_n}_time", f"{f_n}_date"}.issubset(cls._meta.combined.keys()) and cls._meta.combined[f"{f_n}_time"] in normalized and normalized[cls._meta.combined[f"{f_n}_time"]] is not None: normalized[cls._meta.combined[f"{f_n}_date"]] = timestamp_to_date(normalized[cls._meta.combined[f"{f_n}_time"]]) return normalized class JsonSerializedField(SerializedField): def __init__(self, object_hook=utils.from_dict_hook, object_pairs_hook=None, **kwargs): super(JsonSerializedField, self).__init__(serialized_type=SerializedType.JSON, object_hook=object_hook, object_pairs_hook=object_pairs_hook, **kwargs) class RetryingPooledMySQLDatabase(PooledMySQLDatabase): def __init__(self, *args, **kwargs): self.max_retries = kwargs.pop("max_retries", 5) self.retry_delay = kwargs.pop("retry_delay", 1) super().__init__(*args, **kwargs) def execute_sql(self, sql, params=None, commit=True): for attempt in range(self.max_retries + 1): try: return super().execute_sql(sql, params, commit) except (OperationalError, InterfaceError) as e: error_codes = [2013, 2006] error_messages = ['', 'Lost connection'] should_retry = ( (hasattr(e, 'args') and e.args and e.args[0] in error_codes) or (str(e) in error_messages) or (hasattr(e, '__class__') and e.__class__.__name__ == 'InterfaceError') ) if should_retry and attempt < self.max_retries: logging.warning( f"Database connection issue (attempt {attempt+1}/{self.max_retries}): {e}" ) self._handle_connection_loss() time.sleep(self.retry_delay * (2 ** attempt)) else: logging.error(f"DB execution failure: {e}") raise return None def _handle_connection_loss(self): # self.close_all() # self.connect() try: self.close() except Exception: pass try: self.connect() except Exception as e: logging.error(f"Failed to reconnect: {e}") time.sleep(0.1) self.connect() def begin(self): for attempt in range(self.max_retries + 1): try: return super().begin() except (OperationalError, InterfaceError) as e: error_codes = [2013, 2006] error_messages = ['', 'Lost connection'] should_retry = ( (hasattr(e, 'args') and e.args and e.args[0] in error_codes) or (str(e) in error_messages) or (hasattr(e, '__class__') and e.__class__.__name__ == 'InterfaceError') ) if should_retry and attempt < self.max_retries: logging.warning( f"Lost connection during transaction (attempt {attempt+1}/{self.max_retries})" ) self._handle_connection_loss() time.sleep(self.retry_delay * (2 ** attempt)) else: raise return None class RetryingPooledPostgresqlDatabase(PooledPostgresqlDatabase): def __init__(self, *args, **kwargs): self.max_retries = kwargs.pop("max_retries", 5) self.retry_delay = kwargs.pop("retry_delay", 1) super().__init__(*args, **kwargs) def execute_sql(self, sql, params=None, commit=True): for attempt in range(self.max_retries + 1): try: return super().execute_sql(sql, params, commit) except (OperationalError, InterfaceError) as e: # PostgreSQL specific error codes # 57P01: admin_shutdown # 57P02: crash_shutdown # 57P03: cannot_connect_now # 08006: connection_failure # 08003: connection_does_not_exist # 08000: connection_exception error_messages = ['connection', 'server closed', 'connection refused', 'no connection to the server', 'terminating connection'] should_retry = any(msg in str(e).lower() for msg in error_messages) if should_retry and attempt < self.max_retries: logging.warning( f"PostgreSQL connection issue (attempt {attempt+1}/{self.max_retries}): {e}" ) self._handle_connection_loss() time.sleep(self.retry_delay * (2 ** attempt)) else: logging.error(f"PostgreSQL execution failure: {e}") raise return None def _handle_connection_loss(self): try: self.close() except Exception: pass try: self.connect() except Exception as e: logging.error(f"Failed to reconnect to PostgreSQL: {e}") time.sleep(0.1) self.connect() def begin(self): for attempt in range(self.max_retries + 1): try: return super().begin() except (OperationalError, InterfaceError) as e: error_messages = ['connection', 'server closed', 'connection refused', 'no connection to the server', 'terminating connection'] should_retry = any(msg in str(e).lower() for msg in error_messages) if should_retry and attempt < self.max_retries: logging.warning( f"PostgreSQL connection lost during transaction (attempt {attempt+1}/{self.max_retries})" ) self._handle_connection_loss() time.sleep(self.retry_delay * (2 ** attempt)) else: raise return None class PooledDatabase(Enum): MYSQL = RetryingPooledMySQLDatabase POSTGRES = RetryingPooledPostgresqlDatabase class DatabaseMigrator(Enum): MYSQL = MySQLMigrator POSTGRES = PostgresqlMigrator @singleton class BaseDataBase: def __init__(self): database_config = settings.DATABASE.copy() db_name = database_config.pop("name") pool_config = { 'max_retries': 5, 'retry_delay': 1, } database_config.update(pool_config) self.database_connection = PooledDatabase[settings.DATABASE_TYPE.upper()].value( db_name, **database_config ) # self.database_connection = PooledDatabase[settings.DATABASE_TYPE.upper()].value(db_name, **database_config) logging.info("init database on cluster mode successfully") def with_retry(max_retries=3, retry_delay=1.0): """Decorator: Add retry mechanism to database operations Args: max_retries (int): maximum number of retries retry_delay (float): initial retry delay (seconds), will increase exponentially Returns: decorated function """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): last_exception = None for retry in range(max_retries): try: return func(*args, **kwargs) except Exception as e: last_exception = e # get self and method name for logging self_obj = args[0] if args else None func_name = func.__name__ lock_name = getattr(self_obj, "lock_name", "unknown") if self_obj else "unknown" if retry < max_retries - 1: current_delay = retry_delay * (2**retry) logging.warning(f"{func_name} {lock_name} failed: {str(e)}, retrying ({retry + 1}/{max_retries})") time.sleep(current_delay) else: logging.error(f"{func_name} {lock_name} failed after all attempts: {str(e)}") if last_exception: raise last_exception return False return wrapper return decorator class PostgresDatabaseLock: def __init__(self, lock_name, timeout=10, db=None): self.lock_name = lock_name self.lock_id = int(hashlib.md5(lock_name.encode()).hexdigest(), 16) % (2**31 - 1) self.timeout = int(timeout) self.db = db if db else DB @with_retry(max_retries=3, retry_delay=1.0) def lock(self): cursor = self.db.execute_sql("SELECT pg_try_advisory_lock(%s)", (self.lock_id,)) ret = cursor.fetchone() if ret[0] == 0: raise Exception(f"acquire postgres lock {self.lock_name} timeout") elif ret[0] == 1: return True else: raise Exception(f"failed to acquire lock {self.lock_name}") @with_retry(max_retries=3, retry_delay=1.0) def unlock(self): cursor = self.db.execute_sql("SELECT pg_advisory_unlock(%s)", (self.lock_id,)) ret = cursor.fetchone() if ret[0] == 0: raise Exception(f"postgres lock {self.lock_name} was not established by this thread") elif ret[0] == 1: return True else: raise Exception(f"postgres lock {self.lock_name} does not exist") def __enter__(self): if isinstance(self.db, PooledPostgresqlDatabase): self.lock() return self def __exit__(self, exc_type, exc_val, exc_tb): if isinstance(self.db, PooledPostgresqlDatabase): self.unlock() def __call__(self, func): @wraps(func) def magic(*args, **kwargs): with self: return func(*args, **kwargs) return magic class MysqlDatabaseLock: def __init__(self, lock_name, timeout=10, db=None): self.lock_name = lock_name self.timeout = int(timeout) self.db = db if db else DB @with_retry(max_retries=3, retry_delay=1.0) def lock(self): # SQL parameters only support %s format placeholders cursor = self.db.execute_sql("SELECT GET_LOCK(%s, %s)", (self.lock_name, self.timeout)) ret = cursor.fetchone() if ret[0] == 0: raise Exception(f"acquire mysql lock {self.lock_name} timeout") elif ret[0] == 1: return True else: raise Exception(f"failed to acquire lock {self.lock_name}") @with_retry(max_retries=3, retry_delay=1.0) def unlock(self): cursor = self.db.execute_sql("SELECT RELEASE_LOCK(%s)", (self.lock_name,)) ret = cursor.fetchone() if ret[0] == 0: raise Exception(f"mysql lock {self.lock_name} was not established by this thread") elif ret[0] == 1: return True else: raise Exception(f"mysql lock {self.lock_name} does not exist") def __enter__(self): if isinstance(self.db, PooledMySQLDatabase): self.lock() return self def __exit__(self, exc_type, exc_val, exc_tb): if isinstance(self.db, PooledMySQLDatabase): self.unlock() def __call__(self, func): @wraps(func) def magic(*args, **kwargs): with self: return func(*args, **kwargs) return magic class DatabaseLock(Enum): MYSQL = MysqlDatabaseLock POSTGRES = PostgresDatabaseLock DB = BaseDataBase().database_connection DB.lock = DatabaseLock[settings.DATABASE_TYPE.upper()].value def close_connection(): try: if DB: DB.close_stale(age=30) except Exception as e: logging.exception(e) class DataBaseModel(BaseModel): class Meta: database = DB @DB.connection_context() @DB.lock("init_database_tables", 60) def init_database_tables(alter_fields=[]): members = inspect.getmembers(sys.modules[__name__], inspect.isclass) table_objs = [] create_failed_list = [] for name, obj in members: if obj != DataBaseModel and issubclass(obj, DataBaseModel): table_objs.append(obj) if not obj.table_exists(): logging.debug(f"start create table {obj.__name__}") try: obj.create_table(safe=True) logging.debug(f"create table success: {obj.__name__}") except Exception as e: logging.exception(e) create_failed_list.append(obj.__name__) else: logging.debug(f"table {obj.__name__} already exists, skip creation.") if create_failed_list: logging.error(f"create tables failed: {create_failed_list}") raise Exception(f"create tables failed: {create_failed_list}") migrate_db() def fill_db_model_object(model_object, human_model_dict): for k, v in human_model_dict.items(): attr_name = "%s" % k if hasattr(model_object.__class__, attr_name): setattr(model_object, attr_name, v) return model_object class User(DataBaseModel, AuthUser): id = CharField(max_length=32, primary_key=True) access_token = CharField(max_length=255, null=True, index=True) nickname = CharField(max_length=100, null=False, help_text="nicky name", index=True) password = CharField(max_length=255, null=True, help_text="password", index=True) email = CharField(max_length=255, null=False, help_text="email", index=True) avatar = TextField(null=True, help_text="avatar base64 string") language = CharField(max_length=32, null=True, help_text="English|Chinese", default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English", index=True) color_schema = CharField(max_length=32, null=True, help_text="Bright|Dark", default="Bright", index=True) timezone = CharField(max_length=64, null=True, help_text="Timezone", default="UTC+8\tAsia/Shanghai", index=True) last_login_time = DateTimeField(null=True, index=True) is_authenticated = CharField(max_length=1, null=False, default="1", index=True) is_active = CharField(max_length=1, null=False, default="1", index=True) is_anonymous = CharField(max_length=1, null=False, default="0", index=True) login_channel = CharField(null=True, help_text="from which user login", index=True) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) is_superuser = BooleanField(null=True, help_text="is root", default=False, index=True) def __str__(self): return self.email def get_id(self): jwt = Serializer(secret_key=settings.SECRET_KEY) return jwt.dumps(str(self.access_token)) class Meta: db_table = "user" class Tenant(DataBaseModel): id = CharField(max_length=32, primary_key=True) name = CharField(max_length=100, null=True, help_text="Tenant name", index=True) public_key = CharField(max_length=255, null=True, index=True) llm_id = CharField(max_length=128, null=False, help_text="default llm ID", index=True) embd_id = CharField(max_length=128, null=False, help_text="default embedding model ID", index=True) asr_id = CharField(max_length=128, null=False, help_text="default ASR model ID", index=True) img2txt_id = CharField(max_length=128, null=False, help_text="default image to text model ID", index=True) rerank_id = CharField(max_length=128, null=False, help_text="default rerank model ID", index=True) tts_id = CharField(max_length=256, null=True, help_text="default tts model ID", index=True) parser_ids = CharField(max_length=256, null=False, help_text="document processors", index=True) credit = IntegerField(default=512, index=True) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) class Meta: db_table = "tenant" class UserTenant(DataBaseModel): id = CharField(max_length=32, primary_key=True) user_id = CharField(max_length=32, null=False, index=True) tenant_id = CharField(max_length=32, null=False, index=True) role = CharField(max_length=32, null=False, help_text="UserTenantRole", index=True) invited_by = CharField(max_length=32, null=False, index=True) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) class Meta: db_table = "user_tenant" class InvitationCode(DataBaseModel): id = CharField(max_length=32, primary_key=True) code = CharField(max_length=32, null=False, index=True) visit_time = DateTimeField(null=True, index=True) user_id = CharField(max_length=32, null=True, index=True) tenant_id = CharField(max_length=32, null=True, index=True) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) class Meta: db_table = "invitation_code" class LLMFactories(DataBaseModel): name = CharField(max_length=128, null=False, help_text="LLM factory name", primary_key=True) logo = TextField(null=True, help_text="llm logo base64") tags = CharField(max_length=255, null=False, help_text="LLM, Text Embedding, Image2Text, ASR", index=True) rank = IntegerField(default=0, index=False) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) def __str__(self): return self.name class Meta: db_table = "llm_factories" class LLM(DataBaseModel): # LLMs dictionary llm_name = CharField(max_length=128, null=False, help_text="LLM name", index=True) model_type = CharField(max_length=128, null=False, help_text="LLM, Text Embedding, Image2Text, ASR", index=True) fid = CharField(max_length=128, null=False, help_text="LLM factory id", index=True) max_tokens = IntegerField(default=0) tags = CharField(max_length=255, null=False, help_text="LLM, Text Embedding, Image2Text, Chat, 32k...", index=True) is_tools = BooleanField(null=False, help_text="support tools", default=False) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) def __str__(self): return self.llm_name class Meta: primary_key = CompositeKey("fid", "llm_name") db_table = "llm" class TenantLLM(DataBaseModel): tenant_id = CharField(max_length=32, null=False, index=True) llm_factory = CharField(max_length=128, null=False, help_text="LLM factory name", index=True) model_type = CharField(max_length=128, null=True, help_text="LLM, Text Embedding, Image2Text, ASR", index=True) llm_name = CharField(max_length=128, null=True, help_text="LLM name", default="", index=True) api_key = TextField(null=True, help_text="API KEY") api_base = CharField(max_length=255, null=True, help_text="API Base") max_tokens = IntegerField(default=8192, index=True) used_tokens = IntegerField(default=0, index=True) status = CharField(max_length=1, null=False, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) def __str__(self): return self.llm_name class Meta: db_table = "tenant_llm" primary_key = CompositeKey("tenant_id", "llm_factory", "llm_name") class TenantLangfuse(DataBaseModel): tenant_id = CharField(max_length=32, null=False, primary_key=True) secret_key = CharField(max_length=2048, null=False, help_text="SECRET KEY", index=True) public_key = CharField(max_length=2048, null=False, help_text="PUBLIC KEY", index=True) host = CharField(max_length=128, null=False, help_text="HOST", index=True) def __str__(self): return "Langfuse host" + self.host class Meta: db_table = "tenant_langfuse" class Knowledgebase(DataBaseModel): id = CharField(max_length=32, primary_key=True) avatar = TextField(null=True, help_text="avatar base64 string") tenant_id = CharField(max_length=32, null=False, index=True) name = CharField(max_length=128, null=False, help_text="KB name", index=True) language = CharField(max_length=32, null=True, default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English", help_text="English|Chinese", index=True) description = TextField(null=True, help_text="KB description") embd_id = CharField(max_length=128, null=False, help_text="default embedding model ID", index=True) permission = CharField(max_length=16, null=False, help_text="me|team", default="me", index=True) created_by = CharField(max_length=32, null=False, index=True) doc_num = IntegerField(default=0, index=True) token_num = IntegerField(default=0, index=True) chunk_num = IntegerField(default=0, index=True) similarity_threshold = FloatField(default=0.2, index=True) vector_similarity_weight = FloatField(default=0.3, index=True) parser_id = CharField(max_length=32, null=False, help_text="default parser ID", default=ParserType.NAIVE.value, index=True) pipeline_id = CharField(max_length=32, null=True, help_text="Pipeline ID", index=True) parser_config = JSONField(null=False, default={"pages": [[1, 1000000]], "table_context_size": 0, "image_context_size": 0}) pagerank = IntegerField(default=0, index=False) graphrag_task_id = CharField(max_length=32, null=True, help_text="Graph RAG task ID", index=True) graphrag_task_finish_at = DateTimeField(null=True) raptor_task_id = CharField(max_length=32, null=True, help_text="RAPTOR task ID", index=True) raptor_task_finish_at = DateTimeField(null=True) mindmap_task_id = CharField(max_length=32, null=True, help_text="Mindmap task ID", index=True) mindmap_task_finish_at = DateTimeField(null=True) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) def __str__(self): return self.name class Meta: db_table = "knowledgebase" class Document(DataBaseModel): id = CharField(max_length=32, primary_key=True) thumbnail = TextField(null=True, help_text="thumbnail base64 string") kb_id = CharField(max_length=256, null=False, index=True) parser_id = CharField(max_length=32, null=False, help_text="default parser ID", index=True) pipeline_id = CharField(max_length=32, null=True, help_text="pipeline ID", index=True) parser_config = JSONField(null=False, default={"pages": [[1, 1000000]], "table_context_size": 0, "image_context_size": 0}) source_type = CharField(max_length=128, null=False, default="local", help_text="where dose this document come from", index=True) type = CharField(max_length=32, null=False, help_text="file extension", index=True) created_by = CharField(max_length=32, null=False, help_text="who created it", index=True) name = CharField(max_length=255, null=True, help_text="file name", index=True) location = CharField(max_length=255, null=True, help_text="where dose it store", index=True) size = IntegerField(default=0, index=True) token_num = IntegerField(default=0, index=True) chunk_num = IntegerField(default=0, index=True) progress = FloatField(default=0, index=True) progress_msg = TextField(null=True, help_text="process message", default="") process_begin_at = DateTimeField(null=True, index=True) process_duration = FloatField(default=0) meta_fields = JSONField(null=True, default={}) suffix = CharField(max_length=32, null=False, help_text="The real file extension suffix", index=True) run = CharField(max_length=1, null=True, help_text="start to run processing or cancel.(1: run it; 2: cancel)", default="0", index=True) status = CharField(max_length=1, null=True, help_text="is it validate(0: wasted, 1: validate)", default="1", index=True) class Meta: db_table = "document" class File(DataBaseModel): id = CharField(max_length=32, primary_key=True)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/__init__.py
api/db/__init__.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 enum import IntEnum from strenum import StrEnum class UserTenantRole(StrEnum): OWNER = 'owner' ADMIN = 'admin' NORMAL = 'normal' INVITE = 'invite' class TenantPermission(StrEnum): ME = 'me' TEAM = 'team' class SerializedType(IntEnum): PICKLE = 1 JSON = 2 class FileType(StrEnum): PDF = 'pdf' DOC = 'doc' VISUAL = 'visual' AURAL = 'aural' VIRTUAL = 'virtual' FOLDER = 'folder' OTHER = "other" VALID_FILE_TYPES = {FileType.PDF, FileType.DOC, FileType.VISUAL, FileType.AURAL, FileType.VIRTUAL, FileType.FOLDER, FileType.OTHER} class InputType(StrEnum): LOAD_STATE = "load_state" # e.g. loading a current full state or a save state, such as from a file POLL = "poll" # e.g. calling an API to get all documents in the last hour EVENT = "event" # e.g. registered an endpoint as a listener, and processing connector events SLIM_RETRIEVAL = "slim_retrieval" class CanvasCategory(StrEnum): Agent = "agent_canvas" DataFlow = "dataflow_canvas" class PipelineTaskType(StrEnum): PARSE = "Parse" DOWNLOAD = "Download" RAPTOR = "RAPTOR" GRAPH_RAG = "GraphRAG" MINDMAP = "Mindmap" VALID_PIPELINE_TASK_TYPES = {PipelineTaskType.PARSE, PipelineTaskType.DOWNLOAD, PipelineTaskType.RAPTOR, PipelineTaskType.GRAPH_RAG, PipelineTaskType.MINDMAP} PIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPES = {PipelineTaskType.RAPTOR.lower(), PipelineTaskType.GRAPH_RAG.lower(), PipelineTaskType.MINDMAP.lower()} KNOWLEDGEBASE_FOLDER_NAME=".knowledgebase"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/db_utils.py
api/db/db_utils.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 operator from functools import reduce from playhouse.pool import PooledMySQLDatabase from common.time_utils import current_timestamp, timestamp_to_date from api.db.db_models import DB, DataBaseModel @DB.connection_context() def bulk_insert_into_db(model, data_source, replace_on_conflict=False): DB.create_tables([model]) for i, data in enumerate(data_source): current_time = current_timestamp() + i current_date = timestamp_to_date(current_time) if 'create_time' not in data: data['create_time'] = current_time data['create_date'] = timestamp_to_date(data['create_time']) data['update_time'] = current_time data['update_date'] = current_date preserve = tuple(data_source[0].keys() - {'create_time', 'create_date'}) batch_size = 1000 for i in range(0, len(data_source), batch_size): with DB.atomic(): query = model.insert_many(data_source[i:i + batch_size]) if replace_on_conflict: if isinstance(DB, PooledMySQLDatabase): query = query.on_conflict(preserve=preserve) else: query = query.on_conflict(conflict_target="id", preserve=preserve) query.execute() def get_dynamic_db_model(base, job_id): return type(base.model( table_index=get_dynamic_tracking_table_index(job_id=job_id))) def get_dynamic_tracking_table_index(job_id): return job_id[:8] def fill_db_model_object(model_object, human_model_dict): for k, v in human_model_dict.items(): attr_name = 'f_%s' % k if hasattr(model_object.__class__, attr_name): setattr(model_object, attr_name, v) return model_object # https://docs.peewee-orm.com/en/latest/peewee/query_operators.html supported_operators = { '==': operator.eq, '<': operator.lt, '<=': operator.le, '>': operator.gt, '>=': operator.ge, '!=': operator.ne, '<<': operator.lshift, '>>': operator.rshift, '%': operator.mod, '**': operator.pow, '^': operator.xor, '~': operator.inv, } def query_dict2expression( model: type[DataBaseModel], query: dict[str, bool | int | str | list | tuple]): expression = [] for field, value in query.items(): if not isinstance(value, (list, tuple)): value = ('==', value) op, *val = value field = getattr(model, f'f_{field}') value = supported_operators[op]( field, val[0]) if op in supported_operators else getattr( field, op)( *val) expression.append(value) return reduce(operator.iand, expression) def query_db(model: type[DataBaseModel], limit: int = 0, offset: int = 0, query: dict = None, order_by: str | list | tuple | None = None): data = model.select() if query: data = data.where(query_dict2expression(model, query)) count = data.count() if not order_by: order_by = 'create_time' if not isinstance(order_by, (list, tuple)): order_by = (order_by, 'asc') order_by, order = order_by order_by = getattr(model, f'f_{order_by}') order_by = getattr(order_by, order)() data = data.order_by(order_by) if limit > 0: data = data.limit(limit) if offset > 0: data = data.offset(offset) return list(data), count
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/init_data.py
api/db/init_data.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 json import os import time import uuid from copy import deepcopy from api.db import UserTenantRole from api.db.db_models import init_database_tables as init_web_db, LLMFactories, LLM, TenantLLM from api.db.services import UserService from api.db.services.canvas_service import CanvasTemplateService from api.db.services.document_service import DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.tenant_llm_service import LLMFactoriesService, TenantLLMService from api.db.services.llm_service import LLMService, LLMBundle, get_init_tenant_llm from api.db.services.user_service import TenantService, UserTenantService from api.db.services.system_settings_service import SystemSettingsService from api.db.joint_services.memory_message_service import init_message_id_sequence, init_memory_size_cache from common.constants import LLMType from common.file_utils import get_project_base_directory from common import settings from api.common.base64 import encode_to_base64 DEFAULT_SUPERUSER_NICKNAME = os.getenv("DEFAULT_SUPERUSER_NICKNAME", "admin") DEFAULT_SUPERUSER_EMAIL = os.getenv("DEFAULT_SUPERUSER_EMAIL", "admin@ragflow.io") DEFAULT_SUPERUSER_PASSWORD = os.getenv("DEFAULT_SUPERUSER_PASSWORD", "admin") def init_superuser(nickname=DEFAULT_SUPERUSER_NICKNAME, email=DEFAULT_SUPERUSER_EMAIL, password=DEFAULT_SUPERUSER_PASSWORD, role=UserTenantRole.OWNER): user_info = { "id": uuid.uuid1().hex, "password": encode_to_base64(password), "nickname": nickname, "is_superuser": True, "email": email, "creator": "system", "status": "1", } tenant = { "id": user_info["id"], "name": user_info["nickname"] + "‘s Kingdom", "llm_id": settings.CHAT_MDL, "embd_id": settings.EMBEDDING_MDL, "asr_id": settings.ASR_MDL, "parser_ids": settings.PARSERS, "img2txt_id": settings.IMAGE2TEXT_MDL } usr_tenant = { "tenant_id": user_info["id"], "user_id": user_info["id"], "invited_by": user_info["id"], "role": role } tenant_llm = get_init_tenant_llm(user_info["id"]) if not UserService.save(**user_info): logging.error("can't init admin.") return TenantService.insert(**tenant) UserTenantService.insert(**usr_tenant) TenantLLMService.insert_many(tenant_llm) logging.info( f"Super user initialized. email: {email},A default password has been set; changing the password after login is strongly recommended.") chat_mdl = LLMBundle(tenant["id"], LLMType.CHAT, tenant["llm_id"]) msg = asyncio.run(chat_mdl.async_chat(system="", history=[{"role": "user", "content": "Hello!"}], gen_conf={})) if msg.find("ERROR: ") == 0: logging.error( "'{}' doesn't work. {}".format( tenant["llm_id"], msg)) embd_mdl = LLMBundle(tenant["id"], LLMType.EMBEDDING, tenant["embd_id"]) v, c = embd_mdl.encode(["Hello!"]) if c == 0: logging.error( "'{}' doesn't work!".format( tenant["embd_id"])) def init_llm_factory(): LLMFactoriesService.filter_delete([1 == 1]) factory_llm_infos = settings.FACTORY_LLM_INFOS for factory_llm_info in factory_llm_infos: info = deepcopy(factory_llm_info) llm_infos = info.pop("llm") try: LLMFactoriesService.save(**info) except Exception: pass LLMService.filter_delete([LLM.fid == factory_llm_info["name"]]) for llm_info in llm_infos: llm_info["fid"] = factory_llm_info["name"] try: LLMService.save(**llm_info) except Exception: pass LLMFactoriesService.filter_delete([(LLMFactories.name == "Local") | (LLMFactories.name == "novita.ai")]) LLMService.filter_delete([LLM.fid == "Local"]) LLMService.filter_delete([LLM.llm_name == "qwen-vl-max"]) LLMService.filter_delete([LLM.fid == "Moonshot", LLM.llm_name == "flag-embedding"]) TenantLLMService.filter_delete([TenantLLM.llm_factory == "Moonshot", TenantLLM.llm_name == "flag-embedding"]) LLMFactoriesService.filter_delete([LLMFactoriesService.model.name == "QAnything"]) LLMService.filter_delete([LLMService.model.fid == "QAnything"]) TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "QAnything"], {"llm_factory": "Youdao"}) TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "cohere"], {"llm_factory": "Cohere"}) TenantService.filter_update([1 == 1], { "parser_ids": "naive:General,qa:Q&A,resume:Resume,manual:Manual,table:Table,paper:Paper,book:Book,laws:Laws,presentation:Presentation,picture:Picture,one:One,audio:Audio,email:Email,tag:Tag"}) ## insert openai two embedding models to the current openai user. # print("Start to insert 2 OpenAI embedding models...") tenant_ids = set([row["tenant_id"] for row in TenantLLMService.get_openai_models()]) for tid in tenant_ids: for row in TenantLLMService.query(llm_factory="OpenAI", tenant_id=tid): row = row.to_dict() row["model_type"] = LLMType.EMBEDDING.value row["llm_name"] = "text-embedding-3-small" row["used_tokens"] = 0 try: TenantLLMService.save(**row) row = deepcopy(row) row["llm_name"] = "text-embedding-3-large" TenantLLMService.save(**row) except Exception: pass break doc_count = DocumentService.get_all_kb_doc_count() for kb_id in KnowledgebaseService.get_all_ids(): KnowledgebaseService.update_document_number_in_init(kb_id=kb_id, doc_num=doc_count.get(kb_id, 0)) def add_graph_templates(): dir = os.path.join(get_project_base_directory(), "agent", "templates") CanvasTemplateService.filter_delete([1 == 1]) if not os.path.exists(dir): logging.warning("Missing agent templates!") return for fnm in os.listdir(dir): try: cnvs = json.load(open(os.path.join(dir, fnm), "r",encoding="utf-8")) try: CanvasTemplateService.save(**cnvs) except Exception: CanvasTemplateService.update_by_id(cnvs["id"], cnvs) except Exception as e: logging.exception(f"Add agent templates error: {e}") def init_web_data(): start_time = time.time() init_table() init_llm_factory() # if not UserService.get_all().count(): # init_superuser() add_graph_templates() init_message_id_sequence() init_memory_size_cache() logging.info("init web data success:{}".format(time.time() - start_time)) def init_table(): # init system_settings with open(os.path.join(get_project_base_directory(), "conf", "system_settings.json"), "r") as f: records_from_file = json.load(f)["system_settings"] record_index = {} records_from_db = SystemSettingsService.get_all() for index, record in enumerate(records_from_db): record_index[record.name] = index to_save = [] for record in records_from_file: setting_name = record["name"] if setting_name not in record_index: to_save.append(record) len_to_save = len(to_save) if len_to_save > 0: # not initialized try: SystemSettingsService.insert_many(to_save, len_to_save) except Exception as e: logging.exception("System settings init error: {}".format(e)) raise e if __name__ == '__main__': init_web_db() init_web_data()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/reload_config_base.py
api/db/reload_config_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. # class ReloadConfigBase: @classmethod def get_all(cls): configs = {} for k, v in cls.__dict__.items(): if not callable(getattr(cls, k)) and not k.startswith( "__") and not k.startswith("_"): configs[k] = v return configs @classmethod def get(cls, config_name): return getattr(cls, config_name) if hasattr(cls, config_name) else None
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/runtime_config.py
api/db/runtime_config.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.versions import get_ragflow_version from .reload_config_base import ReloadConfigBase class RuntimeConfig(ReloadConfigBase): DEBUG = None WORK_MODE = None HTTP_PORT = None JOB_SERVER_HOST = None JOB_SERVER_VIP = None ENV = dict() SERVICE_DB = None LOAD_CONFIG_MANAGER = False @classmethod def init_config(cls, **kwargs): for k, v in kwargs.items(): if hasattr(cls, k): setattr(cls, k, v) @classmethod def init_env(cls): cls.ENV.update({"version": get_ragflow_version()}) @classmethod def load_config_manager(cls): cls.LOAD_CONFIG_MANAGER = True @classmethod def get_env(cls, key): return cls.ENV.get(key, None) @classmethod def get_all_env(cls): return cls.ENV @classmethod def set_service_db(cls, service_db): cls.SERVICE_DB = service_db
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/knowledgebase_service.py
api/db/services/knowledgebase_service.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 datetime import datetime from peewee import fn, JOIN from api.db import TenantPermission from api.db.db_models import DB, Document, Knowledgebase, User, UserTenant, UserCanvas from api.db.services.common_service import CommonService from common.time_utils import current_timestamp, datetime_format from api.db.services import duplicate_name from api.db.services.user_service import TenantService from common.misc_utils import get_uuid from common.constants import StatusEnum from api.constants import DATASET_NAME_LIMIT from api.utils.api_utils import get_parser_config, get_data_error_result class KnowledgebaseService(CommonService): """Service class for managing dataset operations. This class extends CommonService to provide specialized functionality for dataset management, including document parsing status tracking, access control, and configuration management. It handles operations such as listing, creating, updating, and deleting knowledge bases, as well as managing their associated documents and permissions. The class implements a comprehensive set of methods for: - Document parsing status verification - Knowledge base access control - Parser configuration management - Tenant-based dataset organization Attributes: model: The Knowledgebase model class for database operations. """ model = Knowledgebase @classmethod @DB.connection_context() def accessible4deletion(cls, kb_id, user_id): """Check if a dataset can be deleted by a specific user. This method verifies whether a user has permission to delete a dataset by checking if they are the creator of that dataset. Args: kb_id (str): The unique identifier of the dataset to check. user_id (str): The unique identifier of the user attempting the deletion. Returns: bool: True if the user has permission to delete the dataset, False if the user doesn't have permission or the dataset doesn't exist. Example: >>> KnowledgebaseService.accessible4deletion("kb123", "user456") True Note: - This method only checks creator permissions - A return value of False can mean either: 1. The dataset doesn't exist 2. The user is not the creator of the dataset """ # Check if a dataset can be deleted by a user docs = cls.model.select( cls.model.id).where(cls.model.id == kb_id, cls.model.created_by == user_id).paginate(0, 1) docs = docs.dicts() if not docs: return False return True @classmethod @DB.connection_context() def is_parsed_done(cls, kb_id): # Check if all documents in the dataset have completed parsing # # Args: # kb_id: Knowledge base ID # # Returns: # If all documents are parsed successfully, returns (True, None) # If any document is not fully parsed, returns (False, error_message) from common.constants import TaskStatus from api.db.services.document_service import DocumentService # Get dataset information kbs = cls.query(id=kb_id) if not kbs: return False, "Knowledge base not found" kb = kbs[0] # Get all documents in the dataset docs, _ = DocumentService.get_by_kb_id(kb_id, 1, 1000, "create_time", True, "", [], []) # Check parsing status of each document for doc in docs: # If document is being parsed, don't allow chat creation if doc['run'] == TaskStatus.RUNNING.value or doc['run'] == TaskStatus.CANCEL.value or doc['run'] == TaskStatus.FAIL.value: return False, f"Document '{doc['name']}' in dataset '{kb.name}' is still being parsed. Please wait until all documents are parsed before starting a chat." # If document is not yet parsed and has no chunks, don't allow chat creation if doc['run'] == TaskStatus.UNSTART.value and doc['chunk_num'] == 0: return False, f"Document '{doc['name']}' in dataset '{kb.name}' has not been parsed yet. Please parse all documents before starting a chat." return True, None @classmethod @DB.connection_context() def list_documents_by_ids(cls, kb_ids): # Get document IDs associated with given dataset IDs # Args: # kb_ids: List of dataset IDs # Returns: # List of document IDs doc_ids = cls.model.select(Document.id.alias("document_id")).join(Document, on=(cls.model.id == Document.kb_id)).where( cls.model.id.in_(kb_ids) ) doc_ids = list(doc_ids.dicts()) doc_ids = [doc["document_id"] for doc in doc_ids] return doc_ids @classmethod @DB.connection_context() def get_by_tenant_ids(cls, joined_tenant_ids, user_id, page_number, items_per_page, orderby, desc, keywords, parser_id=None ): # Get knowledge bases by tenant IDs with pagination and filtering # Args: # joined_tenant_ids: List of tenant IDs # user_id: Current user ID # page_number: Page number for pagination # items_per_page: Number of items per page # orderby: Field to order by # desc: Boolean indicating descending order # keywords: Search keywords # parser_id: Optional parser ID filter # Returns: # Tuple of (knowledge_base_list, total_count) fields = [ cls.model.id, cls.model.avatar, cls.model.name, cls.model.language, cls.model.description, cls.model.tenant_id, cls.model.permission, cls.model.doc_num, cls.model.token_num, cls.model.chunk_num, cls.model.parser_id, cls.model.embd_id, User.nickname, User.avatar.alias('tenant_avatar'), cls.model.update_time ] if keywords: kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where( ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission == TenantPermission.TEAM.value)) | ( cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value), (fn.LOWER(cls.model.name).contains(keywords.lower())) ) else: kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where( ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission == TenantPermission.TEAM.value)) | ( cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value) ) if parser_id: kbs = kbs.where(cls.model.parser_id == parser_id) if desc: kbs = kbs.order_by(cls.model.getter_by(orderby).desc()) else: kbs = kbs.order_by(cls.model.getter_by(orderby).asc()) count = kbs.count() if page_number and items_per_page: kbs = kbs.paginate(page_number, items_per_page) return list(kbs.dicts()), count @classmethod @DB.connection_context() def get_all_kb_by_tenant_ids(cls, tenant_ids, user_id): # will get all permitted kb, be cautious. fields = [ cls.model.name, cls.model.avatar, cls.model.language, cls.model.permission, cls.model.doc_num, cls.model.token_num, cls.model.chunk_num, cls.model.status, cls.model.create_date, cls.model.update_date ] # find team kb and owned kb kbs = cls.model.select(*fields).where( (cls.model.tenant_id.in_(tenant_ids) & (cls.model.permission ==TenantPermission.TEAM.value)) | ( cls.model.tenant_id == user_id ) ) # sort by create_time asc kbs.order_by(cls.model.create_time.asc()) # maybe cause slow query by deep paginate, optimize later. offset, limit = 0, 50 res = [] while True: kb_batch = kbs.offset(offset).limit(limit) _temp = list(kb_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res @classmethod @DB.connection_context() def get_kb_ids(cls, tenant_id): # Get all dataset IDs for a tenant # Args: # tenant_id: Tenant ID # Returns: # List of dataset IDs fields = [ cls.model.id, ] kbs = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id) kb_ids = [kb.id for kb in kbs] return kb_ids @classmethod @DB.connection_context() def get_detail(cls, kb_id): # Get detailed information about a dataset # Args: # kb_id: Knowledge base ID # Returns: # Dictionary containing dataset details fields = [ cls.model.id, cls.model.embd_id, cls.model.avatar, cls.model.name, cls.model.language, cls.model.description, cls.model.permission, cls.model.doc_num, cls.model.token_num, cls.model.chunk_num, cls.model.parser_id, cls.model.pipeline_id, UserCanvas.title.alias("pipeline_name"), UserCanvas.avatar.alias("pipeline_avatar"), cls.model.parser_config, cls.model.pagerank, cls.model.graphrag_task_id, cls.model.graphrag_task_finish_at, cls.model.raptor_task_id, cls.model.raptor_task_finish_at, cls.model.mindmap_task_id, cls.model.mindmap_task_finish_at, cls.model.create_time, cls.model.update_time ] kbs = cls.model.select(*fields)\ .join(UserCanvas, on=(cls.model.pipeline_id == UserCanvas.id), join_type=JOIN.LEFT_OUTER)\ .where( (cls.model.id == kb_id), (cls.model.status == StatusEnum.VALID.value) ).dicts() if not kbs: return None return kbs[0] @classmethod @DB.connection_context() def update_parser_config(cls, id, config): # Update parser configuration for a dataset # Args: # id: Knowledge base ID # config: New parser configuration e, m = cls.get_by_id(id) if not e: raise LookupError(f"dataset({id}) not found.") def dfs_update(old, new): # Deep update of nested configuration for k, v in new.items(): if k not in old: old[k] = v continue if isinstance(v, dict): assert isinstance(old[k], dict) dfs_update(old[k], v) elif isinstance(v, list): assert isinstance(old[k], list) old[k] = list(set(old[k] + v)) else: old[k] = v dfs_update(m.parser_config, config) cls.update_by_id(id, {"parser_config": m.parser_config}) @classmethod @DB.connection_context() def delete_field_map(cls, id): e, m = cls.get_by_id(id) if not e: raise LookupError(f"dataset({id}) not found.") m.parser_config.pop("field_map", None) cls.update_by_id(id, {"parser_config": m.parser_config}) @classmethod @DB.connection_context() def get_field_map(cls, ids): # Get field mappings for knowledge bases # Args: # ids: List of dataset IDs # Returns: # Dictionary of field mappings conf = {} for k in cls.get_by_ids(ids): if k.parser_config and "field_map" in k.parser_config: conf.update(k.parser_config["field_map"]) return conf @classmethod @DB.connection_context() def get_by_name(cls, kb_name, tenant_id): # Get dataset by name and tenant ID # Args: # kb_name: Knowledge base name # tenant_id: Tenant ID # Returns: # Tuple of (exists, knowledge_base) kb = cls.model.select().where( (cls.model.name == kb_name) & (cls.model.tenant_id == tenant_id) & (cls.model.status == StatusEnum.VALID.value) ) if kb: return True, kb[0] return False, None @classmethod @DB.connection_context() def get_all_ids(cls): # Get all dataset IDs # Returns: # List of all dataset IDs return [m["id"] for m in cls.model.select(cls.model.id).dicts()] @classmethod @DB.connection_context() def create_with_name( cls, *, name: str, tenant_id: str, parser_id: str | None = None, **kwargs ): """Create a dataset (knowledgebase) by name with kb_app defaults. This encapsulates the creation logic used in kb_app.create so other callers (including RESTFul endpoints) can reuse the same behavior. Returns: (ok: bool, model_or_msg): On success, returns (True, Knowledgebase model instance); on failure, returns (False, error_message). """ # Validate name if not isinstance(name, str): return False, get_data_error_result(message="Dataset name must be string.") dataset_name = name.strip() if dataset_name == "": return False, get_data_error_result(message="Dataset name can't be empty.") if len(dataset_name.encode("utf-8")) > DATASET_NAME_LIMIT: return False, get_data_error_result(message=f"Dataset name length is {len(dataset_name)} which is larger than {DATASET_NAME_LIMIT}") # Deduplicate name within tenant dataset_name = duplicate_name( cls.query, name=dataset_name, tenant_id=tenant_id, status=StatusEnum.VALID.value, ) # Verify tenant exists ok, _t = TenantService.get_by_id(tenant_id) if not ok: return False, get_data_error_result(message="Tenant not found.") # Build payload kb_id = get_uuid() payload = { "id": kb_id, "name": dataset_name, "tenant_id": tenant_id, "created_by": tenant_id, "parser_id": (parser_id or "naive"), **kwargs # Includes optional fields such as description, language, permission, avatar, parser_config, etc. } # Update parser_config (always override with validated default/merged config) payload["parser_config"] = get_parser_config(parser_id, kwargs.get("parser_config")) payload["parser_config"]["llm_id"] = _t.llm_id return True, payload @classmethod @DB.connection_context() def get_list(cls, joined_tenant_ids, user_id, page_number, items_per_page, orderby, desc, id, name): # Get list of knowledge bases with filtering and pagination # Args: # joined_tenant_ids: List of tenant IDs # user_id: Current user ID # page_number: Page number for pagination # items_per_page: Number of items per page # orderby: Field to order by # desc: Boolean indicating descending order # id: Optional ID filter # name: Optional name filter # Returns: # List of knowledge bases # Total count of knowledge bases kbs = cls.model.select() if id: kbs = kbs.where(cls.model.id == id) if name: kbs = kbs.where(cls.model.name == name) kbs = kbs.where( ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission == TenantPermission.TEAM.value)) | ( cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value) ) if desc: kbs = kbs.order_by(cls.model.getter_by(orderby).desc()) else: kbs = kbs.order_by(cls.model.getter_by(orderby).asc()) total = kbs.count() kbs = kbs.paginate(page_number, items_per_page) return list(kbs.dicts()), total @classmethod @DB.connection_context() def accessible(cls, kb_id, user_id): # Check if a dataset is accessible by a user # Args: # kb_id: Knowledge base ID # user_id: User ID # Returns: # Boolean indicating accessibility docs = cls.model.select( cls.model.id).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id) ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1) docs = docs.dicts() if not docs: return False return True @classmethod @DB.connection_context() def get_kb_by_id(cls, kb_id, user_id): # Get dataset by ID and user ID # Args: # kb_id: Knowledge base ID # user_id: User ID # Returns: # List containing dataset information kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id) ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1) kbs = kbs.dicts() return list(kbs) @classmethod @DB.connection_context() def get_kb_by_name(cls, kb_name, user_id): # Get dataset by name and user ID # Args: # kb_name: Knowledge base name # user_id: User ID # Returns: # List containing dataset information kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id) ).where(cls.model.name == kb_name, UserTenant.user_id == user_id).paginate(0, 1) kbs = kbs.dicts() return list(kbs) @classmethod @DB.connection_context() def atomic_increase_doc_num_by_id(cls, kb_id): data = {} data["update_time"] = current_timestamp() data["update_date"] = datetime_format(datetime.now()) data["doc_num"] = cls.model.doc_num + 1 num = cls.model.update(data).where(cls.model.id == kb_id).execute() return num @classmethod @DB.connection_context() def update_document_number_in_init(cls, kb_id, doc_num): """ Only use this function when init system """ ok, kb = cls.get_by_id(kb_id) if not ok: return kb.doc_num = doc_num dirty_fields = kb.dirty_fields if cls.model._meta.combined.get("update_time") in dirty_fields: dirty_fields.remove(cls.model._meta.combined["update_time"]) if cls.model._meta.combined.get("update_date") in dirty_fields: dirty_fields.remove(cls.model._meta.combined["update_date"]) try: kb.save(only=dirty_fields) except ValueError as e: if str(e) == "no data to save!": pass # that's OK else: raise e @classmethod @DB.connection_context() def decrease_document_num_in_delete(cls, kb_id, doc_num_info: dict): kb_row = cls.model.get_by_id(kb_id) if not kb_row: raise RuntimeError(f"kb_id {kb_id} does not exist") update_dict = { 'doc_num': kb_row.doc_num - doc_num_info['doc_num'], 'chunk_num': kb_row.chunk_num - doc_num_info['chunk_num'], 'token_num': kb_row.token_num - doc_num_info['token_num'], 'update_time': current_timestamp(), 'update_date': datetime_format(datetime.now()) } return cls.model.update(update_dict).where(cls.model.id == kb_id).execute()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/search_service.py
api/db/services/search_service.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 datetime import datetime from peewee import fn from common.constants import StatusEnum from api.db.db_models import DB, Search, User from api.db.services.common_service import CommonService from common.time_utils import current_timestamp, datetime_format class SearchService(CommonService): model = Search @classmethod def save(cls, **kwargs): current_ts = current_timestamp() current_date = datetime_format(datetime.now()) kwargs["create_time"] = current_ts kwargs["create_date"] = current_date kwargs["update_time"] = current_ts kwargs["update_date"] = current_date obj = cls.model.create(**kwargs) return obj @classmethod @DB.connection_context() def accessible4deletion(cls, search_id, user_id) -> bool: search = ( cls.model.select(cls.model.id) .where( cls.model.id == search_id, cls.model.created_by == user_id, cls.model.status == StatusEnum.VALID.value, ) .first() ) return search is not None @classmethod @DB.connection_context() def get_detail(cls, search_id): fields = [ cls.model.id, cls.model.avatar, cls.model.tenant_id, cls.model.name, cls.model.description, cls.model.created_by, cls.model.search_config, cls.model.update_time, User.nickname, User.avatar.alias("tenant_avatar"), ] search = ( cls.model.select(*fields) .join(User, on=((User.id == cls.model.tenant_id) & (User.status == StatusEnum.VALID.value))) .where((cls.model.id == search_id) & (cls.model.status == StatusEnum.VALID.value)) .first() .to_dict() ) if not search: return {} return search @classmethod @DB.connection_context() def get_by_tenant_ids(cls, joined_tenant_ids, user_id, page_number, items_per_page, orderby, desc, keywords): fields = [ cls.model.id, cls.model.avatar, cls.model.tenant_id, cls.model.name, cls.model.description, cls.model.created_by, cls.model.status, cls.model.update_time, cls.model.create_time, User.nickname, User.avatar.alias("tenant_avatar"), ] query = ( cls.model.select(*fields) .join(User, on=(cls.model.tenant_id == User.id)) .where(((cls.model.tenant_id.in_(joined_tenant_ids)) | (cls.model.tenant_id == user_id)) & ( cls.model.status == StatusEnum.VALID.value)) ) if keywords: query = query.where(fn.LOWER(cls.model.name).contains(keywords.lower())) if desc: query = query.order_by(cls.model.getter_by(orderby).desc()) else: query = query.order_by(cls.model.getter_by(orderby).asc()) count = query.count() if page_number and items_per_page: query = query.paginate(page_number, items_per_page) return list(query.dicts()), count @classmethod @DB.connection_context() def delete_by_tenant_id(cls, tenant_id): return cls.model.delete().where(cls.model.tenant_id == tenant_id).execute()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/user_canvas_version.py
api/db/services/user_canvas_version.py
from api.db.db_models import UserCanvasVersion, DB from api.db.services.common_service import CommonService from peewee import DoesNotExist class UserCanvasVersionService(CommonService): model = UserCanvasVersion @classmethod @DB.connection_context() def list_by_canvas_id(cls, user_canvas_id): try: user_canvas_version = cls.model.select( *[cls.model.id, cls.model.create_time, cls.model.title, cls.model.create_date, cls.model.update_date, cls.model.user_canvas_id, cls.model.update_time] ).where(cls.model.user_canvas_id == user_canvas_id) return user_canvas_version except DoesNotExist: return None except Exception: return None @classmethod @DB.connection_context() def get_all_canvas_version_by_canvas_ids(cls, canvas_ids): fields = [cls.model.id] versions = cls.model.select(*fields).where(cls.model.user_canvas_id.in_(canvas_ids)) versions.order_by(cls.model.create_time.asc()) offset, limit = 0, 100 res = [] while True: version_batch = versions.offset(offset).limit(limit) _temp = list(version_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res @classmethod @DB.connection_context() def delete_all_versions(cls, user_canvas_id): try: user_canvas_version = cls.model.select().where(cls.model.user_canvas_id == user_canvas_id).order_by( cls.model.create_time.desc()) if user_canvas_version.count() > 20: delete_ids = [] for i in range(20, user_canvas_version.count()): delete_ids.append(user_canvas_version[i].id) cls.delete_by_ids(delete_ids) return True except DoesNotExist: return None except Exception: return None
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/tenant_llm_service.py
api/db/services/tenant_llm_service.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 json import logging from peewee import IntegrityError from langfuse import Langfuse from common import settings from common.constants import MINERU_DEFAULT_CONFIG, MINERU_ENV_KEYS, LLMType from api.db.db_models import DB, LLMFactories, TenantLLM from api.db.services.common_service import CommonService from api.db.services.langfuse_service import TenantLangfuseService from api.db.services.user_service import TenantService from rag.llm import ChatModel, CvModel, EmbeddingModel, OcrModel, RerankModel, Seq2txtModel, TTSModel class LLMFactoriesService(CommonService): model = LLMFactories class TenantLLMService(CommonService): model = TenantLLM @classmethod @DB.connection_context() def get_api_key(cls, tenant_id, model_name): mdlnm, fid = TenantLLMService.split_model_name_and_factory(model_name) if not fid: objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm) else: objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid) if (not objs) and fid: if fid == "LocalAI": mdlnm += "___LocalAI" elif fid == "HuggingFace": mdlnm += "___HuggingFace" elif fid == "OpenAI-API-Compatible": mdlnm += "___OpenAI-API" elif fid == "VLLM": mdlnm += "___VLLM" objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid) if not objs: return None return objs[0] @classmethod @DB.connection_context() def get_my_llms(cls, tenant_id): fields = [cls.model.llm_factory, LLMFactories.logo, LLMFactories.tags, cls.model.model_type, cls.model.llm_name, cls.model.used_tokens, cls.model.status] objs = cls.model.select(*fields).join(LLMFactories, on=(cls.model.llm_factory == LLMFactories.name)).where( cls.model.tenant_id == tenant_id, ~cls.model.api_key.is_null()).dicts() return list(objs) @staticmethod def split_model_name_and_factory(model_name): arr = model_name.split("@") if len(arr) < 2: return model_name, None if len(arr) > 2: return "@".join(arr[0:-1]), arr[-1] # model name must be xxx@yyy try: model_factories = settings.FACTORY_LLM_INFOS model_providers = set([f["name"] for f in model_factories]) if arr[-1] not in model_providers: return model_name, None return arr[0], arr[-1] except Exception as e: logging.exception(f"TenantLLMService.split_model_name_and_factory got exception: {e}") return model_name, None @classmethod @DB.connection_context() def get_model_config(cls, tenant_id, llm_type, llm_name=None): from api.db.services.llm_service import LLMService e, tenant = TenantService.get_by_id(tenant_id) if not e: raise LookupError("Tenant not found") if llm_type == LLMType.EMBEDDING.value: mdlnm = tenant.embd_id if not llm_name else llm_name elif llm_type == LLMType.SPEECH2TEXT.value: mdlnm = tenant.asr_id if not llm_name else llm_name elif llm_type == LLMType.IMAGE2TEXT.value: mdlnm = tenant.img2txt_id if not llm_name else llm_name elif llm_type == LLMType.CHAT.value: mdlnm = tenant.llm_id if not llm_name else llm_name elif llm_type == LLMType.RERANK: mdlnm = tenant.rerank_id if not llm_name else llm_name elif llm_type == LLMType.TTS: mdlnm = tenant.tts_id if not llm_name else llm_name elif llm_type == LLMType.OCR: if not llm_name: raise LookupError("OCR model name is required") mdlnm = llm_name else: assert False, "LLM type error" model_config = cls.get_api_key(tenant_id, mdlnm) mdlnm, fid = TenantLLMService.split_model_name_and_factory(mdlnm) if not model_config: # for some cases seems fid mismatch model_config = cls.get_api_key(tenant_id, mdlnm) if model_config: model_config = model_config.to_dict() elif llm_type == LLMType.EMBEDDING and fid == 'Builtin' and "tei-" in os.getenv("COMPOSE_PROFILES", "") and mdlnm == os.getenv('TEI_MODEL', ''): embedding_cfg = settings.EMBEDDING_CFG model_config = {"llm_factory": 'Builtin', "api_key": embedding_cfg["api_key"], "llm_name": mdlnm, "api_base": embedding_cfg["base_url"]} else: raise LookupError(f"Model({mdlnm}@{fid}) not authorized") llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid) if not llm and fid: # for some cases seems fid mismatch llm = LLMService.query(llm_name=mdlnm) if llm: model_config["is_tools"] = llm[0].is_tools return model_config @classmethod @DB.connection_context() def model_instance(cls, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs): model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name) kwargs.update({"provider": model_config["llm_factory"]}) if llm_type == LLMType.EMBEDDING.value: if model_config["llm_factory"] not in EmbeddingModel: return None return EmbeddingModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"]) elif llm_type == LLMType.RERANK: if model_config["llm_factory"] not in RerankModel: return None return RerankModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"]) elif llm_type == LLMType.IMAGE2TEXT.value: if model_config["llm_factory"] not in CvModel: return None return CvModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], lang, base_url=model_config["api_base"], **kwargs) elif llm_type == LLMType.CHAT.value: if model_config["llm_factory"] not in ChatModel: return None return ChatModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"], **kwargs) elif llm_type == LLMType.SPEECH2TEXT: if model_config["llm_factory"] not in Seq2txtModel: return None return Seq2txtModel[model_config["llm_factory"]](key=model_config["api_key"], model_name=model_config["llm_name"], lang=lang, base_url=model_config["api_base"]) elif llm_type == LLMType.TTS: if model_config["llm_factory"] not in TTSModel: return None return TTSModel[model_config["llm_factory"]]( model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"], ) elif llm_type == LLMType.OCR: if model_config["llm_factory"] not in OcrModel: return None return OcrModel[model_config["llm_factory"]]( key=model_config["api_key"], model_name=model_config["llm_name"], base_url=model_config.get("api_base", ""), **kwargs, ) return None @classmethod @DB.connection_context() def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None): e, tenant = TenantService.get_by_id(tenant_id) if not e: logging.error(f"Tenant not found: {tenant_id}") return 0 llm_map = { LLMType.EMBEDDING.value: tenant.embd_id if not llm_name else llm_name, LLMType.SPEECH2TEXT.value: tenant.asr_id, LLMType.IMAGE2TEXT.value: tenant.img2txt_id, LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name, LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name, LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name, LLMType.OCR.value: llm_name, } mdlnm = llm_map.get(llm_type) if mdlnm is None: logging.error(f"LLM type error: {llm_type}") return 0 llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm) try: num = ( cls.model.update(used_tokens=cls.model.used_tokens + used_tokens) .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name, cls.model.llm_factory == llm_factory if llm_factory else True) .execute() ) except Exception: logging.exception( "TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s", tenant_id, llm_name) return 0 return num @classmethod @DB.connection_context() def get_openai_models(cls): objs = cls.model.select().where((cls.model.llm_factory == "OpenAI"), ~(cls.model.llm_name == "text-embedding-3-small"), ~(cls.model.llm_name == "text-embedding-3-large")).dicts() return list(objs) @classmethod def _collect_mineru_env_config(cls) -> dict | None: cfg = MINERU_DEFAULT_CONFIG found = False for key in MINERU_ENV_KEYS: val = os.environ.get(key) if val: found = True cfg[key] = val return cfg if found else None @classmethod @DB.connection_context() def ensure_mineru_from_env(cls, tenant_id: str) -> str | None: """ Ensure a MinerU OCR model exists for the tenant if env variables are present. Return the existing or newly created llm_name, or None if env not set. """ cfg = cls._collect_mineru_env_config() if not cfg: return None saved_mineru_models = cls.query(tenant_id=tenant_id, llm_factory="MinerU", model_type=LLMType.OCR.value) def _parse_api_key(raw: str) -> dict: try: return json.loads(raw or "{}") except Exception: return {} for item in saved_mineru_models: api_cfg = _parse_api_key(item.api_key) normalized = {k: api_cfg.get(k, MINERU_DEFAULT_CONFIG.get(k)) for k in MINERU_ENV_KEYS} if normalized == cfg: return item.llm_name used_names = {item.llm_name for item in saved_mineru_models} idx = 1 base_name = "mineru-from-env" while True: candidate = f"{base_name}-{idx}" if candidate in used_names: idx += 1 continue try: cls.save( tenant_id=tenant_id, llm_factory="MinerU", llm_name=candidate, model_type=LLMType.OCR.value, api_key=json.dumps(cfg), api_base="", max_tokens=0, ) return candidate except IntegrityError: logging.warning("MinerU env model %s already exists for tenant %s, retry with next name", candidate, tenant_id) used_names.add(candidate) idx += 1 continue @classmethod @DB.connection_context() def delete_by_tenant_id(cls, tenant_id): return cls.model.delete().where(cls.model.tenant_id == tenant_id).execute() @staticmethod def llm_id2llm_type(llm_id: str) -> str | None: from api.db.services.llm_service import LLMService llm_id, *_ = TenantLLMService.split_model_name_and_factory(llm_id) llm_factories = settings.FACTORY_LLM_INFOS for llm_factory in llm_factories: for llm in llm_factory["llm"]: if llm_id == llm["llm_name"]: return llm["model_type"].split(",")[-1] for llm in LLMService.query(llm_name=llm_id): return llm.model_type llm = TenantLLMService.get_or_none(llm_name=llm_id) if llm: return llm.model_type for llm in TenantLLMService.query(llm_name=llm_id): return llm.model_type return None class LLM4Tenant: def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs): self.tenant_id = tenant_id self.llm_type = llm_type self.llm_name = llm_name self.mdl = TenantLLMService.model_instance(tenant_id, llm_type, llm_name, lang=lang, **kwargs) assert self.mdl, "Can't find model for {}/{}/{}".format(tenant_id, llm_type, llm_name) model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name) self.max_length = model_config.get("max_tokens", 8192) self.is_tools = model_config.get("is_tools", False) self.verbose_tool_use = kwargs.get("verbose_tool_use") langfuse_keys = TenantLangfuseService.filter_by_tenant(tenant_id=tenant_id) self.langfuse = None if langfuse_keys: langfuse = Langfuse(public_key=langfuse_keys.public_key, secret_key=langfuse_keys.secret_key, host=langfuse_keys.host) if langfuse.auth_check(): self.langfuse = langfuse trace_id = self.langfuse.create_trace_id() self.trace_context = {"trace_id": trace_id}
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/dialog_service.py
api/db/services/dialog_service.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 binascii import logging import re import time from copy import deepcopy from datetime import datetime from functools import partial from timeit import default_timer as timer from langfuse import Langfuse from peewee import fn from agentic_reasoning import DeepResearcher from api.db.services.file_service import FileService from common.constants import LLMType, ParserType, StatusEnum from api.db.db_models import DB, Dialog from api.db.services.common_service import CommonService from api.db.services.document_service import DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.langfuse_service import TenantLangfuseService from api.db.services.llm_service import LLMBundle from common.metadata_utils import apply_meta_data_filter from api.db.services.tenant_llm_service import TenantLLMService from common.time_utils import current_timestamp, datetime_format from graphrag.general.mind_map_extractor import MindMapExtractor from rag.app.resume import forbidden_select_fields4resume from rag.app.tag import label_question from rag.nlp.search import index_name from rag.prompts.generator import chunks_format, citation_prompt, cross_languages, full_question, kb_prompt, keyword_extraction, message_fit_in, \ PROMPT_JINJA_ENV, ASK_SUMMARY from common.token_utils import num_tokens_from_string from rag.utils.tavily_conn import Tavily from common.string_utils import remove_redundant_spaces from common import settings class DialogService(CommonService): model = Dialog @classmethod def save(cls, **kwargs): """Save a new record to database. This method creates a new record in the database with the provided field values, forcing an insert operation rather than an update. Args: **kwargs: Record field values as keyword arguments. Returns: Model instance: The created record object. """ sample_obj = cls.model(**kwargs).save(force_insert=True) return sample_obj @classmethod def update_many_by_id(cls, data_list): """Update multiple records by their IDs. This method updates multiple records in the database, identified by their IDs. It automatically updates the update_time and update_date fields for each record. Args: data_list (list): List of dictionaries containing record data to update. Each dictionary must include an 'id' field. """ with DB.atomic(): for data in data_list: data["update_time"] = current_timestamp() data["update_date"] = datetime_format(datetime.now()) cls.model.update(data).where(cls.model.id == data["id"]).execute() @classmethod @DB.connection_context() def get_list(cls, tenant_id, page_number, items_per_page, orderby, desc, id, name): chats = cls.model.select() if id: chats = chats.where(cls.model.id == id) if name: chats = chats.where(cls.model.name == name) chats = chats.where((cls.model.tenant_id == tenant_id) & (cls.model.status == StatusEnum.VALID.value)) if desc: chats = chats.order_by(cls.model.getter_by(orderby).desc()) else: chats = chats.order_by(cls.model.getter_by(orderby).asc()) chats = chats.paginate(page_number, items_per_page) return list(chats.dicts()) @classmethod @DB.connection_context() def get_by_tenant_ids(cls, joined_tenant_ids, user_id, page_number, items_per_page, orderby, desc, keywords, parser_id=None): from api.db.db_models import User fields = [ cls.model.id, cls.model.tenant_id, cls.model.name, cls.model.description, cls.model.language, cls.model.llm_id, cls.model.llm_setting, cls.model.prompt_type, cls.model.prompt_config, cls.model.similarity_threshold, cls.model.vector_similarity_weight, cls.model.top_n, cls.model.top_k, cls.model.do_refer, cls.model.rerank_id, cls.model.kb_ids, cls.model.icon, cls.model.status, User.nickname, User.avatar.alias("tenant_avatar"), cls.model.update_time, cls.model.create_time, ] if keywords: dialogs = ( cls.model.select(*fields) .join(User, on=(cls.model.tenant_id == User.id)) .where( (cls.model.tenant_id.in_(joined_tenant_ids) | (cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value), (fn.LOWER(cls.model.name).contains(keywords.lower())), ) ) else: dialogs = ( cls.model.select(*fields) .join(User, on=(cls.model.tenant_id == User.id)) .where( (cls.model.tenant_id.in_(joined_tenant_ids) | (cls.model.tenant_id == user_id)) & (cls.model.status == StatusEnum.VALID.value), ) ) if parser_id: dialogs = dialogs.where(cls.model.parser_id == parser_id) if desc: dialogs = dialogs.order_by(cls.model.getter_by(orderby).desc()) else: dialogs = dialogs.order_by(cls.model.getter_by(orderby).asc()) count = dialogs.count() if page_number and items_per_page: dialogs = dialogs.paginate(page_number, items_per_page) return list(dialogs.dicts()), count @classmethod @DB.connection_context() def get_all_dialogs_by_tenant_id(cls, tenant_id): fields = [cls.model.id] dialogs = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id) dialogs.order_by(cls.model.create_time.asc()) offset, limit = 0, 100 res = [] while True: d_batch = dialogs.offset(offset).limit(limit) _temp = list(d_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res async def async_chat_solo(dialog, messages, stream=True): attachments = "" if "files" in messages[-1]: attachments = "\n\n".join(FileService.get_files(messages[-1]["files"])) if TenantLLMService.llm_id2llm_type(dialog.llm_id) == "image2text": chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id) else: chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id) prompt_config = dialog.prompt_config tts_mdl = None if prompt_config.get("tts"): tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS) msg = [{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])} for m in messages if m["role"] != "system"] if attachments and msg: msg[-1]["content"] += attachments if stream: last_ans = "" delta_ans = "" answer = "" async for ans in chat_mdl.async_chat_streamly(prompt_config.get("system", ""), msg, dialog.llm_setting): answer = ans delta_ans = ans[len(last_ans):] if num_tokens_from_string(delta_ans) < 16: continue last_ans = answer yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans), "prompt": "", "created_at": time.time()} delta_ans = "" if delta_ans: yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans), "prompt": "", "created_at": time.time()} else: answer = await chat_mdl.async_chat(prompt_config.get("system", ""), msg, dialog.llm_setting) user_content = msg[-1].get("content", "[content not available]") logging.debug("User: {}|Assistant: {}".format(user_content, answer)) yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, answer), "prompt": "", "created_at": time.time()} def get_models(dialog): embd_mdl, chat_mdl, rerank_mdl, tts_mdl = None, None, None, None kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids) embedding_list = list(set([kb.embd_id for kb in kbs])) if len(embedding_list) > 1: raise Exception("**ERROR**: Knowledge bases use different embedding models.") if embedding_list: embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embedding_list[0]) if not embd_mdl: raise LookupError("Embedding model(%s) not found" % embedding_list[0]) if TenantLLMService.llm_id2llm_type(dialog.llm_id) == "image2text": chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id) else: chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id) if dialog.rerank_id: rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id) if dialog.prompt_config.get("tts"): tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS) return kbs, embd_mdl, rerank_mdl, chat_mdl, tts_mdl BAD_CITATION_PATTERNS = [ re.compile(r"\(\s*ID\s*[: ]*\s*(\d+)\s*\)"), # (ID: 12) re.compile(r"\[\s*ID\s*[: ]*\s*(\d+)\s*\]"), # [ID: 12] re.compile(r"【\s*ID\s*[: ]*\s*(\d+)\s*】"), # 【ID: 12】 re.compile(r"ref\s*(\d+)", flags=re.IGNORECASE), # ref12、REF 12 ] def repair_bad_citation_formats(answer: str, kbinfos: dict, idx: set): max_index = len(kbinfos["chunks"]) def safe_add(i): if 0 <= i < max_index: idx.add(i) return True return False def find_and_replace(pattern, group_index=1, repl=lambda i: f"ID:{i}", flags=0): nonlocal answer def replacement(match): try: i = int(match.group(group_index)) if safe_add(i): return f"[{repl(i)}]" except Exception: pass return match.group(0) answer = re.sub(pattern, replacement, answer, flags=flags) for pattern in BAD_CITATION_PATTERNS: find_and_replace(pattern) return answer, idx async def async_chat(dialog, messages, stream=True, **kwargs): assert messages[-1]["role"] == "user", "The last content of this conversation is not from user." if not dialog.kb_ids and not dialog.prompt_config.get("tavily_api_key"): async for ans in async_chat_solo(dialog, messages, stream): yield ans return chat_start_ts = timer() if TenantLLMService.llm_id2llm_type(dialog.llm_id) == "image2text": llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id) else: llm_model_config = TenantLLMService.get_model_config(dialog.tenant_id, LLMType.CHAT, dialog.llm_id) max_tokens = llm_model_config.get("max_tokens", 8192) check_llm_ts = timer() langfuse_tracer = None trace_context = {} langfuse_keys = TenantLangfuseService.filter_by_tenant(tenant_id=dialog.tenant_id) if langfuse_keys: langfuse = Langfuse(public_key=langfuse_keys.public_key, secret_key=langfuse_keys.secret_key, host=langfuse_keys.host) if langfuse.auth_check(): langfuse_tracer = langfuse trace_id = langfuse_tracer.create_trace_id() trace_context = {"trace_id": trace_id} check_langfuse_tracer_ts = timer() kbs, embd_mdl, rerank_mdl, chat_mdl, tts_mdl = get_models(dialog) toolcall_session, tools = kwargs.get("toolcall_session"), kwargs.get("tools") if toolcall_session and tools: chat_mdl.bind_tools(toolcall_session, tools) bind_models_ts = timer() retriever = settings.retriever questions = [m["content"] for m in messages if m["role"] == "user"][-3:] attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else [] attachments_= "" if "doc_ids" in messages[-1]: attachments = messages[-1]["doc_ids"] if "files" in messages[-1]: attachments_ = "\n\n".join(FileService.get_files(messages[-1]["files"])) prompt_config = dialog.prompt_config field_map = KnowledgebaseService.get_field_map(dialog.kb_ids) # try to use sql if field mapping is good to go if field_map: logging.debug("Use SQL to retrieval:{}".format(questions[-1])) ans = await use_sql(questions[-1], field_map, dialog.tenant_id, chat_mdl, prompt_config.get("quote", True), dialog.kb_ids) if ans: yield ans return for p in prompt_config["parameters"]: if p["key"] == "knowledge": continue if p["key"] not in kwargs and not p["optional"]: raise KeyError("Miss parameter: " + p["key"]) if p["key"] not in kwargs: prompt_config["system"] = prompt_config["system"].replace("{%s}" % p["key"], " ") if len(questions) > 1 and prompt_config.get("refine_multiturn"): questions = [await full_question(dialog.tenant_id, dialog.llm_id, messages)] else: questions = questions[-1:] if prompt_config.get("cross_languages"): questions = [await cross_languages(dialog.tenant_id, dialog.llm_id, questions[0], prompt_config["cross_languages"])] if dialog.meta_data_filter: metas = DocumentService.get_meta_by_kbs(dialog.kb_ids) attachments = await apply_meta_data_filter( dialog.meta_data_filter, metas, questions[-1], chat_mdl, attachments, ) if prompt_config.get("keyword", False): questions[-1] += await keyword_extraction(chat_mdl, questions[-1]) refine_question_ts = timer() thought = "" kbinfos = {"total": 0, "chunks": [], "doc_aggs": []} knowledges = [] if attachments is not None and "knowledge" in [p["key"] for p in prompt_config["parameters"]]: tenant_ids = list(set([kb.tenant_id for kb in kbs])) knowledges = [] if prompt_config.get("reasoning", False): reasoner = DeepResearcher( chat_mdl, prompt_config, partial( retriever.retrieval, embd_mdl=embd_mdl, tenant_ids=tenant_ids, kb_ids=dialog.kb_ids, page=1, page_size=dialog.top_n, similarity_threshold=0.2, vector_similarity_weight=0.3, doc_ids=attachments, ), ) async for think in reasoner.thinking(kbinfos, attachments_ + " ".join(questions)): if isinstance(think, str): thought = think knowledges = [t for t in think.split("\n") if t] elif stream: yield think else: if embd_mdl: kbinfos = retriever.retrieval( " ".join(questions), embd_mdl, tenant_ids, dialog.kb_ids, 1, dialog.top_n, dialog.similarity_threshold, dialog.vector_similarity_weight, doc_ids=attachments, top=dialog.top_k, aggs=True, rerank_mdl=rerank_mdl, rank_feature=label_question(" ".join(questions), kbs), ) if prompt_config.get("toc_enhance"): cks = retriever.retrieval_by_toc(" ".join(questions), kbinfos["chunks"], tenant_ids, chat_mdl, dialog.top_n) if cks: kbinfos["chunks"] = cks kbinfos["chunks"] = retriever.retrieval_by_children(kbinfos["chunks"], tenant_ids) if prompt_config.get("tavily_api_key"): tav = Tavily(prompt_config["tavily_api_key"]) tav_res = tav.retrieve_chunks(" ".join(questions)) kbinfos["chunks"].extend(tav_res["chunks"]) kbinfos["doc_aggs"].extend(tav_res["doc_aggs"]) if prompt_config.get("use_kg"): ck = await settings.kg_retriever.retrieval(" ".join(questions), tenant_ids, dialog.kb_ids, embd_mdl, LLMBundle(dialog.tenant_id, LLMType.CHAT)) if ck["content_with_weight"]: kbinfos["chunks"].insert(0, ck) knowledges = kb_prompt(kbinfos, max_tokens) logging.debug("{}->{}".format(" ".join(questions), "\n->".join(knowledges))) retrieval_ts = timer() if not knowledges and prompt_config.get("empty_response"): empty_res = prompt_config["empty_response"] yield {"answer": empty_res, "reference": kbinfos, "prompt": "\n\n### Query:\n%s" % " ".join(questions), "audio_binary": tts(tts_mdl, empty_res)} yield {"answer": prompt_config["empty_response"], "reference": kbinfos} return kwargs["knowledge"] = "\n------\n" + "\n\n------\n\n".join(knowledges) gen_conf = dialog.llm_setting msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)+attachments_}] prompt4citation = "" if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)): prompt4citation = citation_prompt() msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])} for m in messages if m["role"] != "system"]) used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.95)) assert len(msg) >= 2, f"message_fit_in has bug: {msg}" prompt = msg[0]["content"] if "max_tokens" in gen_conf: gen_conf["max_tokens"] = min(gen_conf["max_tokens"], max_tokens - used_token_count) def decorate_answer(answer): nonlocal embd_mdl, prompt_config, knowledges, kwargs, kbinfos, prompt, retrieval_ts, questions, langfuse_tracer refs = [] ans = answer.split("</think>") think = "" if len(ans) == 2: think = ans[0] + "</think>" answer = ans[1] if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)): idx = set([]) if embd_mdl and not re.search(r"\[ID:([0-9]+)\]", answer): answer, idx = retriever.insert_citations( answer, [ck["content_ltks"] for ck in kbinfos["chunks"]], [ck["vector"] for ck in kbinfos["chunks"]], embd_mdl, tkweight=1 - dialog.vector_similarity_weight, vtweight=dialog.vector_similarity_weight, ) else: for match in re.finditer(r"\[ID:([0-9]+)\]", answer): i = int(match.group(1)) if i < len(kbinfos["chunks"]): idx.add(i) answer, idx = repair_bad_citation_formats(answer, kbinfos, idx) idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx]) recall_docs = [d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx] if not recall_docs: recall_docs = kbinfos["doc_aggs"] kbinfos["doc_aggs"] = recall_docs refs = deepcopy(kbinfos) for c in refs["chunks"]: if c.get("vector"): del c["vector"] if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0: answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'" finish_chat_ts = timer() total_time_cost = (finish_chat_ts - chat_start_ts) * 1000 check_llm_time_cost = (check_llm_ts - chat_start_ts) * 1000 check_langfuse_tracer_cost = (check_langfuse_tracer_ts - check_llm_ts) * 1000 bind_embedding_time_cost = (bind_models_ts - check_langfuse_tracer_ts) * 1000 refine_question_time_cost = (refine_question_ts - bind_models_ts) * 1000 retrieval_time_cost = (retrieval_ts - refine_question_ts) * 1000 generate_result_time_cost = (finish_chat_ts - retrieval_ts) * 1000 tk_num = num_tokens_from_string(think + answer) prompt += "\n\n### Query:\n%s" % " ".join(questions) prompt = ( f"{prompt}\n\n" "## Time elapsed:\n" f" - Total: {total_time_cost:.1f}ms\n" f" - Check LLM: {check_llm_time_cost:.1f}ms\n" f" - Check Langfuse tracer: {check_langfuse_tracer_cost:.1f}ms\n" f" - Bind models: {bind_embedding_time_cost:.1f}ms\n" f" - Query refinement(LLM): {refine_question_time_cost:.1f}ms\n" f" - Retrieval: {retrieval_time_cost:.1f}ms\n" f" - Generate answer: {generate_result_time_cost:.1f}ms\n\n" "## Token usage:\n" f" - Generated tokens(approximately): {tk_num}\n" f" - Token speed: {int(tk_num / (generate_result_time_cost / 1000.0))}/s" ) # Add a condition check to call the end method only if langfuse_tracer exists if langfuse_tracer and "langfuse_generation" in locals(): langfuse_output = "\n" + re.sub(r"^.*?(### Query:.*)", r"\1", prompt, flags=re.DOTALL) langfuse_output = {"time_elapsed:": re.sub(r"\n", " \n", langfuse_output), "created_at": time.time()} langfuse_generation.update(output=langfuse_output) langfuse_generation.end() return {"answer": think + answer, "reference": refs, "prompt": re.sub(r"\n", " \n", prompt), "created_at": time.time()} if langfuse_tracer: langfuse_generation = langfuse_tracer.start_generation( trace_context=trace_context, name="chat", model=llm_model_config["llm_name"], input={"prompt": prompt, "prompt4citation": prompt4citation, "messages": msg} ) if stream: last_ans = "" answer = "" async for ans in chat_mdl.async_chat_streamly(prompt + prompt4citation, msg[1:], gen_conf): if thought: ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL) answer = ans delta_ans = ans[len(last_ans):] if num_tokens_from_string(delta_ans) < 16: continue last_ans = answer yield {"answer": thought + answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)} delta_ans = answer[len(last_ans):] if delta_ans: yield {"answer": thought + answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)} yield decorate_answer(thought + answer) else: answer = await chat_mdl.async_chat(prompt + prompt4citation, msg[1:], gen_conf) user_content = msg[-1].get("content", "[content not available]") logging.debug("User: {}|Assistant: {}".format(user_content, answer)) res = decorate_answer(answer) res["audio_binary"] = tts(tts_mdl, answer) yield res return async def use_sql(question, field_map, tenant_id, chat_mdl, quota=True, kb_ids=None): sys_prompt = """ You are a Database Administrator. You need to check the fields of the following tables based on the user's list of questions and write the SQL corresponding to the last question. Ensure that: 1. Field names should not start with a digit. If any field name starts with a digit, use double quotes around it. 2. Write only the SQL, no explanations or additional text. """ user_prompt = """ Table name: {}; Table of database fields are as follows: {} Question are as follows: {} Please write the SQL, only SQL, without any other explanations or text. """.format(index_name(tenant_id), "\n".join([f"{k}: {v}" for k, v in field_map.items()]), question) tried_times = 0 async def get_table(): nonlocal sys_prompt, user_prompt, question, tried_times sql = await chat_mdl.async_chat(sys_prompt, [{"role": "user", "content": user_prompt}], {"temperature": 0.06}) sql = re.sub(r"^.*</think>", "", sql, flags=re.DOTALL) logging.debug(f"{question} ==> {user_prompt} get SQL: {sql}") sql = re.sub(r"[\r\n]+", " ", sql.lower()) sql = re.sub(r".*select ", "select ", sql.lower()) sql = re.sub(r" +", " ", sql) sql = re.sub(r"([;;]|```).*", "", sql) sql = re.sub(r"&", "and", sql) if sql[: len("select ")] != "select ": return None, None if not re.search(r"((sum|avg|max|min)\(|group by )", sql.lower()): if sql[: len("select *")] != "select *": sql = "select doc_id,docnm_kwd," + sql[6:] else: flds = [] for k in field_map.keys(): if k in forbidden_select_fields4resume: continue if len(flds) > 11: break flds.append(k) sql = "select doc_id,docnm_kwd," + ",".join(flds) + sql[8:] if kb_ids: kb_filter = "(" + " OR ".join([f"kb_id = '{kb_id}'" for kb_id in kb_ids]) + ")" if "where" not in sql.lower(): o = sql.lower().split("order by") if len(o) > 1: sql = o[0] + f" WHERE {kb_filter} order by " + o[1] else: sql += f" WHERE {kb_filter}" else: sql += f" AND {kb_filter}" logging.debug(f"{question} get SQL(refined): {sql}") tried_times += 1 return settings.retriever.sql_retrieval(sql, format="json"), sql try: tbl, sql = await get_table() except Exception as e: user_prompt = """ Table name: {}; Table of database fields are as follows: {} Question are as follows: {} Please write the SQL, only SQL, without any other explanations or text. The SQL error you provided last time is as follows: {} Please correct the error and write SQL again, only SQL, without any other explanations or text. """.format(index_name(tenant_id), "\n".join([f"{k}: {v}" for k, v in field_map.items()]), question, e) try: tbl, sql = await get_table() except Exception: return if len(tbl["rows"]) == 0: return None docid_idx = set([ii for ii, c in enumerate(tbl["columns"]) if c["name"] == "doc_id"]) doc_name_idx = set([ii for ii, c in enumerate(tbl["columns"]) if c["name"] == "docnm_kwd"]) column_idx = [ii for ii in range(len(tbl["columns"])) if ii not in (docid_idx | doc_name_idx)] # compose Markdown table columns = ( "|" + "|".join( [re.sub(r"(/.*|([^()]+))", "", field_map.get(tbl["columns"][i]["name"], tbl["columns"][i]["name"])) for i in column_idx]) + ( "|Source|" if docid_idx and docid_idx else "|") ) line = "|" + "|".join(["------" for _ in range(len(column_idx))]) + ("|------|" if docid_idx and docid_idx else "") rows = ["|" + "|".join([remove_redundant_spaces(str(r[i])) for i in column_idx]).replace("None", " ") + "|" for r in tbl["rows"]] rows = [r for r in rows if re.sub(r"[ |]+", "", r)] if quota: rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)]) else: rows = "\n".join([r + f" ##{ii}$$ |" for ii, r in enumerate(rows)]) rows = re.sub(r"T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+Z)?\|", "|", rows) if not docid_idx or not doc_name_idx: logging.warning("SQL missing field: " + sql) return {"answer": "\n".join([columns, line, rows]), "reference": {"chunks": [], "doc_aggs": []}, "prompt": sys_prompt} docid_idx = list(docid_idx)[0] doc_name_idx = list(doc_name_idx)[0] doc_aggs = {} for r in tbl["rows"]: if r[docid_idx] not in doc_aggs: doc_aggs[r[docid_idx]] = {"doc_name": r[doc_name_idx], "count": 0} doc_aggs[r[docid_idx]]["count"] += 1 return { "answer": "\n".join([columns, line, rows]), "reference": { "chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[doc_name_idx]} for r in tbl["rows"]], "doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in doc_aggs.items()], }, "prompt": sys_prompt, } 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 def tts(tts_mdl, 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") async def async_ask(question, kb_ids, tenant_id, chat_llm_name=None, search_config={}): doc_ids = search_config.get("doc_ids", []) rerank_mdl = None kb_ids = search_config.get("kb_ids", kb_ids) chat_llm_name = search_config.get("chat_id", chat_llm_name) rerank_id = search_config.get("rerank_id", "") meta_data_filter = search_config.get("meta_data_filter") kbs = KnowledgebaseService.get_by_ids(kb_ids) embedding_list = list(set([kb.embd_id for kb in kbs])) is_knowledge_graph = all([kb.parser_id == ParserType.KG for kb in kbs]) retriever = settings.retriever if not is_knowledge_graph else settings.kg_retriever embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embedding_list[0]) chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, chat_llm_name) if rerank_id: rerank_mdl = LLMBundle(tenant_id, LLMType.RERANK, rerank_id) max_tokens = chat_mdl.max_length tenant_ids = list(set([kb.tenant_id for kb in kbs])) if meta_data_filter: metas = DocumentService.get_meta_by_kbs(kb_ids) doc_ids = await apply_meta_data_filter(meta_data_filter, metas, question, chat_mdl, doc_ids) kbinfos = retriever.retrieval( question=question, embd_mdl=embd_mdl, tenant_ids=tenant_ids, kb_ids=kb_ids, page=1, page_size=12, similarity_threshold=search_config.get("similarity_threshold", 0.1), vector_similarity_weight=search_config.get("vector_similarity_weight", 0.3), top=search_config.get("top_k", 1024), doc_ids=doc_ids, aggs=True, rerank_mdl=rerank_mdl, rank_feature=label_question(question, kbs) ) knowledges = kb_prompt(kbinfos, max_tokens) sys_prompt = PROMPT_JINJA_ENV.from_string(ASK_SUMMARY).render(knowledge="\n".join(knowledges)) msg = [{"role": "user", "content": question}] def decorate_answer(answer): nonlocal knowledges, kbinfos, sys_prompt answer, idx = retriever.insert_citations(answer, [ck["content_ltks"] for ck in kbinfos["chunks"]], [ck["vector"] for ck in kbinfos["chunks"]], embd_mdl, tkweight=0.7, vtweight=0.3) idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx]) recall_docs = [d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx] if not recall_docs: recall_docs = kbinfos["doc_aggs"] kbinfos["doc_aggs"] = recall_docs refs = deepcopy(kbinfos)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/document_service.py
api/db/services/document_service.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 random import re from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from datetime import datetime from io import BytesIO import xxhash from peewee import fn, Case, JOIN from api.constants import IMG_BASE64_PREFIX, FILE_NAME_LEN_LIMIT from api.db import PIPELINE_SPECIAL_PROGRESS_FREEZE_TASK_TYPES, FileType, UserTenantRole, CanvasCategory from api.db.db_models import DB, Document, Knowledgebase, Task, Tenant, UserTenant, File2Document, File, UserCanvas, \ User from api.db.db_utils import bulk_insert_into_db from api.db.services.common_service import CommonService from api.db.services.knowledgebase_service import KnowledgebaseService from common.metadata_utils import dedupe_list from common.misc_utils import get_uuid from common.time_utils import current_timestamp, get_format_time from common.constants import LLMType, ParserType, StatusEnum, TaskStatus, SVR_CONSUMER_GROUP_NAME from rag.nlp import rag_tokenizer, search from rag.utils.redis_conn import REDIS_CONN from common.doc_store.doc_store_base import OrderByExpr from common import settings class DocumentService(CommonService): model = Document @classmethod def get_cls_model_fields(cls): return [ cls.model.id, cls.model.thumbnail, cls.model.kb_id, cls.model.parser_id, cls.model.pipeline_id, cls.model.parser_config, cls.model.source_type, cls.model.type, cls.model.created_by, cls.model.name, cls.model.location, cls.model.size, cls.model.token_num, cls.model.chunk_num, cls.model.progress, cls.model.progress_msg, cls.model.process_begin_at, cls.model.process_duration, cls.model.meta_fields, cls.model.suffix, cls.model.run, cls.model.status, cls.model.create_time, cls.model.create_date, cls.model.update_time, cls.model.update_date, ] @classmethod @DB.connection_context() def get_list(cls, kb_id, page_number, items_per_page, orderby, desc, keywords, id, name, suffix=None, run = None, doc_ids=None): fields = cls.get_cls_model_fields() docs = cls.model.select(*[*fields, UserCanvas.title]).join(File2Document, on = (File2Document.document_id == cls.model.id))\ .join(File, on = (File.id == File2Document.file_id))\ .join(UserCanvas, on = ((cls.model.pipeline_id == UserCanvas.id) & (UserCanvas.canvas_category == CanvasCategory.DataFlow.value)), join_type=JOIN.LEFT_OUTER)\ .where(cls.model.kb_id == kb_id) if id: docs = docs.where( cls.model.id == id) if name: docs = docs.where( cls.model.name == name ) if keywords: docs = docs.where( fn.LOWER(cls.model.name).contains(keywords.lower()) ) if doc_ids: docs = docs.where(cls.model.id.in_(doc_ids)) if suffix: docs = docs.where(cls.model.suffix.in_(suffix)) if run: docs = docs.where(cls.model.run.in_(run)) if desc: docs = docs.order_by(cls.model.getter_by(orderby).desc()) else: docs = docs.order_by(cls.model.getter_by(orderby).asc()) count = docs.count() docs = docs.paginate(page_number, items_per_page) return list(docs.dicts()), count @classmethod @DB.connection_context() def check_doc_health(cls, tenant_id: str, filename): import os MAX_FILE_NUM_PER_USER = int(os.environ.get("MAX_FILE_NUM_PER_USER", 0)) if 0 < MAX_FILE_NUM_PER_USER <= DocumentService.get_doc_count(tenant_id): raise RuntimeError("Exceed the maximum file number of a free user!") if len(filename.encode("utf-8")) > FILE_NAME_LEN_LIMIT: raise RuntimeError("Exceed the maximum length of file name!") return True @classmethod @DB.connection_context() def get_by_kb_id(cls, kb_id, page_number, items_per_page, orderby, desc, keywords, run_status, types, suffix, doc_ids=None, return_empty_metadata=False): fields = cls.get_cls_model_fields() if keywords: docs = ( cls.model.select(*[*fields, UserCanvas.title.alias("pipeline_name"), User.nickname]) .join(File2Document, on=(File2Document.document_id == cls.model.id)) .join(File, on=(File.id == File2Document.file_id)) .join(UserCanvas, on=(cls.model.pipeline_id == UserCanvas.id), join_type=JOIN.LEFT_OUTER) .join(User, on=(cls.model.created_by == User.id), join_type=JOIN.LEFT_OUTER) .where((cls.model.kb_id == kb_id), (fn.LOWER(cls.model.name).contains(keywords.lower()))) ) else: docs = ( cls.model.select(*[*fields, UserCanvas.title.alias("pipeline_name"), User.nickname]) .join(File2Document, on=(File2Document.document_id == cls.model.id)) .join(UserCanvas, on=(cls.model.pipeline_id == UserCanvas.id), join_type=JOIN.LEFT_OUTER) .join(File, on=(File.id == File2Document.file_id)) .join(User, on=(cls.model.created_by == User.id), join_type=JOIN.LEFT_OUTER) .where(cls.model.kb_id == kb_id) ) if doc_ids: docs = docs.where(cls.model.id.in_(doc_ids)) if run_status: docs = docs.where(cls.model.run.in_(run_status)) if types: docs = docs.where(cls.model.type.in_(types)) if suffix: docs = docs.where(cls.model.suffix.in_(suffix)) if return_empty_metadata: docs = docs.where(fn.COALESCE(fn.JSON_LENGTH(cls.model.meta_fields), 0) == 0) count = docs.count() if desc: docs = docs.order_by(cls.model.getter_by(orderby).desc()) else: docs = docs.order_by(cls.model.getter_by(orderby).asc()) if page_number and items_per_page: docs = docs.paginate(page_number, items_per_page) return list(docs.dicts()), count @classmethod @DB.connection_context() def get_filter_by_kb_id(cls, kb_id, keywords, run_status, types, suffix): """ returns: { "suffix": { "ppt": 1, "doxc": 2 }, "run_status": { "1": 2, "2": 2 } "metadata": { "key1": { "key1_value1": 1, "key1_value2": 2, }, "key2": { "key2_value1": 2, "key2_value2": 1, }, } }, total where "1" => RUNNING, "2" => CANCEL """ fields = cls.get_cls_model_fields() if keywords: query = cls.model.select(*fields).join(File2Document, on=(File2Document.document_id == cls.model.id)).join(File, on=(File.id == File2Document.file_id)).where( (cls.model.kb_id == kb_id), (fn.LOWER(cls.model.name).contains(keywords.lower())) ) else: query = cls.model.select(*fields).join(File2Document, on=(File2Document.document_id == cls.model.id)).join(File, on=(File.id == File2Document.file_id)).where(cls.model.kb_id == kb_id) if run_status: query = query.where(cls.model.run.in_(run_status)) if types: query = query.where(cls.model.type.in_(types)) if suffix: query = query.where(cls.model.suffix.in_(suffix)) rows = query.select(cls.model.run, cls.model.suffix, cls.model.meta_fields) total = rows.count() suffix_counter = {} run_status_counter = {} metadata_counter = {} empty_metadata_count = 0 for row in rows: suffix_counter[row.suffix] = suffix_counter.get(row.suffix, 0) + 1 run_status_counter[str(row.run)] = run_status_counter.get(str(row.run), 0) + 1 meta_fields = row.meta_fields or {} if not meta_fields: empty_metadata_count += 1 continue has_valid_meta = False for key, value in meta_fields.items(): values = value if isinstance(value, list) else [value] for vv in values: if vv is None: continue if isinstance(vv, str) and not vv.strip(): continue sv = str(vv) if key not in metadata_counter: metadata_counter[key] = {} metadata_counter[key][sv] = metadata_counter[key].get(sv, 0) + 1 has_valid_meta = True if not has_valid_meta: empty_metadata_count += 1 metadata_counter["empty_metadata"] = {"true": empty_metadata_count} return { "suffix": suffix_counter, "run_status": run_status_counter, "metadata": metadata_counter, }, total @classmethod @DB.connection_context() def count_by_kb_id(cls, kb_id, keywords, run_status, types): if keywords: docs = cls.model.select().where( (cls.model.kb_id == kb_id), (fn.LOWER(cls.model.name).contains(keywords.lower())) ) else: docs = cls.model.select().where(cls.model.kb_id == kb_id) if run_status: docs = docs.where(cls.model.run.in_(run_status)) if types: docs = docs.where(cls.model.type.in_(types)) count = docs.count() return count @classmethod @DB.connection_context() def get_total_size_by_kb_id(cls, kb_id, keywords="", run_status=[], types=[]): query = cls.model.select(fn.COALESCE(fn.SUM(cls.model.size), 0)).where( cls.model.kb_id == kb_id ) if keywords: query = query.where(fn.LOWER(cls.model.name).contains(keywords.lower())) if run_status: query = query.where(cls.model.run.in_(run_status)) if types: query = query.where(cls.model.type.in_(types)) return int(query.scalar()) or 0 @classmethod @DB.connection_context() def get_all_doc_ids_by_kb_ids(cls, kb_ids): fields = [cls.model.id] docs = cls.model.select(*fields).where(cls.model.kb_id.in_(kb_ids)) docs.order_by(cls.model.create_time.asc()) # maybe cause slow query by deep paginate, optimize later offset, limit = 0, 100 res = [] while True: doc_batch = docs.offset(offset).limit(limit) _temp = list(doc_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res @classmethod @DB.connection_context() def get_all_docs_by_creator_id(cls, creator_id): fields = [ cls.model.id, cls.model.kb_id, cls.model.token_num, cls.model.chunk_num, Knowledgebase.tenant_id ] docs = cls.model.select(*fields).join(Knowledgebase, on=(Knowledgebase.id == cls.model.kb_id)).where( cls.model.created_by == creator_id ) docs.order_by(cls.model.create_time.asc()) # maybe cause slow query by deep paginate, optimize later offset, limit = 0, 100 res = [] while True: doc_batch = docs.offset(offset).limit(limit) _temp = list(doc_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res @classmethod @DB.connection_context() def insert(cls, doc): if not cls.save(**doc): raise RuntimeError("Database error (Document)!") if not KnowledgebaseService.atomic_increase_doc_num_by_id(doc["kb_id"]): raise RuntimeError("Database error (Knowledgebase)!") return Document(**doc) @classmethod @DB.connection_context() def remove_document(cls, doc, tenant_id): from api.db.services.task_service import TaskService cls.clear_chunk_num(doc.id) try: TaskService.filter_delete([Task.doc_id == doc.id]) cls.delete_chunk_images(doc, tenant_id) if doc.thumbnail and not doc.thumbnail.startswith(IMG_BASE64_PREFIX): if settings.STORAGE_IMPL.obj_exist(doc.kb_id, doc.thumbnail): settings.STORAGE_IMPL.rm(doc.kb_id, doc.thumbnail) settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), doc.kb_id) graph_source = settings.docStoreConn.get_fields( settings.docStoreConn.search(["source_id"], [], {"kb_id": doc.kb_id, "knowledge_graph_kwd": ["graph"]}, [], OrderByExpr(), 0, 1, search.index_name(tenant_id), [doc.kb_id]), ["source_id"] ) if len(graph_source) > 0 and doc.id in list(graph_source.values())[0]["source_id"]: settings.docStoreConn.update({"kb_id": doc.kb_id, "knowledge_graph_kwd": ["entity", "relation", "graph", "subgraph", "community_report"], "source_id": doc.id}, {"remove": {"source_id": doc.id}}, search.index_name(tenant_id), doc.kb_id) settings.docStoreConn.update({"kb_id": doc.kb_id, "knowledge_graph_kwd": ["graph"]}, {"removed_kwd": "Y"}, search.index_name(tenant_id), doc.kb_id) settings.docStoreConn.delete({"kb_id": doc.kb_id, "knowledge_graph_kwd": ["entity", "relation", "graph", "subgraph", "community_report"], "must_not": {"exists": "source_id"}}, search.index_name(tenant_id), doc.kb_id) except Exception: pass return cls.delete_by_id(doc.id) @classmethod @DB.connection_context() def delete_chunk_images(cls, doc, tenant_id): page = 0 page_size = 1000 while True: chunks = settings.docStoreConn.search(["img_id"], [], {"doc_id": doc.id}, [], OrderByExpr(), page * page_size, page_size, search.index_name(tenant_id), [doc.kb_id]) chunk_ids = settings.docStoreConn.get_doc_ids(chunks) if not chunk_ids: break for cid in chunk_ids: if settings.STORAGE_IMPL.obj_exist(doc.kb_id, cid): settings.STORAGE_IMPL.rm(doc.kb_id, cid) page += 1 @classmethod @DB.connection_context() def get_newly_uploaded(cls): fields = [ cls.model.id, cls.model.kb_id, cls.model.parser_id, cls.model.parser_config, cls.model.name, cls.model.type, cls.model.location, cls.model.size, Knowledgebase.tenant_id, Tenant.embd_id, Tenant.img2txt_id, Tenant.asr_id, cls.model.update_time] docs = cls.model.select(*fields) \ .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id)) \ .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id)) \ .where( cls.model.status == StatusEnum.VALID.value, ~(cls.model.type == FileType.VIRTUAL.value), cls.model.progress == 0, cls.model.update_time >= current_timestamp() - 1000 * 600, cls.model.run == TaskStatus.RUNNING.value) \ .order_by(cls.model.update_time.asc()) return list(docs.dicts()) @classmethod @DB.connection_context() def get_unfinished_docs(cls): fields = [cls.model.id, cls.model.process_begin_at, cls.model.parser_config, cls.model.progress_msg, cls.model.run, cls.model.parser_id] unfinished_task_query = Task.select(Task.doc_id).where( (Task.progress >= 0) & (Task.progress < 1) ) docs = cls.model.select(*fields) \ .where( cls.model.status == StatusEnum.VALID.value, ~(cls.model.type == FileType.VIRTUAL.value), (((cls.model.progress < 1) & (cls.model.progress > 0)) | (cls.model.id.in_(unfinished_task_query)))) # including unfinished tasks like GraphRAG, RAPTOR and Mindmap return list(docs.dicts()) @classmethod @DB.connection_context() def increment_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duration): num = cls.model.update(token_num=cls.model.token_num + token_num, chunk_num=cls.model.chunk_num + chunk_num, process_duration=cls.model.process_duration + duration).where( cls.model.id == doc_id).execute() if num == 0: logging.warning("Document not found which is supposed to be there") num = Knowledgebase.update( token_num=Knowledgebase.token_num + token_num, chunk_num=Knowledgebase.chunk_num + chunk_num).where( Knowledgebase.id == kb_id).execute() return num @classmethod @DB.connection_context() def decrement_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duration): num = cls.model.update(token_num=cls.model.token_num - token_num, chunk_num=cls.model.chunk_num - chunk_num, process_duration=cls.model.process_duration + duration).where( cls.model.id == doc_id).execute() if num == 0: raise LookupError( "Document not found which is supposed to be there") num = Knowledgebase.update( token_num=Knowledgebase.token_num - token_num, chunk_num=Knowledgebase.chunk_num - chunk_num ).where( Knowledgebase.id == kb_id).execute() return num @classmethod @DB.connection_context() def clear_chunk_num(cls, doc_id): doc = cls.model.get_by_id(doc_id) assert doc, "Can't fine document in database." num = Knowledgebase.update( token_num=Knowledgebase.token_num - doc.token_num, chunk_num=Knowledgebase.chunk_num - doc.chunk_num, doc_num=Knowledgebase.doc_num - 1 ).where( Knowledgebase.id == doc.kb_id).execute() return num @classmethod @DB.connection_context() def clear_chunk_num_when_rerun(cls, doc_id): doc = cls.model.get_by_id(doc_id) assert doc, "Can't fine document in database." num = ( Knowledgebase.update( token_num=Knowledgebase.token_num - doc.token_num, chunk_num=Knowledgebase.chunk_num - doc.chunk_num, ) .where(Knowledgebase.id == doc.kb_id) .execute() ) return num @classmethod @DB.connection_context() def get_tenant_id(cls, doc_id): docs = cls.model.select( Knowledgebase.tenant_id).join( Knowledgebase, on=( Knowledgebase.id == cls.model.kb_id)).where( cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value) docs = docs.dicts() if not docs: return None return docs[0]["tenant_id"] @classmethod @DB.connection_context() def get_knowledgebase_id(cls, doc_id): docs = cls.model.select(cls.model.kb_id).where(cls.model.id == doc_id) docs = docs.dicts() if not docs: return None return docs[0]["kb_id"] @classmethod @DB.connection_context() def get_tenant_id_by_name(cls, name): docs = cls.model.select( Knowledgebase.tenant_id).join( Knowledgebase, on=( Knowledgebase.id == cls.model.kb_id)).where( cls.model.name == name, Knowledgebase.status == StatusEnum.VALID.value) docs = docs.dicts() if not docs: return None return docs[0]["tenant_id"] @classmethod @DB.connection_context() def accessible(cls, doc_id, user_id): docs = cls.model.select( cls.model.id).join( Knowledgebase, on=( Knowledgebase.id == cls.model.kb_id) ).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id) ).where(cls.model.id == doc_id, UserTenant.user_id == user_id).paginate(0, 1) docs = docs.dicts() if not docs: return False return True @classmethod @DB.connection_context() def accessible4deletion(cls, doc_id, user_id): docs = cls.model.select(cls.model.id ).join( Knowledgebase, on=( Knowledgebase.id == cls.model.kb_id) ).join( UserTenant, on=( (UserTenant.tenant_id == Knowledgebase.created_by) & (UserTenant.user_id == user_id)) ).where( cls.model.id == doc_id, UserTenant.status == StatusEnum.VALID.value, ((UserTenant.role == UserTenantRole.NORMAL) | (UserTenant.role == UserTenantRole.OWNER)) ).paginate(0, 1) docs = docs.dicts() if not docs: return False return True @classmethod @DB.connection_context() def get_embd_id(cls, doc_id): docs = cls.model.select( Knowledgebase.embd_id).join( Knowledgebase, on=( Knowledgebase.id == cls.model.kb_id)).where( cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value) docs = docs.dicts() if not docs: return None return docs[0]["embd_id"] @classmethod @DB.connection_context() def get_chunking_config(cls, doc_id): configs = ( cls.model.select( cls.model.id, cls.model.kb_id, cls.model.parser_id, cls.model.parser_config, Knowledgebase.language, Knowledgebase.embd_id, Tenant.id.alias("tenant_id"), Tenant.img2txt_id, Tenant.asr_id, Tenant.llm_id, ) .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id)) .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id)) .where(cls.model.id == doc_id) ) configs = configs.dicts() if not configs: return None return configs[0] @classmethod @DB.connection_context() def get_doc_id_by_doc_name(cls, doc_name): fields = [cls.model.id] doc_id = cls.model.select(*fields) \ .where(cls.model.name == doc_name) doc_id = doc_id.dicts() if not doc_id: return None return doc_id[0]["id"] @classmethod @DB.connection_context() def get_doc_ids_by_doc_names(cls, doc_names): if not doc_names: return [] query = cls.model.select(cls.model.id).where(cls.model.name.in_(doc_names)) return list(query.scalars().iterator()) @classmethod @DB.connection_context() def get_thumbnails(cls, docids): fields = [cls.model.id, cls.model.kb_id, cls.model.thumbnail] return list(cls.model.select( *fields).where(cls.model.id.in_(docids)).dicts()) @classmethod @DB.connection_context() def update_parser_config(cls, id, config): if not config: return e, d = cls.get_by_id(id) if not e: raise LookupError(f"Document({id}) not found.") def dfs_update(old, new): for k, v in new.items(): if k not in old: old[k] = v continue if isinstance(v, dict): assert isinstance(old[k], dict) dfs_update(old[k], v) else: old[k] = v dfs_update(d.parser_config, config) if not config.get("raptor") and d.parser_config.get("raptor"): del d.parser_config["raptor"] cls.update_by_id(id, {"parser_config": d.parser_config}) @classmethod @DB.connection_context() def get_doc_count(cls, tenant_id): docs = cls.model.select(cls.model.id).join(Knowledgebase, on=(Knowledgebase.id == cls.model.kb_id)).where( Knowledgebase.tenant_id == tenant_id) return len(docs) @classmethod @DB.connection_context() def begin2parse(cls, doc_id, keep_progress=False): info = { "progress_msg": "Task is queued...", "process_begin_at": get_format_time(), } if not keep_progress: info["progress"] = random.random() * 1 / 100. info["run"] = TaskStatus.RUNNING.value # keep the doc in DONE state when keep_progress=True for GraphRAG, RAPTOR and Mindmap tasks cls.update_by_id(doc_id, info) @classmethod @DB.connection_context() def update_meta_fields(cls, doc_id, meta_fields): return cls.update_by_id(doc_id, {"meta_fields": meta_fields}) @classmethod @DB.connection_context() def get_meta_by_kbs(cls, kb_ids): """ Legacy metadata aggregator (backward-compatible). - Does NOT expand list values and a list is kept as one string key. Example: {"tags": ["foo","bar"]} -> meta["tags"]["['foo', 'bar']"] = [doc_id] - Expects meta_fields is a dict. Use when existing callers rely on the old list-as-string semantics. """ fields = [ cls.model.id, cls.model.meta_fields, ] meta = {} for r in cls.model.select(*fields).where(cls.model.kb_id.in_(kb_ids)): doc_id = r.id for k,v in r.meta_fields.items(): if k not in meta: meta[k] = {} if not isinstance(v, list): v = [v] for vv in v: if vv not in meta[k]: if isinstance(vv, list) or isinstance(vv, dict): continue meta[k][vv] = [] meta[k][vv].append(doc_id) return meta @classmethod @DB.connection_context() def get_flatted_meta_by_kbs(cls, kb_ids): """ - Parses stringified JSON meta_fields when possible and skips non-dict or unparsable values. - Expands list values into individual entries. Example: {"tags": ["foo","bar"], "author": "alice"} -> meta["tags"]["foo"] = [doc_id], meta["tags"]["bar"] = [doc_id], meta["author"]["alice"] = [doc_id] Prefer for metadata_condition filtering and scenarios that must respect list semantics. """ fields = [ cls.model.id, cls.model.meta_fields, ] meta = {} for r in cls.model.select(*fields).where(cls.model.kb_id.in_(kb_ids)): doc_id = r.id meta_fields = r.meta_fields or {} if isinstance(meta_fields, str): try: meta_fields = json.loads(meta_fields) except Exception: continue if not isinstance(meta_fields, dict): continue for k, v in meta_fields.items(): if k not in meta: meta[k] = {} values = v if isinstance(v, list) else [v] for vv in values: if vv is None: continue sv = str(vv) if sv not in meta[k]: meta[k][sv] = [] meta[k][sv].append(doc_id) return meta @classmethod @DB.connection_context() def get_metadata_summary(cls, kb_id): fields = [cls.model.id, cls.model.meta_fields] summary = {} for r in cls.model.select(*fields).where(cls.model.kb_id == kb_id): meta_fields = r.meta_fields or {} if isinstance(meta_fields, str): try: meta_fields = json.loads(meta_fields) except Exception: continue if not isinstance(meta_fields, dict): continue for k, v in meta_fields.items(): values = v if isinstance(v, list) else [v] for vv in values: if not vv: continue sv = str(vv) if k not in summary: summary[k] = {} summary[k][sv] = summary[k].get(sv, 0) + 1 return {k: sorted([(val, cnt) for val, cnt in v.items()], key=lambda x: x[1], reverse=True) for k, v in summary.items()} @classmethod @DB.connection_context() def batch_update_metadata(cls, kb_id, doc_ids, updates=None, deletes=None): updates = updates or [] deletes = deletes or [] if not doc_ids: return 0 def _normalize_meta(meta): if isinstance(meta, str): try: meta = json.loads(meta) except Exception: return {} if not isinstance(meta, dict): return {} return deepcopy(meta) def _str_equal(a, b): return str(a) == str(b) def _apply_updates(meta): changed = False for upd in updates: key = upd.get("key") if not key or key not in meta: continue new_value = upd.get("value") match_provided = "match" in upd if isinstance(meta[key], list): if not match_provided: if isinstance(new_value, list): meta[key] = dedupe_list(new_value) else: meta[key] = new_value changed = True else: match_value = upd.get("match") replaced = False new_list = [] for item in meta[key]: if _str_equal(item, match_value): new_list.append(new_value) replaced = True else: new_list.append(item) if replaced: meta[key] = dedupe_list(new_list) changed = True else: if not match_provided: meta[key] = new_value changed = True else: match_value = upd.get("match") if _str_equal(meta[key], match_value): meta[key] = new_value changed = True return changed def _apply_deletes(meta): changed = False for d in deletes: key = d.get("key") if not key or key not in meta: continue value = d.get("value", None)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
true
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/pipeline_operation_log_service.py
api/db/services/pipeline_operation_log_service.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 import logging import os from datetime import datetime, timedelta from peewee import fn from api.db import VALID_PIPELINE_TASK_TYPES, PipelineTaskType from api.db.db_models import DB, Document, PipelineOperationLog from api.db.services.canvas_service import UserCanvasService from api.db.services.common_service import CommonService from api.db.services.document_service import DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.task_service import GRAPH_RAPTOR_FAKE_DOC_ID from common.misc_utils import get_uuid from common.time_utils import current_timestamp, datetime_format class PipelineOperationLogService(CommonService): model = PipelineOperationLog @classmethod def get_file_logs_fields(cls): return [ cls.model.id, cls.model.document_id, cls.model.tenant_id, cls.model.kb_id, cls.model.pipeline_id, cls.model.pipeline_title, cls.model.parser_id, cls.model.document_name, cls.model.document_suffix, cls.model.document_type, cls.model.source_from, cls.model.progress, cls.model.progress_msg, cls.model.process_begin_at, cls.model.process_duration, cls.model.dsl, cls.model.task_type, cls.model.operation_status, cls.model.avatar, cls.model.status, cls.model.create_time, cls.model.create_date, cls.model.update_time, cls.model.update_date, ] @classmethod def get_dataset_logs_fields(cls): return [ cls.model.id, cls.model.tenant_id, cls.model.kb_id, cls.model.progress, cls.model.progress_msg, cls.model.process_begin_at, cls.model.process_duration, cls.model.task_type, cls.model.operation_status, cls.model.avatar, cls.model.status, cls.model.create_time, cls.model.create_date, cls.model.update_time, cls.model.update_date, ] @classmethod def save(cls, **kwargs): """ wrap this function in a transaction """ sample_obj = cls.model(**kwargs).save(force_insert=True) return sample_obj @classmethod @DB.connection_context() def create(cls, document_id, pipeline_id, task_type, fake_document_ids=[], dsl: str = "{}"): referred_document_id = document_id if referred_document_id == GRAPH_RAPTOR_FAKE_DOC_ID and fake_document_ids: referred_document_id = fake_document_ids[0] ok, document = DocumentService.get_by_id(referred_document_id) if not ok: logging.warning(f"Document for referred_document_id {referred_document_id} not found") return None DocumentService.update_progress_immediately([document.to_dict()]) ok, document = DocumentService.get_by_id(referred_document_id) if not ok: logging.warning(f"Document for referred_document_id {referred_document_id} not found") return None if document.progress not in [1, -1]: return None operation_status = document.run if pipeline_id: ok, user_pipeline = UserCanvasService.get_by_id(pipeline_id) if not ok: raise RuntimeError(f"Pipeline {pipeline_id} not found") tenant_id = user_pipeline.user_id title = user_pipeline.title avatar = user_pipeline.avatar else: ok, kb_info = KnowledgebaseService.get_by_id(document.kb_id) if not ok: raise RuntimeError(f"Cannot find dataset {document.kb_id} for referred_document {referred_document_id}") tenant_id = kb_info.tenant_id title = document.parser_id avatar = document.thumbnail if task_type not in VALID_PIPELINE_TASK_TYPES: raise ValueError(f"Invalid task type: {task_type}") if task_type in [PipelineTaskType.GRAPH_RAG, PipelineTaskType.RAPTOR, PipelineTaskType.MINDMAP]: finish_at = document.process_begin_at + timedelta(seconds=document.process_duration) if task_type == PipelineTaskType.GRAPH_RAG: KnowledgebaseService.update_by_id( document.kb_id, {"graphrag_task_finish_at": finish_at}, ) elif task_type == PipelineTaskType.RAPTOR: KnowledgebaseService.update_by_id( document.kb_id, {"raptor_task_finish_at": finish_at}, ) elif task_type == PipelineTaskType.MINDMAP: KnowledgebaseService.update_by_id( document.kb_id, {"mindmap_task_finish_at": finish_at}, ) log = dict( id=get_uuid(), document_id=document_id, # GRAPH_RAPTOR_FAKE_DOC_ID or real document_id tenant_id=tenant_id, kb_id=document.kb_id, pipeline_id=pipeline_id, pipeline_title=title, parser_id=document.parser_id, document_name=document.name, document_suffix=document.suffix, document_type=document.type, source_from=document.source_type.split("/")[0], progress=document.progress, progress_msg=document.progress_msg, process_begin_at=document.process_begin_at, process_duration=document.process_duration, dsl=json.loads(dsl), task_type=task_type, operation_status=operation_status, avatar=avatar, ) timestamp = current_timestamp() datetime_now = datetime_format(datetime.now()) log["create_time"] = timestamp log["create_date"] = datetime_now log["update_time"] = timestamp log["update_date"] = datetime_now with DB.atomic(): obj = cls.save(**log) limit = int(os.getenv("PIPELINE_OPERATION_LOG_LIMIT", 1000)) total = cls.model.select().where(cls.model.kb_id == document.kb_id).count() if total > limit: keep_ids = [m.id for m in cls.model.select(cls.model.id).where(cls.model.kb_id == document.kb_id).order_by(cls.model.create_time.desc()).limit(limit)] deleted = cls.model.delete().where(cls.model.kb_id == document.kb_id, cls.model.id.not_in(keep_ids)).execute() logging.info(f"[PipelineOperationLogService] Cleaned {deleted} old logs, kept latest {limit} for {document.kb_id}") return obj @classmethod @DB.connection_context() def record_pipeline_operation(cls, document_id, pipeline_id, task_type, fake_document_ids=[]): return cls.create(document_id=document_id, pipeline_id=pipeline_id, task_type=task_type, fake_document_ids=fake_document_ids) @classmethod @DB.connection_context() def get_file_logs_by_kb_id(cls, kb_id, page_number, items_per_page, orderby, desc, keywords, operation_status, types, suffix, create_date_from=None, create_date_to=None): fields = cls.get_file_logs_fields() if keywords: logs = cls.model.select(*fields).where((cls.model.kb_id == kb_id), (fn.LOWER(cls.model.document_name).contains(keywords.lower()))) else: logs = cls.model.select(*fields).where(cls.model.kb_id == kb_id) logs = logs.where(cls.model.document_id != GRAPH_RAPTOR_FAKE_DOC_ID) if operation_status: logs = logs.where(cls.model.operation_status.in_(operation_status)) if types: logs = logs.where(cls.model.document_type.in_(types)) if suffix: logs = logs.where(cls.model.document_suffix.in_(suffix)) if create_date_from: logs = logs.where(cls.model.create_date >= create_date_from) if create_date_to: logs = logs.where(cls.model.create_date <= create_date_to) count = logs.count() if desc: logs = logs.order_by(cls.model.getter_by(orderby).desc()) else: logs = logs.order_by(cls.model.getter_by(orderby).asc()) if page_number and items_per_page: logs = logs.paginate(page_number, items_per_page) return list(logs.dicts()), count @classmethod @DB.connection_context() def get_documents_info(cls, id): fields = [Document.id, Document.name, Document.progress, Document.kb_id] return ( cls.model.select(*fields) .join(Document, on=(cls.model.document_id == Document.id)) .where( cls.model.id == id ) .dicts() ) @classmethod @DB.connection_context() def get_dataset_logs_by_kb_id(cls, kb_id, page_number, items_per_page, orderby, desc, operation_status, create_date_from=None, create_date_to=None): fields = cls.get_dataset_logs_fields() logs = cls.model.select(*fields).where((cls.model.kb_id == kb_id), (cls.model.document_id == GRAPH_RAPTOR_FAKE_DOC_ID)) if operation_status: logs = logs.where(cls.model.operation_status.in_(operation_status)) if create_date_from: logs = logs.where(cls.model.create_date >= create_date_from) if create_date_to: logs = logs.where(cls.model.create_date <= create_date_to) count = logs.count() if desc: logs = logs.order_by(cls.model.getter_by(orderby).desc()) else: logs = logs.order_by(cls.model.getter_by(orderby).asc()) if page_number and items_per_page: logs = logs.paginate(page_number, items_per_page) return list(logs.dicts()), count
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/conversation_service.py
api/db/services/conversation_service.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 time from uuid import uuid4 from common.constants import StatusEnum from api.db.db_models import Conversation, DB from api.db.services.api_service import API4ConversationService from api.db.services.common_service import CommonService from api.db.services.dialog_service import DialogService, async_chat from common.misc_utils import get_uuid import json from rag.prompts.generator import chunks_format class ConversationService(CommonService): model = Conversation @classmethod @DB.connection_context() def get_list(cls, dialog_id, page_number, items_per_page, orderby, desc, id, name, user_id=None): sessions = cls.model.select().where(cls.model.dialog_id == dialog_id) if id: sessions = sessions.where(cls.model.id == id) if name: sessions = sessions.where(cls.model.name == name) if user_id: sessions = sessions.where(cls.model.user_id == user_id) if desc: sessions = sessions.order_by(cls.model.getter_by(orderby).desc()) else: sessions = sessions.order_by(cls.model.getter_by(orderby).asc()) sessions = sessions.paginate(page_number, items_per_page) return list(sessions.dicts()) @classmethod @DB.connection_context() def get_all_conversation_by_dialog_ids(cls, dialog_ids): sessions = cls.model.select().where(cls.model.dialog_id.in_(dialog_ids)) sessions.order_by(cls.model.create_time.asc()) offset, limit = 0, 100 res = [] while True: s_batch = sessions.offset(offset).limit(limit) _temp = list(s_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res def structure_answer(conv, ans, message_id, session_id): reference = ans["reference"] if not isinstance(reference, dict): reference = {} ans["reference"] = {} chunk_list = chunks_format(reference) reference["chunks"] = chunk_list ans["id"] = message_id ans["session_id"] = session_id if not conv: return ans if not conv.message: conv.message = [] if not conv.message or conv.message[-1].get("role", "") != "assistant": conv.message.append({"role": "assistant", "content": ans["answer"], "created_at": time.time(), "id": message_id}) else: conv.message[-1] = {"role": "assistant", "content": ans["answer"], "created_at": time.time(), "id": message_id} if conv.reference: conv.reference[-1] = reference return ans async def async_completion(tenant_id, chat_id, question, name="New session", session_id=None, stream=True, **kwargs): assert name, "`name` can not be empty." dia = DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value) assert dia, "You do not own the chat." if not session_id: session_id = get_uuid() conv = { "id": session_id, "dialog_id": chat_id, "name": name, "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue"), "created_at": time.time()}], "user_id": kwargs.get("user_id", "") } ConversationService.save(**conv) if stream: yield "data:" + json.dumps({"code": 0, "message": "", "data": { "answer": conv["message"][0]["content"], "reference": {}, "audio_binary": None, "id": None, "session_id": session_id }}, ensure_ascii=False) + "\n\n" yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n" return else: answer = { "answer": conv["message"][0]["content"], "reference": {}, "audio_binary": None, "id": None, "session_id": session_id } yield answer return conv = ConversationService.query(id=session_id, dialog_id=chat_id) if not conv: raise LookupError("Session does not exist") conv = conv[0] msg = [] question = { "content": question, "role": "user", "id": str(uuid4()) } conv.message.append(question) for m in conv.message: if m["role"] == "system": continue if m["role"] == "assistant" and not msg: continue msg.append(m) message_id = msg[-1].get("id") e, dia = DialogService.get_by_id(conv.dialog_id) kb_ids = kwargs.get("kb_ids",[]) dia.kb_ids = list(set(dia.kb_ids + kb_ids)) if not conv.reference: conv.reference = [] conv.message.append({"role": "assistant", "content": "", "id": message_id}) conv.reference.append({"chunks": [], "doc_aggs": []}) if stream: try: async for ans in async_chat(dia, msg, True, **kwargs): ans = structure_answer(conv, ans, message_id, session_id) yield "data:" + json.dumps({"code": 0, "data": ans}, ensure_ascii=False) + "\n\n" ConversationService.update_by_id(conv.id, conv.to_dict()) except Exception as e: yield "data:" + json.dumps({"code": 500, "message": str(e), "data": {"answer": "**ERROR**: " + str(e), "reference": []}}, ensure_ascii=False) + "\n\n" yield "data:" + json.dumps({"code": 0, "data": True}, ensure_ascii=False) + "\n\n" else: answer = None async for ans in async_chat(dia, msg, False, **kwargs): answer = structure_answer(conv, ans, message_id, session_id) ConversationService.update_by_id(conv.id, conv.to_dict()) break yield answer async def async_iframe_completion(dialog_id, question, session_id=None, stream=True, **kwargs): e, dia = DialogService.get_by_id(dialog_id) assert e, "Dialog not found" if not session_id: session_id = get_uuid() conv = { "id": session_id, "dialog_id": dialog_id, "user_id": kwargs.get("user_id", ""), "message": [{"role": "assistant", "content": dia.prompt_config["prologue"], "created_at": time.time()}] } API4ConversationService.save(**conv) yield "data:" + json.dumps({"code": 0, "message": "", "data": { "answer": conv["message"][0]["content"], "reference": {}, "audio_binary": None, "id": None, "session_id": session_id }}, ensure_ascii=False) + "\n\n" yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n" return else: session_id = session_id e, conv = API4ConversationService.get_by_id(session_id) assert e, "Session not found!" if not conv.message: conv.message = [] messages = conv.message question = { "role": "user", "content": question, "id": str(uuid4()) } messages.append(question) msg = [] for m in messages: if m["role"] == "system": continue if m["role"] == "assistant" and not msg: continue msg.append(m) if not msg[-1].get("id"): msg[-1]["id"] = get_uuid() message_id = msg[-1]["id"] if not conv.reference: conv.reference = [] conv.reference.append({"chunks": [], "doc_aggs": []}) if stream: try: async for ans in async_chat(dia, msg, True, **kwargs): ans = structure_answer(conv, ans, message_id, session_id) yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n" API4ConversationService.append_message(conv.id, conv.to_dict()) except Exception as e: yield "data:" + json.dumps({"code": 500, "message": str(e), "data": {"answer": "**ERROR**: " + str(e), "reference": []}}, ensure_ascii=False) + "\n\n" yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n" else: answer = None async for ans in async_chat(dia, msg, False, **kwargs): answer = structure_answer(conv, ans, message_id, session_id) API4ConversationService.append_message(conv.id, conv.to_dict()) break yield answer
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/langfuse_service.py
api/db/services/langfuse_service.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 datetime import datetime import peewee from api.db.db_models import DB, TenantLangfuse from api.db.services.common_service import CommonService from common.time_utils import current_timestamp, datetime_format class TenantLangfuseService(CommonService): """ All methods that modify the status should be enclosed within a DB.atomic() context to ensure atomicity and maintain data integrity in case of errors during execution. """ model = TenantLangfuse @classmethod @DB.connection_context() def filter_by_tenant(cls, tenant_id): fields = [cls.model.tenant_id, cls.model.host, cls.model.secret_key, cls.model.public_key] try: keys = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id).first() return keys except peewee.DoesNotExist: return None @classmethod @DB.connection_context() def filter_by_tenant_with_info(cls, tenant_id): fields = [cls.model.tenant_id, cls.model.host, cls.model.secret_key, cls.model.public_key] try: keys = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id).dicts().first() return keys except peewee.DoesNotExist: return None @classmethod @DB.connection_context() def delete_ty_tenant_id(cls, tenant_id): return cls.model.delete().where(cls.model.tenant_id == tenant_id).execute() @classmethod def update_by_tenant(cls, tenant_id, langfuse_keys): langfuse_keys["update_time"] = current_timestamp() langfuse_keys["update_date"] = datetime_format(datetime.now()) return cls.model.update(**langfuse_keys).where(cls.model.tenant_id == tenant_id).execute() @classmethod def save(cls, **kwargs): current_ts = current_timestamp() current_date = datetime_format(datetime.now()) kwargs["create_time"] = current_ts kwargs["create_date"] = current_date kwargs["update_time"] = current_ts kwargs["update_date"] = current_date obj = cls.model.create(**kwargs) return obj @classmethod def delete_model(cls, langfuse_model): langfuse_model.delete_instance()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/mcp_server_service.py
api/db/services/mcp_server_service.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 peewee import fn from api.db.db_models import DB, MCPServer from api.db.services.common_service import CommonService class MCPServerService(CommonService): """Service class for managing MCP server related database operations. This class extends CommonService to provide specialized functionality for MCP server management, including MCP server creation, updates, and deletions. Attributes: model: The MCPServer model class for database operations. """ model = MCPServer @classmethod @DB.connection_context() def get_servers(cls, tenant_id: str, id_list: list[str] | None, page_number, items_per_page, orderby, desc, keywords): """Retrieve all MCP servers associated with a tenant. This method fetches all MCP servers for a given tenant, ordered by creation time. It only includes fields for list display. Args: tenant_id (str): The unique identifier of the tenant. id_list (list[str]): Get servers by ID list. Will ignore this condition if None. Returns: list[dict]: List of MCP server dictionaries containing MCP server details. Returns None if no MCP servers are found. """ fields = [ cls.model.id, cls.model.name, cls.model.server_type, cls.model.url, cls.model.description, cls.model.variables, cls.model.create_date, cls.model.update_date, ] query = cls.model.select(*fields).order_by(cls.model.create_time.desc()).where(cls.model.tenant_id == tenant_id) if id_list: query = query.where(cls.model.id.in_(id_list)) if keywords: query = query.where(fn.LOWER(cls.model.name).contains(keywords.lower())) if desc: query = query.order_by(cls.model.getter_by(orderby).desc()) else: query = query.order_by(cls.model.getter_by(orderby).asc()) if page_number and items_per_page: query = query.paginate(page_number, items_per_page) servers = list(query.dicts()) if not servers: return None return servers @classmethod @DB.connection_context() def get_by_name_and_tenant(cls, name: str, tenant_id: str): try: mcp_server = cls.model.query(name=name, tenant_id=tenant_id) return bool(mcp_server), mcp_server except Exception: return False, None @classmethod @DB.connection_context() def delete_by_tenant_id(cls, tenant_id: str): return cls.model.delete().where(cls.model.tenant_id == tenant_id).execute()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/memory_service.py
api/db/services/memory_service.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 typing import List from api.db.db_models import DB, Memory, User from api.db.services import duplicate_name from api.db.services.common_service import CommonService from api.utils.memory_utils import calculate_memory_type from api.constants import MEMORY_NAME_LIMIT from common.misc_utils import get_uuid from common.time_utils import get_format_time, current_timestamp from memory.utils.prompt_util import PromptAssembler class MemoryService(CommonService): # Service class for manage memory operations model = Memory @classmethod @DB.connection_context() def get_by_memory_id(cls, memory_id: str): return cls.model.select().where(cls.model.id == memory_id).first() @classmethod @DB.connection_context() def get_by_tenant_id(cls, tenant_id: str): return cls.model.select().where(cls.model.tenant_id == tenant_id) @classmethod @DB.connection_context() def get_all_memory(cls): memory_list = cls.model.select() return list(memory_list) @classmethod @DB.connection_context() def get_with_owner_name_by_id(cls, memory_id: str): fields = [ cls.model.id, cls.model.name, cls.model.avatar, cls.model.tenant_id, User.nickname.alias("owner_name"), cls.model.memory_type, cls.model.storage_type, cls.model.embd_id, cls.model.llm_id, cls.model.permissions, cls.model.description, cls.model.memory_size, cls.model.forgetting_policy, cls.model.temperature, cls.model.system_prompt, cls.model.user_prompt, cls.model.create_date, cls.model.create_time ] memory = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where( cls.model.id == memory_id ).first() return memory @classmethod @DB.connection_context() def get_by_filter(cls, filter_dict: dict, keywords: str, page: int = 1, page_size: int = 50): fields = [ cls.model.id, cls.model.name, cls.model.avatar, cls.model.tenant_id, User.nickname.alias("owner_name"), cls.model.memory_type, cls.model.storage_type, cls.model.permissions, cls.model.description, cls.model.create_time, cls.model.create_date ] memories = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)) if filter_dict.get("tenant_id"): memories = memories.where(cls.model.tenant_id.in_(filter_dict["tenant_id"])) if filter_dict.get("memory_type"): memory_type_int = calculate_memory_type(filter_dict["memory_type"]) memories = memories.where(cls.model.memory_type.bin_and(memory_type_int) > 0) if filter_dict.get("storage_type"): memories = memories.where(cls.model.storage_type == filter_dict["storage_type"]) if keywords: memories = memories.where(cls.model.name.contains(keywords)) count = memories.count() memories = memories.order_by(cls.model.update_time.desc()) memories = memories.paginate(page, page_size) return list(memories.dicts()), count @classmethod @DB.connection_context() def create_memory(cls, tenant_id: str, name: str, memory_type: List[str], embd_id: str, llm_id: str): # Deduplicate name within tenant memory_name = duplicate_name( cls.query, name=name, tenant_id=tenant_id ) if len(memory_name) > MEMORY_NAME_LIMIT: return False, f"Memory name {memory_name} exceeds limit of {MEMORY_NAME_LIMIT}." timestamp = current_timestamp() format_time = get_format_time() # build create dict memory_info = { "id": get_uuid(), "name": memory_name, "memory_type": calculate_memory_type(memory_type), "tenant_id": tenant_id, "embd_id": embd_id, "llm_id": llm_id, "system_prompt": PromptAssembler.assemble_system_prompt({"memory_type": memory_type}), "create_time": timestamp, "create_date": format_time, "update_time": timestamp, "update_date": format_time, } obj = cls.model(**memory_info).save(force_insert=True) if not obj: return False, "Could not create new memory." db_row = cls.model.select().where(cls.model.id == memory_info["id"]).first() return obj, db_row @classmethod @DB.connection_context() def update_memory(cls, tenant_id: str, memory_id: str, update_dict: dict): if not update_dict: return 0 if "temperature" in update_dict and isinstance(update_dict["temperature"], str): update_dict["temperature"] = float(update_dict["temperature"]) if "memory_type" in update_dict and isinstance(update_dict["memory_type"], list): update_dict["memory_type"] = calculate_memory_type(update_dict["memory_type"]) if "name" in update_dict: update_dict["name"] = duplicate_name( cls.query, name=update_dict["name"], tenant_id=tenant_id ) update_dict.update({ "update_time": current_timestamp(), "update_date": get_format_time() }) return cls.model.update(update_dict).where(cls.model.id == memory_id).execute() @classmethod @DB.connection_context() def delete_memory(cls, memory_id: str): return cls.model.delete().where(cls.model.id == memory_id).execute()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/system_settings_service.py
api/db/services/system_settings_service.py
# # Copyright 2026 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from datetime import datetime from common.time_utils import current_timestamp, datetime_format from api.db.db_models import DB from api.db.db_models import SystemSettings from api.db.services.common_service import CommonService class SystemSettingsService(CommonService): model = SystemSettings @classmethod @DB.connection_context() def get_by_name(cls, name): objs = cls.model.select().where(cls.model.name.startswith(name)) return objs @classmethod @DB.connection_context() def update_by_name(cls, name, obj): obj["update_time"] = current_timestamp() obj["update_date"] = datetime_format(datetime.now()) cls.model.update(obj).where(cls.model.name.startswith(name)).execute() return SystemSettings(**obj) @classmethod @DB.connection_context() def get_record_count(cls): count = cls.model.select().count() return count
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/task_service.py
api/db/services/task_service.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 random import xxhash from datetime import datetime from api.db.db_utils import bulk_insert_into_db from deepdoc.parser import PdfParser from peewee import JOIN from api.db.db_models import DB, File2Document, File from api.db import FileType from api.db.db_models import Task, Document, Knowledgebase, Tenant from api.db.services.common_service import CommonService from api.db.services.document_service import DocumentService from common.misc_utils import get_uuid from common.time_utils import current_timestamp from common.constants import StatusEnum, TaskStatus from deepdoc.parser.excel_parser import RAGFlowExcelParser from rag.utils.redis_conn import REDIS_CONN from common import settings from rag.nlp import search CANVAS_DEBUG_DOC_ID = "dataflow_x" GRAPH_RAPTOR_FAKE_DOC_ID = "graph_raptor_x" def trim_header_by_lines(text: str, max_length) -> str: # Trim header text to maximum length while preserving line breaks # Args: # text: Input text to trim # max_length: Maximum allowed length # Returns: # Trimmed text len_text = len(text) if len_text <= max_length: return text for i in range(len_text): if text[i] == '\n' and len_text - i <= max_length: return text[i + 1:] return text class TaskService(CommonService): """Service class for managing document processing tasks. This class extends CommonService to provide specialized functionality for document processing task management, including task creation, progress tracking, and chunk management. It handles various document types (PDF, Excel, etc.) and manages their processing lifecycle. The class implements a robust task queue system with retry mechanisms and progress tracking, supporting both synchronous and asynchronous task execution. Attributes: model: The Task model class for database operations. """ model = Task @classmethod @DB.connection_context() def get_task(cls, task_id, doc_ids=[]): """Retrieve detailed task information by task ID. This method fetches comprehensive task details including associated document, dataset, and tenant information. It also handles task retry logic and progress updates. Args: task_id (str): The unique identifier of the task to retrieve. Returns: dict: Task details dictionary containing all task information and related metadata. Returns None if task is not found or has exceeded retry limit. """ doc_id = cls.model.doc_id if doc_id == CANVAS_DEBUG_DOC_ID and doc_ids: doc_id = doc_ids[0] fields = [ cls.model.id, cls.model.doc_id, cls.model.from_page, cls.model.to_page, cls.model.retry_count, Document.kb_id, Document.parser_id, Document.parser_config, Document.name, Document.type, Document.location, Document.size, Knowledgebase.tenant_id, Knowledgebase.language, Knowledgebase.embd_id, Knowledgebase.pagerank, Knowledgebase.parser_config.alias("kb_parser_config"), Tenant.img2txt_id, Tenant.asr_id, Tenant.llm_id, cls.model.update_time, ] docs = ( cls.model.select(*fields) .join(Document, on=(doc_id == Document.id)) .join(Knowledgebase, on=(Document.kb_id == Knowledgebase.id)) .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id)) .where(cls.model.id == task_id) ) docs = list(docs.dicts()) # Assuming docs = list(docs.dicts()) if docs: kb_config = docs[0]['kb_parser_config'] # Dict from Knowledgebase.parser_config mineru_method = kb_config.get('mineru_parse_method', 'auto') mineru_formula = kb_config.get('mineru_formula_enable', True) mineru_table = kb_config.get('mineru_table_enable', True) print(mineru_method, mineru_formula, mineru_table) if not docs: return None msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task has been received." prog = random.random() / 10.0 if docs[0]["retry_count"] >= 3: msg = "\nERROR: Task is abandoned after 3 times attempts." prog = -1 cls.model.update( progress_msg=cls.model.progress_msg + msg, progress=prog, retry_count=docs[0]["retry_count"] + 1, ).where(cls.model.id == docs[0]["id"]).execute() if docs[0]["retry_count"] >= 3: return None return docs[0] @classmethod @DB.connection_context() def get_tasks(cls, doc_id: str): """Retrieve all tasks associated with a document. This method fetches all processing tasks for a given document, ordered by page number and creation time. It includes task progress and chunk information. Args: doc_id (str): The unique identifier of the document. Returns: list[dict]: List of task dictionaries containing task details. Returns None if no tasks are found. """ fields = [ cls.model.id, cls.model.from_page, cls.model.progress, cls.model.digest, cls.model.chunk_ids, ] tasks = ( cls.model.select(*fields).order_by(cls.model.from_page.asc(), cls.model.create_time.desc()) .where(cls.model.doc_id == doc_id) ) tasks = list(tasks.dicts()) if not tasks: return None return tasks @classmethod @DB.connection_context() def update_chunk_ids(cls, id: str, chunk_ids: str): """Update the chunk IDs associated with a task. This method updates the chunk_ids field of a task, which stores the IDs of processed document chunks in a space-separated string format. Args: id (str): The unique identifier of the task. chunk_ids (str): Space-separated string of chunk identifiers. """ cls.model.update(chunk_ids=chunk_ids).where(cls.model.id == id).execute() @classmethod @DB.connection_context() def get_ongoing_doc_name(cls): """Get names of documents that are currently being processed. This method retrieves information about documents that are in the processing state, including their locations and associated IDs. It uses database locking to ensure thread safety when accessing the task information. Returns: list[tuple]: A list of tuples, each containing (parent_id/kb_id, location) for documents currently being processed. Returns empty list if no documents are being processed. """ with DB.lock("get_task", -1): docs = ( cls.model.select( *[Document.id, Document.kb_id, Document.location, File.parent_id] ) .join(Document, on=(cls.model.doc_id == Document.id)) .join( File2Document, on=(File2Document.document_id == Document.id), join_type=JOIN.LEFT_OUTER, ) .join( File, on=(File2Document.file_id == File.id), join_type=JOIN.LEFT_OUTER, ) .where( Document.status == StatusEnum.VALID.value, Document.run == TaskStatus.RUNNING.value, ~(Document.type == FileType.VIRTUAL.value), cls.model.progress < 1, cls.model.create_time >= current_timestamp() - 1000 * 600, ) ) docs = list(docs.dicts()) if not docs: return [] return list( set( [ ( d["parent_id"] if d["parent_id"] else d["kb_id"], d["location"], ) for d in docs ] ) ) @classmethod @DB.connection_context() def do_cancel(cls, id): """Check if a task should be cancelled based on its document status. This method determines whether a task should be cancelled by checking the associated document's run status and progress. A task should be cancelled if its document is marked for cancellation or has negative progress. Args: id (str): The unique identifier of the task to check. Returns: bool: True if the task should be cancelled, False otherwise. """ task = cls.model.get_by_id(id) _, doc = DocumentService.get_by_id(task.doc_id) return doc.run == TaskStatus.CANCEL.value or doc.progress < 0 @classmethod @DB.connection_context() def update_progress(cls, id, info): """Update the progress information for a task. This method updates both the progress message and completion percentage of a task. It handles platform-specific behavior (macOS vs others) and uses database locking when necessary to ensure thread safety. Update Rules: - progress_msg: Always appends the new message to the existing one, and trims the result to max 3000 lines. - progress: Only updates if the current progress is not -1 AND (the new progress is -1 OR greater than the existing progress), to avoid overwriting valid progress with invalid or regressive values. Args: id (str): The unique identifier of the task to update. info (dict): Dictionary containing progress information with keys: - progress_msg (str, optional): Progress message to append - progress (float, optional): Progress percentage (0.0 to 1.0) """ task = cls.model.get_by_id(id) if not task: logging.warning("Update_progress error: task not found") return if os.environ.get("MACOS"): if info["progress_msg"]: progress_msg = trim_header_by_lines(task.progress_msg + "\n" + info["progress_msg"], 3000) cls.model.update(progress_msg=progress_msg).where(cls.model.id == id).execute() if "progress" in info: prog = info["progress"] cls.model.update(progress=prog).where( (cls.model.id == id) & ( (cls.model.progress != -1) & ((prog == -1) | (prog > cls.model.progress)) ) ).execute() else: with DB.lock("update_progress", -1): if info["progress_msg"]: progress_msg = trim_header_by_lines(task.progress_msg + "\n" + info["progress_msg"], 3000) cls.model.update(progress_msg=progress_msg).where(cls.model.id == id).execute() if "progress" in info: prog = info["progress"] cls.model.update(progress=prog).where( (cls.model.id == id) & ( (cls.model.progress != -1) & ((prog == -1) | (prog > cls.model.progress)) ) ).execute() process_duration = (datetime.now() - task.begin_at).total_seconds() cls.model.update(process_duration=process_duration).where(cls.model.id == id).execute() @classmethod @DB.connection_context() def delete_by_doc_ids(cls, doc_ids): """Delete task associated with a document.""" return cls.model.delete().where(cls.model.doc_id.in_(doc_ids)).execute() def queue_tasks(doc: dict, bucket: str, name: str, priority: int): """Create and queue document processing tasks. This function creates processing tasks for a document based on its type and configuration. It handles different document types (PDF, Excel, etc.) differently and manages task chunking and configuration. It also implements task reuse optimization by checking for previously completed tasks. Args: doc (dict): Document dictionary containing metadata and configuration. bucket (str): Storage bucket name where the document is stored. name (str): File name of the document. priority (int, optional): Priority level for task queueing (default is 0). Note: - For PDF documents, tasks are created per page range based on configuration - For Excel documents, tasks are created per row range - Task digests are calculated for optimization and reuse - Previous task chunks may be reused if available """ def new_task(): return { "id": get_uuid(), "doc_id": doc["id"], "progress": 0.0, "from_page": 0, "to_page": 100000000, "begin_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } parse_task_array = [] if doc["type"] == FileType.PDF.value: file_bin = settings.STORAGE_IMPL.get(bucket, name) do_layout = doc["parser_config"].get("layout_recognize", "DeepDOC") pages = PdfParser.total_page_number(doc["name"], file_bin) if pages is None: pages = 0 page_size = doc["parser_config"].get("task_page_size") or 12 if doc["parser_id"] == "paper": page_size = doc["parser_config"].get("task_page_size") or 22 if doc["parser_id"] in ["one", "knowledge_graph"] or do_layout != "DeepDOC" or doc["parser_config"].get("toc_extraction", False): page_size = 10 ** 9 page_ranges = doc["parser_config"].get("pages") or [(1, 10 ** 5)] for s, e in page_ranges: s -= 1 s = max(0, s) e = min(e - 1, pages) for p in range(s, e, page_size): task = new_task() task["from_page"] = p task["to_page"] = min(p + page_size, e) parse_task_array.append(task) elif doc["parser_id"] == "table": file_bin = settings.STORAGE_IMPL.get(bucket, name) rn = RAGFlowExcelParser.row_number(doc["name"], file_bin) for i in range(0, rn, 3000): task = new_task() task["from_page"] = i task["to_page"] = min(i + 3000, rn) parse_task_array.append(task) else: parse_task_array.append(new_task()) chunking_config = DocumentService.get_chunking_config(doc["id"]) for task in parse_task_array: hasher = xxhash.xxh64() for field in sorted(chunking_config.keys()): if field == "parser_config": for k in ["raptor", "graphrag"]: if k in chunking_config[field]: del chunking_config[field][k] hasher.update(str(chunking_config[field]).encode("utf-8")) for field in ["doc_id", "from_page", "to_page"]: hasher.update(str(task.get(field, "")).encode("utf-8")) task_digest = hasher.hexdigest() task["digest"] = task_digest task["progress"] = 0.0 task["priority"] = priority prev_tasks = TaskService.get_tasks(doc["id"]) ck_num = 0 if prev_tasks: for task in parse_task_array: ck_num += reuse_prev_task_chunks(task, prev_tasks, chunking_config) TaskService.filter_delete([Task.doc_id == doc["id"]]) pre_chunk_ids = [] for pre_task in prev_tasks: if pre_task["chunk_ids"]: pre_chunk_ids.extend(pre_task["chunk_ids"].split()) if pre_chunk_ids: settings.docStoreConn.delete({"id": pre_chunk_ids}, search.index_name(chunking_config["tenant_id"]), chunking_config["kb_id"]) DocumentService.update_by_id(doc["id"], {"chunk_num": ck_num}) bulk_insert_into_db(Task, parse_task_array, True) DocumentService.begin2parse(doc["id"]) unfinished_task_array = [task for task in parse_task_array if task["progress"] < 1.0] for unfinished_task in unfinished_task_array: assert REDIS_CONN.queue_product( settings.get_svr_queue_name(priority), message=unfinished_task ), "Can't access Redis. Please check the Redis' status." def reuse_prev_task_chunks(task: dict, prev_tasks: list[dict], chunking_config: dict): """Attempt to reuse chunks from previous tasks for optimization. This function checks if chunks from previously completed tasks can be reused for the current task, which can significantly improve processing efficiency. It matches tasks based on page ranges and configuration digests. Args: task (dict): Current task dictionary to potentially reuse chunks for. prev_tasks (list[dict]): List of previous task dictionaries to check for reuse. chunking_config (dict): Configuration dictionary for chunk processing. Returns: int: Number of chunks successfully reused. Returns 0 if no chunks could be reused. Note: Chunks can only be reused if: - A previous task exists with matching page range and configuration digest - The previous task was completed successfully (progress = 1.0) - The previous task has valid chunk IDs """ idx = 0 while idx < len(prev_tasks): prev_task = prev_tasks[idx] if prev_task.get("from_page", 0) == task.get("from_page", 0) \ and prev_task.get("digest", 0) == task.get("digest", ""): break idx += 1 if idx >= len(prev_tasks): return 0 prev_task = prev_tasks[idx] if prev_task["progress"] < 1.0 or not prev_task["chunk_ids"]: return 0 task["chunk_ids"] = prev_task["chunk_ids"] task["progress"] = 1.0 if "from_page" in task and "to_page" in task and int(task['to_page']) - int(task['from_page']) >= 10 ** 6: task["progress_msg"] = f"Page({task['from_page']}~{task['to_page']}): " else: task["progress_msg"] = "" task["progress_msg"] = " ".join( [datetime.now().strftime("%H:%M:%S"), task["progress_msg"], "Reused previous task's chunks."]) prev_task["chunk_ids"] = "" return len(task["chunk_ids"].split()) def cancel_all_task_of(doc_id): for t in TaskService.query(doc_id=doc_id): try: REDIS_CONN.set(f"{t.id}-cancel", "x") except Exception as e: logging.exception(e) def has_canceled(task_id): try: if REDIS_CONN.get(f"{task_id}-cancel"): return True except Exception as e: logging.exception(e) return False def queue_dataflow(tenant_id:str, flow_id:str, task_id:str, doc_id:str=CANVAS_DEBUG_DOC_ID, file:dict=None, priority: int=0, rerun:bool=False) -> tuple[bool, str]: task = dict( id=task_id, doc_id=doc_id, from_page=0, to_page=100000000, task_type="dataflow" if not rerun else "dataflow_rerun", priority=priority, begin_at= datetime.now().strftime("%Y-%m-%d %H:%M:%S"), ) if doc_id not in [CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID]: TaskService.model.delete().where(TaskService.model.doc_id == doc_id).execute() DocumentService.begin2parse(doc_id) bulk_insert_into_db(model=Task, data_source=[task], replace_on_conflict=True) task["kb_id"] = DocumentService.get_knowledgebase_id(doc_id) task["tenant_id"] = tenant_id task["dataflow_id"] = flow_id task["file"] = file if not REDIS_CONN.queue_product( settings.get_svr_queue_name(priority), message=task ): return False, "Can't access Redis. Please check the Redis' status." return True, ""
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/common_service.py
api/db/services/common_service.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 datetime import datetime from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type import peewee from peewee import InterfaceError, OperationalError from api.db.db_models import DB from common.misc_utils import get_uuid from common.time_utils import current_timestamp, datetime_format def retry_db_operation(func): @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=5), retry=retry_if_exception_type((InterfaceError, OperationalError)), before_sleep=lambda retry_state: print(f"RETRY {retry_state.attempt_number} TIMES"), reraise=True, ) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper class CommonService: """Base service class that provides common database operations. This class serves as a foundation for all service classes in the application, implementing standard CRUD operations and common database query patterns. It uses the Peewee ORM for database interactions and provides a consistent interface for database operations across all derived service classes. Attributes: model: The Peewee model class that this service operates on. Must be set by subclasses. """ model = None @classmethod @DB.connection_context() def query(cls, cols=None, reverse=None, order_by=None, **kwargs): """Execute a database query with optional column selection and ordering. This method provides a flexible way to query the database with various filters and sorting options. It supports column selection, sort order control, and additional filter conditions. Args: cols (list, optional): List of column names to select. If None, selects all columns. reverse (bool, optional): If True, sorts in descending order. If False, sorts in ascending order. order_by (str, optional): Column name to sort results by. **kwargs: Additional filter conditions passed as keyword arguments. Returns: peewee.ModelSelect: A query result containing matching records. """ return cls.model.query(cols=cols, reverse=reverse, order_by=order_by, **kwargs) @classmethod @DB.connection_context() def get_all(cls, cols=None, reverse=None, order_by=None): """Retrieve all records from the database with optional column selection and ordering. This method fetches all records from the model's table with support for column selection and result ordering. If no order_by is specified and reverse is True, it defaults to ordering by create_time. Args: cols (list, optional): List of column names to select. If None, selects all columns. reverse (bool, optional): If True, sorts in descending order. If False, sorts in ascending order. order_by (str, optional): Column name to sort results by. Defaults to 'create_time' if reverse is specified. Returns: peewee.ModelSelect: A query containing all matching records. """ if cols: query_records = cls.model.select(*cols) else: query_records = cls.model.select() if reverse is not None: if not order_by or not hasattr(cls.model, order_by): order_by = "create_time" if reverse is True: query_records = query_records.order_by(cls.model.getter_by(order_by).desc()) elif reverse is False: query_records = query_records.order_by(cls.model.getter_by(order_by).asc()) return query_records @classmethod @DB.connection_context() def get(cls, **kwargs): """Get a single record matching the given criteria. This method retrieves a single record from the database that matches the specified filter conditions. Args: **kwargs: Filter conditions as keyword arguments. Returns: Model instance: Single matching record. Raises: peewee.DoesNotExist: If no matching record is found. """ return cls.model.get(**kwargs) @classmethod @DB.connection_context() def get_or_none(cls, **kwargs): """Get a single record or None if not found. This method attempts to retrieve a single record matching the given criteria, returning None if no match is found instead of raising an exception. Args: **kwargs: Filter conditions as keyword arguments. Returns: Model instance or None: Matching record if found, None otherwise. """ try: return cls.model.get(**kwargs) except peewee.DoesNotExist: return None @classmethod @DB.connection_context() def save(cls, **kwargs): """Save a new record to database. This method creates a new record in the database with the provided field values, forcing an insert operation rather than an update. Args: **kwargs: Record field values as keyword arguments. Returns: Model instance: The created record object. """ sample_obj = cls.model(**kwargs).save(force_insert=True) return sample_obj @classmethod @DB.connection_context() def insert(cls, **kwargs): """Insert a new record with automatic ID and timestamps. This method creates a new record with automatically generated ID and timestamp fields. It handles the creation of create_time, create_date, update_time, and update_date fields. Args: **kwargs: Record field values as keyword arguments. Returns: Model instance: The newly created record object. """ if "id" not in kwargs: kwargs["id"] = get_uuid() timestamp = current_timestamp() cur_datetime = datetime_format(datetime.now()) kwargs["create_time"] = timestamp kwargs["create_date"] = cur_datetime kwargs["update_time"] = timestamp kwargs["update_date"] = cur_datetime sample_obj = cls.model(**kwargs).save(force_insert=True) return sample_obj @classmethod @DB.connection_context() def insert_many(cls, data_list, batch_size=100): """Insert multiple records in batches. This method efficiently inserts multiple records into the database using batch processing. It automatically sets creation timestamps for all records. Args: data_list (list): List of dictionaries containing record data to insert. batch_size (int, optional): Number of records to insert in each batch. Defaults to 100. """ current_ts = current_timestamp() current_datetime = datetime_format(datetime.now()) with DB.atomic(): for d in data_list: d["create_time"] = current_ts d["create_date"] = current_datetime d["update_time"] = current_ts d["update_date"] = current_datetime for i in range(0, len(data_list), batch_size): cls.model.insert_many(data_list[i : i + batch_size]).execute() @classmethod @DB.connection_context() def update_many_by_id(cls, data_list): """Update multiple records by their IDs. This method updates multiple records in the database, identified by their IDs. It automatically updates the update_time and update_date fields for each record. Args: data_list (list): List of dictionaries containing record data to update. Each dictionary must include an 'id' field. """ timestamp = current_timestamp() cur_datetime = datetime_format(datetime.now()) for data in data_list: data["update_time"] = timestamp data["update_date"] = cur_datetime with DB.atomic(): for data in data_list: cls.model.update(data).where(cls.model.id == data["id"]).execute() @classmethod @DB.connection_context() @retry_db_operation def update_by_id(cls, pid, data): # Update a single record by ID # Args: # pid: Record ID # data: Updated field values # Returns: # Number of records updated data["update_time"] = current_timestamp() data["update_date"] = datetime_format(datetime.now()) num = cls.model.update(data).where(cls.model.id == pid).execute() return num @classmethod @DB.connection_context() def get_by_id(cls, pid): # Get a record by ID # Args: # pid: Record ID # Returns: # Tuple of (success, record) try: obj = cls.model.get_or_none(cls.model.id == pid) if obj: return True, obj except Exception: pass return False, None @classmethod @DB.connection_context() def get_by_ids(cls, pids, cols=None): # Get multiple records by their IDs # Args: # pids: List of record IDs # cols: List of columns to select # Returns: # Query of matching records if cols: objs = cls.model.select(*cols) else: objs = cls.model.select() return objs.where(cls.model.id.in_(pids)) @classmethod @DB.connection_context() def delete_by_id(cls, pid): # Delete a record by ID # Args: # pid: Record ID # Returns: # Number of records deleted return cls.model.delete().where(cls.model.id == pid).execute() @classmethod @DB.connection_context() def delete_by_ids(cls, pids): # Delete multiple records by their IDs # Args: # pids: List of record IDs # Returns: # Number of records deleted with DB.atomic(): res = cls.model.delete().where(cls.model.id.in_(pids)).execute() return res @classmethod @DB.connection_context() def filter_delete(cls, filters): # Delete records matching given filters # Args: # filters: List of filter conditions # Returns: # Number of records deleted with DB.atomic(): num = cls.model.delete().where(*filters).execute() return num @classmethod @DB.connection_context() def filter_update(cls, filters, update_data): # Update records matching given filters # Args: # filters: List of filter conditions # update_data: Updated field values # Returns: # Number of records updated with DB.atomic(): return cls.model.update(update_data).where(*filters).execute() @staticmethod def cut_list(tar_list, n): # Split a list into chunks of size n # Args: # tar_list: List to split # n: Chunk size # Returns: # List of tuples containing chunks length = len(tar_list) arr = range(length) result = [tuple(tar_list[x : (x + n)]) for x in arr[::n]] return result @classmethod @DB.connection_context() def filter_scope_list(cls, in_key, in_filters_list, filters=None, cols=None): # Get records matching IN clause filters with optional column selection # Args: # in_key: Field name for IN clause # in_filters_list: List of values for IN clause # filters: Additional filter conditions # cols: List of columns to select # Returns: # List of matching records in_filters_tuple_list = cls.cut_list(in_filters_list, 20) if not filters: filters = [] res_list = [] if cols: for i in in_filters_tuple_list: query_records = cls.model.select(*cols).where(getattr(cls.model, in_key).in_(i), *filters) if query_records: res_list.extend([query_record for query_record in query_records]) else: for i in in_filters_tuple_list: query_records = cls.model.select().where(getattr(cls.model, in_key).in_(i), *filters) if query_records: res_list.extend([query_record for query_record in query_records]) return res_list
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/__init__.py
api/db/services/__init__.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 re from pathlib import PurePath from .user_service import UserService as UserService def _split_name_counter(filename: str) -> tuple[str, int | None]: """ Splits a filename into main part and counter (if present in parentheses). Args: filename: Input filename string to be parsed Returns: A tuple containing: - The main filename part (string) - The counter from parentheses (integer) or None if no counter exists """ pattern = re.compile(r"^(.*?)\((\d+)\)$") match = pattern.search(filename) if match: main_part = match.group(1).rstrip() bracket_part = match.group(2) return main_part, int(bracket_part) return filename, None def duplicate_name(query_func, **kwargs) -> str: """ Generates a unique filename by appending/incrementing a counter when duplicates exist. Continuously checks for name availability using the provided query function, automatically appending (1), (2), etc. until finding an available name or reaching maximum retries. Args: query_func: Callable that accepts keyword arguments and returns: - True if name exists (should be modified) - False if name is available **kwargs: Must contain 'name' key with original filename to check Returns: str: Available filename, either: - Original name (if available) - Modified name with counter (e.g., "file(1).txt") Raises: KeyError: If 'name' key not provided in kwargs RuntimeError: If unable to generate unique name after maximum retries Example: >>> def name_exists(name): return name in existing_files >>> duplicate_name(name_exists, name="document.pdf") 'document(1).pdf' # If original exists """ MAX_RETRIES = 1000 if "name" not in kwargs: raise KeyError("Arguments must contain 'name' key") original_name = kwargs["name"] current_name = original_name retries = 0 while retries < MAX_RETRIES: if not query_func(**kwargs): return current_name path = PurePath(current_name) stem = path.stem suffix = path.suffix main_part, counter = _split_name_counter(stem) counter = counter + 1 if counter else 1 new_name = f"{main_part}({counter}){suffix}" kwargs["name"] = new_name current_name = new_name retries += 1 raise RuntimeError(f"Failed to generate unique name within {MAX_RETRIES} attempts. Original: {original_name}")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/api_service.py
api/db/services/api_service.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 datetime import datetime import peewee from api.db.db_models import DB, API4Conversation, APIToken, Dialog from api.db.services.common_service import CommonService from common.time_utils import current_timestamp, datetime_format class APITokenService(CommonService): model = APIToken @classmethod @DB.connection_context() def used(cls, token): return cls.model.update({ "update_time": current_timestamp(), "update_date": datetime_format(datetime.now()), }).where( cls.model.token == token ) @classmethod @DB.connection_context() def delete_by_tenant_id(cls, tenant_id): return cls.model.delete().where(cls.model.tenant_id == tenant_id).execute() class API4ConversationService(CommonService): model = API4Conversation @classmethod @DB.connection_context() def get_list(cls, dialog_id, tenant_id, page_number, items_per_page, orderby, desc, id, user_id=None, include_dsl=True, keywords="", from_date=None, to_date=None ): if include_dsl: sessions = cls.model.select().where(cls.model.dialog_id == dialog_id) else: fields = [field for field in cls.model._meta.fields.values() if field.name != 'dsl'] sessions = cls.model.select(*fields).where(cls.model.dialog_id == dialog_id) if id: sessions = sessions.where(cls.model.id == id) if user_id: sessions = sessions.where(cls.model.user_id == user_id) if keywords: sessions = sessions.where(peewee.fn.LOWER(cls.model.message).contains(keywords.lower())) if from_date: sessions = sessions.where(cls.model.create_date >= from_date) if to_date: sessions = sessions.where(cls.model.create_date <= to_date) if desc: sessions = sessions.order_by(cls.model.getter_by(orderby).desc()) else: sessions = sessions.order_by(cls.model.getter_by(orderby).asc()) count = sessions.count() sessions = sessions.paginate(page_number, items_per_page) return count, list(sessions.dicts()) @classmethod @DB.connection_context() def append_message(cls, id, conversation): cls.update_by_id(id, conversation) return cls.model.update(round=cls.model.round + 1).where(cls.model.id == id).execute() @classmethod @DB.connection_context() def stats(cls, tenant_id, from_date, to_date, source=None): if len(to_date) == 10: to_date += " 23:59:59" return cls.model.select( cls.model.create_date.truncate("day").alias("dt"), peewee.fn.COUNT( cls.model.id).alias("pv"), peewee.fn.COUNT( cls.model.user_id.distinct()).alias("uv"), peewee.fn.SUM( cls.model.tokens).alias("tokens"), peewee.fn.SUM( cls.model.duration).alias("duration"), peewee.fn.AVG( cls.model.round).alias("round"), peewee.fn.SUM( cls.model.thumb_up).alias("thumb_up") ).join(Dialog, on=((cls.model.dialog_id == Dialog.id) & (Dialog.tenant_id == tenant_id))).where( cls.model.create_date >= from_date, cls.model.create_date <= to_date, cls.model.source == source ).group_by(cls.model.create_date.truncate("day")).dicts() @classmethod @DB.connection_context() def delete_by_dialog_ids(cls, dialog_ids): return cls.model.delete().where(cls.model.dialog_id.in_(dialog_ids)).execute()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/file_service.py
api/db/services/file_service.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 logging import re import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Union from peewee import fn from api.db import KNOWLEDGEBASE_FOLDER_NAME, FileType from api.db.db_models import DB, Document, File, File2Document, Knowledgebase, Task from api.db.services import duplicate_name from api.db.services.common_service import CommonService from api.db.services.document_service import DocumentService from api.db.services.file2document_service import File2DocumentService from common.misc_utils import get_uuid from common.constants import TaskStatus, FileSource, ParserType from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.task_service import TaskService from api.utils.file_utils import filename_type, read_potential_broken_pdf, thumbnail_img, sanitize_path from rag.llm.cv_model import GptV4 from common import settings class FileService(CommonService): # Service class for managing file operations and storage model = File @classmethod @DB.connection_context() def get_by_pf_id(cls, tenant_id, pf_id, page_number, items_per_page, orderby, desc, keywords): # Get files by parent folder ID with pagination and filtering # Args: # tenant_id: ID of the tenant # pf_id: Parent folder ID # page_number: Page number for pagination # items_per_page: Number of items per page # orderby: Field to order by # desc: Boolean indicating descending order # keywords: Search keywords # Returns: # Tuple of (file_list, total_count) if keywords: files = cls.model.select().where((cls.model.tenant_id == tenant_id), (cls.model.parent_id == pf_id), (fn.LOWER(cls.model.name).contains(keywords.lower())), ~(cls.model.id == pf_id)) else: files = cls.model.select().where((cls.model.tenant_id == tenant_id), (cls.model.parent_id == pf_id), ~(cls.model.id == pf_id)) count = files.count() if desc: files = files.order_by(cls.model.getter_by(orderby).desc()) else: files = files.order_by(cls.model.getter_by(orderby).asc()) files = files.paginate(page_number, items_per_page) res_files = list(files.dicts()) for file in res_files: if file["type"] == FileType.FOLDER.value: file["size"] = cls.get_folder_size(file["id"]) file["kbs_info"] = [] children = list( cls.model.select() .where( (cls.model.tenant_id == tenant_id), (cls.model.parent_id == file["id"]), ~(cls.model.id == file["id"]), ) .dicts() ) file["has_child_folder"] = any(value["type"] == FileType.FOLDER.value for value in children) continue kbs_info = cls.get_kb_id_by_file_id(file["id"]) file["kbs_info"] = kbs_info return res_files, count @classmethod @DB.connection_context() def get_kb_id_by_file_id(cls, file_id): # Get dataset IDs associated with a file # Args: # file_id: File ID # Returns: # List of dictionaries containing dataset IDs and names kbs = ( cls.model.select(*[Knowledgebase.id, Knowledgebase.name, File2Document.document_id]) .join(File2Document, on=(File2Document.file_id == file_id)) .join(Document, on=(File2Document.document_id == Document.id)) .join(Knowledgebase, on=(Knowledgebase.id == Document.kb_id)) .where(cls.model.id == file_id) ) if not kbs: return [] kbs_info_list = [] for kb in list(kbs.dicts()): kbs_info_list.append({"kb_id": kb["id"], "kb_name": kb["name"], "document_id": kb["document_id"]}) return kbs_info_list @classmethod @DB.connection_context() def get_by_pf_id_name(cls, id, name): # Get file by parent folder ID and name # Args: # id: Parent folder ID # name: File name # Returns: # File object or None if not found file = cls.model.select().where((cls.model.parent_id == id) & (cls.model.name == name)) if file.count(): e, file = cls.get_by_id(file[0].id) if not e: raise RuntimeError("Database error (File retrieval)!") return file return None @classmethod @DB.connection_context() def get_id_list_by_id(cls, id, name, count, res): # Recursively get list of file IDs by traversing folder structure # Args: # id: Starting folder ID # name: List of folder names to traverse # count: Current depth in traversal # res: List to store results # Returns: # List of file IDs if count < len(name): file = cls.get_by_pf_id_name(id, name[count]) if file: res.append(file.id) return cls.get_id_list_by_id(file.id, name, count + 1, res) else: return res else: return res @classmethod @DB.connection_context() def get_all_innermost_file_ids(cls, folder_id, result_ids): # Get IDs of all files in the deepest level of folders # Args: # folder_id: Starting folder ID # result_ids: List to store results # Returns: # List of file IDs subfolders = cls.model.select().where(cls.model.parent_id == folder_id) if subfolders.exists(): for subfolder in subfolders: cls.get_all_innermost_file_ids(subfolder.id, result_ids) else: result_ids.append(folder_id) return result_ids @classmethod @DB.connection_context() def get_all_file_ids_by_tenant_id(cls, tenant_id): fields = [cls.model.id] files = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id) files.order_by(cls.model.create_time.asc()) offset, limit = 0, 100 res = [] while True: file_batch = files.offset(offset).limit(limit) _temp = list(file_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res @classmethod @DB.connection_context() def create_folder(cls, file, parent_id, name, count): from api.apps import current_user # Recursively create folder structure # Args: # file: Current file object # parent_id: Parent folder ID # name: List of folder names to create # count: Current depth in creation # Returns: # Created file object if count > len(name) - 2: return file else: file = cls.insert( {"id": get_uuid(), "parent_id": parent_id, "tenant_id": current_user.id, "created_by": current_user.id, "name": name[count], "location": "", "size": 0, "type": FileType.FOLDER.value} ) return cls.create_folder(file, file.id, name, count + 1) @classmethod @DB.connection_context() def is_parent_folder_exist(cls, parent_id): # Check if parent folder exists # Args: # parent_id: Parent folder ID # Returns: # Boolean indicating if folder exists parent_files = cls.model.select().where(cls.model.id == parent_id) if parent_files.count(): return True cls.delete_folder_by_pf_id(parent_id) return False @classmethod @DB.connection_context() def get_root_folder(cls, tenant_id): # Get or create root folder for tenant # Args: # tenant_id: Tenant ID # Returns: # Root folder dictionary for file in cls.model.select().where((cls.model.tenant_id == tenant_id), (cls.model.parent_id == cls.model.id)): return file.to_dict() file_id = get_uuid() file = { "id": file_id, "parent_id": file_id, "tenant_id": tenant_id, "created_by": tenant_id, "name": "/", "type": FileType.FOLDER.value, "size": 0, "location": "", } cls.save(**file) return file @classmethod @DB.connection_context() def get_kb_folder(cls, tenant_id): # Get dataset folder for tenant # Args: # tenant_id: Tenant ID # Returns: # Knowledge base folder dictionary root_folder = cls.get_root_folder(tenant_id) root_id = root_folder["id"] kb_folder = cls.model.select().where((cls.model.tenant_id == tenant_id), (cls.model.parent_id == root_id), (cls.model.name == KNOWLEDGEBASE_FOLDER_NAME)).first() if not kb_folder: kb_folder = cls.new_a_file_from_kb(tenant_id, KNOWLEDGEBASE_FOLDER_NAME, root_id) return kb_folder return kb_folder.to_dict() @classmethod @DB.connection_context() def new_a_file_from_kb(cls, tenant_id, name, parent_id, ty=FileType.FOLDER.value, size=0, location=""): # Create a new file from dataset # Args: # tenant_id: Tenant ID # name: File name # parent_id: Parent folder ID # ty: File type # size: File size # location: File location # Returns: # Created file dictionary for file in cls.query(tenant_id=tenant_id, parent_id=parent_id, name=name): return file.to_dict() file = { "id": get_uuid(), "parent_id": parent_id, "tenant_id": tenant_id, "created_by": tenant_id, "name": name, "type": ty, "size": size, "location": location, "source_type": FileSource.KNOWLEDGEBASE, } cls.save(**file) return file @classmethod @DB.connection_context() def init_knowledgebase_docs(cls, root_id, tenant_id): # Initialize dataset documents # Args: # root_id: Root folder ID # tenant_id: Tenant ID for _ in cls.model.select().where((cls.model.name == KNOWLEDGEBASE_FOLDER_NAME) & (cls.model.parent_id == root_id)): return folder = cls.new_a_file_from_kb(tenant_id, KNOWLEDGEBASE_FOLDER_NAME, root_id) for kb in Knowledgebase.select(*[Knowledgebase.id, Knowledgebase.name]).where(Knowledgebase.tenant_id == tenant_id): kb_folder = cls.new_a_file_from_kb(tenant_id, kb.name, folder["id"]) for doc in DocumentService.query(kb_id=kb.id): FileService.add_file_from_kb(doc.to_dict(), kb_folder["id"], tenant_id) @classmethod @DB.connection_context() def get_parent_folder(cls, file_id): # Get parent folder of a file # Args: # file_id: File ID # Returns: # Parent folder object file = cls.model.select().where(cls.model.id == file_id) if file.count(): e, file = cls.get_by_id(file[0].parent_id) if not e: raise RuntimeError("Database error (File retrieval)!") else: raise RuntimeError("Database error (File doesn't exist)!") return file @classmethod @DB.connection_context() def get_all_parent_folders(cls, start_id): # Get all parent folders in path # Args: # start_id: Starting file ID # Returns: # List of parent folder objects parent_folders = [] current_id = start_id while current_id: e, file = cls.get_by_id(current_id) if e and file.parent_id != file.id: parent_folders.append(file) current_id = file.parent_id else: parent_folders.append(file) break return parent_folders @classmethod @DB.connection_context() def insert(cls, file): # Insert a new file record # Args: # file: File data dictionary # Returns: # Created file object if not cls.save(**file): raise RuntimeError("Database error (File)!") return File(**file) @classmethod @DB.connection_context() def delete(cls, file): # return cls.delete_by_id(file.id) @classmethod @DB.connection_context() def delete_by_pf_id(cls, folder_id): return cls.model.delete().where(cls.model.parent_id == folder_id).execute() @classmethod @DB.connection_context() def delete_folder_by_pf_id(cls, user_id, folder_id): try: files = cls.model.select().where((cls.model.tenant_id == user_id) & (cls.model.parent_id == folder_id)) for file in files: cls.delete_folder_by_pf_id(user_id, file.id) return (cls.model.delete().where((cls.model.tenant_id == user_id) & (cls.model.id == folder_id)).execute(),) except Exception: logging.exception("delete_folder_by_pf_id") raise RuntimeError("Database error (File retrieval)!") @classmethod @DB.connection_context() def get_file_count(cls, tenant_id): files = cls.model.select(cls.model.id).where(cls.model.tenant_id == tenant_id) return len(files) @classmethod @DB.connection_context() def get_folder_size(cls, folder_id): size = 0 def dfs(parent_id): nonlocal size for f in cls.model.select(*[cls.model.id, cls.model.size, cls.model.type]).where(cls.model.parent_id == parent_id, cls.model.id != parent_id): size += f.size if f.type == FileType.FOLDER.value: dfs(f.id) dfs(folder_id) return size @classmethod @DB.connection_context() def add_file_from_kb(cls, doc, kb_folder_id, tenant_id): for _ in File2DocumentService.get_by_document_id(doc["id"]): return file = { "id": get_uuid(), "parent_id": kb_folder_id, "tenant_id": tenant_id, "created_by": tenant_id, "name": doc["name"], "type": doc["type"], "size": doc["size"], "location": doc["location"], "source_type": FileSource.KNOWLEDGEBASE, } cls.save(**file) File2DocumentService.save(**{"id": get_uuid(), "file_id": file["id"], "document_id": doc["id"]}) @classmethod @DB.connection_context() def move_file(cls, file_ids, folder_id): try: cls.filter_update((cls.model.id << file_ids,), {"parent_id": folder_id}) except Exception: logging.exception("move_file") raise RuntimeError("Database error (File move)!") @classmethod @DB.connection_context() def upload_document(self, kb, file_objs, user_id, src="local", parent_path: str | None = None): root_folder = self.get_root_folder(user_id) pf_id = root_folder["id"] self.init_knowledgebase_docs(pf_id, user_id) kb_root_folder = self.get_kb_folder(user_id) kb_folder = self.new_a_file_from_kb(kb.tenant_id, kb.name, kb_root_folder["id"]) safe_parent_path = sanitize_path(parent_path) err, files = [], [] for file in file_objs: try: DocumentService.check_doc_health(kb.tenant_id, file.filename) filename = duplicate_name(DocumentService.query, name=file.filename, kb_id=kb.id) filetype = filename_type(filename) if filetype == FileType.OTHER.value: raise RuntimeError("This type of file has not been supported yet!") location = filename if not safe_parent_path else f"{safe_parent_path}/{filename}" while settings.STORAGE_IMPL.obj_exist(kb.id, location): location += "_" blob = file.read() if filetype == FileType.PDF.value: blob = read_potential_broken_pdf(blob) settings.STORAGE_IMPL.put(kb.id, location, blob) doc_id = get_uuid() img = thumbnail_img(filename, blob) thumbnail_location = "" if img is not None: thumbnail_location = f"thumbnail_{doc_id}.png" settings.STORAGE_IMPL.put(kb.id, thumbnail_location, img) doc = { "id": doc_id, "kb_id": kb.id, "parser_id": self.get_parser(filetype, filename, kb.parser_id), "pipeline_id": kb.pipeline_id, "parser_config": kb.parser_config, "created_by": user_id, "type": filetype, "name": filename, "source_type": src, "suffix": Path(filename).suffix.lstrip("."), "location": location, "size": len(blob), "thumbnail": thumbnail_location, } DocumentService.insert(doc) FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id) files.append((doc, blob)) except Exception as e: err.append(file.filename + ": " + str(e)) return err, files @classmethod @DB.connection_context() def list_all_files_by_parent_id(cls, parent_id): try: files = cls.model.select().where((cls.model.parent_id == parent_id) & (cls.model.id != parent_id)) return list(files) except Exception: logging.exception("list_by_parent_id failed") raise RuntimeError("Database error (list_by_parent_id)!") @staticmethod def parse_docs(file_objs, user_id): exe = ThreadPoolExecutor(max_workers=12) threads = [] for file in file_objs: threads.append(exe.submit(FileService.parse, file.filename, file.read(), False)) res = [] for th in threads: res.append(th.result()) return "\n\n".join(res) @staticmethod def parse(filename, blob, img_base64=True, tenant_id=None): from rag.app import audio, email, naive, picture, presentation from api.apps import current_user def dummy(prog=None, msg=""): pass FACTORY = {ParserType.PRESENTATION.value: presentation, ParserType.PICTURE.value: picture, ParserType.AUDIO.value: audio, ParserType.EMAIL.value: email} parser_config = {"chunk_token_num": 16096, "delimiter": "\n!?;。;!?", "layout_recognize": "Plain Text"} kwargs = {"lang": "English", "callback": dummy, "parser_config": parser_config, "from_page": 0, "to_page": 100000, "tenant_id": current_user.id if current_user else tenant_id} file_type = filename_type(filename) if img_base64 and file_type == FileType.VISUAL.value: return GptV4.image2base64(blob) cks = FACTORY.get(FileService.get_parser(filename_type(filename), filename, ""), naive).chunk(filename, blob, **kwargs) return f"\n -----------------\nFile: {filename}\nContent as following: \n" + "\n".join([ck["content_with_weight"] for ck in cks]) @staticmethod def get_parser(doc_type, filename, default): if doc_type == FileType.VISUAL: return ParserType.PICTURE.value if doc_type == FileType.AURAL: return ParserType.AUDIO.value if re.search(r"\.(ppt|pptx|pages)$", filename): return ParserType.PRESENTATION.value if re.search(r"\.(msg|eml)$", filename): return ParserType.EMAIL.value return default @staticmethod def get_blob(user_id, location): bname = f"{user_id}-downloads" return settings.STORAGE_IMPL.get(bname, location) @staticmethod def put_blob(user_id, location, blob): bname = f"{user_id}-downloads" return settings.STORAGE_IMPL.put(bname, location, blob) @classmethod @DB.connection_context() def delete_docs(cls, doc_ids, tenant_id): root_folder = FileService.get_root_folder(tenant_id) pf_id = root_folder["id"] FileService.init_knowledgebase_docs(pf_id, tenant_id) errors = "" kb_table_num_map = {} for doc_id in doc_ids: try: e, doc = DocumentService.get_by_id(doc_id) if not e: raise Exception("Document not found!") tenant_id = DocumentService.get_tenant_id(doc_id) if not tenant_id: raise Exception("Tenant not found!") b, n = File2DocumentService.get_storage_address(doc_id=doc_id) TaskService.filter_delete([Task.doc_id == doc_id]) if not DocumentService.remove_document(doc, tenant_id): raise Exception("Database error (Document removal)!") f2d = File2DocumentService.get_by_document_id(doc_id) deleted_file_count = 0 if f2d: deleted_file_count = FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id]) File2DocumentService.delete_by_document_id(doc_id) if deleted_file_count > 0: settings.STORAGE_IMPL.rm(b, n) doc_parser = doc.parser_id if doc_parser == ParserType.TABLE: kb_id = doc.kb_id if kb_id not in kb_table_num_map: counts = DocumentService.count_by_kb_id(kb_id=kb_id, keywords="", run_status=[TaskStatus.DONE], types=[]) kb_table_num_map[kb_id] = counts kb_table_num_map[kb_id] -= 1 if kb_table_num_map[kb_id] <= 0: KnowledgebaseService.delete_field_map(kb_id) except Exception as e: errors += str(e) return errors @staticmethod def upload_info(user_id, file, url: str|None=None): def structured(filename, filetype, blob, content_type): nonlocal user_id if filetype == FileType.PDF.value: blob = read_potential_broken_pdf(blob) location = get_uuid() FileService.put_blob(user_id, location, blob) return { "id": location, "name": filename, "size": sys.getsizeof(blob), "extension": filename.split(".")[-1].lower(), "mime_type": content_type, "created_by": user_id, "created_at": time.time(), "preview_url": None } if url: from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, DefaultMarkdownGenerator, PruningContentFilter, CrawlResult ) filename = re.sub(r"\?.*", "", url.split("/")[-1]) async def adownload(): browser_config = BrowserConfig( headless=True, verbose=False, ) async with AsyncWebCrawler(config=browser_config) as crawler: crawler_config = CrawlerRunConfig( markdown_generator=DefaultMarkdownGenerator( content_filter=PruningContentFilter() ), pdf=True, screenshot=False ) result: CrawlResult = await crawler.arun( url=url, config=crawler_config ) return result page = asyncio.run(adownload()) if page.pdf: if filename.split(".")[-1].lower() != "pdf": filename += ".pdf" return structured(filename, "pdf", page.pdf, page.response_headers["content-type"]) return structured(filename, "html", str(page.markdown).encode("utf-8"), page.response_headers["content-type"], user_id) DocumentService.check_doc_health(user_id, file.filename) return structured(file.filename, filename_type(file.filename), file.read(), file.content_type) @staticmethod def get_files(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")) exe = ThreadPoolExecutor(max_workers=5) threads = [] for file in files: if file["mime_type"].find("image") >=0: threads.append(exe.submit(image_to_base64, file)) continue threads.append(exe.submit(FileService.parse, file["name"], FileService.get_blob(file["created_by"], file["id"]), True, file["created_by"])) return [th.result() for th in threads]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/file2document_service.py
api/db/services/file2document_service.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 datetime import datetime from common.constants import FileSource from api.db.db_models import DB from api.db.db_models import File, File2Document from api.db.services.common_service import CommonService from api.db.services.document_service import DocumentService from common.time_utils import current_timestamp, datetime_format class File2DocumentService(CommonService): model = File2Document @classmethod @DB.connection_context() def get_by_file_id(cls, file_id): objs = cls.model.select().where(cls.model.file_id == file_id) return objs @classmethod @DB.connection_context() def get_by_document_id(cls, document_id): objs = cls.model.select().where(cls.model.document_id == document_id) return objs @classmethod @DB.connection_context() def get_by_document_ids(cls, document_ids): objs = cls.model.select().where(cls.model.document_id.in_(document_ids)) return list(objs.dicts()) @classmethod @DB.connection_context() def insert(cls, obj): if not cls.save(**obj): raise RuntimeError("Database error (File)!") return File2Document(**obj) @classmethod @DB.connection_context() def delete_by_file_id(cls, file_id): return cls.model.delete().where(cls.model.file_id == file_id).execute() @classmethod @DB.connection_context() def delete_by_document_ids_or_file_ids(cls, document_ids, file_ids): if not document_ids: return cls.model.delete().where(cls.model.file_id.in_(file_ids)).execute() elif not file_ids: return cls.model.delete().where(cls.model.document_id.in_(document_ids)).execute() return cls.model.delete().where(cls.model.document_id.in_(document_ids) | cls.model.file_id.in_(file_ids)).execute() @classmethod @DB.connection_context() def delete_by_document_id(cls, doc_id): return cls.model.delete().where(cls.model.document_id == doc_id).execute() @classmethod @DB.connection_context() def update_by_file_id(cls, file_id, obj): obj["update_time"] = current_timestamp() obj["update_date"] = datetime_format(datetime.now()) cls.model.update(obj).where(cls.model.id == file_id).execute() return File2Document(**obj) @classmethod @DB.connection_context() def get_storage_address(cls, doc_id=None, file_id=None): if doc_id: f2d = cls.get_by_document_id(doc_id) else: f2d = cls.get_by_file_id(file_id) if f2d: file = File.get_by_id(f2d[0].file_id) if not file.source_type or file.source_type == FileSource.LOCAL: return file.parent_id, file.location doc_id = f2d[0].document_id assert doc_id, "please specify doc_id" e, doc = DocumentService.get_by_id(doc_id) return doc.kb_id, doc.location
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/canvas_service.py
api/db/services/canvas_service.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 time from uuid import uuid4 from agent.canvas import Canvas from api.db import CanvasCategory, TenantPermission from api.db.db_models import DB, CanvasTemplate, User, UserCanvas, API4Conversation from api.db.services.api_service import API4ConversationService from api.db.services.common_service import CommonService from common.misc_utils import get_uuid from api.utils.api_utils import get_data_openai import tiktoken from peewee import fn class CanvasTemplateService(CommonService): model = CanvasTemplate class DataFlowTemplateService(CommonService): """ Alias of CanvasTemplateService """ model = CanvasTemplate class UserCanvasService(CommonService): model = UserCanvas @classmethod @DB.connection_context() def get_list(cls, tenant_id, page_number, items_per_page, orderby, desc, id, title, canvas_category=CanvasCategory.Agent): agents = cls.model.select() if id: agents = agents.where(cls.model.id == id) if title: agents = agents.where(cls.model.title == title) agents = agents.where(cls.model.user_id == tenant_id) agents = agents.where(cls.model.canvas_category == canvas_category) if desc: agents = agents.order_by(cls.model.getter_by(orderby).desc()) else: agents = agents.order_by(cls.model.getter_by(orderby).asc()) agents = agents.paginate(page_number, items_per_page) return list(agents.dicts()) @classmethod @DB.connection_context() def get_all_agents_by_tenant_ids(cls, tenant_ids, user_id): # will get all permitted agents, be cautious fields = [ cls.model.id, cls.model.avatar, cls.model.title, cls.model.permission, cls.model.canvas_type, cls.model.canvas_category ] # find team agents and owned agents agents = cls.model.select(*fields).where( (cls.model.user_id.in_(tenant_ids) & (cls.model.permission == TenantPermission.TEAM.value)) | ( cls.model.user_id == user_id ) ) # sort by create_time, asc agents.order_by(cls.model.create_time.asc()) # maybe cause slow query by deep paginate, optimize later offset, limit = 0, 50 res = [] while True: ag_batch = agents.offset(offset).limit(limit) _temp = list(ag_batch.dicts()) if not _temp: break res.extend(_temp) offset += limit return res @classmethod @DB.connection_context() def get_by_canvas_id(cls, pid): try: fields = [ cls.model.id, cls.model.avatar, cls.model.title, cls.model.dsl, cls.model.description, cls.model.permission, cls.model.update_time, cls.model.user_id, cls.model.create_time, cls.model.create_date, cls.model.update_date, cls.model.canvas_category, User.nickname, User.avatar.alias('tenant_avatar'), ] agents = cls.model.select(*fields) \ .join(User, on=(cls.model.user_id == User.id)) \ .where(cls.model.id == pid) # obj = cls.model.query(id=pid)[0] return True, agents.dicts()[0] except Exception as e: logging.exception(e) return False, None @classmethod @DB.connection_context() def get_basic_info_by_canvas_ids(cls, canvas_id): fields = [ cls.model.id, cls.model.avatar, cls.model.user_id, cls.model.title, cls.model.permission, cls.model.canvas_category ] return cls.model.select(*fields).where(cls.model.id.in_(canvas_id)).dicts() @classmethod @DB.connection_context() def get_by_tenant_ids(cls, joined_tenant_ids, user_id, page_number, items_per_page, orderby, desc, keywords, canvas_category=None ): fields = [ cls.model.id, cls.model.avatar, cls.model.title, cls.model.dsl, cls.model.description, cls.model.permission, cls.model.user_id.alias("tenant_id"), User.nickname, User.avatar.alias('tenant_avatar'), cls.model.update_time, cls.model.canvas_category, ] if keywords: agents = cls.model.select(*fields).join(User, on=(cls.model.user_id == User.id)).where( (((cls.model.user_id.in_(joined_tenant_ids)) & (cls.model.permission == TenantPermission.TEAM.value)) | (cls.model.user_id == user_id)), (fn.LOWER(cls.model.title).contains(keywords.lower())) ) else: agents = cls.model.select(*fields).join(User, on=(cls.model.user_id == User.id)).where( (((cls.model.user_id.in_(joined_tenant_ids)) & (cls.model.permission == TenantPermission.TEAM.value)) | (cls.model.user_id == user_id)) ) if canvas_category: agents = agents.where(cls.model.canvas_category == canvas_category) if desc: agents = agents.order_by(cls.model.getter_by(orderby).desc()) else: agents = agents.order_by(cls.model.getter_by(orderby).asc()) count = agents.count() if page_number and items_per_page: agents = agents.paginate(page_number, items_per_page) return list(agents.dicts()), count @classmethod @DB.connection_context() def accessible(cls, canvas_id, tenant_id): from api.db.services.user_service import UserTenantService e, c = UserCanvasService.get_by_canvas_id(canvas_id) if not e: return False tids = [t.tenant_id for t in UserTenantService.query(user_id=tenant_id)] if c["user_id"] != canvas_id and c["user_id"] not in tids: return False return True async def completion(tenant_id, agent_id, session_id=None, **kwargs): query = kwargs.get("query", "") or kwargs.get("question", "") files = kwargs.get("files", []) inputs = kwargs.get("inputs", {}) user_id = kwargs.get("user_id", "") if session_id: e, conv = API4ConversationService.get_by_id(session_id) assert e, "Session not found!" if not conv.message: conv.message = [] if not isinstance(conv.dsl, str): conv.dsl = json.dumps(conv.dsl, ensure_ascii=False) canvas = Canvas(conv.dsl, tenant_id, agent_id) else: e, cvs = UserCanvasService.get_by_id(agent_id) assert e, "Agent not found." assert cvs.user_id == tenant_id, "You do not own the agent." if not isinstance(cvs.dsl, str): cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False) session_id=get_uuid() canvas = Canvas(cvs.dsl, tenant_id, agent_id, canvas_id=cvs.id) canvas.reset() conv = { "id": session_id, "dialog_id": cvs.id, "user_id": user_id, "message": [], "source": "agent", "dsl": cvs.dsl, "reference": [] } API4ConversationService.save(**conv) conv = API4Conversation(**conv) message_id = str(uuid4()) conv.message.append({ "role": "user", "content": query, "id": message_id }) txt = "" async for ans in canvas.run(query=query, files=files, user_id=user_id, inputs=inputs): ans["session_id"] = session_id if ans["event"] == "message": txt += ans["data"]["content"] if ans["data"].get("start_to_think", False): txt += "<think>" elif ans["data"].get("end_to_think", False): txt += "</think>" yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n" conv.message.append({"role": "assistant", "content": txt, "created_at": time.time(), "id": message_id}) conv.reference = canvas.get_reference() conv.errors = canvas.error conv.dsl = str(canvas) conv = conv.to_dict() API4ConversationService.append_message(conv["id"], conv) async def completion_openai(tenant_id, agent_id, question, session_id=None, stream=True, **kwargs): tiktoken_encoder = tiktoken.get_encoding("cl100k_base") prompt_tokens = len(tiktoken_encoder.encode(str(question))) user_id = kwargs.get("user_id", "") if stream: completion_tokens = 0 try: async for ans in completion( tenant_id=tenant_id, agent_id=agent_id, session_id=session_id, query=question, user_id=user_id, **kwargs ): if isinstance(ans, str): try: ans = json.loads(ans[5:]) # remove "data:" except Exception as e: logging.exception(f"Agent OpenAI-Compatible completion_openai parse answer failed: {e}") continue if ans.get("event") not in ["message", "message_end"]: continue content_piece = "" if ans["event"] == "message": content_piece = ans["data"]["content"] completion_tokens += len(tiktoken_encoder.encode(content_piece)) openai_data = get_data_openai( id=session_id or str(uuid4()), model=agent_id, content=content_piece, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, stream=True ) if ans.get("data", {}).get("reference", None): openai_data["choices"][0]["delta"]["reference"] = ans["data"]["reference"] yield "data: " + json.dumps(openai_data, ensure_ascii=False) + "\n\n" yield "data: [DONE]\n\n" except Exception as e: logging.exception(e) yield "data: " + json.dumps( get_data_openai( id=session_id or str(uuid4()), model=agent_id, content=f"**ERROR**: {str(e)}", finish_reason="stop", prompt_tokens=prompt_tokens, completion_tokens=len(tiktoken_encoder.encode(f"**ERROR**: {str(e)}")), stream=True ), ensure_ascii=False ) + "\n\n" yield "data: [DONE]\n\n" else: try: all_content = "" reference = {} async for ans in completion( tenant_id=tenant_id, agent_id=agent_id, session_id=session_id, query=question, user_id=user_id, **kwargs ): if isinstance(ans, str): ans = json.loads(ans[5:]) if ans.get("event") not in ["message", "message_end"]: continue if ans["event"] == "message": all_content += ans["data"]["content"] if ans.get("data", {}).get("reference", None): reference.update(ans["data"]["reference"]) completion_tokens = len(tiktoken_encoder.encode(all_content)) openai_data = get_data_openai( id=session_id or str(uuid4()), model=agent_id, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, content=all_content, finish_reason="stop", param=None ) if reference: openai_data["choices"][0]["message"]["reference"] = reference yield openai_data except Exception as e: logging.exception(e) yield get_data_openai( id=session_id or str(uuid4()), model=agent_id, prompt_tokens=prompt_tokens, completion_tokens=len(tiktoken_encoder.encode(f"**ERROR**: {str(e)}")), content=f"**ERROR**: {str(e)}", finish_reason="stop", param=None )
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/llm_service.py
api/db/services/llm_service.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 inspect import logging import queue import re import threading from functools import partial from typing import Generator from api.db.db_models import LLM from api.db.services.common_service import CommonService from api.db.services.tenant_llm_service import LLM4Tenant, TenantLLMService from common.constants import LLMType from common.token_utils import num_tokens_from_string class LLMService(CommonService): model = LLM def get_init_tenant_llm(user_id): from common import settings tenant_llm = [] model_configs = { LLMType.CHAT: settings.CHAT_CFG, LLMType.EMBEDDING: settings.EMBEDDING_CFG, LLMType.SPEECH2TEXT: settings.ASR_CFG, LLMType.IMAGE2TEXT: settings.IMAGE2TEXT_CFG, LLMType.RERANK: settings.RERANK_CFG, } seen = set() factory_configs = [] for factory_config in [ settings.CHAT_CFG, settings.EMBEDDING_CFG, settings.ASR_CFG, settings.IMAGE2TEXT_CFG, settings.RERANK_CFG, ]: factory_name = factory_config["factory"] if factory_name not in seen: seen.add(factory_name) factory_configs.append(factory_config) for factory_config in factory_configs: for llm in LLMService.query(fid=factory_config["factory"]): tenant_llm.append( { "tenant_id": user_id, "llm_factory": factory_config["factory"], "llm_name": llm.llm_name, "model_type": llm.model_type, "api_key": model_configs.get(llm.model_type, {}).get("api_key", factory_config["api_key"]), "api_base": model_configs.get(llm.model_type, {}).get("base_url", factory_config["base_url"]), "max_tokens": llm.max_tokens if llm.max_tokens else 8192, } ) unique = {} for item in tenant_llm: key = (item["tenant_id"], item["llm_factory"], item["llm_name"]) if key not in unique: unique[key] = item return list(unique.values()) class LLMBundle(LLM4Tenant): def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs): super().__init__(tenant_id, llm_type, llm_name, lang, **kwargs) def bind_tools(self, toolcall_session, tools): if not self.is_tools: logging.warning(f"Model {self.llm_name} does not support tool call, but you have assigned one or more tools to it!") return self.mdl.bind_tools(toolcall_session, tools) def encode(self, texts: list): if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="encode", model=self.llm_name, input={"texts": texts}) safe_texts = [] for text in texts: token_size = num_tokens_from_string(text) if token_size > self.max_length: target_len = int(self.max_length * 0.95) safe_texts.append(text[:target_len]) else: safe_texts.append(text) embeddings, used_tokens = self.mdl.encode(safe_texts) llm_name = getattr(self, "llm_name", None) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, llm_name): logging.error("LLMBundle.encode can't update token usage for <tenant redacted>/EMBEDDING used_tokens: {}".format(used_tokens)) if self.langfuse: generation.update(usage_details={"total_tokens": used_tokens}) generation.end() return embeddings, used_tokens def encode_queries(self, query: str): if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="encode_queries", model=self.llm_name, input={"query": query}) emd, used_tokens = self.mdl.encode_queries(query) llm_name = getattr(self, "llm_name", None) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, llm_name): logging.error("LLMBundle.encode_queries can't update token usage for <tenant redacted>/EMBEDDING used_tokens: {}".format(used_tokens)) if self.langfuse: generation.update(usage_details={"total_tokens": used_tokens}) generation.end() return emd, used_tokens def similarity(self, query: str, texts: list): if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="similarity", model=self.llm_name, input={"query": query, "texts": texts}) sim, used_tokens = self.mdl.similarity(query, texts) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens): logging.error("LLMBundle.similarity can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens)) if self.langfuse: generation.update(usage_details={"total_tokens": used_tokens}) generation.end() return sim, used_tokens def describe(self, image, max_tokens=300): if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="describe", metadata={"model": self.llm_name}) txt, used_tokens = self.mdl.describe(image) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens): logging.error("LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens)) if self.langfuse: generation.update(output={"output": txt}, usage_details={"total_tokens": used_tokens}) generation.end() return txt def describe_with_prompt(self, image, prompt): if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="describe_with_prompt", metadata={"model": self.llm_name, "prompt": prompt}) txt, used_tokens = self.mdl.describe_with_prompt(image, prompt) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens): logging.error("LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens)) if self.langfuse: generation.update(output={"output": txt}, usage_details={"total_tokens": used_tokens}) generation.end() return txt def transcription(self, audio): if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="transcription", metadata={"model": self.llm_name}) txt, used_tokens = self.mdl.transcription(audio) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens): logging.error("LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens)) if self.langfuse: generation.update(output={"output": txt}, usage_details={"total_tokens": used_tokens}) generation.end() return txt def stream_transcription(self, audio): mdl = self.mdl supports_stream = hasattr(mdl, "stream_transcription") and callable(getattr(mdl, "stream_transcription")) if supports_stream: if self.langfuse: generation = self.langfuse.start_generation( trace_context=self.trace_context, name="stream_transcription", metadata={"model": self.llm_name}, ) final_text = "" used_tokens = 0 try: for evt in mdl.stream_transcription(audio): if evt.get("event") == "final": final_text = evt.get("text", "") yield evt except Exception as e: err = {"event": "error", "text": str(e)} yield err final_text = final_text or "" finally: if final_text: used_tokens = num_tokens_from_string(final_text) TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens) if self.langfuse: generation.update( output={"output": final_text}, usage_details={"total_tokens": used_tokens}, ) generation.end() return if self.langfuse: generation = self.langfuse.start_generation( trace_context=self.trace_context, name="stream_transcription", metadata={"model": self.llm_name}, ) full_text, used_tokens = mdl.transcription(audio) if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens): logging.error(f"LLMBundle.stream_transcription can't update token usage for {self.tenant_id}/SEQUENCE2TXT used_tokens: {used_tokens}") if self.langfuse: generation.update( output={"output": full_text}, usage_details={"total_tokens": used_tokens}, ) generation.end() yield { "event": "final", "text": full_text, "streaming": False, } def tts(self, text: str) -> Generator[bytes, None, None]: if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="tts", input={"text": text}) for chunk in self.mdl.tts(text): if isinstance(chunk, int): if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, chunk, self.llm_name): logging.error("LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id)) return yield chunk if self.langfuse: generation.end() def _remove_reasoning_content(self, txt: str) -> str: first_think_start = txt.find("<think>") if first_think_start == -1: return txt last_think_end = txt.rfind("</think>") if last_think_end == -1: return txt if last_think_end < first_think_start: return txt return txt[last_think_end + len("</think>") :] @staticmethod def _clean_param(chat_partial, **kwargs): func = chat_partial.func sig = inspect.signature(func) support_var_args = False allowed_params = set() for param in sig.parameters.values(): if param.kind == inspect.Parameter.VAR_KEYWORD: support_var_args = True elif param.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY): allowed_params.add(param.name) if support_var_args: return kwargs else: return {k: v for k, v in kwargs.items() if k in allowed_params} def _run_coroutine_sync(self, coro): try: asyncio.get_running_loop() except RuntimeError: return asyncio.run(coro) result_queue: queue.Queue = queue.Queue() def runner(): try: result_queue.put((True, asyncio.run(coro))) except Exception as e: result_queue.put((False, e)) thread = threading.Thread(target=runner, daemon=True) thread.start() thread.join() success, value = result_queue.get_nowait() if success: return value raise value def _sync_from_async_stream(self, async_gen_fn, *args, **kwargs): result_queue: queue.Queue = queue.Queue() def runner(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) async def consume(): try: async for item in async_gen_fn(*args, **kwargs): result_queue.put(item) except Exception as e: result_queue.put(e) finally: result_queue.put(StopIteration) loop.run_until_complete(consume()) loop.close() threading.Thread(target=runner, daemon=True).start() while True: item = result_queue.get() if item is StopIteration: break if isinstance(item, Exception): raise item yield item def _bridge_sync_stream(self, gen): loop = asyncio.get_running_loop() queue: asyncio.Queue = asyncio.Queue() def worker(): try: for item in gen: loop.call_soon_threadsafe(queue.put_nowait, item) except Exception as e: loop.call_soon_threadsafe(queue.put_nowait, e) finally: loop.call_soon_threadsafe(queue.put_nowait, StopAsyncIteration) threading.Thread(target=worker, daemon=True).start() return queue async def async_chat(self, system: str, history: list, gen_conf: dict = {}, **kwargs): if self.is_tools and getattr(self.mdl, "is_tools", False) and hasattr(self.mdl, "async_chat_with_tools"): base_fn = self.mdl.async_chat_with_tools elif hasattr(self.mdl, "async_chat"): base_fn = self.mdl.async_chat else: raise RuntimeError(f"Model {self.mdl} does not implement async_chat or async_chat_with_tools") generation = None if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="chat", model=self.llm_name, input={"system": system, "history": history}) chat_partial = partial(base_fn, system, history, gen_conf) use_kwargs = self._clean_param(chat_partial, **kwargs) try: txt, used_tokens = await chat_partial(**use_kwargs) except Exception as e: if generation: generation.update(output={"error": str(e)}) generation.end() raise txt = self._remove_reasoning_content(txt) if not self.verbose_tool_use: txt = re.sub(r"<tool_call>.*?</tool_call>", "", txt, flags=re.DOTALL) if used_tokens and not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, self.llm_name): logging.error("LLMBundle.async_chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name, used_tokens)) if generation: generation.update(output={"output": txt}, usage_details={"total_tokens": used_tokens}) generation.end() return txt async def async_chat_streamly(self, system: str, history: list, gen_conf: dict = {}, **kwargs): total_tokens = 0 ans = "" if self.is_tools and getattr(self.mdl, "is_tools", False) and hasattr(self.mdl, "async_chat_streamly_with_tools"): stream_fn = getattr(self.mdl, "async_chat_streamly_with_tools", None) elif hasattr(self.mdl, "async_chat_streamly"): stream_fn = getattr(self.mdl, "async_chat_streamly", None) else: raise RuntimeError(f"Model {self.mdl} does not implement async_chat or async_chat_with_tools") generation = None if self.langfuse: generation = self.langfuse.start_generation(trace_context=self.trace_context, name="chat_streamly", model=self.llm_name, input={"system": system, "history": history}) if stream_fn: chat_partial = partial(stream_fn, system, history, gen_conf) use_kwargs = self._clean_param(chat_partial, **kwargs) try: async for txt in chat_partial(**use_kwargs): if isinstance(txt, int): total_tokens = txt break if txt.endswith("</think>"): ans = ans[: -len("</think>")] if not self.verbose_tool_use: txt = re.sub(r"<tool_call>.*?</tool_call>", "", txt, flags=re.DOTALL) ans += txt yield ans except Exception as e: if generation: generation.update(output={"error": str(e)}) generation.end() raise if total_tokens and not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, total_tokens, self.llm_name): logging.error("LLMBundle.async_chat_streamly can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name, total_tokens)) if generation: generation.update(output={"output": ans}, usage_details={"total_tokens": total_tokens}) generation.end() return
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/connector_service.py
api/db/services/connector_service.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 from datetime import datetime import os from typing import Tuple, List from anthropic import BaseModel from peewee import SQL, fn from api.db import InputType from api.db.db_models import Connector, SyncLogs, Connector2Kb, Knowledgebase from api.db.services.common_service import CommonService from api.db.services.document_service import DocumentService from common.misc_utils import get_uuid from common.constants import TaskStatus from common.time_utils import current_timestamp, timestamp_to_date class ConnectorService(CommonService): model = Connector @classmethod def resume(cls, connector_id, status): for c2k in Connector2KbService.query(connector_id=connector_id): task = SyncLogsService.get_latest_task(connector_id, c2k.kb_id) if not task: if status == TaskStatus.SCHEDULE: SyncLogsService.schedule(connector_id, c2k.kb_id) ConnectorService.update_by_id(connector_id, {"status": status}) return if task.status == TaskStatus.DONE: if status == TaskStatus.SCHEDULE: SyncLogsService.schedule(connector_id, c2k.kb_id, task.poll_range_end, total_docs_indexed=task.total_docs_indexed) ConnectorService.update_by_id(connector_id, {"status": status}) return task = task.to_dict() task["status"] = status SyncLogsService.update_by_id(task["id"], task) ConnectorService.update_by_id(connector_id, {"status": status}) @classmethod def list(cls, tenant_id): fields = [ cls.model.id, cls.model.name, cls.model.source, cls.model.status ] return list(cls.model.select(*fields).where( cls.model.tenant_id == tenant_id ).dicts()) @classmethod def rebuild(cls, kb_id:str, connector_id: str, tenant_id:str): from api.db.services.file_service import FileService e, conn = cls.get_by_id(connector_id) if not e: return None SyncLogsService.filter_delete([SyncLogs.connector_id==connector_id, SyncLogs.kb_id==kb_id]) docs = DocumentService.query(source_type=f"{conn.source}/{conn.id}", kb_id=kb_id) err = FileService.delete_docs([d.id for d in docs], tenant_id) SyncLogsService.schedule(connector_id, kb_id, reindex=True) return err class SyncLogsService(CommonService): model = SyncLogs @classmethod def list_sync_tasks(cls, connector_id=None, page_number=None, items_per_page=15) -> Tuple[List[dict], int]: fields = [ cls.model.id, cls.model.connector_id, cls.model.kb_id, cls.model.update_date, cls.model.poll_range_start, cls.model.poll_range_end, cls.model.new_docs_indexed, cls.model.total_docs_indexed, cls.model.error_msg, cls.model.full_exception_trace, cls.model.error_count, Connector.name, Connector.source, Connector.tenant_id, Connector.timeout_secs, Knowledgebase.name.alias("kb_name"), Knowledgebase.avatar.alias("kb_avatar"), Connector2Kb.auto_parse, cls.model.from_beginning.alias("reindex"), cls.model.status, cls.model.update_time ] if not connector_id: fields.append(Connector.config) query = cls.model.select(*fields)\ .join(Connector, on=(cls.model.connector_id==Connector.id))\ .join(Connector2Kb, on=(cls.model.kb_id==Connector2Kb.kb_id))\ .join(Knowledgebase, on=(cls.model.kb_id==Knowledgebase.id)) if connector_id: query = query.where(cls.model.connector_id == connector_id) else: database_type = os.getenv("DB_TYPE", "mysql") if "postgres" in database_type.lower(): interval_expr = SQL("make_interval(mins => t2.refresh_freq)") else: interval_expr = SQL("INTERVAL `t2`.`refresh_freq` MINUTE") query = query.where( Connector.input_type == InputType.POLL, Connector.status == TaskStatus.SCHEDULE, cls.model.status == TaskStatus.SCHEDULE, cls.model.update_date < (fn.NOW() - interval_expr) ) query = query.distinct().order_by(cls.model.update_time.desc()) total = query.count() if page_number: query = query.paginate(page_number, items_per_page) return list(query.dicts()), total @classmethod def start(cls, id, connector_id): cls.update_by_id(id, {"status": TaskStatus.RUNNING, "time_started": datetime.now().strftime('%Y-%m-%d %H:%M:%S') }) ConnectorService.update_by_id(connector_id, {"status": TaskStatus.RUNNING}) @classmethod def done(cls, id, connector_id): cls.update_by_id(id, {"status": TaskStatus.DONE}) ConnectorService.update_by_id(connector_id, {"status": TaskStatus.DONE}) @classmethod def schedule(cls, connector_id, kb_id, poll_range_start=None, reindex=False, total_docs_indexed=0): try: if cls.model.select().where(cls.model.kb_id == kb_id, cls.model.connector_id == connector_id).count() > 100: rm_ids = [m.id for m in cls.model.select(cls.model.id).where(cls.model.kb_id == kb_id, cls.model.connector_id == connector_id).order_by(cls.model.update_time.asc()).limit(70)] deleted = cls.model.delete().where(cls.model.id.in_(rm_ids)).execute() logging.info(f"[SyncLogService] Cleaned {deleted} old logs.") except Exception as e: logging.exception(e) try: e = cls.query(kb_id=kb_id, connector_id=connector_id, status=TaskStatus.SCHEDULE) if e: logging.warning(f"{kb_id}--{connector_id} has already had a scheduling sync task which is abnormal.") return None reindex = "1" if reindex else "0" ConnectorService.update_by_id(connector_id, {"status": TaskStatus.SCHEDULE}) return cls.save(**{ "id": get_uuid(), "kb_id": kb_id, "status": TaskStatus.SCHEDULE, "connector_id": connector_id, "poll_range_start": poll_range_start, "from_beginning": reindex, "total_docs_indexed": total_docs_indexed }) except Exception as e: logging.exception(e) task = cls.get_latest_task(connector_id, kb_id) if task: cls.model.update(status=TaskStatus.SCHEDULE, poll_range_start=poll_range_start, error_msg=cls.model.error_msg + str(e), full_exception_trace=cls.model.full_exception_trace + str(e) ) \ .where(cls.model.id == task.id).execute() ConnectorService.update_by_id(connector_id, {"status": TaskStatus.SCHEDULE}) @classmethod def increase_docs(cls, id, min_update, max_update, doc_num, err_msg="", error_count=0): cls.model.update(new_docs_indexed=cls.model.new_docs_indexed + doc_num, total_docs_indexed=cls.model.total_docs_indexed + doc_num, poll_range_start=fn.COALESCE(fn.LEAST(cls.model.poll_range_start,min_update), min_update), poll_range_end=fn.COALESCE(fn.GREATEST(cls.model.poll_range_end, max_update), max_update), error_msg=cls.model.error_msg + err_msg, error_count=cls.model.error_count + error_count, update_time=current_timestamp(), update_date=timestamp_to_date(current_timestamp()) )\ .where(cls.model.id == id).execute() @classmethod def duplicate_and_parse(cls, kb, docs, tenant_id, src, auto_parse=True): from api.db.services.file_service import FileService if not docs: return None class FileObj(BaseModel): filename: str blob: bytes def read(self) -> bytes: return self.blob errs = [] files = [FileObj(filename=d["semantic_identifier"]+(f"{d['extension']}" if d["semantic_identifier"][::-1].find(d['extension'][::-1])<0 else ""), blob=d["blob"]) for d in docs] doc_ids = [] err, doc_blob_pairs = FileService.upload_document(kb, files, tenant_id, src) errs.extend(err) # Create a mapping from filename to metadata for later use metadata_map = {} for d in docs: if d.get("metadata"): filename = d["semantic_identifier"]+(f"{d['extension']}" if d["semantic_identifier"][::-1].find(d['extension'][::-1])<0 else "") metadata_map[filename] = d["metadata"] kb_table_num_map = {} for doc, _ in doc_blob_pairs: doc_ids.append(doc["id"]) # Set metadata if available for this document if doc["name"] in metadata_map: DocumentService.update_by_id(doc["id"], {"meta_fields": metadata_map[doc["name"]]}) if not auto_parse or auto_parse == "0": continue DocumentService.run(tenant_id, doc, kb_table_num_map) return errs, doc_ids @classmethod def get_latest_task(cls, connector_id, kb_id): return cls.model.select().where( cls.model.connector_id==connector_id, cls.model.kb_id == kb_id ).order_by(cls.model.update_time.desc()).first() class Connector2KbService(CommonService): model = Connector2Kb @classmethod def link_connectors(cls, kb_id:str, connectors: list[dict], tenant_id:str): arr = cls.query(kb_id=kb_id) old_conn_ids = [a.connector_id for a in arr] connector_ids = [] for conn in connectors: conn_id = conn["id"] connector_ids.append(conn_id) if conn_id in old_conn_ids: cls.filter_update([cls.model.connector_id==conn_id, cls.model.kb_id==kb_id], {"auto_parse": conn.get("auto_parse", "1")}) continue cls.save(**{ "id": get_uuid(), "connector_id": conn_id, "kb_id": kb_id, "auto_parse": conn.get("auto_parse", "1") }) SyncLogsService.schedule(conn_id, kb_id, reindex=True) errs = [] for conn_id in old_conn_ids: if conn_id in connector_ids: continue cls.filter_delete([cls.model.kb_id==kb_id, cls.model.connector_id==conn_id]) e, conn = ConnectorService.get_by_id(conn_id) if not e: continue #SyncLogsService.filter_delete([SyncLogs.connector_id==conn_id, SyncLogs.kb_id==kb_id]) # Do not delete docs while unlinking. SyncLogsService.filter_update([SyncLogs.connector_id==conn_id, SyncLogs.kb_id==kb_id, SyncLogs.status.in_([TaskStatus.SCHEDULE, TaskStatus.RUNNING])], {"status": TaskStatus.CANCEL}) #docs = DocumentService.query(source_type=f"{conn.source}/{conn.id}") #err = FileService.delete_docs([d.id for d in docs], tenant_id) #if err: # errs.append(err) return "\n".join(errs) @classmethod def list_connectors(cls, kb_id): fields = [ Connector.id, Connector.source, Connector.name, cls.model.auto_parse, Connector.status ] return list(cls.model.select(*fields)\ .join(Connector, on=(cls.model.connector_id==Connector.id))\ .where( cls.model.kb_id==kb_id ).dicts() )
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/user_service.py
api/db/services/user_service.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 hashlib from datetime import datetime import logging import peewee from werkzeug.security import generate_password_hash, check_password_hash from api.db import UserTenantRole from api.db.db_models import DB, UserTenant from api.db.db_models import User, Tenant from api.db.services.common_service import CommonService from common.misc_utils import get_uuid from common.time_utils import current_timestamp, datetime_format from common.constants import StatusEnum from common import settings class UserService(CommonService): """Service class for managing user-related database operations. This class extends CommonService to provide specialized functionality for user management, including authentication, user creation, updates, and deletions. Attributes: model: The User model class for database operations. """ model = User @classmethod @DB.connection_context() def query(cls, cols=None, reverse=None, order_by=None, **kwargs): if 'access_token' in kwargs: access_token = kwargs['access_token'] # Reject empty, None, or whitespace-only access tokens if not access_token or not str(access_token).strip(): logging.warning("UserService.query: Rejecting empty access_token query") return cls.model.select().where(cls.model.id == "INVALID_EMPTY_TOKEN") # Returns empty result # Reject tokens that are too short (should be UUID, 32+ chars) if len(str(access_token).strip()) < 32: logging.warning(f"UserService.query: Rejecting short access_token query: {len(str(access_token))} chars") return cls.model.select().where(cls.model.id == "INVALID_SHORT_TOKEN") # Returns empty result # Reject tokens that start with "INVALID_" (from logout) if str(access_token).startswith("INVALID_"): logging.warning("UserService.query: Rejecting invalidated access_token") return cls.model.select().where(cls.model.id == "INVALID_LOGOUT_TOKEN") # Returns empty result # Call parent query method for valid requests return super().query(cols=cols, reverse=reverse, order_by=order_by, **kwargs) @classmethod @DB.connection_context() def filter_by_id(cls, user_id): """Retrieve a user by their ID. Args: user_id: The unique identifier of the user. Returns: User object if found, None otherwise. """ try: user = cls.model.select().where(cls.model.id == user_id).get() return user except peewee.DoesNotExist: return None @classmethod @DB.connection_context() def query_user(cls, email, password): """Authenticate a user with email and password. Args: email: User's email address. password: User's password in plain text. Returns: User object if authentication successful, None otherwise. """ user = cls.model.select().where((cls.model.email == email), (cls.model.status == StatusEnum.VALID.value)).first() if user and check_password_hash(str(user.password), password): return user else: return None @classmethod @DB.connection_context() def query_user_by_email(cls, email): users = cls.model.select().where((cls.model.email == email)) return list(users) @classmethod @DB.connection_context() def save(cls, **kwargs): if "id" not in kwargs: kwargs["id"] = get_uuid() if "password" in kwargs: kwargs["password"] = generate_password_hash( str(kwargs["password"])) current_ts = current_timestamp() current_date = datetime_format(datetime.now()) kwargs["create_time"] = current_ts kwargs["create_date"] = current_date kwargs["update_time"] = current_ts kwargs["update_date"] = current_date obj = cls.model(**kwargs).save(force_insert=True) return obj @classmethod @DB.connection_context() def delete_user(cls, user_ids, update_user_dict): with DB.atomic(): cls.model.update({"status": 0}).where( cls.model.id.in_(user_ids)).execute() @classmethod @DB.connection_context() def update_user(cls, user_id, user_dict): with DB.atomic(): if user_dict: user_dict["update_time"] = current_timestamp() user_dict["update_date"] = datetime_format(datetime.now()) cls.model.update(user_dict).where( cls.model.id == user_id).execute() @classmethod @DB.connection_context() def update_user_password(cls, user_id, new_password): with DB.atomic(): update_dict = { "password": generate_password_hash(str(new_password)), "update_time": current_timestamp(), "update_date": datetime_format(datetime.now()) } cls.model.update(update_dict).where(cls.model.id == user_id).execute() @classmethod @DB.connection_context() def is_admin(cls, user_id): return cls.model.select().where( cls.model.id == user_id, cls.model.is_superuser == 1).count() > 0 @classmethod @DB.connection_context() def get_all_users(cls): users = cls.model.select().order_by(cls.model.email) return list(users) class TenantService(CommonService): """Service class for managing tenant-related database operations. This class extends CommonService to provide functionality for tenant management, including tenant information retrieval and credit management. Attributes: model: The Tenant model class for database operations. """ model = Tenant @classmethod @DB.connection_context() def get_info_by(cls, user_id): fields = [ cls.model.id.alias("tenant_id"), cls.model.name, cls.model.llm_id, cls.model.embd_id, cls.model.rerank_id, cls.model.asr_id, cls.model.img2txt_id, cls.model.tts_id, cls.model.parser_ids, UserTenant.role] return list(cls.model.select(*fields) .join(UserTenant, on=((cls.model.id == UserTenant.tenant_id) & (UserTenant.user_id == user_id) & (UserTenant.status == StatusEnum.VALID.value) & (UserTenant.role == UserTenantRole.OWNER))) .where(cls.model.status == StatusEnum.VALID.value).dicts()) @classmethod @DB.connection_context() def get_joined_tenants_by_user_id(cls, user_id): fields = [ cls.model.id.alias("tenant_id"), cls.model.name, cls.model.llm_id, cls.model.embd_id, cls.model.asr_id, cls.model.img2txt_id, UserTenant.role] return list(cls.model.select(*fields) .join(UserTenant, on=((cls.model.id == UserTenant.tenant_id) & (UserTenant.user_id == user_id) & (UserTenant.status == StatusEnum.VALID.value) & (UserTenant.role == UserTenantRole.NORMAL))) .where(cls.model.status == StatusEnum.VALID.value).dicts()) @classmethod @DB.connection_context() def decrease(cls, user_id, num): num = cls.model.update(credit=cls.model.credit - num).where( cls.model.id == user_id).execute() if num == 0: raise LookupError("Tenant not found which is supposed to be there") @classmethod @DB.connection_context() def user_gateway(cls, tenant_id): hash_obj = hashlib.sha256(tenant_id.encode("utf-8")) return int(hash_obj.hexdigest(), 16)%len(settings.MINIO) class UserTenantService(CommonService): """Service class for managing user-tenant relationship operations. This class extends CommonService to handle the many-to-many relationship between users and tenants, managing user roles and tenant memberships. Attributes: model: The UserTenant model class for database operations. """ model = UserTenant @classmethod @DB.connection_context() def filter_by_id(cls, user_tenant_id): try: user_tenant = cls.model.select().where((cls.model.id == user_tenant_id) & (cls.model.status == StatusEnum.VALID.value)).get() return user_tenant except peewee.DoesNotExist: return None @classmethod @DB.connection_context() def save(cls, **kwargs): if "id" not in kwargs: kwargs["id"] = get_uuid() obj = cls.model(**kwargs).save(force_insert=True) return obj @classmethod @DB.connection_context() def get_by_tenant_id(cls, tenant_id): fields = [ cls.model.id, cls.model.user_id, cls.model.status, cls.model.role, User.nickname, User.email, User.avatar, User.is_authenticated, User.is_active, User.is_anonymous, User.status, User.update_date, User.is_superuser] return list(cls.model.select(*fields) .join(User, on=((cls.model.user_id == User.id) & (cls.model.status == StatusEnum.VALID.value) & (cls.model.role != UserTenantRole.OWNER))) .where(cls.model.tenant_id == tenant_id) .dicts()) @classmethod @DB.connection_context() def get_tenants_by_user_id(cls, user_id): fields = [ cls.model.tenant_id, cls.model.role, User.nickname, User.email, User.avatar, User.update_date ] return list(cls.model.select(*fields) .join(User, on=((cls.model.tenant_id == User.id) & (UserTenant.user_id == user_id) & (UserTenant.status == StatusEnum.VALID.value))) .where(cls.model.status == StatusEnum.VALID.value).dicts()) @classmethod @DB.connection_context() def get_user_tenant_relation_by_user_id(cls, user_id): fields = [ cls.model.id, cls.model.user_id, cls.model.tenant_id, cls.model.role ] return list(cls.model.select(*fields).where(cls.model.user_id == user_id).dicts().dicts()) @classmethod @DB.connection_context() def get_num_members(cls, user_id: str): cnt_members = cls.model.select(peewee.fn.COUNT(cls.model.id)).where(cls.model.tenant_id == user_id).scalar() return cnt_members @classmethod @DB.connection_context() def filter_by_tenant_and_user_id(cls, tenant_id, user_id): try: user_tenant = cls.model.select().where( (cls.model.tenant_id == tenant_id) & (cls.model.status == StatusEnum.VALID.value) & (cls.model.user_id == user_id) ).first() return user_tenant except peewee.DoesNotExist: return None
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/services/evaluation_service.py
api/db/services/evaluation_service.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. # """ RAG Evaluation Service Provides functionality for evaluating RAG system performance including: - Dataset management - Test case management - Evaluation execution - Metrics computation - Configuration recommendations """ import asyncio import logging import queue import threading from typing import List, Dict, Any, Optional, Tuple from datetime import datetime from timeit import default_timer as timer from api.db.db_models import EvaluationDataset, EvaluationCase, EvaluationRun, EvaluationResult from api.db.services.common_service import CommonService from api.db.services.dialog_service import DialogService from common.misc_utils import get_uuid from common.time_utils import current_timestamp from common.constants import StatusEnum class EvaluationService(CommonService): """Service for managing RAG evaluations""" model = EvaluationDataset # ==================== Dataset Management ==================== @classmethod def create_dataset(cls, name: str, description: str, kb_ids: List[str], tenant_id: str, user_id: str) -> Tuple[bool, str]: """ Create a new evaluation dataset. Args: name: Dataset name description: Dataset description kb_ids: List of knowledge base IDs to evaluate against tenant_id: Tenant ID user_id: User ID who creates the dataset Returns: (success, dataset_id or error_message) """ try: timestamp= current_timestamp() dataset_id = get_uuid() dataset = { "id": dataset_id, "tenant_id": tenant_id, "name": name, "description": description, "kb_ids": kb_ids, "created_by": user_id, "create_time": timestamp, "update_time": timestamp, "status": StatusEnum.VALID.value } if not EvaluationDataset.create(**dataset): return False, "Failed to create dataset" return True, dataset_id except Exception as e: logging.error(f"Error creating evaluation dataset: {e}") return False, str(e) @classmethod def get_dataset(cls, dataset_id: str) -> Optional[Dict[str, Any]]: """Get dataset by ID""" try: dataset = EvaluationDataset.get_by_id(dataset_id) if dataset: return dataset.to_dict() return None except Exception as e: logging.error(f"Error getting dataset {dataset_id}: {e}") return None @classmethod def list_datasets(cls, tenant_id: str, user_id: str, page: int = 1, page_size: int = 20) -> Dict[str, Any]: """List datasets for a tenant""" try: query = EvaluationDataset.select().where( (EvaluationDataset.tenant_id == tenant_id) & (EvaluationDataset.status == StatusEnum.VALID.value) ).order_by(EvaluationDataset.create_time.desc()) total = query.count() datasets = query.paginate(page, page_size) return { "total": total, "datasets": [d.to_dict() for d in datasets] } except Exception as e: logging.error(f"Error listing datasets: {e}") return {"total": 0, "datasets": []} @classmethod def update_dataset(cls, dataset_id: str, **kwargs) -> bool: """Update dataset""" try: kwargs["update_time"] = current_timestamp() return EvaluationDataset.update(**kwargs).where( EvaluationDataset.id == dataset_id ).execute() > 0 except Exception as e: logging.error(f"Error updating dataset {dataset_id}: {e}") return False @classmethod def delete_dataset(cls, dataset_id: str) -> bool: """Soft delete dataset""" try: return EvaluationDataset.update( status=StatusEnum.INVALID.value, update_time=current_timestamp() ).where(EvaluationDataset.id == dataset_id).execute() > 0 except Exception as e: logging.error(f"Error deleting dataset {dataset_id}: {e}") return False # ==================== Test Case Management ==================== @classmethod def add_test_case(cls, dataset_id: str, question: str, reference_answer: Optional[str] = None, relevant_doc_ids: Optional[List[str]] = None, relevant_chunk_ids: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None) -> Tuple[bool, str]: """ Add a test case to a dataset. Args: dataset_id: Dataset ID question: Test question reference_answer: Optional ground truth answer relevant_doc_ids: Optional list of relevant document IDs relevant_chunk_ids: Optional list of relevant chunk IDs metadata: Optional additional metadata Returns: (success, case_id or error_message) """ try: case_id = get_uuid() case = { "id": case_id, "dataset_id": dataset_id, "question": question, "reference_answer": reference_answer, "relevant_doc_ids": relevant_doc_ids, "relevant_chunk_ids": relevant_chunk_ids, "metadata": metadata, "create_time": current_timestamp() } if not EvaluationCase.create(**case): return False, "Failed to create test case" return True, case_id except Exception as e: logging.error(f"Error adding test case: {e}") return False, str(e) @classmethod def get_test_cases(cls, dataset_id: str) -> List[Dict[str, Any]]: """Get all test cases for a dataset""" try: cases = EvaluationCase.select().where( EvaluationCase.dataset_id == dataset_id ).order_by(EvaluationCase.create_time) return [c.to_dict() for c in cases] except Exception as e: logging.error(f"Error getting test cases for dataset {dataset_id}: {e}") return [] @classmethod def delete_test_case(cls, case_id: str) -> bool: """Delete a test case""" try: return EvaluationCase.delete().where( EvaluationCase.id == case_id ).execute() > 0 except Exception as e: logging.error(f"Error deleting test case {case_id}: {e}") return False @classmethod def import_test_cases(cls, dataset_id: str, cases: List[Dict[str, Any]]) -> Tuple[int, int]: """ Bulk import test cases from a list. Args: dataset_id: Dataset ID cases: List of test case dictionaries Returns: (success_count, failure_count) """ success_count = 0 failure_count = 0 for case_data in cases: success, _ = cls.add_test_case( dataset_id=dataset_id, question=case_data.get("question", ""), reference_answer=case_data.get("reference_answer"), relevant_doc_ids=case_data.get("relevant_doc_ids"), relevant_chunk_ids=case_data.get("relevant_chunk_ids"), metadata=case_data.get("metadata") ) if success: success_count += 1 else: failure_count += 1 return success_count, failure_count # ==================== Evaluation Execution ==================== @classmethod def start_evaluation(cls, dataset_id: str, dialog_id: str, user_id: str, name: Optional[str] = None) -> Tuple[bool, str]: """ Start an evaluation run. Args: dataset_id: Dataset ID dialog_id: Dialog configuration to evaluate user_id: User ID who starts the run name: Optional run name Returns: (success, run_id or error_message) """ try: # Get dialog configuration success, dialog = DialogService.get_by_id(dialog_id) if not success: return False, "Dialog not found" # Create evaluation run run_id = get_uuid() if not name: name = f"Evaluation Run {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" run = { "id": run_id, "dataset_id": dataset_id, "dialog_id": dialog_id, "name": name, "config_snapshot": dialog.to_dict(), "metrics_summary": None, "status": "RUNNING", "created_by": user_id, "create_time": current_timestamp(), "complete_time": None } if not EvaluationRun.create(**run): return False, "Failed to create evaluation run" # Execute evaluation asynchronously (in production, use task queue) # For now, we'll execute synchronously cls._execute_evaluation(run_id, dataset_id, dialog) return True, run_id except Exception as e: logging.error(f"Error starting evaluation: {e}") return False, str(e) @classmethod def _execute_evaluation(cls, run_id: str, dataset_id: str, dialog: Any): """ Execute evaluation for all test cases. This method runs the RAG pipeline for each test case and computes metrics. """ try: # Get all test cases test_cases = cls.get_test_cases(dataset_id) if not test_cases: EvaluationRun.update( status="FAILED", complete_time=current_timestamp() ).where(EvaluationRun.id == run_id).execute() return # Execute each test case results = [] for case in test_cases: result = cls._evaluate_single_case(run_id, case, dialog) if result: results.append(result) # Compute summary metrics metrics_summary = cls._compute_summary_metrics(results) # Update run status EvaluationRun.update( status="COMPLETED", metrics_summary=metrics_summary, complete_time=current_timestamp() ).where(EvaluationRun.id == run_id).execute() except Exception as e: logging.error(f"Error executing evaluation {run_id}: {e}") EvaluationRun.update( status="FAILED", complete_time=current_timestamp() ).where(EvaluationRun.id == run_id).execute() @classmethod def _evaluate_single_case(cls, run_id: str, case: Dict[str, Any], dialog: Any) -> Optional[Dict[str, Any]]: """ Evaluate a single test case. Args: run_id: Evaluation run ID case: Test case dictionary dialog: Dialog configuration Returns: Result dictionary or None if failed """ try: # Prepare messages messages = [{"role": "user", "content": case["question"]}] # Execute RAG pipeline start_time = timer() answer = "" retrieved_chunks = [] def _sync_from_async_gen(async_gen): result_queue: queue.Queue = queue.Queue() def runner(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) async def consume(): try: async for item in async_gen: result_queue.put(item) except Exception as e: result_queue.put(e) finally: result_queue.put(StopIteration) loop.run_until_complete(consume()) loop.close() threading.Thread(target=runner, daemon=True).start() while True: item = result_queue.get() if item is StopIteration: break if isinstance(item, Exception): raise item yield item def chat(dialog, messages, stream=True, **kwargs): from api.db.services.dialog_service import async_chat return _sync_from_async_gen(async_chat(dialog, messages, stream=stream, **kwargs)) for ans in chat(dialog, messages, stream=False): if isinstance(ans, dict): answer = ans.get("answer", "") retrieved_chunks = ans.get("reference", {}).get("chunks", []) break execution_time = timer() - start_time # Compute metrics metrics = cls._compute_metrics( question=case["question"], generated_answer=answer, reference_answer=case.get("reference_answer"), retrieved_chunks=retrieved_chunks, relevant_chunk_ids=case.get("relevant_chunk_ids"), dialog=dialog ) # Save result result_id = get_uuid() result = { "id": result_id, "run_id": run_id, "case_id": case["id"], "generated_answer": answer, "retrieved_chunks": retrieved_chunks, "metrics": metrics, "execution_time": execution_time, "token_usage": None, # TODO: Track token usage "create_time": current_timestamp() } EvaluationResult.create(**result) return result except Exception as e: logging.error(f"Error evaluating case {case.get('id')}: {e}") return None @classmethod def _compute_metrics(cls, question: str, generated_answer: str, reference_answer: Optional[str], retrieved_chunks: List[Dict[str, Any]], relevant_chunk_ids: Optional[List[str]], dialog: Any) -> Dict[str, float]: """ Compute evaluation metrics for a single test case. Returns: Dictionary of metric names to values """ metrics = {} # Retrieval metrics (if ground truth chunks provided) if relevant_chunk_ids: retrieved_ids = [c.get("chunk_id") for c in retrieved_chunks] metrics.update(cls._compute_retrieval_metrics(retrieved_ids, relevant_chunk_ids)) # Generation metrics if generated_answer: # Basic metrics metrics["answer_length"] = len(generated_answer) metrics["has_answer"] = 1.0 if generated_answer.strip() else 0.0 # TODO: Implement advanced metrics using LLM-as-judge # - Faithfulness (hallucination detection) # - Answer relevance # - Context relevance # - Semantic similarity (if reference answer provided) return metrics @classmethod def _compute_retrieval_metrics(cls, retrieved_ids: List[str], relevant_ids: List[str]) -> Dict[str, float]: """ Compute retrieval metrics. Args: retrieved_ids: List of retrieved chunk IDs relevant_ids: List of relevant chunk IDs (ground truth) Returns: Dictionary of retrieval metrics """ if not relevant_ids: return {} retrieved_set = set(retrieved_ids) relevant_set = set(relevant_ids) # Precision: proportion of retrieved that are relevant precision = len(retrieved_set & relevant_set) / len(retrieved_set) if retrieved_set else 0.0 # Recall: proportion of relevant that were retrieved recall = len(retrieved_set & relevant_set) / len(relevant_set) if relevant_set else 0.0 # F1 score f1 = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0.0 # Hit rate: whether any relevant chunk was retrieved hit_rate = 1.0 if (retrieved_set & relevant_set) else 0.0 # MRR (Mean Reciprocal Rank): position of first relevant chunk mrr = 0.0 for i, chunk_id in enumerate(retrieved_ids, 1): if chunk_id in relevant_set: mrr = 1.0 / i break return { "precision": precision, "recall": recall, "f1_score": f1, "hit_rate": hit_rate, "mrr": mrr } @classmethod def _compute_summary_metrics(cls, results: List[Dict[str, Any]]) -> Dict[str, Any]: """ Compute summary metrics across all test cases. Args: results: List of result dictionaries Returns: Summary metrics dictionary """ if not results: return {} # Aggregate metrics metric_sums = {} metric_counts = {} for result in results: metrics = result.get("metrics", {}) for key, value in metrics.items(): if isinstance(value, (int, float)): metric_sums[key] = metric_sums.get(key, 0) + value metric_counts[key] = metric_counts.get(key, 0) + 1 # Compute averages summary = { "total_cases": len(results), "avg_execution_time": sum(r.get("execution_time", 0) for r in results) / len(results) } for key in metric_sums: summary[f"avg_{key}"] = metric_sums[key] / metric_counts[key] return summary # ==================== Results & Analysis ==================== @classmethod def get_run_results(cls, run_id: str) -> Dict[str, Any]: """Get results for an evaluation run""" try: run = EvaluationRun.get_by_id(run_id) if not run: return {} results = EvaluationResult.select().where( EvaluationResult.run_id == run_id ).order_by(EvaluationResult.create_time) return { "run": run.to_dict(), "results": [r.to_dict() for r in results] } except Exception as e: logging.error(f"Error getting run results {run_id}: {e}") return {} @classmethod def get_recommendations(cls, run_id: str) -> List[Dict[str, Any]]: """ Analyze evaluation results and provide configuration recommendations. Args: run_id: Evaluation run ID Returns: List of recommendation dictionaries """ try: run = EvaluationRun.get_by_id(run_id) if not run or not run.metrics_summary: return [] metrics = run.metrics_summary recommendations = [] # Low precision: retrieving irrelevant chunks if metrics.get("avg_precision", 1.0) < 0.7: recommendations.append({ "issue": "Low Precision", "severity": "high", "description": "System is retrieving many irrelevant chunks", "suggestions": [ "Increase similarity_threshold to filter out less relevant chunks", "Enable reranking to improve chunk ordering", "Reduce top_k to return fewer chunks" ] }) # Low recall: missing relevant chunks if metrics.get("avg_recall", 1.0) < 0.7: recommendations.append({ "issue": "Low Recall", "severity": "high", "description": "System is missing relevant chunks", "suggestions": [ "Increase top_k to retrieve more chunks", "Lower similarity_threshold to be more inclusive", "Enable hybrid search (keyword + semantic)", "Check chunk size - may be too large or too small" ] }) # Slow response time if metrics.get("avg_execution_time", 0) > 5.0: recommendations.append({ "issue": "Slow Response Time", "severity": "medium", "description": f"Average response time is {metrics['avg_execution_time']:.2f}s", "suggestions": [ "Reduce top_k to retrieve fewer chunks", "Optimize embedding model selection", "Consider caching frequently asked questions" ] }) return recommendations except Exception as e: logging.error(f"Error generating recommendations for run {run_id}: {e}") return []
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/joint_services/user_account_service.py
api/db/joint_services/user_account_service.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 uuid from api.utils.api_utils import group_by from api.db import FileType, UserTenantRole from api.db.services.api_service import APITokenService, API4ConversationService from api.db.services.canvas_service import UserCanvasService from api.db.services.conversation_service import ConversationService from api.db.services.dialog_service import DialogService from api.db.services.document_service import DocumentService from api.db.services.file2document_service import File2DocumentService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.langfuse_service import TenantLangfuseService from api.db.services.llm_service import get_init_tenant_llm from api.db.services.file_service import FileService from api.db.services.mcp_server_service import MCPServerService from api.db.services.search_service import SearchService from api.db.services.task_service import TaskService from api.db.services.tenant_llm_service import TenantLLMService from api.db.services.user_canvas_version import UserCanvasVersionService from api.db.services.user_service import TenantService, UserService, UserTenantService from api.db.services.memory_service import MemoryService from memory.services.messages import MessageService from rag.nlp import search from common.constants import ActiveEnum from common import settings def create_new_user(user_info: dict) -> dict: """ Add a new user, and create tenant, tenant llm, file folder for new user. :param user_info: { "email": <example@example.com>, "nickname": <str, "name">, "password": <decrypted password>, "login_channel": <enum, "password">, "is_superuser": <bool, role == "admin">, } :return: { "success": <bool>, "user_info": <dict>, # if true, return user_info } """ # generate user_id and access_token for user user_id = uuid.uuid1().hex user_info['id'] = user_id user_info['access_token'] = uuid.uuid1().hex # construct tenant info tenant = { "id": user_id, "name": user_info["nickname"] + "‘s Kingdom", "llm_id": settings.CHAT_MDL, "embd_id": settings.EMBEDDING_MDL, "asr_id": settings.ASR_MDL, "parser_ids": settings.PARSERS, "img2txt_id": settings.IMAGE2TEXT_MDL, "rerank_id": settings.RERANK_MDL, } usr_tenant = { "tenant_id": user_id, "user_id": user_id, "invited_by": user_id, "role": UserTenantRole.OWNER, } # construct file folder info file_id = uuid.uuid1().hex file = { "id": file_id, "parent_id": file_id, "tenant_id": user_id, "created_by": user_id, "name": "/", "type": FileType.FOLDER.value, "size": 0, "location": "", } try: tenant_llm = get_init_tenant_llm(user_id) if not UserService.save(**user_info): return {"success": False} TenantService.insert(**tenant) UserTenantService.insert(**usr_tenant) TenantLLMService.insert_many(tenant_llm) FileService.insert(file) return { "success": True, "user_info": user_info, } except Exception as create_error: logging.exception(create_error) # rollback try: TenantService.delete_by_id(user_id) except Exception as e: logging.exception(e) try: u = UserTenantService.query(tenant_id=user_id) if u: UserTenantService.delete_by_id(u[0].id) except Exception as e: logging.exception(e) try: TenantLLMService.delete_by_tenant_id(user_id) except Exception as e: logging.exception(e) try: FileService.delete_by_id(file["id"]) except Exception as e: logging.exception(e) # delete user row finally try: UserService.delete_by_id(user_id) except Exception as e: logging.exception(e) # reraise raise create_error def delete_user_data(user_id: str) -> dict: # use user_id to delete usr = UserService.filter_by_id(user_id) if not usr: return {"success": False, "message": f"{user_id} can't be found."} # check is inactive and not admin if usr.is_active == ActiveEnum.ACTIVE.value: return {"success": False, "message": f"{user_id} is active and can't be deleted."} if usr.is_superuser: return {"success": False, "message": "Can't delete the super user."} # tenant info tenants = UserTenantService.get_user_tenant_relation_by_user_id(usr.id) owned_tenant = [t for t in tenants if t["role"] == UserTenantRole.OWNER.value] done_msg = '' try: # step1. delete owned tenant info if owned_tenant: done_msg += "Start to delete owned tenant.\n" tenant_id = owned_tenant[0]["tenant_id"] kb_ids = KnowledgebaseService.get_kb_ids(usr.id) # step1.1 delete dataset related file and info if kb_ids: # step1.1.1 delete files in storage, remove bucket for kb_id in kb_ids: if settings.STORAGE_IMPL.bucket_exists(kb_id): settings.STORAGE_IMPL.remove_bucket(kb_id) done_msg += f"- Removed {len(kb_ids)} dataset's buckets.\n" # step1.1.2 delete file and document info in db doc_ids = DocumentService.get_all_doc_ids_by_kb_ids(kb_ids) if doc_ids: doc_delete_res = DocumentService.delete_by_ids([i["id"] for i in doc_ids]) done_msg += f"- Deleted {doc_delete_res} document records.\n" task_delete_res = TaskService.delete_by_doc_ids([i["id"] for i in doc_ids]) done_msg += f"- Deleted {task_delete_res} task records.\n" file_ids = FileService.get_all_file_ids_by_tenant_id(usr.id) if file_ids: file_delete_res = FileService.delete_by_ids([f["id"] for f in file_ids]) done_msg += f"- Deleted {file_delete_res} file records.\n" if doc_ids or file_ids: file2doc_delete_res = File2DocumentService.delete_by_document_ids_or_file_ids( [i["id"] for i in doc_ids], [f["id"] for f in file_ids] ) done_msg += f"- Deleted {file2doc_delete_res} document-file relation records.\n" # step1.1.3 delete chunk in es r = settings.docStoreConn.delete({"kb_id": kb_ids}, search.index_name(tenant_id), kb_ids) done_msg += f"- Deleted {r} chunk records.\n" kb_delete_res = KnowledgebaseService.delete_by_ids(kb_ids) done_msg += f"- Deleted {kb_delete_res} dataset records.\n" # step1.1.4 delete agents agent_delete_res = delete_user_agents(usr.id) done_msg += f"- Deleted {agent_delete_res['agents_deleted_count']} agent, {agent_delete_res['version_deleted_count']} versions records.\n" # step1.1.5 delete dialogs dialog_delete_res = delete_user_dialogs(usr.id) done_msg += f"- Deleted {dialog_delete_res['dialogs_deleted_count']} dialogs, {dialog_delete_res['conversations_deleted_count']} conversations, {dialog_delete_res['api_token_deleted_count']} api tokens, {dialog_delete_res['api4conversation_deleted_count']} api4conversations.\n" # step1.1.6 delete mcp server mcp_delete_res = MCPServerService.delete_by_tenant_id(usr.id) done_msg += f"- Deleted {mcp_delete_res} MCP server.\n" # step1.1.7 delete search search_delete_res = SearchService.delete_by_tenant_id(usr.id) done_msg += f"- Deleted {search_delete_res} search records.\n" # step1.2 delete tenant_llm and tenant_langfuse llm_delete_res = TenantLLMService.delete_by_tenant_id(tenant_id) done_msg += f"- Deleted {llm_delete_res} tenant-LLM records.\n" langfuse_delete_res = TenantLangfuseService.delete_ty_tenant_id(tenant_id) done_msg += f"- Deleted {langfuse_delete_res} langfuse records.\n" # step1.3 delete memory and messages user_memory = MemoryService.get_by_tenant_id(tenant_id) if user_memory: for memory in user_memory: if MessageService.has_index(tenant_id, memory.id): MessageService.delete_index(tenant_id, memory.id) done_msg += " Deleted memory index." memory_delete_res = MemoryService.delete_by_ids([m.id for m in user_memory]) done_msg += f"Deleted {memory_delete_res} memory datasets." # step1.4 delete own tenant tenant_delete_res = TenantService.delete_by_id(tenant_id) done_msg += f"- Deleted {tenant_delete_res} tenant.\n" # step2 delete user-tenant relation if tenants: # step2.1 delete docs and files in joined team joined_tenants = [t for t in tenants if t["role"] == UserTenantRole.NORMAL.value] if joined_tenants: done_msg += "Start to delete data in joined tenants.\n" created_documents = DocumentService.get_all_docs_by_creator_id(usr.id) if created_documents: # step2.1.1 delete files doc_file_info = File2DocumentService.get_by_document_ids([d['id'] for d in created_documents]) created_files = FileService.get_by_ids([f['file_id'] for f in doc_file_info]) if created_files: # step2.1.1.1 delete file in storage for f in created_files: settings.STORAGE_IMPL.rm(f.parent_id, f.location) done_msg += f"- Deleted {len(created_files)} uploaded file.\n" # step2.1.1.2 delete file record file_delete_res = FileService.delete_by_ids([f.id for f in created_files]) done_msg += f"- Deleted {file_delete_res} file records.\n" # step2.1.2 delete document-file relation record file2doc_delete_res = File2DocumentService.delete_by_document_ids_or_file_ids( [d['id'] for d in created_documents], [f.id for f in created_files] ) done_msg += f"- Deleted {file2doc_delete_res} document-file relation records.\n" # step2.1.3 delete chunks doc_groups = group_by(created_documents, "tenant_id") kb_grouped_doc = {k: group_by(v, "kb_id") for k, v in doc_groups.items()} # chunks in {'tenant_id': {'kb_id': [{'id': doc_id}]}} structure chunk_delete_res = 0 kb_doc_info = {} for _tenant_id, kb_doc in kb_grouped_doc.items(): for _kb_id, docs in kb_doc.items(): chunk_delete_res += settings.docStoreConn.delete( {"doc_id": [d["id"] for d in docs]}, search.index_name(_tenant_id), _kb_id ) # record doc info if _kb_id in kb_doc_info.keys(): kb_doc_info[_kb_id]['doc_num'] += 1 kb_doc_info[_kb_id]['token_num'] += sum([d["token_num"] for d in docs]) kb_doc_info[_kb_id]['chunk_num'] += sum([d["chunk_num"] for d in docs]) else: kb_doc_info[_kb_id] = { 'doc_num': 1, 'token_num': sum([d["token_num"] for d in docs]), 'chunk_num': sum([d["chunk_num"] for d in docs]) } done_msg += f"- Deleted {chunk_delete_res} chunks.\n" # step2.1.4 delete tasks task_delete_res = TaskService.delete_by_doc_ids([d['id'] for d in created_documents]) done_msg += f"- Deleted {task_delete_res} tasks.\n" # step2.1.5 delete document record doc_delete_res = DocumentService.delete_by_ids([d['id'] for d in created_documents]) done_msg += f"- Deleted {doc_delete_res} documents.\n" # step2.1.6 update dataset doc&chunk&token cnt for kb_id, doc_num in kb_doc_info.items(): KnowledgebaseService.decrease_document_num_in_delete(kb_id, doc_num) # step2.2 delete relation user_tenant_delete_res = UserTenantService.delete_by_ids([t["id"] for t in tenants]) done_msg += f"- Deleted {user_tenant_delete_res} user-tenant records.\n" # step3 finally delete user user_delete_res = UserService.delete_by_id(usr.id) done_msg += f"- Deleted {user_delete_res} user.\nDelete done!" return {"success": True, "message": f"Successfully deleted user. Details:\n{done_msg}"} except Exception as e: logging.exception(e) return {"success": False, "message": "An internal error occurred during user deletion. Some operations may have completed.","details": done_msg} def delete_user_agents(user_id: str) -> dict: """ use user_id to delete :return: { "agents_deleted_count": 1, "version_deleted_count": 2 } """ agents_deleted_count, agents_version_deleted_count = 0, 0 user_agents = UserCanvasService.get_all_agents_by_tenant_ids([user_id], user_id) if user_agents: agents_version = UserCanvasVersionService.get_all_canvas_version_by_canvas_ids([a['id'] for a in user_agents]) agents_version_deleted_count = UserCanvasVersionService.delete_by_ids([v['id'] for v in agents_version]) agents_deleted_count = UserCanvasService.delete_by_ids([a['id'] for a in user_agents]) return { "agents_deleted_count": agents_deleted_count, "version_deleted_count": agents_version_deleted_count } def delete_user_dialogs(user_id: str) -> dict: """ use user_id to delete :return: { "dialogs_deleted_count": 1, "conversations_deleted_count": 1, "api_token_deleted_count": 2, "api4conversation_deleted_count": 2 } """ dialog_deleted_count, conversations_deleted_count, api_token_deleted_count, api4conversation_deleted_count = 0, 0, 0, 0 user_dialogs = DialogService.get_all_dialogs_by_tenant_id(user_id) if user_dialogs: # delete conversation conversations = ConversationService.get_all_conversation_by_dialog_ids([ud['id'] for ud in user_dialogs]) conversations_deleted_count = ConversationService.delete_by_ids([c['id'] for c in conversations]) # delete api token api_token_deleted_count = APITokenService.delete_by_tenant_id(user_id) # delete api for conversation api4conversation_deleted_count = API4ConversationService.delete_by_dialog_ids([ud['id'] for ud in user_dialogs]) # delete dialog at last dialog_deleted_count = DialogService.delete_by_ids([ud['id'] for ud in user_dialogs]) return { "dialogs_deleted_count": dialog_deleted_count, "conversations_deleted_count": conversations_deleted_count, "api_token_deleted_count": api_token_deleted_count, "api4conversation_deleted_count": api4conversation_deleted_count }
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/joint_services/memory_message_service.py
api/db/joint_services/memory_message_service.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 from typing import List from api.db.services.task_service import TaskService from common import settings from common.time_utils import current_timestamp, timestamp_to_date, format_iso_8601_to_ymd_hms from common.constants import MemoryType, LLMType from common.doc_store.doc_store_base import FusionExpr from common.misc_utils import get_uuid from api.db.db_utils import bulk_insert_into_db from api.db.db_models import Task from api.db.services.memory_service import MemoryService from api.db.services.tenant_llm_service import TenantLLMService from api.db.services.llm_service import LLMBundle from api.utils.memory_utils import get_memory_type_human from memory.services.messages import MessageService from memory.services.query import MsgTextQuery, get_vector from memory.utils.prompt_util import PromptAssembler from memory.utils.msg_util import get_json_result_from_llm_response from rag.utils.redis_conn import REDIS_CONN async def save_to_memory(memory_id: str, message_dict: dict): """ :param memory_id: :param message_dict: { "user_id": str, "agent_id": str, "session_id": str, "user_input": str, "agent_response": str } """ memory = MemoryService.get_by_memory_id(memory_id) if not memory: return False, f"Memory '{memory_id}' not found." tenant_id = memory.tenant_id extracted_content = await extract_by_llm( tenant_id, memory.llm_id, {"temperature": memory.temperature}, get_memory_type_human(memory.memory_type), message_dict.get("user_input", ""), message_dict.get("agent_response", "") ) if memory.memory_type != MemoryType.RAW.value else [] # if only RAW, no need to extract raw_message_id = REDIS_CONN.generate_auto_increment_id(namespace="memory") message_list = [{ "message_id": raw_message_id, "message_type": MemoryType.RAW.name.lower(), "source_id": 0, "memory_id": memory_id, "user_id": "", "agent_id": message_dict["agent_id"], "session_id": message_dict["session_id"], "content": f"User Input: {message_dict.get('user_input')}\nAgent Response: {message_dict.get('agent_response')}", "valid_at": timestamp_to_date(current_timestamp()), "invalid_at": None, "forget_at": None, "status": True }, *[{ "message_id": REDIS_CONN.generate_auto_increment_id(namespace="memory"), "message_type": content["message_type"], "source_id": raw_message_id, "memory_id": memory_id, "user_id": "", "agent_id": message_dict["agent_id"], "session_id": message_dict["session_id"], "content": content["content"], "valid_at": content["valid_at"], "invalid_at": content["invalid_at"] if content["invalid_at"] else None, "forget_at": None, "status": True } for content in extracted_content]] return await embed_and_save(memory, message_list) async def save_extracted_to_memory_only(memory_id: str, message_dict, source_message_id: int): memory = MemoryService.get_by_memory_id(memory_id) if not memory: return False, f"Memory '{memory_id}' not found." if memory.memory_type == MemoryType.RAW.value: return True, f"Memory '{memory_id}' don't need to extract." tenant_id = memory.tenant_id extracted_content = await extract_by_llm( tenant_id, memory.llm_id, {"temperature": memory.temperature}, get_memory_type_human(memory.memory_type), message_dict.get("user_input", ""), message_dict.get("agent_response", "") ) message_list = [{ "message_id": REDIS_CONN.generate_auto_increment_id(namespace="memory"), "message_type": content["message_type"], "source_id": source_message_id, "memory_id": memory_id, "user_id": "", "agent_id": message_dict["agent_id"], "session_id": message_dict["session_id"], "content": content["content"], "valid_at": content["valid_at"], "invalid_at": content["invalid_at"] if content["invalid_at"] else None, "forget_at": None, "status": True } for content in extracted_content] if not message_list: return True, "No memory extracted from raw message." return await embed_and_save(memory, message_list) async def extract_by_llm(tenant_id: str, llm_id: str, extract_conf: dict, memory_type: List[str], user_input: str, agent_response: str, system_prompt: str = "", user_prompt: str="") -> List[dict]: llm_type = TenantLLMService.llm_id2llm_type(llm_id) if not llm_type: raise RuntimeError(f"Unknown type of LLM '{llm_id}'") if not system_prompt: system_prompt = PromptAssembler.assemble_system_prompt({"memory_type": memory_type}) conversation_content = f"User Input: {user_input}\nAgent Response: {agent_response}" conversation_time = timestamp_to_date(current_timestamp()) user_prompts = [] if user_prompt: user_prompts.append({"role": "user", "content": user_prompt}) user_prompts.append({"role": "user", "content": f"Conversation: {conversation_content}\nConversation Time: {conversation_time}\nCurrent Time: {conversation_time}"}) else: user_prompts.append({"role": "user", "content": PromptAssembler.assemble_user_prompt(conversation_content, conversation_time, conversation_time)}) llm = LLMBundle(tenant_id, llm_type, llm_id) res = await llm.async_chat(system_prompt, user_prompts, extract_conf) res_json = get_json_result_from_llm_response(res) return [{ "content": extracted_content["content"], "valid_at": format_iso_8601_to_ymd_hms(extracted_content["valid_at"]), "invalid_at": format_iso_8601_to_ymd_hms(extracted_content["invalid_at"]) if extracted_content.get("invalid_at") else "", "message_type": message_type } for message_type, extracted_content_list in res_json.items() for extracted_content in extracted_content_list] async def embed_and_save(memory, message_list: list[dict]): embedding_model = LLMBundle(memory.tenant_id, llm_type=LLMType.EMBEDDING, llm_name=memory.embd_id) vector_list, _ = embedding_model.encode([msg["content"] for msg in message_list]) for idx, msg in enumerate(message_list): msg["content_embed"] = vector_list[idx] vector_dimension = len(vector_list[0]) if not MessageService.has_index(memory.tenant_id, memory.id): created = MessageService.create_index(memory.tenant_id, memory.id, vector_size=vector_dimension) if not created: return False, "Failed to create message index." new_msg_size = sum([MessageService.calculate_message_size(m) for m in message_list]) current_memory_size = get_memory_size_cache(memory.tenant_id, memory.id) if new_msg_size + current_memory_size > memory.memory_size: size_to_delete = current_memory_size + new_msg_size - memory.memory_size if memory.forgetting_policy == "FIFO": message_ids_to_delete, delete_size = MessageService.pick_messages_to_delete_by_fifo(memory.id, memory.tenant_id, size_to_delete) MessageService.delete_message({"message_id": message_ids_to_delete}, memory.tenant_id, memory.id) decrease_memory_size_cache(memory.id, delete_size) else: return False, "Failed to insert message into memory. Memory size reached limit and cannot decide which to delete." fail_cases = MessageService.insert_message(message_list, memory.tenant_id, memory.id) if fail_cases: return False, "Failed to insert message into memory. Details: " + "; ".join(fail_cases) increase_memory_size_cache(memory.id, new_msg_size) return True, "Message saved successfully." def query_message(filter_dict: dict, params: dict): """ :param filter_dict: { "memory_id": List[str], "agent_id": optional "session_id": optional } :param params: { "query": question str, "similarity_threshold": float, "keywords_similarity_weight": float, "top_n": int } """ memory_ids = filter_dict["memory_id"] memory_list = MemoryService.get_by_ids(memory_ids) if not memory_list: return [] condition_dict = {k: v for k, v in filter_dict.items() if v} uids = [memory.tenant_id for memory in memory_list] question = params["query"] question = question.strip() memory = memory_list[0] embd_model = LLMBundle(memory.tenant_id, llm_type=LLMType.EMBEDDING, llm_name=memory.embd_id) match_dense = get_vector(question, embd_model, similarity=params["similarity_threshold"]) match_text, _ = MsgTextQuery().question(question, min_match=params["similarity_threshold"]) keywords_similarity_weight = params.get("keywords_similarity_weight", 0.7) fusion_expr = FusionExpr("weighted_sum", params["top_n"], {"weights": ",".join([str(1 - keywords_similarity_weight), str(keywords_similarity_weight)])}) return MessageService.search_message(memory_ids, condition_dict, uids, [match_text, match_dense, fusion_expr], params["top_n"]) def init_message_id_sequence(): message_id_redis_key = "id_generator:memory" if REDIS_CONN.exist(message_id_redis_key): current_max_id = REDIS_CONN.get(message_id_redis_key) logging.info(f"No need to init message_id sequence, current max id is {current_max_id}.") else: max_id = 1 exist_memory_list = MemoryService.get_all_memory() if not exist_memory_list: REDIS_CONN.set(message_id_redis_key, max_id) else: max_id = MessageService.get_max_message_id( uid_list=[m.tenant_id for m in exist_memory_list], memory_ids=[m.id for m in exist_memory_list] ) REDIS_CONN.set(message_id_redis_key, max_id) logging.info(f"Init message_id sequence done, current max id is {max_id}.") def get_memory_size_cache(memory_id: str, uid: str): redis_key = f"memory_{memory_id}" if REDIS_CONN.exist(redis_key): return int(REDIS_CONN.get(redis_key)) else: memory_size_map = MessageService.calculate_memory_size( [memory_id], [uid] ) memory_size = memory_size_map.get(memory_id, 0) set_memory_size_cache(memory_id, memory_size) return memory_size def set_memory_size_cache(memory_id: str, size: int): redis_key = f"memory_{memory_id}" return REDIS_CONN.set(redis_key, size) def increase_memory_size_cache(memory_id: str, size: int): redis_key = f"memory_{memory_id}" return REDIS_CONN.incrby(redis_key, size) def decrease_memory_size_cache(memory_id: str, size: int): redis_key = f"memory_{memory_id}" return REDIS_CONN.decrby(redis_key, size) def init_memory_size_cache(): memory_list = MemoryService.get_all_memory() if not memory_list: logging.info("No memory found, no need to init memory size.") else: for m in memory_list: get_memory_size_cache(m.id, m.tenant_id) logging.info("Memory size cache init done.") def judge_system_prompt_is_default(system_prompt: str, memory_type: int|list[str]): memory_type_list = memory_type if isinstance(memory_type, list) else get_memory_type_human(memory_type) return system_prompt == PromptAssembler.assemble_system_prompt({"memory_type": memory_type_list}) async def queue_save_to_memory_task(memory_ids: list[str], message_dict: dict): """ :param memory_ids: :param message_dict: { "user_id": str, "agent_id": str, "session_id": str, "user_input": str, "agent_response": str } """ def new_task(_memory_id: str, _source_id: int): return { "id": get_uuid(), "doc_id": _memory_id, "task_type": "memory", "progress": 0.0, "digest": str(_source_id) } not_found_memory = [] failed_memory = [] for memory_id in memory_ids: memory = MemoryService.get_by_memory_id(memory_id) if not memory: not_found_memory.append(memory_id) continue raw_message_id = REDIS_CONN.generate_auto_increment_id(namespace="memory") raw_message = { "message_id": raw_message_id, "message_type": MemoryType.RAW.name.lower(), "source_id": 0, "memory_id": memory_id, "user_id": "", "agent_id": message_dict["agent_id"], "session_id": message_dict["session_id"], "content": f"User Input: {message_dict.get('user_input')}\nAgent Response: {message_dict.get('agent_response')}", "valid_at": timestamp_to_date(current_timestamp()), "invalid_at": None, "forget_at": None, "status": True } res, msg = await embed_and_save(memory, [raw_message]) if not res: failed_memory.append({"memory_id": memory_id, "fail_msg": msg}) continue task = new_task(memory_id, raw_message_id) bulk_insert_into_db(Task, [task], replace_on_conflict=True) task_message = { "id": task["id"], "task_id": task["id"], "task_type": task["task_type"], "memory_id": memory_id, "source_id": raw_message_id, "message_dict": message_dict } if not REDIS_CONN.queue_product(settings.get_svr_queue_name(priority=0), message=task_message): failed_memory.append({"memory_id": memory_id, "fail_msg": "Can't access Redis."}) error_msg = "" if not_found_memory: error_msg = f"Memory {not_found_memory} not found." if failed_memory: error_msg += "".join([f"Memory {fm['memory_id']} failed. Detail: {fm['fail_msg']}" for fm in failed_memory]) if error_msg: return False, error_msg return True, "All add to task." async def handle_save_to_memory_task(task_param: dict): """ :param task_param: { "id": task_id "memory_id": id "source_id": id "message_dict": { "user_id": str, "agent_id": str, "session_id": str, "user_input": str, "agent_response": str } } """ _, task = TaskService.get_by_id(task_param["id"]) if not task: return False, f"Task {task_param['id']} is not found." if task.progress == -1: return False, f"Task {task_param['id']} is already failed." now_time = current_timestamp() TaskService.update_by_id(task_param["id"], {"begin_at": timestamp_to_date(now_time)}) memory_id = task_param["memory_id"] source_id = task_param["source_id"] message_dict = task_param["message_dict"] success, msg = await save_extracted_to_memory_only(memory_id, message_dict, source_id) if success: TaskService.update_progress(task.id, {"progress": 1.0, "progress_msg": msg}) return True, msg logging.error(msg) TaskService.update_progress(task.id, {"progress": -1, "progress_msg": None}) return False, msg
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/db/joint_services/__init__.py
api/db/joint_services/__init__.py
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/validation_utils.py
api/utils/validation_utils.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 collections import Counter import string from typing import Annotated, Any, Literal from uuid import UUID from quart import Request from pydantic import ( BaseModel, ConfigDict, Field, StringConstraints, ValidationError, field_validator, model_validator, ) from pydantic_core import PydanticCustomError from werkzeug.exceptions import BadRequest, UnsupportedMediaType from api.constants import DATASET_NAME_LIMIT async def validate_and_parse_json_request(request: Request, validator: type[BaseModel], *, extras: dict[str, Any] | None = None, exclude_unset: bool = False) -> tuple[dict[str, Any] | None, str | None]: """ Validates and parses JSON requests through a multi-stage validation pipeline. Implements a four-stage validation process: 1. Content-Type verification (must be application/json) 2. JSON syntax validation 3. Payload structure type checking 4. Pydantic model validation with error formatting Args: request (Request): Flask request object containing HTTP payload validator (type[BaseModel]): Pydantic model class for data validation extras (dict[str, Any] | None): Additional fields to merge into payload before validation. These fields will be removed from the final output exclude_unset (bool): Whether to exclude fields that have not been explicitly set Returns: tuple[Dict[str, Any] | None, str | None]: - First element: - Validated dictionary on success - None on validation failure - Second element: - None on success - Diagnostic error message on failure Raises: UnsupportedMediaType: When Content-Type header is not application/json BadRequest: For structural JSON syntax errors ValidationError: When payload violates Pydantic schema rules Examples: >>> validate_and_parse_json_request(valid_request, DatasetSchema) ({"name": "Dataset1", "format": "csv"}, None) >>> validate_and_parse_json_request(xml_request, DatasetSchema) (None, "Unsupported content type: Expected application/json, got text/xml") >>> validate_and_parse_json_request(bad_json_request, DatasetSchema) (None, "Malformed JSON syntax: Missing commas/brackets or invalid encoding") Notes: 1. Validation Priority: - Content-Type verification precedes JSON parsing - Structural validation occurs before schema validation 2. Extra fields added via `extras` parameter are automatically removed from the final output after validation """ try: payload = await request.get_json() or {} except UnsupportedMediaType: return None, f"Unsupported content type: Expected application/json, got {request.content_type}" except BadRequest: return None, "Malformed JSON syntax: Missing commas/brackets or invalid encoding" if not isinstance(payload, dict): return None, f"Invalid request payload: expected object, got {type(payload).__name__}" try: if extras is not None: payload.update(extras) validated_request = validator(**payload) except ValidationError as e: return None, format_validation_error_message(e) parsed_payload = validated_request.model_dump(by_alias=True, exclude_unset=exclude_unset) if extras is not None: for key in list(parsed_payload.keys()): if key in extras: del parsed_payload[key] return parsed_payload, None def validate_and_parse_request_args(request: Request, validator: type[BaseModel], *, extras: dict[str, Any] | None = None) -> tuple[dict[str, Any] | None, str | None]: """ Validates and parses request arguments against a Pydantic model. This function performs a complete request validation workflow: 1. Extracts query parameters from the request 2. Merges with optional extra values (if provided) 3. Validates against the specified Pydantic model 4. Cleans the output by removing extra values 5. Returns either parsed data or an error message Args: request (Request): Web framework request object containing query parameters validator (type[BaseModel]): Pydantic model class for validation extras (dict[str, Any] | None): Optional additional values to include in validation but exclude from final output. Defaults to None. Returns: tuple[dict[str, Any] | None, str | None]: - First element: Validated/parsed arguments as dict if successful, None otherwise - Second element: Formatted error message if validation failed, None otherwise Behavior: - Query parameters are merged with extras before validation - Extras are automatically removed from the final output - All validation errors are formatted into a human-readable string Raises: TypeError: If validator is not a Pydantic BaseModel subclass Examples: Successful validation: >>> validate_and_parse_request_args(request, MyValidator) ({'param1': 'value'}, None) Failed validation: >>> validate_and_parse_request_args(request, MyValidator) (None, "param1: Field required") With extras: >>> validate_and_parse_request_args(request, MyValidator, extras={'internal_id': 123}) ({'param1': 'value'}, None) # internal_id removed from output Notes: - Uses request.args.to_dict() for Flask-compatible parameter extraction - Maintains immutability of original request arguments - Preserves type conversion from Pydantic validation """ args = request.args.to_dict(flat=True) try: if extras is not None: args.update(extras) validated_args = validator(**args) except ValidationError as e: return None, format_validation_error_message(e) parsed_args = validated_args.model_dump() if extras is not None: for key in list(parsed_args.keys()): if key in extras: del parsed_args[key] return parsed_args, None def format_validation_error_message(e: ValidationError) -> str: """ Formats validation errors into a standardized string format. Processes pydantic ValidationError objects to create human-readable error messages containing field locations, error descriptions, and input values. Args: e (ValidationError): The validation error instance containing error details Returns: str: Formatted error messages joined by newlines. Each line contains: - Field path (dot-separated) - Error message - Truncated input value (max 128 chars) Example: >>> try: ... UserModel(name=123, email="invalid") ... except ValidationError as e: ... print(format_validation_error_message(e)) Field: <name> - Message: <Input should be a valid string> - Value: <123> Field: <email> - Message: <value is not a valid email address> - Value: <invalid> """ error_messages = [] for error in e.errors(): field = ".".join(map(str, error["loc"])) msg = error["msg"] input_val = error["input"] input_str = str(input_val) if len(input_str) > 128: input_str = input_str[:125] + "..." error_msg = f"Field: <{field}> - Message: <{msg}> - Value: <{input_str}>" error_messages.append(error_msg) return "\n".join(error_messages) def normalize_str(v: Any) -> Any: """ Normalizes string values to a standard format while preserving non-string inputs. Performs the following transformations when input is a string: 1. Trims leading/trailing whitespace (str.strip()) 2. Converts to lowercase (str.lower()) Non-string inputs are returned unchanged, making this function safe for mixed-type processing pipelines. Args: v (Any): Input value to normalize. Accepts any Python object. Returns: Any: Normalized string if input was string-type, original value otherwise. Behavior Examples: String Input: " Admin " → "admin" Empty String: " " → "" (empty string) Non-String: - 123 → 123 - None → None - ["User"] → ["User"] Typical Use Cases: - Standardizing user input - Preparing data for case-insensitive comparison - Cleaning API parameters - Normalizing configuration values Edge Cases: - Unicode whitespace is handled by str.strip() - Locale-independent lowercasing (str.lower()) - Preserves falsy values (0, False, etc.) Example: >>> normalize_str(" ReadOnly ") 'readonly' >>> normalize_str(42) 42 """ if isinstance(v, str): stripped = v.strip() normalized = stripped.lower() return normalized return v def validate_uuid1_hex(v: Any) -> str: """ Validates and converts input to a UUID version 1 hexadecimal string. This function performs strict validation and normalization: 1. Accepts either UUID objects or UUID-formatted strings 2. Verifies the UUID is version 1 (time-based) 3. Returns the 32-character hexadecimal representation Args: v (Any): Input value to validate. Can be: - UUID object (must be version 1) - String in UUID format (e.g. "550e8400-e29b-41d4-a716-446655440000") Returns: str: 32-character lowercase hexadecimal string without hyphens Example: "550e8400e29b41d4a716446655440000" Raises: PydanticCustomError: With code "invalid_UUID1_format" when: - Input is not a UUID object or valid UUID string - UUID version is not 1 - String doesn't match UUID format Examples: Valid cases: >>> validate_uuid1_hex("550e8400-e29b-41d4-a716-446655440000") '550e8400e29b41d4a716446655440000' >>> validate_uuid1_hex(UUID('550e8400-e29b-41d4-a716-446655440000')) '550e8400e29b41d4a716446655440000' Invalid cases: >>> validate_uuid1_hex("not-a-uuid") # raises PydanticCustomError >>> validate_uuid1_hex(12345) # raises PydanticCustomError >>> validate_uuid1_hex(UUID(int=0)) # v4, raises PydanticCustomError Notes: - Uses Python's built-in UUID parser for format validation - Version check prevents accidental use of other UUID versions - Hyphens in input strings are automatically removed in output """ try: uuid_obj = UUID(v) if isinstance(v, str) else v if uuid_obj.version != 1: raise PydanticCustomError("invalid_UUID1_format", "Must be a UUID1 format") return uuid_obj.hex except (AttributeError, ValueError, TypeError): raise PydanticCustomError("invalid_UUID1_format", "Invalid UUID1 format") class Base(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) class RaptorConfig(Base): use_raptor: Annotated[bool, Field(default=False)] prompt: Annotated[ str, StringConstraints(strip_whitespace=True, min_length=1), Field( default="Please summarize the following paragraphs. Be careful with the numbers, do not make things up. Paragraphs as following:\n {cluster_content}\nThe above is the content you need to summarize." ), ] max_token: Annotated[int, Field(default=256, ge=1, le=2048)] threshold: Annotated[float, Field(default=0.1, ge=0.0, le=1.0)] max_cluster: Annotated[int, Field(default=64, ge=1, le=1024)] random_seed: Annotated[int, Field(default=0, ge=0)] auto_disable_for_structured_data: Annotated[bool, Field(default=True)] class GraphragConfig(Base): use_graphrag: Annotated[bool, Field(default=False)] entity_types: Annotated[list[str], Field(default_factory=lambda: ["organization", "person", "geo", "event", "category"])] method: Annotated[Literal["light", "general"], Field(default="light")] community: Annotated[bool, Field(default=False)] resolution: Annotated[bool, Field(default=False)] class ParserConfig(Base): auto_keywords: Annotated[int, Field(default=0, ge=0, le=32)] auto_questions: Annotated[int, Field(default=0, ge=0, le=10)] chunk_token_num: Annotated[int, Field(default=512, ge=1, le=2048)] delimiter: Annotated[str, Field(default=r"\n", min_length=1)] graphrag: Annotated[GraphragConfig, Field(default_factory=lambda: GraphragConfig(use_graphrag=False))] html4excel: Annotated[bool, Field(default=False)] layout_recognize: Annotated[str, Field(default="DeepDOC")] raptor: Annotated[RaptorConfig, Field(default_factory=lambda: RaptorConfig(use_raptor=False))] tag_kb_ids: Annotated[list[str], Field(default_factory=list)] topn_tags: Annotated[int, Field(default=1, ge=1, le=10)] filename_embd_weight: Annotated[float | None, Field(default=0.1, ge=0.0, le=1.0)] task_page_size: Annotated[int | None, Field(default=None, ge=1)] pages: Annotated[list[list[int]] | None, Field(default=None)] class CreateDatasetReq(Base): name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=DATASET_NAME_LIMIT), Field(...)] avatar: Annotated[str | None, Field(default=None, max_length=65535)] description: Annotated[str | None, Field(default=None, max_length=65535)] embedding_model: Annotated[str | None, Field(default=None, max_length=255, serialization_alias="embd_id")] permission: Annotated[Literal["me", "team"], Field(default="me", min_length=1, max_length=16)] chunk_method: Annotated[str | None, Field(default=None, serialization_alias="parser_id")] parse_type: Annotated[int | None, Field(default=None, ge=0, le=64)] pipeline_id: Annotated[str | None, Field(default=None, min_length=32, max_length=32, serialization_alias="pipeline_id")] parser_config: Annotated[ParserConfig | None, Field(default=None)] @field_validator("avatar", mode="after") @classmethod def validate_avatar_base64(cls, v: str | None) -> str | None: """ Validates Base64-encoded avatar string format and MIME type compliance. Implements a three-stage validation workflow: 1. MIME prefix existence check 2. MIME type format validation 3. Supported type verification Args: v (str): Raw avatar field value Returns: str: Validated Base64 string Raises: PydanticCustomError: For structural errors in these cases: - Missing MIME prefix header - Invalid MIME prefix format - Unsupported image MIME type Example: ```python # Valid case CreateDatasetReq(avatar="data:image/png;base64,iVBORw0KGg...") # Invalid cases CreateDatasetReq(avatar="image/jpeg;base64,...") # Missing 'data:' prefix CreateDatasetReq(avatar="data:video/mp4;base64,...") # Unsupported MIME type ``` """ if v is None: return v if "," in v: prefix, _ = v.split(",", 1) if not prefix.startswith("data:"): raise PydanticCustomError("format_invalid", "Invalid MIME prefix format. Must start with 'data:'") mime_type = prefix[5:].split(";")[0] supported_mime_types = ["image/jpeg", "image/png"] if mime_type not in supported_mime_types: raise PydanticCustomError("format_invalid", "Unsupported MIME type. Allowed: {supported_mime_types}", {"supported_mime_types": supported_mime_types}) return v else: raise PydanticCustomError("format_invalid", "Missing MIME prefix. Expected format: data:<mime>;base64,<data>") @field_validator("embedding_model", mode="before") @classmethod def normalize_embedding_model(cls, v: Any) -> Any: """Normalize embedding model string by stripping whitespace""" if isinstance(v, str): return v.strip() return v @field_validator("embedding_model", mode="after") @classmethod def validate_embedding_model(cls, v: str | None) -> str | None: """ Validates embedding model identifier format compliance. Validation pipeline: 1. Structural format verification 2. Component non-empty check 3. Value normalization Args: v (str): Raw model identifier Returns: str: Validated <model_name>@<provider> format Raises: PydanticCustomError: For these violations: - Missing @ separator - Empty model_name/provider - Invalid component structure Examples: Valid: "text-embedding-3-large@openai" Invalid: "invalid_model" (no @) Invalid: "@openai" (empty model_name) Invalid: "text-embedding-3-large@" (empty provider) """ if isinstance(v, str): if "@" not in v: raise PydanticCustomError("format_invalid", "Embedding model identifier must follow <model_name>@<provider> format") components = v.split("@", 1) if len(components) != 2 or not all(components): raise PydanticCustomError("format_invalid", "Both model_name and provider must be non-empty strings") model_name, provider = components if not model_name.strip() or not provider.strip(): raise PydanticCustomError("format_invalid", "Model name and provider cannot be whitespace-only strings") return v # @field_validator("permission", mode="before") # @classmethod # def normalize_permission(cls, v: Any) -> Any: # return normalize_str(v) @field_validator("parser_config", mode="before") @classmethod def normalize_empty_parser_config(cls, v: Any) -> Any: """ Normalizes empty parser configuration by converting empty dictionaries to None. This validator ensures consistent handling of empty parser configurations across the application by converting empty dicts to None values. Args: v (Any): Raw input value for the parser config field Returns: Any: Returns None if input is an empty dict, otherwise returns the original value Example: >>> normalize_empty_parser_config({}) None >>> normalize_empty_parser_config({"key": "value"}) {"key": "value"} """ if v == {}: return None return v @field_validator("parser_config", mode="after") @classmethod def validate_parser_config_json_length(cls, v: ParserConfig | None) -> ParserConfig | None: """ Validates serialized JSON length constraints for parser configuration. Implements a two-stage validation workflow: 1. Null check - bypass validation for empty configurations 2. Model serialization - convert Pydantic model to JSON string 3. Size verification - enforce maximum allowed payload size Args: v (ParserConfig | None): Raw parser configuration object Returns: ParserConfig | None: Validated configuration object Raises: PydanticCustomError: When serialized JSON exceeds 65,535 characters """ if v is None: return None if (json_str := v.model_dump_json()) and len(json_str) > 65535: raise PydanticCustomError("string_too_long", "Parser config exceeds size limit (max 65,535 characters). Current size: {actual}", {"actual": len(json_str)}) return v @field_validator("pipeline_id", mode="after") @classmethod def validate_pipeline_id(cls, v: str | None) -> str | None: """Validate pipeline_id as 32-char lowercase hex string if provided. Rules: - None or empty string: treat as None (not set) - Must be exactly length 32 - Must contain only hex digits (0-9a-fA-F); normalized to lowercase """ if v is None: return None if v == "": return None if len(v) != 32: raise PydanticCustomError("format_invalid", "pipeline_id must be 32 hex characters") if any(ch not in string.hexdigits for ch in v): raise PydanticCustomError("format_invalid", "pipeline_id must be hexadecimal") return v.lower() @model_validator(mode="after") def validate_parser_dependency(self) -> "CreateDatasetReq": """ Mixed conditional validation: - If parser_id is omitted (field not set): * If both parse_type and pipeline_id are omitted → default chunk_method = "naive" * If both parse_type and pipeline_id are provided → allow ingestion pipeline mode - If parser_id is provided (valid enum) → parse_type and pipeline_id must be None (disallow mixed usage) Raises: PydanticCustomError with code 'dependency_error' on violation. """ # Omitted chunk_method (not in fields) logic if self.chunk_method is None and "chunk_method" not in self.model_fields_set: # All three absent → default naive if self.parse_type is None and self.pipeline_id is None: object.__setattr__(self, "chunk_method", "naive") return self # parser_id omitted: require BOTH parse_type & pipeline_id present (no partial allowed) if self.parse_type is None or self.pipeline_id is None: missing = [] if self.parse_type is None: missing.append("parse_type") if self.pipeline_id is None: missing.append("pipeline_id") raise PydanticCustomError( "dependency_error", "parser_id omitted → required fields missing: {fields}", {"fields": ", ".join(missing)}, ) # Both provided → allow pipeline mode return self # parser_id provided (valid): MUST NOT have parse_type or pipeline_id if isinstance(self.chunk_method, str): if self.parse_type is not None or self.pipeline_id is not None: invalid = [] if self.parse_type is not None: invalid.append("parse_type") if self.pipeline_id is not None: invalid.append("pipeline_id") raise PydanticCustomError( "dependency_error", "parser_id provided → disallowed fields present: {fields}", {"fields": ", ".join(invalid)}, ) return self @field_validator("chunk_method", mode="wrap") @classmethod def validate_chunk_method(cls, v: Any, handler) -> Any: """Wrap validation to unify error messages, including type errors (e.g. list).""" allowed = {"naive", "book", "email", "laws", "manual", "one", "paper", "picture", "presentation", "qa", "table", "tag"} error_msg = "Input should be 'naive', 'book', 'email', 'laws', 'manual', 'one', 'paper', 'picture', 'presentation', 'qa', 'table' or 'tag'" # Omitted field: handler won't be invoked (wrap still gets value); None treated as explicit invalid if v is None: raise PydanticCustomError("literal_error", error_msg) try: # Run inner validation (type checking) result = handler(v) except Exception: raise PydanticCustomError("literal_error", error_msg) # After handler, enforce enumeration if not isinstance(result, str) or result == "" or result not in allowed: raise PydanticCustomError("literal_error", error_msg) return result class UpdateDatasetReq(CreateDatasetReq): dataset_id: Annotated[str, Field(...)] name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=DATASET_NAME_LIMIT), Field(default="")] pagerank: Annotated[int, Field(default=0, ge=0, le=100)] @field_validator("dataset_id", mode="before") @classmethod def validate_dataset_id(cls, v: Any) -> str: return validate_uuid1_hex(v) class DeleteReq(Base): ids: Annotated[list[str] | None, Field(...)] @field_validator("ids", mode="after") @classmethod def validate_ids(cls, v_list: list[str] | None) -> list[str] | None: """ Validates and normalizes a list of UUID strings with None handling. This post-processing validator performs: 1. None input handling (pass-through) 2. UUID version 1 validation for each list item 3. Duplicate value detection 4. Returns normalized UUID hex strings or None Args: v_list (list[str] | None): Input list that has passed initial validation. Either a list of UUID strings or None. Returns: list[str] | None: - None if input was None - List of normalized UUID hex strings otherwise: * 32-character lowercase * Valid UUID version 1 * Unique within list Raises: PydanticCustomError: With structured error details when: - "invalid_UUID1_format": Any string fails UUIDv1 validation - "duplicate_uuids": If duplicate IDs are detected Validation Rules: - None input returns None - Empty list returns empty list - All non-None items must be valid UUIDv1 - No duplicates permitted - Original order preserved Examples: Valid cases: >>> validate_ids(None) None >>> validate_ids([]) [] >>> validate_ids(["550e8400-e29b-41d4-a716-446655440000"]) ["550e8400e29b41d4a716446655440000"] Invalid cases: >>> validate_ids(["invalid"]) # raises PydanticCustomError(invalid_UUID1_format) >>> validate_ids(["550e...", "550e..."]) # raises PydanticCustomError(duplicate_uuids) Security Notes: - Validates UUID version to prevent version spoofing - Duplicate check prevents data injection - None handling maintains pipeline integrity """ if v_list is None: return None ids_list = [] for v in v_list: try: ids_list.append(validate_uuid1_hex(v)) except PydanticCustomError as e: raise e duplicates = [item for item, count in Counter(ids_list).items() if count > 1] if duplicates: duplicates_str = ", ".join(duplicates) raise PydanticCustomError("duplicate_uuids", "Duplicate ids: '{duplicate_ids}'", {"duplicate_ids": duplicates_str}) return ids_list class DeleteDatasetReq(DeleteReq): ... class BaseListReq(BaseModel): model_config = ConfigDict(extra="forbid") id: Annotated[str | None, Field(default=None)] name: Annotated[str | None, Field(default=None)] page: Annotated[int, Field(default=1, ge=1)] page_size: Annotated[int, Field(default=30, ge=1)] orderby: Annotated[Literal["create_time", "update_time"], Field(default="create_time")] desc: Annotated[bool, Field(default=True)] @field_validator("id", mode="before") @classmethod def validate_id(cls, v: Any) -> str: return validate_uuid1_hex(v) class ListDatasetReq(BaseListReq): ...
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/file_utils.py
api/utils/file_utils.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. # # Standard library imports import base64 import re import shutil import subprocess import sys import tempfile import threading from io import BytesIO import pdfplumber from PIL import Image # Local imports from api.constants import IMG_BASE64_PREFIX from api.db import FileType LOCK_KEY_pdfplumber = "global_shared_lock_pdfplumber" if LOCK_KEY_pdfplumber not in sys.modules: sys.modules[LOCK_KEY_pdfplumber] = threading.Lock() def filename_type(filename): filename = filename.lower() if re.match(r".*\.pdf$", filename): return FileType.PDF.value if re.match(r".*\.(msg|eml|doc|docx|ppt|pptx|yml|xml|htm|json|jsonl|ldjson|csv|txt|ini|xls|xlsx|wps|rtf|hlp|pages|numbers|key|md|mdx|py|js|java|c|cpp|h|php|go|ts|sh|cs|kt|html|sql)$", filename): return FileType.DOC.value if re.match(r".*\.(wav|flac|ape|alac|wavpack|wv|mp3|aac|ogg|vorbis|opus)$", filename): return FileType.AURAL.value if re.match(r".*\.(jpg|jpeg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|avif|apng|icon|ico|mpg|mpeg|avi|rm|rmvb|mov|wmv|asf|dat|asx|wvx|mpe|mpa|mp4|avi|mkv)$", filename): return FileType.VISUAL.value return FileType.OTHER.value def thumbnail_img(filename, blob): """ MySQL LongText max length is 65535 """ filename = filename.lower() if re.match(r".*\.pdf$", filename): with sys.modules[LOCK_KEY_pdfplumber]: pdf = pdfplumber.open(BytesIO(blob)) buffered = BytesIO() resolution = 32 img = None for _ in range(10): # https://github.com/jsvine/pdfplumber?tab=readme-ov-file#creating-a-pageimage-with-to_image pdf.pages[0].to_image(resolution=resolution).annotated.save(buffered, format="png") img = buffered.getvalue() if len(img) >= 64000 and resolution >= 2: resolution = resolution / 2 buffered = BytesIO() else: break pdf.close() return img elif re.match(r".*\.(jpg|jpeg|png|tif|gif|icon|ico|webp)$", filename): image = Image.open(BytesIO(blob)) image.thumbnail((30, 30)) buffered = BytesIO() image.save(buffered, format="png") return buffered.getvalue() elif re.match(r".*\.(ppt|pptx)$", filename): import aspose.pydrawing as drawing import aspose.slides as slides try: with slides.Presentation(BytesIO(blob)) as presentation: buffered = BytesIO() scale = 0.03 img = None for _ in range(10): # https://reference.aspose.com/slides/python-net/aspose.slides/slide/get_thumbnail/#float-float presentation.slides[0].get_thumbnail(scale, scale).save(buffered, drawing.imaging.ImageFormat.png) img = buffered.getvalue() if len(img) >= 64000: scale = scale / 2.0 buffered = BytesIO() else: break return img except Exception: pass return None def thumbnail(filename, blob): img = thumbnail_img(filename, blob) if img is not None: return IMG_BASE64_PREFIX + base64.b64encode(img).decode("utf-8") else: return "" def repair_pdf_with_ghostscript(input_bytes): if shutil.which("gs") is None: return input_bytes with tempfile.NamedTemporaryFile(suffix=".pdf") as temp_in, tempfile.NamedTemporaryFile(suffix=".pdf") as temp_out: temp_in.write(input_bytes) temp_in.flush() cmd = [ "gs", "-o", temp_out.name, "-sDEVICE=pdfwrite", "-dPDFSETTINGS=/prepress", temp_in.name, ] try: proc = subprocess.run(cmd, capture_output=True, text=True) if proc.returncode != 0: return input_bytes except Exception: return input_bytes temp_out.seek(0) repaired_bytes = temp_out.read() return repaired_bytes def read_potential_broken_pdf(blob): def try_open(blob): try: with pdfplumber.open(BytesIO(blob)) as pdf: if pdf.pages: return True except Exception: return False return False if try_open(blob): return blob repaired = repair_pdf_with_ghostscript(blob) if try_open(repaired): return repaired return blob def sanitize_path(raw_path: str | None) -> str: """Normalize and sanitize a user-provided path segment. - Converts backslashes to forward slashes - Strips leading/trailing slashes - Removes '.' and '..' segments - Restricts characters to A-Za-z0-9, underscore, dash, and '/' """ if not raw_path: return "" backslash_re = re.compile(r"[\\]+") unsafe_re = re.compile(r"[^A-Za-z0-9_\-/]") normalized = backslash_re.sub("/", raw_path) normalized = normalized.strip("/") parts = [seg for seg in normalized.split("/") if seg and seg not in (".", "..")] sanitized = "/".join(parts) sanitized = unsafe_re.sub("", sanitized) return sanitized
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/memory_utils.py
api/utils/memory_utils.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 typing import List from common.constants import MemoryType def format_ret_data_from_memory(memory): return { "id": memory.id, "name": memory.name, "avatar": memory.avatar, "tenant_id": memory.tenant_id, "owner_name": memory.owner_name if hasattr(memory, "owner_name") else None, "memory_type": get_memory_type_human(memory.memory_type), "storage_type": memory.storage_type, "embd_id": memory.embd_id, "llm_id": memory.llm_id, "permissions": memory.permissions, "description": memory.description, "memory_size": memory.memory_size, "forgetting_policy": memory.forgetting_policy, "temperature": memory.temperature, "system_prompt": memory.system_prompt, "user_prompt": memory.user_prompt, "create_time": memory.create_time, "create_date": memory.create_date, "update_time": memory.update_time, "update_date": memory.update_date } def get_memory_type_human(memory_type: int) -> List[str]: return [mem_type.name.lower() for mem_type in MemoryType if memory_type & mem_type.value] def calculate_memory_type(memory_type_name_list: List[str]) -> int: memory_type = 0 type_value_map = {mem_type.name.lower(): mem_type.value for mem_type in MemoryType} for mem_type in memory_type_name_list: if mem_type in type_value_map: memory_type |= type_value_map[mem_type] return memory_type
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/common.py
api/utils/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. # def string_to_bytes(string): return string if isinstance( string, bytes) else string.encode(encoding="utf-8") def bytes_to_string(byte): return byte.decode(encoding="utf-8")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/crypt.py
api/utils/crypt.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 base64 import os import sys from Cryptodome.PublicKey import RSA from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from common.file_utils import get_project_base_directory def crypt(line): """ decrypt(crypt(input_string)) == base64(input_string), which frontend and admin_client use. """ file_path = os.path.join(get_project_base_directory(), "conf", "public.pem") rsa_key = RSA.importKey(open(file_path).read(), "Welcome") cipher = Cipher_pkcs1_v1_5.new(rsa_key) password_base64 = base64.b64encode(line.encode('utf-8')).decode("utf-8") encrypted_password = cipher.encrypt(password_base64.encode()) return base64.b64encode(encrypted_password).decode('utf-8') def decrypt(line): file_path = os.path.join(get_project_base_directory(), "conf", "private.pem") rsa_key = RSA.importKey(open(file_path).read(), "Welcome") cipher = Cipher_pkcs1_v1_5.new(rsa_key) return cipher.decrypt(base64.b64decode(line), "Fail to decrypt password!").decode('utf-8') def decrypt2(crypt_text): from base64 import b64decode, b16decode from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5 from Crypto.PublicKey import RSA decode_data = b64decode(crypt_text) if len(decode_data) == 127: hex_fixed = '00' + decode_data.hex() decode_data = b16decode(hex_fixed.upper()) file_path = os.path.join(get_project_base_directory(), "conf", "private.pem") pem = open(file_path).read() rsa_key = RSA.importKey(pem, "Welcome") cipher = Cipher_PKCS1_v1_5.new(rsa_key) decrypt_text = cipher.decrypt(decode_data, None) return (b64decode(decrypt_text)).decode() if __name__ == "__main__": passwd = crypt(sys.argv[1]) print(passwd) print(decrypt(passwd))
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/web_utils.py
api/utils/web_utils.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 base64 import ipaddress import json import re import socket from urllib.parse import urlparse import aiosmtplib from email.mime.text import MIMEText from email.header import Header from common import settings from quart import render_template_string from api.utils.email_templates import EMAIL_TEMPLATES from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import staleness_of from selenium.webdriver.support.ui import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager OTP_LENGTH = 4 OTP_TTL_SECONDS = 5 * 60 # valid for 5 minutes ATTEMPT_LIMIT = 5 # maximum attempts ATTEMPT_LOCK_SECONDS = 30 * 60 # lock for 30 minutes RESEND_COOLDOWN_SECONDS = 60 # cooldown for 1 minute CONTENT_TYPE_MAP = { # Office "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "doc": "application/msword", "pdf": "application/pdf", "csv": "text/csv", "xls": "application/vnd.ms-excel", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", # Text/code "txt": "text/plain", "py": "text/plain", "js": "text/plain", "java": "text/plain", "c": "text/plain", "cpp": "text/plain", "h": "text/plain", "php": "text/plain", "go": "text/plain", "ts": "text/plain", "sh": "text/plain", "cs": "text/plain", "kt": "text/plain", "sql": "text/plain", # Web "md": "text/markdown", "markdown": "text/markdown", "mdx": "text/markdown", "htm": "text/html", "html": "text/html", "json": "application/json", # Image formats "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "bmp": "image/bmp", "tiff": "image/tiff", "tif": "image/tiff", "webp": "image/webp", "svg": "image/svg+xml", "ico": "image/x-icon", "avif": "image/avif", "heic": "image/heic", } def html2pdf( source: str, timeout: int = 2, install_driver: bool = True, print_options: dict = {}, ): result = __get_pdf_from_html(source, timeout, install_driver, print_options) return result def __send_devtools(driver, cmd, params={}): resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id url = driver.command_executor._url + resource body = json.dumps({"cmd": cmd, "params": params}) response = driver.command_executor._request("POST", url, body) if not response: raise Exception(response.get("value")) return response.get("value") def __get_pdf_from_html(path: str, timeout: int, install_driver: bool, print_options: dict): webdriver_options = Options() webdriver_prefs = {} webdriver_options.add_argument("--headless") webdriver_options.add_argument("--disable-gpu") webdriver_options.add_argument("--no-sandbox") webdriver_options.add_argument("--disable-dev-shm-usage") webdriver_options.experimental_options["prefs"] = webdriver_prefs webdriver_prefs["profile.default_content_settings"] = {"images": 2} if install_driver: service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=webdriver_options) else: driver = webdriver.Chrome(options=webdriver_options) driver.get(path) try: WebDriverWait(driver, timeout).until(staleness_of(driver.find_element(by=By.TAG_NAME, value="html"))) except TimeoutException: calculated_print_options = { "landscape": False, "displayHeaderFooter": False, "printBackground": True, "preferCSSPageSize": True, } calculated_print_options.update(print_options) result = __send_devtools(driver, "Page.printToPDF", calculated_print_options) driver.quit() return base64.b64decode(result["data"]) def is_private_ip(ip: str) -> bool: try: ip_obj = ipaddress.ip_address(ip) return ip_obj.is_private except ValueError: return False def is_valid_url(url: str) -> bool: if not re.match(r"(https?)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]", url): return False parsed_url = urlparse(url) hostname = parsed_url.hostname if not hostname: return False try: ip = socket.gethostbyname(hostname) if is_private_ip(ip): return False except socket.gaierror: return False return True def safe_json_parse(data: str | dict) -> dict: if isinstance(data, dict): return data try: return json.loads(data) if data else {} except (json.JSONDecodeError, TypeError): return {} def get_float(req: dict, key: str, default: float | int = 10.0) -> float: try: parsed = float(req.get(key, default)) return parsed if parsed > 0 else default except (TypeError, ValueError): return default async def send_email_html(to_email: str, subject: str, template_key: str, **context): body = await render_template_string(EMAIL_TEMPLATES.get(template_key), **context) msg = MIMEText(body, "plain", "utf-8") msg["Subject"] = Header(subject, "utf-8") msg["From"] = f"{settings.MAIL_DEFAULT_SENDER[0]} <{settings.MAIL_DEFAULT_SENDER[1]}>" msg["To"] = to_email smtp = aiosmtplib.SMTP( hostname=settings.MAIL_SERVER, port=settings.MAIL_PORT, use_tls=True, timeout=10, ) await smtp.connect() await smtp.login(settings.MAIL_USERNAME, settings.MAIL_PASSWORD) await smtp.send_message(msg) await smtp.quit() async def send_invite_email(to_email, invite_url, tenant_id, inviter): # Reuse the generic HTML sender with 'invite' template await send_email_html( to_email=to_email, subject="RAGFlow Invitation", template_key="invite", email=to_email, invite_url=invite_url, tenant_id=tenant_id, inviter=inviter, ) def otp_keys(email: str): email = (email or "").strip().lower() return ( f"otp:{email}", f"otp_attempts:{email}", f"otp_last_sent:{email}", f"otp_lock:{email}", ) def hash_code(code: str, salt: bytes) -> str: import hashlib import hmac return hmac.new(salt, (code or "").encode("utf-8"), hashlib.sha256).hexdigest() def captcha_key(email: str) -> str: return f"captcha:{email}"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/configs.py
api/utils/configs.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 io import base64 import pickle from api.utils.common import bytes_to_string, string_to_bytes from common.config_utils import get_base_config safe_module = { 'numpy', 'rag_flow' } class RestrictedUnpickler(pickle.Unpickler): def find_class(self, module, name): import importlib if module.split('.')[0] in safe_module: _module = importlib.import_module(module) return getattr(_module, name) # Forbid everything else. raise pickle.UnpicklingError("global '%s.%s' is forbidden" % (module, name)) def restricted_loads(src): """Helper function analogous to pickle.loads().""" return RestrictedUnpickler(io.BytesIO(src)).load() def serialize_b64(src, to_str=False): dest = base64.b64encode(pickle.dumps(src)) if not to_str: return dest else: return bytes_to_string(dest) def deserialize_b64(src): src = base64.b64decode( string_to_bytes(src) if isinstance( src, str) else src) use_deserialize_safe_module = get_base_config( 'use_deserialize_safe_module', False) if use_deserialize_safe_module: return restricted_loads(src) return pickle.loads(src)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/health_utils.py
api/utils/health_utils.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 datetime import datetime import json import os import requests from timeit import default_timer as timer from api.db.db_models import DB from rag.utils.redis_conn import REDIS_CONN from rag.utils.es_conn import ESConnection from rag.utils.infinity_conn import InfinityConnection from common import settings def _ok_nok(ok: bool) -> str: return "ok" if ok else "nok" def check_db() -> tuple[bool, dict]: st = timer() try: # lightweight probe; works for MySQL/Postgres DB.execute_sql("SELECT 1") return True, {"elapsed": f"{(timer() - st) * 1000.0:.1f}"} except Exception as e: return False, {"elapsed": f"{(timer() - st) * 1000.0:.1f}", "error": str(e)} def check_redis() -> tuple[bool, dict]: st = timer() try: ok = bool(REDIS_CONN.health()) return ok, {"elapsed": f"{(timer() - st) * 1000.0:.1f}"} except Exception as e: return False, {"elapsed": f"{(timer() - st) * 1000.0:.1f}", "error": str(e)} def check_doc_engine() -> tuple[bool, dict]: st = timer() try: meta = settings.docStoreConn.health() # treat any successful call as ok return True, {"elapsed": f"{(timer() - st) * 1000.0:.1f}", **(meta or {})} except Exception as e: return False, {"elapsed": f"{(timer() - st) * 1000.0:.1f}", "error": str(e)} def check_storage() -> tuple[bool, dict]: st = timer() try: settings.STORAGE_IMPL.health() return True, {"elapsed": f"{(timer() - st) * 1000.0:.1f}"} except Exception as e: return False, {"elapsed": f"{(timer() - st) * 1000.0:.1f}", "error": str(e)} def get_es_cluster_stats() -> dict: doc_engine = os.getenv('DOC_ENGINE', 'elasticsearch') if doc_engine != 'elasticsearch': raise Exception("Elasticsearch is not in use.") try: return { "status": "alive", "message": ESConnection().get_cluster_stats() } except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}", } def get_infinity_status(): doc_engine = os.getenv('DOC_ENGINE', 'elasticsearch') if doc_engine != 'infinity': raise Exception("Infinity is not in use.") try: return { "status": "alive", "message": InfinityConnection().health() } except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}", } def get_mysql_status(): try: cursor = DB.execute_sql("SHOW PROCESSLIST;") res_rows = cursor.fetchall() headers = ['id', 'user', 'host', 'db', 'command', 'time', 'state', 'info'] cursor.close() return { "status": "alive", "message": [dict(zip(headers, r)) for r in res_rows] } except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}", } def check_minio_alive(): start_time = timer() try: response = requests.get(f'http://{settings.MINIO["host"]}/minio/health/live') if response.status_code == 200: return {"status": "alive", "message": f"Confirm elapsed: {(timer() - start_time) * 1000.0:.1f} ms."} else: return {"status": "timeout", "message": f"Confirm elapsed: {(timer() - start_time) * 1000.0:.1f} ms."} except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}", } def get_redis_info(): try: return { "status": "alive", "message": REDIS_CONN.info() } except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}", } def check_ragflow_server_alive(): start_time = timer() try: url = f'http://{settings.HOST_IP}:{settings.HOST_PORT}/v1/system/ping' if '0.0.0.0' in url: url = url.replace('0.0.0.0', '127.0.0.1') response = requests.get(url) if response.status_code == 200: return {"status": "alive", "message": f"Confirm elapsed: {(timer() - start_time) * 1000.0:.1f} ms."} else: return {"status": "timeout", "message": f"Confirm elapsed: {(timer() - start_time) * 1000.0:.1f} ms."} except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}", } def check_task_executor_alive(): task_executor_heartbeats = {} try: task_executors = REDIS_CONN.smembers("TASKEXE") now = datetime.now().timestamp() for task_executor_id in task_executors: heartbeats = REDIS_CONN.zrangebyscore(task_executor_id, now - 60 * 30, now) heartbeats = [json.loads(heartbeat) for heartbeat in heartbeats] task_executor_heartbeats[task_executor_id] = heartbeats if task_executor_heartbeats: status = "alive" if any(task_executor_heartbeats.values()) else "timeout" return {"status": status, "message": task_executor_heartbeats} else: return {"status": "timeout", "message": "Not found any task executor."} except Exception as e: return { "status": "timeout", "message": f"error: {str(e)}" } def run_health_checks() -> tuple[dict, bool]: result: dict[str, str | dict] = {} db_ok, db_meta = check_db() result["db"] = _ok_nok(db_ok) if not db_ok: result.setdefault("_meta", {})["db"] = db_meta try: redis_ok, redis_meta = check_redis() result["redis"] = _ok_nok(redis_ok) if not redis_ok: result.setdefault("_meta", {})["redis"] = redis_meta except Exception: result["redis"] = "nok" try: doc_ok, doc_meta = check_doc_engine() result["doc_engine"] = _ok_nok(doc_ok) if not doc_ok: result.setdefault("_meta", {})["doc_engine"] = doc_meta except Exception: result["doc_engine"] = "nok" try: sto_ok, sto_meta = check_storage() result["storage"] = _ok_nok(sto_ok) if not sto_ok: result.setdefault("_meta", {})["storage"] = sto_meta except Exception: result["storage"] = "nok" all_ok = (result.get("db") == "ok") and (result.get("redis") == "ok") and (result.get("doc_engine") == "ok") and ( result.get("storage") == "ok") result["status"] = "ok" if all_ok else "nok" return result, all_ok
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/commands.py
api/utils/commands.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 base64 import click import re from quart import Quart from werkzeug.security import generate_password_hash from api.db.services import UserService @click.command('reset-password', help='Reset the account password.') @click.option('--email', prompt=True, help='The email address of the account whose password you need to reset') @click.option('--new-password', prompt=True, help='the new password.') @click.option('--password-confirm', prompt=True, help='the new password confirm.') def reset_password(email, new_password, password_confirm): if str(new_password).strip() != str(password_confirm).strip(): click.echo(click.style('sorry. The two passwords do not match.', fg='red')) return user = UserService.query(email=email) if not user: click.echo(click.style('sorry. The Email is not registered!.', fg='red')) return encode_password = base64.b64encode(new_password.encode('utf-8')).decode('utf-8') password_hash = generate_password_hash(encode_password) user_dict = { 'password': password_hash } UserService.update_user(user[0].id,user_dict) click.echo(click.style('Congratulations! Password has been reset.', fg='green')) @click.command('reset-email', help='Reset the account email.') @click.option('--email', prompt=True, help='The old email address of the account whose email you need to reset') @click.option('--new-email', prompt=True, help='the new email.') @click.option('--email-confirm', prompt=True, help='the new email confirm.') def reset_email(email, new_email, email_confirm): if str(new_email).strip() != str(email_confirm).strip(): click.echo(click.style('Sorry, new email and confirm email do not match.', fg='red')) return if str(new_email).strip() == str(email).strip(): click.echo(click.style('Sorry, new email and old email are the same.', fg='red')) return user = UserService.query(email=email) if not user: click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red')) return if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", new_email): click.echo(click.style('sorry. {} is not a valid email. '.format(new_email), fg='red')) return new_user = UserService.query(email=new_email) if new_user: click.echo(click.style('sorry. the account: [{}] is exist .'.format(new_email), fg='red')) return user_dict = { 'email': new_email } UserService.update_user(user[0].id,user_dict) click.echo(click.style('Congratulations!, email has been reset.', fg='green')) def register_commands(app: Quart): app.cli.add_command(reset_password) app.cli.add_command(reset_email)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/log_utils.py
api/utils/log_utils.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. #
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/__init__.py
api/utils/__init__.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 importlib def from_dict_hook(in_dict: dict): if "type" in in_dict and "data" in in_dict: if in_dict["module"] is None: return in_dict["data"] else: return getattr(importlib.import_module( in_dict["module"]), in_dict["type"])(**in_dict["data"]) else: return in_dict
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/base64_image.py
api/utils/base64_image.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. #
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/json_encode.py
api/utils/json_encode.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 datetime import json from enum import Enum, IntEnum from api.utils.common import string_to_bytes, bytes_to_string class BaseType: def to_dict(self): return dict([(k.lstrip("_"), v) for k, v in self.__dict__.items()]) def to_dict_with_type(self): def _dict(obj): module = None if issubclass(obj.__class__, BaseType): data = {} for attr, v in obj.__dict__.items(): k = attr.lstrip("_") data[k] = _dict(v) module = obj.__module__ elif isinstance(obj, (list, tuple)): data = [] for i, vv in enumerate(obj): data.append(_dict(vv)) elif isinstance(obj, dict): data = {} for _k, vv in obj.items(): data[_k] = _dict(vv) else: data = obj return {"type": obj.__class__.__name__, "data": data, "module": module} return _dict(self) class CustomJSONEncoder(json.JSONEncoder): def __init__(self, **kwargs): self._with_type = kwargs.pop("with_type", False) super().__init__(**kwargs) def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, datetime.date): return obj.strftime('%Y-%m-%d') elif isinstance(obj, datetime.timedelta): return str(obj) elif issubclass(type(obj), Enum) or issubclass(type(obj), IntEnum): return obj.value elif isinstance(obj, set): return list(obj) elif issubclass(type(obj), BaseType): if not self._with_type: return obj.to_dict() else: return obj.to_dict_with_type() elif isinstance(obj, type): return obj.__name__ else: return json.JSONEncoder.default(self, obj) def json_dumps(src, byte=False, indent=None, with_type=False): dest = json.dumps( src, indent=indent, cls=CustomJSONEncoder, with_type=with_type) if byte: dest = string_to_bytes(dest) return dest def json_loads(src, object_hook=None, object_pairs_hook=None): if isinstance(src, bytes): src = bytes_to_string(src) return json.loads(src, object_hook=object_hook, object_pairs_hook=object_pairs_hook)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/email_templates.py
api/utils/email_templates.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. # """ Reusable HTML email templates and registry. """ # Invitation email template INVITE_EMAIL_TMPL = """ Hi {{email}}, {{inviter}} has invited you to join their team (ID: {{tenant_id}}). Click the link below to complete your registration: {{invite_url}} If you did not request this, please ignore this email. """ # Password reset code template RESET_CODE_EMAIL_TMPL = """ Hello, Your password reset code is: {{ code }} This code will expire in {{ ttl_min }} minutes. """ # Template registry EMAIL_TEMPLATES = { "invite": INVITE_EMAIL_TMPL, "reset_code": RESET_CODE_EMAIL_TMPL, }
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/utils/api_utils.py
api/utils/api_utils.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 functools import inspect import json import logging import os import time from copy import deepcopy from functools import wraps from typing import Any import requests from quart import ( Response, jsonify, request ) from peewee import OperationalError from common.constants import ActiveEnum from api.db.db_models import APIToken from api.utils.json_encode import CustomJSONEncoder from common.mcp_tool_call_conn import MCPToolCallSession, close_multiple_mcp_toolcall_sessions from api.db.services.tenant_llm_service import LLMFactoriesService from common.connection_utils import timeout from common.constants import RetCode from common import settings requests.models.complexjson.dumps = functools.partial(json.dumps, cls=CustomJSONEncoder) async def _coerce_request_data() -> dict: """Fetch JSON body with sane defaults; fallback to form data.""" payload: Any = None last_error: Exception | None = None try: payload = await request.get_json(force=True, silent=True) except Exception as e: last_error = e payload = None if payload is None: try: form = await request.form payload = form.to_dict() except Exception as e: last_error = e payload = None if payload is None: if last_error is not None: raise last_error raise ValueError("No JSON body or form data found in request.") if isinstance(payload, dict): return payload or {} if isinstance(payload, str): raise AttributeError("'str' object has no attribute 'get'") raise TypeError(f"Unsupported request payload type: {type(payload)!r}") async def get_request_json(): return await _coerce_request_data() def serialize_for_json(obj): """ Recursively serialize objects to make them JSON serializable. Handles ModelMetaclass and other non-serializable objects. """ if hasattr(obj, "__dict__"): # For objects with __dict__, try to serialize their attributes try: return {key: serialize_for_json(value) for key, value in obj.__dict__.items() if not key.startswith("_")} except (AttributeError, TypeError): return str(obj) elif hasattr(obj, "__name__"): # For classes and metaclasses, return their name return f"<{obj.__module__}.{obj.__name__}>" if hasattr(obj, "__module__") else f"<{obj.__name__}>" elif isinstance(obj, (list, tuple)): return [serialize_for_json(item) for item in obj] elif isinstance(obj, dict): return {key: serialize_for_json(value) for key, value in obj.items()} elif isinstance(obj, (str, int, float, bool)) or obj is None: return obj else: # Fallback: convert to string representation return str(obj) def get_data_error_result(code=RetCode.DATA_ERROR, message="Sorry! Data missing!"): logging.exception(Exception(message)) result_dict = {"code": code, "message": message} response = {} for key, value in result_dict.items(): if value is None and key != "code": continue else: response[key] = value return jsonify(response) def server_error_response(e): # Quart invokes this handler outside the original except block, so we must pass exc_info manually. logging.error("Unhandled exception during request", exc_info=(type(e), e, e.__traceback__)) try: msg = repr(e).lower() if getattr(e, "code", None) == 401 or ("unauthorized" in msg) or ("401" in msg): return get_json_result(code=RetCode.UNAUTHORIZED, message=repr(e)) except Exception as ex: logging.warning(f"error checking authorization: {ex}") if len(e.args) > 1: try: serialized_data = serialize_for_json(e.args[1]) return get_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e.args[0]), data=serialized_data) except Exception: return get_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e.args[0]), data=None) if repr(e).find("index_not_found_exception") >= 0: return get_json_result(code=RetCode.EXCEPTION_ERROR, message="No chunk found, please upload file and parse it.") return get_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e)) def validate_request(*args, **kwargs): def process_args(input_arguments): no_arguments = [] error_arguments = [] for arg in args: if arg not in input_arguments: no_arguments.append(arg) for k, v in kwargs.items(): config_value = input_arguments.get(k, None) if config_value is None: no_arguments.append(k) elif isinstance(v, (tuple, list)): if config_value not in v: error_arguments.append((k, set(v))) elif config_value != v: error_arguments.append((k, v)) if no_arguments or error_arguments: error_string = "" if no_arguments: error_string += "required argument are missing: {}; ".format(",".join(no_arguments)) if error_arguments: error_string += "required argument values: {}".format(",".join(["{}={}".format(a[0], a[1]) for a in error_arguments])) return error_string return None def wrapper(func): @wraps(func) async def decorated_function(*_args, **_kwargs): errs = process_args(await _coerce_request_data()) if errs: return get_json_result(code=RetCode.ARGUMENT_ERROR, message=errs) if inspect.iscoroutinefunction(func): return await func(*_args, **_kwargs) return func(*_args, **_kwargs) return decorated_function return wrapper def not_allowed_parameters(*params): def decorator(func): async def wrapper(*args, **kwargs): input_arguments = await _coerce_request_data() for param in params: if param in input_arguments: return get_json_result(code=RetCode.ARGUMENT_ERROR, message=f"Parameter {param} isn't allowed") if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) return func(*args, **kwargs) return wrapper return decorator def active_required(func): @wraps(func) async def wrapper(*args, **kwargs): from api.db.services import UserService from api.apps import current_user user_id = current_user.id usr = UserService.filter_by_id(user_id) # check is_active if not usr or not usr.is_active == ActiveEnum.ACTIVE.value: return get_json_result(code=RetCode.FORBIDDEN, message="User isn't active, please activate first.") if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) return func(*args, **kwargs) return wrapper def get_json_result(code: RetCode = RetCode.SUCCESS, message="success", data=None): response = {"code": code, "message": message, "data": data} return jsonify(response) def apikey_required(func): @wraps(func) async def decorated_function(*args, **kwargs): token = request.headers.get("Authorization").split()[1] objs = APIToken.query(token=token) if not objs: return build_error_result(message="API-KEY is invalid!", code=RetCode.FORBIDDEN) kwargs["tenant_id"] = objs[0].tenant_id if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) return func(*args, **kwargs) return decorated_function def build_error_result(code=RetCode.FORBIDDEN, message="success"): response = {"code": code, "message": message} response = jsonify(response) response.status_code = code return response def construct_json_result(code: RetCode = RetCode.SUCCESS, message="success", data=None): if data is None: return jsonify({"code": code, "message": message}) else: return jsonify({"code": code, "message": message, "data": data}) def token_required(func): def get_tenant_id(**kwargs): if os.environ.get("DISABLE_SDK"): return False, get_json_result(data=False, message="`Authorization` can't be empty") authorization_str = request.headers.get("Authorization") if not authorization_str: return False, get_json_result(data=False, message="`Authorization` can't be empty") authorization_list = authorization_str.split() if len(authorization_list) < 2: return False, get_json_result(data=False, message="Please check your authorization format.") token = authorization_list[1] objs = APIToken.query(token=token) if not objs: return False, get_json_result(data=False, message="Authentication error: API key is invalid!", code=RetCode.AUTHENTICATION_ERROR) kwargs["tenant_id"] = objs[0].tenant_id return True, kwargs @wraps(func) def decorated_function(*args, **kwargs): e, kwargs = get_tenant_id(**kwargs) if not e: return kwargs return func(*args, **kwargs) @wraps(func) async def adecorated_function(*args, **kwargs): e, kwargs = get_tenant_id(**kwargs) if not e: return kwargs return await func(*args, **kwargs) if inspect.iscoroutinefunction(func): return adecorated_function return decorated_function def get_result(code=RetCode.SUCCESS, message="", data=None, total=None): """ Standard API response format: { "code": 0, "data": [...], # List or object, backward compatible "total": 47, # Optional field for pagination "message": "..." # Error or status message } """ response = {"code": code} if code == RetCode.SUCCESS: if data is not None: response["data"] = data if total is not None: response["total_datasets"] = total else: response["message"] = message or "Error" return jsonify(response) def get_error_data_result( message="Sorry! Data missing!", code=RetCode.DATA_ERROR, ): result_dict = {"code": code, "message": message} response = {} for key, value in result_dict.items(): if value is None and key != "code": continue else: response[key] = value return jsonify(response) def get_error_argument_result(message="Invalid arguments"): return get_result(code=RetCode.ARGUMENT_ERROR, message=message) def get_error_permission_result(message="Permission error"): return get_result(code=RetCode.PERMISSION_ERROR, message=message) def get_error_operating_result(message="Operating error"): return get_result(code=RetCode.OPERATING_ERROR, message=message) def generate_confirmation_token(): import secrets return "ragflow-" + secrets.token_urlsafe(32) def get_parser_config(chunk_method, parser_config): if not chunk_method: chunk_method = "naive" # Define default configurations for each chunking method base_defaults = { "table_context_size": 0, "image_context_size": 0, } key_mapping = { "naive": { "layout_recognize": "DeepDOC", "chunk_token_num": 512, "delimiter": "\n", "auto_keywords": 0, "auto_questions": 0, "html4excel": False, "topn_tags": 3, "raptor": { "use_raptor": True, "prompt": "Please summarize the following paragraphs. Be careful with the numbers, do not make things up. Paragraphs as following:\n {cluster_content}\nThe above is the content you need to summarize.", "max_token": 256, "threshold": 0.1, "max_cluster": 64, "random_seed": 0, }, "graphrag": { "use_graphrag": True, "entity_types": [ "organization", "person", "geo", "event", "category", ], "method": "light", }, }, "qa": {"raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}}, "tag": None, "resume": None, "manual": {"raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}}, "table": None, "paper": {"raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}}, "book": {"raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}}, "laws": {"raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}}, "presentation": {"raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}}, "one": None, "knowledge_graph": { "chunk_token_num": 8192, "delimiter": r"\n", "entity_types": ["organization", "person", "location", "event", "time"], "raptor": {"use_raptor": False}, "graphrag": {"use_graphrag": False}, }, "email": None, "picture": None, } default_config = key_mapping[chunk_method] # If no parser_config provided, return default merged with base defaults if not parser_config: if default_config is None: return deep_merge(base_defaults, {}) return deep_merge(base_defaults, default_config) # If parser_config is provided, merge with defaults to ensure required fields exist if default_config is None: return deep_merge(base_defaults, parser_config) # Ensure raptor and graph_rag fields have default values if not provided merged_config = deep_merge(base_defaults, default_config) merged_config = deep_merge(merged_config, parser_config) return merged_config def get_data_openai(id=None, created=None, model=None, prompt_tokens=0, completion_tokens=0, content=None, finish_reason=None, object="chat.completion", param=None, stream=False): total_tokens = prompt_tokens + completion_tokens if stream: return { "id": f"{id}", "object": "chat.completion.chunk", "model": model, "choices": [ { "delta": {"content": content}, "finish_reason": finish_reason, "index": 0, } ], } return { "id": f"{id}", "object": object, "created": int(time.time()) if created else None, "model": model, "param": param, "usage": { "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens, "completion_tokens_details": { "reasoning_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0, }, }, "choices": [ { "message": {"role": "assistant", "content": content}, "logprobs": None, "finish_reason": finish_reason, "index": 0, } ], } def check_duplicate_ids(ids, id_type="item"): """ Check for duplicate IDs in a list and return unique IDs and error messages. Args: ids (list): List of IDs to check for duplicates id_type (str): Type of ID for error messages (e.g., 'document', 'dataset', 'chunk') Returns: tuple: (unique_ids, error_messages) - unique_ids (list): List of unique IDs - error_messages (list): List of error messages for duplicate IDs """ id_count = {} duplicate_messages = [] # Count occurrences of each ID for id_value in ids: id_count[id_value] = id_count.get(id_value, 0) + 1 # Check for duplicates for id_value, count in id_count.items(): if count > 1: duplicate_messages.append(f"Duplicate {id_type} ids: {id_value}") # Return unique IDs and error messages return list(set(ids)), duplicate_messages def verify_embedding_availability(embd_id: str, tenant_id: str) -> tuple[bool, Response | None]: from api.db.services.llm_service import LLMService from api.db.services.tenant_llm_service import TenantLLMService """ Verifies availability of an embedding model for a specific tenant. Performs comprehensive verification through: 1. Identifier Parsing: Decomposes embd_id into name and factory components 2. System Verification: Checks model registration in LLMService 3. Tenant Authorization: Validates tenant-specific model assignments 4. Built-in Model Check: Confirms inclusion in predefined system models Args: embd_id (str): Unique identifier for the embedding model in format "model_name@factory" tenant_id (str): Tenant identifier for access control Returns: tuple[bool, Response | None]: - First element (bool): - True: Model is available and authorized - False: Validation failed - Second element contains: - None on success - Error detail dict on failure Raises: ValueError: When model identifier format is invalid OperationalError: When database connection fails (auto-handled) Examples: >>> verify_embedding_availability("text-embedding@openai", "tenant_123") (True, None) >>> verify_embedding_availability("invalid_model", "tenant_123") (False, {'code': 101, 'message': "Unsupported model: <invalid_model>"}) """ try: llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(embd_id) in_llm_service = bool(LLMService.query(llm_name=llm_name, fid=llm_factory, model_type="embedding")) tenant_llms = TenantLLMService.get_my_llms(tenant_id=tenant_id) is_tenant_model = any(llm["llm_name"] == llm_name and llm["llm_factory"] == llm_factory and llm["model_type"] == "embedding" for llm in tenant_llms) is_builtin_model = llm_factory == "Builtin" if not (is_builtin_model or is_tenant_model or in_llm_service): return False, get_error_argument_result(f"Unsupported model: <{embd_id}>") if not (is_builtin_model or is_tenant_model): return False, get_error_argument_result(f"Unauthorized model: <{embd_id}>") except OperationalError as e: logging.exception(e) return False, get_error_data_result(message="Database operation failed") return True, None def deep_merge(default: dict, custom: dict) -> dict: """ Recursively merges two dictionaries with priority given to `custom` values. Creates a deep copy of the `default` dictionary and iteratively merges nested dictionaries using a stack-based approach. Non-dict values in `custom` will completely override corresponding entries in `default`. Args: default (dict): Base dictionary containing default values. custom (dict): Dictionary containing overriding values. Returns: dict: New merged dictionary combining values from both inputs. Example: >>> from copy import deepcopy >>> default = {"a": 1, "nested": {"x": 10, "y": 20}} >>> custom = {"b": 2, "nested": {"y": 99, "z": 30}} >>> deep_merge(default, custom) {'a': 1, 'b': 2, 'nested': {'x': 10, 'y': 99, 'z': 30}} >>> deep_merge({"config": {"mode": "auto"}}, {"config": "manual"}) {'config': 'manual'} Notes: 1. Merge priority is always given to `custom` values at all nesting levels 2. Non-dict values (e.g. list, str) in `custom` will replace entire values in `default`, even if the original value was a dictionary 3. Time complexity: O(N) where N is total key-value pairs in `custom` 4. Recommended for configuration merging and nested data updates """ merged = deepcopy(default) stack = [(merged, custom)] while stack: base_dict, override_dict = stack.pop() for key, val in override_dict.items(): if key in base_dict and isinstance(val, dict) and isinstance(base_dict[key], dict): stack.append((base_dict[key], val)) else: base_dict[key] = val return merged def remap_dictionary_keys(source_data: dict, key_aliases: dict = None) -> dict: """ Transform dictionary keys using a configurable mapping schema. Args: source_data: Original dictionary to process key_aliases: Custom key transformation rules (Optional) When provided, overrides default key mapping Format: {<original_key>: <new_key>, ...} Returns: dict: New dictionary with transformed keys preserving original values Example: >>> input_data = {"old_key": "value", "another_field": 42} >>> remap_dictionary_keys(input_data, {"old_key": "new_key"}) {'new_key': 'value', 'another_field': 42} """ DEFAULT_KEY_MAP = { "chunk_num": "chunk_count", "doc_num": "document_count", "parser_id": "chunk_method", "embd_id": "embedding_model", } transformed_data = {} mapping = key_aliases or DEFAULT_KEY_MAP for original_key, value in source_data.items(): mapped_key = mapping.get(original_key, original_key) transformed_data[mapped_key] = value return transformed_data def group_by(list_of_dict, key): res = {} for item in list_of_dict: if item[key] in res.keys(): res[item[key]].append(item) else: res[item[key]] = [item] return res def get_mcp_tools(mcp_servers: list, timeout: float | int = 10) -> tuple[dict, str]: results = {} tool_call_sessions = [] try: for mcp_server in mcp_servers: server_key = mcp_server.id cached_tools = mcp_server.variables.get("tools", {}) tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables) tool_call_sessions.append(tool_call_session) try: tools = tool_call_session.get_tools(timeout) except Exception: tools = [] results[server_key] = [] for tool in tools: tool_dict = tool.model_dump() cached_tool = cached_tools.get(tool_dict["name"], {}) tool_dict["enabled"] = cached_tool.get("enabled", True) results[server_key].append(tool_dict) # PERF: blocking call to close sessions — consider moving to background thread or task queue close_multiple_mcp_toolcall_sessions(tool_call_sessions) return results, "" except Exception as e: return {}, str(e) async def is_strong_enough(chat_model, embedding_model): count = settings.STRONG_TEST_COUNT if not chat_model or not embedding_model: return if isinstance(count, int) and count <= 0: return @timeout(60, 2) async def _is_strong_enough(): nonlocal chat_model, embedding_model if embedding_model: await asyncio.wait_for( asyncio.to_thread(embedding_model.encode, ["Are you strong enough!?"]), timeout=10 ) if chat_model: res = await asyncio.wait_for( chat_model.async_chat("Nothing special.", [{"role": "user", "content": "Are you strong enough!?"}]), timeout=30 ) if "**ERROR**" in res: raise Exception(res) # Pressure test for GraphRAG task tasks = [ asyncio.create_task(_is_strong_enough()) for _ in range(count) ] try: await asyncio.gather(*tasks, return_exceptions=False) except Exception as e: logging.error(f"Pressure test failed: {e}") for t in tasks: t.cancel() await asyncio.gather(*tasks, return_exceptions=True) raise def get_allowed_llm_factories() -> list: factories = list(LLMFactoriesService.get_all(reverse=True, order_by="rank")) if settings.ALLOWED_LLM_FACTORIES is None: return factories return [factory for factory in factories if factory.name in settings.ALLOWED_LLM_FACTORIES]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/common/base64.py
api/common/base64.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 base64 def encode_to_base64(input_string): base64_encoded = base64.b64encode(input_string.encode('utf-8')) return base64_encoded.decode('utf-8')
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/common/exceptions.py
api/common/exceptions.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 AdminException(Exception): def __init__(self, message, code=400): super().__init__(message) self.type = "admin" self.code = code self.message = message class UserNotFoundError(AdminException): def __init__(self, username): super().__init__(f"User '{username}' not found", 404) class UserAlreadyExistsError(AdminException): def __init__(self, username): super().__init__(f"User '{username}' already exists", 409) class CannotDeleteAdminError(AdminException): def __init__(self): super().__init__("Cannot delete admin account", 403) class NotAdminError(AdminException): def __init__(self, username): super().__init__(f"User '{username}' is not admin", 403)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/api/common/check_team_permission.py
api/common/check_team_permission.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 api.db import TenantPermission from api.db.db_models import File, Knowledgebase from api.db.services.file_service import FileService from api.db.services.knowledgebase_service import KnowledgebaseService from api.db.services.user_service import TenantService def check_kb_team_permission(kb: dict | Knowledgebase, other: str) -> bool: kb = kb.to_dict() if isinstance(kb, Knowledgebase) else kb kb_tenant_id = kb["tenant_id"] if kb_tenant_id == other: return True if kb["permission"] != TenantPermission.TEAM: return False joined_tenants = TenantService.get_joined_tenants_by_user_id(other) return any(tenant["tenant_id"] == kb_tenant_id for tenant in joined_tenants) def check_file_team_permission(file: dict | File, other: str) -> bool: file = file.to_dict() if isinstance(file, File) else file file_tenant_id = file["tenant_id"] if file_tenant_id == other: return True file_id = file["id"] kb_ids = [kb_info["kb_id"] for kb_info in FileService.get_kb_id_by_file_id(file_id)] for kb_id in kb_ids: ok, kb = KnowledgebaseService.get_by_id(kb_id) if not ok: continue if check_kb_team_permission(kb, other): return True return False
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/token_utils.py
common/token_utils.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 tiktoken from common.file_utils import get_project_base_directory tiktoken_cache_dir = get_project_base_directory() os.environ["TIKTOKEN_CACHE_DIR"] = tiktoken_cache_dir # encoder = tiktoken.encoding_for_model("gpt-3.5-turbo") encoder = tiktoken.get_encoding("cl100k_base") def num_tokens_from_string(string: str) -> int: """Returns the number of tokens in a text string.""" try: code_list = encoder.encode(string) return len(code_list) except Exception: return 0 def total_token_count_from_response(resp): """ Extract token count from LLM response in various formats. Handles None responses and different response structures from various LLM providers. Returns 0 if token count cannot be determined. """ if resp is None: return 0 try: if hasattr(resp, "usage") and hasattr(resp.usage, "total_tokens"): return resp.usage.total_tokens except Exception: pass try: if hasattr(resp, "usage_metadata") and hasattr(resp.usage_metadata, "total_tokens"): return resp.usage_metadata.total_tokens except Exception: pass try: if hasattr(resp, "meta") and hasattr(resp.meta, "billed_units") and hasattr(resp.meta.billed_units, "input_tokens"): return resp.meta.billed_units.input_tokens except Exception: pass if isinstance(resp, dict) and 'usage' in resp and 'total_tokens' in resp['usage']: try: return resp["usage"]["total_tokens"] except Exception: pass if isinstance(resp, dict) and 'usage' in resp and 'input_tokens' in resp['usage'] and 'output_tokens' in resp['usage']: try: return resp["usage"]["input_tokens"] + resp["usage"]["output_tokens"] except Exception: pass if isinstance(resp, dict) and 'meta' in resp and 'tokens' in resp['meta'] and 'input_tokens' in resp['meta']['tokens'] and 'output_tokens' in resp['meta']['tokens']: try: return resp["meta"]["tokens"]["input_tokens"] + resp["meta"]["tokens"]["output_tokens"] except Exception: pass return 0 def truncate(string: str, max_len: int) -> str: """Returns truncated text if the length of text exceed max_len.""" return encoder.decode(encoder.encode(string)[:max_len])
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/metadata_utils.py
common/metadata_utils.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 logging from typing import Any, Callable, Dict import json_repair from rag.prompts.generator import gen_meta_filter def convert_conditions(metadata_condition): if metadata_condition is None: metadata_condition = {} op_mapping = { "is": "=", "not is": "≠" } return [ { "op": op_mapping.get(cond["comparison_operator"], cond["comparison_operator"]), "key": cond["name"], "value": cond["value"] } for cond in metadata_condition.get("conditions", []) ] def meta_filter(metas: dict, filters: list[dict], logic: str = "and"): doc_ids = set([]) def filter_out(v2docs, operator, value): ids = [] for input, docids in v2docs.items(): if operator in ["=", "≠", ">", "<", "≥", "≤"]: try: if isinstance(input, list): input = input[0] input = ast.literal_eval(input) value = ast.literal_eval(value) except Exception: pass if isinstance(input, str): input = input.lower() if isinstance(value, str): value = value.lower() matched = False try: if operator == "contains": matched = input in value if not isinstance(input, list) else all(i in value for i in input) elif operator == "not contains": matched = input not in value if not isinstance(input, list) else all(i not in value for i in input) elif operator == "in": matched = input in value if not isinstance(input, list) else all(i in value for i in input) elif operator == "not in": matched = input not in value if not isinstance(input, list) else all(i not in value for i in input) elif operator == "start with": matched = str(input).lower().startswith(str(value).lower()) if not isinstance(input, list) else "".join([str(i).lower() for i in input]).startswith(str(value).lower()) elif operator == "end with": matched = str(input).lower().endswith(str(value).lower()) if not isinstance(input, list) else "".join([str(i).lower() for i in input]).endswith(str(value).lower()) elif operator == "empty": matched = not input elif operator == "not empty": matched = bool(input) elif operator == "=": matched = input == value elif operator == "≠": matched = input != value elif operator == ">": matched = input > value elif operator == "<": matched = input < value elif operator == "≥": matched = input >= value elif operator == "≤": matched = input <= value except Exception: pass if matched: ids.extend(docids) return ids for k, v2docs in metas.items(): for f in filters: if k != f["key"]: continue ids = filter_out(v2docs, f["op"], f["value"]) if not doc_ids: doc_ids = set(ids) else: if logic == "and": doc_ids = doc_ids & set(ids) else: doc_ids = doc_ids | set(ids) if not doc_ids: return [] return list(doc_ids) async def apply_meta_data_filter( meta_data_filter: dict | None, metas: dict, question: str, chat_mdl: Any = None, base_doc_ids: list[str] | None = None, manual_value_resolver: Callable[[dict], dict] | None = None, ) -> list[str] | None: """ Apply metadata filtering rules and return the filtered doc_ids. meta_data_filter supports three modes: - auto: generate filter conditions via LLM (gen_meta_filter) - semi_auto: generate conditions using selected metadata keys only - manual: directly filter based on provided conditions Returns: list of doc_ids, ["-999"] when manual filters yield no result, or None when auto/semi_auto filters return empty. """ doc_ids = list(base_doc_ids) if base_doc_ids else [] if not meta_data_filter: return doc_ids method = meta_data_filter.get("method") if method == "auto": filters: dict = await gen_meta_filter(chat_mdl, metas, question) doc_ids.extend(meta_filter(metas, filters["conditions"], filters.get("logic", "and"))) if not doc_ids: return None elif method == "semi_auto": selected_keys = meta_data_filter.get("semi_auto", []) if selected_keys: filtered_metas = {key: metas[key] for key in selected_keys if key in metas} if filtered_metas: filters: dict = await gen_meta_filter(chat_mdl, filtered_metas, question) doc_ids.extend(meta_filter(metas, filters["conditions"], filters.get("logic", "and"))) if not doc_ids: return None elif method == "manual": filters = meta_data_filter.get("manual", []) if manual_value_resolver: filters = [manual_value_resolver(flt) for flt in filters] doc_ids.extend(meta_filter(metas, filters, meta_data_filter.get("logic", "and"))) if filters and not doc_ids: doc_ids = ["-999"] return doc_ids def dedupe_list(values: list) -> list: seen = set() deduped = [] for item in values: key = str(item) if key in seen: continue seen.add(key) deduped.append(item) return deduped def update_metadata_to(metadata, meta): if not meta: return metadata if isinstance(meta, str): try: meta = json_repair.loads(meta) except Exception: logging.error("Meta data format error.") return metadata if not isinstance(meta, dict): return metadata for k, v in meta.items(): if isinstance(v, list): v = [vv for vv in v if isinstance(vv, str)] if not v: continue v = dedupe_list(v) if not isinstance(v, list) and not isinstance(v, str): continue if k not in metadata: metadata[k] = v continue if isinstance(metadata[k], list): if isinstance(v, list): metadata[k].extend(v) else: metadata[k].append(v) metadata[k] = dedupe_list(metadata[k]) else: metadata[k] = v return metadata def metadata_schema(metadata: list|None) -> Dict[str, Any]: if not metadata: return {} properties = {} for item in metadata: key = item.get("key") if not key: continue prop_schema = { "description": item.get("description", "") } if "enum" in item and item["enum"]: prop_schema["enum"] = item["enum"] prop_schema["type"] = "string" properties[key] = prop_schema json_schema = { "type": "object", "properties": properties, } json_schema["additionalProperties"] = False return json_schema
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/file_utils.py
common/file_utils.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 PROJECT_BASE = os.getenv("RAG_PROJECT_BASE") or os.getenv("RAG_DEPLOY_BASE") def get_project_base_directory(*args): global PROJECT_BASE if PROJECT_BASE is None: PROJECT_BASE = os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, ) ) if args: return os.path.join(PROJECT_BASE, *args) return PROJECT_BASE def traversal_files(base): for root, ds, fs in os.walk(base): for f in fs: fullname = os.path.join(root, f) yield fullname
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/crypto_utils.py
common/crypto_utils.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 cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import padding from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import hashes class BaseCrypto: """Base class for cryptographic algorithms""" # Magic header to identify encrypted data ENCRYPTED_MAGIC = b'RAGF' def __init__(self, key, iv=None, block_size=16, key_length=32, iv_length=16): """ Initialize cryptographic algorithm Args: key: Encryption key iv: Initialization vector, automatically generated if None block_size: Block size key_length: Key length iv_length: Initialization vector length """ self.block_size = block_size self.key_length = key_length self.iv_length = iv_length # Normalize key self.key = self._normalize_key(key) self.iv = iv def _normalize_key(self, key): """Normalize key length""" if isinstance(key, str): key = key.encode('utf-8') # Use PBKDF2 for key derivation to ensure correct key length kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=self.key_length, salt=b"ragflow_crypto_salt", # Fixed salt to ensure consistent key derivation results iterations=100000, backend=default_backend() ) return kdf.derive(key) def encrypt(self, data): """ Encrypt data (template method) Args: data: Data to encrypt (bytes) Returns: Encrypted data (bytes), format: magic_header + iv + encrypted_data """ # Generate random IV iv = os.urandom(self.iv_length) if not self.iv else self.iv # Use PKCS7 padding padder = padding.PKCS7(self.block_size * 8).padder() padded_data = padder.update(data) + padder.finalize() # Delegate to subclass for specific encryption ciphertext = self._encrypt(padded_data, iv) # Return Magic Header + IV + encrypted data return self.ENCRYPTED_MAGIC + iv + ciphertext def decrypt(self, encrypted_data): """ Decrypt data (template method) Args: encrypted_data: Encrypted data (bytes) Returns: Decrypted data (bytes) """ # Check if data is encrypted by magic header if not encrypted_data.startswith(self.ENCRYPTED_MAGIC): # Not encrypted, return as-is return encrypted_data # Remove magic header encrypted_data = encrypted_data[len(self.ENCRYPTED_MAGIC):] # Separate IV and encrypted data iv = encrypted_data[:self.iv_length] ciphertext = encrypted_data[self.iv_length:] # Delegate to subclass for specific decryption padded_data = self._decrypt(ciphertext, iv) # Remove padding unpadder = padding.PKCS7(self.block_size * 8).unpadder() data = unpadder.update(padded_data) + unpadder.finalize() return data def _encrypt(self, padded_data, iv): """ Encrypt padded data with specific algorithm Args: padded_data: Padded data to encrypt iv: Initialization vector Returns: Encrypted data """ raise NotImplementedError("_encrypt method must be implemented by subclass") def _decrypt(self, ciphertext, iv): """ Decrypt ciphertext with specific algorithm Args: ciphertext: Ciphertext to decrypt iv: Initialization vector Returns: Decrypted padded data """ raise NotImplementedError("_decrypt method must be implemented by subclass") class AESCrypto(BaseCrypto): """Base class for AES cryptographic algorithm""" def __init__(self, key, iv=None, key_length=32): """ Initialize AES cryptographic algorithm Args: key: Encryption key iv: Initialization vector, automatically generated if None key_length: Key length (16 for AES-128, 32 for AES-256) """ super().__init__(key, iv, block_size=16, key_length=key_length, iv_length=16) def _encrypt(self, padded_data, iv): """AES encryption implementation""" # Create encryptor cipher = Cipher( algorithms.AES(self.key), modes.CBC(iv), backend=default_backend() ) encryptor = cipher.encryptor() # Encrypt data return encryptor.update(padded_data) + encryptor.finalize() def _decrypt(self, ciphertext, iv): """AES decryption implementation""" # Create decryptor cipher = Cipher( algorithms.AES(self.key), modes.CBC(iv), backend=default_backend() ) decryptor = cipher.decryptor() # Decrypt data return decryptor.update(ciphertext) + decryptor.finalize() class AES128CBC(AESCrypto): """AES-128-CBC cryptographic algorithm""" def __init__(self, key, iv=None): """ Initialize AES-128-CBC cryptographic algorithm Args: key: Encryption key iv: Initialization vector, automatically generated if None """ super().__init__(key, iv, key_length=16) class AES256CBC(AESCrypto): """AES-256-CBC cryptographic algorithm""" def __init__(self, key, iv=None): """ Initialize AES-256-CBC cryptographic algorithm Args: key: Encryption key iv: Initialization vector, automatically generated if None """ super().__init__(key, iv, key_length=32) class SM4CBC(BaseCrypto): """SM4-CBC cryptographic algorithm using cryptography library for better performance""" def __init__(self, key, iv=None): """ Initialize SM4-CBC cryptographic algorithm Args: key: Encryption key iv: Initialization vector, automatically generated if None """ super().__init__(key, iv, block_size=16, key_length=16, iv_length=16) def _encrypt(self, padded_data, iv): """SM4 encryption implementation using cryptography library""" # Create encryptor cipher = Cipher( algorithms.SM4(self.key), modes.CBC(iv), backend=default_backend() ) encryptor = cipher.encryptor() # Encrypt data return encryptor.update(padded_data) + encryptor.finalize() def _decrypt(self, ciphertext, iv): """SM4 decryption implementation using cryptography library""" # Create decryptor cipher = Cipher( algorithms.SM4(self.key), modes.CBC(iv), backend=default_backend() ) decryptor = cipher.decryptor() # Decrypt data return decryptor.update(ciphertext) + decryptor.finalize() class CryptoUtil: """Cryptographic utility class, using factory pattern to create cryptographic algorithm instances""" # Supported cryptographic algorithms mapping SUPPORTED_ALGORITHMS = { "aes-128-cbc": AES128CBC, "aes-256-cbc": AES256CBC, "sm4-cbc": SM4CBC } def __init__(self, algorithm="aes-256-cbc", key=None, iv=None): """ Initialize cryptographic utility Args: algorithm: Cryptographic algorithm, default is aes-256-cbc key: Encryption key, uses RAGFLOW_CRYPTO_KEY environment variable if None iv: Initialization vector, automatically generated if None """ if algorithm not in self.SUPPORTED_ALGORITHMS: raise ValueError(f"Unsupported algorithm: {algorithm}") if not key: raise ValueError("Encryption key not provided and RAGFLOW_CRYPTO_KEY environment variable not set") # Create cryptographic algorithm instance self.algorithm_name = algorithm self.crypto = self.SUPPORTED_ALGORITHMS[algorithm](key=key, iv=iv) def encrypt(self, data): """ Encrypt data Args: data: Data to encrypt (bytes) Returns: Encrypted data (bytes) """ # import time # start_time = time.time() encrypted = self.crypto.encrypt(data) # end_time = time.time() # logging.info(f"Encryption completed, data length: {len(data)} bytes, time: {(end_time - start_time)*1000:.2f} ms") return encrypted def decrypt(self, encrypted_data): """ Decrypt data Args: encrypted_data: Encrypted data (bytes) Returns: Decrypted data (bytes) """ # import time # start_time = time.time() decrypted = self.crypto.decrypt(encrypted_data) # end_time = time.time() # logging.info(f"Decryption completed, data length: {len(encrypted_data)} bytes, time: {(end_time - start_time)*1000:.2f} ms") return decrypted # Test code if __name__ == "__main__": # Test AES encryption crypto = CryptoUtil(algorithm="aes-256-cbc", key="test_key_123456") test_data = b"Hello, RAGFlow! This is a test for encryption." encrypted = crypto.encrypt(test_data) decrypted = crypto.decrypt(encrypted) print("AES Test:") print(f"Original: {test_data}") print(f"Encrypted: {encrypted}") print(f"Decrypted: {decrypted}") print(f"Success: {test_data == decrypted}") print() # Test SM4 encryption try: crypto_sm4 = CryptoUtil(algorithm="sm4-cbc", key="test_key_123456") encrypted_sm4 = crypto_sm4.encrypt(test_data) decrypted_sm4 = crypto_sm4.decrypt(encrypted_sm4) print("SM4 Test:") print(f"Original: {test_data}") print(f"Encrypted: {encrypted_sm4}") print(f"Decrypted: {decrypted_sm4}") print(f"Success: {test_data == decrypted_sm4}") except Exception as e: print(f"SM4 Test Failed: {e}") import traceback traceback.print_exc() # Test with specific algorithm classes directly print("\nDirect Algorithm Class Test:") # Test AES-128-CBC aes128 = AES128CBC(key="test_key_123456") encrypted_aes128 = aes128.encrypt(test_data) decrypted_aes128 = aes128.decrypt(encrypted_aes128) print(f"AES-128-CBC test: {'passed' if decrypted_aes128 == test_data else 'failed'}") # Test AES-256-CBC aes256 = AES256CBC(key="test_key_123456") encrypted_aes256 = aes256.encrypt(test_data) decrypted_aes256 = aes256.decrypt(encrypted_aes256) print(f"AES-256-CBC test: {'passed' if decrypted_aes256 == test_data else 'failed'}") # Test SM4-CBC try: sm4 = SM4CBC(key="test_key_123456") encrypted_sm4 = sm4.encrypt(test_data) decrypted_sm4 = sm4.decrypt(encrypted_sm4) print(f"SM4-CBC test: {'passed' if decrypted_sm4 == test_data else 'failed'}") except Exception as e: print(f"SM4-CBC test failed: {e}")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/time_utils.py
common/time_utils.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 datetime import logging import time def current_timestamp(): """ Get the current timestamp in milliseconds. Returns: int: Current Unix timestamp in milliseconds (13 digits) Example: >>> current_timestamp() 1704067200000 """ return int(time.time() * 1000) def timestamp_to_date(timestamp, format_string="%Y-%m-%d %H:%M:%S"): """ Convert a timestamp to formatted date string. Args: timestamp: Unix timestamp in milliseconds. If None or empty, uses current time. format_string: Format string for the output date (default: "%Y-%m-%d %H:%M:%S") Returns: str: Formatted date string Example: >>> timestamp_to_date(1704067200000) '2024-01-01 08:00:00' """ if not timestamp: timestamp = time.time() timestamp = int(timestamp) / 1000 time_array = time.localtime(timestamp) str_date = time.strftime(format_string, time_array) return str_date def date_string_to_timestamp(time_str, format_string="%Y-%m-%d %H:%M:%S"): """ Convert a date string to timestamp in milliseconds. Args: time_str: Date string to convert format_string: Format of the input date string (default: "%Y-%m-%d %H:%M:%S") Returns: int: Unix timestamp in milliseconds Example: >>> date_string_to_timestamp("2024-01-01 00:00:00") 1704067200000 """ time_array = time.strptime(time_str, format_string) time_stamp = int(time.mktime(time_array) * 1000) return time_stamp def datetime_format(date_time: datetime.datetime) -> datetime.datetime: """ Normalize a datetime object by removing microsecond component. Creates a new datetime object with only year, month, day, hour, minute, second. Microseconds are set to 0. Args: date_time: datetime object to normalize Returns: datetime.datetime: New datetime object without microseconds Example: >>> dt = datetime.datetime(2024, 1, 1, 12, 30, 45, 123456) >>> datetime_format(dt) datetime.datetime(2024, 1, 1, 12, 30, 45) """ return datetime.datetime(date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second) def get_format_time() -> datetime.datetime: """ Get current datetime normalized without microseconds. Returns: datetime.datetime: Current datetime with microseconds set to 0 Example: >>> get_format_time() datetime.datetime(2024, 1, 1, 12, 30, 45) """ return datetime_format(datetime.datetime.now()) def delta_seconds(date_string: str): """ Calculate seconds elapsed from a given date string to now. Args: date_string: Date string in "YYYY-MM-DD HH:MM:SS" format Returns: float: Number of seconds between the given date and current time Example: >>> delta_seconds("2024-01-01 12:00:00") 3600.0 # If current time is 2024-01-01 13:00:00 """ dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") return (datetime.datetime.now() - dt).total_seconds() def format_iso_8601_to_ymd_hms(time_str: str) -> str: """ Convert ISO 8601 formatted string to "YYYY-MM-DD HH:MM:SS" format. Args: time_str: ISO 8601 date string (e.g. "2024-01-01T12:00:00Z") Returns: str: Date string in "YYYY-MM-DD HH:MM:SS" format Example: >>> format_iso_8601_to_ymd_hms("2024-01-01T12:00:00Z") '2024-01-01 12:00:00' """ from dateutil import parser try: if parser.isoparse(time_str): dt = datetime.datetime.fromisoformat(time_str.replace("Z", "+00:00")) return dt.strftime("%Y-%m-%d %H:%M:%S") else: return time_str except Exception as e: logging.error(str(e)) return time_str
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/constants.py
common/constants.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 enum import Enum, IntEnum from strenum import StrEnum SERVICE_CONF = "service_conf.yaml" RAG_FLOW_SERVICE_NAME = "ragflow" class CustomEnum(Enum): @classmethod def valid(cls, value): try: cls(value) return True except BaseException: return False @classmethod def values(cls): return [member.value for member in cls.__members__.values()] @classmethod def names(cls): return [member.name for member in cls.__members__.values()] class RetCode(IntEnum, CustomEnum): SUCCESS = 0 NOT_EFFECTIVE = 10 EXCEPTION_ERROR = 100 ARGUMENT_ERROR = 101 DATA_ERROR = 102 OPERATING_ERROR = 103 CONNECTION_ERROR = 105 RUNNING = 106 PERMISSION_ERROR = 108 AUTHENTICATION_ERROR = 109 BAD_REQUEST = 400 UNAUTHORIZED = 401 SERVER_ERROR = 500 FORBIDDEN = 403 NOT_FOUND = 404 CONFLICT = 409 class StatusEnum(Enum): VALID = "1" INVALID = "0" class ActiveEnum(Enum): ACTIVE = "1" INACTIVE = "0" class LLMType(StrEnum): CHAT = 'chat' EMBEDDING = 'embedding' SPEECH2TEXT = 'speech2text' IMAGE2TEXT = 'image2text' RERANK = 'rerank' TTS = 'tts' OCR = 'ocr' class TaskStatus(StrEnum): UNSTART = "0" RUNNING = "1" CANCEL = "2" DONE = "3" FAIL = "4" SCHEDULE = "5" VALID_TASK_STATUS = {TaskStatus.UNSTART, TaskStatus.RUNNING, TaskStatus.CANCEL, TaskStatus.DONE, TaskStatus.FAIL, TaskStatus.SCHEDULE} class ParserType(StrEnum): PRESENTATION = "presentation" LAWS = "laws" MANUAL = "manual" PAPER = "paper" RESUME = "resume" BOOK = "book" QA = "qa" TABLE = "table" NAIVE = "naive" PICTURE = "picture" ONE = "one" AUDIO = "audio" EMAIL = "email" KG = "knowledge_graph" TAG = "tag" class FileSource(StrEnum): LOCAL = "" KNOWLEDGEBASE = "knowledgebase" S3 = "s3" NOTION = "notion" DISCORD = "discord" CONFLUENCE = "confluence" GMAIL = "gmail" GOOGLE_DRIVE = "google_drive" JIRA = "jira" SHAREPOINT = "sharepoint" SLACK = "slack" TEAMS = "teams" WEBDAV = "webdav" MOODLE = "moodle" DROPBOX = "dropbox" BOX = "box" R2 = "r2" OCI_STORAGE = "oci_storage" GOOGLE_CLOUD_STORAGE = "google_cloud_storage" AIRTABLE = "airtable" ASANA = "asana" GITHUB = "github" GITLAB = "gitlab" IMAP = "imap" BITBUCKET = "bitbucket" ZENDESK = "zendesk" class PipelineTaskType(StrEnum): PARSE = "Parse" DOWNLOAD = "Download" RAPTOR = "RAPTOR" GRAPH_RAG = "GraphRAG" MINDMAP = "Mindmap" MEMORY = "Memory" VALID_PIPELINE_TASK_TYPES = {PipelineTaskType.PARSE, PipelineTaskType.DOWNLOAD, PipelineTaskType.RAPTOR, PipelineTaskType.GRAPH_RAG, PipelineTaskType.MINDMAP} class MCPServerType(StrEnum): SSE = "sse" STREAMABLE_HTTP = "streamable-http" VALID_MCP_SERVER_TYPES = {MCPServerType.SSE, MCPServerType.STREAMABLE_HTTP} class Storage(Enum): MINIO = 1 AZURE_SPN = 2 AZURE_SAS = 3 AWS_S3 = 4 OSS = 5 OPENDAL = 6 GCS = 7 class MemoryType(Enum): RAW = 0b0001 # 1 << 0 = 1 (0b00000001) SEMANTIC = 0b0010 # 1 << 1 = 2 (0b00000010) EPISODIC = 0b0100 # 1 << 2 = 4 (0b00000100) PROCEDURAL = 0b1000 # 1 << 3 = 8 (0b00001000) class MemoryStorageType(StrEnum): TABLE = "table" GRAPH = "graph" class ForgettingPolicy(StrEnum): FIFO = "FIFO" # environment # ENV_STRONG_TEST_COUNT = "STRONG_TEST_COUNT" # ENV_RAGFLOW_SECRET_KEY = "RAGFLOW_SECRET_KEY" # ENV_REGISTER_ENABLED = "REGISTER_ENABLED" # ENV_DOC_ENGINE = "DOC_ENGINE" # ENV_SANDBOX_ENABLED = "SANDBOX_ENABLED" # ENV_SANDBOX_HOST = "SANDBOX_HOST" # ENV_MAX_CONTENT_LENGTH = "MAX_CONTENT_LENGTH" # ENV_COMPONENT_EXEC_TIMEOUT = "COMPONENT_EXEC_TIMEOUT" # ENV_TRINO_USE_TLS = "TRINO_USE_TLS" # ENV_MAX_FILE_NUM_PER_USER = "MAX_FILE_NUM_PER_USER" # ENV_MACOS = "MACOS" # ENV_RAGFLOW_DEBUGPY_LISTEN = "RAGFLOW_DEBUGPY_LISTEN" # ENV_WERKZEUG_RUN_MAIN = "WERKZEUG_RUN_MAIN" # ENV_DISABLE_SDK = "DISABLE_SDK" # ENV_ENABLE_TIMEOUT_ASSERTION = "ENABLE_TIMEOUT_ASSERTION" # ENV_LOG_LEVELS = "LOG_LEVELS" # ENV_TENSORRT_DLA_SVR = "TENSORRT_DLA_SVR" # ENV_OCR_GPU_MEM_LIMIT_MB = "OCR_GPU_MEM_LIMIT_MB" # ENV_OCR_ARENA_EXTEND_STRATEGY = "OCR_ARENA_EXTEND_STRATEGY" # ENV_MAX_CONCURRENT_PROCESS_AND_EXTRACT_CHUNK = "MAX_CONCURRENT_PROCESS_AND_EXTRACT_CHUNK" # ENV_MAX_MAX_CONCURRENT_CHATS = "MAX_CONCURRENT_CHATS" # ENV_RAGFLOW_MCP_BASE_URL = "RAGFLOW_MCP_BASE_URL" # ENV_RAGFLOW_MCP_HOST = "RAGFLOW_MCP_HOST" # ENV_RAGFLOW_MCP_PORT = "RAGFLOW_MCP_PORT" # ENV_RAGFLOW_MCP_LAUNCH_MODE = "RAGFLOW_MCP_LAUNCH_MODE" # ENV_RAGFLOW_MCP_HOST_API_KEY = "RAGFLOW_MCP_HOST_API_KEY" # ENV_MINERU_EXECUTABLE = "MINERU_EXECUTABLE" # ENV_MINERU_APISERVER = "MINERU_APISERVER" # ENV_MINERU_OUTPUT_DIR = "MINERU_OUTPUT_DIR" # ENV_MINERU_BACKEND = "MINERU_BACKEND" # ENV_MINERU_DELETE_OUTPUT = "MINERU_DELETE_OUTPUT" # ENV_TCADP_OUTPUT_DIR = "TCADP_OUTPUT_DIR" # ENV_LM_TIMEOUT_SECONDS = "LM_TIMEOUT_SECONDS" # ENV_LLM_MAX_RETRIES = "LLM_MAX_RETRIES" # ENV_LLM_BASE_DELAY = "LLM_BASE_DELAY" # ENV_OLLAMA_KEEP_ALIVE = "OLLAMA_KEEP_ALIVE" # ENV_DOC_BULK_SIZE = "DOC_BULK_SIZE" # ENV_EMBEDDING_BATCH_SIZE = "EMBEDDING_BATCH_SIZE" # ENV_MAX_CONCURRENT_TASKS = "MAX_CONCURRENT_TASKS" # ENV_MAX_CONCURRENT_CHUNK_BUILDERS = "MAX_CONCURRENT_CHUNK_BUILDERS" # ENV_MAX_CONCURRENT_MINIO = "MAX_CONCURRENT_MINIO" # ENV_WORKER_HEARTBEAT_TIMEOUT = "WORKER_HEARTBEAT_TIMEOUT" # ENV_TRACE_MALLOC_ENABLED = "TRACE_MALLOC_ENABLED" PAGERANK_FLD = "pagerank_fea" SVR_QUEUE_NAME = "rag_flow_svr_queue" SVR_CONSUMER_GROUP_NAME = "rag_flow_svr_task_broker" TAG_FLD = "tag_feas" MINERU_ENV_KEYS = ["MINERU_APISERVER", "MINERU_OUTPUT_DIR", "MINERU_BACKEND", "MINERU_SERVER_URL", "MINERU_DELETE_OUTPUT"] MINERU_DEFAULT_CONFIG = { "MINERU_APISERVER": "", "MINERU_OUTPUT_DIR": "", "MINERU_BACKEND": "pipeline", "MINERU_SERVER_URL": "", "MINERU_DELETE_OUTPUT": 1, }
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/connection_utils.py
common/connection_utils.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 queue import threading from typing import Any, Callable, Coroutine, Optional, Type, Union import asyncio from functools import wraps from quart import make_response, jsonify from common.constants import RetCode TimeoutException = Union[Type[BaseException], BaseException] OnTimeoutCallback = Union[Callable[..., Any], Coroutine[Any, Any, Any]] def timeout(seconds: float | int | str = None, attempts: int = 2, *, exception: Optional[TimeoutException] = None, on_timeout: Optional[OnTimeoutCallback] = None): if isinstance(seconds, str): seconds = float(seconds) def decorator(func): @wraps(func) def wrapper(*args, **kwargs): result_queue = queue.Queue(maxsize=1) def target(): try: result = func(*args, **kwargs) result_queue.put(result) except Exception as e: result_queue.put(e) thread = threading.Thread(target=target) thread.daemon = True thread.start() for a in range(attempts): try: if os.environ.get("ENABLE_TIMEOUT_ASSERTION"): result = result_queue.get(timeout=seconds) else: result = result_queue.get() if isinstance(result, Exception): raise result return result except queue.Empty: pass raise TimeoutError(f"Function '{func.__name__}' timed out after {seconds} seconds and {attempts} attempts.") @wraps(func) async def async_wrapper(*args, **kwargs) -> Any: if seconds is None: return await func(*args, **kwargs) for a in range(attempts): try: if os.environ.get("ENABLE_TIMEOUT_ASSERTION"): return await asyncio.wait_for(func(*args, **kwargs), timeout=seconds) else: return await func(*args, **kwargs) except asyncio.TimeoutError: if a < attempts - 1: continue if on_timeout is not None: if callable(on_timeout): result = on_timeout() if isinstance(result, Coroutine): return await result return result return on_timeout if exception is None: raise TimeoutError(f"Operation timed out after {seconds} seconds and {attempts} attempts.") if isinstance(exception, BaseException): raise exception if isinstance(exception, type) and issubclass(exception, BaseException): raise exception(f"Operation timed out after {seconds} seconds and {attempts} attempts.") raise RuntimeError("Invalid exception type provided") if asyncio.iscoroutinefunction(func): return async_wrapper return wrapper return decorator async def construct_response(code=RetCode.SUCCESS, message="success", data=None, auth=None): result_dict = {"code": code, "message": message, "data": data} response_dict = {} for key, value in result_dict.items(): if value is None and key != "code": continue else: response_dict[key] = value response = await make_response(jsonify(response_dict)) if auth: response.headers["Authorization"] = auth response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Method"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" response.headers["Access-Control-Expose-Headers"] = "Authorization" return response def sync_construct_response(code=RetCode.SUCCESS, message="success", data=None, auth=None): import flask result_dict = {"code": code, "message": message, "data": data} response_dict = {} for key, value in result_dict.items(): if value is None and key != "code": continue else: response_dict[key] = value response = flask.make_response(flask.jsonify(response_dict)) if auth: response.headers["Authorization"] = auth response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Method"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" response.headers["Access-Control-Expose-Headers"] = "Authorization" return response
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/exceptions.py
common/exceptions.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 TaskCanceledException(Exception): def __init__(self, msg): self.msg = msg
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/versions.py
common/versions.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 subprocess RAGFLOW_VERSION_INFO = "unknown" def get_ragflow_version() -> str: global RAGFLOW_VERSION_INFO if RAGFLOW_VERSION_INFO != "unknown": return RAGFLOW_VERSION_INFO version_path = os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, "VERSION" ) ) if os.path.exists(version_path): with open(version_path, "r") as f: RAGFLOW_VERSION_INFO = f.read().strip() else: RAGFLOW_VERSION_INFO = get_closest_tag_and_count() return RAGFLOW_VERSION_INFO def get_closest_tag_and_count(): try: # Get the current commit hash version_info = ( subprocess.check_output(["git", "describe", "--tags", "--match=v*", "--first-parent", "--always"]) .strip() .decode("utf-8") ) return version_info except Exception: return "unknown"
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/http_client.py
common/http_client.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 logging import os import time from typing import Any, Dict, Optional from urllib.parse import urlparse, urlunparse from common import settings import httpx logger = logging.getLogger(__name__) # Default knobs; keep conservative to avoid unexpected behavioural changes. DEFAULT_TIMEOUT = float(os.environ.get("HTTP_CLIENT_TIMEOUT", "15")) # Align with requests default: follow redirects with a max of 30 unless overridden. DEFAULT_FOLLOW_REDIRECTS = bool( int(os.environ.get("HTTP_CLIENT_FOLLOW_REDIRECTS", "1")) ) DEFAULT_MAX_REDIRECTS = int(os.environ.get("HTTP_CLIENT_MAX_REDIRECTS", "30")) DEFAULT_MAX_RETRIES = int(os.environ.get("HTTP_CLIENT_MAX_RETRIES", "2")) DEFAULT_BACKOFF_FACTOR = float(os.environ.get("HTTP_CLIENT_BACKOFF_FACTOR", "0.5")) DEFAULT_PROXY = os.environ.get("HTTP_CLIENT_PROXY") DEFAULT_USER_AGENT = os.environ.get("HTTP_CLIENT_USER_AGENT", "ragflow-http-client") def _clean_headers( headers: Optional[Dict[str, str]], auth_token: Optional[str] = None ) -> Optional[Dict[str, str]]: merged_headers: Dict[str, str] = {} if DEFAULT_USER_AGENT: merged_headers["User-Agent"] = DEFAULT_USER_AGENT if auth_token: merged_headers["Authorization"] = auth_token if headers is None: return merged_headers or None merged_headers.update({str(k): str(v) for k, v in headers.items() if v is not None}) return merged_headers or None def _get_delay(backoff_factor: float, attempt: int) -> float: return backoff_factor * (2**attempt) # List of sensitive parameters to redact from URLs before logging _SENSITIVE_QUERY_KEYS = {"client_secret", "secret", "code", "access_token", "refresh_token", "password", "token", "app_secret"} def _redact_sensitive_url_params(url: str) -> str: """ Return a version of the URL that is safe to log. We intentionally drop query parameters and userinfo to avoid leaking credentials or tokens via logs. Only scheme, host, port and path are preserved. """ try: parsed = urlparse(url) # Remove any potential userinfo (username:password@) netloc = parsed.hostname or "" if parsed.port: netloc = f"{netloc}:{parsed.port}" # Reconstruct URL without query, params, fragment, or userinfo. safe_url = urlunparse( ( parsed.scheme, netloc, parsed.path, "", # params "", # query "", # fragment ) ) return safe_url except Exception: # If parsing fails, fall back to omitting the URL entirely. return "<redacted-url>" def _is_sensitive_url(url: str) -> bool: """Return True if URL is one of the configured OAuth endpoints.""" # Collect known sensitive endpoint URLs from settings oauth_urls = set() # GitHub OAuth endpoints try: if settings.GITHUB_OAUTH is not None: url_val = settings.GITHUB_OAUTH.get("url") if url_val: oauth_urls.add(url_val) except Exception: pass # Feishu OAuth endpoints try: if settings.FEISHU_OAUTH is not None: for k in ("app_access_token_url", "user_access_token_url"): url_val = settings.FEISHU_OAUTH.get(k) if url_val: oauth_urls.add(url_val) except Exception: pass # Defensive normalization: compare only scheme+netloc+path url_obj = urlparse(url) for sensitive_url in oauth_urls: sensitive_obj = urlparse(sensitive_url) if (url_obj.scheme, url_obj.netloc, url_obj.path) == (sensitive_obj.scheme, sensitive_obj.netloc, sensitive_obj.path): return True return False async def async_request( method: str, url: str, *, request_timeout: float | httpx.Timeout | None = None, follow_redirects: bool | None = None, max_redirects: Optional[int] = None, headers: Optional[Dict[str, str]] = None, auth_token: Optional[str] = None, retries: Optional[int] = None, backoff_factor: Optional[float] = None, proxy: Any = None, **kwargs: Any, ) -> httpx.Response: """Lightweight async HTTP wrapper using httpx.AsyncClient with safe defaults.""" timeout = request_timeout if request_timeout is not None else DEFAULT_TIMEOUT follow_redirects = ( DEFAULT_FOLLOW_REDIRECTS if follow_redirects is None else follow_redirects ) max_redirects = DEFAULT_MAX_REDIRECTS if max_redirects is None else max_redirects retries = DEFAULT_MAX_RETRIES if retries is None else max(retries, 0) backoff_factor = ( DEFAULT_BACKOFF_FACTOR if backoff_factor is None else backoff_factor ) headers = _clean_headers(headers, auth_token=auth_token) proxy = DEFAULT_PROXY if proxy is None else proxy async with httpx.AsyncClient( timeout=timeout, follow_redirects=follow_redirects, max_redirects=max_redirects, proxy=proxy, ) as client: last_exc: Exception | None = None for attempt in range(retries + 1): try: start = time.monotonic() response = await client.request( method=method, url=url, headers=headers, **kwargs ) duration = time.monotonic() - start if not _is_sensitive_url(url): log_url = _redact_sensitive_url_params(url) logger.debug(f"async_request {method} {log_url} -> {response.status_code} in {duration:.3f}s") return response except httpx.RequestError as exc: last_exc = exc if attempt >= retries: if not _is_sensitive_url(url): log_url = _redact_sensitive_url_params(url) logger.warning(f"async_request exhausted retries for {method}") raise delay = _get_delay(backoff_factor, attempt) if not _is_sensitive_url(url): log_url = _redact_sensitive_url_params(url) logger.warning( f"async_request attempt {attempt + 1}/{retries + 1} failed for {method}; retrying in {delay:.2f}s" ) raise delay = _get_delay(backoff_factor, attempt) # Avoid including the (potentially sensitive) URL in retry logs. logger.warning( f"async_request attempt {attempt + 1}/{retries + 1} failed for {method}; retrying in {delay:.2f}s" ) await asyncio.sleep(delay) raise last_exc # pragma: no cover def sync_request( method: str, url: str, *, timeout: float | httpx.Timeout | None = None, follow_redirects: bool | None = None, max_redirects: Optional[int] = None, headers: Optional[Dict[str, str]] = None, auth_token: Optional[str] = None, retries: Optional[int] = None, backoff_factor: Optional[float] = None, proxy: Any = None, **kwargs: Any, ) -> httpx.Response: """Synchronous counterpart to async_request, for CLI/tests or sync contexts.""" timeout = timeout if timeout is not None else DEFAULT_TIMEOUT follow_redirects = ( DEFAULT_FOLLOW_REDIRECTS if follow_redirects is None else follow_redirects ) max_redirects = DEFAULT_MAX_REDIRECTS if max_redirects is None else max_redirects retries = DEFAULT_MAX_RETRIES if retries is None else max(retries, 0) backoff_factor = ( DEFAULT_BACKOFF_FACTOR if backoff_factor is None else backoff_factor ) headers = _clean_headers(headers, auth_token=auth_token) proxy = DEFAULT_PROXY if proxy is None else proxy with httpx.Client( timeout=timeout, follow_redirects=follow_redirects, max_redirects=max_redirects, proxy=proxy, ) as client: last_exc: Exception | None = None for attempt in range(retries + 1): try: start = time.monotonic() response = client.request( method=method, url=url, headers=headers, **kwargs ) duration = time.monotonic() - start logger.debug( f"sync_request {method} {url} -> {response.status_code} in {duration:.3f}s" ) return response except httpx.RequestError as exc: last_exc = exc if attempt >= retries: logger.warning( f"sync_request exhausted retries for {method} {url}: {exc}" ) raise delay = _get_delay(backoff_factor, attempt) logger.warning( f"sync_request attempt {attempt + 1}/{retries + 1} failed for {method} {url}: {exc}; retrying in {delay:.2f}s" ) time.sleep(delay) raise last_exc # pragma: no cover __all__ = [ "async_request", "sync_request", "DEFAULT_TIMEOUT", "DEFAULT_FOLLOW_REDIRECTS", "DEFAULT_MAX_REDIRECTS", "DEFAULT_MAX_RETRIES", "DEFAULT_BACKOFF_FACTOR", "DEFAULT_PROXY", "DEFAULT_USER_AGENT", ]
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/parser_config_utils.py
common/parser_config_utils.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 typing import Any def normalize_layout_recognizer(layout_recognizer_raw: Any) -> tuple[Any, str | None]: parser_model_name: str | None = None layout_recognizer = layout_recognizer_raw if isinstance(layout_recognizer_raw, str): lowered = layout_recognizer_raw.lower() if lowered.endswith("@mineru"): parser_model_name = layout_recognizer_raw.rsplit("@", 1)[0] layout_recognizer = "MinerU" return layout_recognizer, parser_model_name
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/float_utils.py
common/float_utils.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 get_float(v): """ Convert a value to float, handling None and exceptions gracefully. Attempts to convert the input value to a float. If the value is None or cannot be converted to float, returns negative infinity as a default value. Args: v: The value to convert to float. Can be any type that float() accepts, or None. Returns: float: The converted float value if successful, otherwise float('-inf'). Examples: >>> get_float("3.14") 3.14 >>> get_float(None) -inf >>> get_float("invalid") -inf >>> get_float(42) 42.0 """ if v is None: return float('-inf') try: return float(v) except Exception: return float('-inf')
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/settings.py
common/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. # import os import json import secrets from datetime import date import logging from common.constants import RAG_FLOW_SERVICE_NAME from common.file_utils import get_project_base_directory from common.config_utils import get_base_config, decrypt_database_config from common.misc_utils import pip_install_torch from common.constants import SVR_QUEUE_NAME, Storage import rag.utils import rag.utils.es_conn import rag.utils.infinity_conn import rag.utils.ob_conn import rag.utils.opensearch_conn from rag.utils.azure_sas_conn import RAGFlowAzureSasBlob from rag.utils.azure_spn_conn import RAGFlowAzureSpnBlob from rag.utils.gcs_conn import RAGFlowGCS from rag.utils.minio_conn import RAGFlowMinio from rag.utils.opendal_conn import OpenDALStorage from rag.utils.s3_conn import RAGFlowS3 from rag.utils.oss_conn import RAGFlowOSS from rag.nlp import search import memory.utils.es_conn as memory_es_conn import memory.utils.infinity_conn as memory_infinity_conn LLM = None LLM_FACTORY = None LLM_BASE_URL = None CHAT_MDL = "" EMBEDDING_MDL = "" RERANK_MDL = "" ASR_MDL = "" IMAGE2TEXT_MDL = "" CHAT_CFG = "" EMBEDDING_CFG = "" RERANK_CFG = "" ASR_CFG = "" IMAGE2TEXT_CFG = "" API_KEY = None PARSERS = None HOST_IP = None HOST_PORT = None SECRET_KEY = None FACTORY_LLM_INFOS = None ALLOWED_LLM_FACTORIES = None DATABASE_TYPE = os.getenv("DB_TYPE", "mysql") DATABASE = decrypt_database_config(name=DATABASE_TYPE) # authentication AUTHENTICATION_CONF = None # client CLIENT_AUTHENTICATION = None HTTP_APP_KEY = None GITHUB_OAUTH = None FEISHU_OAUTH = None OAUTH_CONFIG = None DOC_ENGINE = os.getenv('DOC_ENGINE', 'elasticsearch') DOC_ENGINE_INFINITY = (DOC_ENGINE.lower() == "infinity") docStoreConn = None msgStoreConn = None retriever = None kg_retriever = None # user registration switch REGISTER_ENABLED = 1 # sandbox-executor-manager SANDBOX_HOST = None STRONG_TEST_COUNT = int(os.environ.get("STRONG_TEST_COUNT", "8")) SMTP_CONF = None MAIL_SERVER = "" MAIL_PORT = 000 MAIL_USE_SSL = True MAIL_USE_TLS = False MAIL_USERNAME = "" MAIL_PASSWORD = "" MAIL_DEFAULT_SENDER = () MAIL_FRONTEND_URL = "" # move from rag.settings ES = {} INFINITY = {} AZURE = {} S3 = {} MINIO = {} OB = {} OSS = {} OS = {} GCS = {} DOC_MAXIMUM_SIZE: int = 128 * 1024 * 1024 DOC_BULK_SIZE: int = 4 EMBEDDING_BATCH_SIZE: int = 16 PARALLEL_DEVICES: int = 0 STORAGE_IMPL_TYPE = os.getenv('STORAGE_IMPL', 'MINIO') STORAGE_IMPL = None def get_svr_queue_name(priority: int) -> str: if priority == 0: return SVR_QUEUE_NAME return f"{SVR_QUEUE_NAME}_{priority}" def get_svr_queue_names(): return [get_svr_queue_name(priority) for priority in [1, 0]] def _get_or_create_secret_key(): secret_key = os.environ.get("RAGFLOW_SECRET_KEY") if secret_key and len(secret_key) >= 32: return secret_key # Check if there's a configured secret key configured_key = get_base_config(RAG_FLOW_SERVICE_NAME, {}).get("secret_key") if configured_key and configured_key != str(date.today()) and len(configured_key) >= 32: return configured_key # Generate a new secure key and warn about it import logging new_key = secrets.token_hex(32) logging.warning("SECURITY WARNING: Using auto-generated SECRET_KEY.") return new_key class StorageFactory: storage_mapping = { Storage.MINIO: RAGFlowMinio, Storage.AZURE_SPN: RAGFlowAzureSpnBlob, Storage.AZURE_SAS: RAGFlowAzureSasBlob, Storage.AWS_S3: RAGFlowS3, Storage.OSS: RAGFlowOSS, Storage.OPENDAL: OpenDALStorage, Storage.GCS: RAGFlowGCS, } @classmethod def create(cls, storage: Storage): return cls.storage_mapping[storage]() def init_settings(): global DATABASE_TYPE, DATABASE DATABASE_TYPE = os.getenv("DB_TYPE", "mysql") DATABASE = decrypt_database_config(name=DATABASE_TYPE) global ALLOWED_LLM_FACTORIES, LLM_FACTORY, LLM_BASE_URL llm_settings = get_base_config("user_default_llm", {}) or {} llm_default_models = llm_settings.get("default_models", {}) or {} LLM_FACTORY = llm_settings.get("factory", "") or "" LLM_BASE_URL = llm_settings.get("base_url", "") or "" ALLOWED_LLM_FACTORIES = llm_settings.get("allowed_factories", None) global REGISTER_ENABLED try: REGISTER_ENABLED = int(os.environ.get("REGISTER_ENABLED", "1")) except Exception: pass global FACTORY_LLM_INFOS try: with open(os.path.join(get_project_base_directory(), "conf", "llm_factories.json"), "r") as f: FACTORY_LLM_INFOS = json.load(f)["factory_llm_infos"] except Exception: FACTORY_LLM_INFOS = [] global API_KEY API_KEY = llm_settings.get("api_key") global PARSERS PARSERS = llm_settings.get( "parsers", "naive:General,qa:Q&A,resume:Resume,manual:Manual,table:Table,paper:Paper,book:Book,laws:Laws,presentation:Presentation,picture:Picture,one:One,audio:Audio,email:Email,tag:Tag" ) global CHAT_MDL, EMBEDDING_MDL, RERANK_MDL, ASR_MDL, IMAGE2TEXT_MDL chat_entry = _parse_model_entry(llm_default_models.get("chat_model", CHAT_MDL)) embedding_entry = _parse_model_entry(llm_default_models.get("embedding_model", EMBEDDING_MDL)) rerank_entry = _parse_model_entry(llm_default_models.get("rerank_model", RERANK_MDL)) asr_entry = _parse_model_entry(llm_default_models.get("asr_model", ASR_MDL)) image2text_entry = _parse_model_entry(llm_default_models.get("image2text_model", IMAGE2TEXT_MDL)) global CHAT_CFG, EMBEDDING_CFG, RERANK_CFG, ASR_CFG, IMAGE2TEXT_CFG CHAT_CFG = _resolve_per_model_config(chat_entry, LLM_FACTORY, API_KEY, LLM_BASE_URL) EMBEDDING_CFG = _resolve_per_model_config(embedding_entry, LLM_FACTORY, API_KEY, LLM_BASE_URL) RERANK_CFG = _resolve_per_model_config(rerank_entry, LLM_FACTORY, API_KEY, LLM_BASE_URL) ASR_CFG = _resolve_per_model_config(asr_entry, LLM_FACTORY, API_KEY, LLM_BASE_URL) IMAGE2TEXT_CFG = _resolve_per_model_config(image2text_entry, LLM_FACTORY, API_KEY, LLM_BASE_URL) CHAT_MDL = CHAT_CFG.get("model", "") or "" EMBEDDING_MDL = EMBEDDING_CFG.get("model", "") or "" compose_profiles = os.getenv("COMPOSE_PROFILES", "") if "tei-" in compose_profiles: EMBEDDING_MDL = os.getenv("TEI_MODEL", EMBEDDING_MDL or "BAAI/bge-small-en-v1.5") RERANK_MDL = RERANK_CFG.get("model", "") or "" ASR_MDL = ASR_CFG.get("model", "") or "" IMAGE2TEXT_MDL = IMAGE2TEXT_CFG.get("model", "") or "" global HOST_IP, HOST_PORT HOST_IP = get_base_config(RAG_FLOW_SERVICE_NAME, {}).get("host", "127.0.0.1") HOST_PORT = get_base_config(RAG_FLOW_SERVICE_NAME, {}).get("http_port") global SECRET_KEY SECRET_KEY = _get_or_create_secret_key() # authentication authentication_conf = get_base_config("authentication", {}) global CLIENT_AUTHENTICATION, HTTP_APP_KEY, GITHUB_OAUTH, FEISHU_OAUTH, OAUTH_CONFIG # client CLIENT_AUTHENTICATION = authentication_conf.get("client", {}).get("switch", False) HTTP_APP_KEY = authentication_conf.get("client", {}).get("http_app_key") GITHUB_OAUTH = get_base_config("oauth", {}).get("github") FEISHU_OAUTH = get_base_config("oauth", {}).get("feishu") OAUTH_CONFIG = get_base_config("oauth", {}) global DOC_ENGINE, DOC_ENGINE_INFINITY, docStoreConn, ES, OB, OS, INFINITY DOC_ENGINE = os.environ.get("DOC_ENGINE", "elasticsearch") DOC_ENGINE_INFINITY = (DOC_ENGINE.lower() == "infinity") lower_case_doc_engine = DOC_ENGINE.lower() if lower_case_doc_engine == "elasticsearch": ES = get_base_config("es", {}) docStoreConn = rag.utils.es_conn.ESConnection() elif lower_case_doc_engine == "infinity": INFINITY = get_base_config("infinity", {"uri": "infinity:23817"}) docStoreConn = rag.utils.infinity_conn.InfinityConnection() elif lower_case_doc_engine == "opensearch": OS = get_base_config("os", {}) docStoreConn = rag.utils.opensearch_conn.OSConnection() elif lower_case_doc_engine == "oceanbase": OB = get_base_config("oceanbase", {}) docStoreConn = rag.utils.ob_conn.OBConnection() else: raise Exception(f"Not supported doc engine: {DOC_ENGINE}") global msgStoreConn # use the same engine for message store if DOC_ENGINE == "elasticsearch": ES = get_base_config("es", {}) msgStoreConn = memory_es_conn.ESConnection() elif DOC_ENGINE == "infinity": INFINITY = get_base_config("infinity", {"uri": "infinity:23817"}) msgStoreConn = memory_infinity_conn.InfinityConnection() global AZURE, S3, MINIO, OSS, GCS if STORAGE_IMPL_TYPE in ['AZURE_SPN', 'AZURE_SAS']: AZURE = get_base_config("azure", {}) elif STORAGE_IMPL_TYPE == 'AWS_S3': S3 = get_base_config("s3", {}) elif STORAGE_IMPL_TYPE == 'MINIO': MINIO = decrypt_database_config(name="minio") elif STORAGE_IMPL_TYPE == 'OSS': OSS = get_base_config("oss", {}) elif STORAGE_IMPL_TYPE == 'GCS': GCS = get_base_config("gcs", {}) global STORAGE_IMPL storage_impl = StorageFactory.create(Storage[STORAGE_IMPL_TYPE]) # Define crypto settings crypto_enabled = os.environ.get("RAGFLOW_CRYPTO_ENABLED", "false").lower() == "true" # Check if encryption is enabled if crypto_enabled: try: from rag.utils.encrypted_storage import create_encrypted_storage algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc") crypto_key = os.environ.get("RAGFLOW_CRYPTO_KEY") STORAGE_IMPL = create_encrypted_storage(storage_impl, algorithm=algorithm, key=crypto_key, encryption_enabled=crypto_enabled) except Exception as e: logging.error(f"Failed to initialize encrypted storage: {e}") STORAGE_IMPL = storage_impl else: STORAGE_IMPL = storage_impl global retriever, kg_retriever retriever = search.Dealer(docStoreConn) from graphrag import search as kg_search kg_retriever = kg_search.KGSearch(docStoreConn) global SANDBOX_HOST if int(os.environ.get("SANDBOX_ENABLED", "0")): SANDBOX_HOST = os.environ.get("SANDBOX_HOST", "sandbox-executor-manager") global SMTP_CONF SMTP_CONF = get_base_config("smtp", {}) global MAIL_SERVER, MAIL_PORT, MAIL_USE_SSL, MAIL_USE_TLS, MAIL_USERNAME, MAIL_PASSWORD, MAIL_DEFAULT_SENDER, MAIL_FRONTEND_URL MAIL_SERVER = SMTP_CONF.get("mail_server", "") MAIL_PORT = SMTP_CONF.get("mail_port", 000) MAIL_USE_SSL = SMTP_CONF.get("mail_use_ssl", True) MAIL_USE_TLS = SMTP_CONF.get("mail_use_tls", False) MAIL_USERNAME = SMTP_CONF.get("mail_username", "") MAIL_PASSWORD = SMTP_CONF.get("mail_password", "") mail_default_sender = SMTP_CONF.get("mail_default_sender", []) if mail_default_sender and len(mail_default_sender) >= 2: MAIL_DEFAULT_SENDER = (mail_default_sender[0], mail_default_sender[1]) MAIL_FRONTEND_URL = SMTP_CONF.get("mail_frontend_url", "") global DOC_MAXIMUM_SIZE, DOC_BULK_SIZE, EMBEDDING_BATCH_SIZE DOC_MAXIMUM_SIZE = int(os.environ.get("MAX_CONTENT_LENGTH", 128 * 1024 * 1024)) DOC_BULK_SIZE = int(os.environ.get("DOC_BULK_SIZE", 4)) EMBEDDING_BATCH_SIZE = int(os.environ.get("EMBEDDING_BATCH_SIZE", 16)) os.environ["DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"] = "1" def check_and_install_torch(): global PARALLEL_DEVICES try: pip_install_torch() import torch.cuda PARALLEL_DEVICES = torch.cuda.device_count() logging.info(f"found {PARALLEL_DEVICES} gpus") except Exception: logging.info("can't import package 'torch'") def _parse_model_entry(entry): if isinstance(entry, str): return {"name": entry, "factory": None, "api_key": None, "base_url": None} if isinstance(entry, dict): name = entry.get("name") or entry.get("model") or "" return { "name": name, "factory": entry.get("factory"), "api_key": entry.get("api_key"), "base_url": entry.get("base_url"), } return {"name": "", "factory": None, "api_key": None, "base_url": None} def _resolve_per_model_config(entry_dict, backup_factory, backup_api_key, backup_base_url): name = (entry_dict.get("name") or "").strip() m_factory = entry_dict.get("factory") or backup_factory or "" m_api_key = entry_dict.get("api_key") or backup_api_key or "" m_base_url = entry_dict.get("base_url") or backup_base_url or "" if name and "@" not in name and m_factory: name = f"{name}@{m_factory}" return { "model": name, "factory": m_factory, "api_key": m_api_key, "base_url": m_base_url, } def print_rag_settings(): logging.info(f"MAX_CONTENT_LENGTH: {DOC_MAXIMUM_SIZE}") logging.info(f"MAX_FILE_COUNT_PER_USER: {int(os.environ.get('MAX_FILE_NUM_PER_USER', 0))}")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/signal_utils.py
common/signal_utils.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 sys from datetime import datetime import logging import tracemalloc from common.log_utils import get_project_base_directory # SIGUSR1 handler: start tracemalloc and take snapshot def start_tracemalloc_and_snapshot(signum, frame): if not tracemalloc.is_tracing(): logging.info("start tracemalloc") tracemalloc.start() else: logging.info("tracemalloc is already running") timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") snapshot_file = f"snapshot_{timestamp}.trace" snapshot_file = os.path.abspath(os.path.join(get_project_base_directory(), "logs", f"{os.getpid()}_snapshot_{timestamp}.trace")) snapshot = tracemalloc.take_snapshot() snapshot.dump(snapshot_file) current, peak = tracemalloc.get_traced_memory() if sys.platform == "win32": import psutil process = psutil.Process() max_rss = process.memory_info().rss / 1024 else: import resource max_rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss logging.info(f"taken snapshot {snapshot_file}. max RSS={max_rss / 1000:.2f} MB, current memory usage: {current / 10**6:.2f} MB, Peak memory usage: {peak / 10**6:.2f} MB") # SIGUSR2 handler: stop tracemalloc def stop_tracemalloc(signum, frame): if tracemalloc.is_tracing(): logging.info("stop tracemalloc") tracemalloc.stop() else: logging.info("tracemalloc not running")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/log_utils.py
common/log_utils.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 os.path import logging from logging.handlers import RotatingFileHandler from common.file_utils import get_project_base_directory initialized_root_logger = False def init_root_logger(logfile_basename: str, log_format: str = "%(asctime)-15s %(levelname)-8s %(process)d %(message)s"): global initialized_root_logger if initialized_root_logger: return initialized_root_logger = True logger = logging.getLogger() logger.handlers.clear() log_path = os.path.abspath(os.path.join(get_project_base_directory(), "logs", f"{logfile_basename}.log")) os.makedirs(os.path.dirname(log_path), exist_ok=True) formatter = logging.Formatter(log_format) handler1 = RotatingFileHandler(log_path, maxBytes=10*1024*1024, backupCount=5) handler1.setFormatter(formatter) logger.addHandler(handler1) handler2 = logging.StreamHandler() handler2.setFormatter(formatter) logger.addHandler(handler2) logging.captureWarnings(True) LOG_LEVELS = os.environ.get("LOG_LEVELS", "") pkg_levels = {} for pkg_name_level in LOG_LEVELS.split(","): terms = pkg_name_level.split("=") if len(terms)!= 2: continue pkg_name, pkg_level = terms[0], terms[1] pkg_name = pkg_name.strip() pkg_level = logging.getLevelName(pkg_level.strip().upper()) if not isinstance(pkg_level, int): pkg_level = logging.INFO pkg_levels[pkg_name] = logging.getLevelName(pkg_level) for pkg_name in ['peewee', 'pdfminer']: if pkg_name not in pkg_levels: pkg_levels[pkg_name] = logging.getLevelName(logging.WARNING) if 'root' not in pkg_levels: pkg_levels['root'] = logging.getLevelName(logging.INFO) for pkg_name, pkg_level in pkg_levels.items(): pkg_logger = logging.getLogger(pkg_name) pkg_logger.setLevel(pkg_level) msg = f"{logfile_basename} log path: {log_path}, log levels: {pkg_levels}" logger.info(msg) def log_exception(e, *args): logging.exception(e) for a in args: try: text = getattr(a, "text") except Exception: text = None if text is not None: logging.error(text) raise Exception(text) logging.error(str(a)) raise e
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/__init__.py
common/__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/common/config_utils.py
common/config_utils.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 copy import logging import importlib from filelock import FileLock from common.file_utils import get_project_base_directory from common.constants import SERVICE_CONF from ruamel.yaml import YAML def load_yaml_conf(conf_path): if not os.path.isabs(conf_path): conf_path = os.path.join(get_project_base_directory(), conf_path) try: with open(conf_path) as f: yaml = YAML(typ="safe", pure=True) return yaml.load(f) except Exception as e: raise EnvironmentError("loading yaml file config from {} failed:".format(conf_path), e) def rewrite_yaml_conf(conf_path, config): if not os.path.isabs(conf_path): conf_path = os.path.join(get_project_base_directory(), conf_path) try: with open(conf_path, "w") as f: yaml = YAML(typ="safe") yaml.dump(config, f) except Exception as e: raise EnvironmentError("rewrite yaml file config {} failed:".format(conf_path), e) def conf_realpath(conf_name): conf_path = f"conf/{conf_name}" return os.path.join(get_project_base_directory(), conf_path) def read_config(conf_name=SERVICE_CONF): local_config = {} local_path = conf_realpath(f'local.{conf_name}') # load local config file if os.path.exists(local_path): local_config = load_yaml_conf(local_path) if not isinstance(local_config, dict): raise ValueError(f'Invalid config file: "{local_path}".') global_config_path = conf_realpath(conf_name) global_config = load_yaml_conf(global_config_path) if not isinstance(global_config, dict): raise ValueError(f'Invalid config file: "{global_config_path}".') global_config.update(local_config) return global_config CONFIGS = read_config() def show_configs(): msg = f"Current configs, from {conf_realpath(SERVICE_CONF)}:" for k, v in CONFIGS.items(): if isinstance(v, dict): if "password" in v: v = copy.deepcopy(v) v["password"] = "*" * 8 if "access_key" in v: v = copy.deepcopy(v) v["access_key"] = "*" * 8 if "secret_key" in v: v = copy.deepcopy(v) v["secret_key"] = "*" * 8 if "secret" in v: v = copy.deepcopy(v) v["secret"] = "*" * 8 if "sas_token" in v: v = copy.deepcopy(v) v["sas_token"] = "*" * 8 if "oauth" in k: v = copy.deepcopy(v) for key, val in v.items(): if "client_secret" in val: val["client_secret"] = "*" * 8 if "authentication" in k: v = copy.deepcopy(v) for key, val in v.items(): if "http_secret_key" in val: val["http_secret_key"] = "*" * 8 msg += f"\n\t{k}: {v}" logging.info(msg) def get_base_config(key, default=None): if key is None: return None if default is None: default = os.environ.get(key.upper()) return CONFIGS.get(key, default) def decrypt_database_password(password): encrypt_password = get_base_config("encrypt_password", False) encrypt_module = get_base_config("encrypt_module", False) private_key = get_base_config("private_key", None) if not password or not encrypt_password: return password if not private_key: raise ValueError("No private key") module_fun = encrypt_module.split("#") pwdecrypt_fun = getattr( importlib.import_module( module_fun[0]), module_fun[1]) return pwdecrypt_fun(private_key, password) def decrypt_database_config(database=None, passwd_key="password", name="database"): if not database: database = get_base_config(name, {}) database[passwd_key] = decrypt_database_password(database[passwd_key]) return database def update_config(key, value, conf_name=SERVICE_CONF): conf_path = conf_realpath(conf_name=conf_name) if not os.path.isabs(conf_path): conf_path = os.path.join(get_project_base_directory(), conf_path) with FileLock(os.path.join(os.path.dirname(conf_path), ".lock")): config = load_yaml_conf(conf_path=conf_path) or {} config[key] = value rewrite_yaml_conf(conf_path=conf_path, config=config)
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/misc_utils.py
common/misc_utils.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 base64 import hashlib import uuid import requests import threading import subprocess import sys import os import logging def get_uuid(): return uuid.uuid1().hex def download_img(url): if not url: return "" response = requests.get(url) return "data:" + \ response.headers.get('Content-Type', 'image/jpg') + ";" + \ "base64," + base64.b64encode(response.content).decode("utf-8") def hash_str2int(line: str, mod: int = 10 ** 8) -> int: return int(hashlib.sha1(line.encode("utf-8")).hexdigest(), 16) % mod def convert_bytes(size_in_bytes: int) -> str: """ Format size in bytes. """ if size_in_bytes == 0: return "0 B" units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 size = float(size_in_bytes) while size >= 1024 and i < len(units) - 1: size /= 1024 i += 1 if i == 0 or size >= 100: return f"{size:.0f} {units[i]}" elif size >= 10: return f"{size:.1f} {units[i]}" else: return f"{size:.2f} {units[i]}" def once(func): """ A thread-safe decorator that ensures the decorated function runs exactly once, caching and returning its result for all subsequent calls. This prevents race conditions in multi-thread environments by using a lock to protect the execution state. Args: func (callable): The function to be executed only once. Returns: callable: A wrapper function that executes `func` on the first call and returns the cached result thereafter. Example: @once def compute_expensive_value(): print("Computing...") return 42 # First call: executes and prints # Subsequent calls: return 42 without executing """ executed = False result = None lock = threading.Lock() def wrapper(*args, **kwargs): nonlocal executed, result with lock: if not executed: executed = True result = func(*args, **kwargs) return result return wrapper @once def pip_install_torch(): device = os.getenv("DEVICE", "cpu") if device=="cpu": return logging.info("Installing pytorch") pkg_names = ["torch>=2.5.0,<3.0.0"] subprocess.check_call([sys.executable, "-m", "pip", "install", *pkg_names])
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/decorator.py
common/decorator.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 def singleton(cls, *args, **kw): instances = {} def _singleton(): key = str(cls) + str(os.getpid()) if key not in instances: instances[key] = cls(*args, **kw) return instances[key] return _singleton
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/string_utils.py
common/string_utils.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 re def remove_redundant_spaces(txt: str): """ Remove redundant spaces around punctuation marks while preserving meaningful spaces. This function performs two main operations: 1. Remove spaces after left-boundary characters (opening brackets, etc.) 2. Remove spaces before right-boundary characters (closing brackets, punctuation, etc.) Args: txt (str): Input text to process Returns: str: Text with redundant spaces removed """ # First pass: Remove spaces after left-boundary characters # Matches: [non-alphanumeric-and-specific-right-punctuation] + [non-space] # Removes spaces after characters like '(', '<', and other non-alphanumeric chars # Examples: # "( test" → "(test" txt = re.sub(r"([^a-z0-9.,\)>]) +([^ ])", r"\1\2", txt, flags=re.IGNORECASE) # Second pass: Remove spaces before right-boundary characters # Matches: [non-space] + [non-alphanumeric-and-specific-left-punctuation] # Removes spaces before characters like non-')', non-',', non-'.', and non-alphanumeric chars # Examples: # "world !" → "world!" return re.sub(r"([^ ]) +([^a-z0-9.,\(<])", r"\1\2", txt, flags=re.IGNORECASE) def clean_markdown_block(text): """ Remove Markdown code block syntax from the beginning and end of text. This function cleans Markdown code blocks by removing: - Opening ```Markdown tags (with optional whitespace and newlines) - Closing ``` tags (with optional whitespace and newlines) Args: text (str): Input text that may be wrapped in Markdown code blocks Returns: str: Cleaned text with Markdown code block syntax removed, and stripped of surrounding whitespace """ # Remove opening ```Markdown tag with optional whitespace and newlines # Matches: optional whitespace + ```markdown + optional whitespace + optional newline text = re.sub(r'^\s*```markdown\s*\n?', '', text) # Remove closing ``` tag with optional whitespace and newlines # Matches: optional newline + optional whitespace + ``` + optional whitespace at end text = re.sub(r'\n?\s*```\s*$', '', text) # Return text with surrounding whitespace removed return text.strip()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/query_base.py
common/query_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. # import re from abc import ABC, abstractmethod class QueryBase(ABC): @staticmethod def is_chinese(line): arr = re.split(r"[ \t]+", line) if len(arr) <= 3: return True e = 0 for t in arr: if not re.match(r"[a-zA-Z]+$", t): e += 1 return e * 1.0 / len(arr) >= 0.7 @staticmethod def sub_special_char(line): return re.sub(r"([:\{\}/\[\]\-\*\"\(\)\|\+~\^])", r"\\\1", line).strip() @staticmethod def rmWWW(txt): patts = [ ( r"是*(怎么办|什么样的|哪家|一下|那家|请问|啥样|咋样了|什么时候|何时|何地|何人|是否|是不是|多少|哪里|怎么|哪儿|怎么样|如何|哪些|是啥|啥是|啊|吗|呢|吧|咋|什么|有没有|呀|谁|哪位|哪个)是*", "", ), (r"(^| )(what|who|how|which|where|why)('re|'s)? ", " "), ( r"(^| )('s|'re|is|are|were|was|do|does|did|don't|doesn't|didn't|has|have|be|there|you|me|your|my|mine|just|please|may|i|should|would|wouldn't|will|won't|done|go|for|with|so|the|a|an|by|i'm|it's|he's|she's|they|they're|you're|as|by|on|in|at|up|out|down|of|to|or|and|if) ", " ") ] otxt = txt for r, p in patts: txt = re.sub(r, p, txt, flags=re.IGNORECASE) if not txt: txt = otxt return txt @staticmethod def add_space_between_eng_zh(txt): # (ENG/ENG+NUM) + ZH txt = re.sub(r'([A-Za-z]+[0-9]+)([\u4e00-\u9fa5]+)', r'\1 \2', txt) # ENG + ZH txt = re.sub(r'([A-Za-z])([\u4e00-\u9fa5]+)', r'\1 \2', txt) # ZH + (ENG/ENG+NUM) txt = re.sub(r'([\u4e00-\u9fa5]+)([A-Za-z]+[0-9]+)', r'\1 \2', txt) txt = re.sub(r'([\u4e00-\u9fa5]+)([A-Za-z])', r'\1 \2', txt) return txt @abstractmethod def question(self, text, tbl, min_match): """ Returns a query object based on the input text, table, and minimum match criteria. """ raise NotImplementedError("Not implemented")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/mcp_tool_call_conn.py
common/mcp_tool_call_conn.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 logging import threading import weakref from concurrent.futures import ThreadPoolExecutor from concurrent.futures import TimeoutError as FuturesTimeoutError from string import Template from typing import Any, Literal, Protocol from typing_extensions import override from common.constants import MCPServerType from mcp.client.session import ClientSession from mcp.client.sse import sse_client from mcp.client.streamable_http import streamablehttp_client from mcp.types import CallToolResult, ListToolsResult, TextContent, Tool MCPTaskType = Literal["list_tools", "tool_call"] MCPTask = tuple[MCPTaskType, dict[str, Any], asyncio.Queue[Any]] class ToolCallSession(Protocol): def tool_call(self, name: str, arguments: dict[str, Any]) -> str: ... class MCPToolCallSession(ToolCallSession): _ALL_INSTANCES: weakref.WeakSet["MCPToolCallSession"] = weakref.WeakSet() def __init__(self, mcp_server: Any, server_variables: dict[str, Any] | None = None) -> None: self.__class__._ALL_INSTANCES.add(self) self._mcp_server = mcp_server self._server_variables = server_variables or {} self._queue = asyncio.Queue() self._close = False self._event_loop = asyncio.new_event_loop() self._thread_pool = ThreadPoolExecutor(max_workers=1) self._thread_pool.submit(self._event_loop.run_forever) asyncio.run_coroutine_threadsafe(self._mcp_server_loop(), self._event_loop) async def _mcp_server_loop(self) -> None: url = self._mcp_server.url.strip() raw_headers: dict[str, str] = self._mcp_server.headers or {} headers: dict[str, str] = {} for h, v in raw_headers.items(): nh = Template(h).safe_substitute(self._server_variables) nv = Template(v).safe_substitute(self._server_variables) if nh.strip() and nv.strip().strip("Bearer"): headers[nh] = nv if self._mcp_server.server_type == MCPServerType.SSE: # SSE transport try: async with sse_client(url, headers) as stream: async with ClientSession(*stream) as client_session: try: await asyncio.wait_for(client_session.initialize(), timeout=5) logging.info("client_session initialized successfully") await self._process_mcp_tasks(client_session) except asyncio.TimeoutError: msg = f"Timeout initializing client_session for server {self._mcp_server.id}" logging.error(msg) await self._process_mcp_tasks(None, msg) except asyncio.CancelledError: logging.warning(f"SSE transport MCP session cancelled for server {self._mcp_server.id}") return except Exception: msg = "Connection failed (possibly due to auth error). Please check authentication settings first" await self._process_mcp_tasks(None, msg) elif self._mcp_server.server_type == MCPServerType.STREAMABLE_HTTP: # Streamable HTTP transport try: async with streamablehttp_client(url, headers) as (read_stream, write_stream, _): async with ClientSession(read_stream, write_stream) as client_session: try: await asyncio.wait_for(client_session.initialize(), timeout=5) logging.info("client_session initialized successfully") await self._process_mcp_tasks(client_session) except asyncio.TimeoutError: msg = f"Timeout initializing client_session for server {self._mcp_server.id}" logging.error(msg) await self._process_mcp_tasks(None, msg) except asyncio.CancelledError: logging.warning(f"STREAMABLE_HTTP MCP session cancelled for server {self._mcp_server.id}") return except Exception as e: logging.exception(e) msg = "Connection failed (possibly due to auth error). Please check authentication settings first" await self._process_mcp_tasks(None, msg) else: await self._process_mcp_tasks(None, f"Unsupported MCP server type: {self._mcp_server.server_type}, id: {self._mcp_server.id}") async def _process_mcp_tasks(self, client_session: ClientSession | None, error_message: str | None = None) -> None: while not self._close: try: mcp_task, arguments, result_queue = await asyncio.wait_for(self._queue.get(), timeout=1) except asyncio.TimeoutError: continue except asyncio.CancelledError: break logging.debug(f"Got MCP task {mcp_task} arguments {arguments}") r: Any = None if not client_session or error_message: r = ValueError(error_message) try: await result_queue.put(r) except asyncio.CancelledError: break continue try: if mcp_task == "list_tools": r = await client_session.list_tools() elif mcp_task == "tool_call": r = await client_session.call_tool(**arguments) else: r = ValueError(f"Unknown MCP task {mcp_task}") except Exception as e: r = e except asyncio.CancelledError: break try: await result_queue.put(r) except asyncio.CancelledError: break async def _call_mcp_server(self, task_type: MCPTaskType, request_timeout: float | int = 8, **kwargs) -> Any: if self._close: raise ValueError("Session is closed") results = asyncio.Queue() await self._queue.put((task_type, kwargs, results)) try: result: CallToolResult | Exception = await asyncio.wait_for(results.get(), timeout=request_timeout) if isinstance(result, Exception): raise result return result except asyncio.TimeoutError: raise asyncio.TimeoutError(f"MCP task '{task_type}' timeout after {request_timeout}s") except Exception: raise async def _call_mcp_tool(self, name: str, arguments: dict[str, Any], request_timeout: float | int = 10) -> str: result: CallToolResult = await self._call_mcp_server("tool_call", name=name, arguments=arguments, request_timeout=request_timeout) if result.isError: return f"MCP server error: {result.content}" # For now, we only support text content if isinstance(result.content[0], TextContent): return result.content[0].text else: return f"Unsupported content type {type(result.content)}" async def _get_tools_from_mcp_server(self, request_timeout: float | int = 8) -> list[Tool]: try: result: ListToolsResult = await self._call_mcp_server("list_tools", request_timeout=request_timeout) return result.tools except Exception: raise def get_tools(self, timeout: float | int = 10) -> list[Tool]: if self._close: raise ValueError("Session is closed") future = asyncio.run_coroutine_threadsafe(self._get_tools_from_mcp_server(request_timeout=timeout), self._event_loop) try: return future.result(timeout=timeout) except FuturesTimeoutError: msg = f"Timeout when fetching tools from MCP server: {self._mcp_server.id} (timeout={timeout})" logging.error(msg) raise RuntimeError(msg) except Exception: logging.exception(f"Error fetching tools from MCP server: {self._mcp_server.id}") raise @override def tool_call(self, name: str, arguments: dict[str, Any], timeout: float | int = 10) -> str: if self._close: return "Error: Session is closed" future = asyncio.run_coroutine_threadsafe(self._call_mcp_tool(name, arguments), self._event_loop) try: return future.result(timeout=timeout) except FuturesTimeoutError: logging.error(f"Timeout calling tool '{name}' on MCP server: {self._mcp_server.id} (timeout={timeout})") return f"Timeout calling tool '{name}' (timeout={timeout})." except Exception as e: logging.exception(f"Error calling tool '{name}' on MCP server: {self._mcp_server.id}") return f"Error calling tool '{name}': {e}." async def close(self) -> None: if self._close: return self._close = True while not self._queue.empty(): try: _, _, result_queue = self._queue.get_nowait() try: await result_queue.put(asyncio.CancelledError("Session is closing")) except Exception: pass except asyncio.QueueEmpty: break except Exception: break try: self._event_loop.call_soon_threadsafe(self._event_loop.stop) except Exception: pass try: self._thread_pool.shutdown(wait=True) except Exception: pass self.__class__._ALL_INSTANCES.discard(self) def close_sync(self, timeout: float | int = 5) -> None: if not self._event_loop.is_running(): logging.warning(f"Event loop already stopped for {self._mcp_server.id}") return try: future = asyncio.run_coroutine_threadsafe(self.close(), self._event_loop) try: future.result(timeout=timeout) except FuturesTimeoutError: logging.error(f"Timeout while closing session for server {self._mcp_server.id} (timeout={timeout})") except Exception: logging.exception(f"Unexpected error during close_sync for {self._mcp_server.id}") except Exception: logging.exception(f"Exception while scheduling close for server {self._mcp_server.id}") def close_multiple_mcp_toolcall_sessions(sessions: list[MCPToolCallSession]) -> None: logging.info(f"Want to clean up {len(sessions)} MCP sessions") async def _gather_and_stop() -> None: try: await asyncio.gather(*[s.close() for s in sessions if s is not None], return_exceptions=True) except Exception: logging.exception("Exception during MCP session cleanup") finally: try: loop.call_soon_threadsafe(loop.stop) except Exception: pass try: loop = asyncio.new_event_loop() thread = threading.Thread(target=loop.run_forever, daemon=True) thread.start() asyncio.run_coroutine_threadsafe(_gather_and_stop(), loop).result() thread.join() except Exception: logging.exception("Exception during MCP session cleanup thread management") logging.info( f"{len(sessions)} MCP sessions has been cleaned up. {len(list(MCPToolCallSession._ALL_INSTANCES))} in global context.") def shutdown_all_mcp_sessions(): """Gracefully shutdown all active MCPToolCallSession instances.""" sessions = list(MCPToolCallSession._ALL_INSTANCES) if not sessions: logging.info("No MCPToolCallSession instances to close.") return logging.info(f"Shutting down {len(sessions)} MCPToolCallSession instances...") close_multiple_mcp_toolcall_sessions(sessions) logging.info("All MCPToolCallSession instances have been closed.") def mcp_tool_metadata_to_openai_tool(mcp_tool: Tool | dict) -> dict[str, Any]: if isinstance(mcp_tool, dict): return { "type": "function", "function": { "name": mcp_tool["name"], "description": mcp_tool["description"], "parameters": mcp_tool["inputSchema"], }, } return { "type": "function", "function": { "name": mcp_tool.name, "description": mcp_tool.description, "parameters": mcp_tool.inputSchema, }, }
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/doc_store/infinity_conn_pool.py
common/doc_store/infinity_conn_pool.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 import time import infinity from infinity.connection_pool import ConnectionPool from infinity.errors import ErrorCode from common import settings from common.decorator import singleton @singleton class InfinityConnectionPool: def __init__(self): if hasattr(settings, "INFINITY"): self.INFINITY_CONFIG = settings.INFINITY else: self.INFINITY_CONFIG = settings.get_base_config("infinity", {"uri": "infinity:23817"}) infinity_uri = self.INFINITY_CONFIG["uri"] if ":" in infinity_uri: host, port = infinity_uri.split(":") self.infinity_uri = infinity.common.NetworkAddress(host, int(port)) for _ in range(24): try: conn_pool = ConnectionPool(self.infinity_uri, max_size=4) inf_conn = conn_pool.get_conn() res = inf_conn.show_current_node() if res.error_code == ErrorCode.OK and res.server_status in ["started", "alive"]: self.conn_pool = conn_pool conn_pool.release_conn(inf_conn) break except Exception as e: logging.warning(f"{str(e)}. Waiting Infinity {infinity_uri} to be healthy.") time.sleep(5) if self.conn_pool is None: msg = f"Infinity {infinity_uri} is unhealthy in 120s." logging.error(msg) raise Exception(msg) logging.info(f"Infinity {infinity_uri} is healthy.") def get_conn_pool(self): return self.conn_pool def refresh_conn_pool(self): try: inf_conn = self.conn_pool.get_conn() res = inf_conn.show_current_node() if res.error_code == ErrorCode.OK and res.server_status in ["started", "alive"]: return self.conn_pool else: raise Exception(f"{res.error_code}: {res.server_status}") except Exception as e: logging.error(str(e)) if hasattr(self, "conn_pool") and self.conn_pool: self.conn_pool.destroy() self.conn_pool = ConnectionPool(self.infinity_uri, max_size=32) return self.conn_pool def __del__(self): if hasattr(self, "conn_pool") and self.conn_pool: self.conn_pool.destroy() INFINITY_CONN = InfinityConnectionPool()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/doc_store/es_conn_pool.py
common/doc_store/es_conn_pool.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 import time from elasticsearch import Elasticsearch from common import settings from common.decorator import singleton ATTEMPT_TIME = 2 @singleton class ElasticSearchConnectionPool: def __init__(self): if hasattr(settings, "ES"): self.ES_CONFIG = settings.ES else: self.ES_CONFIG = settings.get_base_config("es", {}) for _ in range(ATTEMPT_TIME): try: if self._connect(): break except Exception as e: logging.warning(f"{str(e)}. Waiting Elasticsearch {self.ES_CONFIG['hosts']} to be healthy.") time.sleep(5) if not hasattr(self, "es_conn") or not self.es_conn or not self.es_conn.ping(): msg = f"Elasticsearch {self.ES_CONFIG['hosts']} is unhealthy in 10s." logging.error(msg) raise Exception(msg) v = self.info.get("version", {"number": "8.11.3"}) v = v["number"].split(".")[0] if int(v) < 8: msg = f"Elasticsearch version must be greater than or equal to 8, current version: {v}" logging.error(msg) raise Exception(msg) def _connect(self): self.es_conn = Elasticsearch( self.ES_CONFIG["hosts"].split(","), basic_auth=(self.ES_CONFIG["username"], self.ES_CONFIG[ "password"]) if "username" in self.ES_CONFIG and "password" in self.ES_CONFIG else None, verify_certs= self.ES_CONFIG.get("verify_certs", False), timeout=600 ) if self.es_conn: self.info = self.es_conn.info() return True return False def get_conn(self): return self.es_conn def refresh_conn(self): if self.es_conn.ping(): return self.es_conn else: # close current if exist if self.es_conn: self.es_conn.close() self._connect() return self.es_conn def __del__(self): if hasattr(self, "es_conn") and self.es_conn: self.es_conn.close() ES_CONN = ElasticSearchConnectionPool()
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/doc_store/infinity_conn_base.py
common/doc_store/infinity_conn_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. # import logging import os import re import json import time from abc import abstractmethod import infinity from infinity.common import ConflictType from infinity.index import IndexInfo, IndexType from infinity.errors import ErrorCode import pandas as pd from common.file_utils import get_project_base_directory from rag.nlp import is_english from common import settings from common.doc_store.doc_store_base import DocStoreConnection, MatchExpr, OrderByExpr class InfinityConnectionBase(DocStoreConnection): def __init__(self, mapping_file_name: str="infinity_mapping.json", logger_name: str="ragflow.infinity_conn"): from common.doc_store.infinity_conn_pool import INFINITY_CONN self.dbName = settings.INFINITY.get("db_name", "default_db") self.mapping_file_name = mapping_file_name self.logger = logging.getLogger(logger_name) infinity_uri = settings.INFINITY["uri"] if ":" in infinity_uri: host, port = infinity_uri.split(":") infinity_uri = infinity.common.NetworkAddress(host, int(port)) self.connPool = None self.logger.info(f"Use Infinity {infinity_uri} as the doc engine.") conn_pool = INFINITY_CONN.get_conn_pool() for _ in range(24): try: inf_conn = conn_pool.get_conn() res = inf_conn.show_current_node() if res.error_code == ErrorCode.OK and res.server_status in ["started", "alive"]: self._migrate_db(inf_conn) self.connPool = conn_pool conn_pool.release_conn(inf_conn) break conn_pool.release_conn(inf_conn) self.logger.warning(f"Infinity status: {res.server_status}. Waiting Infinity {infinity_uri} to be healthy.") time.sleep(5) except Exception as e: conn_pool = INFINITY_CONN.refresh_conn_pool() self.logger.warning(f"{str(e)}. Waiting Infinity {infinity_uri} to be healthy.") time.sleep(5) if self.connPool is None: msg = f"Infinity {infinity_uri} is unhealthy in 120s." self.logger.error(msg) raise Exception(msg) self.logger.info(f"Infinity {infinity_uri} is healthy.") def _migrate_db(self, inf_conn): inf_db = inf_conn.create_database(self.dbName, ConflictType.Ignore) fp_mapping = os.path.join(get_project_base_directory(), "conf", self.mapping_file_name) if not os.path.exists(fp_mapping): raise Exception(f"Mapping file not found at {fp_mapping}") schema = json.load(open(fp_mapping)) table_names = inf_db.list_tables().table_names for table_name in table_names: inf_table = inf_db.get_table(table_name) index_names = inf_table.list_indexes().index_names if "q_vec_idx" not in index_names: # Skip tables not created by me continue column_names = inf_table.show_columns()["name"] column_names = set(column_names) for field_name, field_info in schema.items(): if field_name in column_names: continue res = inf_table.add_columns({field_name: field_info}) assert res.error_code == infinity.ErrorCode.OK self.logger.info(f"INFINITY added following column to table {table_name}: {field_name} {field_info}") if field_info["type"] != "varchar" or "analyzer" not in field_info: continue analyzers = field_info["analyzer"] if isinstance(analyzers, str): analyzers = [analyzers] for analyzer in analyzers: inf_table.create_index( f"ft_{re.sub(r'[^a-zA-Z0-9]', '_', field_name)}_{re.sub(r'[^a-zA-Z0-9]', '_', analyzer)}", IndexInfo(field_name, IndexType.FullText, {"ANALYZER": analyzer}), ConflictType.Ignore, ) """ Dataframe and fields convert """ @staticmethod @abstractmethod def field_keyword(field_name: str): # judge keyword or not, such as "*_kwd" tag-like columns. raise NotImplementedError("Not implemented") @abstractmethod def convert_select_fields(self, output_fields: list[str]) -> list[str]: # rm _kwd, _tks, _sm_tks, _with_weight suffix in field name. raise NotImplementedError("Not implemented") @staticmethod @abstractmethod def convert_matching_field(field_weight_str: str) -> str: # convert matching field to raise NotImplementedError("Not implemented") @staticmethod def list2str(lst: str | list, sep: str = " ") -> str: if isinstance(lst, str): return lst return sep.join(lst) def equivalent_condition_to_str(self, condition: dict, table_instance=None) -> str | None: assert "_id" not in condition columns = {} if table_instance: for n, ty, de, _ in table_instance.show_columns().rows(): columns[n] = (ty, de) def exists(cln): nonlocal columns assert cln in columns, f"'{cln}' should be in '{columns}'." ty, de = columns[cln] if ty.lower().find("cha"): if not de: de = "" return f" {cln}!='{de}' " return f"{cln}!={de}" cond = list() for k, v in condition.items(): if not isinstance(k, str) or not v: continue if self.field_keyword(k): if isinstance(v, list): inCond = list() for item in v: if isinstance(item, str): item = item.replace("'", "''") inCond.append(f"filter_fulltext('{self.convert_matching_field(k)}', '{item}')") if inCond: strInCond = " or ".join(inCond) strInCond = f"({strInCond})" cond.append(strInCond) else: cond.append(f"filter_fulltext('{self.convert_matching_field(k)}', '{v}')") elif isinstance(v, list): inCond = list() for item in v: if isinstance(item, str): item = item.replace("'", "''") inCond.append(f"'{item}'") else: inCond.append(str(item)) if inCond: strInCond = ", ".join(inCond) strInCond = f"{k} IN ({strInCond})" cond.append(strInCond) elif k == "must_not": if isinstance(v, dict): for kk, vv in v.items(): if kk == "exists": cond.append("NOT (%s)" % exists(vv)) elif isinstance(v, str): cond.append(f"{k}='{v}'") elif k == "exists": cond.append(exists(v)) else: cond.append(f"{k}={str(v)}") return " AND ".join(cond) if cond else "1=1" @staticmethod def concat_dataframes(df_list: list[pd.DataFrame], select_fields: list[str]) -> pd.DataFrame: df_list2 = [df for df in df_list if not df.empty] if df_list2: return pd.concat(df_list2, axis=0).reset_index(drop=True) schema = [] for field_name in select_fields: if field_name == "score()": # Workaround: fix schema is changed to score() schema.append("SCORE") elif field_name == "similarity()": # Workaround: fix schema is changed to similarity() schema.append("SIMILARITY") else: schema.append(field_name) return pd.DataFrame(columns=schema) """ Database operations """ def db_type(self) -> str: return "infinity" def health(self) -> dict: """ Return the health status of the database. """ inf_conn = self.connPool.get_conn() res = inf_conn.show_current_node() self.connPool.release_conn(inf_conn) res2 = { "type": "infinity", "status": "green" if res.error_code == 0 and res.server_status in ["started", "alive"] else "red", "error": res.error_msg, } return res2 """ Table operations """ def create_idx(self, index_name: str, dataset_id: str, vector_size: int): table_name = f"{index_name}_{dataset_id}" inf_conn = self.connPool.get_conn() inf_db = inf_conn.create_database(self.dbName, ConflictType.Ignore) fp_mapping = os.path.join(get_project_base_directory(), "conf", self.mapping_file_name) if not os.path.exists(fp_mapping): raise Exception(f"Mapping file not found at {fp_mapping}") schema = json.load(open(fp_mapping)) vector_name = f"q_{vector_size}_vec" schema[vector_name] = {"type": f"vector,{vector_size},float"} inf_table = inf_db.create_table( table_name, schema, ConflictType.Ignore, ) inf_table.create_index( "q_vec_idx", IndexInfo( vector_name, IndexType.Hnsw, { "M": "16", "ef_construction": "50", "metric": "cosine", "encode": "lvq", }, ), ConflictType.Ignore, ) for field_name, field_info in schema.items(): if field_info["type"] != "varchar" or "analyzer" not in field_info: continue analyzers = field_info["analyzer"] if isinstance(analyzers, str): analyzers = [analyzers] for analyzer in analyzers: inf_table.create_index( f"ft_{re.sub(r'[^a-zA-Z0-9]', '_', field_name)}_{re.sub(r'[^a-zA-Z0-9]', '_', analyzer)}", IndexInfo(field_name, IndexType.FullText, {"ANALYZER": analyzer}), ConflictType.Ignore, ) self.connPool.release_conn(inf_conn) self.logger.info(f"INFINITY created table {table_name}, vector size {vector_size}") return True def delete_idx(self, index_name: str, dataset_id: str): table_name = f"{index_name}_{dataset_id}" inf_conn = self.connPool.get_conn() db_instance = inf_conn.get_database(self.dbName) db_instance.drop_table(table_name, ConflictType.Ignore) self.connPool.release_conn(inf_conn) self.logger.info(f"INFINITY dropped table {table_name}") def index_exist(self, index_name: str, dataset_id: str) -> bool: table_name = f"{index_name}_{dataset_id}" try: inf_conn = self.connPool.get_conn() db_instance = inf_conn.get_database(self.dbName) _ = db_instance.get_table(table_name) self.connPool.release_conn(inf_conn) return True except Exception as e: self.logger.warning(f"INFINITY indexExist {str(e)}") return False """ CRUD operations """ @abstractmethod def search( self, select_fields: list[str], highlight_fields: list[str], condition: dict, match_expressions: list[MatchExpr], order_by: OrderByExpr, offset: int, limit: int, index_names: str | list[str], dataset_ids: list[str], agg_fields: list[str] | None = None, rank_feature: dict | None = None, ) -> tuple[pd.DataFrame, int]: raise NotImplementedError("Not implemented") @abstractmethod def get(self, doc_id: str, index_name: str, knowledgebase_ids: list[str]) -> dict | None: raise NotImplementedError("Not implemented") @abstractmethod def insert(self, documents: list[dict], index_name: str, dataset_ids: str = None) -> list[str]: raise NotImplementedError("Not implemented") @abstractmethod def update(self, condition: dict, new_value: dict, index_name: str, dataset_id: str) -> bool: raise NotImplementedError("Not implemented") def delete(self, condition: dict, index_name: str, dataset_id: str) -> int: inf_conn = self.connPool.get_conn() db_instance = inf_conn.get_database(self.dbName) table_name = f"{index_name}_{dataset_id}" try: table_instance = db_instance.get_table(table_name) except Exception: self.logger.warning(f"Skipped deleting from table {table_name} since the table doesn't exist.") return 0 filter = self.equivalent_condition_to_str(condition, table_instance) self.logger.debug(f"INFINITY delete table {table_name}, filter {filter}.") res = table_instance.delete(filter) self.connPool.release_conn(inf_conn) return res.deleted_rows """ Helper functions for search result """ def get_total(self, res: tuple[pd.DataFrame, int] | pd.DataFrame) -> int: if isinstance(res, tuple): return res[1] return len(res) def get_doc_ids(self, res: tuple[pd.DataFrame, int] | pd.DataFrame) -> list[str]: if isinstance(res, tuple): res = res[0] return list(res["id"]) @abstractmethod def get_fields(self, res: tuple[pd.DataFrame, int] | pd.DataFrame, fields: list[str]) -> dict[str, dict]: raise NotImplementedError("Not implemented") def get_highlight(self, res: tuple[pd.DataFrame, int] | pd.DataFrame, keywords: list[str], field_name: str): if isinstance(res, tuple): res = res[0] ans = {} num_rows = len(res) column_id = res["id"] if field_name not in res: return {} for i in range(num_rows): id = column_id[i] txt = res[field_name][i] if re.search(r"<em>[^<>]+</em>", txt, flags=re.IGNORECASE | re.MULTILINE): ans[id] = txt continue txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE | re.MULTILINE) txt_list = [] for t in re.split(r"[.?!;\n]", txt): if is_english([t]): for w in keywords: t = re.sub( r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])" % re.escape(w), r"\1<em>\2</em>\3", t, flags=re.IGNORECASE | re.MULTILINE, ) else: for w in sorted(keywords, key=len, reverse=True): t = re.sub( re.escape(w), f"<em>{w}</em>", t, flags=re.IGNORECASE | re.MULTILINE, ) if not re.search(r"<em>[^<>]+</em>", t, flags=re.IGNORECASE | re.MULTILINE): continue txt_list.append(t) if txt_list: ans[id] = "...".join(txt_list) else: ans[id] = txt return ans def get_aggregation(self, res: tuple[pd.DataFrame, int] | pd.DataFrame, field_name: str): """ Manual aggregation for tag fields since Infinity doesn't provide native aggregation """ from collections import Counter # Extract DataFrame from result if isinstance(res, tuple): df, _ = res else: df = res if df.empty or field_name not in df.columns: return [] # Aggregate tag counts tag_counter = Counter() for value in df[field_name]: if pd.isna(value) or not value: continue # Handle different tag formats if isinstance(value, str): # Split by ### for tag_kwd field or comma for other formats if field_name == "tag_kwd" and "###" in value: tags = [tag.strip() for tag in value.split("###") if tag.strip()] else: # Try comma separation as fallback tags = [tag.strip() for tag in value.split(",") if tag.strip()] for tag in tags: if tag: # Only count non-empty tags tag_counter[tag] += 1 elif isinstance(value, list): # Handle list format for tag in value: if tag and isinstance(tag, str): tag_counter[tag.strip()] += 1 # Return as list of [tag, count] pairs, sorted by count descending return [[tag, count] for tag, count in tag_counter.most_common()] """ SQL """ def sql(self, sql: str, fetch_size: int, format: str): raise NotImplementedError("Not implemented")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/doc_store/es_conn_base.py
common/doc_store/es_conn_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. # import logging import re import json import time import os from abc import abstractmethod from elasticsearch import NotFoundError from elasticsearch_dsl import Index from elastic_transport import ConnectionTimeout from common.file_utils import get_project_base_directory from common.misc_utils import convert_bytes from common.doc_store.doc_store_base import DocStoreConnection, OrderByExpr, MatchExpr from rag.nlp import is_english, rag_tokenizer from common import settings ATTEMPT_TIME = 2 class ESConnectionBase(DocStoreConnection): def __init__(self, mapping_file_name: str="mapping.json", logger_name: str='ragflow.es_conn'): from common.doc_store.es_conn_pool import ES_CONN self.logger = logging.getLogger(logger_name) self.info = {} self.logger.info(f"Use Elasticsearch {settings.ES['hosts']} as the doc engine.") self.es = ES_CONN.get_conn() fp_mapping = os.path.join(get_project_base_directory(), "conf", mapping_file_name) if not os.path.exists(fp_mapping): msg = f"Elasticsearch mapping file not found at {fp_mapping}" self.logger.error(msg) raise Exception(msg) self.mapping = json.load(open(fp_mapping, "r")) self.logger.info(f"Elasticsearch {settings.ES['hosts']} is healthy.") def _connect(self): from common.doc_store.es_conn_pool import ES_CONN if self.es.ping(): return True self.es = ES_CONN.refresh_conn() return True """ Database operations """ def db_type(self) -> str: return "elasticsearch" def health(self) -> dict: health_dict = dict(self.es.cluster.health()) health_dict["type"] = "elasticsearch" return health_dict def get_cluster_stats(self): """ curl -XGET "http://{es_host}/_cluster/stats" -H "kbn-xsrf: reporting" to view raw stats. """ raw_stats = self.es.cluster.stats() self.logger.debug(f"ESConnection.get_cluster_stats: {raw_stats}") try: res = { 'cluster_name': raw_stats['cluster_name'], 'status': raw_stats['status'] } indices_status = raw_stats['indices'] res.update({ 'indices': indices_status['count'], 'indices_shards': indices_status['shards']['total'] }) doc_info = indices_status['docs'] res.update({ 'docs': doc_info['count'], 'docs_deleted': doc_info['deleted'] }) store_info = indices_status['store'] res.update({ 'store_size': convert_bytes(store_info['size_in_bytes']), 'total_dataset_size': convert_bytes(store_info['total_data_set_size_in_bytes']) }) mappings_info = indices_status['mappings'] res.update({ 'mappings_fields': mappings_info['total_field_count'], 'mappings_deduplicated_fields': mappings_info['total_deduplicated_field_count'], 'mappings_deduplicated_size': convert_bytes(mappings_info['total_deduplicated_mapping_size_in_bytes']) }) node_info = raw_stats['nodes'] res.update({ 'nodes': node_info['count']['total'], 'nodes_version': node_info['versions'], 'os_mem': convert_bytes(node_info['os']['mem']['total_in_bytes']), 'os_mem_used': convert_bytes(node_info['os']['mem']['used_in_bytes']), 'os_mem_used_percent': node_info['os']['mem']['used_percent'], 'jvm_versions': node_info['jvm']['versions'][0]['vm_version'], 'jvm_heap_used': convert_bytes(node_info['jvm']['mem']['heap_used_in_bytes']), 'jvm_heap_max': convert_bytes(node_info['jvm']['mem']['heap_max_in_bytes']) }) return res except Exception as e: self.logger.exception(f"ESConnection.get_cluster_stats: {e}") return None """ Table operations """ def create_idx(self, index_name: str, dataset_id: str, vector_size: int): if self.index_exist(index_name, dataset_id): return True try: from elasticsearch.client import IndicesClient return IndicesClient(self.es).create(index=index_name, settings=self.mapping["settings"], mappings=self.mapping["mappings"]) except Exception: self.logger.exception("ESConnection.createIndex error %s" % index_name) def delete_idx(self, index_name: str, dataset_id: str): if len(dataset_id) > 0: # The index need to be alive after any kb deletion since all kb under this tenant are in one index. return try: self.es.indices.delete(index=index_name, allow_no_indices=True) except NotFoundError: pass except Exception: self.logger.exception("ESConnection.deleteIdx error %s" % index_name) def index_exist(self, index_name: str, dataset_id: str = None) -> bool: s = Index(index_name, self.es) for i in range(ATTEMPT_TIME): try: return s.exists() except ConnectionTimeout: self.logger.exception("ES request timeout") time.sleep(3) self._connect() continue except Exception as e: self.logger.exception(e) break return False """ CRUD operations """ def get(self, doc_id: str, index_name: str, dataset_ids: list[str]) -> dict | None: for i in range(ATTEMPT_TIME): try: res = self.es.get(index=index_name, id=doc_id, source=True, ) if str(res.get("timed_out", "")).lower() == "true": raise Exception("Es Timeout.") doc = res["_source"] doc["id"] = doc_id return doc except NotFoundError: return None except Exception as e: self.logger.exception(f"ESConnection.get({doc_id}) got exception") raise e self.logger.error(f"ESConnection.get timeout for {ATTEMPT_TIME} times!") raise Exception("ESConnection.get timeout.") @abstractmethod def search( self, select_fields: list[str], highlight_fields: list[str], condition: dict, match_expressions: list[MatchExpr], order_by: OrderByExpr, offset: int, limit: int, index_names: str | list[str], dataset_ids: list[str], agg_fields: list[str] | None = None, rank_feature: dict | None = None ): raise NotImplementedError("Not implemented") @abstractmethod def insert(self, documents: list[dict], index_name: str, dataset_id: str = None) -> list[str]: raise NotImplementedError("Not implemented") @abstractmethod def update(self, condition: dict, new_value: dict, index_name: str, dataset_id: str) -> bool: raise NotImplementedError("Not implemented") @abstractmethod def delete(self, condition: dict, index_name: str, dataset_id: str) -> int: raise NotImplementedError("Not implemented") """ Helper functions for search result """ def get_total(self, res): if isinstance(res["hits"]["total"], type({})): return res["hits"]["total"]["value"] return res["hits"]["total"] def get_doc_ids(self, res): return [d["_id"] for d in res["hits"]["hits"]] def _get_source(self, res): rr = [] for d in res["hits"]["hits"]: d["_source"]["id"] = d["_id"] d["_source"]["_score"] = d["_score"] rr.append(d["_source"]) return rr @abstractmethod def get_fields(self, res, fields: list[str]) -> dict[str, dict]: raise NotImplementedError("Not implemented") def get_highlight(self, res, keywords: list[str], field_name: str): ans = {} for d in res["hits"]["hits"]: highlights = d.get("highlight") if not highlights: continue txt = "...".join([a for a in list(highlights.items())[0][1]]) if not is_english(txt.split()): ans[d["_id"]] = txt continue txt = d["_source"][field_name] txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE | re.MULTILINE) txt_list = [] for t in re.split(r"[.?!;\n]", txt): for w in keywords: t = re.sub(r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])" % re.escape(w), r"\1<em>\2</em>\3", t, flags=re.IGNORECASE | re.MULTILINE) if not re.search(r"<em>[^<>]+</em>", t, flags=re.IGNORECASE | re.MULTILINE): continue txt_list.append(t) ans[d["_id"]] = "...".join(txt_list) if txt_list else "...".join([a for a in list(highlights.items())[0][1]]) return ans def get_aggregation(self, res, field_name: str): agg_field = "aggs_" + field_name if "aggregations" not in res or agg_field not in res["aggregations"]: return list() buckets = res["aggregations"][agg_field]["buckets"] return [(b["key"], b["doc_count"]) for b in buckets] """ SQL """ def sql(self, sql: str, fetch_size: int, format: str): self.logger.debug(f"ESConnection.sql get sql: {sql}") sql = re.sub(r"[ `]+", " ", sql) sql = sql.replace("%", "") replaces = [] for r in re.finditer(r" ([a-z_]+_l?tks)( like | ?= ?)'([^']+)'", sql): fld, v = r.group(1), r.group(3) match = " MATCH({}, '{}', 'operator=OR;minimum_should_match=30%') ".format( fld, rag_tokenizer.fine_grained_tokenize(rag_tokenizer.tokenize(v))) replaces.append( ("{}{}'{}'".format( r.group(1), r.group(2), r.group(3)), match)) for p, r in replaces: sql = sql.replace(p, r, 1) self.logger.debug(f"ESConnection.sql to es: {sql}") for i in range(ATTEMPT_TIME): try: res = self.es.sql.query(body={"query": sql, "fetch_size": fetch_size}, format=format, request_timeout="2s") return res except ConnectionTimeout: self.logger.exception("ES request timeout") time.sleep(3) self._connect() continue except Exception as e: self.logger.exception(f"ESConnection.sql got exception. SQL:\n{sql}") raise Exception(f"SQL error: {e}\n\nSQL: {sql}") self.logger.error(f"ESConnection.sql timeout for {ATTEMPT_TIME} times!") return None
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/doc_store/doc_store_base.py
common/doc_store/doc_store_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. # from abc import ABC, abstractmethod from dataclasses import dataclass import numpy as np DEFAULT_MATCH_VECTOR_TOPN = 10 DEFAULT_MATCH_SPARSE_TOPN = 10 VEC = list | np.ndarray @dataclass class SparseVector: indices: list[int] values: list[float] | list[int] | None = None def __post_init__(self): assert (self.values is None) or (len(self.indices) == len(self.values)) def to_dict_old(self): d = {"indices": self.indices} if self.values is not None: d["values"] = self.values return d def to_dict(self): if self.values is None: raise ValueError("SparseVector.values is None") result = {} for i, v in zip(self.indices, self.values): result[str(i)] = v return result @staticmethod def from_dict(d): return SparseVector(d["indices"], d.get("values")) def __str__(self): return f"SparseVector(indices={self.indices}{'' if self.values is None else f', values={self.values}'})" def __repr__(self): return str(self) class MatchTextExpr: def __init__( self, fields: list[str], matching_text: str, topn: int, extra_options: dict | None = None, ): self.fields = fields self.matching_text = matching_text self.topn = topn self.extra_options = extra_options class MatchDenseExpr: def __init__( self, vector_column_name: str, embedding_data: VEC, embedding_data_type: str, distance_type: str, topn: int = DEFAULT_MATCH_VECTOR_TOPN, extra_options: dict | None = None, ): self.vector_column_name = vector_column_name self.embedding_data = embedding_data self.embedding_data_type = embedding_data_type self.distance_type = distance_type self.topn = topn self.extra_options = extra_options class MatchSparseExpr: def __init__( self, vector_column_name: str, sparse_data: SparseVector | dict, distance_type: str, topn: int, opt_params: dict | None = None, ): self.vector_column_name = vector_column_name self.sparse_data = sparse_data self.distance_type = distance_type self.topn = topn self.opt_params = opt_params class MatchTensorExpr: def __init__( self, column_name: str, query_data: VEC, query_data_type: str, topn: int, extra_option: dict | None = None, ): self.column_name = column_name self.query_data = query_data self.query_data_type = query_data_type self.topn = topn self.extra_option = extra_option class FusionExpr: def __init__(self, method: str, topn: int, fusion_params: dict | None = None): self.method = method self.topn = topn self.fusion_params = fusion_params MatchExpr = MatchTextExpr | MatchDenseExpr | MatchSparseExpr | MatchTensorExpr | FusionExpr class OrderByExpr: def __init__(self): self.fields = list() def asc(self, field: str): self.fields.append((field, 0)) return self def desc(self, field: str): self.fields.append((field, 1)) return self def fields(self): return self.fields class DocStoreConnection(ABC): """ Database operations """ @abstractmethod def db_type(self) -> str: """ Return the type of the database. """ raise NotImplementedError("Not implemented") @abstractmethod def health(self) -> dict: """ Return the health status of the database. """ raise NotImplementedError("Not implemented") """ Table operations """ @abstractmethod def create_idx(self, index_name: str, dataset_id: str, vector_size: int): """ Create an index with given name """ raise NotImplementedError("Not implemented") @abstractmethod def delete_idx(self, index_name: str, dataset_id: str): """ Delete an index with given name """ raise NotImplementedError("Not implemented") @abstractmethod def index_exist(self, index_name: str, dataset_id: str) -> bool: """ Check if an index with given name exists """ raise NotImplementedError("Not implemented") """ CRUD operations """ @abstractmethod def search( self, select_fields: list[str], highlight_fields: list[str], condition: dict, match_expressions: list[MatchExpr], order_by: OrderByExpr, offset: int, limit: int, index_names: str|list[str], dataset_ids: list[str], agg_fields: list[str] | None = None, rank_feature: dict | None = None ): """ Search with given conjunctive equivalent filtering condition and return all fields of matched documents """ raise NotImplementedError("Not implemented") @abstractmethod def get(self, data_id: str, index_name: str, dataset_ids: list[str]) -> dict | None: """ Get single chunk with given id """ raise NotImplementedError("Not implemented") @abstractmethod def insert(self, rows: list[dict], index_name: str, dataset_id: str = None) -> list[str]: """ Update or insert a bulk of rows """ raise NotImplementedError("Not implemented") @abstractmethod def update(self, condition: dict, new_value: dict, index_name: str, dataset_id: str) -> bool: """ Update rows with given conjunctive equivalent filtering condition """ raise NotImplementedError("Not implemented") @abstractmethod def delete(self, condition: dict, index_name: str, dataset_id: str) -> int: """ Delete rows with given conjunctive equivalent filtering condition """ raise NotImplementedError("Not implemented") """ Helper functions for search result """ @abstractmethod def get_total(self, res): raise NotImplementedError("Not implemented") @abstractmethod def get_doc_ids(self, res): raise NotImplementedError("Not implemented") @abstractmethod def get_fields(self, res, fields: list[str]) -> dict[str, dict]: raise NotImplementedError("Not implemented") @abstractmethod def get_highlight(self, res, keywords: list[str], field_name: str): raise NotImplementedError("Not implemented") @abstractmethod def get_aggregation(self, res, field_name: str): raise NotImplementedError("Not implemented") """ SQL """ @abstractmethod def sql(self, sql: str, fetch_size: int, format: str): """ Run the sql generated by text-to-sql """ raise NotImplementedError("Not implemented")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/doc_store/__init__.py
common/doc_store/__init__.py
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/data_source/interfaces.py
common/data_source/interfaces.py
"""Interface definitions""" import abc import uuid from abc import ABC, abstractmethod from enum import IntFlag, auto from types import TracebackType from typing import Any, Dict, Generator, TypeVar, Generic, Callable, TypeAlias from collections.abc import Iterator from anthropic import BaseModel from common.data_source.models import ( Document, SlimDocument, ConnectorCheckpoint, ConnectorFailure, SecondsSinceUnixEpoch, GenerateSlimDocumentOutput ) GenerateDocumentsOutput = Iterator[list[Document]] class LoadConnector(ABC): """Load connector interface""" @abstractmethod def load_credentials(self, credentials: Dict[str, Any]) -> Dict[str, Any] | None: """Load credentials""" pass @abstractmethod def load_from_state(self) -> Generator[list[Document], None, None]: """Load documents from state""" pass def validate_connector_settings(self) -> None: """Validate connector settings""" pass class PollConnector(ABC): """Poll connector interface""" @abstractmethod def poll_source(self, start: SecondsSinceUnixEpoch, end: SecondsSinceUnixEpoch) -> Generator[list[Document], None, None]: """Poll source to get documents""" pass class CredentialsConnector(ABC): """Credentials connector interface""" @abstractmethod def load_credentials(self, credentials: Dict[str, Any]) -> Dict[str, Any] | None: """Load credentials""" pass class SlimConnectorWithPermSync(ABC): """Simplified connector interface (with permission sync)""" @abstractmethod def retrieve_all_slim_docs_perm_sync( self, start: SecondsSinceUnixEpoch | None = None, end: SecondsSinceUnixEpoch | None = None, callback: Any = None, ) -> Generator[list[SlimDocument], None, None]: """Retrieve all simplified documents (with permission sync)""" pass class CheckpointedConnectorWithPermSync(ABC): """Checkpoint connector interface (with permission sync)""" @abstractmethod def load_from_checkpoint( self, start: SecondsSinceUnixEpoch, end: SecondsSinceUnixEpoch, checkpoint: ConnectorCheckpoint, ) -> Generator[Document | ConnectorFailure, None, ConnectorCheckpoint]: """Load documents from checkpoint""" pass @abstractmethod def load_from_checkpoint_with_perm_sync( self, start: SecondsSinceUnixEpoch, end: SecondsSinceUnixEpoch, checkpoint: ConnectorCheckpoint, ) -> Generator[Document | ConnectorFailure, None, ConnectorCheckpoint]: """Load documents from checkpoint (with permission sync)""" pass @abstractmethod def build_dummy_checkpoint(self) -> ConnectorCheckpoint: """Build dummy checkpoint""" pass @abstractmethod def validate_checkpoint_json(self, checkpoint_json: str) -> ConnectorCheckpoint: """Validate checkpoint JSON""" pass T = TypeVar("T", bound="CredentialsProviderInterface") class CredentialsProviderInterface(abc.ABC, Generic[T]): @abc.abstractmethod def __enter__(self) -> T: raise NotImplementedError @abc.abstractmethod def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: raise NotImplementedError @abc.abstractmethod def get_tenant_id(self) -> str | None: raise NotImplementedError @abc.abstractmethod def get_provider_key(self) -> str: """a unique key that the connector can use to lock around a credential that might be used simultaneously. Will typically be the credential id, but can also just be something random in cases when there is nothing to lock (aka static credentials) """ raise NotImplementedError @abc.abstractmethod def get_credentials(self) -> dict[str, Any]: raise NotImplementedError @abc.abstractmethod def set_credentials(self, credential_json: dict[str, Any]) -> None: raise NotImplementedError @abc.abstractmethod def is_dynamic(self) -> bool: """If dynamic, the credentials may change during usage ... meaning the client needs to use the locking features of the credentials provider to operate correctly. If static, the client can simply reference the credentials once and use them through the entire indexing run. """ raise NotImplementedError class StaticCredentialsProvider( CredentialsProviderInterface["StaticCredentialsProvider"] ): """Implementation (a very simple one!) to handle static credentials.""" def __init__( self, tenant_id: str | None, connector_name: str, credential_json: dict[str, Any], ): self._tenant_id = tenant_id self._connector_name = connector_name self._credential_json = credential_json self._provider_key = str(uuid.uuid4()) def __enter__(self) -> "StaticCredentialsProvider": return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: pass def get_tenant_id(self) -> str | None: return self._tenant_id def get_provider_key(self) -> str: return self._provider_key def get_credentials(self) -> dict[str, Any]: return self._credential_json def set_credentials(self, credential_json: dict[str, Any]) -> None: self._credential_json = credential_json def is_dynamic(self) -> bool: return False CT = TypeVar("CT", bound=ConnectorCheckpoint) class BaseConnector(abc.ABC, Generic[CT]): REDIS_KEY_PREFIX = "da_connector_data:" # Common image file extensions supported across connectors IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif"} @abc.abstractmethod def load_credentials(self, credentials: dict[str, Any]) -> dict[str, Any] | None: raise NotImplementedError @staticmethod def parse_metadata(metadata: dict[str, Any]) -> list[str]: """Parse the metadata for a document/chunk into a string to pass to Generative AI as additional context""" custom_parser_req_msg = ( "Specific metadata parsing required, connector has not implemented it." ) metadata_lines = [] for metadata_key, metadata_value in metadata.items(): if isinstance(metadata_value, str): metadata_lines.append(f"{metadata_key}: {metadata_value}") elif isinstance(metadata_value, list): if not all([isinstance(val, str) for val in metadata_value]): raise RuntimeError(custom_parser_req_msg) metadata_lines.append(f'{metadata_key}: {", ".join(metadata_value)}') else: raise RuntimeError(custom_parser_req_msg) return metadata_lines def validate_connector_settings(self) -> None: """ Override this if your connector needs to validate credentials or settings. Raise an exception if invalid, otherwise do nothing. Default is a no-op (always successful). """ def validate_perm_sync(self) -> None: """ Permission-sync validation hook. RAGFlow doesn't ship the Onyx EE permission-sync validation package. Connectors that support permission sync should override `validate_connector_settings()` as needed. """ return None def set_allow_images(self, value: bool) -> None: """Implement if the underlying connector wants to skip/allow image downloading based on the application level image analysis setting.""" def build_dummy_checkpoint(self) -> CT: # TODO: find a way to make this work without type: ignore return ConnectorCheckpoint(has_more=True) # type: ignore CheckpointOutput: TypeAlias = Generator[Document | ConnectorFailure, None, CT] LoadFunction = Callable[[CT], CheckpointOutput[CT]] class CheckpointedConnector(BaseConnector[CT]): @abc.abstractmethod def load_from_checkpoint( self, start: SecondsSinceUnixEpoch, end: SecondsSinceUnixEpoch, checkpoint: CT, ) -> CheckpointOutput[CT]: """Yields back documents or failures. Final return is the new checkpoint. Final return can be access via either: ``` try: for document_or_failure in connector.load_from_checkpoint(start, end, checkpoint): print(document_or_failure) except StopIteration as e: checkpoint = e.value # Extracting the return value print(checkpoint) ``` OR ``` checkpoint = yield from connector.load_from_checkpoint(start, end, checkpoint) ``` """ raise NotImplementedError @abc.abstractmethod def build_dummy_checkpoint(self) -> CT: raise NotImplementedError @abc.abstractmethod def validate_checkpoint_json(self, checkpoint_json: str) -> CT: """Validate the checkpoint json and return the checkpoint object""" raise NotImplementedError class CheckpointOutputWrapper(Generic[CT]): """ Wraps a CheckpointOutput generator to give things back in a more digestible format, specifically for Document outputs. The connector format is easier for the connector implementor (e.g. it enforces exactly one new checkpoint is returned AND that the checkpoint is at the end), thus the different formats. """ def __init__(self) -> None: self.next_checkpoint: CT | None = None def __call__( self, checkpoint_connector_generator: CheckpointOutput[CT], ) -> Generator[ tuple[Document | None, ConnectorFailure | None, CT | None], None, None, ]: # grabs the final return value and stores it in the `next_checkpoint` variable def _inner_wrapper( checkpoint_connector_generator: CheckpointOutput[CT], ) -> CheckpointOutput[CT]: self.next_checkpoint = yield from checkpoint_connector_generator return self.next_checkpoint # not used for document_or_failure in _inner_wrapper(checkpoint_connector_generator): if isinstance(document_or_failure, Document): yield document_or_failure, None, None elif isinstance(document_or_failure, ConnectorFailure): yield None, document_or_failure, None else: raise ValueError( f"Invalid document_or_failure type: {type(document_or_failure)}" ) if self.next_checkpoint is None: raise RuntimeError( "Checkpoint is None. This should never happen - the connector should always return a checkpoint." ) yield None, None, self.next_checkpoint class CheckpointedConnectorWithPermSyncGH(CheckpointedConnector[CT]): @abc.abstractmethod def load_from_checkpoint_with_perm_sync( self, start: SecondsSinceUnixEpoch, end: SecondsSinceUnixEpoch, checkpoint: CT, ) -> CheckpointOutput[CT]: raise NotImplementedError # Slim connectors retrieve just the ids of documents class SlimConnector(BaseConnector): @abc.abstractmethod def retrieve_all_slim_docs( self, ) -> GenerateSlimDocumentOutput: raise NotImplementedError class ConfluenceUser(BaseModel): user_id: str # accountId in Cloud, userKey in Server username: str | None # Confluence Cloud doesn't give usernames display_name: str # Confluence Data Center doesn't give email back by default, # have to fetch it with a different endpoint email: str | None type: str class TokenResponse(BaseModel): access_token: str expires_in: int token_type: str refresh_token: str scope: str class OnyxExtensionType(IntFlag): Plain = auto() Document = auto() Multimedia = auto() All = Plain | Document | Multimedia class AttachmentProcessingResult(BaseModel): """ A container for results after processing a Confluence attachment. 'text' is the textual content of the attachment. 'file_name' is the final file name used in FileStore to store the content. 'error' holds an exception or string if something failed. """ text: str | None file_blob: bytes | bytearray | None file_name: str | None error: str | None = None model_config = {"arbitrary_types_allowed": True} class IndexingHeartbeatInterface(ABC): """Defines a callback interface to be passed to run_indexing_entrypoint.""" @abstractmethod def should_stop(self) -> bool: """Signal to stop the looping function in flight.""" @abstractmethod def progress(self, tag: str, amount: int) -> None: """Send progress updates to the caller. Amount can be a positive number to indicate progress or <= 0 just to act as a keep-alive. """
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false
infiniflow/ragflow
https://github.com/infiniflow/ragflow/blob/5ebe334a2f452cb35d4247a8c688bd3d3c76be4c/common/data_source/airtable_connector.py
common/data_source/airtable_connector.py
from datetime import datetime, timezone import logging from typing import Any, Generator import requests from pyairtable import Api as AirtableApi from common.data_source.config import AIRTABLE_CONNECTOR_SIZE_THRESHOLD, INDEX_BATCH_SIZE, DocumentSource from common.data_source.exceptions import ConnectorMissingCredentialError from common.data_source.interfaces import LoadConnector, PollConnector from common.data_source.models import Document, GenerateDocumentsOutput, SecondsSinceUnixEpoch from common.data_source.utils import extract_size_bytes, get_file_ext class AirtableClientNotSetUpError(PermissionError): def __init__(self) -> None: super().__init__( "Airtable client is not set up. Did you forget to call load_credentials()?" ) class AirtableConnector(LoadConnector, PollConnector): """ Lightweight Airtable connector. This connector ingests Airtable attachments as raw blobs without parsing file content or generating text/image sections. """ def __init__( self, base_id: str, table_name_or_id: str, batch_size: int = INDEX_BATCH_SIZE, ) -> None: self.base_id = base_id self.table_name_or_id = table_name_or_id self.batch_size = batch_size self._airtable_client: AirtableApi | None = None self.size_threshold = AIRTABLE_CONNECTOR_SIZE_THRESHOLD # ------------------------- # Credentials # ------------------------- def load_credentials(self, credentials: dict[str, Any]) -> dict[str, Any] | None: self._airtable_client = AirtableApi(credentials["airtable_access_token"]) return None @property def airtable_client(self) -> AirtableApi: if not self._airtable_client: raise AirtableClientNotSetUpError() return self._airtable_client # ------------------------- # Core logic # ------------------------- def load_from_state(self) -> GenerateDocumentsOutput: """ Fetch all Airtable records and ingest attachments as raw blobs. Each attachment is converted into a single Document(blob=...). """ if not self._airtable_client: raise ConnectorMissingCredentialError("Airtable credentials not loaded") table = self.airtable_client.table(self.base_id, self.table_name_or_id) records = table.all() logging.info( f"Starting Airtable blob ingestion for table {self.table_name_or_id}, " f"{len(records)} records found." ) batch: list[Document] = [] for record in records: record_id = record.get("id") fields = record.get("fields", {}) created_time = record.get("createdTime") for field_value in fields.values(): # We only care about attachment fields (lists of dicts with url/filename) if not isinstance(field_value, list): continue for attachment in field_value: url = attachment.get("url") filename = attachment.get("filename") attachment_id = attachment.get("id") if not url or not filename or not attachment_id: continue try: resp = requests.get(url, timeout=30) resp.raise_for_status() content = resp.content except Exception: logging.exception( f"Failed to download attachment {filename} " f"(record={record_id})" ) continue size_bytes = extract_size_bytes(attachment) if ( self.size_threshold is not None and isinstance(size_bytes, int) and size_bytes > self.size_threshold ): logging.warning( f"{filename} exceeds size threshold of {self.size_threshold}. Skipping." ) continue batch.append( Document( id=f"airtable:{record_id}:{attachment_id}", blob=content, source=DocumentSource.AIRTABLE, semantic_identifier=filename, extension=get_file_ext(filename), size_bytes=size_bytes if size_bytes else 0, doc_updated_at=datetime.strptime(created_time, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc) ) ) if len(batch) >= self.batch_size: yield batch batch = [] if batch: yield batch def poll_source(self, start: SecondsSinceUnixEpoch, end: SecondsSinceUnixEpoch) -> Generator[list[Document], None, None]: """Poll source to get documents""" start_dt = datetime.fromtimestamp(start, tz=timezone.utc) end_dt = datetime.fromtimestamp(end, tz=timezone.utc) for batch in self.load_from_state(): filtered: list[Document] = [] for doc in batch: if not doc.doc_updated_at: continue doc_dt = doc.doc_updated_at.astimezone(timezone.utc) if start_dt <= doc_dt < end_dt: filtered.append(doc) if filtered: yield filtered if __name__ == "__main__": import os logging.basicConfig(level=logging.DEBUG) connector = AirtableConnector("xxx","xxx") connector.load_credentials({"airtable_access_token": os.environ.get("AIRTABLE_ACCESS_TOKEN")}) connector.validate_connector_settings() document_batches = connector.load_from_state() try: first_batch = next(document_batches) print(f"Loaded {len(first_batch)} documents in first batch.") for doc in first_batch: print(f"- {doc.semantic_identifier} ({doc.size_bytes} bytes)") except StopIteration: print("No documents available in Dropbox.")
python
Apache-2.0
5ebe334a2f452cb35d4247a8c688bd3d3c76be4c
2026-01-04T14:38:19.006015Z
false