Skip to main content

Knowledge > Products > Chatbot > Agents

Chatbot Agents

The chatbot uses 4 marketing agent types, each with specialized personas, domain expertise, and filtered tool sets. Unlike the voice agent (which consolidated to 2 agents to avoid phone silence gaps), the chatbot retains all 4 because chat has no latency penalty for agent routing -- the user simply types and the correct specialist responds.


4 Marketing Agent Types​

Agent TypeDisplay NameTaglineIconChannelsPersonas
coordinatorCoordinator AgentVisitors, events, volunteersUserschat, voicewelcome, new_member, volunteer, youth
careCare AgentPrayer, grief, and pastoral careHeartchat, voicepastoral_care, prayer
stewardshipStewardship AgentGiving, benevolenceHandCoinschat, voicegiving
discipleshipDiscipleship AgentDevotionals, lesson plans, theological deep divesBookOpenchat onlybible_study, sermon_prep, small_group

Source: AGENT_TYPE_META and AGENT_PERSONA_MAP in agent-type-config.ts.

Key Design Decision: Chat Uses 4, Voice Uses 2​

The voice agent merged Stewardship into Coordinator and deferred Discipleship entirely. Rationale:

  • Stewardship on voice: Giving/tithing questions are logistically similar to service times -- callers want a link or an answer, not pastoral depth. The Coordinator handles giving via send_giving_link.
  • Discipleship on voice: Bible study and theological content produces lengthy responses better consumed as text. The voice agent keeps calls short and action-oriented.
  • On chat, all 4 agents remain because text-based conversation supports long-form answers, link sharing, and formatted content (devotionals, lesson plans, theological analysis).

Tier Availability​

Plan tier determines which agents a church can activate:

Plan TierAvailable Agents
StarterCoordinator + Care (2 agents)
ProCoordinator + Care + Stewardship + Discipleship (all 4)
SuiteAll 4 + custom agents (future)

Source: TIER_AGENTS in agent-type-config.ts.

When a church has not customized their agent config (no saved organization_settings.agent_config), all plan-allowed agents default to enabled. Agents outside the plan are force-disabled regardless of saved config, but their customization (personality, handoff rules) is preserved for upgrade.


Agent-to-Persona Mapping​

Each marketing agent type maps to one or more specialized personas. Personas are the fine-grained specialist identities defined in persona-templates.ts, each with its own system prompt, domain ruleset, personality defaults, and tool whitelist.

coordinator --> welcome (4 personas)
new_member
volunteer
youth

care --> pastoral_care (2 personas)
prayer

stewardship --> giving (1 persona)

discipleship --> bible_study (3 personas)
sermon_prep
small_group

Total: 10 personas across 4 agent types.

Reverse Lookup​

getMarketingAgentForPersona(personaType) returns the parent marketing agent type for any persona. Used by the care hub and admin UI to group personas under their agent.


System Prompt Construction (5 Layers)​

The chatbot system prompt is assembled in layers. The base layer is built in route.ts; the agent-specific layers are built by buildAgentSystemPrompt() in agent-prompts.ts.

Layer 1: BASE (built in route.ts)​

Church-specific facts injected into every conversation regardless of agent type:

  • Church name, denomination, address, phone, website, email
  • Service times, mission statement, what-to-expect details
  • RAG context from the church's knowledge base (unified_rag_content embeddings)
  • Product knowledge from product_knowledge table
  • Contact capture protocol (when and how to ask for visitor info)
  • Safety protocol (crisis escalation, mandatory reporting)
  • Theological lens name and ID (from sai_theological_lenses)

Layer 2: AGENT PERSONA (from persona-templates.ts)​

The persona's system prompt and description. Each persona template includes:

  • name -- display name (e.g. "Pastoral Care Specialist")
  • description -- one-line summary
  • systemPrompt -- detailed behavioral instructions specific to the persona's domain
  • personality -- default personality settings (tone, formality, responseLength, emojiUsage, specialInstructions)

Layer 3: DOMAIN RULESET (from DOMAIN_RULESETS in agent-prompts.ts)​

Professional methodology injected per persona type. Each ruleset is 300-500 words of domain-specific training:

PersonaDomain RulesetKey Frameworks
pastoral_careGrief & Crisis CareWorden's 4 Tasks of Mourning, Dual Process Model (Stroebe & Schut), Reflective Listening Protocol, Lament Theology, Crisis Response Protocol, Grief Timeline Sensitivity. Includes explicit "NEVER SAY" list (no "they're in a better place," "God needed another angel," etc.)
welcomeVisitor WelcomeThom Rainer's visitor research (8-11 minute decision window), Eliminate Insider Language guide, Three Visitor Fears (fitting in, kid safety, embarrassment), Progressive Engagement Model (Attend-Connect-Belong-Serve), Cultural Sensitivity protocol
prayerPrayer MinistryACTS Framework (Adoration-Confession-Thanksgiving-Supplication), Listening Prayer Approach, Confidentiality as Sacred protocol, Avoid Prayer Cliches list, When NOT to Pray Immediately guidelines
youthYouth MinistrySafe Sanctuaries / MinistrySafe Protocol (two-adult rule, mandatory reporting), Developmental Awareness (middle school vs high school), OARS Technique (Motivational Interviewing), Mental Health Literacy (warning signs, crisis resources: 988, Crisis Text Line), Digital Native Awareness
bible_studyBible StudyInductive Bible Study (OIA method), Historical-Grammatical Method, Theological Triage (Al Mohler: first/second/third order), Socratic Questioning, Multiple Translations guidance
sermon_prepSermon PreparationHaddon Robinson's Big Idea, Exegetical Rigor protocol, Multiple Homiletical Forms (deductive/inductive/narrative), Illustration Principles, Application Guidelines
small_groupSmall Group LeadershipTuckman's group dynamics (Forming-Storming-Norming-Performing), Facilitation Not Teaching (leader talks <30%), Managing Group Dynamics, Conflict as Growth
new_memberNew Member IntegrationRainer/Stetzer assimilation research (6 connections in 6 months), Progressive Discipleship Pathway (Believe-Belong-Become-Build), No-Pressure Principle, Handling Different Backgrounds
volunteerVolunteer CoordinationGift-Based Placement, Volunteer Lifecycle (Recruit-Equip-Deploy-Support-Appreciate-Re-engage), Burnout Prevention, Never Guilt policy
givingGiving & StewardshipBiblical Stewardship Theology, Generosity Research (Notre Dame), Never Guilt Never Pressure policy, Practical Guidance (online giving, tax receipts), Professional Advice Boundary (deflect financial/legal/medical advice to qualified professionals)

Layer 4: PERSONALITY (from buildPersonalityInstructions())​

Tone and style directives derived from the persona template's defaults, with optional admin overrides applied on top:

Configurable fields:

FieldOptionsEffect
tonewarm, empathetic, encouraging, professional, pastoral, friendly, authoritative, gentle, energeticControls emotional register of responses
formalitycasual, moderate, formalControls language register (contractions, sentence structure)
responseLengthconcise, moderate, thoroughControls paragraph count (1-2, 2-3, or 2-4 paragraphs)
emojiUsagenone, minimal, moderate, frequentControls emoji presence in responses
specialInstructionsfree textTemplate-level special instructions
customInstructionsfree textAdmin-provided custom instructions (appended after everything else)

Override precedence: admin overrides > template defaults. If an admin sets tone: "professional" for the Care agent, it replaces the template's tone: "empathetic".

Source: PersonalityOverrides type in agent-type-config.ts.

Layer 5: TOOL INSTRUCTIONS (from buildToolInstructions())​

Filtered tool list with natural-language invocation guidance:

=== YOUR TOOLS ===
You have tools available to take action. Use them when the moment is right:
- When someone shares a prayer need -> submit_prayer_request (after showing empathy first)
- When someone asks about directions or parking -> get_church_directions
- When someone makes threats or shows self-harm signals -> flag_safety_concern IMMEDIATELY
...
IMPORTANT: Don't announce that you're "using a tool." Just do it naturally.

The tool list is the intersection of church-enabled tools AND the persona's tool whitelist (AGENT_TOOL_MAP).


Personality Overrides​

Churches configure agent personality via the admin Settings tab. Configuration is stored in organization_settings.agent_config as JSONB:

{
"care": {
"enabled": true,
"voiceId": null,
"personalityOverrides": {
"tone": "empathetic",
"formality": "moderate",
"responseLength": "thorough",
"emojiUsage": "minimal",
"customInstructions": "Always mention our GriefShare program when someone mentions loss."
},
"handoffRules": {
"discipleship": {
"enabled": true,
"customMessage": "I think our Discipleship specialist might be a better fit for this question."
},
"humanEscalation": {
"contactName": "Pastor Mike",
"contactMethod": "call the church office at 555-0123",
"whenToEscalate": "someone mentions suicidal thoughts, domestic violence, or child abuse"
}
}
},
"coordinator": { "enabled": true },
"discipleship": { "enabled": true },
"stewardship": { "enabled": false }
}

Validation Constants​

Personality fields are validated against allowlists:

  • Tones: warm, empathetic, encouraging, professional, pastoral, friendly, authoritative, gentle, energetic
  • Formality: casual, moderate, formal
  • Response length: concise, moderate, thorough
  • Emoji usage: none, minimal, moderate, frequent

Source: VALID_TONE_VALUES, VALID_FORMALITY_VALUES, etc. in agent-type-config.ts.


Handoff Rules​

Agent handoff configuration controls how agents transfer conversations to other agents or escalate to humans.

Agent-to-Agent Handoff​

Each agent can be configured to hand off to other agent types when the conversation shifts domains:

type HandoffTarget = {
enabled: boolean; // Whether this handoff is active
customMessage: string; // What the agent says when handing off
};

Example: Care agent detects a giving question and says "I think our Stewardship specialist might be a better fit for this question" before routing to the Stewardship agent.

Human Escalation​

Every agent can be configured with a human escalation trigger:

type HumanEscalationConfig = {
contactName: string; // "Pastor Mike"
contactMethod: string; // "call the church office at 555-0123"
whenToEscalate: string; // "mentions suicidal thoughts, domestic violence, or child abuse"
};

When the escalation condition is met, the agent provides the contact information and encourages the visitor to reach out to the human directly. The agent does NOT end the conversation -- it continues to be available while making the human contact clear.


How Agent Routing Works​

The routing flow in the chatbot chat endpoint (route.ts):

1. Request arrives with optional `agentType` parameter

2. Resolve agent type:
a. If agentType provided:
- Check if it's a valid CareAgentType (direct match)
- Check if it's a URL slug that maps to a type (getCareAgentBySlug)
- Check if it's a super-agent key (care_support, visitor_guide, etc.)
b. If not provided: no agent specialization (generic chatbot behavior)

3. Load church config from organization_settings:
- agent_tool_config.chatbot_tools -> enabledChatbotTools
- agent_config -> personality overrides + handoff rules for this agent

4. Filter tools:
effectiveTools = enabledChatbotTools.filter(t => AGENT_TOOL_MAP[agentType].includes(t))

5. Build system prompt:
basePrompt (church facts, RAG, safety)
+ buildAgentSystemPrompt(agentType, effectiveTools, personalityOverrides, handoffRules)

6. Set model parameters:
getModelParams(agentType) -> { temperature, max_tokens }

7. Call LLM with assembled prompt + tool definitions

Model Parameters by Persona​

Each persona has tuned temperature and max_tokens settings:

PersonaTemperatureMax TokensRationale
pastoral_care0.6500Moderate creativity, enough space for empathy
welcome0.8400Higher creativity for warm, varied greetings
prayer0.65500Slightly creative for personalized prayer responses
new_member0.75400Balanced for progressive engagement guidance
youth0.85400Highest creativity for relatable, natural youth conversation
bible_study0.5700Lower temperature for theological accuracy, more tokens for depth
sermon_prep0.5800Lowest temperature + most tokens for scholarly rigor
small_group0.7400Moderate for facilitation guidance
volunteer0.75400Balanced for gift-based placement conversations
giving0.6400Moderate -- sensitive topic needs consistency

Default (no agent): temperature 0.75, max_tokens 450.

Source: MODEL_PARAMS in agent-prompts.ts.


Super Agents​

For churches that prefer fewer, broader agents instead of 10 specialists, the system supports "super agents" that combine multiple persona tool sets and rulesets:

Super Agent KeyConstituent PersonasUse Case
care_supportpastoral_care + prayerCombined pastoral care specialist
visitor_guidewelcome + new_memberCombined visitor experience agent
ministry_hubsmall_group + volunteer + givingCombined ministry engagement agent
teachingbible_study + sermon_prepCombined theological teaching agent

Super agent behavior:

  • Tools: Union of all constituent persona tool lists
  • Domain rulesets: All constituent rulesets concatenated
  • Personality: First constituent's personality used as primary, with admin overrides applied
  • Model parameters: Averaged across constituents (temperature and max_tokens)

Source: SUPER_AGENTS in agent-prompts.ts.


Config Resolution​

resolveAgentConfig(saved, planTier) merges saved church config with plan-tier limits:

  1. Start with all agents disabled
  2. For each agent type:
    • If agent is NOT in the plan's allowed list: force disabled, but preserve saved customization (personality, handoff rules, voice ID) for when the church upgrades
    • If agent IS allowed AND church has saved config: use saved enabled/disabled state + all saved customization
    • If agent IS allowed AND no saved config: default to enabled

This means:

  • A Starter church cannot enable Stewardship or Discipleship, even if they save config for them
  • If a Starter church upgrades to Pro, their previously-saved Discipleship personality config takes effect immediately
  • A church on any plan can disable agents they don't want (e.g., disable Care if they have no prayer ministry)

Source: resolveAgentConfig() in agent-type-config.ts.


Code References​

  • Agent type definitions and tier mapping: churchwiseai-web/src/lib/agent-type-config.ts
  • Persona templates (system prompts, personality defaults): churchwiseai-web/src/lib/persona-templates.ts
  • Domain rulesets and prompt construction: churchwiseai-web/src/lib/agent-prompts.ts
  • Agent-to-tool mapping: churchwiseai-web/src/lib/agent-prompts.ts -- AGENT_TOOL_MAP
  • Tool-to-agent mapping: churchwiseai-web/src/lib/tool-config.ts -- TOOL_AGENT_MAP
  • Chat route (wiring): churchwiseai-web/src/app/api/chatbot/stream/route.ts
  • Admin agent settings UI: churchwiseai-web/src/app/admin/[token]/ (Settings tab)