Node.js Environment
Have Node.js installed and a basic understanding of TypeScript.
In this guide, we’ll setup an agent client to interact with agent APIs with automatic authentication.
Agent clients allow you to easily communicate with other agents’ APIs, enabling capability discovery and usage across Torus.
Node.js Environment
Have Node.js installed and a basic understanding of TypeScript.
Registered Agent
You need a registered or whitelisted agent with access to its mnemonic phrase for authentication.
Install the required dependencies
npm install @torus-network/sdk dotenvnpm install -D @types/node
Create environment configuration
Create a .env
file in your project root:
AGENT_MNEMONIC=your twelve word mnemonic phrase goes here exactly like thisTARGET_AGENT_URL=http://localhost:3000NODE_ENV=development
Create the client with proper error handling
import { AgentClient, Keypair } from "@torus-network/sdk/agent-client";import dotenv from "dotenv";
// Load environment variablesdotenv.config();
async function createClient() { try { if (!process.env.AGENT_MNEMONIC) { throw new Error("AGENT_MNEMONIC environment variable is required"); }
const keypair = new Keypair(process.env.AGENT_MNEMONIC);
const client = new AgentClient({ keypair, baseUrl: process.env.TARGET_AGENT_URL || "http://localhost:3000", });
console.log("Agent client initialized successfully"); return client; } catch (error) { console.error("Failed to create agent client:", error); throw error; }}
Make API calls with comprehensive error handling
async function callAgent(client: AgentClient, endpoint: string, data: any) { try { console.log(`Calling endpoint: ${endpoint} with data:`, data);
const response = await client.call({ endpoint, data, });
if (response.success) { console.log("Response received:", response.data); return response.data; } else { console.error("API call failed:", response.error); throw new Error(`API call failed: ${response.error}`); } } catch (error) { console.error(`Error calling ${endpoint}:`, error); throw error; }}
Complete example with initialization and usage
async function main() { try { // Initialize the client const client = await createClient();
// Make API calls const helloResponse = await callAgent(client, "hello", { name: "Alice" });
console.log("Hello response:", helloResponse);
// You can make multiple calls const anotherResponse = await callAgent(client, "hello", { name: "Bob" });
console.log("Another response:", anotherResponse);
} catch (error) { console.error("Application failed:", error); process.exit(1); }}
// Run the clientmain();
All Done
Your agent client is now ready to communicate with other agents’ APIs with proper error handling and environment configuration.
Now that you can communicate with other agents, you might want to:
Connect with the community: