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. With triggers, an agent can run on a schedule such as hourly or daily, react to document lifecycle events like creation or submission, filter executions through conditions, and keep separate conversation histories for each user. These capabilities turn agents from on-demand tools into proactive automation.
Trigger Types
Triggers fall into five broad categories depending on who or what starts them and whether they run inside the product or from an external system.
1. Manual Execution
Manual execution puts you in direct control: you run the agent exactly when you need it, without any trigger configuration. You can start it through the real-time Agent Chat, click Run on the Agent DocType form, or call the run_agent_sync method from your own code. This is the best option for testing an agent, handling one-off tasks, supporting user-initiated interactions, and debugging behavior.
2. Scheduled Triggers
Scheduled triggers make an agent run repeatedly at fixed intervals. They are useful when an agent needs to produce recurring output without anyone remembering to start it, such as daily reports or periodic health checks. They are configured through the Agent Trigger DocType.
| Frequency | Description |
|---|---|
| Hourly | Runs every hour |
| Daily | Runs once per day at a specified time |
| Weekly | Runs on selected day(s) of the week |
| Custom Cron | Advanced scheduling using a cron expression |
Common use cases include daily report generation, hourly inventory checks, weekly summarization tasks, periodic data synchronization, and scheduled notifications.
Example:
3. Document Event Triggers
Document event triggers react to changes in Frappe documents, so agents can validate, route, or enrich records as they move through a workflow. This lets automation stay tightly coupled to the business data it acts on.
| Event | Description |
|---|---|
| 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) |
Typical use cases include validating invoices on submission, auto-assigning leads when they are created, notifying the team when deals update, running quality checks on document submission, and enriching data on creation.
Example:
4. Chat-Based Execution
Chat-based execution lets users talk to an agent through a chat interface. To enable it, set allow_chat = 1 on the Agent DocType. The agent can then be reached from the Agent Chat DocType in Desk and from the /huf frontend interface, which is being expanded. This mode is useful for customer support, interactive assistants, conversational workflows, and any user-facing agent.
5. API Execution
API execution lets external systems invoke an agent over HTTP. The agent exposes the whitelisted run_agent_sync method, and requests use standard Frappe API authentication. This is the right choice for webhook integrations, external app automation, custom frontends, and third-party service integration.
Endpoint: run_agent_sync (whitelisted method)
Authentication: Standard Frappe API authentication
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 both configured through the Agent Trigger DocType. To create or manage them, go to Desk → Huf → Agent Trigger.
Key Fields
The Agent Trigger form contains the fields that decide which agent runs, when it runs, and what instructions it receives.
| Field | Description |
|---|---|
| Agent | Which agent to run |
| Trigger Type | Schedule or Doc Event |
| Reference DocType | For doc events, which DocType |
| Document Event | Which event (After Insert, On Submit, etc.) |
| Condition | Optional filter conditions |
| Schedule | For scheduled triggers, the frequency/time |
| Prompt Template | What message to send to the agent |
| Enabled | Active/inactive toggle |
Creating a Trigger
To set up a new trigger, open Agent Trigger and click New, then fill out the form and save. The process is:
Scheduled Trigger Configuration
Scheduled triggers need a frequency or cron expression and a prompt that tells the agent what to do each time it runs.
Setting the Schedule
Scheduled triggers rely on a frequency or cron expression to decide when the agent wakes up. Choose the option that matches how often the task needs to run.
| Frequency Option | When It Runs |
|---|---|
| Hourly | Runs every hour |
| Daily | Specify a time such as "09:00" |
| Weekly | Choose day(s) and a time |
| Cron | Advanced scheduling with a 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
The prompt template tells a scheduled agent what to do each time it runs. You can keep it static or include dynamic instructions about the current day, period, or data set.
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:
Prompt:
"Check inventory for items below reorder level and create purchase
requisitions if needed. Prioritize high-demand items."Document Event Trigger Configuration
Document event triggers need a DocType, an event, optional conditions, and a prompt that can reference document fields.
Selecting the DocType
First, choose which DocType the trigger should watch. The Reference DocType field is the document type name, such as "Sales Invoice", "Lead", or "Support Ticket".
Selecting the Event
Next, pick the document event that starts the agent. Each event fires at a different point in the document lifecycle.
| Event | When It Fires |
|---|---|
| After Insert | Document is created and saved |
| On Update | Document is modified |
| On Submit | Submittable document is submitted |
| On Cancel | Document is cancelled |
| Before Save | Before save (can prevent save with errors) |
| After Delete | After document is deleted |
Conditional Execution
Conditions let you run a document event trigger only when a document matches specific field values, which prevents unnecessary agent runs and keeps costs predictable. The Condition field accepts a 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
Prompt Templates for Doc Event Triggers
For document triggers, the prompt template can include placeholders such as {field_name} to insert values from the current document.
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}The data available to the prompt includes all fields on the document, standard fields such as name, creation, modified, and owner, and linked document data when the agent has tools that can fetch it.
Example:
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
Triggers can use either per-user or shared conversation history, depending on whether you want isolation between users or continuity across runs.
Per-User Conversation
By default, triggers keep each user’s history separate (persist_user_history = 1). This preserves privacy and ensures user-specific context does not leak between users. For example, if a Support Ticket Agent runs On Submit, User A’s submission creates a separate conversation for User A, User B’s submission creates a separate conversation for User B, and the histories stay independent.
Shared Conversation
In shared mode (persist_user_history = 0), all trigger executions share one conversation. This lets the agent build cumulative knowledge: a daily sales summary scheduled agent can remember yesterday’s report, compare trends, and build on previous days’ data. You configure this on the Agent DocType with the Persist Conversation toggle and the Persist per User (Doc/Schedule) checkbox: check it for per-user history, uncheck it for shared history.
Trigger Best Practices
Following a few guidelines keeps triggers reliable, cost-effective, and easy to maintain.
Scheduling
Good scheduling keeps agents reliable and avoids resource contention.
- Run heavy tasks during off-peak hours to reduce load on users.
- Stagger multiple agents so they do not overlap.
- Choose reasonable frequencies to avoid over-scheduling.
- Monitor the cost of scheduled runs.
- Schedule too frequently, such as every minute.
- Run multiple heavy agents at the same time.
- Ignore timezone considerations.
- Leave failed runs unreviewed.
Document Events
Be precise with document events to prevent loops and unnecessary agent runs.
- Use specific events rather than every available event.
- Add conditions to limit executions.
- Handle errors gracefully.
- Test with draft documents first.
- Trigger on every update, which can cause loops.
- Use Before Save unless it is necessary.
- Forget permission checks.
- Create infinite trigger loops.
Prompt Templates
A clear prompt produces a clear result.
- Be specific about the task.
- Include relevant document fields.
- Provide clear instructions.
- Mention expected outputs.
- Use vague prompts.
- Forget to test with real data.
- Include sensitive data unnecessarily.
- Assume the agent already knows the document structure.
Error Handling
Agent triggers run unattended, so monitoring is essential. Regularly check Agent Run logs, set up failure notifications, review errors and adjust prompts, and test trigger conditions thoroughly.
Common Use Cases
These examples show how triggers combine event types, agents, and prompt templates to automate common workflows.
1. Automated Lead Assignment
When a new Lead is created, the Lead Router agent can evaluate territory, workload, and industry fit to assign the best sales rep and schedule the next follow-up.
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
On submission of a Sales Invoice, the Invoice Validator agent can check pricing, credit limits, taxes, and anomalies before the invoice is finalized.
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
A scheduled morning run can produce a daily sales summary and send it to the team without manual intervention.
Prompt:
Generate daily sales summary:
- Total orders and revenue
- Top 5 customers
- Pending payments
- Trends vs yesterday
Send report to sales@company.com4. Support Ticket Routing
When a new Support Ticket arrives, the Ticket Router agent can triage priority, set SLAs, and route the ticket to the right team.
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 priority5. Inventory Monitoring
A recurring inventory check can raise purchase requisitions when stock falls below reorder levels.
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
When a trigger does not behave as expected, use the symptoms below to narrow down the cause.
Trigger doesn’t fire:
- Verify the trigger is Enabled.
- Check that the condition matches the document.
- Review the DocType and Event selection.
- Confirm the agent is active.
- Verify there are no Frappe permission issues.
Trigger fires too often:
- Add more specific conditions.
- Change from “On Update” to “On Submit”.
- Review the document workflow.
- Check for trigger loops.
Agent gets wrong data:
- Verify prompt template field names.
- Check the document state at trigger time.
- Test field access and permissions.
- Review the agent’s 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:
- Running Agents - Detailed guide to execution methods
- Agent Triggers Deep Dive - Advanced trigger patterns
- Monitoring - Track trigger performance
- Creating Agents - Design automation workflows
Need help with triggers? Check GitHub discussions .