Skip to content

Examples

Yaqing2023 edited this page Mar 7, 2026 · 1 revision

Examples

Real-world use cases for MoltsPay Python SDK.

Basic Usage

Pay for Video Generation

from moltspay import MoltsPay

client = MoltsPay()

result = client.pay(
    "https://juai8.com/zen7",
    "text-to-video",
    prompt="a golden retriever running on a beach at sunset"
)

print(f"Video URL: {result.result['video_url']}")

Discover and Choose Service

from moltspay import MoltsPay

client = MoltsPay()

# List available services
services = client.discover("https://juai8.com/zen7")

for svc in services:
    print(f"{svc.id}: {svc.price} {svc.currency}")
    print(f"  {svc.description}")

# Choose the cheapest one
cheapest = min(services, key=lambda s: s.price)
print(f"\nUsing: {cheapest.id} for ${cheapest.price}")

Async Operations

Concurrent Requests

import asyncio
from moltspay import AsyncMoltsPay

async def generate_videos(prompts: list[str]):
    async with AsyncMoltsPay() as client:
        tasks = [
            client.pay(
                "https://juai8.com/zen7",
                "text-to-video",
                prompt=prompt
            )
            for prompt in prompts
        ]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        for prompt, result in zip(prompts, results):
            if isinstance(result, Exception):
                print(f"Failed: {prompt} - {result}")
            else:
                print(f"Success: {prompt} - {result.result['video_url']}")

prompts = [
    "a cat playing piano",
    "a dog surfing",
    "a bird singing"
]

asyncio.run(generate_videos(prompts))

Error Handling

Comprehensive Error Handling

from moltspay import (
    MoltsPay, 
    InsufficientFunds, 
    LimitExceeded, 
    PaymentError
)

client = MoltsPay()

def safe_pay(url: str, service: str, **params):
    try:
        result = client.pay(url, service, **params)
        return {"success": True, "result": result.result}
    
    except InsufficientFunds as e:
        return {
            "success": False,
            "error": "insufficient_funds",
            "message": f"Need {e.required} USDC, have {e.balance}"
        }
    
    except LimitExceeded as e:
        return {
            "success": False,
            "error": "limit_exceeded",
            "message": f"Exceeds {e.limit_type} limit: {e.amount} > {e.limit}"
        }
    
    except PaymentError as e:
        return {
            "success": False,
            "error": "payment_failed",
            "message": str(e)
        }

# Usage
result = safe_pay(
    "https://juai8.com/zen7",
    "text-to-video",
    prompt="a cat dancing"
)

if result["success"]:
    print(f"Video: {result['result']['video_url']}")
else:
    print(f"Error: {result['message']}")

LangChain Agent

Autonomous Video Generator

from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from moltspay.integrations.langchain import get_moltspay_tools

llm = ChatOpenAI(model="gpt-4", temperature=0)
memory = ConversationBufferMemory(
    memory_key="chat_history", 
    return_messages=True
)

tools = get_moltspay_tools(
    max_per_tx=5.0,
    max_per_day=50.0
)

agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.OPENAI_FUNCTIONS,
    memory=memory,
    verbose=True
)

# Agent discovers and uses services
response = agent.run("""
I need to create a video for my presentation.
First, check what video services are available at juai8.com/zen7.
Then generate a video of "a professional business meeting with 
diverse team members discussing charts and graphs".
""")

print(response)

Multi-Service Pipeline

Chain Multiple Services

from moltspay import MoltsPay

client = MoltsPay()

def create_enhanced_video(idea: str) -> dict:
    """
    Pipeline:
    1. Generate script from idea
    2. Generate image for thumbnail
    3. Generate video
    """
    
    # Step 1: Generate script (hypothetical service)
    script = client.pay(
        "https://ai-writer.example.com",
        "generate-script",
        idea=idea,
        style="cinematic"
    )
    
    # Step 2: Generate thumbnail
    thumbnail = client.pay(
        "https://ai-images.example.com",
        "generate-image",
        prompt=f"Thumbnail for: {script.result['title']}"
    )
    
    # Step 3: Generate video
    video = client.pay(
        "https://juai8.com/zen7",
        "text-to-video",
        prompt=script.result['visual_description']
    )
    
    return {
        "title": script.result['title'],
        "thumbnail": thumbnail.result['image_url'],
        "video": video.result['video_url']
    }

# Usage
result = create_enhanced_video("A day in the life of a software developer")
print(result)

Budget Management

Track Spending

from moltspay import MoltsPay

client = MoltsPay()

def check_budget_and_pay(url: str, service: str, **params):
    """Only pay if within budget."""
    
    limits = client.limits()
    remaining_today = limits.max_per_day - limits.spent_today
    
    # Discover price
    services = client.discover(url)
    service_info = next(s for s in services if s.id == service)
    
    print(f"Service price: ${service_info.price}")
    print(f"Remaining budget: ${remaining_today:.2f}")
    
    if service_info.price > remaining_today:
        print("❌ Would exceed daily budget!")
        return None
    
    print("✅ Within budget, proceeding...")
    return client.pay(url, service, **params)

# Usage
result = check_budget_and_pay(
    "https://juai8.com/zen7",
    "text-to-video",
    prompt="a cat dancing"
)

Batch Processing

Process Multiple Items with Retry

import time
from moltspay import MoltsPay, PaymentError

client = MoltsPay()

def batch_generate(prompts: list[str], max_retries: int = 3):
    """Process multiple prompts with retry logic."""
    
    results = []
    
    for prompt in prompts:
        for attempt in range(max_retries):
            try:
                result = client.pay(
                    "https://juai8.com/zen7",
                    "text-to-video",
                    prompt=prompt
                )
                results.append({
                    "prompt": prompt,
                    "success": True,
                    "url": result.result['video_url']
                })
                break
                
            except PaymentError as e:
                if attempt < max_retries - 1:
                    print(f"Retry {attempt + 1} for: {prompt}")
                    time.sleep(2)
                else:
                    results.append({
                        "prompt": prompt,
                        "success": False,
                        "error": str(e)
                    })
    
    return results

# Usage
prompts = [
    "a sunset over mountains",
    "a city at night",
    "ocean waves"
]

results = batch_generate(prompts)
print(f"Success: {sum(1 for r in results if r['success'])}/{len(results)}")