✨ v0.0.3 is available
SocietyAI Logo

Next-Generation Multi-Agent Orchestration

SocietyAI is a TypeScript library for building complex collaborative AI systems. DAG engine, zero dependencies, and completely model agnostic.

Robust Architecture

Designed for performance and flexibility. No "black magic", just solid engineering.

Model Agnostic
Compatible with OpenAI, Anthropic, Mistral, or your local models. You control the interface.
Graph Orchestration
Native support for DAGs (Directed Acyclic Graphs) and cycles for complex workflows.
Zero Dependencies
The core of the library is pure TypeScript. Lightweight, fast, and easy to audit.
Type-Safe
Built in TypeScript for TypeScript. Autocompletion and static validation of your workflows.
Fluent API
An intuitive builder to define your agents, tasks, and relationships in a few lines.
Extensible
Middleware system, custom tools (Function Calling), and managed memory.

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.

  • N
    Nodes : Agents, parallel tasks, conditions
  • E
    Edges : Dependencies (dependsOn) and data flow
  • V
    Validation : 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 history

Execution Types

Five orchestration modes for all your needs.

Sequential

Agents execute one by one. Each agent receives the result of the previous one.

.sequential()
A1
A2
A3

Perfect for: Linear workflows, processing pipelines

Parallel

All agents execute simultaneously with the same input.

.parallel()
A1
A2
A3

Perfect for: Multiple analyses, votes, consensus

Collaborative

Agents exchange messages over multiple iterations.

.collaborative(3)
A1
A2
A3

Perfect for: Brainstorming, peer review, consensus

Conditional

Dynamic branching: route to different tasks based on previous results.

.withBranch(...)
?
A
B

Perfect for: Routers, adaptive workflows

Human-in-the-Loop

Pause the workflow to wait for human input before continuing.

.isHuman()
A1
👤
A2

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/output
timing()Measure duration
metrics(collector)Collect metrics

Resilience

timeout(ms)Configurable timeout
retry({ maxAttempts })Exp. backoff
cache({ ttl })Response caching
rateLimit()Rate limiting
circuitBreaker()Circuit breaker
dedupe()Deduplicate calls
fallback(value)Fallback on error

Transform

validation()Input/output validation
transformInput(fn)Pre-process input
transformOutput(fn)Post-process output
middleware-example.ts
import { 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
hierarchical.ts
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.

Install via npm
Add SocietyAI to your TypeScript/Node.js project
npminstallsocietyai
TypeScript Support
Zero Dependencies
MIT License

Full Example

A complete workflow: writing, review, and publication

blog-workflow.ts
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.

Complete Documentation
Complete guide, architecture, API reference, and advanced examples.
Source Code
Explore the source code, contribute, and follow development.

Two API Levels

Choose the abstraction level that fits your needs.

✨ RECOMMENDED
High-Level API
For most use cases. Simple, fluent, fast.

Entry Point

Society.create()

Building Blocks

Task + TaskExecutionType

Best For

Standard workflows, rapid prototyping

🚀 ADVANCED
Low-Level API
For complex cases. Total graph control.

Entry Point

GraphBuilder.create()

Building Blocks

GraphNode + 10 NodeTypes

Best 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.

Ready to Build Intelligent Systems?

Start orchestrating your multi-agent workflows today with SocietyAI.

MIT License • Open Source • Zero Dependencies