Getting Started with Conversational Agent
This chapter gets you from zero to a working agent in minutes. You’ll install the library, set three environment variables, run one snippet, and send your first message.
TL;DR
- Install the package, set 3 env vars, and run one snippet.
- Defaults:
network=testnet,llmProvider=openai,openAIModelName=gpt-4o.- Two modes:
autonomous(executes) vsreturnBytes(you sign & submit).- Optional MCP servers add filesystem/github/database tools.
PrerequisitesDirect link to Prerequisites
- Node.js 18+ and npm/pnpm
- Hedera testnet account credentials
- OpenAI API key (or Anthropic/OpenRouter — use
openAIApiKeyfor all) - Optional: Terminal for CLI interface
InstallationDirect link to Installation
# Using npm
npm install @hashgraphonline/conversational-agent
# Using pnpm
pnpm add @hashgraphonline/conversational-agent
# Required dependencies
npm install @hashgraph/sdk @hashgraphonline/standards-sdk
Basic SetupDirect link to Basic Setup
Diagram: What happens when I send a message?Direct link to Diagram: What happens when I send a message?
1. Environment ConfigurationDirect link to 1. Environment Configuration
Create a .env file with your credentials:
# Hedera Configuration
HEDERA_NETWORK=testnet
HEDERA_ACCOUNT_ID=0.0.YOUR_ACCOUNT_ID
HEDERA_PRIVATE_KEY=YOUR_PRIVATE_KEY
# OpenAI/Anthropic/OpenRouter Configuration
# Use this key for all providers; the code option is `openAIApiKey`.
OPENAI_API_KEY=YOUR_PROVIDER_API_KEY
2. Initialize the AgentDirect link to 2. Initialize the Agent
import { ConversationalAgent } from '@hashgraphonline/conversational-agent';
import dotenv from 'dotenv';
dotenv.config();
// Create the conversational agent
const agent = new ConversationalAgent({
accountId: process.env.HEDERA_ACCOUNT_ID!,
privateKey: process.env.HEDERA_PRIVATE_KEY!,
network: 'testnet',
openAIApiKey: process.env.OPENAI_API_KEY!,
// LLM provider and model (OpenAI or Anthropic)
llmProvider: 'openai', // or 'anthropic'
openAIModelName: 'gpt-4o',
// Optional: enable entity memory and configure limits
entityMemoryEnabled: true,
entityMemoryConfig: { maxTokens: 6000, reserveTokens: 1000 },
// Optional: dedicated provider/model for entity extraction/resolution
entityMemoryProvider: 'openai', // or 'anthropic'
entityMemoryModelName: 'gpt-4o-mini',
verbose: true
});
// Initialize the agent
await agent.initialize();
// Using OpenRouter instead of OpenAI/Anthropic
const openRouterAgent = new ConversationalAgent({
accountId: process.env.HEDERA_ACCOUNT_ID!,
privateKey: process.env.HEDERA_PRIVATE_KEY!,
network: 'testnet',
// Either set `openRouterApiKey` or reuse OPENAI_API_KEY via `openAIApiKey`
openAIApiKey: process.env.OPENROUTER_API_KEY!,
openRouterApiKey: process.env.OPENROUTER_API_KEY!,
llmProvider: 'openrouter',
// Prefer vendor-prefixed models for routing (avoids candidates requirement)
openAIModelName: 'openai/gpt-4o-mini',
});
await openRouterAgent.initialize();
Using the CLIDirect link to Using the CLI
The easiest way to get started is with the interactive CLI:
# If installed globally
conversational-agent
# Or using pnpm from the project
pnpm cli
# With environment variables
export HEDERA_ACCOUNT_ID=0.0.12345
export HEDERA_PRIVATE_KEY=your-private-key
export OPENAI_API_KEY=sk-your-key
pnpm cli
# With command line arguments
pnpm cli -- --account-id=0.0.12345 --private-key=... --openai-api-key=sk-...
The CLI provides:
- 🎨 Beautiful terminal interface
- 💬 Interactive chat with your agent
- 🔐 Secure credential input
- 📊 Real-time transaction feedback
- 🔌 MCP server configuration and management
Where the CLI stores MCP config
- Set
CONVERSATIONAL_AGENT_ROOTto control where the CLI writesmcp-config.json. - If not set, the CLI computes a project root relative to the CLI package; to avoid surprises, export
CONVERSATIONAL_AGENT_ROOTto your repo path. Example from this repo root:The file will then be written toexport CONVERSATIONAL_AGENT_ROOT="$(pwd)/conversational-agent"conversational-agent/mcp-config.json.
Your First Agent OperationsDirect link to Your First Agent Operations
HCS-10: Register an AI AgentDirect link to HCS-10: Register an AI Agent
const response = await agent.processMessage(
"Register me as an AI assistant named HelperBot with text generation capabilities and ai tag"
);
console.log(response.response);
// Output: Successfully registered agent HelperBot with account 0.0.123456
HCS-10: Connect to Another AgentDirect link to HCS-10: Connect to Another Agent
// Find other agents
const findResponse = await agent.processMessage(
"Find all agents with ai tag"
);
// Connect to an agent
const connectResponse = await agent.processMessage(
"Connect to agent 0.0.789012"
);
// Send a message
const messageResponse = await agent.processMessage(
"Send 'Hello from HelperBot!' to connection 1"
);
HCS-2: Create a RegistryDirect link to HCS-2: Create a Registry
const response = await agent.processMessage(
"Create a new HCS-2 topic registry"
);
console.log(response.response);
// Output: Registry created with topic ID 0.0.123457
Inscription: Store ContentDirect link to Inscription: Store Content
// Inscribe from URL
const inscribeResponse = await agent.processMessage(
"Inscribe the content from https://example.com/data.json"
);
// Create a Hashinal NFT
const nftResponse = await agent.processMessage(
"Create a Hashinal NFT with name 'My First NFT' and description 'Created with Conversational Agent'"
);
Understanding the ArchitectureDirect link to Understanding the Architecture
The agent manages three built-in plugins:
// Access plugins directly if needed
const hcs10Plugin = agent.hcs10Plugin;
const hcs2Plugin = agent.hcs2Plugin;
const inscribePlugin = agent.inscribePlugin;
// Access the underlying Hedera agent
const hederaAgent = agent.getConversationalAgent();
// Access state manager
const stateManager = agent.getStateManager();
State ManagementDirect link to State Management
The agent automatically manages state through OpenConvaiState:
// State is automatically persisted to .env file
// After registering an agent:
// HELPERBOT_ACCOUNT_ID=0.0.123456
// HELPERBOT_PRIVATE_KEY=...
// HELPERBOT_INBOUND_TOPIC_ID=0.0.123457
// HELPERBOT_OUTBOUND_TOPIC_ID=0.0.123458
// The state manager tracks:
// - Registered agents
// - Active connections
// - Registry topics
// - Inscription records
Common OperationsDirect link to Common Operations
HCS-10 Agent CommunicationDirect link to HCS-10 Agent Communication
// List your connections
"List my active connections"
// Check for messages
"Check messages from agent 0.0.789012"
// Accept connection requests
"Show pending connection requests"
"Accept connection request 1"
HCS-2 Registry ManagementDirect link to HCS-2 Registry Management
// Register an entry
"Register topic 0.0.98765 in registry 0.0.123456"
// Query entries
"Query all registered topics from registry 0.0.123456"
// Update an entry
"Register updated version of topic 0.0.98765 in registry 0.0.123456"
Content InscriptionDirect link to Content Inscription
// Inscribe a file
"Inscribe the file at /path/to/document.pdf"
// Retrieve inscription
"Get inscription details for job ID abc123"
Error HandlingDirect link to Error Handling
Always wrap operations in try-catch blocks:
try {
const response = await agent.processMessage(
"Register me as an agent named TestBot"
);
console.log('Success:', response.response);
} catch (error) {
console.error('Error:', error.message);
// The agent provides helpful error messages
if (error.message.includes('already registered')) {
console.log('Agent already exists with that name');
}
}
Operational ModesDirect link to Operational Modes
Autonomous Mode (Default)Direct link to Autonomous Mode (Default)
Agent executes transactions directly:
const agent = new ConversationalAgent({
// ... other config
operationalMode: 'autonomous'
});
ReturnBytes ModeDirect link to ReturnBytes Mode
Returns transaction bytes for external signing:
const agent = new ConversationalAgent({
// ... other config
operationalMode: 'returnBytes'
});
const response = await agent.processMessage(
"Create a topic"
);
// If the underlying tool supports bytes, `response.transactionBytes` will be present.
// Some operations may execute directly even in bytes mode (see tool docs).
Diagram: Mode selectionDirect link to Diagram: Mode selection
Custom PluginsDirect link to Custom Plugins
You can extend the agent with custom plugins:
import { MyCustomPlugin } from './my-plugin';
const agent = new ConversationalAgent({
// ... other config
additionalPlugins: [new MyCustomPlugin()]
});
See the Plugin Development Guide for details.
Using MCP ServersDirect link to Using MCP Servers
MCP (Model Context Protocol) servers extend your agent's capabilities with external tools and services.
Basic MCP SetupDirect link to Basic MCP Setup
import { ConversationalAgent, MCPServers } from '@hashgraphonline/conversational-agent';
// Create agent with filesystem access
const agent = new ConversationalAgent({
accountId: process.env.HEDERA_ACCOUNT_ID!,
privateKey: process.env.HEDERA_PRIVATE_KEY!,
network: 'testnet',
openAIApiKey: process.env.OPENAI_API_KEY!,
mcpServers: [
MCPServers.filesystem('/home/user/documents')
]
});
await agent.initialize();
// Agent can now read and write files
const response = await agent.processMessage(
"Read the project README.md file and summarize it"
);
CLI MCP ConfigurationDirect link to CLI MCP Configuration
The CLI allows you to configure MCP servers interactively:
- Run the CLI:
pnpm cli - Select "MCP Servers" from the main menu
- Enable the filesystem server and set the path
- Add custom MCP servers as needed
Your MCP configuration is saved to the directory set by CONVERSATIONAL_AGENT_ROOT (recommended). If unset, the CLI computes a project root relative to itself; set the env var to avoid surprises.
Common MCP Use CasesDirect link to Common MCP Use Cases
// File operations
"Read all .txt files in the current directory"
"Create a new file called notes.md with my meeting summary"
// With GitHub integration
"Check for open issues in my repository"
"Create a pull request with the changes we discussed"
// With database access
"Query the users table and show me recent signups"
"Update the status field for order ID 12345"
Next StepsDirect link to Next Steps
- Up next: Available Tools — what you can ask the agent to do
- Try example scripts - Real-world usage examples
- Read about HCS-10 Standard - Agent communication protocol
- Learn about HCS-2 Standard - Registry management
- Build custom plugins