macroprompt 1.0.1
Official Python SDK for MacroPrompt - Create, manage, and execute webhooks with ease
License: MIT
Requires Python: >=3.7
Keywords: macroprompt, webhook, automation, ai, api, sdk, python

# MacroPrompt Python SDK

Official Python SDK for MacroPrompt - Create, manage, and execute webhooks with ease.

## Installation

```bash
pip install macroprompt
```

## Quick Start

```python
from macroprompt import MacroPrompt

# Initialize the client with your API key
client = MacroPrompt(api_key="your-api-key-here")

# Test the connection
connection = client.test_connection()
print(f"Connected: {connection.connected}")

# Execute a webhook
result = client.execute_webhook(
    webhook_id="your-webhook-id",
    inputs={"message": "Hello, World!"}
)

if result.success:
    print("Execution successful:", result.data)
else:
    print("Execution failed:", result.error)
```

## Configuration

### Basic Configuration

```python
from macroprompt import MacroPrompt

client = MacroPrompt(
    api_key="your-api-key-here",
    base_url="https://macroprompt.cloud",  # Optional, defaults to https://macroprompt.cloud
    timeout=30  # Optional, request timeout in seconds
)
```

### Using Environment Variables

```python
import os
from macroprompt import MacroPrompt

client = MacroPrompt(
    api_key=os.getenv("MACROPROMPT_API_KEY")
)
```

### Context Manager

```python
from macroprompt import MacroPrompt

with MacroPrompt(api_key="your-api-key-here") as client:
    result = client.execute_webhook("webhook-id", {"input": "data"})
    print(result.data)
# Client session is automatically closed
```

## API Reference

### Client Initialization

#### `MacroPrompt(api_key, base_url=None, timeout=30)`

Initialize the MacroPrompt client.

**Parameters:**
- `api_key` (str): Your MacroPrompt API key (required)
- `base_url` (str): Base URL for the API (default: "https://macroprompt.cloud")
- `timeout` (int): Request timeout in seconds (default: 30)

**Raises:**
- `ValidationError`: If api_key is not provided

### Connection Testing

#### `test_connection() -> ConnectionTest`

Test the connection to MacroPrompt API.

**Returns:**
- `ConnectionTest`: Object containing connection status and details

```python
connection = client.test_connection()
print(f"Connected: {connection.connected}")
print(f"Message: {connection.message}")
```

### Webhook Execution

#### `execute_webhook(webhook_id, inputs) -> ExecutionResult`

Execute a webhook with the provided inputs.

**Parameters:**
- `webhook_id` (str): ID of the webhook to execute
- `inputs` (dict): Input data for the webhook

**Returns:**
- `ExecutionResult`: Object containing execution results

**Raises:**
- `ValidationError`: If webhook_id is not provided
- `MacroPromptError`: For API errors

```python
result = client.execute_webhook(
    webhook_id="content-generator-123",
    inputs={
        "topic": "Artificial Intelligence",
        "length": "medium",
        "tone": "professional"
    }
)

if result.success:
    print("Generated content:", result.data)
    print(f"Execution time: {result.execution_time}s")
else:
    print("Error:", result.error)
```

### Webhook Management

#### `get_webhooks() -> List[Webhook]`

Retrieve all webhooks for the authenticated user.

**Returns:**
- `List[Webhook]`: List of webhook objects

```python
webhooks = client.get_webhooks()
for webhook in webhooks:
    print(f"ID: {webhook.id}, Title: {webhook.title}")
```

#### `get_webhook(webhook_id) -> Webhook`

Retrieve a specific webhook by ID.

**Parameters:**
- `webhook_id` (str): ID of the webhook to retrieve

**Returns:**
- `Webhook`: Webhook object

```python
webhook = client.get_webhook("webhook-123")
print(f"Title: {webhook.title}")
print(f"Description: {webhook.description}")
```

#### `create_webhook(webhook_data) -> Webhook`

Create a new webhook.

**Parameters:**
- `webhook_data` (WebhookData or dict): Webhook configuration

**Returns:**
- `Webhook`: Created webhook object

```python
from macroprompt import WebhookData

# Using WebhookData class
webhook_data = WebhookData(
    title="Content Generator",
    description="Generates content based on topic and parameters",
    inputs=[
        {"name": "topic", "type": "string", "description": "Content topic"},
        {"name": "length", "type": "string", "description": "Content length"}
    ],
    outputs=[
        {"name": "content", "type": "string", "description": "Generated content"}
    ],
    prompt="Generate content about {topic} with {length} length",
    model="gpt-4",
    is_public=False
)

webhook = client.create_webhook(webhook_data)
print(f"Created webhook: {webhook.id}")

# Using dictionary
webhook_dict = {
    "title": "Simple Generator",
    "description": "A simple content generator",
    "inputs": [{"name": "input", "type": "string"}],
    "outputs": [{"name": "output", "type": "string"}],
    "prompt": "Process: {input}",
    "model": "gpt-3.5-turbo"
}

webhook = client.create_webhook(webhook_dict)
```

#### `update_webhook(webhook_id, webhook_data) -> Webhook`

Update an existing webhook.

**Parameters:**
- `webhook_id` (str): ID of the webhook to update
- `webhook_data` (WebhookData or dict): Updated webhook configuration

**Returns:**
- `Webhook`: Updated webhook object

#### `delete_webhook(webhook_id) -> bool`

Delete a webhook.

**Parameters:**
- `webhook_id` (str): ID of the webhook to delete

**Returns:**
- `bool`: True if deletion was successful

```python
success = client.delete_webhook("webhook-123")
if success:
    print("Webhook deleted successfully")
```

## Data Types

### WebhookData

Data class for creating webhook configurations.

```python
from macroprompt import WebhookData

webhook_data = WebhookData(
    title="My Webhook",
    description="Webhook description",
    inputs=[{"name": "input1", "type": "string"}],
    outputs=[{"name": "output1", "type": "string"}],
    prompt="Process {input1}",
    model="gpt-4",
    type="webhook",
    is_public=False
)
```

### Webhook

Webhook object returned from API.

**Attributes:**
- `id` (str): Webhook ID
- `title` (str): Webhook title
- `description` (str): Webhook description
- `inputs` (List[Dict]): Input schema
- `outputs` (List[Dict]): Output schema
- `prompt` (str): Webhook prompt
- `model` (str): AI model used
- `type` (str): Webhook type
- `is_public` (bool): Public visibility
- `created_at` (str): Creation timestamp
- `updated_at` (str): Last update timestamp
- `user_id` (str): Owner user ID

### ExecutionResult

Result of webhook execution.

**Attributes:**
- `success` (bool): Execution success status
- `data` (Dict): Execution result data
- `error` (str): Error message if failed
- `execution_time` (float): Execution time in seconds

### ConnectionTest

Result of connection test.

**Attributes:**
- `connected` (bool): Connection status
- `message` (str): Status message
- `timestamp` (str): Test timestamp

## Examples

### Basic Webhook Execution

```python
from macroprompt import MacroPrompt
import os

client = MacroPrompt(api_key=os.getenv("MACROPROMPT_API_KEY"))

async def generate_content():
    try:
        # Execute a content generation webhook
        result = client.execute_webhook(
            webhook_id="content-generator-webhook-id",
            inputs={
                "topic": "Artificial Intelligence",
                "length": "medium",
                "tone": "professional"
            }
        )
        
        if result.success:
            print("Generated Content:")
            print(result.data.get("content", ""))
            print(f"Execution time: {result.execution_time}s")
        else:
            print(f"Error: {result.error}")
            
    except Exception as e:
        print(f"Unexpected error: {e}")

generate_content()
```

### Webhook Management

```python
from macroprompt import MacroPrompt, WebhookData
import os

client = MacroPrompt(
    api_key=os.getenv("MACROPROMPT_API_KEY"),
    base_url="https://macroprompt.cloud"
)

# Create a new webhook
webhook_data = WebhookData(
    title="Email Subject Generator",
    description="Generates compelling email subjects",
    inputs=[
        {"name": "topic", "type": "string", "description": "Email topic"},
        {"name": "audience", "type": "string", "description": "Target audience"}
    ],
    outputs=[
        {"name": "subject", "type": "string", "description": "Generated subject line"}
    ],
    prompt="Generate an engaging email subject for {topic} targeting {audience}",
    model="gpt-4"
)

try:
    # Create the webhook
    webhook = client.create_webhook(webhook_data)
    print(f"Created webhook: {webhook.id}")
    
    # List all webhooks
    webhooks = client.get_webhooks()
    print(f"Total webhooks: {len(webhooks)}")
    
    # Execute the new webhook
    result = client.execute_webhook(
        webhook.id,
        {
            "topic": "Product Launch",
            "audience": "tech enthusiasts"
        }
    )
    
    if result.success:
        print(f"Generated subject: {result.data}")
        
except Exception as e:
    print(f"Error: {e}")
```

### Error Handling

```python
from macroprompt import (
    MacroPrompt,
    MacroPromptError,
    AuthenticationError,
    ValidationError,
    NotFoundError,
    RateLimitError,
    ServerError
)

client = MacroPrompt(api_key="your-api-key")

try:
    result = client.execute_webhook("webhook-id", {"input": "data"})
except AuthenticationError:
    print("Invalid API key")
except ValidationError as e:
    print(f"Validation error: {e.message}")
except NotFoundError:
    print("Webhook not found")
except RateLimitError:
    print("Rate limit exceeded")
except ServerError:
    print("Server error occurred")
except MacroPromptError as e:
    print(f"API error: {e.message} (Status: {e.status_code})")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## Factory Function

You can also use the `create_client` factory function:

```python
from macroprompt import create_client

client = create_client(
    api_key="your-api-key",
    base_url="https://macroprompt.cloud",
    timeout=60
)
```

## Requirements

- Python 3.7+
- requests >= 2.25.0

## Development

### Installing Development Dependencies

```bash
pip install -e ".[dev]"
```

### Running Tests

```bash
pytest
```

### Code Formatting

```bash
black macroprompt/
```

### Type Checking

```bash
mypy macroprompt/
```

## License

MIT License - see LICENSE file for details.

## Support

- Documentation: https://api.macroprompt.cloud/docs
- Issues: https://github.com/macroprompt/macroprompt-python-sdk/issues
- Email: support@macroprompt.cloud

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.