JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 14
  • Score
    100M100P100Q47739F
  • License MIT

A versatile JavaScript library for designing and managing intelligent agents capable of interacting with AI-driven chat models, leveraging OpenAI's GPT for dynamic conversations and task automation.

Package Exports

  • agents-js
  • agents-js/tools

Readme

agents-js

A powerful JavaScript library for building and orchestrating AI agents with OpenAI's GPT models.

Installation

npm install agents-js

Features

  • 🤖 Multi-Agent Orchestration - Coordinate multiple specialized agents
  • 🔄 Automatic Agent Transfers - Seamless handoffs between agents
  • 🛠️ Pre-built Tools - Web search (Serper, Firecrawl), calculations, time utilities
  • 📊 Token Tracking - Monitor token usage across conversations
  • 🔐 Session Management - Persistent conversation state
  • Streaming Support - Real-time response generation
  • 🎯 Lifecycle Hooks - beforeModel, afterModel, beforeTool, afterTool
  • Tool Confirmation - Human-in-the-loop for sensitive operations
  • 📝 TypeScript Support - Full type definitions included
  • 📋 Detailed Logging - Track agent transfers and tool calls

Quick Start

Basic Agent

require("dotenv").config();
const { Agent, AgentController } = require("agents-js");
const { calculate, getCurrentTime } = require("agents-js/tools");
const OpenAI = require("openai");

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const controller = new AgentController(client);

const agent = new Agent({
  name: "Assistant",
  model: "gpt-4o-mini",
  instructions: "You are a helpful assistant.",
  functions: [calculate, getCurrentTime],
});

const response = await controller.run(agent, [
  { role: "user", content: "What is 25 * 4?" },
]);

console.log(response.messages[response.messages.length - 1].content);

Multi-Agent System with Sub-Agents

require("dotenv").config();
const { Agent, AgentController } = require("agents-js");
const { serperSearch, calculate, getCurrentTime } = require("agents-js/tools");
const OpenAI = require("openai");

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// Create specialized agents
const weatherAgent = new Agent({
  name: "WeatherSpecialist",
  model: "gpt-4o-mini",
  instructions: "You are a weather expert. Use serperSearch to find weather information.",
  functions: [serperSearch],
});

const mathAgent = new Agent({
  name: "MathSpecialist",
  model: "gpt-4o-mini",
  instructions: "You are a math expert. Use calculate for all calculations.",
  functions: [calculate],
});

const timeAgent = new Agent({
  name: "TimeSpecialist",
  model: "gpt-4o-mini",
  instructions: "You are a time expert. Use getCurrentTime to tell the current time.",
  functions: [getCurrentTime],
});

// Create main coordinator agent with sub-agents
const mainAgent = new Agent({
  name: "Assistant",
  model: "gpt-4o-mini",
  instructions: `You are a helpful coordinator. Route requests to specialists:
  - Weather questions → WeatherSpecialist
  - Math problems → MathSpecialist  
  - Time questions → TimeSpecialist`,
  subAgents: [weatherAgent, mathAgent, timeAgent],
});

const controller = new AgentController(client, {
  apiKeys: {
    serper: process.env.SERPER_API_KEY,
  },
});

// The controller will automatically transfer between agents
const response = await controller.run(mainAgent, [
  { role: "user", content: "What's the weather in Tokyo?" },
]);

console.log(response.messages[response.messages.length - 1].content);

// Export for playground
module.exports = { mainAgent, weatherAgent, mathAgent, timeAgent };

Pre-built Tools

agents-js comes with several pre-built tools:

Web Search & Scraping

const { serperSearch, firecrawlSearch, firecrawlScrape } = require("agents-js/tools");

// Serper.dev web search (requires SERPER_API_KEY)
// Automatically falls back to Firecrawl if Serper key is missing

// Firecrawl web search (requires FIRECRAWL_API_KEY)
// Firecrawl web scraping

Calculations & Time

const { calculate, getCurrentTime, getTimestamp, formatDate } = require("agents-js/tools");

Advanced Features

Lifecycle Hooks

const agent = new Agent({
  name: "Assistant",
  model: "gpt-4o-mini",
  instructions: "You are helpful.",
  functions: [calculate],
  beforeModel: async (messages, contextVariables) => {
    console.log("📤 Sending to model:", messages.length, "messages");
  },
  afterModel: async (response, contextVariables) => {
    console.log("📥 Received from model");
  },
  beforeTool: async (toolName, args, contextVariables) => {
    console.log("🔧 Calling tool:", toolName);
  },
  afterTool: async (toolName, args, result, contextVariables) => {
    console.log("✅ Tool completed:", toolName);
  },
});

Session Management

const { Session } = require("agents-js");

const session = new Session();

// Store conversation state
session.set("user_name", "John");
session.set("preferences", { theme: "dark" });

// Retrieve state
const userName = session.get("user_name");

// Pass session in context
const response = await controller.run(agent, messages, {
  session: session,
});

Tool Confirmation (Human-in-the-Loop)

const { ToolConfirmation } = require("agents-js");

function dangerousOperation({ action }) {
  // Sensitive operation
  return `Executed: ${action}`;
}

const agent = new Agent({
  name: "Assistant",
  model: "gpt-4o-mini",
  instructions: "You are helpful.",
  functions: [
    new ToolConfirmation({
      tool: dangerousOperation,
      message: "This action is sensitive. Confirm?",
      autoConfirm: false,
    }),
  ],
});

const controller = new AgentController(client, {
  confirmationHandler: async (toolName, args, message) => {
    console.log(`Confirm ${toolName}?`, args);
    return true; // or false to cancel
  },
});

Disable Logging

const controller = new AgentController(client, {
  enableLogging: false, // Disable automatic logging
});

Testing with Playground

Test your agents interactively with the playground:

# Install playground globally
npm install -g agents-playground

# Run with your agents file
npx agents-playground ./my-agents.js

The playground provides:

  • 🎨 Beautiful chat interface
  • 📊 Real-time token tracking
  • 🔄 Agent transfer visualization
  • 🔧 Environment variable management
  • 📝 Detailed execution logs

Examples

Check out the examples directory for complete working examples:

Running Examples

# Clone the repository
git clone https://github.com/vgulerianb/agents-js.git
cd agents-js

# Install dependencies
npm install
cd packages/agents-js
npm link

# Set up environment variables
cp .env.example .env
# Edit .env with your API keys

# Run an example
node examples/basic-agent.js

# Or test with playground
npx agents-playground examples/multi-agent-system.js

API Reference

Agent

new Agent({
  name: string;
  model: string;
  instructions: string | ((context) => string);
  functions?: Function[];
  subAgents?: Agent[];
  parallelToolCalls?: boolean;
  beforeModel?: (messages, context) => Promise<void>;
  afterModel?: (response, context) => Promise<void>;
  beforeTool?: (toolName, args, context) => Promise<boolean | void>;
  afterTool?: (toolName, args, result, context) => Promise<void>;
});

AgentController

new AgentController(client: OpenAI, options?: {
  confirmationHandler?: (toolName, args, message) => Promise<boolean>;
  apiKeys?: Record<string, string>;
  enableLogging?: boolean;
});

Result

new Result({
  value: string;
  agent?: Agent;
  agentName?: string;
  contextVariables?: Record<string, any>;
});

Environment Variables

Create a .env file:

# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key
OPENAI_BASE_URL=https://api.openai.com/v1  # Optional

# External Tool API Keys
SERPER_API_KEY=your_serper_api_key  # Optional, for web search
FIRECRAWL_API_KEY=your_firecrawl_api_key  # Optional, for web scraping

TypeScript Support

Full TypeScript definitions are included:

import { Agent, AgentController, Result, Session } from "agents-js";
import { serperSearch, calculate } from "agents-js/tools";

License

MIT © Vikrant Guleria

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.