Skip to content

📝docs: sync with examples files, small updates #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: v0.2
Choose a base branch
from
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
187 changes: 159 additions & 28 deletions docs/examples/advanced.md
Original file line number Diff line number Diff line change
@@ -1,52 +1,183 @@
# Advanced Examples

## Custom Kernel Usage
For detailed information about security and architecture, see:

- [Why Sandboxing is Important](../concepts/architecture.md#why-is-sandboxing-important)
- [Implementation Comparison](../concepts/implementations.md#implementation-comparison)

> [!NOTE] Update **main.py** with each example and run it with
>```bash
>python main.py
>```

## Example 1: Basic Usage with Custom Kernels

```python
from codeboxapi import CodeBox
codebox = CodeBox()

def main():
codebox = CodeBox()

# Execute bash commands
result = codebox.exec("ls -la", kernel="bash")
print(result.text)
# Install system packages with timeout
result = codebox.exec(
"apt-get update && apt-get install -y ffmpeg",
kernel="bash",
timeout=300
)
print(result.text)
print("Bash command result:", result.text)

# Create and run Python scripts via bash
result = codebox.exec('echo "print(\'Running from file\')" > script.py', kernel="bash")
result = codebox.exec("python script.py", kernel="bash")
print("Script result:", result.text)

if __name__ == "__main__":
main()
```
### return
```bash
Bash command result: total 16
drwxr-xr-x 4 renzotincopa staff 128 Nov 13 17:52 .
drwxr-xr-x 7 renzotincopa staff 224 Nov 13 13:19 ..
-rw-r--r-- 1 renzotincopa staff 13 Nov 13 17:52 async_file.txt
-rw-r--r-- 1 renzotincopa staff 11 Nov 13 13:29 data.csv

Script result: Running from file
```

## File Streaming with Chunks
## Example 2: File Streaming with Chunks

```python
from codeboxapi import CodeBox
codebox = CodeBox()
# Upload large file with streaming
with open("large_file.dat", "rb") as f:
file = codebox.upload("remote_file.dat", f)
print(f"Uploaded file size: {file.get_size()} bytes")
# Download with streaming and custom chunk size
for chunk in codebox.stream_download("remote_file.dat"):
process_chunk(chunk)

def main():
codebox = CodeBox(verbose=True)

code = """
import time
t0 = time.time()
for i in range(3):
elapsed = time.time() - t0
print(f"{elapsed:.5f}: {i}")
time.sleep(1)
"""

print("Starting streaming example...")

result = codebox.exec(code)
for chunk in result.chunks:
print(chunk.content, end='')


if __name__ == "__main__":
main()
```
### return
```bash
Starting streaming example...
0.00015: 0
1.00524: 1
2.01015: 2
```

## Docker Implementation
## Example 3: Docker Parallel Processing

> Requirements:
> - Docker must be installed and running (start Docker Desktop or docker daemon)
> - Port 8069 must be available
> - User must have permissions to run Docker commands

```python
from codeboxapi import CodeBox
# Using DockerBox with custom port and image
codebox = CodeBox(api_key="docker")
# Execute code in container
result = codebox.exec("import sys; print(sys.version)")
print(result.text)
import asyncio

async def train_model(codebox: CodeBox, data_split: int) -> dict:
# Install required packages
await codebox.ainstall("pandas")
await codebox.ainstall("scikit-learn")

result = await codebox.aexec(f"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# Training simulation
print(f'Training model with split {data_split}')
""")
return {"split": data_split, "output": result.text, "errors": result.errors}

async def main():
try:
# Run multiple instances in parallel
codeboxes = [CodeBox(api_key="docker") for _ in range(4)]
tasks = [train_model(codebox, i) for i, codebox in enumerate(codeboxes)]
results = await asyncio.gather(*tasks)

for result in results:
print(f"Result from split {result['split']}:", result['output'])

except Exception as e:
print(f"Error during execution: {str(e)}")

if __name__ == "__main__":
asyncio.run(main())
```

### return
```bash
Result from split 0: Training model with split 0
Result from split 1: Training model with split 1
Result from split 2: Training model with split 2
Result from split 3: Training model with split 3
```

## Error Handling
## Example 4: Error Handling

```python
from codeboxapi import CodeBox

codebox = CodeBox()
codebox.exec("import non_existent_package")
def main():
codebox = CodeBox()

print("Example 1: Handling package import error")
# Handle execution errors
result = codebox.exec("import non_existent_package")
if result.errors:
print("Error occurred:", result.errors[0])

print("\nExample 2: Handling runtime error")
# Handle runtime errors with try/except
result = codebox.exec("""
try:
1/0
except Exception as e:
print(f"Error: {str(e)}")
""")
print("Result:", result.text)

print("\nExample 3: Handling syntax error")
result = codebox.exec("print('Hello' print('World')")
if result.errors:
print("Syntax error:", result.errors[0])

if __name__ == "__main__":
main()
```

### return
```bash
Example 1: Handling package import error
Error occurred: No module named 'non_existent_package'

Example 2: Handling runtime error
Result: Error: division by zero


Example 3: Handling syntax error
Syntax error: '(' was never closed (<ipython-input-1-8012c158bb8c>, line 1)
```

## Additional Resources

For more advanced usage patterns, see:

- [Components Overview](../concepts/components.md)
- [API Types Reference](../api/types.md)
- [Docker Implementation](../concepts/implementations.md#dockerbox)
- [Data Structures](../concepts/data_structures.md)
158 changes: 123 additions & 35 deletions docs/examples/async.md
Original file line number Diff line number Diff line change
@@ -1,57 +1,145 @@
# Async CodeBox API

## Parallel Execution
For detailed information about async operations, see:

Run multiple CodeBoxes in parallel:
- [Core Methods](../api/codebox.md#core-methods)
- [Data Structures](../concepts/data_structures.md)


## Basic Async Operations

Install aiofiles:

```bash
pip install aiofiles
```
Update main.py with the following examples:

```python
import asyncio
from codeboxapi import CodeBox
import asyncio

async def process_codebox(id: int):
async def async_examples():
codebox = CodeBox()
# Execute code
result = await codebox.aexec(f"print('CodeBox {id}')")
print(result.text)

# Install package
await codebox.ainstall("pandas")

# Run computation
result = await codebox.aexec(
"import pandas as pd; print(pd.__version__)"
)
return result.text
# Async Code Execution
result = await codebox.aexec("print('Async Hello!')")
print(result.text)

async def main():
# Run 5 CodeBoxes in parallel
results = await asyncio.gather(
*[process_codebox(i) for i in range(5)]
)
print(f"Results: {results}")
# Async File Operations
await codebox.aupload("async_file.txt", b"Async content")
downloaded = await codebox.adownload("async_file.txt")
print("File content:", downloaded.get_content())

asyncio.run(main())
# Async Package Installation
await codebox.ainstall("requests")

if __name__ == "__main__":
asyncio.run(async_examples())
```

Then run the example with:

```bash
python main.py
```

## Async File Operations with Progress
### Result:

```bash
Async Hello!
File content: Async content
```

Reference: `async_example.py` lines 6-18


## Async Streaming:

Update again main.py with the following example:
```python
import asyncio
from tqdm import tqdm
from codeboxapi import CodeBox

async def upload_with_progress(codebox, filename: str):
total_size = os.path.getsize(filename)
with tqdm(total=total_size, desc="Uploading") as pbar:
async with aiofiles.open(filename, "rb") as f:
file = await codebox.aupload(filename, f)
pbar.update(total_size)
return file
async def async_stream_exec(cb: CodeBox) -> None:
result = await cb.aexec("""
import time
import asyncio
t0 = time.perf_counter()
for i in range(3):
await asyncio.sleep(1)
print(f"{time.perf_counter() - t0:.5f}: {i}")
""")
print(f"Complete result:\n{result.text}")

if __name__ == "__main__":
codebox = CodeBox(api_key="local")
asyncio.run(async_stream_exec(codebox))
```

### Result:

```bash
Complete result:
1.00121: 0
2.00239: 1
3.00352: 2
```
Reference: `stream_chunk_timing.py` lines 53-62

## Docker Parallel Processing
> Note: Docker must be installed and running on your system to use these features.
> Requirements:
> - Docker must be installed and running (start Docker Desktop or docker daemon)
> - Port 8069 must be available
> - User must have permissions to run Docker commands

Install tenacity:

```bash
pip install tenacity
```
Then, update main file:

```python
import asyncio
from codeboxapi import CodeBox

async def train_model(codebox: CodeBox, data_split: int) -> dict:
# Install required packages
await codebox.ainstall("pandas")
await codebox.ainstall("scikit-learn")

# Execute training code
result = await codebox.aexec(f"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# Training code with split {data_split}
X_train, X_test = train_test_split(X, y, random_state={data_split})
""")
return {"split": data_split, "output": result.text, "errors": result.errors}

async def main():
codebox = CodeBox()
file = await upload_with_progress(codebox, "large_file.dat")
print(f"Uploaded: {file.path}, Size: {await file.aget_size()}")
# Create multiple Docker instances
num_parallel = 4
codeboxes = [CodeBox(api_key="docker") for _ in range(num_parallel)]

# Create and execute tasks
tasks = [train_model(codebox, i) for i, codebox in enumerate(codeboxes)]
results = await asyncio.gather(*tasks)
```

### Result:

asyncio.run(main())
```bash
[{'split': 0, 'output': 'Score for split 0: 1.0\n', 'errors': []}, {'split': 1, 'output': 'Score for split 1: 1.0\n', 'errors': []}, {'split': 2, 'output': 'Score for split 2: 1.0\n', 'errors': []}]
```

Reference: `docker_parallel_execution.py` lines 17-80

For more details on async implementations, see:

- [Implementation Overview](../concepts/implementations.md)
- [API Reference](../api/codebox.md#core-methods)
Loading