| name | ai-agent-orchestrator |
| description | Orchestrates multi-agent AI systems with task delegation, agent communication, shared memory, and workflow coordination. Use when users request "multi-agent system", "agent orchestration", "AI agents", "agent coordination", or "autonomous agents". |
AI Agent Orchestrator
Build coordinated multi-agent systems for complex task automation.
Core Workflow
- Define agents: Create specialized agents
- Design workflow: Plan agent coordination
- Implement handoffs: Agent-to-agent communication
- Add shared memory: Persistent context
- Create supervisor: Orchestrate execution
- Monitor execution: Track agent activities
Agent Architecture
Agent Definition
import { ChatOpenAI } from '@langchain/openai';
import { SystemMessage, HumanMessage, AIMessage } from '@langchain/core/messages';
export interface AgentConfig {
name: string;
role: string;
systemPrompt: string;
tools?: Tool[];
model?: string;
}
export interface AgentResponse {
content: string;
toolCalls?: ToolCall[];
nextAgent?: string;
completed?: boolean;
}
export class Agent {
private model: ChatOpenAI;
private config: AgentConfig;
private messageHistory: BaseMessage[] = [];
constructor(config: AgentConfig) {
this.config = config;
this.model = new ChatOpenAI({
modelName: config.model || 'gpt-4-turbo-preview',
temperature: 0.7,
});
}
async execute(input: string, context?: Record<string, any>): Promise<AgentResponse> {
const systemMessage = new SystemMessage(
this.buildSystemPrompt(context)
);
const messages = [
systemMessage,
...this.messageHistory,
new HumanMessage(input),
];
const response = await this.model.invoke(messages, {
tools: this.config.tools,
});
this.messageHistory.push(new HumanMessage(input));
this.messageHistory.push(new AIMessage(response.content as string));
return this.parseResponse(response);
}
private buildSystemPrompt(context?: Record<string, any>): string {
let prompt = this.config.systemPrompt;
if (context) {
prompt += `\n\nContext:\n${JSON.stringify(context, null, 2)}`;
}
return prompt;
}
private parseResponse(response: any): AgentResponse {
return {
content: response.content as string,
toolCalls: response.tool_calls,
completed: response.content?.includes('[TASK_COMPLETE]'),
};
}
clearHistory() {
this.messageHistory = [];
}
}
Specialized Agents
import { Agent, AgentConfig } from './base';
export const ResearchAgent = new Agent({
name: 'researcher',
role: 'Research Specialist',
systemPrompt: `You are a research specialist. Your job is to:
- Search for and gather relevant information
- Analyze sources and extract key insights
- Summarize findings clearly
- Cite sources when possible
When you have gathered sufficient information, include [TASK_COMPLETE] in your response.
If you need help from another agent, specify: [HANDOFF:agent_name]`,
tools: [searchTool, webScrapeTool],
});
export const WriterAgent = new Agent({
name: 'writer',
role: 'Content Writer',
systemPrompt: `You are a professional content writer. Your job is to:
- Create engaging, well-structured content
- Adapt tone and style to the target audience
- Incorporate research and data effectively
- Edit and refine for clarity
Use the research provided to create compelling content.
When complete, include [TASK_COMPLETE].`,
});
export const ReviewerAgent = new Agent({
name: 'reviewer',
role: 'Quality Reviewer',
systemPrompt: `You are a quality reviewer. Your job is to:
- Review content for accuracy and clarity
- Check for errors and inconsistencies
- Suggest improvements
- Approve or request revisions
Provide specific feedback. If approved, include [APPROVED].
If revisions needed, include [REVISIONS_NEEDED] with specific changes.`,
});
= ({
: ,
: ,
: ,
});
Orchestrator
Simple Sequential Orchestrator
import { Agent } from '../agents/base';
interface WorkflowStep {
agent: Agent;
task: string;
inputFrom?: string;
}
export class SequentialOrchestrator {
private agents: Map<string, Agent> = new Map();
private results: Map<string, string> = new Map();
registerAgent(name: string, agent: Agent) {
this.agents.set(name, agent);
}
async execute(workflow: WorkflowStep[]): Promise<Record<string, string>> {
for (const step of workflow) {
const agent = step.agent;
input = step.;
(step. && ..(step.)) {
input = ;
}
.();
result = agent.(input);
..(agent., result.);
.();
}
.(.);
}
}
orchestrator = ();
orchestrator.(, );
orchestrator.(, );
orchestrator.(, );
results = orchestrator.([
{ : , : },
{ : , : , : },
{ : , : , : },
]);
Supervisor Orchestrator
import { ChatOpenAI } from '@langchain/openai';
import { Agent } from '../agents/base';
interface AgentRegistry {
[name: string]: {
agent: Agent;
description: string;
};
}
export class SupervisorOrchestrator {
private supervisor: ChatOpenAI;
private agents: AgentRegistry = {};
private sharedContext: Record<string, any> = {};
private maxIterations = 10;
constructor() {
this.supervisor = new ChatOpenAI({
modelName: 'gpt-4-turbo-preview',
temperature: 0,
});
}
registerAgent(name: string, agent: Agent, description: string) {
this.agents[name] = { agent, description };
}
(: ): <> {
iteration = ;
currentTask = task;
: [] = [];
(iteration < .) {
iteration++;
decision = .(currentTask, history);
(decision.) {
decision.!;
}
{ agent } = .[decision.!];
result = agent.(decision.!, .);
.[decision.!] = result.;
history.();
(result.) {
currentTask = ;
}
}
();
}
(
: ,
: []
): <{
: ;
?: ;
?: ;
?: ;
}> {
agentList = .(.)
.( )
.();
prompt = ;
response = ..([{ : , : prompt }]);
.(response. );
}
}
Parallel Agent Execution
export class ParallelOrchestrator {
private agents: Map<string, Agent> = new Map();
async executeParallel(
tasks: Array<{ agentName: string; task: string }>
): Promise<Map<string, string>> {
const results = new Map<string, string>();
await Promise.all(
tasks.map(async ({ agentName, task }) => {
const agent = this.agents.get(agentName);
if (!agent) throw new Error(`Agent ${agentName} not found`);
const result = await agent.execute(task);
results.set(agentName, result.content);
})
);
return results;
}
async fanOutFanIn(
: ,
: [],
:
): <> {
parallelResults = .(
agentNames.( ({ : name, task }))
);
aggregatedInput = .(parallelResults.())
.( )
.();
finalResult = aggregator.(
);
finalResult.;
}
}
Shared Memory
import { Redis } from 'ioredis';
export class SharedMemory {
private redis: Redis;
private prefix: string;
constructor(sessionId: string) {
this.redis = new Redis(process.env.REDIS_URL!);
this.prefix = `agent:${sessionId}:`;
}
async set(key: string, value: any, ttl?: number): Promise<void> {
const serialized = JSON.stringify(value);
if (ttl) {
await this.redis.setex(this.prefix + key, ttl, serialized);
} else {
await this.redis.set(. + key, serialized);
}
}
get<T>(: ): <T | > {
value = ..(. + key);
value ? .(value) : ;
}
(: , : ): <> {
list = ( .<[]>(key)) || [];
list.(item);
.(key, list);
}
(): <[]> {
( .<[]>()) || [];
}
(: ): <> {
.(, message);
}
(): <<, >> {
( .<<, >>()) || {};
}
(: , : ): <> {
outputs = .();
outputs[agent] = output;
.(, outputs);
}
(): <> {
keys = ..(. + );
(keys. > ) {
..(...keys);
}
}
}
Event-Driven Agent Communication
import { EventEmitter } from 'events';
export class AgentEventBus extends EventEmitter {
private static instance: AgentEventBus;
static getInstance(): AgentEventBus {
if (!this.instance) {
this.instance = new AgentEventBus();
}
return this.instance;
}
emitAgentMessage(from: string, to: string, message: any) {
this.emit(`message:${to}`, { from, message, timestamp: new Date() });
}
emitAgentComplete(agent: string, result: any) {
this.emit('agent:complete', { agent, result, timestamp: () });
}
() {
.(, { agent, error, : () });
}
() {
.(, handler);
}
() {
.(, handler);
}
}
eventBus = .();
eventBus.(, ({ , message }) => {
.(, message);
result = .(message);
eventBus.(, result);
});
eventBus.( {
.(, result.);
});
Workflow Definition
interface WorkflowDefinition {
name: string;
description: string;
agents: string[];
steps: WorkflowStep[];
errorHandling: 'retry' | 'fallback' | 'abort';
}
const ContentCreationWorkflow: WorkflowDefinition = {
name: 'content-creation',
description: 'Create and publish content',
agents: ['planner', 'researcher', 'writer', 'reviewer'],
steps: [
{
id: 'plan',
agent: 'planner',
input: '{task}',
outputKey: 'plan',
},
{
id: 'research',
agent: 'researcher',
input: 'Research for: {plan.topic}',
outputKey: 'research',
parallel: true,
},
{
id: 'write',
agent: 'writer',
input: 'Write about {plan.topic} using research: {research}',
: ,
: [],
},
{
: ,
: ,
: ,
: ,
: {
: ,
: ,
: ,
},
},
],
: ,
};
Best Practices
- Single responsibility: Each agent has one clear role
- Clear handoffs: Explicit agent-to-agent communication
- Shared context: Use memory for persistent state
- Iteration limits: Prevent infinite loops
- Error handling: Graceful degradation
- Observability: Log all agent actions
- Testing: Test agents individually and together
- Timeout handling: Prevent stuck agents
Output Checklist
Every agent system should include: