Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Add multi-file write support for python-sdk sync
0diva379a587f060
diff --git a/packages/js-sdk/tests/sandbox/files/write.test.ts b/packages/js-sdk/tests/sandbox/files/write.test.tsindex 3e918cb26..137e84ebc 100644--- a/packages/js-sdk/tests/sandbox/files/write.test.ts+++ b/packages/js-sdk/tests/sandbox/files/write.test.ts@@ -32,7 +32,7 @@ sandboxTest('write multiple files', async ({ sandbox }) => {assert.include(err.message, 'Expected to receive information about written file')})- // Attempt to write with patn and file array+ // Attempt to write with path and file arrayawait sandbox.files.write('/path/to/file', [{ path: 'one_test_file.txt', data: 'This is a test file.' }]).then((e) => {@@ -68,6 +68,7 @@ sandboxTest('write multiple files', async ({ sandbox }) => {assert.isTrue(Array.isArray(infos))assert.equal((infos as EntryInfo[]).length, files.length)+ // Attempt to write with multiple files in arrayfor (let i = 0; i < files.length; i++) {const file = files[i]const info = infos[i] as EntryInfodiff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.pyindex 8188f144b..8d5eb1815 100644--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py@@ -1,6 +1,6 @@from enum import Enumfrom dataclasses import dataclass-from typing import Optional+from typing import IO, Optional, Unionfrom e2b.envd.filesystem import filesystem_pb2@@ -22,3 +22,10 @@ class EntryInfo:name: strtype: Optional[FileType]path: str++WriteData = Union[str, bytes, IO]++@dataclass+class FileWriteData:+ path: str+ data: WriteDatadiff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.pyindex eea910554..401f00e01 100644--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py@@ -1,5 +1,6 @@from io import TextIOBase-from typing import IO, Iterator, List, Literal, Optional, Union, overload+from typing import Iterator, List, Literal, Optional, overload+from e2b.sandbox.filesystem.filesystem import WriteData, FileWriteDataimport e2b_connectimport httpcore@@ -93,23 +94,48 @@ class Filesystem:def write(self,- path: str,- data: Union[str, bytes, IO],+ path: str | None,+ data: WriteData | List[FileWriteData],user: Username = "user",request_timeout: Optional[float] = None,- ) -> EntryInfo:- """Write to file+ ) -> EntryInfo | List[EntryInfo]:+ """Write to file(s)When writing to a file that doesn't exist, the file will get created.When writing to a file that already exists, the file will get overwritten.When writing to a file that's in a directory that doesn't exist, you'll get an error."""- if isinstance(data, TextIOBase):- data = data.read().encode()++ write_files = []+ if path is None:+ if not isinstance(data, list):+ raise Exception("Expected data to be a list of FileWriteData")+ write_files = data+ else:+ if isinstance(data, list):+ raise Exception("Cannot specify path with array of files")+ write_files = [{"path": path, "data": data}]++ if len(write_files) == 0:+ raise Exception("Need at least one file to write")++ # Prepare the files for the multipart/form-data request+ httpx_files = []+ for file in write_files:+ file_path, file_data = file['path'], file['data']+ if isinstance(file_data, str) or isinstance(file_data, bytes):+ httpx_files.append(('file', (file_path, file_data)))+ elif isinstance(file_data, TextIOBase):+ httpx_files.append(('file', (file_path, file_data.read())))+ else:+ raise ValueError(f"Unsupported data type for file {file_path}")++ params = {"username": user}+ if path is not None: params["path"] = pathr = self._envd_api.post(ENVD_API_FILES_ROUTE,- files={"file": data},- params={"path": path, "username": user},+ files=httpx_files,+ params=params,timeout=self._connection_config.get_request_timeout(request_timeout),)@@ -117,13 +143,16 @@ class Filesystem:if err:raise err- files = r.json()+ write_files = r.json()- if not isinstance(files, list) or len(files) == 0:+ if not isinstance(write_files, list) or len(write_files) == 0:raise Exception("Expected to receive information about written file")- file = files[0]- return EntryInfo(**file)+ if len(write_files) == 1 and path:+ file = write_files[0]+ return EntryInfo(**file)+ else:+ return [EntryInfo(**file) for file in write_files]def list(self,diff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.pyindex ba0390ee1..83addec27 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py@@ -1,3 +1,5 @@+from e2b.sandbox.filesystem.filesystem import EntryInfo+def test_write_file(sandbox):filename = "test_write.txt"content = "This is a test file."@@ -11,6 +13,50 @@ def test_write_file(sandbox):read_content = sandbox.files.read(filename)assert read_content == content+def test_write_multiple_files(sandbox):+ # Attempt to write with empty files array+ try:+ sandbox.files.write(None, [])+ except Exception as e:+ assert "Need at least one file to write" in str(e)++ # Attempt to write with path and file array+ try:+ sandbox.files.write("/path/to/file", [{ "path": "one_test_file.txt", "data": "This is a test file." }])+ except Exception as e:+ assert "Cannot specify path with array of files" in str(e)++ # Attempt to write with one file in array+ info = sandbox.files.write(None, [{ "path": "one_test_file.txt", "data": "This is a test file." }])+ assert isinstance(info, list)+ assert len(info) == 1+ info = info[0]+ assert isinstance(info, EntryInfo)+ assert info.path == "/home/user/one_test_file.txt"+ exists = sandbox.files.exists(info.path)+ assert exists++ read_content = sandbox.files.read(info.path)+ assert read_content == "This is a test file."++ # Attempt to write with multiple files in array+ files = []+ for i in range(10):+ filename = f"test_write_{i}.txt"+ content = f"This is a test file {i}."+ files.append({"path": filename, "data": content})++ infos = sandbox.files.write(None, files)+ assert isinstance(infos, list)+ assert len(infos) == len(files)+ for i, info in enumerate(infos):+ assert isinstance(info, EntryInfo)+ assert info.path == f"/home/user/test_write_{i}.txt"+ exists = sandbox.files.exists(filename)+ assert exists++ read_content = sandbox.files.read(info.path)+ assert read_content == files[i]["data"]def test_overwrite_file(sandbox):filename = "test_overwrite.txt"