Skip to main content
Version: 0.3.0
Last Verified: 2025-01-27
Package: hopx-ai on PyPI

Overview

The Cache resource provides methods for managing the execution result cache in sandboxes. The cache stores execution results to improve performance for repeated code executions. Use this resource to view cache statistics and clear the cache when needed.

Access

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")
cache = sandbox.cache  # Lazy-loaded

Methods

stats

Get cache statistics.
cache.stats(*, timeout=None) -> Dict[str, Any]
Returns: Dict[str, Any] - Cache statistics dictionary with:
  • cache.total_hits (int): Total cache hits
  • cache.size (int): Current cache size
  • cache.max_size (int): Maximum cache size
  • cache.ttl (int): Time-to-live in seconds
  • timestamp (str): Timestamp of the statistics
Example:
stats = sandbox.cache.stats()
cache_data = stats['cache']
print(f"Cache hits: {cache_data['total_hits']}")
print(f"Cache size: {cache_data['size']} / {cache_data['max_size']}")

clear

Clear the execution result cache.
cache.clear(*, timeout=None) -> Dict[str, Any]
Returns: Dict[str, Any] - Confirmation message
This clears all cached execution results. Subsequent executions will not benefit from cached results until cache is repopulated.
Example:
# Check cache size before clearing
stats_before = sandbox.cache.stats()
print(f"Cache size before: {stats_before['cache']['size']}")

# Clear cache
sandbox.cache.clear()

# Check cache size after clearing
stats_after = sandbox.cache.stats()
print(f"Cache size after: {stats_after['cache']['size']}")
See Also:

Examples

Example 1: Viewing Cache Statistics

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Get cache statistics
stats = sandbox.cache.stats()
cache_data = stats['cache']

print(f"Total cache hits: {cache_data['total_hits']}")
print(f"Current size: {cache_data['size']}")
print(f"Max size: {cache_data['max_size']}")
print(f"TTL: {cache_data['ttl']} seconds")

sandbox.kill()

Example 2: Clearing Cache

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute code (may be cached)
result1 = sandbox.run_code("print('Hello')")

# Clear cache
sandbox.cache.clear()
print("Cache cleared")

# Execute again (not cached)
result2 = sandbox.run_code("print('Hello')")

sandbox.kill()

Example 3: Monitoring Cache Usage

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Check initial cache state
initial_stats = sandbox.cache.stats()
print(f"Initial cache size: {initial_stats['cache']['size']}")

# Run multiple executions
for i in range(5):
    sandbox.run_code(f"print('Execution {i}')")

# Check cache after executions
final_stats = sandbox.cache.stats()
print(f"Final cache size: {final_stats['cache']['size']}")
print(f"Cache hits: {final_stats['cache']['total_hits']}")

sandbox.kill()

See Also

Next Steps