V1 Documentation

TeamDynamics Docs

Learn how to build, run, and analyze multi-agent AI simulations that predict team dynamics, breakdowns, and resilience under crisis conditions — complete with world state constraints, hidden agendas, power hierarchies, and dramatic outcomes.

Overview

TeamDynamics is a multi-agent AI simulation sandbox designed for founders, HR leaders, and organizational strategists. It lets you create a virtual team of AI-driven employees, inject real-world crises, and observe how your team would react—before it happens in real life.

Each agent has deep psychological profiles including traits like empathy, ambition, stress tolerance, and loyalty. When a crisis hits, agents react based on their personality, relationships, hidden agendas, and current state—producing realistic Slack-like conversations alongside their hidden internal thoughts. A dynamic World State engine tracks budget, deadlines, and reputation, while a Decision Engine manages team proposals with hierarchy-weighted voting.

AI Persona Agents

Design psychological profiles with deep personality traits, hidden agendas, and persistent memory.

Live Drama Engine

Watch public vs. private conversations unfold in real-time with typing indicators.

World State System

Track budget, deadlines, team capacity, technical debt, and company reputation.

Decision Engine

Hierarchy-weighted proposals, voting, and team decision-making with real consequences.

Random Events

Unpredictable events (client threats, positive press, security breaches) inject chaos.

Burnout Prediction

Identify breaking points with personality-weighted stress absorption and natural recovery.

Quick Start

Get your first simulation running in under 5 minutes. Follow these steps:

1

Sign In or Register

Create an account with email/password or sign in with Google OAuth. You start with 10 free simulation credits. Admin users have unlimited credits.

2

Configure Your Company

Navigate to the Setup page and define your company name, culture, and context. Optionally upload a document (PDF, DOCX, Excel) for AI-powered requirement extraction and crisis suggestions.

3

Assemble Your Team

Choose from 4 preset agent personas (Alex, Sam, Jordan, Casey) or create fully custom agents with unique personality traits, motivations, expertise, and per-agent LLM model overrides. Up to 8 agents per simulation.

4

Inject a Crisis

Select a pre-built scenario, use the AI Auto-Generate button for a tailored crisis based on your company profile, or write your own custom crisis event.

5

Start & Observe

Hit 'Launch Simulation' and watch your AI team react in a live Slack-like interface. Use God Mode to intervene in real-time. Random events may inject additional chaos mid-simulation.

Pro Tip
Start with the default preset team and a pre-built crisis to get familiar with the system. Each agent has a hidden agenda you won't see until the drama unfolds.

Architecture

TeamDynamics is built on a modern stack designed for real-time AI interactions with persistent state:

Frontend

• Next.js 16 (App Router)

• React 19 with Server Components

• Tailwind CSS v4 + shadcn/ui

• Framer Motion for animations

• Recharts for data visualization

• Google OAuth (Client SDK)

• Sonner toast notifications

Backend (AI Engine)

• FastAPI (Python) with Uvicorn

• Multi-LLM: OpenAI / Gemini / OpenRouter

• WebSocket for real-time streaming

• PostgreSQL + asyncpg connection pooling

• JWT Authentication (bcrypt + jose)

• Personality-Weighted State Machine

• Decision Engine & World State System

System Architecturetext
┌──────────────────────────────────────────────────────────────┐
│                    Next.js Frontend                         │
│  ┌─────────┐  ┌──────────┐  ┌──────────┐  ┌────────────┐  │
│  │  Login / │  │  Setup   │  │Simulation│  │  Report /  │  │
│  │Register │  │  Page    │  │  Page     │  │ Dashboard  │  │
│  └────┬────┘  └─────┬────┘  └─────┬─────┘  └──────┬─────┘  │
│       │  Auth Context (JWT)  │ WebSocket   │ REST API   │  │
└───────┼──────────────────────┼─────────────┼────────────┘  │
        │                      │             │               │
┌───────┼──────────────────────┼─────────────┼───────────────┐
│       ▼     FastAPI Backend  ▼             ▼               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │         Auth Router ─── Simulation Router           │   │
│  │         Agent Router ── Document Router              │   │
│  │         WebSocket Router (Background Tasks)         │   │
│  ├─────────────────────────────────────────────────────┤   │
│  │              Simulation Engine (Orchestrator)       │   │
│  ├──────────┬──────────┬──────────┬───────────────────┤   │
│  │ Agent 1  │ Agent 2  │ Agent N  │ Per-Agent LLM     │   │
│  │ (LLM)    │ (LLM)    │ (LLM)    │ Model Override    │   │
│  ├──────────┴──────────┴──────────┴───────────────────┤   │
│  │   Personality-Weighted State Machine               │   │
│  │   (Morale, Stress, Loyalty, Productivity)          │   │
│  ├────────────────────────────────────────────────────┤   │
│  │   Decision Engine  │  World State  │ Round Agenda  │   │
│  │   (Proposals,      │  (Budget,     │ (5 Phases,    │   │
│  │    Voting,          │  Deadline,    │  Crisis-aware │   │
│  │    Hierarchy)       │  Reputation)  │  Modifiers)   │   │
│  ├────────────────────────────────────────────────────┤   │
│  │   Hidden Agendas │ Random Events │ Agent Memory    │   │
│  └────────────────────────────────────────────────────┘   │
│  ┌────────────────────────────────────────────────────┐   │
│  │  PostgreSQL (asyncpg)  │  Report Generator (LLM)  │   │
│  └────────────────────────────────────────────────────┘   │
└───────────────────────────────────────────────────────────┘

Authentication System

TeamDynamics supports two authentication methods for user accounts. Authentication is optional for simulation access but required for credit tracking and simulation history.

Email + Password

Register with email, name, and password (min 6 chars). Passwords are hashed with bcrypt. JWT tokens expire after 7 days.

Google OAuth

One-click sign-in with Google. Supports both access token and ID token flows. Auto-creates user accounts for new Google users.

Credits & Roles

Every new user receives 10 simulation credits. Each simulation launch consumes 1 credit. Admin users (configured via ADMIN_EMAIL environment variable) have unlimited credits.

RoleCreditsCapabilities
User10 (default)Create simulations, view reports, manage profile
AdminUnlimitedAll user capabilities + unlimited simulations

AI Agents

Each agent in TeamDynamics is a fully autonomous AI entity powered by a large language model. Agents have persistent memory, emotional states, hidden agendas, and evolving relationships with other team members. State changes are personality-weighted — agents with different traits absorb stress, morale hits, and bonuses differently.

Agent Properties

PropertyTypeDescription
namestringAgent display name
rolestringJob title (e.g., "Tech Lead", "Junior Dev")
typestringArchetype label (e.g., "Strict & Burned Out")
personalityPersonalityTraitsDeep psychological profile object (5 traits)
motivationstring?Hidden career motivation driving behavior
expertisestring?Domain expertise area
modelstring?Per-agent LLM model override
moralenumber (0-100)Current emotional well-being
stressnumber (0-100)Current stress/burnout level
loyaltynumber (0-100)Commitment to the company
productivitynumber (0-100)Current output efficiency
memoryMemoryEntry[]Persistent memory across rounds (last 8 entries)
has_resignedbooleanWhether the agent has quit

Personality-Weighted State Machine

State changes are not applied equally to all agents. Each personality trait creates multipliers that modulate how agents absorb changes:

TraitEffectRange
Stress ToleranceHigh tolerance → absorbs less stress0.4x – 1.6x
Empathy + AgreeablenessHigh → morale drops less from negativity, gains more from positivity0.7x – 1.3x
AmbitionHigh ambition → productivity drops less0.5x – 1.2x
Agreeableness + AssertivenessHigh agreeableness + low assertiveness → loyalty more stable0.6x – 1.4x
Natural Recovery
Agents naturally recover a small amount each round based on their personality. High stress tolerance → up to 4 stress recovery/round. High empathy → morale stabilizes toward baseline when below 50%.

Persona Design

Personas define how agents think, communicate, and react to stress. TeamDynamics ships with 4 curated presets, but you can design fully custom personas with up to 8 agents per simulation.

A
Alex
Tech Lead
Strict & Burned Out

Low patience (EMP:30), high competence (AMB:80), extremely low stress tolerance (ST:25), very assertive (ASR:90)

S
Sam
Junior Dev
Ambitious & Naive

High ambition (AMB:90), low experience (ST:30), people-pleaser tendencies (AGR:80), low assertiveness (ASR:25)

J
Jordan
Product Manager
Empathetic

Very high emotional intelligence (EMP:90), strong mediator (AGR:85), good stress tolerance (ST:70), risk-averse

C
Casey
Senior Dev
Silent & Efficient

Introverted, very high resilience (ST:85), low agreeableness (AGR:30), avoids conflict until critical

Per-Agent LLM Override
Each agent can use a different LLM model. Choose from GPT-4o, Claude 3.7 Sonnet, Llama 3.1, Mistral 7B, Gemini 2.0 Flash, Deepseek, or any custom OpenRouter model.

Crisis Injection

Crisis events are the catalysts that trigger agent reactions. They simulate real-world disruptions that test team resilience. Each crisis also initializes a unique World State with appropriate constraints.

Built-in Crisis Scenarios

Mandatory Weekend Coding for v2.0
Forces entire engineering team to work weekends indefinitely. Budget: 60%, Deadline: 6 weeks.
High
Budget Cut: 30% Layoffs Required
Management demands immediate headcount reduction. Budget: 35%, Reputation: 55%.
Critical
CEO Resigns Unexpectedly
Leadership vacuum creates uncertainty and power struggles. Reputation: 40%.
Critical
Critical Database Deleted on Friday
Production incident requiring emergency all-hands response. Deadline: 2 weeks, Customer Satisfaction: 30%.
High
AI Auto-Generate & Custom Crises
Use the Auto-Generate button to create an AI-tailored crisis based on your company profile, or write free-form crisis descriptions that the AI engine will interpret contextually.

Document Upload & AI Analysis

Upload documents (PDF, DOCX, TXT, CSV, Excel — max 10MB) for AI-powered analysis. The system extracts text and produces:

  • Document summary and key requirements
  • Team risk identification
  • Suggested crisis scenario tailored to the document content
  • Suggested agent roles and rationale
  • Actionable insights for simulation setup

Simulation Flow

Once configured, the simulation runs as a background task that survives WebSocket disconnects — clients can reconnect and resume viewing. Each round, agents process the current situation, update their internal states, and produce public messages, private thoughts, actions, and memory updates.

Round Lifecycle

Simulation Round Flowtext
Round Start
  │
  ├─→ World State tick (deadline approaches, budget burns, debt creeps)
  │
  ├─→ Phase transition check (broadcast phase shift announcement)
  │
  ├─→ Roll for Random Event (may inject chaos)
  │
  ├─→ Each agent processes (sequentially):
  │   ├── Typing indicator broadcast
  │   ├── Reviews personality, memory, hidden agenda
  │   ├── Reads World State constraints & round agenda
  │   ├── Evaluates hierarchy position & decision context
  │   ├── Generates via LLM (per-agent model override)
  │   └── Produces: public_message, internal_thought,
  │                  state_changes, memory_update, action, action_detail
  │
  ├─→ Apply personality-weighted state changes
  ├─→ Process action through Decision Engine (proposals/votes/consequences)
  ├─→ Check for critical events (resignation, burnout)
  ├─→ Apply resignation effects to World State
  │
  ├─→ God Mode check: Player can intervene via WebSocket
  │
  └─→ Record metrics snapshot → Check end conditions → Next Round
       └─→ If final round or all resigned → Determine Outcome

Message Types

Public messages are what agents say in the team Slack channel. These are filtered through their personality—an agent with high agreeableness might sugarcoat their frustration.

Alex (Tech Lead): “Are you serious right now? We've been working 60-hour weeks for a month.”

Simulation Phases & Round Agenda

Each simulation progresses through 5 distinct phases based on round progression. Phases define the purpose of each round so conversations drive toward concrete decisions rather than aimless discussion.

1
Crisis Impact0–15%

The crisis just hit. Agents react emotionally and assess the damage.

Tone: Reactive, emotional, uncertain

2
Strategy Debate15–35%

Agents propose competing solutions and argue their merits.

Tone: Argumentative, strategic

3
Decision Point35–50%

The team must converge on a decision. Fence-sitters must pick a side.

Tone: Decisive, urgent

4
Execution & Adaptation50–75%

The team executes their decision and deals with consequences.

Tone: Focused, stressed

5
Resolution & Reflection75–100%

The crisis nears resolution. Agents reflect and decide their future.

Tone: Reflective, honest

Crisis-Specific Modifiers
Each crisis injects specific discussion points per phase. For example, during the “Decision Point” phase of a Layoffs crisis, agents debate criteria like performance vs. seniority vs. role criticality.

World State Engine

The World State provides concrete, measurable constraints that ground agent decisions in reality. Agents reference these numbers when proposing solutions — no proposing hiring if budget is below 30%.

MetricTypePer-Round DecayAffected By
Budget Remaining0–100%−2% / roundActions, events, decisions
Deadline (Weeks Left)countdown−1 / roundTime only
Team Capacity0–100%NoneResignations, rally actions
Customer Satisfaction0–100%NoneEvents, transparency, blame
Technical Debt0–100%+1% / roundRushed decisions, alarms
Company Reputation0–100%NoneMedia, events, decisions

Decision Engine

The Decision Engine tracks proposals, votes, and team consensus using a hierarchy-weighted influence system. A proposal needs 3.0+ weighted influence to pass as a team decision.

Power Hierarchy

LevelRolesInfluence Weight
C-SuiteCEO, CTO, CFO, COO3.0
VP / DirectorVP, Vice President, Director2.5
Lead / ManagerLead, Manager, Head, Principal2.0
SeniorSenior, Staff, Architect1.5
Individual ContributorDefault level1.0
JuniorJunior, Intern, Associate, Entry0.7

Available Agent Actions

propose_solutionPropose a concrete solution to the crisis
support_proposalSupport another team member's proposal
oppose_proposalDisagree with a proposal and explain why
negotiateSeek a compromise between competing proposals
escalateEscalate the issue to management/leadership
rally_teamBoost team morale and unity
blamePoint fingers at who caused the problem
resign_threatThreaten or hint at resignation
report_progressReport on progress of the current plan
raise_alarmSound alarm that something is going wrong

Hidden Agendas

Every agent has a secret hidden agenda that colors their decisions without other agents knowing. Preset agents have curated agendas, while custom agents receive randomly assigned ones.

Alex (Tech Lead)

Secretly angling for a VP promotion. Prefers solutions that showcase their leadership, subtly undermines proposals that would make others the hero.

Sam (Junior Dev)

Secretly interviewing at other companies. Wants visible, impressive tasks for resume-building. Avoids grunt work.

Jordan (PM)

Secretly promised a customer an impossible timeline. Steers conversations away from customer commitments.

Casey (Senior Dev)

Wants to stay under the radar and go home at 5pm. Resists any proposal that increases their workload.

Random Events

Random events inject unpredictability into the simulation. Each round, there's a chance (8-15% per event) that an unexpected event fires. Events affect the World State and all active agents' morale/stress.

Negative Events

  • • Key Client Threatens to Leave
  • • Competitor Poaching Attempt
  • • Additional Budget Cuts
  • • Minor Security Incident
  • • Negative Press Coverage

Positive Events

  • • Investor Shows Renewed Confidence
  • • Major Customer Sends Praise
  • • Positive Media Coverage
  • • Critical Resource Discovered

Mixed Events

  • • Emergency Board Meeting Called
  • • New Industry Regulation

God Mode

During any active simulation, you have access to God Mode—a powerful intervention system that lets you alter the course of the simulation in real-time. Interventions are personality-weighted — cynical agents (low agreeableness) benefit less from positive interventions.

Quick Actions

Give Bonus
Award a surprise bonus. Morale +15, Stress -5, Loyalty +10 (base values, modified by personality).
Pizza Party
Lighten the mood. Morale +8, Stress -10, Loyalty +5 (personality-weighted).
Cancel Overtime
Revoke mandatory extra hours. Morale +20, Stress -25, but Productivity -10.
Custom Message
Type any intervention as a management announcement. Morale +10, Stress -8.
Use Responsibly
God Mode interventions affect agent states immediately. Cynical agents (low agreeableness) have an effectiveness range of 0.5x–1.3x for interventions. Excessive positive interventions may produce unrealistic results.

Simulation Outcomes

When a simulation ends (final round reached or all agents resign), the engine determines one of 6 possible outcomes based on agent states, decision status, and world health:

🏆Team Triumph

High morale, no resignations, decision reached, healthy world.

🤝Negotiated Settlement

Decision reached through debate, acceptable state.

Pyrrhic Victory

Crisis addressed, but at significant human cost.

💔Team Fracture

>50% resigned or avg morale <20%. Deep fault lines exposed.

🔥Total Collapse

All agents resigned or burned out. No team left.

Stalemate

No proposals made, team talked in circles while crisis deepened.

Metrics & Tracking

During a simulation, the dashboard tracks key organizational health metrics in real-time with timeline history:

MetricRangeCritical ThresholdImpact
Morale0-100%< 30%Agent may resign or become uncooperative
Stress0-100%> 80%Output quality drops, burnout threshold hit
Loyalty0-100%< 20%Agent begins job-hunting behavior
Productivity0-100%< 40%Deadlines will be missed
Team Cohesion0-100%< 30%Composite of loyalty, morale, and alignment

Post-Simulation Reports

After a simulation completes, TeamDynamics generates a comprehensive AI-powered report including:

  • Executive Summary with key findings and critical alerts
  • Simulation Overview — detailed objective and scenario description
  • Structured Key Metrics (total agents, active, resignations, averages)
  • In-depth Analysis Insights — AI-generated paragraph analyzing patterns
  • Agent Resiliency Profiles showing start vs. end states with status labels
  • Conclusion — final summary and risk assessment
  • Timeline visualization (morale, stress, output per round)
  • Actionable Recommendations — 3-5 AI-generated management actions
  • Exportable to PDF for stakeholder sharing

AI Insights

The AI engine analyzes simulation data to produce actionable recommendations. These insights help leaders understand what went wrong and how to prevent similar outcomes.

Example Report Output
Critical Finding: Stress reached a dangerous 95% peak at Week 8 — a direct result of unresolved interpersonal blame between Dinesh and Gilfoyle.
Analysis Insight: The simulation revealed a critical leadership vacuum during weeks 4-8 when the CEO defaulted to micromanagement rather than strategic delegation.

Recommended Actions:

  • Implement a crisis communication protocol with designated roles.
  • Train leaders on conflict mediation techniques.
  • Establish mandatory post-incident debrief sessions within 48 hours.

API Endpoints

The TeamDynamics backend exposes a RESTful API with WebSocket support. All endpoints return JSON. Authentication uses Bearer JWT tokens.

Authentication

POST
/api/auth/register

Register a new user with email, name, and password.

POST
/api/auth/login

Login with email and password. Returns JWT token and user profile.

POST
/api/auth/google

Authenticate with Google OAuth credential. Auto-creates user if new.

GET
/api/auth/me

Get current user profile (requires Bearer token).

GET
/api/auth/me/simulations

Get all simulations for the authenticated user.

Simulation

POST
/api/simulation/create

Create a new simulation with company profile, agents, crisis config, and params. Deducts 1 credit.

POST
/api/simulation/generate-crisis

AI-generate a tailored crisis based on company name and culture.

GET
/api/simulation/{id}/status

Get current simulation status, round, agents, messages, and metrics.

POST
/api/simulation/{id}/intervene

Send a God Mode intervention (bonus, pizza, cancel_overtime, custom).

GET
/api/simulation/{id}/report

Generate and retrieve the full post-simulation report with AI insights.

Other Endpoints

GET
/api/agents/presets

List all 4 available preset agent personas.

POST
/api/document/analyze

Upload a document (multipart) for AI-powered analysis. Max 10MB.

GET
/health

Health check — returns service status, version, and LLM provider.

WS
/ws/simulation/{id}

WebSocket for real-time simulation streaming. Supports interventions via JSON messages.

Data Models

Core data structures used across the TeamDynamics system:

Create Simulation Requesttypescript
interface CreateSimulationRequest {
  company: {
    name: string;           // 1-100 chars
    culture: string;        // 1-1000 chars
  };
  agents: {
    id: string;
    name: string;
    role: string;
    type: string;           // e.g. "Strict & Burned Out"
    color?: string;
    personality: {
      empathy: number;           // 0-100
      ambition: number;          // 0-100
      stressTolerance: number;   // 0-100
      agreeableness: number;     // 0-100
      assertiveness: number;     // 0-100
    };
    motivation?: string;    // Career motivation text
    expertise?: string;     // Domain expertise area
    model?: string;         // Per-agent LLM model override
  }[];
  crisis: {
    scenario: "rnd1" | "rnd2" | "rnd3" | "rnd4" | "custom";
    custom_description?: string;
  };
  params: {
    duration_weeks: number; // 1-52 (default: 12)
    pacing: "slow" | "normal" | "fast";
  };
}
WebSocket Message Payloadtypescript
// Sent on each agent message during simulation
interface WebSocketPayload {
  type: "init" | "message" | "completed" | "error" | "typing_start";
  data?: {                     // Agent message data
    id: number;
    round: number;
    agent_id: string;
    agent_name: string;
    type: "public" | "thought" | "system";
    content: string;
    thought?: string;          // Internal thought (hidden insight)
    state_changes?: {
      morale?: number;         // Delta (e.g., -5, +10)
      stress?: number;
      loyalty?: number;
      productivity?: number;
    };
    timestamp: string;
  };
  agents: AgentState[];        // Updated agent states
  metrics: {
    avgMorale: number;
    avgStress: number;
    productivity: number;
    resignations: number;
    avgLoyalty: number;
    teamCohesion: number;      // Composite metric
  };
  worldState?: {               // Dynamic world constraints
    budgetRemaining: number;
    customerSatisfaction: number;
    companyReputation: number;
    teamCapacity: number;
    technicalDebt: number;
    deadlineWeeksLeft: number;
  };
  decisionStatus?: {           // Decision engine state
    proposalCount: number;
    hasDecision: boolean;
    decidedProposal?: string;
    leadingProposal?: string;
    leadingSupport: number;
    escalationCount: number;
    resignThreats: string[];
  };
  currentRound: number;
  totalRounds: number;
  status: "idle" | "running" | "completed";
  metricsHistory?: { round: number; morale: number; stress: number;
                     productivity: number; loyalty: number; cohesion: number; }[];
}
Report Response Modeltypescript
interface ReportResponse {
  simulation_id: string;
  company_name: string;
  crisis_name: string;
  total_rounds: number;
  completed_rounds: number;
  executive_summary: string;     // AI-generated overview
  critical_finding: string;      // Most critical issue identified
  simulation_overview: string;   // Detailed scenario description
  key_metrics: {
    total_agents: number;
    active_agents: number;
    resignations: number;
    avg_morale: number;
    avg_stress: number;
    avg_loyalty: number;
    avg_productivity: number;
    productivity_drop: number;
    simulation_weeks: number;
    total_planned_weeks: number;
  };
  analysis_insights: string;     // In-depth analysis paragraph
  conclusion: string;            // Final summary
  agent_reports: {
    id: string;
    name: string;
    role: string;
    starting_morale: number;
    ending_morale: number;
    peak_stress: number;
    has_resigned: boolean;
    resigned_week?: number;
    status: "Failed" | "Critical" | "Stressed" | "Stable" | "Thriving";
    status_label: string;        // e.g., "Resigned • Week 9"
  }[];
  productivity_drop: number;
  recommendations: string[];     // 3-5 AI-generated actions
  timeline: {                    // Per-round metrics for charts
    round: number;
    morale: number;
    stress: number;
    output: number;
  }[];
}
WebSocket Streaming
For real-time message streaming during simulations, connect to ws://localhost:8000/ws/simulation/{id}. The simulation runs as a background task — disconnecting does NOT stop the simulation. Reconnect anytime to resume viewing.
Multi-LLM Provider Support
The backend supports three LLM providers configured via the LLM_PROVIDER env variable: OpenAI (gpt-4o-mini, gpt-4o), Google Gemini (gemini-2.0-flash), and OpenRouter (any model including free options like Llama 3.1 8B).

Ready to simulate?

Configure your team, inject a crisis, and discover the breaking point of your organization — complete with hidden agendas, random events, and dramatic outcomes.