0.0.2 • Published 5 months ago

@hashgraphonline/agent-kit v0.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
5 months ago

@hashgraphonline/hedera-agent-kit

Build LLM-powered applications that interact with the Hedera Network. Create conversational agents that can understand user requests in natural language and execute Hedera transactions, or build backend systems that leverage AI for on-chain operations.

Key Features

  • Conversational Hedera: Easily build chat-based interfaces for Hedera actions.
  • Flexible Transaction Handling:
    • Direct Execution: For autonomous agents or backend control.
    • Provide Bytes: For user-centric apps where users sign with their own wallets (e.g., HashPack via WalletConnect).
    • Scheduled Transactions: Built-in support for "human-in-the-loop" workflows, where AI prepares transactions for user review and approval.
  • Comprehensive Toolset: Pre-built tools for HTS, HCS, HBAR transfers, account management, files, and smart contracts.
  • Extensible: Add your own custom tools with the plugin system.
  • Simplified SDK Interaction: Abstracts away much of the Hedera SDK boilerplate.

Table of Contents

Installation

npm install @hashgraphonline/hedera-agent-kit @hashgraph/sdk zod @langchain/openai @langchain/core
# or
yarn add @hashgraphonline/hedera-agent-kit @hashgraph/sdk zod @langchain/openai @langchain/core

(Ensure you have dotenv for environment variable management if you use .env files.)

Quick Start: Your First Conversational Hedera Agent

This example demonstrates setting up the HederaConversationalAgent for a user-centric scenario where the user signs scheduled transactions. The agent's operator account will pay to create the schedule, and the user's account will be set to pay for the actual scheduled transaction when it's signed and submitted by the user.

1. Set up your .env file:

OPENAI_API_KEY="sk-..."
HEDERA_ACCOUNT_ID="0.0.YOUR_AGENT_OPERATOR_ID"
HEDERA_PRIVATE_KEY="your_agent_operator_private_key"
HEDERA_NETWORK="testnet"
USER_ACCOUNT_ID="0.0.YOUR_USER_ACCOUNT_ID"
USER_PRIVATE_KEY="your_user_private_key"

2. Run the interactive demo:

npm install
npm run demo:langchain

3. Example Interaction:

User > Schedule a transfer of 0.1 HBAR from my account to 0.0.34567
Agent > Okay, I have scheduled a transfer of 0.1 HBAR from your account (0.0.USER_ACCOUNT_ID) to 0.0.34567. The Schedule ID is 0.0.xxxxxx.
Agent > Transaction bytes received. Do you want to sign and execute this with YOUR account 0.0.USER_ACCOUNT_ID? (y/n): y
Agent > Transaction executed with your key. Receipt: { ... }

4. Demo Source Reference:

The demo code is in examples/langchain-demo.ts. Here is a simplified excerpt:

import * as dotenv from 'dotenv';
dotenv.config();
import { ServerSigner } from '../src/signer/server-signer';
import { HederaConversationalAgent } from '../src/agent/conversational-agent';

async function main() {
  const operatorId = process.env.HEDERA_ACCOUNT_ID;
  const operatorKey = process.env.HEDERA_PRIVATE_KEY;
  const network = process.env.HEDERA_NETWORK || 'testnet';
  const openaiApiKey = process.env.OPENAI_API_KEY;
  const userAccountId = process.env.USER_ACCOUNT_ID;
  const userPrivateKey = process.env.USER_PRIVATE_KEY;

  if (!operatorId || !operatorKey) throw new Error('HEDERA_ACCOUNT_ID and HEDERA_PRIVATE_KEY must be set in .env');

  const agentSigner = new ServerSigner(operatorId, operatorKey, network);
  const conversationalAgent = new HederaConversationalAgent(agentSigner, {
    operationalMode: 'provideBytes',
    userAccountId: userAccountId,
    verbose: false,
    openAIApiKey: openaiApiKey,
  });
  await conversationalAgent.initialize();
  // ... (see examples/langchain-demo.ts for full interactive loop)
}
main().catch(console.error);

Core Concepts

Understanding these concepts will help you make the most of the Hedera Agent Kit:

  • HederaConversationalAgent: The primary interface for building chat-based applications. It combines the power of an LLM with the Hedera-specific tools provided by HederaAgentKit.
  • HederaAgentKit: The core engine that bundles tools, manages network clients, and holds the signer configuration. It's used internally by HederaConversationalAgent but can also be used directly for more programmatic control.
  • Signers (AbstractSigner): Determine how transactions are signed and paid for:
    • ServerSigner: Holds a private key directly. Useful for backend agents where the agent's account pays for transactions it executes.
    • BrowserSigner (Conceptual for this README): Represents integrating with a user's browser wallet (e.g., HashPack). The agent prepares transaction bytes, and the user signs and submits them via their wallet.
  • Operational Modes: Configure how the agent handles transactions:
    • operationalMode: 'directExecution': Agent signs and submits all transactions using its signer. The agent's operator account pays.
    • operationalMode: 'provideBytes': Agent returns transaction bytes. Your application (and the user, via their wallet) is responsible for signing and submitting. This is key for user-centric apps.
    • scheduleUserTransactionsInBytesMode: boolean (Default: true): When operationalMode is 'provideBytes', this flag makes the agent automatically schedule transactions initiated by the user (e.g., "transfer my HBAR..."). The agent's operator pays to create the schedule entity, and the user pays for the actual scheduled transaction when they sign the ScheduleSignTransaction.
    • metaOptions: { schedule: true }: Allows the LLM to explicitly request scheduling for any tool call, overriding defaults.
  • Human-in-the-Loop Flow: The Quick Start example demonstrates this. The agent first creates a schedule (agent pays). Then, after user confirmation, it prepares a ScheduleSignTransaction (user pays to sign and submit this, triggering the original scheduled transaction).

Available Tools

The Hedera Agent Kit provides a comprehensive set of tools organized by service type. These tools can be used both by the conversational agent and programmatically.

Account Management Tools

Tool NameDescriptionExample Usage
hedera-account-createCreates a new Hedera accountCreate an account with initial balance and key
hedera-account-updateUpdates properties of an existing accountChange account memo, auto-renew period, etc.
hedera-account-deleteDeletes an account and transfers remaining balanceDelete an account and transfer funds to another account
hedera-transfer-hbarTransfers HBAR between accountsSend HBAR from one account to another
hedera-approve-hbar-allowanceApproves an HBAR allowance for a spender accountGrant permission for another account to spend your HBAR
hedera-approve-fungible-token-allowanceApproves a fungible token allowanceGrant permission for another account to spend your tokens
hedera-approve-token-nft-allowanceApproves an NFT allowanceGrant permission for another account to spend your NFTs
hedera-revoke-hbar-allowanceRevokes an HBAR allowanceRemove permission for an account to spend your HBAR
hedera-revoke-fungible-token-allowanceRevokes a fungible token allowanceRemove permission for an account to spend your tokens
hedera-sign-and-execute-scheduled-transactionSigns and executes a scheduled transactionUser signs a transaction prepared by the agent

HBAR Transaction Tools

Tool NameDescriptionExample Usage
hedera-account-transfer-hbarTransfers HBAR between accountsSend HBAR with memo support and detailed parameters
hedera-account-balance-hbarRetrieves HBAR balance for an accountCheck your HBAR balance

HTS Token Service Tools

Tool NameDescriptionExample Usage
hedera-hts-create-fungible-tokenCreates a new fungible tokenCreate a custom token with name, symbol, decimals, etc.
hedera-hts-create-nftCreates a new NFT collectionCreate an NFT collection with configurable properties
hedera-hts-mint-fungible-tokenMints additional supply of a fungible tokenAdd more tokens to circulation
hedera-hts-mint-nftMints a new NFT within a collectionCreate a new NFT with metadata
hedera-hts-transfer-tokensTransfers fungible tokens between accountsSend tokens from one account to another
hedera-hts-transfer-nftTransfers NFT ownershipSend an NFT to another account
hedera-hts-associate-tokenAssociates a token to an accountEnable an account to receive a token
hedera-hts-dissociate-tokensRemoves token associationsRemove a token from your account
hedera-hts-reject-tokensRejects automatically associated tokensReject tokens you don't want
hedera-hts-burn-fungible-tokenBurns fungible tokens (reduces supply)Remove tokens from circulation
hedera-hts-burn-nftBurns an NFT (destroys it)Destroy an NFT permanently
hedera-hts-update-tokenUpdates token propertiesModify token name, symbol, or other properties
hedera-hts-delete-tokenDeletes a tokenRemove a token completely
hedera-hts-pause-tokenPauses a token (prevents transfers)Temporarily freeze all transfers of a token
hedera-hts-unpause-tokenUnpauses a tokenResume transfers for a paused token
hedera-hts-freeze-token-accountFreezes a token for a specific accountPrevent an account from transferring a specific token
hedera-hts-unfreeze-token-accountUnfreezes a token for an accountAllow transfers for a previously frozen account
hedera-hts-grant-kyc-tokenGrants KYC for a token to an accountApprove KYC for an account to use a token
hedera-hts-revoke-kyc-tokenRevokes KYC for a token from an accountRemove KYC approval for an account
hedera-hts-wipe-token-accountWipes tokens from an accountRemove tokens from an account
hedera-hts-token-fee-schedule-updateUpdates token fee scheduleModify fees for a token
hedera-airdrop-tokenAirdrops tokens to multiple recipientsSend tokens to many accounts at once
hedera-claim-airdropClaims an airdropClaim tokens sent to you

HCS Consensus Service Tools

Tool NameDescriptionExample Usage
hedera-create-topicCreates a new HCS topicCreate a topic for message consensus
hedera-delete-topicDeletes an HCS topicRemove a topic you created
hedera-submit-topic-messageSubmits a message to a topicSend a message to be recorded on Hedera
hedera-get-topic-messagesGets messages from a topicRetrieve messages from a topic
hedera-get-topic-infoGets information about a topicRetrieve topic details

File Service Tools

Tool NameDescriptionExample Usage
hedera-create-fileCreates a new file on HederaStore immutable data on Hedera
hedera-append-fileAppends content to an existing fileAdd more data to a file
hedera-update-fileUpdates a file's contentsReplace file contents
hedera-delete-fileDeletes a fileRemove a file

Smart Contract Service Tools

Tool NameDescriptionExample Usage
hedera-create-contractDeploys a smart contractDeploy Solidity contract bytecode
hedera-update-contractUpdates a contractUpdate contract properties
hedera-delete-contractDeletes a contractRemove a deployed contract
hedera-execute-contractExecutes a contract functionCall functions on your deployed contract

Advanced Usage

Using HederaAgentKit Directly

For more programmatic control, you can use HederaAgentKit directly instead of the conversational agent:

import { HederaAgentKit, ServerSigner } from '@hashgraphonline/hedera-agent-kit';
import { Hbar } from '@hashgraph/sdk';

async function useKitDirectly() {
  const signer = new ServerSigner(process.env.HEDERA_ACCOUNT_ID!, process.env.HEDERA_PRIVATE_KEY!, 'testnet');
  const kit = new HederaAgentKit(signer, undefined, 'directExecution'); 
  await kit.initialize();

  // Transfer HBAR
  const transferResult = await kit.accounts().transferHbar({
    transfers: [
      { accountId: '0.0.RECIPIENT', amount: new Hbar(1) },
      { accountId: signer.getAccountId().toString(), amount: new Hbar(-1) }
    ],
    memo: 'Direct kit HBAR transfer'
  }).execute();
  console.log('Transfer result:', transferResult);
  
  // Create a token
  const createTokenResult = await kit.hts().createFungibleToken({
    name: "My Token",
    symbol: "TKN",
    decimals: 2,
    initialSupply: 1000,
    maxSupply: 10000,
    memo: "My first token"
  }).execute();
  console.log('Token created:', createTokenResult);
}

Plugin System

Extend the agent's capabilities with custom plugins:

import { HederaAgentKit, ServerSigner } from '@hashgraphonline/hedera-agent-kit';

async function useCustomPlugin() {
  const signer = new ServerSigner(process.env.HEDERA_ACCOUNT_ID!, process.env.HEDERA_PRIVATE_KEY!, 'testnet');
  
  // Create the kit with plugin configuration
  const kit = new HederaAgentKit(signer, {
    directories: ['./plugins'], // Local plugin directory
    packages: ['@my-org/my-hedera-plugin'], // NPM package plugin
    appConfig: { customSetting: 'value' } // Custom config passed to plugins
  }, 'directExecution');
  
  await kit.initialize();
  
  // Now the kit has all your plugin tools available
  const tools = kit.getAggregatedLangChainTools();
  console.log('Available tools including plugins:', tools.map(t => t.name));
}

API Reference

HederaConversationalAgent Options

interface HederaConversationalAgentOptions {
  // LLM Configuration
  llm?: BaseChatModel; // Provide your own LLM instance
  openAIApiKey?: string; // Or provide just the API key
  
  // Agent Configuration
  userAccountId?: string; // User's account ID for user-centric operations
  operationalMode?: AgentOperationalMode; // 'directExecution' or 'provideBytes'
  scheduleUserTransactionsInBytesMode?: boolean; // Auto-schedule user transactions
  
  // Plugin Configuration
  pluginConfig?: PluginConfig; // Configure plugins
  
  // Debug Options
  verbose?: boolean; // Enable verbose logging
}

Architecture Diagram

graph TD;
    UserInput["User via Application UI"] --> AppCode["Application Logic (e.g., demo.ts)"];
    AppCode -- "Sends user prompt to" --> ConversationalAgent["HederaConversationalAgent"];
    
    subgraph AgentCore ["HederaConversationalAgent Internals"]
        ConversationalAgent -- "Manages" --> LLM["LLM (e.g., GPT-4o)"];
        ConversationalAgent -- "Uses" --> AgentKit["HederaAgentKit Instance"];
        LLM -- "Decides to use a tool" --> Tools[Aggregated LangChain Tools];
    end

    AgentKit -- "Provides tools to" --> Tools;
    AgentKit -- "Configured with" --> Signer["AbstractSigner (ServerSigner/BrowserSigner)"];
    AgentKit -- "Configured with" --> OpModes["Operational Modes"];

    Tools -- "Calls e.g., kit.accounts()" --> AgentKit;
    Tools -- "Invokes e.g., accountBuilder.prepareTransferHbar()" --> ServiceBuilders["Service Builders (AccountBuilder, etc.)"];
    ServiceBuilders -- "Prepares SDK Transaction" --> SDKTx["@hashgraph/sdk Transaction"];

    subgraph ExecutionPath ["Transaction Execution / Byte Generation"]
        ServiceBuilders -- "Based on OpModes & Tool Logic" --> DecisionPoint["Execute or GetBytes?"];
        DecisionPoint -- "Execute (Agent Pays/Signs via ServerSigner)" --> Signer;
        DecisionPoint -- "ProvideBytes (User Pays/Signs)" --> TxBytes["Transaction Bytes"];
        DecisionPoint -- "Schedule (Agent Pays for CreateSchedule)" --> Signer;
        TxBytes -- "Returned to AppCode --> User Wallet" --> UserWallet["User Wallet (HashPack, etc)"];
        Signer -- "Uses SDK Client" --> HederaNetwork["Hedera Network"];
        UserWallet -- "Submits to" --> HederaNetwork;
    end

Local Development

  1. Clone the repo:
git clone https://github.com/hedera-dev/hedera-agent-kit.git
  1. Install dependencies:
cd hedera-agent-kit
npm install
  1. Configure environment variables (e.g., OPENAI_API_KEY, HEDERA_ACCOUNT_ID, HEDERA_PRIVATE_KEY) in a .env file based on the sample.env template.

  2. Test the kit:

npm run test
  1. Run the demo:
npm run demo:langchain

Contributing

We welcome contributions! Please see our CONTRIBUTING.md for details on our process, how to get started, and how to sign your commits under the DCO.

License

Apache 2.0