openai-swarmjs
Version:
Agentic framework inspired from OpenAI's swarm framework for TS, JS
92 lines (91 loc) • 3.39 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runExample = runExample;
require("dotenv/config");
const readline_1 = require("readline");
const chalk_1 = __importDefault(require("chalk"));
const swarm_1 = require("../core/swarm");
const openai_1 = __importDefault(require("openai"));
const DEBUG = process.env.DEBUG === 'true';
const rl = (0, readline_1.createInterface)({
input: process.stdin,
output: process.stdout,
});
async function processAndPrintStreamingResponse(response) {
let content = '';
let lastSender = '';
for await (const chunk of response) {
if ('sender' in chunk) {
lastSender = chunk.sender;
}
if ('content' in chunk && chunk.content !== null) {
if (!content && lastSender) {
process.stdout.write(chalk_1.default.blue(`${lastSender}: `));
lastSender = '';
}
process.stdout.write(chunk.content);
content += chunk.content;
}
if ('toolCalls' in chunk && chunk.toolCalls) {
for (const toolCall of chunk.toolCalls) {
const name = toolCall.function?.name;
if (!name)
continue;
console.log(chalk_1.default.magenta(`\n${lastSender}: ${name}()`));
}
}
if ('delim' in chunk && chunk.delim === 'end' && content) {
console.log();
content = '';
}
}
}
async function runExample(name, getAgent) {
const client = new openai_1.default({
apiKey: process.env.OPENAI_API_KEY,
});
const swarm = new swarm_1.Swarm(client);
console.log(chalk_1.default.green(`Starting SwarmJS CLI with ${name} 🐝`));
console.log(chalk_1.default.gray('Type your messages and press Enter. Press Ctrl+C to exit.\n'));
const messages = [];
const agent = await Promise.resolve(getAgent());
while (true) {
const userInput = await new Promise((resolve) => {
rl.question(chalk_1.default.gray('User: '), resolve);
});
if (userInput.trim().includes('quit!')) {
console.log(chalk_1.default.yellow('\nGoodbye! 👋'));
rl.close();
process.exit(0);
}
messages.push({ role: 'user', content: userInput });
try {
const response = await swarm.run(agent, messages, {}, // context variables
null, // model override
true, // stream
DEBUG // debug
);
if (Symbol.asyncIterator in Object(response)) {
await processAndPrintStreamingResponse(response);
}
}
catch (error) {
console.error(chalk_1.default.red('Error during execution:'), error);
if (error instanceof Error) {
console.error(chalk_1.default.red('Error details:'), error.message);
}
}
}
}
if (require.main === module) {
console.log(chalk_1.default.yellow('Please run a specific example file instead of this generic REPL.'));
process.exit(1);
}
process.on('SIGINT', () => {
console.log(chalk_1.default.yellow('\nGoodbye! 👋'));
rl.close();
process.exit(0);
});
;