Skip to main content

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://api.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

To run the unit tests:

pytest

Running Integration Tests

We have a comprehensive suite of integration tests that validate the client against the live API. These tests are automatically run as part of our CI/CD pipeline before each release.

To run the integration tests locally:

  1. Set the required environment variables:
export AI_COMPUTER_API_KEY="your_api_key_here"
# Optional: Use a specific sandbox ID (if not provided, a new one will be created)
export AI_COMPUTER_SANDBOX_ID="optional_sandbox_id"
  1. Run the tests:
python -m integration_tests.test_integration

For more details, see the Integration Tests README.

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

Metadata

Release files for ai-computer-client 0.3.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ai-computer-client 0.3.4
File Size Uploaded
ai_computer_client-0.3.4.tar.gz 10.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for ai-computer-client 0.3.4
File Interpreter ABI Platform
ai_computer_client-0.3.4-py3-none-any.whl Python 3 none any Details

Total release size: 26.2 kB

Release files / ai_computer_client-0.3.4.tar.gz

Download URL ai_computer_client-0.3.4.tar.gz
Size 10.9 kB
Tags Source
SHA-256 checksum
How to use checksums
79b466a67c73ca51e07383d5dd4bd75b93d853adebf6298ce2a9160b90fc9ebc
BLAKE2b-256 checksum
How to use checksums
5c529bfea8209218c5c74c08356b409274a83fd415fe913bdc5b567064ca9fc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.11

Release files / ai_computer_client-0.3.4-py3-none-any.whl

Download URL ai_computer_client-0.3.4-py3-none-any.whl
Size 15.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
910bfcfaa2f8f222632202522278a76f8f440de1b3977f89caaed5457336b779
BLAKE2b-256 checksum
How to use checksums
9b07828fb6076edc605924af51cbb6a5d456a9c35d7dce7cf0bb3fb08ab0556e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.11

Release history Release notifications | RSS feed

This release

0.3.4 This release

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page