Skip to Content
DocsConceptsTriggers

Triggers

Triggers define when and how agents run automatically. Instead of manually running agents, triggers let them respond to events, run on schedules, or execute based on specific conditions.

What Are Triggers?

A trigger is an automated execution rule for an agent. Triggers enable agents to:

  • Run on a schedule (hourly, daily, weekly)
  • Respond to document events (creation, updates, submissions)
  • Execute with specific conditions
  • Maintain per-user conversation history

Without triggers, you manually run agents. With triggers, agents become proactive automation.

Trigger Types

1. Manual Execution

How it works: You run the agent yourself

Methods:

  • Agent Chat: Real-time chat interface
  • Agent DocType: “Run” button in the form
  • API: Call run_agent_sync programmatically

Use Cases:

  • Testing agents
  • On-demand tasks
  • User-initiated interactions
  • Development and debugging

No trigger configuration needed—just run the agent when you want.

2. Scheduled Triggers

How it works: Agent runs automatically at specified intervals

Configuration: Set up via Agent Trigger DocType

Frequencies:

  • Hourly: Every hour
  • Daily: Once per day at specified time
  • Weekly: Specific day(s) of the week
  • Custom Cron: Advanced scheduling with cron expressions

Use Cases:

  • Daily report generation
  • Hourly inventory checks
  • Weekly summarization tasks
  • Periodic data synchronization
  • Scheduled notifications

Example:

Agent: Daily Sales Summary Trigger: Every day at 9:00 AM Action: Generates sales report and sends via email

3. Document Event Triggers

How it works: Agent runs when specific document events occur

Events:

  • After Insert: Document is created
  • On Update: Document is modified
  • On Submit: Submittable document is submitted
  • On Cancel: Document is cancelled
  • Before Save: Before document is saved (use carefully)
  • After Delete: Document is deleted (use rarely)

Use Cases:

  • Validate invoices on submission
  • Auto-assign leads when created
  • Notify team when deals update
  • Quality check on document submission
  • Enrich data on creation

Example:

Agent: Invoice Validator Trigger: After Submit on DocType "Sales Invoice" Action: Validates pricing, checks credit limits, flags issues

4. Chat-Based Execution

How it works: User interacts via chat interface

Enable: Set allow_chat = 1 in Agent DocType

Access:

  • Desk: Agent Chat DocType
  • Frontend: /huf interface (expanding)

Use Cases:

  • Customer support
  • Interactive assistants
  • Conversational workflows
  • User-facing agents

No separate trigger needed—enabled on the agent itself.

5. API Execution

How it works: External systems call agent via API

Endpoint: run_agent_sync (whitelisted method)

Authentication: Standard Frappe API authentication

Use Cases:

  • Webhook integrations
  • External app automation
  • Custom frontends
  • Third-party service integration

Example:

response = requests.post( "https://yoursite.com/api/method/huf.ai.agent_integration.run_agent_sync", headers={"Authorization": f"token {api_key}:{api_secret}"}, json={ "agent_name": "Customer Support Agent", "prompt": "What is the status of order SO-001?", "session_id": "api:external_system:12345" } )

Agent Trigger DocType

Scheduled and document event triggers are configured via Agent Trigger.

Navigate to: Desk → Huf → Agent Trigger

Key Fields

FieldDescription
AgentWhich agent to run
Trigger TypeSchedule or Doc Event
Reference DocTypeFor doc events, which DocType
Document EventWhich event (After Insert, On Submit, etc.)
ConditionOptional filter conditions
ScheduleFor scheduled triggers, the frequency/time
Prompt TemplateWhat message to send to the agent
EnabledActive/inactive toggle

Creating a Trigger

  1. Navigate to Agent Trigger, click New
  2. Select Agent from dropdown
  3. Choose Trigger Type:
    • Doc Event: For document-based automation
    • Schedule: For time-based execution
  4. Configure Details (see below)
  5. Set Prompt Template (what to tell the agent)
  6. Enable and Save

Scheduled Trigger Configuration

Setting the Schedule

Frequency Options:

  • Hourly: Runs every hour
  • Daily: Specify time (e.g., “09:00”)
  • Weekly: Choose day(s) and time
  • Cron: Advanced cron expression

Examples:

Daily at 9 AM: "0 9 * * *" Every Monday at 2 PM: "0 14 * * 1" Every 30 minutes: "*/30 * * * *" First day of month: "0 0 1 * *"

Prompt Templates for Scheduled Triggers

Use templates to pass context to the agent:

Generate a summary of today's sales and send it to the sales team.

Or with dynamic data:

Check inventory levels and alert if any items are below reorder point. Focus on fast-moving items from the last 7 days.

Example Trigger:

Agent: Inventory Monitor Schedule: Every day at 8:00 AM Prompt: "Check inventory for items below reorder level and create purchase requisitions if needed. Prioritize high-demand items."

Document Event Trigger Configuration

Selecting the DocType

Choose which DocType to monitor:

  • Reference DocType: The DocType name (e.g., “Sales Invoice”, “Lead”, “Support Ticket”)

Selecting the Event

EventWhen It Fires
After InsertDocument is created and saved
On UpdateDocument is modified
On SubmitSubmittable document is submitted
On CancelDocument is cancelled
Before SaveBefore save (can prevent save with errors)
After DeleteAfter document is deleted

Most Common: After Insert, On Submit, On Update

Conditional Execution

Run triggers only when conditions match:

Condition Field: JSON filter object

Example Conditions:

{ "status": "Open", "priority": "High" }

→ Only triggers if document status is “Open” AND priority is “High”

{ "grand_total": [">", 10000] }

→ Only triggers if grand_total exceeds 10,000

{ "customer_group": ["in", ["Wholesale", "Distributor"]] }

→ Only triggers for specific customer groups

No condition = triggers on every matching event

Prompt Templates for Doc Event Triggers

Access document fields in the prompt using {field_name} placeholders:

A new lead has been created: {lead_name} from {company_name}. Please review the lead, score it based on our criteria, and assign it to the appropriate sales rep. Lead Details: - Email: {email_id} - Source: {source} - Territory: {territory}

Available Data:

  • All fields from the document
  • Standard fields (name, creation, modified, owner, etc.)
  • Linked document data (may need tool calls)

Example:

Agent: Lead Qualifier DocType: Lead Event: After Insert Prompt: "A new lead was created: {lead_name} from {company_name} in {territory}. Score this lead, assign to appropriate sales rep, and set next follow-up date."

Conversation Modes for Triggers

Per-User Conversation

Default behavior (persist_user_history = 1):

  • Each triggering user gets separate conversation history
  • Useful for user-specific context
  • Privacy preserved between users

Example:

Support Ticket Agent (On Submit): - User A submits ticket → Separate conversation for User A - User B submits ticket → Separate conversation for User B - Each user's history is independent

Shared Conversation

Shared mode (persist_user_history = 0):

  • Single conversation history across all trigger executions
  • Agent builds cumulative knowledge
  • All users share the same context

Example:

Daily Sales Summary (Scheduled): - Day 1: Agent generates report - Day 2: Agent remembers Day 1, compares trends - Day 3: Agent builds on previous days' data - Cumulative learning across runs

Configuration: In Agent DocType:

  • Persist Conversation: Enable to keep history
  • Persist per User (Doc/Schedule): Check for per-user, uncheck for shared

Trigger Best Practices

Scheduling

Do:

  • Run during off-peak hours for heavy tasks
  • Stagger multiple agents to avoid overlap
  • Use reasonable frequencies (don’t over-schedule)
  • Monitor costs of scheduled runs

Don’t:

  • Schedule too frequently (every minute)
  • Run multiple heavy agents simultaneously
  • Forget timezone considerations
  • Ignore failed runs

Document Events

Do:

  • Use specific events (not every event)
  • Add conditions to limit executions
  • Handle errors gracefully
  • Test with draft documents first

Don’t:

  • Trigger on every update (can cause loops)
  • Use Before Save unless necessary
  • Forget permission checks
  • Create infinite trigger loops

Prompt Templates

Do:

  • Be specific about the task
  • Include relevant document fields
  • Provide clear instructions
  • Mention expected outputs

Don’t:

  • Use vague prompts
  • Forget to test with real data
  • Include sensitive data unnecessarily
  • Assume agent knows document structure

Error Handling

Monitor:

  • Check Agent Run logs regularly
  • Set up failure notifications
  • Review errors and adjust prompts
  • Test trigger conditions thoroughly

Common Use Cases

1. Automated Lead Assignment

Trigger: After Insert on Lead Agent: Lead Router Prompt:

New lead: {lead_name} from {territory}. Assign to the best sales rep based on: - Territory coverage - Current workload - Specialization in {industry} Update the lead with assigned rep and next follow-up date.

2. Invoice Validation

Trigger: On Submit on Sales Invoice Agent: Invoice Validator Prompt:

Validate this invoice: - Check pricing against price list - Verify credit limit for customer {customer} - Confirm tax calculations - Flag any anomalies If issues found, add comment and notify accounts team.

3. Daily Report Generation

Trigger: Schedule (Daily at 9 AM) Agent: Sales Report Generator Prompt:

Generate daily sales summary: - Total orders and revenue - Top 5 customers - Pending payments - Trends vs yesterday Send report to sales@company.com

4. Support Ticket Routing

Trigger: After Insert on Support Ticket Agent: Ticket Router Prompt:

New ticket: {subject} Priority: {priority} Analyze the issue and: - Assign to appropriate team - Set SLA deadline - Add initial response if simple - Escalate if high priority

5. Inventory Monitoring

Trigger: Schedule (Every 6 hours) Agent: Inventory Monitor Prompt:

Check all items with stock below reorder level. For each item: - Calculate required quantity - Create purchase requisition - Notify procurement team Focus on fast-moving items.

Troubleshooting

Trigger doesn’t fire:

  • Verify trigger is Enabled
  • Check Condition matches document
  • Review DocType and Event selection
  • Check agent is active
  • Verify no Frappe permission issues

Trigger fires too often:

  • Add more specific conditions
  • Change from “On Update” to “On Submit”
  • Review document workflow
  • Check for trigger loops

Agent gets wrong data:

  • Verify prompt template field names
  • Check document state at trigger time
  • Test field access and permissions
  • Review tool assignments

High costs from triggers:

  • Reduce trigger frequency
  • Add stricter conditions
  • Use cheaper models for simple triggers
  • Limit conversation history length

Performance issues:

  • Stagger scheduled triggers
  • Use background jobs for heavy tasks
  • Optimize agent tools
  • Monitor Agent Run duration

What’s Next?

Now that you understand triggers:


Need help with triggers? Check GitHub discussions .

Last updated on