Robust Architecture
Designed for performance and flexibility. No "black magic", just solid engineering.
Key Features
Everything you need to build powerful multi-agent systems.
Multi-Agent System
Define roles, personalities, and contexts for each agent. Agents can collaborate, debate, and work together.
Flexible Workflows
Support for sequential, parallel, collaborative, and conditional workflows to meet all your needs.
Memory & Context
Native management of short and long-term memory, and shared context between steps.
Execution Strategies
The engine transforms your configuration into an execution graph optimized for maximum performance.
Observability
Complete event system to monitor and debug your workflows.
Cyclic Graphs
Support for workflows with loops and self-correction.
Tools & Function Calling
Integrate external tools and use the ReAct pattern for more powerful agents.
Validation
Validate agent outputs with JSON Schema for structured and reliable results.
Worker Threads
Execute CPU-intensive agents in isolated worker threads, preventing event loop blocking for responsive applications.
MCP Protocol
Model Context Protocol support for seamless integration with external tools and services (filesystem, git, search, etc.).
System Architecture
Discover the powerful workflow that orchestrates your intelligent agents.
Define Roles & Agents
Each agent has a role (system instructions), an AI model (OpenAI, Claude, etc.), and a unique ID.
const writerRole = createRole('writer')
.withSystemPrompt('You are..');
const reviewerRole = createRole('reviewer')
.withSystemPrompt('You review...');Create Society & Tasks
Use Society.create() to add agents and tasks. Each task defines: who, what, and how.
const society = Society.create()
.withId('blog-team')
.addAgent(a => a
.withId('writer')
.withRole(writerRole)
.withModel(model))
.addAgent(a => a
.withId('reviewer')
.withRole(reviewerRole)
.withModel(model))
.addTask(t => t
.withId('draft')
.withAgents(['writer'])
.sequential())
.addTask(t => t
.withId('review')
.dependsOn('draft')
.withAgents(['reviewer'])
.sequential());Graph Transformation (DAG)
Behind the scenes, the SocietyExecutor transforms your configuration into an execution graph.
- NNodes : Agents, parallel tasks, conditions
- EEdges : Dependencies (dependsOn) and data flow
- VValidation : Detection of invalid cycles and config errors
Execution & Results
Call .execute(input) to launch the orchestration. Results are aggregated and returned.
const result = await society
.execute('Write about...');
console.log(result.output);
// Final result
console.log(result.taskResults);
// Task historyExecution Types
Five orchestration modes for all your needs.
Agents execute one by one. Each agent receives the result of the previous one.
.sequential()Perfect for: Linear workflows, processing pipelines
All agents execute simultaneously with the same input.
.parallel()Perfect for: Multiple analyses, votes, consensus
Agents exchange messages over multiple iterations.
.collaborative(3)Perfect for: Brainstorming, peer review, consensus
Dynamic branching: route to different tasks based on previous results.
.withBranch(...)Perfect for: Routers, adaptive workflows
Pause the workflow to wait for human input before continuing.
.isHuman()Perfect for: Approval gates, manual review, interactive workflows
13 Built-in Middlewares
Composable middleware chain with priority ordering. Add logging, caching, rate limiting, and more in one line.
Observability
logging()Log input/outputtiming()Measure durationmetrics(collector)Collect metricsResilience
timeout(ms)Configurable timeoutretry({ maxAttempts })Exp. backoffcache({ ttl })Response cachingrateLimit()Rate limitingcircuitBreaker()Circuit breakerdedupe()Deduplicate callsfallback(value)Fallback on errorTransform
validation()Input/output validationtransformInput(fn)Pre-process inputtransformOutput(fn)Post-process outputimport { Society, Middlewares, MiddlewareChain } from 'societyai';
// Compose a middleware chain with priority ordering
const chain = MiddlewareChain.create()
.use(Middlewares.logging())
.use(Middlewares.timeout(30000))
.use(Middlewares.retry({ maxAttempts: 3 }))
.use(Middlewares.cache({ ttl: 60000 }))
.use(Middlewares.circuitBreaker({ threshold: 5 }));
const society = Society.create()
.addMiddleware(chain.build())Hierarchical Societies
Compose entire societies inside other societies using EngineAsModel. A complete multi-agent workflow becomes a single model.
How it works
- 1.Build an inner society (sub-team)
- 2.Wrap it with
EngineAsModel - 3.Use it as a regular model in an outer society
Use Cases
- • Manager delegating to sub-teams
- • Nested multi-stage pipelines
- • Reusable domain-specific societies
- • Recursive problem decomposition
import { Society, GraphBuilder, NodeType,
EngineAsModel } from 'societyai';
// 1. Build the inner team graph
const codeTeam = GraphBuilder.create()
.addNode('start', NodeType.START)
.addNode('coder', NodeType.AGENT, { agentId: 'coder' })
.addNode('tester', NodeType.AGENT, { agentId: 'tester' })
.addNode('end', NodeType.END)
.addEdge('start', 'coder')
.addEdge('coder', 'tester')
.addEdge('tester', 'end')
.build();
// 2. Wrap as a model
const codeTeamModel = new EngineAsModel({
engine: codeTeam,
agents: [coderAgent, testerAgent],
name: 'code-team'
});
// 3. Use the inner team as a single agent
const result = await Society.create()
.addAgent(a => a
.withId('manager')
.withRole(r => r.withSystemPrompt('...'))
.withModel(codeTeamModel) // ← sub-team!
)
.addTask(t => t
.withId('delegate')
.withAgents(['manager'])
.sequential())
.execute('Build a REST API');Ready-to-Use Patterns
Save time with SocietyPatterns and AggregationStrategies.
SocietyPatterns
.chain(agents)Simple sequential chain
.parallel(agents)Parallel execution with aggregation
.collaborative(agents, maxIterations)Multi-iteration collaborative dialog
.review(writer, reviewer)Draft → Review → Revise pipeline
AggregationStrategies
.concat(separator)Concatenates all results
.first() / .last()Takes first or last successful result
.best(scoreFn)Selects the best based on a score function
.structured('json' | 'markdown' | 'list')Formats results as structured output
.reduce(reducer, initial, finalize)Custom reducer for full control
Installation
Get started in minutes with SocietyAI.
npminstallsocietyaiFull Example
A complete workflow: writing, review, and publication
import { Society } from 'societyai';
// SocietyAI is model-agnostic (Zero Dependencies).
// Bring your own AI model adapter (OpenAI, Anthropic, etc.)
import { MyAIModel } from './my-model-adapter';
const model = new MyAIModel(process.env.OPENAI_API_KEY);
const result = await Society.create()
.withId('blog-team')
// -- Define Agents --
.addAgent(agent => agent
.withId('writer')
.withRole(role => role
.withName('Technical Writer')
.withSystemPrompt('You are an expert in concise technical writing.')
)
.withModel(model)
)
.addAgent(agent => agent
.withId('editor')
.withRole(role => role
.withName('Editor in Chief')
.withSystemPrompt('You correct style and verify clarity.')
)
.withModel(model)
)
// -- Define Workflow --
// Task 1: The writer writes
.addTask(task => task
.withId('draft')
.withAgents(['writer'])
.withInstructions('Write a paragraph about the benefits of TypeScript.')
.sequential()
)
// Task 2: The editor reviews (depends on 'draft')
.addTask(task => task
.withId('review')
.dependsOn('draft')
.withAgents(['editor'])
.withInstructions('Review the text, correct mistakes, and improve tone.')
.sequential()
)
// Execute
.execute('Start Project');
console.log('Final Result:', result.output);Resources
Explore the complete documentation and examples to master SocietyAI.
Two API Levels
Choose the abstraction level that fits your needs.
Entry Point
Society.create()Building Blocks
Task + TaskExecutionTypeBest For
Standard workflows, rapid prototyping
Entry Point
GraphBuilder.create()Building Blocks
GraphNode + 10 NodeTypesBest For
Cycles, custom transformations, complex aggregations
💡 Tip: Always start with the High-Level API. Only switch to Low-Level if you need cycles or personalized transformations.
