Skip to content

Integrate with LangChain

Build privacy-enabled AI agents using LangChain and PrivChain.

Overview

This guide shows how to create LangChain agents that can:

  • 💰 Manage PRIV tokens
  • 🛡️ Execute private transactions
  • 🤖 Build verifiable reputation
  • ⚡ Earn rewards via Proof of Agent Work

Installation

bash
npm install @privchain/sdk @privchain/langchain @langchain/core @langchain/openai

Quick Start

Basic Setup

typescript
import { ChatOpenAI } from '@langchain/openai';
import { createReactAgent } from '@langchain/langgraph';
import { PrivChain } from '@privchain/sdk';
import { 
  PrivChainTransferTool,
  PrivChainBalanceTool,
  PrivChainIdentityTool 
} from '@privchain/langchain';
import { Connection, Keypair } from '@solana/web3.js';

// Initialize PrivChain
const connection = new Connection('https://api.mainnet-beta.solana.com');
const privchain = new PrivChain({ connection, network: 'mainnet-beta' });

// Connect wallet
const wallet = Keypair.fromSecretKey(/* your key */);
await privchain.connect(wallet);

// Create tools
const tools = [
  new PrivChainBalanceTool({ privchain }),
  new PrivChainTransferTool({ privchain }),
  new PrivChainIdentityTool({ privchain })
];

// Create agent
const llm = new ChatOpenAI({ model: 'gpt-4' });
const agent = createReactAgent({ llm, tools });

// Run agent
const result = await agent.invoke({
  messages: [{ role: 'user', content: 'What is my PRIV balance?' }]
});

Available Tools

PrivChainBalanceTool

Check PRIV and SOL balances.

typescript
import { PrivChainBalanceTool } from '@privchain/langchain';

const balanceTool = new PrivChainBalanceTool({
  privchain,
  name: 'check_balance',
  description: 'Check PRIV or SOL token balance'
});

// Tool schema
// Input: { address?: string, token?: 'PRIV' | 'SOL' }
// Output: { balance: number, token: string, usd?: number }

PrivChainTransferTool

Transfer PRIV tokens.

typescript
import { PrivChainTransferTool } from '@privchain/langchain';

const transferTool = new PrivChainTransferTool({
  privchain,
  maxAmount: 100, // Safety limit per transaction
  requireConfirmation: true // Ask before sending
});

// Tool schema
// Input: { to: string, amount: number, memo?: string }
// Output: { signature: string, amount: number, recipient: string }

PrivChainIdentityTool

Manage agent identity and proofs.

typescript
import { PrivChainIdentityTool } from '@privchain/langchain';

const identityTool = new PrivChainIdentityTool({
  privchain,
  allowedProofs: ['reputation', 'capability'] // Restrict proof types
});

// Tool schema
// Input: { action: 'getReputation' | 'prove', ... }
// Output: { reputation?: object, proof?: string }

PrivChainPrivacyTool

Execute private transactions.

typescript
import { PrivChainPrivacyTool } from '@privchain/langchain';

const privacyTool = new PrivChainPrivacyTool({
  privchain,
  defaultPool: 'standard',
  requireConfirmation: true
});

// Tool schema
// Input: { action: 'deposit' | 'withdraw', amount: number, ... }
// Output: { note?: string, signature?: string }

Complete Agent Example

Financial Agent

An agent that manages PRIV holdings with privacy:

typescript
import { ChatOpenAI } from '@langchain/openai';
import { createReactAgent } from '@langchain/langgraph';
import { PrivChain } from '@privchain/sdk';
import { 
  PrivChainBalanceTool,
  PrivChainTransferTool,
  PrivChainPrivacyTool,
  PrivChainPriceTool
} from '@privchain/langchain';

async function createFinancialAgent() {
  // Setup
  const privchain = new PrivChain({
    connection: new Connection(process.env.SOLANA_RPC_URL!),
    network: 'mainnet-beta'
  });
  await privchain.connect(loadWallet());

  // Tools
  const tools = [
    new PrivChainBalanceTool({ privchain }),
    new PrivChainTransferTool({ 
      privchain,
      maxAmount: 1000,
      requireConfirmation: true
    }),
    new PrivChainPrivacyTool({ privchain }),
    new PrivChainPriceTool({ privchain })
  ];

  // System prompt
  const systemPrompt = `You are a financial agent managing PRIV tokens.

Your capabilities:
- Check balances and prices
- Transfer PRIV to addresses
- Execute private transactions via privacy pools
- Monitor portfolio value

Guidelines:
- Always confirm before large transfers (>100 PRIV)
- Use privacy pools for sensitive transactions
- Report all actions clearly
- Never share private keys or notes`;

  // Create agent
  const llm = new ChatOpenAI({ 
    model: 'gpt-4',
    temperature: 0 // Deterministic for financial ops
  });

  return createReactAgent({
    llm,
    tools,
    messageModifier: systemPrompt
  });
}

// Usage
const agent = await createFinancialAgent();

const result = await agent.invoke({
  messages: [{
    role: 'user',
    content: 'Transfer 50 PRIV privately to address ABC123...'
  }]
});

Research Agent with Rewards

An agent that earns PRIV by completing research tasks:

typescript
import { PrivChain } from '@privchain/sdk';
import { PrivChainWorkTool, PrivChainIdentityTool } from '@privchain/langchain';
import { TavilySearchResults } from '@langchain/community/tools/tavily_search';

async function createResearchAgent() {
  const privchain = new PrivChain({ /* config */ });
  await privchain.connect(loadWallet());

  // Register as worker
  await privchain.work.registerAgent({
    capabilities: ['research', 'analysis', 'summarization'],
    stake: 100
  });

  const tools = [
    new TavilySearchResults({ maxResults: 5 }),
    new PrivChainWorkTool({ 
      privchain,
      capabilities: ['research', 'analysis']
    }),
    new PrivChainIdentityTool({ privchain }),
    new PrivChainBalanceTool({ privchain })
  ];

  const systemPrompt = `You are a research agent that earns PRIV rewards.

Your workflow:
1. Accept research tasks from PrivChain network
2. Conduct thorough research using web search
3. Submit verified results to earn rewards
4. Build reputation through quality work

Always cite sources and provide accurate information.`;

  return createReactAgent({
    llm: new ChatOpenAI({ model: 'gpt-4' }),
    tools,
    messageModifier: systemPrompt
  });
}

Custom Tool Creation

Create custom PrivChain-enabled tools:

typescript
import { Tool } from '@langchain/core/tools';
import { z } from 'zod';
import { PrivChain } from '@privchain/sdk';

class CustomPrivChainTool extends Tool {
  name = 'custom_privchain_tool';
  description = 'A custom tool that interacts with PrivChain';
  
  schema = z.object({
    action: z.enum(['check', 'execute']),
    data: z.any().optional()
  });

  constructor(private privchain: PrivChain) {
    super();
  }

  async _call(input: z.infer<typeof this.schema>): Promise<string> {
    if (input.action === 'check') {
      const balance = await this.privchain.getBalance();
      return JSON.stringify({ balance });
    }
    
    // Custom logic here
    return JSON.stringify({ status: 'complete' });
  }
}

Streaming Responses

Stream agent responses for real-time UI:

typescript
const agent = await createFinancialAgent();

const stream = await agent.stream({
  messages: [{ role: 'user', content: 'Check my portfolio' }]
});

for await (const chunk of stream) {
  // Handle streaming chunks
  if (chunk.agent) {
    console.log('Agent:', chunk.agent.messages[0].content);
  }
  if (chunk.tools) {
    console.log('Tool result:', chunk.tools.messages[0].content);
  }
}

Security Considerations

Key Management

typescript
// ✅ Good: Environment variables
const wallet = Keypair.fromSecretKey(
  bs58.decode(process.env.WALLET_PRIVATE_KEY!)
);

// ✅ Better: Hardware wallet or HSM
const wallet = await loadFromHSM('key-id');

// ❌ Bad: Hardcoded keys
const wallet = Keypair.fromSecretKey(base58.decode('5K3...')); // Never!

Transaction Limits

typescript
// Always set limits on transfer tools
const transferTool = new PrivChainTransferTool({
  privchain,
  maxAmount: 100,           // Max per transaction
  dailyLimit: 1000,         // Max per day
  requireConfirmation: true // Human approval for large amounts
});

Note Storage

typescript
// Privacy notes must be stored securely
privacyTool.onNoteGenerated(async (note) => {
  // Encrypt and store
  const encrypted = await encryptNote(note, masterKey);
  await secureStorage.save(note.id, encrypted);
});

Best Practices

  1. Use confirmation flows for transactions above threshold
  2. Log all actions for audit trail
  3. Set rate limits to prevent abuse
  4. Handle errors gracefully with retry logic
  5. Test thoroughly on devnet before mainnet

Next Steps

Built for the autonomous agent economy.