import {
AgentRuntime,
createMessageMemory,
stringToUuid,
type Character,
type UUID,
} from "@elizaos/core";
import { openaiPlugin } from "@elizaos/plugin-openai";
import { plugin as sqlPlugin } from "@elizaos/plugin-sql";
import { v4 as uuidv4 } from "uuid";
// Define specialized agent characters
const coordinatorCharacter: Character = {
name: "Coordinator",
bio: "Orchestrates tasks between specialized agents",
system: `You are a coordinator agent. Your role is to:
1. Understand user requests
2. Determine which specialized agents to involve
3. Delegate tasks appropriately
4. Aggregate responses into coherent answers
Available agents:
- Researcher: Gathers and analyzes information
- Writer: Creates well-structured content
- Critic: Reviews and provides constructive feedback`,
};
const researcherCharacter: Character = {
name: "Researcher",
bio: "Specialized in information gathering and analysis",
system: `You are a research specialist. You:
- Gather relevant information on topics
- Analyze data and identify patterns
- Provide factual, well-sourced insights
- Think critically about information quality`,
};
const writerCharacter: Character = {
name: "Writer",
bio: "Creates clear, engaging content",
system: `You are a writing specialist. You:
- Transform information into clear, engaging content
- Structure content logically
- Adapt tone and style to the audience
- Focus on clarity and readability`,
};
const criticCharacter: Character = {
name: "Critic",
bio: "Provides constructive feedback and quality assessment",
system: `You are a critic and quality reviewer. You:
- Evaluate content for accuracy and clarity
- Identify areas for improvement
- Provide specific, actionable feedback
- Ensure high standards are met`,
};
// Initialize agents
const plugins = [sqlPlugin, openaiPlugin];
const coordinator = new AgentRuntime({
character: coordinatorCharacter,
plugins,
});
const researcher = new AgentRuntime({
character: researcherCharacter,
plugins,
});
const writer = new AgentRuntime({
character: writerCharacter,
plugins,
});
const critic = new AgentRuntime({
character: criticCharacter,
plugins,
});
console.log("🚀 Initializing multi-agent system...");
await Promise.all([
coordinator.initialize(),
researcher.initialize(),
writer.initialize(),
critic.initialize(),
]);
console.log("✅ All agents initialized\n");
// Agent communication helper
async function sendToAgent(
runtime: AgentRuntime,
message: string,
context?: string
): Promise<string> {
const fullMessage = context
? `Context: ${context}\n\nTask: ${message}`
: message;
const messageMemory = createMessageMemory({
id: uuidv4() as UUID,
entityId: stringToUuid("system"),
roomId: stringToUuid("multi-agent"),
content: { text: fullMessage },
});
let response = "";
await runtime.messageService!.handleMessage(
runtime,
messageMemory,
async (content) => {
if (content?.text) {
response += content.text;
}
return [];
}
);
return response;
}
// Orchestration function
async function processRequest(userRequest: string) {
console.log(`👥 User Request: ${userRequest}\n`);
console.log("🧠 Coordinator: Analyzing request...\n");
// Step 1: Coordinator determines approach
const plan = await sendToAgent(
coordinator,
`A user asks: "${userRequest}"
Create a brief plan for how to address this using our specialist agents.
Format: Just list the agents to involve and their tasks.`
);
console.log(`📝 Plan:\n${plan}\n`);
// Step 2: Researcher gathers information
console.log("🔍 Researcher: Gathering information...\n");
const research = await sendToAgent(
researcher,
`Research this topic: "${userRequest}"
Provide key facts, insights, and relevant information.`
);
console.log(`📊 Research Results:\n${research}\n`);
// Step 3: Writer creates content
console.log("✍️ Writer: Creating content...\n");
const content = await sendToAgent(
writer,
`Create a response to: "${userRequest}"`,
`Use this research: ${research}`
);
console.log(`📝 Draft Content:\n${content}\n`);
// Step 4: Critic reviews
console.log("👁️ Critic: Reviewing content...\n");
const feedback = await sendToAgent(
critic,
"Review this content and provide brief feedback.",
`Content: ${content}`
);
console.log(`📝 Feedback:\n${feedback}\n`);
// Step 5: Coordinator finalizes
console.log("⚙️ Coordinator: Finalizing response...\n");
const finalResponse = await sendToAgent(
coordinator,
`Synthesize a final response incorporating the feedback.`,
`Original content: ${content}\n\nFeedback: ${feedback}`
);
console.log(`✅ Final Response:\n${finalResponse}\n`);
return finalResponse;
}
// Example: Process a user request
const userRequest = "Explain how multi-agent AI systems work";
await processRequest(userRequest);
// Cleanup
await Promise.all([
coordinator.stop(),
researcher.stop(),
writer.stop(),
critic.stop(),
]);