Розробка AI-агента з доступом до файлової системи
AI-агент з доступом до файлової системи може читати, створювати, змінювати та організовувати файли. Це відкриває широкий клас завдань: автоматична обробка документів, аналіз логів, генерація звітів, рефакторинг коду. Ключовий виклик — безпека: агент повинен працювати строго в ізольованій директорії.
Безпечний набір інструментів для роботи з файлами
import os
from pathlib import Path
from typing import Optional
class SafeFilesystemTool:
"""Інструменти файлової системи з обмеженнями пісочниці"""
def __init__(self, sandbox_dir: str):
self.sandbox = Path(sandbox_dir).resolve()
self.sandbox.mkdir(parents=True, exist_ok=True)
def _safe_path(self, relative_path: str) -> Path:
"""Перевіряє, що шлях залишається всередині пісочниці"""
target = (self.sandbox / relative_path).resolve()
if not str(target).startswith(str(self.sandbox)):
raise PermissionError(f"Access denied: {relative_path} is outside sandbox")
return target
def read_file(self, path: str, encoding: str = "utf-8") -> str:
target = self._safe_path(path)
if not target.exists():
return f"Error: File {path} not found"
if target.stat().st_size > 10 * 1024 * 1024: # Ліміт 10MB
return f"Error: File too large (>10MB)"
return target.read_text(encoding=encoding)
def write_file(self, path: str, content: str) -> str:
target = self._safe_path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return f"Successfully written {len(content)} characters to {path}"
def list_directory(self, path: str = ".") -> str:
target = self._safe_path(path)
if not target.is_dir():
return f"Error: {path} is not a directory"
items = []
for item in sorted(target.iterdir()):
size = item.stat().st_size if item.is_file() else "-"
type_char = "d" if item.is_dir() else "f"
items.append(f"{type_char} {item.name} ({size} bytes)")
return "\n".join(items) or "Empty directory"
def search_files(self, pattern: str, directory: str = ".") -> str:
target = self._safe_path(directory)
import glob
matches = glob.glob(str(target / "**" / pattern), recursive=True)
relative_matches = [str(Path(m).relative_to(self.sandbox)) for m in matches[:50]]
return "\n".join(relative_matches) or "No files found"
def move_file(self, source: str, destination: str) -> str:
src = self._safe_path(source)
dst = self._safe_path(destination)
src.rename(dst)
return f"Moved {source} to {destination}"
Агент для обробки документів
from openai import OpenAI
import json
client = OpenAI()
fs_tool = SafeFilesystemTool(sandbox_dir="/data/agent_workspace")
# Визначення інструментів OpenAI
fs_tools = [
{
"type": "function",
"function": {
"name": "read_file",
"description": "Прочитати вміст файлу",
"parameters": {"type": "object", "properties": {
"path": {"type": "string", "description": "Відносний шлях до файлу"}
}, "required": ["path"]}
}
},
{
"type": "function",
"function": {
"name": "write_file",
"description": "Створити або перезаписати файл",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"},
"content": {"type": "string"},
}, "required": ["path", "content"]}
}
},
{
"type": "function",
"function": {
"name": "list_directory",
"description": "Список файлів у директорії",
"parameters": {"type": "object", "properties": {
"path": {"type": "string", "default": "."}
}}
}
},
{
"type": "function",
"function": {
"name": "search_files",
"description": "Пошук файлів за шаблоном (glob)",
"parameters": {"type": "object", "properties": {
"pattern": {"type": "string", "description": "Glob шаблон, наприклад *.pdf"},
"directory": {"type": "string", "default": "."}
}, "required": ["pattern"]}
}
},
]
FS_FUNCTIONS = {
"read_file": fs_tool.read_file,
"write_file": fs_tool.write_file,
"list_directory": fs_tool.list_directory,
"search_files": fs_tool.search_files,
}
Практичний випадок: агент для обробки вхідних документів
Завдання: автоматична обробка вхідної кореспонденції — агент сканує папку з PDF, витягує ключову інформацію, класифікує документи, створює структурований реєстр.
Траєкторія:
-
list_directory("incoming/")→ знаходить 45 PDF файлів - Цикл по файлам:
read_file("incoming/doc_001.txt")(конвертований текст) - Витягує: тип документа, відправник, дата, сума (якщо фінансовий), термін відповіді
-
write_file("registry/2026-03-28.json", classified_data)— реєстр -
move_file("incoming/doc_001.pdf", "processed/contracts/doc_001.pdf")— архівування
Метрики:
- Документів обробленних за годину: 3–5 (вручну) → 180–200 (агент)
- Точність класифікації: 91%
- Точність витягування реквізитів: 87%
Docker Sandbox для повної ізоляції
Для production-деплою — запуск агента в Docker контейнері з обмеженим монтуванням:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY agent.py .
# Створюємо workspace без доступу до системних директорій
RUN mkdir /workspace && chmod 755 /workspace
USER nobody
VOLUME ["/workspace"]
CMD ["python", "agent.py"]
docker run \
-v /host/documents:/workspace/documents:ro \ # Документи - лише читання
-v /host/output:/workspace/output:rw \ # Output - читання-запис
--memory=512m --cpus=1 \ # Обмеження ресурсів
document-agent
Терміни
- Розробка інструментів файлової системи з пісочницею: 3–5 днів
- Агент для конкретного workflow: 1–2 тижні
- Тестування безпеки: 3–5 днів
- Всього: 2–4 тижні







