Condition providers
Pick the right workflow variant from live data, such as whether an order has already shipped.
A condition provider lets one workflow handle the same request in completely different ways, based on live data from your systems. It is a Python function that runs when the AI agent loads the workflow and returns true or false conditions. Octocom picks the first workflow variant whose required conditions all match, and the AI agent follows that variant's instructions.
For example, a customer writes "I want to cancel my order". The provider looks the order up before the AI agent replies. If the order has not shipped, the AI agent follows your cancellation steps. If it has shipped, it follows a different variant that explains the shipping status and offers alternatives. The same works for a subscription's plan, a claim's status or an account's payment state.
Use a custom action instead when the AI agent only needs to fetch data at some point in the conversation. When a small if/else is enough, write it in the workflow instructions.
In the dashboard, condition providers live under Settings -> Automation -> Custom Conditions. They only run on non-embedded workflows. Embedded workflows are always in the system prompt and have a single variant, so turn embedding off before attaching a provider.
When you need one
You don't need one if:
- Your workflow always follows the same steps
- Your branching is simple enough to handle with if/else in the bot instructions
You need one when:
- The same trigger (for example "cancel my order") requires fundamentally different responses based on external state (shipped, not shipped, already refunded)
- You want data fetched before the AI agent starts responding
- You need completely different instruction sets, not just small if/else branches
How it works
- A customer message makes the AI agent load a workflow.
- The condition provider runs and calls your APIs to evaluate the current state.
- It returns a set of boolean conditions (for example
isShipped: true,isRefunded: false) and optional data. - Octocom checks each variant from top to bottom and selects the first one whose required conditions are all true.
- The AI agent follows that variant's instructions, with the provider's data available.
Example flow:
Customer: "I want to cancel my order"
→ Condition provider runs with orderId
Returns: { orderNotFound: false, isRefunded: false, isShipped: true }
→ Variant 0: requires [orderNotFound] → no match
→ Variant 1: requires [isRefunded] → no match
→ Variant 2: requires [isShipped] → match ✓
→ AI follows variant 2: "Your order has already shipped..."Set up variants
Each variant in a workflow has:
- Title: a descriptive name (for example "Already shipped" or "Default")
- Required conditions: boolean conditions that must all be true for this variant to be selected
- Actions: which actions this variant can use
- Bot instructions: what the AI agent should do when this variant is selected
Order matters. Variants are evaluated from top to bottom and the first match wins. Put specific cases first and the default last.
| Position | Variant | Conditions | Purpose |
|---|---|---|---|
| 0 | Not found | orderNotFound | Error recovery |
| 1 | Already refunded | isRefunded | Inform customer, no further action |
| 2 | Already shipped | isShipped | Explain shipping status, offer alternatives |
| Last | Default | (none) | Fallback: always matches |
The last variant should have no required conditions. This ensures every situation is handled, even if none of the specific conditions match.
Write a condition provider
A condition provider implements an evaluate_conditions function. It receives a context object with the workflow arguments, conversation data, customer profile and more (see Python context for the full reference). It calls your APIs and returns conditions and optional data.
import requests
def evaluate_conditions(context):
order_id = context["args"]["orderId"]
# Fetch order from your system
response = requests.get(
"https://api.example.com/orders",
params={"id": order_id},
timeout=30,
)
if response.status_code != 200:
return {
"conditions": {"orderNotFound": True},
"data": {},
}
order = response.json()
return {
"conditions": {
"orderNotFound": False,
"isRefunded": order.get("refundedAt") is not None,
"isShipped": order.get("shippedAt") is not None,
"isDelivered": order.get("deliveredAt") is not None,
},
"data": {
"orderStatus": order.get("status"),
"trackingNumber": order.get("trackingNumber"),
},
}The function returns two things:
| Field | Description |
|---|---|
conditions | Boolean flags matched against each variant's required conditions |
data | Additional data passed to the selected variant. The AI agent can use it in its reply |
Conditions your code doesn't return
Every condition has one of three states: true, false or unknown. A condition is unknown when it's declared on the provider but your code doesn't return it, for example on an early not-found return.
A variant's required condition is met only when it is true. An unknown condition never matches, so it behaves like false for variant selection. The rest of the result still works: Octocom picks the first variant whose conditions are all true, usually your not-found or default variant.
Return every declared condition on every path when you can. When you test a provider, any declared condition that wasn't returned is listed under missingConditions. Check that list on the not-found and error paths too.
Values that are returned must be booleans. Returning None or a string for a condition, or a result without a conditions dict, fails the run.
Arguments
Condition providers receive arguments defined in the workflow configuration. The AI agent collects them from the customer before the provider runs. A provider can also take no arguments and read everything it needs from context, for example the conversation's channel.
Common argument patterns:
orderIdfor order workflowsemailfor customer lookupsubscriptionIdoraccountNumberfor subscription and account workflows
Helpers
Condition providers can call every built-in helper, the same as custom actions, event handlers and sidebar widgets. See Python helpers for the full list.
Knowing which workflow called
When the AI agent runs a provider for a workflow, context["workflow"] holds that workflow's id, slug and title, so one provider can branch per workflow. It is absent in direct tests. See Python context.
Advanced patterns
Passing data to variants
The data field in the provider's result is available to the AI agent in the selected variant. Use it to pre-fetch what the AI agent will need (order details, tracking information, account status) so it can reply immediately without calling separate actions.
return {
"conditions": {"isShipped": True},
"data": {
"trackingNumber": "1Z999AA10123456784",
"carrier": "UPS",
"estimatedDelivery": "2025-04-15",
},
}The AI agent in the "Already shipped" variant can then tell the customer: "Your order is on its way via UPS. Tracking number: 1Z999AA10123456784, estimated delivery: April 15."
Using LLM classification
Condition providers can use llm_classify_binary() and llm_classify_category() to route on the conversation's tone or intent rather than structured data.
def evaluate_conditions(context):
messages = context["conversation"]["messages"]
is_threat = llm_classify_binary(
"Has the customer explicitly threatened a chargeback, "
"bank dispute, or legal action? Frustration or anger "
"alone does not count — look for explicit financial threats.",
messages,
fallback=False,
)
return {
"conditions": {"isExplicitThreat": is_threat},
"data": {},
}For category-based routing:
def evaluate_conditions(context):
messages = context["conversation"]["messages"]
category = llm_classify_category(
"Based on the customer's description, classify the product issue.",
messages,
["medical_concern", "physical_defect", "not_working", "general_dissatisfaction"],
)
return {
"conditions": {
"isMedicalConcern": category == "medical_concern",
"isPhysicalDefect": category == "physical_defect",
"isNotWorking": category == "not_working",
},
"data": {"issueCategory": category},
}A/B testing
Use get_ab_test_variant() to route customers to different variants consistently, for experiments. See A/B testing.
def evaluate_conditions(context):
variant = get_ab_test_variant(context, "retention-flow", ["a", "b"])
return {
"conditions": {
"isVariantA": variant == "a",
"isVariantB": variant == "b",
},
"data": {},
}Each conversation always gets the same variant, so customers don't see different behavior across messages.
Sharing one provider across workflows and brands
When several workflows or brands evaluate the same kind of state, such as an order or a subscription, use one shared provider instead of a copy per workflow or brand. The provider returns every condition it supports, and each workflow's variants require only the conditions they need. A brand that needs extra conditions is not a reason to copy the provider: add them to the shared one.
Keep brand-specific rules as data inside the provider, keyed by the business:
BRAND_RULES = {
"brand-a": {"return_window_days": 60},
"brand-b": {"return_window_days": 30},
}
def evaluate_conditions(context):
rules = BRAND_RULES.get(context["business"]["slug"], {"return_window_days": 30})
...Keep separate providers only when the input differs (for example, one takes orderId and another takes subscriptionId) or the behavior differs for a concrete reason.
To share helper code between providers with different inputs, put it in an organization Python module. Every Python execution in the organization loads its modules, so a fix applies everywhere at once. Keep modules to function and constant definitions: use a prefix for every name, make no API calls at import time, and remember that a syntax error in a module breaks every Python execution in the organization.
If some conditions need an LLM call or an extra API request, compute them only when a variant needs them, so workflows that don't use them stay fast.
Testing
Test a condition provider before connecting it to a workflow.
- Open your condition provider in the dashboard (Settings -> Automation -> Custom Conditions) and go to its Test Provider section.
- Fill in test values for each argument (for example an order ID or email).
- Optionally enter a Conversation ID. This populates
context["conversation"]with real conversation data. Use any conversation from your dashboard: copy the ID or public ID from the conversation detail view. - Click Run Test.
- The dashboard runs your code and shows the returned
conditionsanddata, plus anymissingConditions.
Through Copilot or MCP, use test_condition_provider with the provider ID, a business ID and the argument values.
Without a conversation ID, context["conversation"] is None. This is fine for providers that only use context["args"] to call external APIs, but if your provider reads conversation messages (for LLM classification, for example), provide a conversation ID to test with real data.
Direct tests have no triggering workflow, so context["workflow"] is absent during testing. When the AI agent runs the provider for a workflow, the field contains that workflow's id, slug and title. Code that reads it should use context.get("workflow"). See Python context for the full shape.
Tip: Test with argument values that exercise each condition path. For example, test with an order ID that has been refunded, one that has shipped and one that doesn't exist, and check that the right conditions come back each time.
Find where a provider is used
Through Copilot or MCP, list_condition_providers returns a usage summary for each provider: businessCount, workflowCount and liveWorkflowCount. Unused providers have zero counts.
Pass includeWorkflows: true to also receive usage.businesses. Each business includes its ID, name and slug, and a workflows list with each referencing workflow's ID, title, slug, isLive and isEmbedded. Businesses are ordered by name and workflows by title.
get_condition_provider always includes this breakdown for the requested provider. Pass textFields: [] to inspect usage without loading its Python code.
Usage reports current configuration references, including draft and embedded workflows. Deleted workflows are excluded. A live reference does not prove the provider has run: embedded workflows do not run condition providers, and other workflow eligibility rules still apply.
Limits and failure behavior
- Conditions must be booleans. A non-boolean condition value, or a result without a
conditionsdict, fails the run. - A condition you declare but don't return is unknown and never matches (see Conditions your code doesn't return).
- A provider shares the Python execution budgets: pass a
timeoutto every HTTP request so a slow API can't hold up the AI agent's reply. - A provider that raises an exception or returns an invalid result fires the Automation Execution Failed event, so you can alert your team.
Examples
Subscription cancellation
A language learning app handles cancellation requests differently based on subscription state.
Condition provider:
import requests
def evaluate_conditions(context):
email = context["args"]["email"]
sub_id = context["args"]["subscriptionId"]
response = requests.get(
"https://api.example.com/subscriptions",
params={"email": email, "id": sub_id},
timeout=30,
)
if response.status_code != 200:
return {"conditions": {"subscriptionNotFound": True}, "data": {}}
sub = response.json()
return {
"conditions": {
"subscriptionNotFound": False,
"isRefunded": sub.get("refundedAt") is not None,
"isLifetime": sub.get("type") == "lifetime",
},
"data": {
"planName": sub.get("planName"),
"startDate": sub.get("startDate"),
},
}Variants:
| # | Variant | Conditions | What the AI agent does |
|---|---|---|---|
| 0 | Not found | subscriptionNotFound | Ask the customer to double-check their email |
| 1 | Lifetime plan | isLifetime | Explain lifetime plans can't be cancelled in chat -> transferConversation |
| 2 | Already refunded | isRefunded | Inform the customer their subscription was already refunded |
| 3 | Default | (none) | Confirm intent -> call cancelSubscription -> confirm to the customer |
Order cancellation with a shipping check
An online store handles cancellation requests based on fulfillment state.
Condition provider:
import requests
from datetime import datetime, timedelta
def evaluate_conditions(context):
order_id = context["args"]["orderId"]
response = requests.get(
"https://api.example.com/orders",
params={"id": order_id},
timeout=30,
)
if response.status_code != 200:
return {"conditions": {"orderNotFound": True}, "data": {}}
order = response.json()
created = datetime.fromisoformat(order["createdAt"])
is_old = (datetime.now() - created) > timedelta(days=5)
return {
"conditions": {
"orderNotFound": False,
"isRefunded": order.get("refundedAt") is not None,
"isShipped": order.get("shippedAt") is not None,
"isDelivered": order.get("deliveredAt") is not None,
"isOlderThan5Days": is_old,
},
"data": {
"orderStatus": order.get("status"),
"items": order.get("items", []),
"shippedAt": order.get("shippedAt"),
},
}Variants:
| # | Variant | Conditions | What the AI agent does |
|---|---|---|---|
| 0 | Not found | orderNotFound | Ask the customer to verify their order ID |
| 1 | Already refunded | isRefunded | Inform the customer the order was already refunded |
| 2 | Delivered | isDelivered | Redirect to the returns workflow |
| 3 | Shipped | isShipped | Explain the order is in transit, offer a return on arrival |
| 4 | Too late | isOlderThan5Days | Explain the order may have shipped, suggest checking status |
| 5 | Default | (none) | Confirm intent -> call cancelOrder -> confirm cancellation |
More recipes that combine condition providers with workflows, such as time-based refund windows and per-customer policies, are in Common automation patterns.
Best practices
- Keep conditions boolean. Each condition should be a simple true/false. Put complex logic in the provider code, not in condition names.
- Order variants by specificity. Most specific first (error states, edge cases), most general last (default fallback).
- Always include a fallback. The last variant should have no required conditions so it catches anything unexpected.
- Put the not-found variant first. Give it no actions, so a missing order or subscription can never select a variant that issues refunds or cancellations.
- Pre-fetch useful data. If the AI agent will need order or subscription details, include them in
datato avoid extra action calls. - Name conditions clearly.
isRefunded,orderNotFound,isShipped: the name should make the condition obvious when reading the variant list. - Handle API failures. If your API is down, return an appropriate condition (like
orderNotFound) rather than raising. The AI agent can still give the customer a helpful reply. - Return every declared condition. Leaving one out doesn't break the run, but it never matches. Use
missingConditionsin test results to catch gaps. See Conditions your code doesn't return. - Share instead of copying. Reuse one provider per kind of input across workflows and brands, and share helper code through an organization module. See Sharing one provider across workflows and brands.