
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
swarmjs-node
Advanced tools
A TypeScript library interfacing with OpenAI's Swarm API for building intelligent agent-driven applications.
SwarmJS-Node is a TypeScript library implementation that o1-mini generated from OpenAI's Swarm repository.
Ensure you have Node.js installed. Then, install swarmjs-node via npm:
npm install swarmjs-node
Or using pnpm:
pnpm add swarmjs-node
Below is a simple example demonstrating how to initialize the Swarm client, define agents with custom functions, and run a demo loop.
Clone the Repository:
git clone https://github.com/ColeMurray/swarmjs.git
cd swarmjs
Install Dependencies:
The project uses pnpm. If you don't have it installed, you can install it globally:
npm install -g pnpm
Then, install the project dependencies:
pnpm install
Build the Project:
Compile the TypeScript code to JavaScript:
pnpm run build
Configure Environment Variables:
Create a .env file in the root directory and add your OpenAI API key:
OPENAI_API_KEY=your_openai_api_key_here
Note: Ensure that .env is listed in your .gitignore to prevent accidental commits of sensitive information.
An example script is provided in the examples directory. Here's how to set it up and run it.
examples/main.ts// Filename: examples/main.ts
import { Agent, AgentFunction } from '../swarm';
import { runDemoLoop } from '../swarm/repl';
import * as dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
// Define an addition function
const addFunction: AgentFunction = {
name: 'add',
func: ({ a, b }) => {
return (a + b).toString();
},
descriptor: {
name: 'add',
description: 'Adds two numbers together.',
parameters: {
a: { type: 'number', required: true, description: 'The first number to add.' },
b: { type: 'number', required: true, description: 'The second number to add.' },
},
},
};
// Define a subtraction function
const subFunction: AgentFunction = {
name: 'sub',
func: ({ a, b }) => {
return (a - b).toString();
},
descriptor: {
name: 'sub',
description: 'Subtracts two numbers.',
parameters: {
a: { type: 'number', required: true, description: 'The first number.' },
b: { type: 'number', required: true, description: 'The second number.' },
},
},
};
// Define a function to transfer to another agent
const transferToHaikuAgent: AgentFunction = {
name: 'transfer_to_haiku_agent',
func: () => {
return agentB;
},
descriptor: {
name: 'transfer_to_haiku_agent',
description: 'Transfers the conversation to the Haiku Agent.',
parameters: {},
},
};
// Initialize a Haiku Agent
const agentB = new Agent({
name: 'HaikuAgent',
model: 'gpt-4o-mini',
instructions: 'You only respond in haikus.',
});
// Initialize the Helper Agent with functions
const agent = new Agent({
name: 'HelperAgent',
model: 'gpt-4o-mini',
instructions: 'You are a helpful assistant.',
functions: [transferToHaikuAgent, addFunction, subFunction],
});
// Run the demo loop
runDemoLoop(agent, undefined, true, true).catch(error => {
console.error('Error running demo loop:', error);
});
Ensure the Project is Built:
pnpm run build
Run the Example Script:
pnpm run start:example
Expected Output:
Starting Swarm CLI 🐝
User: Hello
HelperAgent: Hello! How can I assist you today?
User: Add 5 and 3
HelperAgent: The result of adding 5 and 3 is 8.
User: Subtract 10 from 15
HelperAgent: The result of subtracting 10 from 15 is 5.
User: Exit
Exiting Swarm CLI.
Note: The actual responses may vary based on the implementation and interactions with the OpenAI API.
For more comprehensive examples and advanced use cases, refer to the examples directory in the repository. You can modify these examples to suit your specific needs or to explore additional functionalities provided by SwarmJS-Node.
import { Swarm, Agent, AgentFunction } from 'swarmjs-node';
Agent functions extend the capabilities of your agents by allowing them to perform specific tasks.
const multiplyFunction: AgentFunction = {
name: 'multiply',
func: ({ a, b }) => {
return (a * b).toString();
},
descriptor: {
name: 'multiply',
description: 'Multiplies two numbers.',
parameters: {
a: { type: 'number', required: true, description: 'The first number.' },
b: { type: 'number', required: true, description: 'The second number.' },
},
},
};
The runDemoLoop function initializes the interactive CLI for engaging with the Swarm API.
import { runDemoLoop } from 'swarmjs-node';
const agent = new Agent({
name: 'CalculatorAgent',
model: 'gpt-4o-mini',
instructions: 'You are a calculator agent that can perform basic arithmetic operations.',
functions: [addFunction, subFunction, multiplyFunction],
});
runDemoLoop(agent, undefined, true, true).catch(error => {
console.error('Error running demo loop:', error);
});
Comprehensive API documentation is available here. This includes detailed descriptions of classes, methods, and interfaces provided by SwarmJS-Node.
.env file or API keys to version control. Use environment variables to manage sensitive information.SwarmJS-Node includes a testing setup using Jest. To run the tests:
Install Development Dependencies:
pnpm install
Run Tests:
pnpm run test
Run Tests with Coverage:
pnpm run test -- --coverage
Ensure code quality and consistency by running ESLint.
Check for Linting Errors:
pnpm run lint
Automatically Fix Linting Errors:
pnpm run lint:fix
Compile TypeScript source files to JavaScript:
pnpm run build
Define Agent Functions:
Create new AgentFunction objects with appropriate name, func, and descriptor.
Update Agents:
Initialize or update Agent instances with the new functions.
Run and Test:
Use the example scripts or create new ones in the examples directory to test the new features.
Regularly run linting and testing to maintain code quality.
pnpm run lint
pnpm run test
Contributions are welcome! Please follow these steps to contribute:
Fork the Repository:
Click the "Fork" button at the top right of the repository page.
Clone Your Fork:
git clone https://github.com/ColeMurray/swarmjs.git
cd swarmjs-node
Create a New Branch:
git checkout -b feature/YourFeatureName
Make Your Changes:
Implement your feature or bug fix.
Commit Your Changes:
git commit -m "Add feature: YourFeatureName"
Push to Your Fork:
git push origin feature/YourFeatureName
Create a Pull Request:
Navigate to the original repository and click "Compare & pull request."
Please ensure that your contributions adhere to the following guidelines:
For more details, refer to the CONTRIBUTING.md file.
This project is licensed under the MIT License. You are free to use, modify, and distribute this software in accordance with the license terms.
For any inquiries or support, please open an issue on the GitHub repository.
Happy Coding! 🚀
SwarmJS provides rich streaming capabilities with typed events to make it easier to build real-time applications:
// Import stream event types
import {
StreamEvent,
RawResponsesStreamEvent,
RunItemStreamEvent
} from 'swarmjs/stream_events';
import { ItemHelpers } from 'swarmjs/items';
// Initialize and configure your agent...
// Run with streaming enabled
const stream = await swarm.run({
agent,
messages: [{ role: 'user', content: 'Tell me a joke' }],
stream: true
});
// Process the stream
for await (const event of stream) {
switch (event.type) {
case 'raw_response_event':
// Handle token-by-token updates
const content = event.data.choices[0]?.delta?.content || '';
process.stdout.write(content);
break;
case 'run_item_stream_event':
if (event.name === 'message_output_created') {
// Handle completed message
console.log('Message complete:',
ItemHelpers.extractTextContent(event.item.raw_item)
);
}
else if (event.name === 'tool_called') {
// Handle tool call
console.log('Tool called:', event.item.raw_item.function.name);
}
break;
case 'response_complete_event':
// Handle completion of the run
console.log('Run complete:', event.response);
break;
}
}
RunItems represent different components of a run:
You can access these items both during streaming and in the final response:
// After a non-streaming run
const response = await swarm.run({ agent, messages, stream: false });
// Access specific item types
const messageItems = response.getMessageItems();
const toolCallItems = response.getToolCallItems();
const toolOutputItems = response.getToolOutputItems();
// Or access all items
console.log(`Total items: ${response.items.length}`);
Check out the examples directory for more advanced usage patterns:
FAQs
A TypeScript library interfacing with OpenAI's Swarm API for building intelligent agent-driven applications.
The npm package swarmjs-node receives a total of 0 weekly downloads. As such, swarmjs-node popularity was classified as not popular.
We found that swarmjs-node demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.