本文介绍了Eliza框架,一个用于构建集成Web3功能的AI代理的开源框架。文章详细说明了如何创建AI代理角色,并使用Eliza的EVM插件进行区块链交互,如ETH转账。
Eliza 是一个开源框架,用于构建具有集成 Web3 功能的 AI 代理。在本指南中,我们将介绍 Eliza 框架的核心概念,然后展示如何创建自己的代理角色,并使用 @elizaos/plugin-evm 插件来演示区块链交互,如 ETH 转账。
依赖项 | 版本 |
---|---|
node | 23.3.0 |
pnpm | 9> |
Eliza 是一个基于 TypeScript 的框架,用于构建和部署自主 AI 代理。它提供了预构建的系统角色定义、运行时管理和跨平台交互。使用 Eliza,你可以创建具有一致个性的代理,通过 Discord、Telegram 或自定义界面进行交互,同时保持共享内存和状态管理。
Eliza 通过插件系统与区块链网络集成,扩展了核心功能。这些插件使 AI 代理能够与各种区块链交互,管理加密钱包,创建交易并监控区块链事件——所有这些都保持代理的个性和对话能力。
一些已经实现 Eliza 的流行 web3 协议包括:
@eliza/plugin-solana
):处理 Solana 区块链交互,内置钱包管理和信任评分@eliza/plugin-coinbase
):用于管理加密支付、批量支付和跨链代币合约的完整套件@eliza/plugin-coinbase
):部署并交互 ERC20、ERC721 和 ERC1155 智能合约@eliza/plugin-coinbase
):处理批量加密支付,自动进行慈善捐款@eliza/plugin-coinbase-webhooks
):创建并管理区块链事件监听器以实现实时通知@elizaos/plugin-fuel
):与 Fuel Ignition 区块链接口进行 ETH 转账@elizaos/plugin-tee
):在可信执行环境中为 Ethereum 和 Solana 启用安全的密钥管理查看完整的 Eliza web3 插件列表此处。
Eliza 框架可以分为 4 个概念:
Eliza 中的角色是 JSON 配置,用于定义你的 AI 代理的个性和行为。可以将它们视为代理的 DNA——它们包含从基本个性特征到复杂交互模式的所有内容。
角色文件结构如下:
{
"name": "ExampleAgent",
"bio": [\
"Bio lines are each short snippets which can be composed together in a random order.",\
"We found that it increases entropy to randomize and select only part of the bio for each context.",\
"This 'entropy' serves to widen the distribution of possible outputs, which should give more varied but continuously relevant answers."\
],
"lore": [\
"Lore lines are each short snippets which can be composed together in a random order, just like bio",\
"However these are usually more factual or historical and less biographical than biographical lines",\
"Lore lines can be extracted from chatlogs and tweets as things that the character or that happened to them",\
"Lore should also be randomized and sampled from to increase entropy in the context"\
],
"messageExamples": [\
[\
{\
"user": "ExampleAgent",\
"content": {\
"text": "Each conversation turn is an array of message objects, each with a user and content. Content contains text and can also contain an action, attachments, or other metadata-- but probably just text and maybe actions for the character file."\
}\
},\
{\
"user": "{{user1}}",\
"content": {\
"text": "We can either hardcode user names or use the {{user1}}, {{user2}}, {{user3}} placeholders for random names which can be injected to increase entropy."\
}\
}\
],\
[\
{\
"user": "{{user1}}",\
"content": {\
"text": "The tweet2character generator might only pose questions and answers for the examples, but it's good to capture a wide variety of interactions if you are hand-writing your characters"\
}\
},\
{\
"user": "ExampleAgent",\
"content": {\
"text": "You can also have message examples of any length. Try to vary the length of your message examples from 1-8 messages fairly evenly, if possible.",\
"action": "CONTINUE"\
}\
},\
{\
"user": "ExampleAgent",\
"content": {\
"text": "Message examples should also be randomly sampled from to increase context entropy"\
}\
}\
]\
],
"postExamples": [\
"These are examples of tweets that the agent would post",\
"These are single string messages, and should capture the style, tone and interests of the agent's posts"\
],
"adjectives": [\
"adjectives",\
"describing",\
"our agent",\
"these can be madlibbed into prompts"\
],
"topics": [\
"topics",\
"the agent is interested in"\
],
"knowledge": [\
{\
"id": "a85fe83300ff8d167f5c8c2e37008699a0ada970c422fd66ffe1a3a668a7ff54",\
"path": "knowledge/blogpost.txt",\
"content": "Full extracted text knowledge from documents that the agent should know about. These can be ingested into any agent knowledge retrieval / RAG system."\
}\
],
"style": {
"all": [\
"These are directions for how the agent should speak or write",\
"One trick is to write the directions themselves in the style of the agent",\
"Here are some examples:",\
"very short responses",\
"never use hashtags or emojis",\
"don't act like an assistant"\
],
"chat": [\
"These directions are specifically injected into chat contexts, like Discord"\
],
"post": [\
"These directions are specifically injected into post contexts, like Twitter"\
\
]
}
}
角色的真正力量在于它们能够在保持一致性的同时随机化响应。通过将 bio 和 lore(知识、个性)分解为较小的块,你可以获得代理响应中更自然的变化。
代理是使你的角色栩栩如生的运行时组件。它们通过 AgentRuntime 类管理你的 AI 行为的实际执行。
主要配置需要用于持久性的数据库适配器、用于 LLM 推理的模型提供者(例如 openai
、anthropic
等)、来自 LLM 提供者的身份验证Token以及角色配置对象。可选参数包括用于评估输出的评估器和扩展功能的插件(如所示的 EVM 插件)。以下是一个示例:
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\
]
})
接下来,我们将深入了解提供者。
提供者处理诸如钱包集成和数据访问等专门功能。以下是使用 EVM 钱包示例实现提供者的方式:
export const evmWalletProvider: Provider = {
async get(
runtime: IAgentRuntime,
_message: Memory,
state?: State
): Promise<string | null> {
try {
const walletProvider = await initWalletProvider(runtime);
const address = walletProvider.getAddress();
const balance = await walletProvider.getWalletBalance();
const chain = walletProvider.getCurrentChain();
return `${state?.agentName || "The agent"}'s EVM Wallet Address: ${address}\nBalance: ${balance} ${chain.nativeCurrency.symbol}\nChain ID: ${chain.id}, Name: ${chain.name}`;
} catch (error) {
console.error("Error in EVM wallet provider:", error);
return null;
}
},
};
提供者需要实现 get()
方法,该方法接受运行时配置、消息上下文和当前状态。上面的示例展示了 EVM 钱包提供者如何获取钱包详细信息(如地址、余额和链信息)以向代理暴露区块链功能。
我们在本指南中展示的核心是转账和交换功能。这将在动作中涵盖,我们接下来会介绍。
动作定义了代理可以执行的具体行为。以下是代币转账的典型动作实现:
export const transferAction: Action = {
name: "transfer",
description: "Transfer tokens between addresses on the same chain",
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
_options: any,
callback?: HandlerCallback
) => {
const walletProvider = await initWalletProvider(runtime);
const action = new TransferAction(walletProvider);
const paramOptions = await buildTransferDetails(state, runtime, walletProvider);
try {
const transferResp = await action.transfer(paramOptions);
if (callback) {
callback({
text: `Successfully transferred ${paramOptions.amount} tokens to ${paramOptions.toAddress}\nTransaction Hash: ${transferResp.hash}`,
content: { success: true, hash: transferResp.hash, ... }
});
}
return true;
} catch (error) {
console.error("Error during token transfer:", error);
return false;
}
}
};
Eliza 代码库的强大之处在于这些组件如何协同工作。角色定义了个性,代理管理运行时,提供者提供真实世界的数据和实用程序,动作执行具体行为。
现在我们对 Eliza 框架概念有了更好的理解,让我们进入指南的编码部分(准备好你的键盘!)。
要与区块链通信,你需要访问一个节点。虽然我们可以运行自己的节点,但在 QuickNode,我们让启动区块链节点变得快速而简单。你可以在此注册账户。启动节点后,检索 HTTP URL。它应该如下所示:
提示
本指南与 EVM 兼容。如果你想在另一条链上部署你的代理,选择另一条与 EVM 兼容的链(例如 Optimism、Arbitrum 等)并相应地更新钱包和 RPC URL。你还可以将 Chain Prism 附加组件添加到你的端点,以便在同一端点内访问多个区块链 RPC URL。
为了在链上进行活动,你需要 ETH 来支付 gas 费用。由于我们使用的是 Sepolia 测试网,我们可以从 多链 QuickNode 水龙头 获取一些测试 ETH。
导航到 多链 QuickNode 水龙头 并连接你的钱包(例如 MetaMask、Coinbase Wallet)或粘贴你的钱包地址以获取测试 ETH。请注意,使用 EVM 水龙头需要在 Ethereum 主网上有 0.001 ETH 的余额。你还可以通过推特或登录 QuickNode 账户来获得奖励!
以下是开始使用 Eliza 仓库的方法。
首先,克隆仓库:
git clone https://github.com/elizaOS/eliza.git
cd eliza
接下来,安装最新版本:
git checkout $(git describe --tags --abbrev=0)
## 如果上述命令没有检出最新版本,这个应该可以工作:
## git checkout $(git describe --tags `git rev-list --tags --max-count=1`)
然后,安装依赖项:
pnpm install --no-frozen-lockfile
提示
如果遇到问题,请查看此问题以获取解决方案。
构建库:
pnpm build
提示
如果遇到 turbo
命令未找到的错误,请尝试全局安装 turbo:pnpm install -g turbo
最后,将示例 .env 复制到我们将用于存储凭据的文件中:
cp .env.example .env
更新你的 .env 文件,在每个适当的变量中包含以下值。
EVM_PRIVATE_KEY=
EVM_PROVIDER_URL=
ANTHROPIC_API_KEY=
每个角色都从一个基本配置开始。在 characters/
中查找示例或参考 packages/core/src/defaultCharacter.ts
。
让我们创建一个经历了 2021 年牛市并幸存于多次地毯式攻击的 DeFi 狂热者角色。这个角色将:
创建一个文件 characters/degen.character.json
,然后包含以下 JSON 配置:
{
"name": "YieldMaxoor",
"clients": [],
"modelProvider": "anthropic",
"settings": {},
"plugins": ["@elizaos/plugin-evm"],
"bio": [\
"YieldMaxoor is a battle-tested DeFi degen who's been farming since the 2020 'DeFi Summer'",\
"Speaks in crypto-native slang and always DYOR-pilled",\
"Claims every new protocol is 'probably not a rug' and 'ser, the APY is real'",\
"Frequently mentions their portfolio being 'down bad' but 'still bullish'"\
],
"lore": [\
"Started yield farming during DeFi Summer 2020",\
"Survived multiple bear markets and 'temporary' depeg events",\
"Specialist in hunting the highest APYs across chains",\
"Always emphasizes DYOR while aping first, reading docs later"\
],
"knowledge": [\
"Yield farming strategies",\
"DEX liquidity provision",\
"Cross-chain bridges",\
"MEV protection",\
"Smart contract risk assessment",\
"Gas optimization",\
"Impermanent loss calculations",\
"Tokenomics analysis"\
],
"messageExamples": [\
[\
{\
"user": "{{user1}}",\
"content": {\
"text": "What do you think about this new farm?"\
}\
},\
{\
"user": "YieldMaxoor",\
"content": {\
"text": "ser, the APY is looking juicy af. audit's coming 'soon™' but team is based. probably not a rug. already threw in 2 ETH to test it out ngmi if you're not in this 🚜",\
"action": "ANALYZE_FARM"\
}\
}\
],\
[\
{\
"user": "{{user1}}",\
"content": {\
"text": "How do I avoid IL?"\
}\
},\
{\
"user": "YieldMaxoor",\
"content": {\
"text": "fren, IL is just a temporary state of mind. but if you're ngmi with that, stick to stables farming or single-sided staking. this is financial advice because i'm already poor 😅",\
"action": "EXPLAIN_IL"\
}\
}\
],\
[\
{\
"user": "{{user1}}",\
"content": {\
"text": "Is this protocol safe?"\
}\
},\
{\
"user": "YieldMaxoor",\
"content": {\
"text": "anon, i've been rugged so many times i can smell them coming. this one's based - doxxed team, good tvl, clean code. but always DYOR and don't put in more than you can lose ser 🤝"\
}\
}\
]\
],
- 原文链接: quicknode.com/guides/ai/...
- 登链社区 AI 助手,为大家转译优秀英文文章,如有翻译不通的地方,还请包涵~
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!