chiliz-agent-sdk
v0.1.1
Published
An AI agent SDK for Chiliz blockchain
Downloads
114
Maintainers
Readme
Chiliz Agent Sdk
An AI agent SDK for the Chiliz blockchain that enables interaction with Chiliz network through natural language prompts
Features
- 🤖 AI-Powered Blockchain Interactions: Execute blockchain operations using natural language prompts
- 🔒 Built-in Security: AI firewall protection against malicious prompts and llm jailbreaks
- 💰 CHZ Operations: Transfer CHZ tokens and check balances
- 🪙 ERC-20 Support: Transfer, burn, and check balances of ERC-20 tokens
- 🌐 Multiple AI Models: Support for OpenAI and Anthropic models
- 🛡️ Security-First: Pattern matching and LLM-based sanitization to protect sensitive operations
- 🎭 Customizable Personalities: Define custom agent personalities through system prompts
Installation
npm install chiliz-agent-sdkQuick Start
Basic Setup
import { ChilizAgent } from 'chiliz-agent-sdk';
const agent = new ChilizAgent({
privateKey: 'your-private-key',
rpcUrl: 'https://spicy-rpc.chiliz.com', // Chiliz mainnet or testnet RPC
model: 'gpt-5', // or 'claude-3-sonnet'
openAiApiKey: 'your-openai-api-key', // Required for OpenAI models
anthropicApiKey: 'your-anthropic-api-key', // Required for Anthropic models
personalityPrompt: 'You are a helpful assistant for Chiliz blockchain operations...' // Optional: custom agent personality
});Natural Language Execution
// Execute blockchain operations using natural language
const response = await agent.execute(
"Transfer 0.1 CHZ to 0x742d35Cc6b8C9532E78c12A5C3295c2d6F1A8F3e"
);
console.log(response.output);Conversation Memory (Sessions)
The agent maintains per-session conversational memory using LangChain's RunnableWithMessageHistory. Your prompt template already includes {chat_history}, so prior messages in a session are automatically provided to the model and updated after each turn.
Key points:
- Memory is keyed by
sessionIdyou pass toexecute. - If you don't pass a
sessionId, the agent uses a default per-instance session ID generated at construction. - Memory is in-process (not persisted across restarts) and isolated per ChilizAgent instance use external DB for persistance.
Basic usage with the default session:
// Uses the agent's default session (auto-generated). Subsequent calls share memory.
await agent.execute('My name is Pri. Please remember it.');
const r = await agent.execute('What is my name?');
console.log(r.output); // Likely references "Pri"Per-user sessions (recommended for multi-user apps):
const sessionId = `user:${userId}`;
await agent.execute('Store my preferred token as CHZ.', { sessionId });
const res = await agent.execute('What is my preferred token?', { sessionId });
console.log(res.output); // Should recall "CHZ"Isolated sessions example:
await agent.execute('Remember: my color is blue.', { sessionId: 'A' });
const a = await agent.execute('What is my color?', { sessionId: 'A' }); // blue
const b = await agent.execute('What is my color?', { sessionId: 'B' }); // unknown
console.log(a.output, b.output);Resetting memory:
- Start using a new
sessionId, or - Create a new ChilizAgent instance.
Persistence options:
- By default, memory uses an in-process Map and
InMemoryChatMessageHistory. - To persist across restarts or scale horizontally, replace it with a store like Redis by swapping the message history implementation.
API Reference
ChilizAgent Class
Constructor
new ChilizAgent(config: ChilizAgentConfig)Parameters:
config.privateKey(string): Wallet private key for blockchain operationsconfig.rpcUrl(string): Chiliz network RPC URLconfig.model(string): AI model to use ('gpt-4', 'gpt-3.5-turbo', 'claude-3-sonnet', etc.)config.openAiApiKey(string, optional): OpenAI API key (required for OpenAI models)config.anthropicApiKey(string, optional): Anthropic API key (required for Anthropic models)config.personalityPrompt(string, optional): Custom system prompt to define the agent's personality and behavior
Methods
execute(input: string, options?: { sessionId?: string })
Execute blockchain operations using natural language commands.
Parameters:
input(string): Natural language commandoptions.sessionId(string, optional): Identifier for a conversation session. When provided, memory is scoped to this ID. When omitted, a default per-agent session is used.
Returns:
- An object containing
input,chat_history, andoutput.
Customizing Agent Personalities
You can customize the agent's personality by providing a custom system prompt during initialization. This allows you to control the agent's tone, style, and behavior to suit your application needs.
// Creating an agent with a friendly, enthusiastic personality
const friendlyAgent = new ChilizAgent({
privateKey: process.env.PRIVATE_KEY!,
rpcUrl: process.env.CHILIZ_RPC_URL!,
model: 'gpt-4',
openAiApiKey: process.env.OPENAI_API_KEY,
personalityPrompt: `You are a friendly and enthusiastic AI assistant on the Chiliz blockchain.
You LOVE to use exclamation marks and speak with excitement!
Always use emojis like 🚀, 💰, and 🎉 in your responses!
When a transaction is successful, respond with:
AMAZING NEWS! 🎉 Your transaction was successful! The hash is: 0x1234...
When a transaction fails, respond with:
Oh no! 😢 The transaction failed. Let me explain why...`
});
// Creating an agent with a formal, professional personality
const formalAgent = new ChilizAgent({
privateKey: process.env.PRIVATE_KEY!,
rpcUrl: process.env.CHILIZ_RPC_URL!,
model: 'gpt-4',
openAiApiKey: process.env.OPENAI_API_KEY,
personalityPrompt: `You are a professional AI assistant specialized in Chiliz blockchain operations.
Always communicate in a formal, business-like manner using proper technical terms.
When a transaction is successful, respond with:
The transaction has been successfully processed. Transaction hash: 0x1234...
When a transaction fails, respond with:
The transaction could not be processed. The following error occurred: ...`
});Best Practices for Custom Personalities
- Maintain Core Functionality: Ensure your custom prompt preserves the agent's ability to execute blockchain operations.
- Include Response Formats: Specify how transaction results should be formatted.
- Balance Personality with Clarity: Make sure the agent's responses remain clear and informative even with the added personality elements.
- Test Thoroughly: Verify that custom personalities don't interfere with the agent's core functionality.
Security Features
AI Firewall
The SDK includes built-in security features to protect against malicious inputs and llm jailbreaks:
- Pattern Matching: Detects and blocks prompts that might request private keys or sensitive information
- LLM Sanitization: Uses AI models to analyze and sanitize prompts before execution
- Automatic Protection: All natural language inputs are automatically processed through the firewall
Best Practices
- Never include private keys in plain text in your code
- Use environment variables for sensitive configuration
- Test operations on testnet before mainnet deployment
- Validate all user inputs before processing
Environment Setup
Create a .env file in your project root:
PRIVATE_KEY=your-wallet-private-key
CHILIZ_RPC_URL=https://spicy-rpc.chiliz.com
OPENAI_API_KEY=your-openai-api-key
ANTHROPIC_API_KEY=your-anthropic-api-keyNetwork Configuration
Mainnet
RPC URL: https://spicy-rpc.chiliz.com
Chain ID: 88888Testnet (Chiliz Spicy)
RPC URL: https://spicy-rpc.chiliz.com/
Chain ID: 88882Examples
Example 1: Basic Token Operations
import { ChilizAgent } from 'chiliz-agent-sdk';
import { config } from 'dotenv';
config(); // Load environment variables
const agent = new ChilizAgent({
privateKey: process.env.PRIVATE_KEY!,
rpcUrl: process.env.CHILIZ_RPC_URL!,
model: 'gpt-4',
openAiApiKey: process.env.OPENAI_API_KEY
});
async function main() {
// Transfer tokens using natural language
const result = await agent.execute(
"Send 0.01 CHZ to address 0x742d35Cc6b8C9532E78c12A5C3295c2d6F1A8F3e"
);
console.log(result.output);
}
main().catch(console.error);Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the ISC License.
