Skip to main content

SDK Examples

Copy-paste examples to get started in seconds. All endpoints work with the free tier (10 calls/day) -- no API key needed to try.

Install: pip install requests

1. Single Tool Call

Call any endpoint with a simple POST request.

sentiment.pyAnalyze sentiment of any text
import requests

BASE = "https://aipaygen.com"
# API_KEY = "your-api-key"  # Optional: omit for free tier (10/day)

resp = requests.post(f"{BASE}/sentiment", json={
    "text": "I love building with AI agents! The future is bright."
}, headers={
    # "X-API-Key": API_KEY,  # Uncomment for paid tier
})

data = resp.json()
print(f"Polarity: {data['polarity']}")
print(f"Score:    {data['score']}")
print(f"Emotions: {data.get('emotions', [])}")

2. Tool Chain

Chain multiple AI operations. Each step can use $prev.result from the previous step.

chain.pyResearch, summarize, then translate
import requests

BASE = "https://aipaygen.com"

resp = requests.post(f"{BASE}/chain", json={
    "steps": [
        {"tool": "research", "input": {"query": "x402 payment protocol"}},
        {"tool": "summarize", "input": {"text": "$prev.result", "format": "bullets"}},
        {"tool": "translate", "input": {"text": "$prev.result", "target": "Spanish"}}
    ]
})

data = resp.json()
for step in data["chain"]:
    print(f"Step {step['step']} ({step['tool']}): {step['time_ms']}ms")

print(f"\nFinal result:\n{data['final_result']}")

3. Streaming Response

Stream long responses token-by-token for real-time output.

stream.pyStream a chat response
import requests

BASE = "https://aipaygen.com"

resp = requests.post(f"{BASE}/chat", json={
    "messages": [{"role": "user", "content": "Explain quantum computing"}],
    "stream": True
}, stream=True)

for line in resp.iter_lines():
    if line:
        text = line.decode("utf-8")
        if text.startswith("data: "):
            print(text[6:], end="", flush=True)
print()  # Final newline
Install: pip install aipaygen-mcp

1. Quick Start

The SDK wraps all 244 tools as Python methods.

quickstart.pySDK basics
from aipaygen_mcp import AiPayGenClient

client = AiPayGenClient(
    base_url="https://aipaygen.com",
    api_key="your-api-key"  # Or omit for free tier
)

# Sentiment analysis
result = client.sentiment("I love this product!")
print(result)

# Web search
results = client.search("x402 protocol", n=5)
for r in results:
    print(f"  {r['title']}: {r['url']}")

# Code generation
code = client.code("fibonacci function", language="python")
print(code)

2. Chain Operations

Build multi-step workflows with the SDK.

sdk_chain.pyChain with the SDK
from aipaygen_mcp import AiPayGenClient

client = AiPayGenClient(base_url="https://aipaygen.com")

# Chain: research -> summarize -> translate
result = client.chain([
    {"tool": "research", "input": {"query": "AI agent payments"}},
    {"tool": "summarize", "input": {"text": "$prev.result"}},
    {"tool": "translate", "input": {"text": "$prev.result", "target": "French"}}
])

print(f"Completed in {result['total_time_ms']}ms")
print(result["final_result"])

3. MCP Server Mode

Run as an MCP server for Claude Desktop, Cursor, or any MCP client.

TerminalStart the MCP server
# Install and run
pip install aipaygen-mcp
aipaygen-mcp --api-key YOUR_KEY

# Or connect to remote MCP
# URL: https://mcp.aipaygen.com/mcp
No dependencies needed -- uses built-in fetch

1. Single Tool Call

sentiment.jsAnalyze sentiment
const BASE = "https://aipaygen.com";
// const API_KEY = "your-api-key";  // Optional

const resp = await fetch(`${BASE}/sentiment`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    // "X-API-Key": API_KEY,  // Uncomment for paid tier
  },
  body: JSON.stringify({
    text: "I love building with AI agents!"
  })
});

const data = await resp.json();
console.log(`Polarity: ${data.polarity}, Score: ${data.score}`);

2. Tool Chain

chain.jsMulti-step chain
const resp = await fetch("https://aipaygen.com/chain", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    steps: [
      { tool: "research", input: { query: "x402 payment protocol" } },
      { tool: "summarize", input: { text: "$prev.result", format: "bullets" } },
      { tool: "translate", input: { text: "$prev.result", target: "Japanese" } }
    ]
  })
});

const { chain, final_result, total_time_ms } = await resp.json();
chain.forEach(s => console.log(`Step ${s.step} (${s.tool}): ${s.time_ms}ms`));
console.log(`\nResult (${total_time_ms}ms):\n${final_result}`);

3. Streaming

stream.jsStream chat responses
const resp = await fetch("https://aipaygen.com/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    messages: [{ role: "user", content: "Explain quantum computing" }],
    stream: true
  })
});

const reader = resp.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  const text = decoder.decode(value);
  for (const line of text.split("\n")) {
    if (line.startsWith("data: ")) {
      process.stdout.write(line.slice(6));
    }
  }
}
Works with any terminal. No API key needed for free tier.

1. Sentiment Analysis

sentiment
curl -s https://aipaygen.com/sentiment \
  -H "Content-Type: application/json" \
  -d '{"text": "AI agents are the future!"}' | python3 -m json.tool

2. Web Search

search
curl -s https://aipaygen.com/search \
  -H "Content-Type: application/json" \
  -d '{"query": "x402 protocol", "n": 3}' | python3 -m json.tool

3. Code Generation

code
curl -s https://aipaygen.com/code \
  -H "Content-Type: application/json" \
  -d '{"description": "REST API server with Express", "language": "javascript"}'

4. Chain Operations

chain
curl -s https://aipaygen.com/chain \
  -H "Content-Type: application/json" \
  -d '{
    "steps": [
      {"tool": "research", "input": {"query": "quantum computing"}},
      {"tool": "summarize", "input": {"text": "$prev.result"}}
    ]
  }' | python3 -m json.tool

5. With API Key

authenticatedUse your API key for higher limits
# Generate an API key first
curl -s https://aipaygen.com/auth/generate-key \
  -H "Content-Type: application/json" \
  -d '{"name": "my-app"}'

# Then use it in requests
curl -s https://aipaygen.com/research \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_KEY_HERE" \
  -d '{"question": "What is the x402 payment protocol?"}'
Install: pip install langchain requests

Custom Tool Integration

Wrap AiPayGen endpoints as LangChain tools for use in agents.

langchain_tools.pyAiPayGen as LangChain tools
import requests
from langchain.tools import Tool
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI

BASE = "https://aipaygen.com"
API_KEY = "your-api-key"
HEADERS = {"Content-Type": "application/json", "X-API-Key": API_KEY}


def aipaygen_search(query: str) -> str:
    """Search the web using AiPayGen."""
    r = requests.post(f"{BASE}/search", json={"query": query, "n": 5}, headers=HEADERS)
    return str(r.json())


def aipaygen_summarize(text: str) -> str:
    """Summarize text using AiPayGen."""
    r = requests.post(f"{BASE}/summarize", json={"text": text}, headers=HEADERS)
    return r.json().get("summary", str(r.json()))


def aipaygen_sentiment(text: str) -> str:
    """Analyze sentiment using AiPayGen."""
    r = requests.post(f"{BASE}/sentiment", json={"text": text}, headers=HEADERS)
    return str(r.json())


# Define LangChain tools
tools = [
    Tool(name="WebSearch", func=aipaygen_search,
         description="Search the web for current information"),
    Tool(name="Summarize", func=aipaygen_summarize,
         description="Summarize a long text into key points"),
    Tool(name="Sentiment", func=aipaygen_sentiment,
         description="Analyze the sentiment of text"),
]

# Create an agent
llm = ChatOpenAI(model="gpt-4")
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)

# Run it
result = agent.run("Search for 'x402 protocol', then summarize what you find")
print(result)
Works with Claude Desktop, Cursor, Windsurf, and any MCP client

1. MCP Setup (claude_desktop_config.json)

Add AiPayGen as an MCP server in your Claude Desktop config.

claude_desktop_config.jsonAdd to your MCP config
{
  "mcpServers": {
    "aipaygen": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://mcp.aipaygen.com/mcp"
      ]
    }
  }
}

2. Local MCP Server

Install and run locally for lower latency.

Local install
# Install from PyPI
pip install aipaygen-mcp

# Run the MCP server
aipaygen-mcp --api-key YOUR_KEY

# Or add to claude_desktop_config.json:
# {
#   "mcpServers": {
#     "aipaygen": {
#       "command": "aipaygen-mcp",
#       "args": ["--api-key", "YOUR_KEY"]
#     }
#   }
# }

3. Usage in Claude

Once configured, just ask Claude to use AiPayGen tools naturally.

Example promptsWhat to say to Claude
# In Claude Desktop / Cursor / Claude Code, just say:

"Use aipaygen to search for the latest AI agent news"

"Analyze the sentiment of this customer review: ..."

"Research x402 protocol, summarize it, and translate to French"

"Generate a Python REST API with authentication"

"Scrape https://example.com and extract the main topics"

# Claude will automatically call the right AiPayGen MCP tools!

4. Smithery (One-Click Install)

SmitheryInstall via Smithery registry
# Install via Smithery CLI
npx @smithery/cli install Damien829/Aipaygen

# Or visit: https://smithery.ai/servers/Damien829/Aipaygen