fly402langgraph


Namefly402langgraph JSON
Version 0.1.1 PyPI version JSON
download
home_pageNone
SummaryLangGraph integration for the 402fly payment protocol
upload_time2025-11-01 07:17:36
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT License Copyright (c) 2025 402fly Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords 402 402fly agents langgraph payments
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 402fly-langgraph

LangGraph integration for the X402 payment protocol - build workflows that include payment nodes for accessing paid APIs.

## Overview

The `402fly-langgraph` package provides LangGraph nodes and utilities for building AI workflows that can automatically handle payment requirements. Create workflows that seamlessly integrate payment processing for accessing premium APIs.

## Features

- Pre-built payment nodes for LangGraph workflows
- Conditional routing based on payment requirements
- Helper functions for quick workflow creation
- Support for multi-step workflows with multiple API calls
- Async and sync payment node support
- State management utilities for payment workflows

## Installation

```bash
pip install 402fly-langgraph
```

## Quick Start

### Simple Payment Workflow

The easiest way to create a payment-enabled workflow:

```python
from 402fly_langgraph import create_simple_payment_workflow
from solders.keypair import Keypair
import json

# Load wallet
with open("wallet.json") as f:
    wallet_data = json.load(f)
    keypair = Keypair.from_bytes(bytes(wallet_data))

# Create simple workflow
workflow = create_simple_payment_workflow(
    wallet_keypair=keypair,
    api_url="http://localhost:8000/premium-data",
    max_payment="1.0",
)

# Run workflow
result = workflow()
print(f"Payment completed: {result.get('payment_completed')}")
print(f"Response: {result.get('api_response')}")
```

## Usage Patterns

### Pattern 1: Simple Workflow (Recommended)

Best for single API access with payment:

```python
from 402fly_langgraph import create_simple_payment_workflow
from solders.keypair import Keypair

keypair = Keypair()  # Your wallet

workflow = create_simple_payment_workflow(
    wallet_keypair=keypair,
    api_url="https://api.example.com/premium-data",
    max_payment="1.0",
)

result = workflow()
```

### Pattern 2: Custom Workflow with Payment Nodes

For more complex workflows with custom logic:

```python
from typing import TypedDict, Optional
from langgraph.graph import StateGraph, END
from 402fly_langgraph import (
    payment_node,
    fetch_with_payment_node,
    check_payment_required,
)
from solders.keypair import Keypair

# Define state
class WorkflowState(TypedDict):
    api_url: str
    api_response: Optional[str]
    payment_required: bool
    payment_completed: bool
    payment_error: Optional[str]
    wallet_keypair: Keypair
    max_payment_amount: str

# Build workflow
workflow = StateGraph(WorkflowState)

# Add nodes
workflow.add_node("fetch", fetch_with_payment_node)
workflow.add_node("payment", payment_node)

# Set entry point
workflow.set_entry_point("fetch")

# Add conditional routing
workflow.add_conditional_edges(
    "fetch",
    check_payment_required,
    {
        "payment_required": "payment",
        "success": END,
        "error": END
    }
)

workflow.add_edge("payment", END)

app = workflow.compile()

# Run workflow
keypair = Keypair()
result = app.invoke({
    "api_url": "https://api.example.com/data",
    "wallet_keypair": keypair,
    "max_payment_amount": "5.0"
})
```

### Pattern 3: Multi-Step Research Workflow

Build workflows that access multiple paid APIs:

```python
from typing import TypedDict, Optional, List
from langgraph.graph import StateGraph, END
from 402fly_langgraph import fetch_with_payment_node
from solders.keypair import Keypair

# Define state with multiple APIs
class ResearchState(TypedDict):
    wallet_keypair: Keypair
    apis: List[str]
    current_api_index: int
    api_url: str
    api_response: Optional[str]
    payment_completed: bool
    results: List[dict]
    max_payment_amount: str

def plan_node(state: ResearchState) -> ResearchState:
    """Initialize research plan"""
    state["apis"] = [
        "http://localhost:8000/premium-data",
        "http://localhost:8000/tiered-data/premium",
    ]
    state["current_api_index"] = 0
    state["api_url"] = state["apis"][0]
    state["results"] = []
    return state

def collect_result_node(state: ResearchState) -> ResearchState:
    """Collect result and move to next API"""
    if state.get("api_response"):
        state["results"].append({
            "api": state["api_url"],
            "response": state["api_response"]
        })

    # Move to next API
    state["current_api_index"] += 1
    if state["current_api_index"] < len(state["apis"]):
        state["api_url"] = state["apis"][state["current_api_index"]]
        state["api_response"] = None
        state["payment_completed"] = False

    return state

def check_more_apis(state: ResearchState) -> str:
    """Check if there are more APIs to access"""
    if state["current_api_index"] < len(state["apis"]):
        return "fetch_next"
    return "complete"

# Build workflow
workflow = StateGraph(ResearchState)
workflow.add_node("plan", plan_node)
workflow.add_node("fetch", fetch_with_payment_node)
workflow.add_node("collect", collect_result_node)

workflow.set_entry_point("plan")
workflow.add_edge("plan", "fetch")
workflow.add_edge("fetch", "collect")
workflow.add_conditional_edges(
    "collect",
    check_more_apis,
    {"fetch_next": "fetch", "complete": END}
)

app = workflow.compile()

# Run multi-step workflow
keypair = Keypair()
result = app.invoke({
    "wallet_keypair": keypair,
    "max_payment_amount": "5.0"
})

print(f"APIs processed: {len(result.get('results', []))}")
```

## Complete Example

```python
from 402fly_langgraph import create_simple_payment_workflow
from solders.keypair import Keypair
import json

# Load wallet
with open("wallet.json") as f:
    wallet_data = json.load(f)
    keypair = Keypair.from_bytes(bytes(wallet_data))

# Create and run workflow
workflow = create_simple_payment_workflow(
    wallet_keypair=keypair,
    api_url="http://localhost:8000/premium-data",
    max_payment="1.0",
)

result = workflow()

if result.get("payment_completed"):
    print("✅ Payment completed successfully")
    print(f"Response: {result.get('api_response')[:100]}...")
else:
    print(f"❌ Error: {result.get('payment_error')}")
```

## Available Nodes

### Payment Processing Nodes

- `payment_node`: Process payment for current API request
- `async_payment_node`: Async version of payment node
- `fetch_with_payment_node`: Fetch API with automatic payment handling
- `async_fetch_with_payment_node`: Async version

### Conditional Routing Functions

- `check_payment_required`: Route based on payment requirement
- `check_payment_completed`: Route based on payment status

### State Utilities

- `PaymentState`: TypedDict for payment-capable state
- `create_payment_capable_state`: Create custom state with payment fields
- `add_payment_workflow`: Add payment nodes to existing workflow

## Configuration

### Node Parameters (via State)

- `wallet_keypair`: Your Solana wallet keypair (required)
- `api_url`: URL to access (required)
- `max_payment_amount`: Maximum payment limit (required)
- `payment_required`: Payment requirement flag
- `payment_completed`: Payment completion flag
- `payment_error`: Error message if payment fails

## Wallet Setup

```python
import json
from solders.keypair import Keypair

# Create new wallet
keypair = Keypair()
wallet_data = list(bytes(keypair))
with open("wallet.json", "w") as f:
    json.dump(wallet_data, f)

print(f"Wallet address: {keypair.pubkey()}")
print("Fund this wallet with SOL and USDC on devnet!")
```

## Documentation

For complete API reference and guides, see:
- [Documentation](https://402fly.github.io/docs)
- [GitHub Repository](https://github.com/SerPepe/402fly)
- [Full Example](https://github.com/SerPepe/402fly/tree/main/examples/python/langgraph-workflow)

## Testing

```bash
pytest tests/
```

## License

MIT License - See [LICENSE](LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fly402langgraph",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "402, 402fly, agents, langgraph, payments",
    "author": null,
    "author_email": "402fly Contributors <hello@402fly.dev>",
    "download_url": "https://files.pythonhosted.org/packages/2e/1a/5678afbb44d1d85bc395181c80dc9c0340fdf4978ed873628a039e9e8c14/fly402langgraph-0.1.1.tar.gz",
    "platform": null,
    "description": "# 402fly-langgraph\n\nLangGraph integration for the X402 payment protocol - build workflows that include payment nodes for accessing paid APIs.\n\n## Overview\n\nThe `402fly-langgraph` package provides LangGraph nodes and utilities for building AI workflows that can automatically handle payment requirements. Create workflows that seamlessly integrate payment processing for accessing premium APIs.\n\n## Features\n\n- Pre-built payment nodes for LangGraph workflows\n- Conditional routing based on payment requirements\n- Helper functions for quick workflow creation\n- Support for multi-step workflows with multiple API calls\n- Async and sync payment node support\n- State management utilities for payment workflows\n\n## Installation\n\n```bash\npip install 402fly-langgraph\n```\n\n## Quick Start\n\n### Simple Payment Workflow\n\nThe easiest way to create a payment-enabled workflow:\n\n```python\nfrom 402fly_langgraph import create_simple_payment_workflow\nfrom solders.keypair import Keypair\nimport json\n\n# Load wallet\nwith open(\"wallet.json\") as f:\n    wallet_data = json.load(f)\n    keypair = Keypair.from_bytes(bytes(wallet_data))\n\n# Create simple workflow\nworkflow = create_simple_payment_workflow(\n    wallet_keypair=keypair,\n    api_url=\"http://localhost:8000/premium-data\",\n    max_payment=\"1.0\",\n)\n\n# Run workflow\nresult = workflow()\nprint(f\"Payment completed: {result.get('payment_completed')}\")\nprint(f\"Response: {result.get('api_response')}\")\n```\n\n## Usage Patterns\n\n### Pattern 1: Simple Workflow (Recommended)\n\nBest for single API access with payment:\n\n```python\nfrom 402fly_langgraph import create_simple_payment_workflow\nfrom solders.keypair import Keypair\n\nkeypair = Keypair()  # Your wallet\n\nworkflow = create_simple_payment_workflow(\n    wallet_keypair=keypair,\n    api_url=\"https://api.example.com/premium-data\",\n    max_payment=\"1.0\",\n)\n\nresult = workflow()\n```\n\n### Pattern 2: Custom Workflow with Payment Nodes\n\nFor more complex workflows with custom logic:\n\n```python\nfrom typing import TypedDict, Optional\nfrom langgraph.graph import StateGraph, END\nfrom 402fly_langgraph import (\n    payment_node,\n    fetch_with_payment_node,\n    check_payment_required,\n)\nfrom solders.keypair import Keypair\n\n# Define state\nclass WorkflowState(TypedDict):\n    api_url: str\n    api_response: Optional[str]\n    payment_required: bool\n    payment_completed: bool\n    payment_error: Optional[str]\n    wallet_keypair: Keypair\n    max_payment_amount: str\n\n# Build workflow\nworkflow = StateGraph(WorkflowState)\n\n# Add nodes\nworkflow.add_node(\"fetch\", fetch_with_payment_node)\nworkflow.add_node(\"payment\", payment_node)\n\n# Set entry point\nworkflow.set_entry_point(\"fetch\")\n\n# Add conditional routing\nworkflow.add_conditional_edges(\n    \"fetch\",\n    check_payment_required,\n    {\n        \"payment_required\": \"payment\",\n        \"success\": END,\n        \"error\": END\n    }\n)\n\nworkflow.add_edge(\"payment\", END)\n\napp = workflow.compile()\n\n# Run workflow\nkeypair = Keypair()\nresult = app.invoke({\n    \"api_url\": \"https://api.example.com/data\",\n    \"wallet_keypair\": keypair,\n    \"max_payment_amount\": \"5.0\"\n})\n```\n\n### Pattern 3: Multi-Step Research Workflow\n\nBuild workflows that access multiple paid APIs:\n\n```python\nfrom typing import TypedDict, Optional, List\nfrom langgraph.graph import StateGraph, END\nfrom 402fly_langgraph import fetch_with_payment_node\nfrom solders.keypair import Keypair\n\n# Define state with multiple APIs\nclass ResearchState(TypedDict):\n    wallet_keypair: Keypair\n    apis: List[str]\n    current_api_index: int\n    api_url: str\n    api_response: Optional[str]\n    payment_completed: bool\n    results: List[dict]\n    max_payment_amount: str\n\ndef plan_node(state: ResearchState) -> ResearchState:\n    \"\"\"Initialize research plan\"\"\"\n    state[\"apis\"] = [\n        \"http://localhost:8000/premium-data\",\n        \"http://localhost:8000/tiered-data/premium\",\n    ]\n    state[\"current_api_index\"] = 0\n    state[\"api_url\"] = state[\"apis\"][0]\n    state[\"results\"] = []\n    return state\n\ndef collect_result_node(state: ResearchState) -> ResearchState:\n    \"\"\"Collect result and move to next API\"\"\"\n    if state.get(\"api_response\"):\n        state[\"results\"].append({\n            \"api\": state[\"api_url\"],\n            \"response\": state[\"api_response\"]\n        })\n\n    # Move to next API\n    state[\"current_api_index\"] += 1\n    if state[\"current_api_index\"] < len(state[\"apis\"]):\n        state[\"api_url\"] = state[\"apis\"][state[\"current_api_index\"]]\n        state[\"api_response\"] = None\n        state[\"payment_completed\"] = False\n\n    return state\n\ndef check_more_apis(state: ResearchState) -> str:\n    \"\"\"Check if there are more APIs to access\"\"\"\n    if state[\"current_api_index\"] < len(state[\"apis\"]):\n        return \"fetch_next\"\n    return \"complete\"\n\n# Build workflow\nworkflow = StateGraph(ResearchState)\nworkflow.add_node(\"plan\", plan_node)\nworkflow.add_node(\"fetch\", fetch_with_payment_node)\nworkflow.add_node(\"collect\", collect_result_node)\n\nworkflow.set_entry_point(\"plan\")\nworkflow.add_edge(\"plan\", \"fetch\")\nworkflow.add_edge(\"fetch\", \"collect\")\nworkflow.add_conditional_edges(\n    \"collect\",\n    check_more_apis,\n    {\"fetch_next\": \"fetch\", \"complete\": END}\n)\n\napp = workflow.compile()\n\n# Run multi-step workflow\nkeypair = Keypair()\nresult = app.invoke({\n    \"wallet_keypair\": keypair,\n    \"max_payment_amount\": \"5.0\"\n})\n\nprint(f\"APIs processed: {len(result.get('results', []))}\")\n```\n\n## Complete Example\n\n```python\nfrom 402fly_langgraph import create_simple_payment_workflow\nfrom solders.keypair import Keypair\nimport json\n\n# Load wallet\nwith open(\"wallet.json\") as f:\n    wallet_data = json.load(f)\n    keypair = Keypair.from_bytes(bytes(wallet_data))\n\n# Create and run workflow\nworkflow = create_simple_payment_workflow(\n    wallet_keypair=keypair,\n    api_url=\"http://localhost:8000/premium-data\",\n    max_payment=\"1.0\",\n)\n\nresult = workflow()\n\nif result.get(\"payment_completed\"):\n    print(\"\u2705 Payment completed successfully\")\n    print(f\"Response: {result.get('api_response')[:100]}...\")\nelse:\n    print(f\"\u274c Error: {result.get('payment_error')}\")\n```\n\n## Available Nodes\n\n### Payment Processing Nodes\n\n- `payment_node`: Process payment for current API request\n- `async_payment_node`: Async version of payment node\n- `fetch_with_payment_node`: Fetch API with automatic payment handling\n- `async_fetch_with_payment_node`: Async version\n\n### Conditional Routing Functions\n\n- `check_payment_required`: Route based on payment requirement\n- `check_payment_completed`: Route based on payment status\n\n### State Utilities\n\n- `PaymentState`: TypedDict for payment-capable state\n- `create_payment_capable_state`: Create custom state with payment fields\n- `add_payment_workflow`: Add payment nodes to existing workflow\n\n## Configuration\n\n### Node Parameters (via State)\n\n- `wallet_keypair`: Your Solana wallet keypair (required)\n- `api_url`: URL to access (required)\n- `max_payment_amount`: Maximum payment limit (required)\n- `payment_required`: Payment requirement flag\n- `payment_completed`: Payment completion flag\n- `payment_error`: Error message if payment fails\n\n## Wallet Setup\n\n```python\nimport json\nfrom solders.keypair import Keypair\n\n# Create new wallet\nkeypair = Keypair()\nwallet_data = list(bytes(keypair))\nwith open(\"wallet.json\", \"w\") as f:\n    json.dump(wallet_data, f)\n\nprint(f\"Wallet address: {keypair.pubkey()}\")\nprint(\"Fund this wallet with SOL and USDC on devnet!\")\n```\n\n## Documentation\n\nFor complete API reference and guides, see:\n- [Documentation](https://402fly.github.io/docs)\n- [GitHub Repository](https://github.com/SerPepe/402fly)\n- [Full Example](https://github.com/SerPepe/402fly/tree/main/examples/python/langgraph-workflow)\n\n## Testing\n\n```bash\npytest tests/\n```\n\n## License\n\nMIT License - See [LICENSE](LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 402fly Contributors\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "LangGraph integration for the 402fly payment protocol",
    "version": "0.1.1",
    "project_urls": {
        "Documentation": "https://docs.402fly.dev",
        "Homepage": "https://github.com/SerPepe/402fly",
        "Repository": "https://github.com/SerPepe/402fly"
    },
    "split_keywords": [
        "402",
        " 402fly",
        " agents",
        " langgraph",
        " payments"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3eabd102fcb089317f31ffa5875263346da79f29088d21dfa08e82473bca3ab3",
                "md5": "bf3d0b37690c34f5c500f06b7d8bea15",
                "sha256": "55c4511c4dafb5d3f51e35d290cebd45c640683e7c9ff5bc97495e93cf5fbf58"
            },
            "downloads": -1,
            "filename": "fly402langgraph-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bf3d0b37690c34f5c500f06b7d8bea15",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 8747,
            "upload_time": "2025-11-01T07:17:35",
            "upload_time_iso_8601": "2025-11-01T07:17:35.350765Z",
            "url": "https://files.pythonhosted.org/packages/3e/ab/d102fcb089317f31ffa5875263346da79f29088d21dfa08e82473bca3ab3/fly402langgraph-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "2e1a5678afbb44d1d85bc395181c80dc9c0340fdf4978ed873628a039e9e8c14",
                "md5": "5d00ded70650269f71999dcf642c6948",
                "sha256": "4ff922f6423dcd676d5308e4292512119e320fe9beada864476a895dba2503ff"
            },
            "downloads": -1,
            "filename": "fly402langgraph-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "5d00ded70650269f71999dcf642c6948",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 7129,
            "upload_time": "2025-11-01T07:17:36",
            "upload_time_iso_8601": "2025-11-01T07:17:36.969271Z",
            "url": "https://files.pythonhosted.org/packages/2e/1a/5678afbb44d1d85bc395181c80dc9c0340fdf4978ed873628a039e9e8c14/fly402langgraph-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-11-01 07:17:36",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "SerPepe",
    "github_project": "402fly",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fly402langgraph"
}
        
Elapsed time: 2.44526s