Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions api/core/rag/extractor/helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Document loader helpers."""

import concurrent.futures
from typing import NamedTuple
from typing import NamedTuple, Protocol

import charset_normalizer

Expand All @@ -17,7 +17,34 @@ class FileEncoding(NamedTuple):
"""The language of the file."""


def detect_file_encodings(file_path: str, timeout: int = 5, sample_size: int = 1024 * 1024) -> list[FileEncoding]:
class FileSampleReader(Protocol):
"""Boundary that reads a bounded byte sample from a file on disk.

``detect_file_encodings`` takes one of these so callers and tests can hand
in the filesystem access instead of patching ``builtins.open``.
"""

def __call__(self, file_path: str, sample_size: int) -> bytes: ...


def read_file_sample(file_path: str, sample_size: int) -> bytes:
"""Read at most ``sample_size`` bytes from ``file_path``.

This is the production :class:`FileSampleReader`: it touches the local
filesystem, so callers that run inside a sandbox must pass their own
implementation instead.
"""
with open(file_path, "rb") as file:
return file.read(sample_size)


def detect_file_encodings(
file_path: str,
timeout: int = 5,
sample_size: int = 1024 * 1024,
*,
read_sample: FileSampleReader = read_file_sample,
) -> list[FileEncoding]:
"""Try to detect the file encoding.

Returns a list of `FileEncoding` tuples with the detected encodings ordered
Expand All @@ -28,11 +55,12 @@ def detect_file_encodings(file_path: str, timeout: int = 5, sample_size: int = 1
timeout: The timeout in seconds for the encoding detection.
sample_size: The number of bytes to read for encoding detection. Default is 1MB.
For large files, reading only a sample is sufficient and prevents timeout.
read_sample: The filesystem boundary used to read the sample. Defaults to
reading ``file_path`` from the local filesystem.
"""

def read_and_detect(filename: str):
with open(filename, "rb") as file:
sample = file.read(sample_size)
def read_and_detect(filename: str) -> list[FileEncoding]:
sample = read_sample(filename, sample_size)
rst = charset_normalizer.from_bytes(sample)
best = rst.best()
if best is None:
Expand Down
114 changes: 91 additions & 23 deletions api/core/tools/tool_file_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import urllib.parse
from collections.abc import Generator
from mimetypes import guess_extension, guess_type
from typing import Protocol
from uuid import uuid4

import httpx
Expand All @@ -27,7 +28,52 @@
logger = logging.getLogger(__name__)


class ToolFileStorage(Protocol):
"""Storage operations required by ``ToolFileManager``."""

def save(self, filename: str, data: bytes) -> None:
"""Persist ``data`` under a writable ``filename`` key.

Preconditions: ``filename`` names a key accepted by the backend and
``data`` is the complete byte payload. Postconditions: successful calls
make the payload available under that key. Side effects: writes storage.
Failure invariant: backend errors propagate, and this protocol makes no
atomic-write guarantee; a failed write may leave partial stored data.
"""
...

def load_once(self, filename: str) -> bytes:
"""Read the complete payload stored under ``filename``.

Preconditions: ``filename`` names an existing key accepted by the backend.
Postconditions: successful calls return the stored bytes without mutation.
Side effects: reads storage only. Failure invariant: missing-key/backend
errors propagate and do not modify the stored object.
"""
...

def load_stream(self, filename: str) -> Generator:
"""Read the payload under ``filename`` as a lazy byte stream.

Preconditions: ``filename`` names an existing key accepted by the backend.
Postconditions: successful iteration yields the stored bytes without mutation.
Side effects: reads storage only. Failure invariant: backend errors propagate
during iteration and do not modify the stored object.
"""
...


class ToolFileManager:
def __init__(self, *, storage_service: ToolFileStorage | None = None) -> None:
"""Bind a storage service for all file operations.

Preconditions: an explicitly supplied service implements ``ToolFileStorage``.
Postconditions: this manager uses that service, or the configured global
storage when no service is supplied. Construction performs no I/O.
Failure behavior: construction does not catch or transform errors.
"""
self._storage_service: ToolFileStorage = storage_service if storage_service is not None else storage

@staticmethod
def _build_graph_file_reference(tool_file: ToolFile) -> File:
extension = resolve_extension(filename=tool_file.name, mimetype=tool_file.mimetype)
Expand Down Expand Up @@ -74,6 +120,13 @@ def create_file_by_raw(
mimetype: str,
filename: str | None = None,
) -> ToolFile:
"""Persist raw file bytes and return the committed tool-file row.

Preconditions: the identifiers describe the file owner and ``file_binary``
contains the complete payload. Postconditions: bytes are written through
this manager's storage service and the matching row is persisted. Failures
propagate; a database failure after storage succeeds can leave orphaned bytes.
"""
extension = resolve_extension(filename=filename, mimetype=mimetype)
unique_name = uuid4().hex
unique_filename = f"{unique_name}{extension}"
Expand All @@ -84,7 +137,7 @@ def create_file_by_raw(
# Add extension flexibly
present_filename = filename if has_extension else f"{filename}{extension}"
filepath = f"tools/{tenant_id}/{unique_filename}"
storage.save(filepath, file_binary)
self._storage_service.save(filepath, file_binary)

with session_factory.create_session() as session:
tool_file = ToolFile(
Expand All @@ -111,6 +164,14 @@ def create_file_by_url(
file_url: str,
conversation_id: str | None = None,
) -> ToolFile:
"""Download a remote file, persist its bytes, and return its row.

Preconditions: ``file_url`` is an input accepted by the existing remote
fetcher. Postconditions: downloaded bytes and their metadata row are stored
using this manager's storage service. Fetch, storage, and database failures
propagate (timeouts retain the existing ``ValueError`` behavior); a database
failure after storage succeeds can leave orphaned bytes.
"""
# try to download image
try:
response = remote_fetcher.make_request("GET", file_url)
Expand All @@ -129,7 +190,7 @@ def create_file_by_url(
unique_name = uuid4().hex
filename = f"{unique_name}{extension}"
filepath = f"tools/{tenant_id}/{filename}"
storage.save(filepath, blob)
self._storage_service.save(filepath, blob)
with session_factory.create_session() as session:
tool_file = ToolFile(
user_id=user_id,
Expand All @@ -149,30 +210,34 @@ def create_file_by_url(
return tool_file

def get_file_binary(self, id: str) -> tuple[bytes, str] | None:
"""
get file binary

:param id: the id of the file

:return: the binary of the file, mime type
"""Read bytes and MIME type using any string ``id`` as a lookup key.

Preconditions: ``id`` is a string; the referenced row need not exist.
Postconditions: a missing tool-file row returns ``None``; otherwise the
stored bytes and row MIME type are returned. Side effects: database and
storage access are read-only; persistent state is unchanged on success.
Failure behavior: database or storage errors propagate unchanged without
changing persistent state.
"""
with session_factory.create_session() as session:
tool_file: ToolFile | None = session.scalar(select(ToolFile).where(ToolFile.id == id).limit(1))

if not tool_file:
return None

blob = storage.load_once(tool_file.file_key)
blob = self._storage_service.load_once(tool_file.file_key)

return blob, tool_file.mimetype

def get_file_binary_by_message_file_id(self, id: str) -> tuple[bytes, str] | None:
"""
get file binary

:param id: the id of the file

:return: the binary of the file, mime type
"""Read bytes and MIME type using any string ``id`` as a message lookup key.

Preconditions: ``id`` is a string; the referenced message need not exist.
Postconditions: a missing message, a message without a URL, or a missing
referenced tool-file row returns ``None``; otherwise its bytes and MIME type
are returned. Side effects: database and storage access are read-only;
persistent state is unchanged on success. Failure behavior: database or
storage errors propagate unchanged without changing persistent state.
"""
with session_factory.create_session() as session:
message_file: MessageFile | None = session.scalar(select(MessageFile).where(MessageFile.id == id).limit(1))
Expand All @@ -194,25 +259,28 @@ def get_file_binary_by_message_file_id(self, id: str) -> tuple[bytes, str] | Non
if not tool_file:
return None

blob = storage.load_once(tool_file.file_key)
blob = self._storage_service.load_once(tool_file.file_key)

return blob, tool_file.mimetype

def get_file_generator_by_tool_file_id(self, tool_file_id: str) -> tuple[Generator | None, File | None]:
"""
get file binary

:param tool_file_id: the id of the tool file

:return: the binary of the file, mime type
"""Return a file stream and graph reference using any string key.

Preconditions: ``tool_file_id`` is a string; the referenced row need not
exist. Postconditions: a missing tool-file row returns ``(None, None)``;
otherwise a lazy stream and metadata built from the persisted row are
returned. Side effects: database and storage access are read-only; persistent
state is unchanged on success. Failure behavior: database errors propagate,
and storage errors may propagate while opening or consuming the stream;
failures do not change persistent state.
"""
with session_factory.create_session() as session:
tool_file: ToolFile | None = session.scalar(select(ToolFile).where(ToolFile.id == tool_file_id).limit(1))

if not tool_file:
return None, None

stream = storage.load_stream(tool_file.file_key)
stream = self._storage_service.load_stream(tool_file.file_key)

return stream, self._build_graph_file_reference(tool_file)

Expand Down
Loading