Back to Home

$ examples

// Real-world use cases and integration guides

EXAMPLE 3

LangChain Integration

Build an AI agent that can authenticate with Solana wallets and interact with on-chain data. Uses LangChain, OpenAI, and OpenKitx403 for autonomous wallet operations.

$ what-you-will-build

AI Agent

LLM-powered agent that understands Solana operations

Custom Tools

LangChain tools for wallet auth and blockchain queries

Autonomous

Agent makes decisions and executes wallet operations

$ prerequisites

  • [✓] Python 3.11+
  • [✓] OpenAI API key
  • [✓] Basic LangChain knowledge
  • [✓] Solana keypair

$ complete-implementation

1. Setup & Dependencies

# Install dependencies
pip install openkitx403-client langchain langchain-openai solana

# Set environment variables
export OPENAI_API_KEY="your-api-key"
export SOLANA_KEYPAIR_PATH="./keypair.json"

2. Create Wallet Auth Tool

from langchain.tools import BaseTool
from pydantic import Field
from solana.keypair import Keypair
from openkitx403_client import OpenKit403Client
import json

class SolanaWalletAuthTool(BaseTool):
    """Tool for authenticating with Solana wallet and fetching data"""
    
    name: str = "solana_wallet_auth"
    description: str = """
    Authenticate with a Solana wallet to access protected APIs.
    Input should be a JSON string with 'url' and 'method' keys.
    Example: {"url": "https://api.example.com/data", "method": "GET"}
    Returns the API response data.
    """
    
    keypair_path: str = Field(default="./keypair.json")
    
    def _run(self, query: str) -> str:
        """Execute the wallet authentication"""
        try:
            # Parse input
            params = json.loads(query)
            url = params.get('url')
            method = params.get('method', 'GET')
            
            # Load keypair
            with open(self.keypair_path, 'r') as f:
                secret_key = json.load(f)
            keypair = Keypair.from_secret_key(bytes(secret_key))
            
            # Create client and authenticate
            client = OpenKit403Client(keypair)
            response = client.authenticate(url, method=method)
            
            # Return response data
            return json.dumps(response.json(), indent=2)
            
        except Exception as e:
            return f"Error: {str(e)}"
    
    async def _arun(self, query: str) -> str:
        """Async version"""
        return self._run(query)

3. Create LangChain Agent

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder

# Initialize LLM
llm = ChatOpenAI(model="gpt-4", temperature=0)

# Create tools
tools = [SolanaWalletAuthTool(keypair_path="./keypair.json")]

# Create prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", """You are a Solana wallet agent assistant. 
    You can authenticate with Solana wallets and interact with protected APIs.
    
    When asked to fetch data from an API:
    1. Use the solana_wallet_auth tool
    2. Provide the URL and HTTP method
    3. Parse and explain the response to the user
    
    Be helpful and explain what you're doing."""),
    ("user", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

# Create agent
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
    agent=agent, 
    tools=tools, 
    verbose=True,
    max_iterations=3
)

# Run agent
def main():
    print("🤖 Solana AI Agent Started\n")
    
    while True:
        user_input = input("You: ")
        if user_input.lower() in ['exit', 'quit']:
            break
        
        result = agent_executor.invoke({"input": user_input})
        print(f"\nAgent: {result['output']}\n")

if __name__ == "__main__":
    main()

4. Run the Agent

python agent.py

$ example-conversation

You:

Fetch my profile data from https://api.example.com/profile

Agent:

I'll authenticate with your Solana wallet and fetch your profile data...

[Using solana_wallet_auth tool...]

✅ Successfully authenticated!
Here's your profile:
- Wallet: 5Gv8q5t...
- Username: User_5Gv8q5
- Tier: Premium
- Member since: 2025-01-15

You:

Check if I have any new messages

Agent:

Let me check your messages...
✅ You have 3 new messages!

$ advanced-features

Multi-Agent System

Create multiple agents with different wallets for parallel operations

AgentCoordinator + Multiple Wallets

Memory & Context

Add conversation memory for context-aware interactions

ConversationBufferMemory

Custom Tools

Add tools for NFT checks, token transfers, on-chain queries

NFTCheckTool, TokenTransferTool

Autonomous Trading

Build trading agents that monitor markets and execute strategies

DeFi Integration + Risk Management

$ real-world-applications

1. Personal Assistant

"Check my NFT portfolio value" → Agent authenticates, fetches NFTs, queries floor prices, calculates total

2. Trading Bot

"Alert me if SOL drops below $100" → Agent monitors prices, authenticates with DeFi APIs, sends alerts

3. DAO Assistant

"Summarize governance proposals" → Agent fetches proposals, analyzes with LLM, provides recommendations

Download Complete Code

Get the complete working example with additional features, tests, and documentation.