Skip to main content

LangChain Quick Start

Build a working DeFi agent in 5 minutes using LangChain and ZeroQuant.

Prerequisites

  • Python 3.10+
  • An Ethereum wallet with testnet ETH (Sepolia)
  • OpenAI API key (or any LangChain-compatible LLM)

Installation

pip install zeroquant langchain langchain-openai web3 python-dotenv

Step 1: Set Up Environment

Create a .env file:

OPENAI_API_KEY=sk-...
PRIVATE_KEY=0x... # Your wallet private key (testnet only!)
RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY

Step 2: Initialize the Client

import os
import asyncio
from dotenv import load_dotenv
from web3 import Web3
from zeroquant import ZeroQuantClient

load_dotenv()

async def setup():
# Connect to the network
w3 = Web3(Web3.HTTPProvider(os.getenv("RPC_URL")))

# Initialize ZeroQuant client
client = ZeroQuantClient(
web3=w3,
private_key=os.getenv("PRIVATE_KEY"),
factory_address="0x...", # ZeroQuant factory on Sepolia
permission_manager_address="0x...",
)

await client.connect()
return client

# Run with: asyncio.run(setup())

Step 3: Create Tools

from zeroquant.langchain.tools import (
CreateVaultTool,
GetVaultBalanceTool,
ExecuteSwapTool,
)

tools = [
CreateVaultTool(client=client),
GetVaultBalanceTool(client=client),
ExecuteSwapTool(client=client),
]

Step 4: Build the Agent

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

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

prompt = ChatPromptTemplate.from_messages([
("system", """You are a DeFi assistant that helps users manage ZeroQuant vaults.
You can create vaults, check balances, and execute token swaps.
Always confirm operations before executing them.
Be concise and helpful."""),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])

agent = create_openai_functions_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

Step 5: Run the Agent

# Create a vault
result1 = await executor.ainvoke({
"input": "Create a new vault for me with salt 42"
})
print(result1["output"])

# Check balance
result2 = await executor.ainvoke({
"input": "What is the ETH balance of my vault?"
})
print(result2["output"])

Complete Example

Here's the full working code:

import os
import asyncio
from dotenv import load_dotenv
from web3 import Web3
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

from zeroquant import ZeroQuantClient
from zeroquant.langchain.tools import (
CreateVaultTool,
GetVaultBalanceTool,
ExecuteSwapTool,
)

load_dotenv()


async def main():
# Setup
w3 = Web3(Web3.HTTPProvider(os.getenv("RPC_URL")))

client = ZeroQuantClient(
web3=w3,
private_key=os.getenv("PRIVATE_KEY"),
factory_address=os.getenv("FACTORY_ADDRESS"),
permission_manager_address=os.getenv("PERMISSION_MANAGER_ADDRESS"),
)
await client.connect()

# Tools
tools = [
CreateVaultTool(client=client),
GetVaultBalanceTool(client=client),
ExecuteSwapTool(client=client),
]

# Agent
llm = ChatOpenAI(model="gpt-4", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a DeFi assistant. Help users manage vaults and execute swaps safely."),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])

agent = create_openai_functions_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Interactive loop
print("ZeroQuant Agent Ready! Type your commands:\n")

while True:
try:
user_input = input("You: ")
if user_input.lower() == "exit":
break

result = await executor.ainvoke({"input": user_input})
print(f"\nAgent: {result['output']}\n")
except KeyboardInterrupt:
break
except Exception as e:
print(f"Error: {e}")


if __name__ == "__main__":
asyncio.run(main())

What's Next?

Now that you have a basic agent working:

Troubleshooting

"Insufficient funds"

Make sure your wallet has testnet ETH. Get some from the Sepolia Faucet.

"Contract not found"

Verify your factoryAddress and permissionManagerAddress are correct for Sepolia testnet.

Agent not responding

Check your OPENAI_API_KEY is valid and has available credits.