如何构建支持Web3的AI代理Eliza

  • QuickNode
  • 发布于 2024-11-17 20:45
  • 阅读 70

本文介绍了Eliza框架,一个用于构建集成Web3功能的AI代理的开源框架。文章详细说明了如何创建AI代理角色,并使用Eliza的EVM插件进行区块链交互,如ETH转账。

概述

Eliza 是一个开源框架,用于构建具有集成 Web3 功能的 AI 代理。在本指南中,我们将介绍 Eliza 框架的核心概念,然后展示如何创建自己的代理角色,并使用 @elizaos/plugin-evm 插件来演示区块链交互,如 ETH 转账。

你将做什么

  • 设置一个代理角色
  • 查看涵盖转账和交换等操作的代码
  • 与代理交互以在 Ethereum Sepolia 上进行 ETH 转账(或使用你选择的链)
  • 为未来的构建提出建议

你需要什么

  • 对编程概念的中级理解
  • 已安装 Node.jsTypeScriptpnpm(推荐使用 nvm)
  • 一个 EVM 钱包(有一些 ETH 用于模拟转账、交换和支付 gas 费用)
  • 一个 QuickNode 端点(在此创建
  • 一个 Anthropic 或 OpenAI API 密钥
依赖项 版本
node 23.3.0
pnpm 9>

什么是 a16z Eliza?

Eliza 是一个基于 TypeScript 的框架,用于构建和部署自主 AI 代理。它提供了预构建的系统角色定义、运行时管理和跨平台交互。使用 Eliza,你可以创建具有一致个性的代理,通过 Discord、Telegram 或自定义界面进行交互,同时保持共享内存和状态管理。

Eliza 与 Web3 集成

Eliza 通过插件系统与区块链网络集成,扩展了核心功能。这些插件使 AI 代理能够与各种区块链交互,管理加密钱包,创建交易并监控区块链事件——所有这些都保持代理的个性和对话能力。

一些已经实现 Eliza 的流行 web3 协议包括:

  • Solana 插件 (@eliza/plugin-solana):处理 Solana 区块链交互,内置钱包管理和信任评分
  • Coinbase 插件 (@eliza/plugin-coinbase):用于管理加密支付、批量支付和跨链代币合约的完整套件
  • 代币合约插件 (@eliza/plugin-coinbase):部署并交互 ERC20ERC721ERC1155 智能合约
  • 批量支付插件 (@eliza/plugin-coinbase):处理批量加密支付,自动进行慈善捐款
  • Webhook 插件 (@eliza/plugin-coinbase-webhooks):创建并管理区块链事件监听器以实现实时通知
  • Fuel 插件 (@elizaos/plugin-fuel):与 Fuel Ignition 区块链接口进行 ETH 转账
  • TEE 插件 (@elizaos/plugin-tee):在可信执行环境中为 Ethereum 和 Solana 启用安全的密钥管理

查看完整的 Eliza web3 插件列表此处

Eliza 框架:概念

Eliza 框架可以分为 4 个概念:

  • 角色:定义 AI 个性和行为的 JSON 配置文件
  • 代理:管理内存并执行行为的运行时组件
  • 提供者:将上下文注入交互的数据连接器
  • 动作:代理可以执行的可执行行为

角色

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 推理的模型提供者(例如 openaianthropic 等)、来自 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 端点

要与区块链通信,你需要访问一个节点。虽然我们可以运行自己的节点,但在 QuickNode,我们让启动区块链节点变得快速而简单。你可以在此注册账户。启动节点后,检索 HTTP URL。它应该如下所示:

Quicknode 主网端点截图

提示

本指南与 EVM 兼容。如果你想在另一条链上部署你的代理,选择另一条与 EVM 兼容的链(例如 Optimism、Arbitrum 等)并相应地更新钱包和 RPC URL。你还可以将 Chain Prism 附加组件添加到你的端点,以便在同一端点内访问多个区块链 RPC URL。

项目前提:从 QuickNode 多链水龙头获取 ETH

为了在链上进行活动,你需要 ETH 来支付 gas 费用。由于我们使用的是 Sepolia 测试网,我们可以从 多链 QuickNode 水龙头 获取一些测试 ETH。

导航到 多链 QuickNode 水龙头 并连接你的钱包(例如 MetaMask、Coinbase Wallet)或粘贴你的钱包地址以获取测试 ETH。请注意,使用 EVM 水龙头需要在 Ethereum 主网上有 0.001 ETH 的余额。你还可以通过推特或登录 QuickNode 账户来获得奖励!

QuickNode 水龙头

设置 Eliza 仓库

以下是开始使用 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 狂热者角色。这个角色将:

  • 拥有 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 助手,为大家转译优秀英文文章,如有翻译不通的地方,还请包涵~
点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
QuickNode
QuickNode
江湖只有他的大名,没有他的介绍。