












When building intelligent agents (AI Agents), we often need to enable the Agent to have the ability to read, write, search, and edit files. The DeepAgents framework achieves this byBackend (Backend)The mechanism achieves this function, providing an Agent with a secure and controllable file operation environment. This paper will delve into the concept and usage of Backend, demonstrating its powerful capabilities through four progressive examples.
The Backend is a core abstraction in the DeepAgents framework, defining how Agents interact with the file system. Through the Backend, Agents can:
ls_info)read)write)grep_raw)glob_info)edit)The core value of Backend lies in security and flexibility:It can restrict Agent's file operations within specific directories, preventing unauthorized access, while supporting multiple storage media (local file systems, memory, cloud storage, etc.).
The DeepAgents framework provides multiple Backend implementations to meet the needs of different scenarios:
OpenSandboxBackend: Open-source sandbox solution based on OpenSandbox DaytonaBackend: Cloud sandbox solution based on DaytonaBackendProtocol interface. DictBackend (in-memory storage), RedisBackend (Redis storage), etc. | Backend Types | File Operations | Command Execution | Persistence | Security Isolation | Typical Scenarios |
|---|---|---|---|---|---|
| FilesystemBackend | ✅ | ❌ | ✅ | Medium (virtual_mode) | Local File Processing |
| LocalShellBackend | ✅ | ✅(Local) | ✅ | Medium(virtual_mode) | Local script execution |
| SandboxBackend | ✅ | ✅(Sandbox) | Optional | High(Full isolation) | Cloud secure execution |
| Custom Backend | Custom | Custom | Custom | Custom | Special requirements |
The simplest Agent configuration does not use a Backend and relies solely on tool calls to complete tasks:
from deepagents import create_deep_agent
from langgraph.checkpoint.memory import InMemorySaver
# 创建内存检查点保存器
checkpointer = InMemorySaver()
# 创建基础Agent
agent = create_deep_agent(
model=llm,
tools=[web_search],
#checkpointer=checkpointer,
system_prompt='你是一个助手,请根据用户输入的指令,进行相应的操作。'
)
Features:
When an Agent needs to operate on files,FilesystemBackendThe most common choice:
import os
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
# 创建Agent工作目录
temp_workspace = "./agent_workspace"
os.makedirs(temp_workspace, exist_ok=True)
agent = create_deep_agent(
model=llm,
tools=[web_search],
checkpointer=checkpointer,
backend=FilesystemBackend(
root_dir=temp_workspace,
virtual_mode=True, # 防止Agent通过`../../`跳出根目录
),
system_prompt='你是一个助手,请根据用户输入的指令,进行相应的操作。'
)
Key parameters:
root_dir:Specify the working root directory for the Agentvirtual_mode=True:Enable virtual mode to prevent path traversal attacks (such as ../../etc/passwd):Applicable scenarios:
If the Agent not only needs to operate on files but also execute shell commands, LocalShellBackend is a better choice:
import os
import sys
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
temp_workspace = "./agent_workspace"
os.makedirs(temp_workspace, exist_ok=True)
agent = create_deep_agent(
model=llm,
tools=[web_search],
checkpointer=checkpointer,
backend=LocalShellBackend(
root_dir=temp_workspace,
virtual_mode=True,
timeout=30, # 命令执行超时时间(秒)
max_output_bytes=50000, # 命令输出最大字节数
env={
"PATH": f"{os.path.dirname(sys.executable)};{os.environ.get('PATH', '')}",
},
),
system_prompt='你是一个助手,请根据用户输入的指令,进行相应的操作。'
)
New features:
python script.py, ls -la). Applicable scenarios :
The power of DeepAgents lies in its extensibility. By implementingBackendProtocol, we can create fully customizable Backend:
from deepagents.backends.protocol import BackendProtocol, WriteResult, EditResult
from deepagents.backends.utils import FileInfo, GrepMatch
from datetime import datetime
import re
class DictBackend(BackendProtocol):
"""将文件存储在内存字典中的自定义后端"""
def __init__(self):
self.files = {} # 路径 -> 内容
self.metadata = {} # 路径 -> 元数据
def ls_info(self, path: str) -> list[FileInfo]:
"""列出文件和目录信息"""
result = []
seen_dirs = set()
for file_path in self.files.keys():
if file_path.startswith(path):
remaining = file_path[len(path):]
if '/' in remaining:
dir_name = path + remaining.split('/')[0] + '/'
if dir_name not in seen_dirs:
seen_dirs.add(dir_name)
result.append(FileInfo(path=dir_name, is_dir=True))
else:
meta = self.metadata.get(file_path, {})
result.append(FileInfo(
path=file_path,
is_dir=False,
size=meta.get('size', 0),
modified_at=meta.get('modified_at')
))
return result
def read(self, file_path: str, offset: int = 0, limit: int = 2000) -> str:
"""读取文件内容,支持分页"""
if file_path not in self.files:
return f"Error: File '{file_path}' not found"
content = self.files[file_path]
lines = content.splitlines(keepends=True)
start_line = offset
end_line = start_line + limit if limit > 0 else len(lines)
selected_lines = lines[start_line:end_line]
result = ''.join(f"{start_line + i + 1}: {line}" for i, line in enumerate(selected_lines))
return result if result else "(end of file)"
def write(self, file_path: str, content: str) -> WriteResult:
"""写入新文件(仅创建,不覆盖)"""
if file_path in self.files:
return WriteResult(error=f"File '{file_path}' already exists (create-only).")
self.files[file_path] = content
self.metadata[file_path] = {
'size': len(content),
'modified_at': datetime.now().isoformat()
}
return WriteResult(path=file_path, files_update=None)
def grep_raw(self, pattern: str, path: str | None = None, glob: str | None = None) -> list[GrepMatch] | str:
"""正则表达式搜索文件内容"""
try:
re.compile(pattern)
except re.error as e:
return f"Invalid regex pattern: {e}"
matches = []
for file_path, content in self.files.items():
for i, line in enumerate(content.splitlines()):
if re.search(pattern, line):
matches.append(GrepMatch(path=file_path, line=i+1, text=line))
return matches
def glob_info(self, pattern: str, path: str = "/") -> list[FileInfo]:
"""通配符匹配文件"""
import fnmatch
all_files = [
FileInfo(path=p, is_dir=False, size=self.metadata[p]['size'],
modified_at=self.metadata[p]['modified_at'])
for p in self.files.keys() if p.startswith(path)
]
matched = [fi for fi in all_files if fnmatch.fnmatch(fi.path, path.rstrip('/') + '/' + pattern)]
return matched
def edit(self, file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult:
"""编辑文件内容"""
if file_path not in self.files:
return EditResult(error=f"File '{file_path}' not found")
content = self.files[file_path]
if replace_all:
new_content = content.replace(old_string, new_string)
occurrences = content.count(old_string)
else:
if content.count(old_string) != 1:
return EditResult(error=f"Found {content.count(old_string)} occurrences. For safety, edit requires exactly one match unless replace_all=True.")
new_content = content.replace(old_string, new_string, 1)
occurrences = 1
if new_content == content:
return EditResult(error=f"String '{old_string}' not found.")
self.files[file_path] = new_content
self.metadata[file_path]['size'] = len(new_content)
self.metadata[file_path]['modified_at'] = datetime.now().isoformat()
return EditResult(path=file_path, files_update=None, occurrences=occurrences)
using custom Backend :
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend
from langgraph.checkpoint.memory import InMemorySaver
from my_backend import DictBackend
checkpointer = InMemorySaver()
agent = create_deep_agent(
model=llm,
tools=[web_search],
checkpointer=checkpointer,
backend=DictBackend(),
system_prompt='你是一个助手,请根据用户输入的指令,进行相应的操作。'
)
Advantages of custom Backend :
| Scenario | Recommended Backend | Reason |
|---|---|---|
| Only API calls, no file operations | No Backend | Simple and efficient |
| Need persistent file storage | FilesystemBackend | Direct disk file operations |
| Need to execute shell commands | LocalShellBackend | Support command execution + file operations |
| Need full isolation or custom storage | Custom Backend | Flexible and controllable, suitable for special needs |
Backend is the bridge connecting AI Agent with the file system in the DeepAgents framework. By flexibly selecting or customizing Backend, we can create a secure, efficient, and controllable file operation environment for the Agent. From simple no Backend configuration to powerful LocalShellBackend, to fully customizable DictBackend, DeepAgents provides rich options to meet various application scenarios.
Mastering the use of Backend will help you build more powerful and practical AI Agents, enabling smart agents to truly have "hands-on" capabilities!
This content is automatically aggregated by InertiaRSS (RSS Reader) for reading reference only. Original from — Copyright belongs to the original author.