LangChain Quick Start
Build a working DeFi agent in 5 minutes using LangChain and ZeroQuant.
Prerequisites
- Python
- TypeScript
- Python 3.10+
- An Ethereum wallet with testnet ETH (Sepolia)
- OpenAI API key (or any LangChain-compatible LLM)
- Node.js 18+
- An Ethereum wallet with testnet ETH (Sepolia)
- OpenAI API key (or any LangChain-compatible LLM)
Installation
- Python
- TypeScript
pip install zeroquant langchain langchain-openai web3 python-dotenv
npm install @zeroquant/sdk @zeroquant/langchain @langchain/openai langchain ethers
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
- Python
- TypeScript
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())
import { ethers } from 'ethers';
import { ZeroQuantClient } from '@zeroquant/sdk';
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
const client = new ZeroQuantClient(provider, {
factoryAddress: '0x...', // ZeroQuant factory on Sepolia
permissionManagerAddress: '0x...',
});
await client.connect(signer);
Step 3: Create Tools
- Python
- TypeScript
from zeroquant.langchain.tools import (
CreateVaultTool,
GetVaultBalanceTool,
ExecuteSwapTool,
)
tools = [
CreateVaultTool(client=client),
GetVaultBalanceTool(client=client),
ExecuteSwapTool(client=client),
]
import {
CreateVaultTool,
GetVaultBalanceTool,
ExecuteSwapTool
} from '@zeroquant/langchain';
const tools = [
new CreateVaultTool({ client }),
new GetVaultBalanceTool({ client }),
new ExecuteSwapTool({ client }),
];
Step 4: Build the Agent
- Python
- TypeScript
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)
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatPromptTemplate } from '@langchain/core/prompts';
const llm = new ChatOpenAI({
modelName: 'gpt-4',
temperature: 0,
});
const prompt = ChatPromptTemplate.fromMessages([
['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}'],
['placeholder', '{agent_scratchpad}'],
]);
const agent = await createOpenAIFunctionsAgent({ llm, tools, prompt });
const executor = new AgentExecutor({ agent, tools, verbose: true });
Step 5: Run the Agent
- Python
- TypeScript
# 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"])
// Create a vault
const result1 = await executor.invoke({
input: 'Create a new vault for me with salt 42',
});
console.log(result1.output);
// Check balance
const result2 = await executor.invoke({
input: 'What is the ETH balance of my vault?',
});
console.log(result2.output);
Complete Example
Here's the full working code:
- Python
- TypeScript
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())
import { ethers } from 'ethers';
import { ZeroQuantClient } from '@zeroquant/sdk';
import {
CreateVaultTool,
GetVaultBalanceTool,
ExecuteSwapTool
} from '@zeroquant/langchain';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatPromptTemplate } from '@langchain/core/prompts';
import 'dotenv/config';
async function main() {
// Setup
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
const client = new ZeroQuantClient(provider, {
factoryAddress: process.env.FACTORY_ADDRESS!,
permissionManagerAddress: process.env.PERMISSION_MANAGER_ADDRESS!,
});
await client.connect(signer);
// Tools
const tools = [
new CreateVaultTool({ client }),
new GetVaultBalanceTool({ client }),
new ExecuteSwapTool({ client }),
];
// Agent
const llm = new ChatOpenAI({ modelName: 'gpt-4', temperature: 0 });
const prompt = ChatPromptTemplate.fromMessages([
['system', 'You are a DeFi assistant. Help users manage vaults and execute swaps safely.'],
['human', '{input}'],
['placeholder', '{agent_scratchpad}'],
]);
const agent = await createOpenAIFunctionsAgent({ llm, tools, prompt });
const executor = new AgentExecutor({ agent, tools, verbose: true });
// Interactive loop
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.log('ZeroQuant Agent Ready! Type your commands:\n');
const askQuestion = () => {
rl.question('You: ', async (input: string) => {
if (input.toLowerCase() === 'exit') {
rl.close();
return;
}
try {
const result = await executor.invoke({ input });
console.log(`\nAgent: ${result.output}\n`);
} catch (error) {
console.error('Error:', error);
}
askQuestion();
});
};
askQuestion();
}
main().catch(console.error);
What's Next?
Now that you have a basic agent working:
- Add Memory - Make your agent remember previous conversations
- Trading Agent - Build an agent that analyzes markets and executes trades
- Advanced AI Trading - Full trading system with local LLMs
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.