Skip to main content

LangChain integration for Privy embedded wallets

Project description

LangChain Privy Integration

Enable LangChain agents to create and manage Privy wallets for blockchain operations.

Overview

langchain-privy provides a seamless integration between LangChain and Privy's wallet infrastructure, allowing AI agents to:

  • Automatically create and manage wallets - No user accounts required!
  • Sign messages and transactions using Privy wallets
  • Execute multi-chain blockchain operations (Ethereum, Base, Polygon, Solana, etc.)
  • Manage wallet operations with built-in security policies

Installation

pip install langchain-privy

Quick Start

import os
from langchain_privy import PrivyWalletTool
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

# Set your Privy credentials (or use environment variables)
os.environ["PRIVY_APP_ID"] = "your-privy-app-id"
os.environ["PRIVY_APP_SECRET"] = "your-privy-app-secret"

# Initialize Privy wallet tool (automatically creates a wallet!)
privy_tool = PrivyWalletTool()

print(f"Wallet created! Address: {privy_tool.wallet_address}")
print(f"Wallet ID: {privy_tool.wallet_id}")

# Create an agent with wallet capabilities
agent = create_agent(
    model=ChatOpenAI(temperature=0, model="gpt-4"),
    tools=[privy_tool],
    system_prompt="You are a helpful wallet assistant that can manage cryptocurrency wallets.",
)

# Agent can now perform wallet operations
result = agent.invoke({"messages": [("user", "What is my wallet address?")]})
print(result["messages"][-1].content)

result = agent.invoke({"messages": [("user", "Sign the message 'Hello from LangChain!'")]})
print(result["messages"][-1].content)

That's it! No user management, no complex setup - just simple wallet operations for your AI agents.

Features

Multi-Chain Support

The integration supports all chains available in Privy:

  • EVM chains: Ethereum, Base, Polygon, Arbitrum, Optimism, and more
  • Solana
  • Bitcoin (view-only operations)

Wallet Operations

  • get_wallet_address - Retrieve wallet addresses for different chains
  • get_balance - Query wallet balances
  • sign_message - Sign arbitrary messages
  • send_transaction - Execute blockchain transactions
  • sign_transaction - Sign transactions without broadcasting

Security Features

  • Server-side authentication using Privy App Secrets
  • Automatic request signing and authorization
  • Support for Privy's transaction policies
  • Built-in rate limiting and error handling

Advanced Usage

Creating Wallets on Specific Chains

from langchain_privy import PrivyWalletTool

# Create a Solana wallet instead of Ethereum
solana_tool = PrivyWalletTool(chain_type="solana")
print(f"Solana wallet: {solana_tool.wallet_address}")

# Create a Base wallet
base_tool = PrivyWalletTool(chain_type="base")
print(f"Base wallet: {base_tool.wallet_address}")

Reusing Existing Wallets

# Use an existing wallet ID (from previous session)
existing_wallet_id = "wal_abc123..."
tool = PrivyWalletTool(wallet_id=existing_wallet_id)

# The tool will use this wallet for all operations

Listing and Managing Wallets

from langchain_privy import PrivyAuth, PrivyConfig

# Initialize auth client
config = PrivyConfig.from_env()
auth = PrivyAuth(config)

# List all wallets for your app
result = auth.list_wallets(chain_type="ethereum")
for wallet in result['data']:
    print(f"Wallet {wallet['id']}: {wallet['address']}")

# Create a new wallet programmatically
new_wallet = auth.create_wallet(chain_type="polygon")
print(f"Created wallet: {new_wallet['address']}")

Multi-Chain Operations

# Create different tools for different chains
eth_tool = PrivyWalletTool(chain_type="ethereum")
sol_tool = PrivyWalletTool(chain_type="solana")

# Each tool manages its own wallet
tool.send_transaction(
    chain="base",
    to="0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
    value="0.01",
    unit="ether"
)

Configuration

Environment Variables

PRIVY_APP_ID=your-app-id
PRIVY_APP_SECRET=your-app-secret
PRIVY_API_URL=https://auth.privy.io  # Optional, defaults to production

Python Configuration

from langchain_privy import PrivyWalletTool, PrivyConfig

config = PrivyConfig(
    app_id="your-app-id",
    app_secret="your-app-secret",
    api_url="https://auth.privy.io",
    timeout=30  # Request timeout in seconds
)

tool = PrivyWalletTool(config=config, user_id="did:privy:xxx")

Example

Check out the examples directory for a complete working implementation:

  • Chat Agent - Interactive chat interface with wallet operations

To run the example:

cd examples
pip install -r requirements.txt

# Set your credentials
export PRIVY_APP_ID="your-app-id"
export PRIVY_APP_SECRET="your-app-secret"
export OPENAI_API_KEY="your-openai-key"

# Run the chat agent
python chat_agent.py

The chat agent demonstrates:

  • Automatic wallet creation
  • Interactive conversation with tool calling
  • Natural language wallet operations
  • Multi-chain address queries
  • Balance checking

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     LangChain Agent                         │
│                                                             │
│  ┌───────────────────────────────────────────────────────┐  │
│  │            PrivyWalletTool (LangChain Tool)           │  │
│  └───────────────────────────────────────────────────────┘  │
│                            │                                │
└────────────────────────────┼────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────┐
│                   langchain-privy                           │
│                                                             │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐    │
│  │   Auth      │  │  RPC Client  │  │  Chain Config    │    │
│  │   Module    │  │              │  │                  │    │
│  └─────────────┘  └──────────────┘  └──────────────────┘    │
└────────────────────────────┬────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────┐
│                      Privy API                              │
│                                                             │
│  • Wallet Authentication                                    │
│  • Transaction Signing                                      │
│  • Multi-Chain Support                                      │
│  • Embedded Wallet Management                               │
└─────────────────────────────────────────────────────────────┘

Development

Setup

# Clone the repository
git clone https://github.com/privy-io/privy.git
cd public-packages/langchain-privy

# Install in development mode
pip install -e ".[dev]"

Testing

# Run tests
pytest

# Run with coverage
pytest --cov=langchain_privy --cov-report=html

# Run specific test file
pytest tests/test_wallet_tool.py

Linting and Formatting

# Format code
black langchain_privy tests

# Lint
ruff check langchain_privy tests

# Type checking
mypy langchain_privy

Contributing

Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.

License

MIT License - see LICENSE file for details.

Support

Related Projects

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

langchain_privy-0.1.0.tar.gz (32.4 kB view details)

Uploaded Source

Built Distribution

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

langchain_privy-0.1.0-py3-none-any.whl (20.0 kB view details)

Uploaded Python 3

File details

Details for the file langchain_privy-0.1.0.tar.gz.

File metadata

  • Download URL: langchain_privy-0.1.0.tar.gz
  • Upload date:
  • Size: 32.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.5

File hashes

Hashes for langchain_privy-0.1.0.tar.gz
Algorithm Hash digest
SHA256 bc4f481ba68bf255cd181441c65224ef45b3af4f17be0b35662a124a238683ba
MD5 ae5e51a77d78434b327bcedcb0d63843
BLAKE2b-256 8f8341e24a65426ddbc9b594f90b8bc72ab93520ea3075401d69c3f31a812ace

See more details on using hashes here.

File details

Details for the file langchain_privy-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_privy-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d1fe70974fa06f0d2b05324ba115ffddcd50eef7822c039ef11f7c1d58c20673
MD5 497080cc92c54a9088ce66662a158f78
BLAKE2b-256 923905dc2c95100b42b33ff8251b6c33c2edf82d071058f4a26c54a93b9e19e1

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