id: ai-email-triage-clef-confidence-gate
namespace: company.ai
description: |
Classify incoming emails with Cloudflare's Clef decision model and route
them by category and confidence, sending low-confidence mail to human review.
inputs:
- id: email_subject
type: STRING
defaults: "Invoice #4821 overdue, please pay within 3 days"
description: Subject line of the email to classify.
- id: email_body
type: STRING
defaults: |
Hi team, invoice #4821 for $4,200 is now 12 days overdue.
Please arrange payment this week to avoid late fees. Thanks, Accounts.
description: Plain-text body of the email to classify.
- id: sender_email
type: STRING
defaults: accounts@vendor-example.com
description: Sender address.
- id: model
type: SELECT
defaults: clef-flash
values:
- clef-flash
- clef
description: Clef model selector sent in the request body.
- id: confidence_threshold
type: FLOAT
defaults: 0.5
description: Below this confidence the email goes to human review.
tasks:
- id: tier0_heuristics
type: io.kestra.plugin.scripts.python.Script
description: Sanitize guard, flags bulk patterns and redacts codes and account
numbers before any model call.
dependencies:
- kestra
script: |
import json
import re
from kestra import Kestra
subject = """{{ inputs.email_subject }}"""
body = """{{ inputs.email_body }}"""
text = (subject + "\n" + body).lower()
heuristic = "none"
if "list-unsubscribe" in text or "unsubscribe" in text:
heuristic = "newsletter"
safe_subject = re.sub(r"\b\d{4,}\b", "***", subject)
safe_body = re.sub(r"\b\d{4,}\b", "***", body)
safe_state = "From: " + """{{ inputs.sender_email }}""" + " Subject: " + safe_subject + " Body: " + safe_body
safe_state_json = json.dumps(safe_state)
Kestra.outputs({
"heuristic": heuristic,
"safe_subject": safe_subject,
"safe_body": safe_body,
"safe_state_json": safe_state_json,
})
- id: classify_clef
type: io.kestra.plugin.core.http.Request
description: One Clef call evaluating category, safe-to-delete and urgency in parallel.
uri: "https://api.cloudflare.com/client/v4/accounts/{{
secret('CLOUDFLARE_ACCOUNT_ID') }}/ai/run/@cf/cloudflare/clef-flash"
method: POST
contentType: application/json
headers:
Authorization: "Bearer {{ secret('CLOUDFLARE_API_TOKEN') }}"
body: |
{
"model": "{{ inputs.model }}",
"state": {{ outputs.tier0_heuristics.vars.safe_state_json }},
"questions": {
"category": {
"type": "choice",
"instructions": "Classify this email into exactly one category.",
"criteria": {
"newsletter": "subscriptions, digests, marketing blasts",
"promo": "discounts, offers, sales campaigns",
"receipt": "order confirmations, payment receipts, invoices",
"finance-legal": "money movement, contracts, compliance, account security",
"work": "job-related professional correspondence",
"personal": "friends, family, direct human messages",
"urgent": "outage, breach, deadline today, needs immediate action",
"low-priority": "FYI threads, cc loops, no action needed"
}
},
"safe_delete": {
"type": "noul",
"instructions": "Is it safe to delete this email without any loss?"
},
"urgency": {
"type": "score",
"instructions": "How urgent is this email?",
"criteria": ["routine, no rush", "today", "urgent", "critical, act now"]
}
}
}
retry:
type: exponential
interval: PT2S
maxInterval: PT20S
maxAttempts: 3
- id: route_decision
type: io.kestra.plugin.core.flow.If
description: Confidence gate, below threshold goes to human review, never auto-labeled.
condition: "{{ fromJson(outputs.classify_clef.body ??
'{}').result.answers.category.confidence < inputs.confidence_threshold }}"
then:
- id: notify_human_review
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
:eyes: *HUMAN REVIEW*, low-confidence triage
*Subject:* {{ inputs.email_subject }}
*Guessed category:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.category.choice ?? 'unknown' }}` (confidence `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.category.confidence ?? 'n/a' }}`)
else:
- id: route_by_category
type: io.kestra.plugin.core.flow.Switch
description: High-confidence mail fans out to team-specific cards by category.
value: "{{ fromJson(outputs.classify_clef.body ??
'{}').result.answers.category.choice ?? 'unknown' }}"
cases:
newsletter:
- id: log_newsletter_skip
type: io.kestra.plugin.core.log.Log
message: "Newsletter classified with high confidence, logged quietly, no alert.
Subject: {{ inputs.email_subject }}"
urgent:
- id: alert_urgent
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
description: Incident-style card for urgent mail.
messageText: |
:rotating_light: *URGENT EMAIL*
*Subject:* {{ inputs.email_subject }}
*From:* {{ inputs.sender_email }}
*Urgency score:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.urgency.score ?? 'n/a' }}` | *Safe to delete:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.safe_delete.noul ?? 'n/a' }}`
finance-legal:
- id: notify_finance
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
description: Finance card for money and legal mail.
messageText: |
:bank: *FINANCE / LEGAL EMAIL*
*Subject:* {{ inputs.email_subject }}
*From:* {{ inputs.sender_email }}
*Urgency score:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.urgency.score ?? 'n/a' }}`
- id: log_finance_protect
type: io.kestra.plugin.core.log.Log
description: Finance-legal mail is never auto-deleted regardless of safe_delete
score.
message: "PROTECTED: finance-legal sender {{ inputs.sender_email }}, never
auto-delete."
promo:
- id: log_promo_skip
type: io.kestra.plugin.core.log.Log
message: "Promo classified with high confidence, logged quietly, no alert.
Subject: {{ inputs.email_subject }}"
low-priority:
- id: log_low_priority_skip
type: io.kestra.plugin.core.log.Log
message: "Low-priority mail logged quietly, no alert. Subject: {{
inputs.email_subject }}"
defaults:
- id: notify_standard
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
description: Standard triage card for receipt, work, personal and anything else.
messageText: |
:inbox_tray: *Email triaged*
*Subject:* {{ inputs.email_subject }}
*Category:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.category.choice ?? 'unknown' }}` | *Urgency:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.urgency.score ?? 'n/a' }}` | *Safe to delete:* `{{ fromJson(outputs.classify_clef.body ?? '{}').result.answers.safe_delete.noul ?? 'n/a' }}`
triggers:
- id: scheduled_inbox_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Periodic sweep of unread mail. Shipped disabled for safe manual
verification first.
cron: "0 9 * * *"
disabled: true
- id: webhook_inbound_email
type: io.kestra.plugin.core.trigger.Webhook
description: Authenticated webhook endpoint for realtime mail ingestion.
key: "{{ secret('WEBHOOK_KEY') }}"
errors:
- id: alert_triage_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
description: Failure notice if classification or routing throws an unhandled exception.
messageText: ":warning: Execution {{ execution.id }} failed in flow `{{
flow.namespace }}.{{ flow.id }}`."
outputs:
- id: category
type: STRING
value: "{{ fromJson(outputs.classify_clef.body ??
'{}').result.answers.category.choice ?? 'unknown' }}"
- id: confidence
type: FLOAT
value: "{{ fromJson(outputs.classify_clef.body ??
'{}').result.answers.category.confidence ?? 0 }}"