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. 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.

No trigger configuration is needed for manual execution—just run the agent when you want.

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.

FrequencyDescription
HourlyRuns every hour
DailyRuns once per day at a specified time
WeeklyRuns on selected day(s) of the week
Custom CronAdvanced 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:

Trigger Example
AgentDaily Sales Summary
TriggerEvery day at 9:00 AM
ActionGenerates sales report and sends via email

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.

EventDescription
After InsertDocument is created
On UpdateDocument is modified
On SubmitSubmittable document is submitted
On CancelDocument is cancelled
Before SaveBefore document is saved (use carefully)
After DeleteDocument 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:

Trigger Example
AgentInvoice Validator
TriggerAfter Submit on DocType "Sales Invoice"
ActionValidates pricing, checks credit limits, flags issues

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.

No separate trigger is required for chat—chat is enabled on the agent itself.

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.

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

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 OptionWhen It Runs
HourlyRuns every hour
DailySpecify a time such as "09:00"
WeeklyChoose day(s) and a time
CronAdvanced 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:

Trigger Example
AgentInventory Monitor
ScheduleEvery 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

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.

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
The most commonly used events are After Insert, On Submit, and On Update.

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

If you leave the condition empty, the trigger fires on every matching event for that DocType.

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:

Trigger Example
AgentLead Qualifier
DocTypeLead
EventAfter 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

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.

Do
  • 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.
Don't
  • 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.

Do
  • Use specific events rather than every available event.
  • Add conditions to limit executions.
  • Handle errors gracefully.
  • Test with draft documents first.
Don't
  • 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.

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 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.

Trigger Example
TriggerAfter Insert on Lead
AgentLead 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

On submission of a Sales Invoice, the Invoice Validator agent can check pricing, credit limits, taxes, and anomalies before the invoice is finalized.

Trigger Example
TriggerOn Submit on Sales Invoice
AgentInvoice 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

A scheduled morning run can produce a daily sales summary and send it to the team without manual intervention.

Trigger Example
TriggerSchedule (Daily at 9 AM)
AgentSales 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

When a new Support Ticket arrives, the Ticket Router agent can triage priority, set SLAs, and route the ticket to the right team.

Trigger Example
TriggerAfter Insert on Support Ticket
AgentTicket 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

A recurring inventory check can raise purchase requisitions when stock falls below reorder levels.

Trigger Example
TriggerSchedule (Every 6 hours)
AgentInventory 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

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:


Need help with triggers? Check GitHub discussions .

Last updated on