Use the sandbox_code() method to apply AI-assisted code changes in your sandbox environment.

The sandbox_code() Method

def sandbox_code(
    prompt: str,
    editable_files: List[str],
    readonly_files: Optional[List[str]] = None
) -> Dict[str, Any]

Parameters

  • prompt (str): Natural language instruction for the AI
  • editable_files (List[str]): List of absolute paths in the sandbox the AI may modify
  • readonly_files (List[str], optional): List of absolute paths the AI can read but not modify

Return Value

The method returns a dictionary with:

  • success (bool): Whether meaningful changes were made
  • diff (str): Diff of changes in unified format
  • stdout/stderr (optional): Outputs if code execution is part of diff
  • cost and credits_remaining: Cost information if authenticated

Basic Example

# Apply AI modifications to a single file
result = sdk.sandbox_code(
    prompt="Add error handling to hello.py and refactor greet function",
    editable_files=["/home/user/hello.py"]
)

if result["success"]:
    print("Sandbox code changes applied:")
    print(result["diff"])
else:
    print("No significant changes made.")

Multi-File Example

# Modify multiple sandbox files together
result = sdk.sandbox_code(
    prompt="Optimize database queries in models.py and add logging in database.py",
    editable_files=[
        "/home/user/project/models.py",
        "/home/user/project/database.py"
    ],
    readonly_files=[
        "/home/user/project/config.py"
    ]
)

print(result["diff"])

Real-World Scenario

# Add REST endpoint and unit tests
sdk.sandbox_code(
    prompt="Add a new '/status' REST endpoint in app.py and create unit tests in tests/status_test.py",
    editable_files=["/home/user/project/app.py", "/home/user/project/tests/status_test.py"],
    readonly_files=["/home/user/project/routes.py"]
)

Best Practices

  • Use absolute paths starting with /home/user/
  • Provide context files in readonly_files to improve AI suggestions
  • Be specific in the prompt about function names, error handling, and patterns
  • Combine related file changes into a single call for context consistency