Skip to main content

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

Project description

MacroPrompt Python SDK

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

Installation

pip install macroprompt

Quick Start

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

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

import os
from macroprompt import MacroPrompt

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

Context Manager

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
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
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
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
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
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
success = client.delete_webhook("webhook-123")
if success:
    print("Webhook deleted successfully")

Data Types

WebhookData

Data class for creating webhook configurations.

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

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

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

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:

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

pip install -e ".[dev]"

Running Tests

pytest

Code Formatting

black macroprompt/

Type Checking

mypy macroprompt/

License

MIT License - see LICENSE file for details.

Support

Contributing

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

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

macroprompt-1.0.1.tar.gz (13.0 kB view details)

Uploaded Source

Built Distribution

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

macroprompt-1.0.1-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

Details for the file macroprompt-1.0.1.tar.gz.

File metadata

  • Download URL: macroprompt-1.0.1.tar.gz
  • Upload date:
  • Size: 13.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for macroprompt-1.0.1.tar.gz
Algorithm Hash digest
SHA256 55ed71c14d311fda44f2bbd10f7e27f1c092849966d58e542c1ba7280c6659c3
MD5 fc000a104c59637d80d26a6e057793a7
BLAKE2b-256 492f125c3aba4d5974a5358a68898c33c5f27824fc805f1b50245bf81b7dd344

See more details on using hashes here.

File details

Details for the file macroprompt-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: macroprompt-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 8.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for macroprompt-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9231302619cdfd333349d328f505970c0cc5f60d8a2f1d3cdaf37567ef878af5
MD5 fe9750bf740d2b84296c9a72fb786390
BLAKE2b-256 b51dd8c336afae62cfeba307ecbef7aa6ab9c93ba008d90a42e06c81980dfb78

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