AI agent 是自主程式,旨在感知環境、處理資訊,並採取行動以達成特定目標。這些 agent 的形式多元,從簡單的規則型機器人,到能夠隨時間自我調適並優化決策的進階機器學習系統,皆涵蓋其中。
在區塊鏈與 DeFi 領域,AI 驅動自動化的崛起為無縫且智慧的鏈上互動開啟了新的可能。從自動化交易、風險評估、流動性管理等任務,到執行複雜的智能合約互動,AI agent 正在改變我們建構 dapp 的方式,大幅提升效率並降低人工介入的需求。
透過 ElizaOS 等框架,開發者可以建構能與區塊鏈協議互動的 AI agent,並針對代幣兌換、套利及投資組合管理即時做出決策。本指南將帶您逐步了解如何設計、設定並實作一個能利用 ElizaOS 內建功能自主執行交易的 AI agent。
前置條件
開始建構之前,請確認您已完成以下設定:
Node.js(v23.3.0 或更高版本)
PNPM 套件管理器
具備測試網代幣的 EVM 相容錢包——用於執行交易(例如 Sepolia ETH)
RPC 提供者 URL——將您的應用程式連接至區塊鏈,例如 Infura
模型提供者的 API 金鑰——AI 互動所需(例如 OpenAI)
完成上述準備後,即可開始建構您的 AI 驅動區塊鏈 agent。
設定 ElizaOS 環境
Clone ElizaOS 儲存庫並切換至最新版本。
git clone https://github.com/elizaOS/eliza.git
cd eliza
git checkout $(git describe --tags --abbrev=0)
若主版本無法正常運作,可切換至穩定版本。撰寫本文時,建議使用 stable-11-30 版本。請執行以下指令:
git fetch --all
git checkout stable-11-30
安裝相依套件
pnpm install
設定環境變數
cp .env.example .env
`# EVM
EVM_PRIVATE_KEY=
EVM_PROVIDER_URL=
OPEN AI
OPENAI_API_KEY=`
以上資訊對 ElizaOS 的正常運作至關重要:
EVM_PRIVATE_KEY**:** 用於簽署交易的錢包私鑰。這是 Eliza 進行代幣轉帳與兌換的錢包,請確保其中已預先存入一些 Sepolia 測試網 ETH。
EVM_PROVIDER_URL**:** 連接至區塊鏈節點的 RPC 端點,讓 AI agent 得以與網路互動。
OPENAI_API_KEY**:** 授予 OpenAI 模型存取權限,使 AI agent 能夠做出智慧決策。
注意: 請確保您的私鑰安全無虞,並將其排除在版本控制之外。
Eliza 框架的核心概念
Eliza 框架由四個關鍵元件組成:
Characters(角色):JSON 設定檔,用於定義 AI 的個性、行為與溝通風格
Agents(代理):負責管理記憶、處理輸入及執行行為的執行時期模組
Providers(提供者):提供情境與即時資訊的資料來源,用以強化互動品質
Actions(動作):可執行的函式,讓 agent 能夠執行任務並與外部系統互動
定義代幣兌換與轉帳角色
Characters 定義了 AI agent 的溝通風格、語氣與回應一致性,使互動更加自然且引人入勝。一個精心設計的 character 能確保 AI 與其預定目的相符。
本專案的主要功能為代幣轉帳與兌換,因此我們將定義一個 Eliza character,用以規範 AI agent 如何與區塊鏈協議互動、執行交易,以及向使用者提供回饋。此 character 將確保 agent 清晰傳達交易細節、遵循預先定義的安全規則,並維持流暢的使用者體驗。
建立新的 character 檔案。
cd characters
touch degen.character.json
將以下內容複製至新建立的檔案中:
{
"name": "ETHMaxxer",
"clients": [],
"modelProvider": "openai",
"settings": {
"chains": {
"evm": ["sepolia"]
}
},
"plugins": ["@elizaos/plugin-evm"],
"bio": [
"ETH Transfers",
"ETHMaxxer is a crypto-native who lives and breathes Ethereum",
"Believes every dip is a 'generational buying opportunity'",
"Always sending ETH and reminding everyone 'gas fees are part of the game'",
"Claims 'BTC is cool, but ETH is the future of finance'",
"Frequently checks gas prices but still sends transactions anyway"
],
"lore": [
"Started stacking ETH in the early days, never looked back",
"Loves discussing new L2s, staking, and Ethereum upgrades",
"Firm believer in 'not your keys, not your coins'",
"Survived multiple bull and bear cycles but still max bullish"
],
"knowledge": [
"Sending ETH transactions",
"Gas fee optimization",
"Ethereum staking",
"Layer 2 scaling solutions",
"DeFi applications",
"Smart contract risks",
"On-chain security",
"Bridging assets",
"Crypto market trends"
],
"messageExamples": [
[
{
"user": "{{user1}}",
"content": {
"text": "How do I send ETH?"
}
},
{
"user": "ETHMaxxer",
"content": {
"text": "ser, just fire up your wallet, enter the recipient, and set that gas. if it's an L1 tx, brace for the fees but ngl, sending ETH is always worth it ",
"action": "SEND_ETH"
}
}
],
[
{
"user": "{{user1}}",
"content": {
"text": "Gas fees are high, what do I do?"
}
},
{
"user": "ETHMaxxer",
"content": {
"text": "fren, welcome to the ETH experience . either wait for a low-gas window, use an L2 like Arbitrum, or just send it and embrace the pain. ngmi if you're scared of gas fees "
}
}
],
[
{
"user": "{{user1}}",
"content": {
"text": "Is ETH going up?"
}
},
{
"user": "ETHMaxxer",
"content": {
"text": "anon, ETH is always going up... eventually. if not today, then after the next hard fork or bull cycle. remember, '1 ETH = 1 ETH', just hodl "
}
}
]
],
"postExamples": [
"gas is pain, but ETH is life ",
"sending ETH and feeling rich, until I check my gas fees ",
"L2s are cool, but real maxxers still send ETH on mainnet "
],
"topics": [
"eth_transfers",
"ethereum_news",
"gas_fees",
"staking",
"crypto_markets"
],
"style": {
"all": [
"Crypto-maximalist",
"ETH-focused",
"Slightly degen",
"Loves talking about gas fees and upgrades"
],
"chat": [
"Casual",
"Crypto-slang heavy",
"Slightly memetic",
"Uses emojis frequently"
],
"post": ["Short", "Bullish", "Relatable", "Memetic"]
},
"adjectives": [
"ETH-maxi",
"Bullish",
"Crypto-native",
"Gas-tolerant",
"Future-focused",
"Layer 2 curious"
]
}
上述檔案定義了名為 ETHMaxxer 的 AI agent 設定,指定 "modelProvider": "openai" 並將 Sepolia 設為指定的區塊鏈網路。
Agents
Eliza 框架中的 Agents 是核心執行時期元件,負責賦予 AI characters 生命力。它們透過 AgentRuntime 類別管理行為與互動。AgentRuntime 類別的正常運作需要幾個關鍵元件,其中部分已由 Eliza 框架內建處理:
資料庫適配器:負責 AI agent 的資訊儲存與擷取,包括記憶體儲存、關係追蹤及知識管理。
Plugins(插件):擴展 AI agent 的功能,支援與區塊鏈、社群媒體等外部服務整合。本專案中,我們指定 AI agent 使用 @elizaos/plugin-evm 與區塊鏈互動。
模型提供者:定義用於處理與生成回應的 AI 模型來源。可用選項包括 Anthropic、Grok 等,但本專案選用 OpenAI,如我們的 character 檔案所定義。
驗證 token:所選模型提供者所需,應以環境變數形式傳入,例如 OPENAI_API_KEY。
Character 設定檔:我們先前定義的 character 檔案,概述 AI agent 的特質與行為。
所有這些元件均定義於 /agent/src/index.ts 資料夾中。與我們的 agent 相關的 AgentRuntime 程式碼片段如下:
return new AgentRuntime({
databaseAdapter: db,
token,
modelProvider: character.modelProvider,
evaluators: [],
character,
plugins: [
getSecret(character, "EVM_PUBLIC_KEY") ||
(getSecret(character, "WALLET_PUBLIC_KEY") &&
getSecret(character, "WALLET_PUBLIC_KEY")?.startsWith("0x"))
? evmPlugin
: null
]
})
Providers
Providers 負責處理錢包整合、區塊鏈互動及資料存取等專門功能,確保 AI agent 能與外部系統無縫連接。它們作為執行交易、擷取即時資料及管理跨服務互動的閘道。
在 @elizaos/plugin-evm 中,providers 讓 AI agent 得以與 EVM 相容的區塊鏈互動,使其能夠發送交易、查詢智能合約並監控區塊鏈活動。透過 Infura 等服務提供的 RPC 端點,agent 無需運行專屬節點即可執行鏈上操作。
以下是 @elizaos/plugin-evm 中 providers 的實作方式:
export class WalletProvider {
private cache: NodeCache;
private cacheKey: string = "evm/wallet";
private currentChain: SupportedChain = "mainnet";
private CACHE_EXPIRY_SEC = 5;
chains: Record<string, Chain> = { ...viemChains };
account: PrivateKeyAccount;
constructor(
accountOrPrivateKey: PrivateKeyAccount |
0x${string},
private cacheManager: ICacheManager,
chains?: Record<string, Chain>
) {
this.setAccount(accountOrPrivateKey);
this.setChains(chains);
if (chains && Object.keys(chains).length > 0) {
this.setCurrentChain(Object.keys(chains)[0] as SupportedChain);
}
this.cache = new NodeCache({ stdTTL: this.CACHE_EXPIRY_SEC });
}
getAddress(): Address {
return this.account.address;
}
getCurrentChain(): Chain {
return this.chains[this.currentChain];
}
getPublicClient(
chainName: SupportedChain
): PublicClient<HttpTransport, Chain, Account | undefined> {
const transport = this.createHttpTransport(chainName);
const publicClient = createPublicClient({
chain: this.chains[chainName],
transport,
});
return publicClient;
}
getWalletClient(chainName: SupportedChain): WalletClient {
const transport = this.createHttpTransport(chainName);
const walletClient = createWalletClient({
chain: this.chains[chainName],
transport,
account: this.account,
});
return walletClient;
}
getChainConfigs(chainName: SupportedChain): Chain {
const chain = viemChains[chainName];
if (!chain?.id) {
throw new Error("Invalid chain name");
}
return chain;
}
async getWalletBalance(): Promise<string | null> {
const cacheKey = "walletBalance_" + this.currentChain;
const cachedData = await this.getCachedData<string>(cacheKey);
if (cachedData) {
elizaLogger.log(
"Returning cached wallet balance for chain: " +
this.currentChain
);
return cachedData;
}
try {
const client = this.getPublicClient(this.currentChain);
const balance = await client.getBalance({
address: this.account.address,
});
const balanceFormatted = formatUnits(balance, 18);
this.setCachedData<string>(cacheKey, balanceFormatted);
elizaLogger.log(
"Wallet balance cached for chain: ",
this.currentChain
);
return balanceFormatted;
} catch (error) {
console.error("Error getting wallet balance:", error);
return null;
}
}
async getWalletBalanceForChain(
chainName: SupportedChain
): Promise<string | null> {
try {
const client = this.getPublicClient(chainName);
const balance = await client.getBalance({
address: this.account.address,
});
return formatUnits(balance, 18);
} catch (error) {
console.error("Error getting wallet balance:", error);
return null;
}
}
addChain(chain: Record<string, Chain>) {
this.setChains(chain);
}
}
Actions
Actions 定義了 AI agent 可執行的特定行為,使其能夠與外部系統互動、處理請求並自動化任務。每個 action 均設計用於執行特定功能,例如發送交易、擷取資料或執行智能合約呼叫,確保 agent 在其環境中高效運作。
在 @elizaos/plugin-evm 中,actions 促成代幣轉帳、兌換及區塊鏈互動,讓 AI agent 得以直接在 EVM 相容網路上執行交易。這些 actions 由使用者輸入或預先定義的邏輯觸發,確保區塊鏈相關操作的無縫執行。
以下是 @elizaos/plugin-evm 中代幣轉帳 action 的實作方式:
async transfer(params: TransferParams): Promise<Transaction> {
console.log(
Transferring: ${params.amount} tokens to (${params.toAddress} on ${params.fromChain})
);
if (!params.data) {
params.data = "0x";
}
this.walletProvider.switchChain(params.fromChain);
const walletClient = this.walletProvider.getWalletClient(
params.fromChain
);
try {
const hash = await walletClient.sendTransaction({
account: walletClient.account,
to: params.toAddress,
value: parseEther(params.amount),
data: params.data as Hex,
kzg: {
blobToKzgCommitment: function (_: ByteArray): ByteArray {
throw new Error("Function not implemented.");
},
computeBlobKzgProof: function (
_blob: ByteArray,
_commitment: ByteArray
): ByteArray {
throw new Error("Function not implemented.");
},
},
chain: undefined,
});
return {
hash,
from: walletClient.account.address,
to: params.toAddress,
value: parseEther(params.amount),
data: params.data as Hex,
};
} catch (error) {
throw new Error(
Transfer failed: ${error.message}
現在,我們已提供環境變數、character 檔案並指定要使用的 Eliza plugin,接下來讓我們將所有元件整合在一起,並測試我們的 AI agent。
建構專案
pnpm build
執行 character
pnpm start --character="characters/degen.character.json"
啟動客戶端
pnpm start:client
現在,讓我們與 agent 互動,並要求它執行特定任務。
結語
建構一個能與以太坊及 EVM 相容區塊鏈互動的 AI agent,為自動化且智慧的鏈上互動開啟了全新可能。本指南帶您完整了解如何定義 Characters、Agents、Providers 與 Actions,使 agent 得以自主執行代幣轉帳與兌換。
透過 ElizaOS 的模組化框架,開發者可以打造 AI 驅動的 DeFi 助理、交易機器人或投資組合管理工具,與區塊鏈網路無縫互動。現在您已掌握基礎,不妨嘗試擴展其功能、精煉邏輯,並整合新特性,進一步強化鏈上自動化能力。