Skip to content
Part 6

The Specialist Team — Multi-Agent Orchestration

One Agent Isn't Enough

The Availability Agent is useful, but it has blind spots. It can tell you Dylan is available Thursday, but it doesn't know that Dylan has already worked five shifts this week and giving him a sixth would be unfair. It doesn't know that Marcus has had closing shifts three weeks running. It doesn't check whether the store actually has enough people on Saturday.

Each of these is a different kind of reasoning. And each one deserves its own specialist.

Constraints: The Rules Behind Every Schedule

A week at Fabulosa has 21 shifts and eight people who could fill them. Most of the possible schedules are wrong, and some are only worse than others. Constraints are the rules that tell them apart, and the app handles them in two different ways.

Hard constraints can never be broken. A schedule that breaks one is invalid, no matter how good it looks otherwise:

Hard constraint Where the app enforces it
One person per shift The database: the UNIQUE rule on the schedule table (Part 4) makes a second assignment replace the first
Only real shifts and days The assignShift tool's Zod schema: shift must be opening, mid, or closing; day must be 0–6. The model can't call the tool with anything else
No one works two shifts in a day checkAvailability leaves out anyone already scheduled that day, and validateCoverage flags double-booking if it slips through
All 21 shifts filled validateCoverage lists every gap

Soft constraints are preferences. Breaking one makes a schedule worse, not invalid, and they often pull against each other:

  • Total shifts roughly equal across regular staff
  • Closing shifts rotate instead of landing on the same person
  • Saturdays, which run an hour longer, are shared
  • On-call staff only when regular staff can't cover
  • Alvin and Melissa aren't overloaded

These live in the Fairness Agent's instructions, and its getMultiWeekHistory tool turns past weeks into notes like “Marcus has closed 3 times in 3 weeks.”

Why two homes? Hard constraints go in code because a prompt is a request, not a guarantee: a model can be argued out of a rule in its instructions, but not out of a database constraint or a schema. Soft constraints go in prompts because they need judgment. Maybe Marcus has closed three weeks running because he asked for evenings. Code can count, but only a reasoning step can weigh that.

How they work together. Ask the coordinator to “find someone to cover Tuesday closing,” and each kind of constraint gets its turn:

  1. Filter (hard): the Availability Agent drops Marcus, who already opens Tuesday.
  2. Rank (soft): the Fairness Agent sees Dylan has closed least this month and suggests him.
  3. Commit (hard): assignShift writes the shift; the schema and the database reject anything invalid.
  4. Verify (hard): the Coverage Agent confirms Tuesday has no gaps or double-booking.

When the rules can't all be met (three people out sick, say), hard constraints win and soft ones give way, and the coordinator says which preferences it had to break. Part 7 builds that into the instructions.

Try it: add a hard constraint of your own. Many stores ban the “clopening,” closing one night and opening the next morning. Add it to the coverage check:

// lib/tools/coverage-tools.ts — inside validateCoverageTool's execute,
// after the double-booking check

// No "clopening": closing one night, then opening the next morning
for (let day = 0; day < 6; day++) {
  const closer = schedule.find(s => s.day_of_week === day && s.shift_type === 'closing')
  const opener = schedule.find(s => s.day_of_week === day + 1 && s.shift_type === 'opening')
  if (closer?.employee_name && closer.employee_name === opener?.employee_name) {
    issues.push(`${closer.employee_name} closes day ${day} and opens day ${day + 1}`)
  }
}

Then add a line to the Coverage Agent's rules so it explains the new issue, and ask the coordinator to check this week.

The Fairness Agent

Step 40: Create the fairness tools

Create lib/tools/fairness-tools.ts:

// lib/tools/fairness-tools.ts

import { tool } from 'ai'
import { z } from 'zod'
import { getWeekSchedule, getAllEmployees } from '@/lib/db'
import { getDateFromDayOfWeek, getWeekStartDate } from '@/lib/utils'

export const getShiftDistributionTool = tool({
  description: 'Analyze how shifts are distributed across employees for a given week.',
  inputSchema: z.object({
    weekStart: z.string().describe('Week start date (Sunday) in YYYY-MM-DD format'),
  }),
  execute: async ({ weekStart }) => {
    const [employees, schedule] = await Promise.all([
      getAllEmployees(), getWeekSchedule(weekStart),
    ])

    const distribution: Record<string, {
      total: number; opening: number; mid: number; closing: number
    }> = {}

    employees.forEach(emp => {
      distribution[emp.name] = { total: 0, opening: 0, mid: 0, closing: 0 }
    })

    schedule.forEach(entry => {
      if (entry.employee_name && distribution[entry.employee_name]) {
        distribution[entry.employee_name].total++
        distribution[entry.employee_name][entry.shift_type as 'opening' | 'mid' | 'closing']++
      }
    })

    return { weekStart, distribution }
  },
})

export const getMultiWeekHistoryTool = tool({
  description: 'Get shift history across multiple weeks for fairness analysis.',
  inputSchema: z.object({
    weekStart: z.string()
      .describe('The week being planned (Sunday, YYYY-MM-DD); history covers the weeks before it'),
    weeksBack: z.number().min(1).max(8)
      .describe('Number of past weeks to analyze (1-8)'),
  }),
  execute: async ({ weekStart, weeksBack }) => {
    // The Sundays of the previous weeksBack weeks, most recent first
    const weeks = Array.from({ length: weeksBack }, (_, i) =>
      getWeekStartDate(getDateFromDayOfWeek(weekStart, -7 * (i + 1)))
    )
    const [employees, ...schedules] = await Promise.all([
      getAllEmployees(), ...weeks.map(getWeekSchedule),
    ])

    const history: Record<string, {
      totalShifts: number; closingShifts: number; saturdayShifts: number
    }> = {}
    employees.forEach(emp => {
      history[emp.name] = { totalShifts: 0, closingShifts: 0, saturdayShifts: 0 }
    })
    for (const schedule of schedules) {
      for (const entry of schedule) {
        const h = entry.employee_name ? history[entry.employee_name] : undefined
        if (!h) continue
        h.totalShifts++
        if (entry.shift_type === 'closing') h.closingShifts++
        if (entry.day_of_week === 6) h.saturdayShifts++
      }
    }

    // Flag the imbalances the agent should look at first. Regular staff only:
    // on-call staff are meant to work less.
    const regular = employees.filter(emp => !emp.is_on_call)
    const average = regular.reduce((n, emp) => n + history[emp.name].totalShifts, 0)
      / Math.max(regular.length, 1)
    const fairnessNotes: string[] = []
    for (const emp of regular) {
      const h = history[emp.name]
      if (h.totalShifts > average + 2)
        fairnessNotes.push(`${emp.name} worked ${h.totalShifts} shifts (team average ${average.toFixed(1)})`)
      if (h.totalShifts < average - 2)
        fairnessNotes.push(`${emp.name} worked only ${h.totalShifts} shifts (team average ${average.toFixed(1)})`)
      if (weeksBack >= 2 && h.closingShifts >= weeksBack)
        fairnessNotes.push(`${emp.name} has closed ${h.closingShifts} times in ${weeksBack} weeks`)
    }

    return { weeks, history, fairnessNotes }
  },
})
Step 41: Create the Fairness Agent

Create lib/agents/fairness-agent.ts:

// lib/agents/fairness-agent.ts

import { ToolLoopAgent, InferAgentUIMessage } from 'ai'
import { getShiftDistributionTool, getMultiWeekHistoryTool } from '../tools/fairness-tools'

export const fairnessAgent = new ToolLoopAgent({
  model: 'anthropic/claude-sonnet-5.5',
  instructions: `You are the Fairness Agent for Fabulosa Books.

Your job is to analyze whether shift assignments are equitable
across employees. Fabulosa Books cares deeply about treating
everyone fairly — this is a core value of the store.

Fairness principles:
- Total shifts should be roughly equal across regular staff
- No one should get stuck with closing shifts repeatedly — rotate them
- Saturday shifts (which run an extra hour) should be shared
- On-call staff should only be used when regular staff can't cover
- Alvin and Melissa should not be disproportionately burdened

When asked to evaluate fairness, always check the multi-week history —
a single week snapshot can be misleading. Look for patterns over 3-4 weeks.

Be specific: don't just say "distribute more evenly" — say "Give Dylan
a closing shift this week since Marcus has had closing three weeks in a row."`,
  tools: {
    getShiftDistribution: getShiftDistributionTool,
    getMultiWeekHistory: getMultiWeekHistoryTool,
  },
})

Notice how the instructions encode Fabulosa's values, not just rules. The agent knows that fairness matters to the store's identity.

The Coverage Agent

Step 42: Create the coverage tools

Create lib/tools/coverage-tools.ts:

// lib/tools/coverage-tools.ts

import { tool } from 'ai'
import { z } from 'zod'
import { getWeekSchedule } from '@/lib/db'

export const validateCoverageTool = tool({
  description: 'Validate whether a week\'s schedule meets all staffing requirements.',
  inputSchema: z.object({
    weekStart: z.string().describe('Week start date (Sunday) in YYYY-MM-DD format'),
  }),
  execute: async ({ weekStart }) => {
    const schedule = await getWeekSchedule(weekStart)

    const gaps: { day: number; shift: string }[] = []
    const issues: string[] = []

    for (let day = 0; day < 7; day++) {
      for (const shift of ['opening', 'mid', 'closing']) {
        const entry = schedule.find(
          s => s.day_of_week === day && s.shift_type === shift
        )
        if (!entry || !entry.employee_name) {
          gaps.push({ day, shift })
        }
      }
    }

    // Check for double-booking
    for (let day = 0; day < 7; day++) {
      const dayEntries = schedule.filter(s => s.day_of_week === day && s.employee_name)
      const names = dayEntries.map(s => s.employee_name)
      const duplicates = names.filter((name, i) => names.indexOf(name) !== i)
      if (duplicates.length > 0) {
        issues.push(`Double-booked on day ${day}: ${[...new Set(duplicates)].join(', ')}`)
      }
    }

    return {
      weekStart, isFullyCovered: gaps.length === 0,
      gaps, issues,
      totalAssigned: schedule.filter(s => s.employee_name).length,
      totalSlots: 21,
    }
  },
})
Step 43: Create the Coverage Agent
// lib/agents/coverage-agent.ts

import { ToolLoopAgent, InferAgentUIMessage } from 'ai'
import { validateCoverageTool } from '../tools/coverage-tools'

export const coverageAgent = new ToolLoopAgent({
  model: 'anthropic/claude-sonnet-5.5',
  instructions: `You are the Coverage Agent for Fabulosa Books.

Coverage rules:
- Every day must have exactly 3 shifts: opening, mid, closing
- Each shift must have exactly one employee assigned
- No employee should be double-booked (two shifts on the same day)
- A fully covered week = 21 assigned shifts (3 shifts x 7 days)

When reporting gaps, be specific about which day and shift is uncovered.
When reporting issues, explain the impact.`,
  tools: {
    validateCoverage: validateCoverageTool,
  },
})
Three specialist agents: Availability, Fairness, Coverage

The Coordinator: Orchestrating It All

This is the heart of multi-agent orchestration. The Schedule Coordinator is an agent whose tools are the other agents.

Step 44: Create the coordinator agent

Create lib/agents/coordinator-agent.ts:

// lib/agents/coordinator-agent.ts

import { ToolLoopAgent, InferAgentUIMessage, tool } from 'ai'
import { z } from 'zod'
import { availabilityAgent } from './availability-agent'
import { fairnessAgent } from './fairness-agent'
import { coverageAgent } from './coverage-agent'
import { updateSchedule } from '@/lib/db'
import { getTodayTool } from '@/lib/tools/schedule-tools'

// Wrap each specialist as a tool the coordinator can call
const checkAvailabilitySubagent = tool({
  description: 'Ask the Availability Agent about employee availability.',
  inputSchema: z.object({
    question: z.string().describe('The availability question to answer'),
  }),
  execute: async ({ question }) => {
    const result = await availabilityAgent.generate({
      messages: [{ role: 'user', content: question }],
    })
    return { answer: result.text }
  },
})

const checkFairnessSubagent = tool({
  description: 'Ask the Fairness Agent to evaluate shift distribution equity.',
  inputSchema: z.object({
    question: z.string().describe('The fairness question to evaluate'),
  }),
  execute: async ({ question }) => {
    const result = await fairnessAgent.generate({
      messages: [{ role: 'user', content: question }],
    })
    return { answer: result.text }
  },
})

const validateCoverageSubagent = tool({
  description: 'Ask the Coverage Agent to validate staffing.',
  inputSchema: z.object({
    question: z.string().describe('The coverage question to validate'),
  }),
  execute: async ({ question }) => {
    const result = await coverageAgent.generate({
      messages: [{ role: 'user', content: question }],
    })
    return { answer: result.text }
  },
})

const assignShiftTool = tool({
  description: 'Assign an employee to a specific shift.',
  inputSchema: z.object({
    weekStart: z.string(),
    dayOfWeek: z.number().min(0).max(6),
    shiftType: z.enum(['opening', 'mid', 'closing']),
    employeeName: z.string(),
  }),
  execute: async ({ weekStart, dayOfWeek, shiftType, employeeName }) => {
    await updateSchedule(weekStart, dayOfWeek, shiftType, employeeName)
    return { success: true, assigned: `${employeeName} → ${shiftType} on day ${dayOfWeek}` }
  },
})

export const coordinatorAgent = new ToolLoopAgent({
  model: 'anthropic/claude-sonnet-5.5',
  instructions: `You are the Schedule Coordinator for Fabulosa Books.

You coordinate scheduling by delegating to three specialist agents:
1. **Availability Agent** — checks who is free and when
2. **Fairness Agent** — ensures equitable shift distribution
3. **Coverage Agent** — validates store staffing requirements

When handling scheduling requests:
1. First, check availability to understand the current state
2. Then, consult the Fairness Agent to understand distribution patterns
3. Make assignment decisions that balance availability, fairness, and coverage
4. After making assignments, validate coverage to ensure no gaps
5. Report the final result clearly

You can also assign shifts directly using the assignShift tool.

Important guidelines:
- Always consult at least the Availability Agent before making suggestions
- For full schedule creation, consult all three specialists
- Prefer regular staff over on-call staff
- Be transparent about trade-offs
- Present proposed schedules in a table format when possible
- Call getToday before deciding which week the user means, and put the
  week's start date (YYYY-MM-DD) in every question you send a specialist`,
  tools: {
    getToday: getTodayTool,
    checkAvailability: checkAvailabilitySubagent,
    checkFairness: checkFairnessSubagent,
    validateCoverage: validateCoverageSubagent,
    assignShift: assignShiftTool,
  },
})

export type CoordinatorAgentUIMessage = InferAgentUIMessage<typeof coordinatorAgent>

This is the key pattern. The coordinator's tools are the other agents. When it calls checkAvailability, it's actually running the Availability Agent as a subagent—a full agent with its own tools and reasoning loop. The coordinator receives a text summary back, reasons about it, and decides what to do next.

The orchestrator pattern: how the coordinator delegates to specialists

Updating the Chat Route and UI

Step 45: Update the chat API route to use the coordinator
// app/api/chat/route.ts

import { createAgentUIStreamResponse } from 'ai'
import { coordinatorAgent } from '@/lib/agents/coordinator-agent'

export async function POST(request: Request) {
  const { messages } = await request.json()

  return createAgentUIStreamResponse({
    agent: coordinatorAgent,
    uiMessages: messages,
  })
}

One line changed: availabilityAgent → coordinatorAgent. The chat interface is the same, but now the coordinator delegates to all three specialists.

Step 46: Update ChatPanel to show agent activity

Update components/ChatPanel.tsx to handle the coordinator's tool calls. The key upgrade: the chat panel now shows which agent is working. When the coordinator delegates to the Fairness Agent, you see "Fairness Agent" in the response, with a loading indicator while it runs.

// components/ChatPanel.tsx — changes from Part 5

// 1. Type the chat with the coordinator's tools instead of the Availability Agent's
import type { CoordinatorAgentUIMessage } from '@/lib/agents/coordinator-agent'

// 2. A readable name for each tool the coordinator can call
const AGENT_LABELS: Record<string, string> = {
  'tool-checkAvailability': 'Availability Agent',
  'tool-checkFairness': 'Fairness Agent',
  'tool-validateCoverage': 'Coverage Agent',
  'tool-assignShift': 'Assigning Shift',
}

// 3. Accept an onFinish callback (Step 47 uses it) and pass it to useChat
export default function ChatPanel({ onFinish }: { onFinish?: () => void }) {
  const [input, setInput] = useState('')
  const { messages, sendMessage, status } = useChat<CoordinatorAgentUIMessage>({
    transport,
    onFinish,
  })
  const busy = status === 'submitted' || status === 'streaming'
  // ... handleSubmit and the layout stay the same ...

// 4. Replace the message.parts.map(...) switch with:
{message.parts.map((part, i) => {
  if (part.type === 'text') return <span key={i}>{part.text}</span>
  const label = AGENT_LABELS[part.type]
  if (!label || !('state' in part)) return null
  return (
    <div key={i} className="text-xs text-stone-400 italic my-1">
      {part.state === 'output-available' ? `✓ ${label}` : `⏳ ${label} working...`}
    </div>
  )
})}
Step 47: Connect schedule changes back to the grid

Update app/page.tsx so the schedule grid refreshes when the coordinator assigns shifts. A refreshKey state triggers a re-fetch of schedule data after each agent interaction completes.

// components/ScheduleGrid.tsx — two changes from Part 4

// 1. Take a refreshKey prop
export default function ScheduleGrid({ refreshKey = 0 }: { refreshKey?: number }) {

// 2. Re-fetch the week whenever it changes
  useEffect(() => {
    // ... same fetch as before ...
  }, [weekStart, refreshKey])
// app/page.tsx
'use client'

import { useState } from 'react'
import ScheduleGrid from '@/components/ScheduleGrid'
import ChatPanel from '@/components/ChatPanel'

export default function Home() {
  // Bumped after every agent reply, so the grid shows shifts the coordinator assigned
  const [refreshKey, setRefreshKey] = useState(0)

  return (
    <main className="min-h-screen bg-stone-50 p-8">
      <div className="max-w-7xl mx-auto">
        <header className="mb-8">
          <h1 className="text-3xl font-bold text-stone-800">Fabulosa Books</h1>
          <p className="text-stone-500 mt-1">Employee Schedule</p>
        </header>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2">
            <ScheduleGrid refreshKey={refreshKey} />
          </div>
          <div>
            <ChatPanel onFinish={() => setRefreshKey(k => k + 1)} />
          </div>
        </div>
      </div>
    </main>
  )
}
Step 48: Test multi-agent orchestration
npm run dev

Try these prompts:

  • "Is this week's schedule fair?" — The coordinator calls the Availability Agent (to get the current schedule), then the Fairness Agent (to analyze distribution). You'll see both agents activate in the chat panel.
  • "Find someone to cover Tuesday closing" — The coordinator checks availability for Tuesday, checks fairness to pick the best candidate, and suggests an assignment.
  • "Schedule next week" — The full orchestration: availability → fairness → coverage → assignments.
Step 49: Push and deploy
git add -A
git commit -m "Add multi-agent orchestration: Fairness, Coverage, and Coordinator agents"
git push

What You've Built

Take a moment to appreciate what just happened. You've built a multi-agent system where:

  1. A Coordinator Agent receives natural-language scheduling requests
  2. It delegates to an Availability Agent that queries the database
  3. It consults a Fairness Agent that analyzes historical patterns
  4. It validates with a Coverage Agent that checks staffing rules
  5. It synthesizes the results and either makes recommendations or assigns shifts directly
  6. The UI shows the orchestration happening in real-time
  7. The schedule grid updates automatically when shifts are assigned

That's multi-agent orchestration. Not one monolithic AI trying to do everything, but a team of specialists coordinating through a leader—just like Alvin delegates to his team at the bookstore.

Complete multi-agent system architecture deployed on Vercel