Skip to main content

Python client for interacting with the AI Computer service

Project description

AI Computer Python Client

A Python client for interacting with the AI Computer service. This client provides a simple interface for executing Python code in an isolated sandbox environment.

Installation

pip install ai-computer-client

Quick Start

import asyncio
from ai_computer import SandboxClient

async def main():
    # Initialize the client
    client = SandboxClient()
    
    # Setup the client (gets token and creates sandbox)
    setup_response = await client.setup()
    if not setup_response.success:
        print(f"Setup failed: {setup_response.error}")
        return
    
    try:
        # Example 1: Simple code execution
        code = """x = 10
y = 20
result = x + y
print(f"The sum is: {result}")"""
        
        print("\nExample 1: Simple execution")
        print("-" * 50)
        response = await client.execute_code(code)
        if response.success:
            print("Execution result:", response.data)
        else:
            print("Execution failed:", response.error)

        # Example 2: Streaming execution
        code = """import time

for i in range(5):
    print(f"Processing step {i + 1}")
    time.sleep(1)  # Simulate work
    
result = "Calculation complete!"
print(result)"""
        
        print("\nExample 2: Streaming execution")
        print("-" * 50)
        async for event in client.execute_code_stream(code):
            if event.type == 'stdout':
                print(f"Output: {event.data}")
            elif event.type == 'stderr':
                print(f"Error: {event.data}")
            elif event.type == 'error':
                print(f"Execution error: {event.data}")
                break
            elif event.type == 'completed':
                print("Execution completed")
                break
    
    finally:
        # Clean up
        await client.cleanup()

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

Example output:

Example 1: Simple execution
--------------------------------------------------
Execution result: {'output': 'The sum is: 30\n', 'sandbox_id': '06a30496-b535-47b0-9fe7-34f7ec483cd7'}

Example 2: Streaming execution
--------------------------------------------------
Output: Processing step 1
Output: Processing step 2
Output: Processing step 3
Output: Processing step 4
Output: Processing step 5
Output: Calculation complete!
Execution completed

Features

  • Asynchronous API for efficient execution
  • Real-time streaming of code output
  • Automatic sandbox management
  • Error handling and timeouts
  • Type hints for better IDE support

API Reference

SandboxClient

The main client class for interacting with the AI Computer service.

client = SandboxClient(base_url="http://aicomputer.dev")

Methods

async setup() -> SandboxResponse

Initialize the client and create a sandbox. This must be called before executing any code.

response = await client.setup()
if response.success:
    print("Sandbox ready")
async execute_code(code: str, timeout: int = 30) -> SandboxResponse

Execute Python code and return the combined output.

code = """
x = 10
y = 20
result = x + y
print(f"The sum is: {result}")
"""

response = await client.execute_code(code)
if response.success:
    print("Output:", response.data['output'])
async execute_code_stream(code: str, timeout: int = 30) -> AsyncGenerator[StreamEvent, None]

Execute Python code and stream the output in real-time.

async for event in client.execute_code_stream(code):
    if event.type == 'stdout':
        print("Output:", event.data)
    elif event.type == 'stderr':
        print("Error:", event.data)
async cleanup() -> SandboxResponse

Delete the sandbox and clean up resources.

await client.cleanup()

Response Types

SandboxResponse

@dataclass
class SandboxResponse:
    success: bool
    data: Optional[Dict] = None
    error: Optional[str] = None

StreamEvent

@dataclass
class StreamEvent:
    type: str  # 'stdout', 'stderr', 'error', 'completed'
    data: str

Development

Running Tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ai_computer_client-0.1.1.tar.gz (5.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ai_computer_client-0.1.1-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file ai_computer_client-0.1.1.tar.gz.

File metadata

  • Download URL: ai_computer_client-0.1.1.tar.gz
  • Upload date:
  • Size: 5.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for ai_computer_client-0.1.1.tar.gz
Algorithm Hash digest
SHA256 df0cb6c0483a36faafda75a31943b1124161e5c14c7c269f609a3669903e5605
MD5 b4b498fb29d2c700e2c85703bf2d1360
BLAKE2b-256 dfe88e3183df4f77ffe64f800de4c36a3b3407444838ced5c8b81d44dfe744c0

See more details on using hashes here.

File details

Details for the file ai_computer_client-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for ai_computer_client-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 380f5d9fde682318cdcb30e88ef86e45a429f8ed7189707c46d4b97f5e556152
MD5 bc62db13c778d516e928e34b4f542f25
BLAKE2b-256 b1ad1ebb13d1f9ae93b026d5e81bde2d7637200de29c2d1f6af8e401af46ddb0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page