# RevCent AI Assistants Overview for Ecommerce Businesses

RevCent AI Assistants allow ecommerce businesses to automate work using AI models connected through RevCent. An AI Assistant is triggered by an event, schedule, API/web action, or another AI Assistant, then runs an autonomous AI Thread designed in the Thread Builder.

Source:
- RevCent Knowledge Base: AI Assistants — `https://kb.revcent.com/tools/ai/assistants`

---

## What Are AI Assistants?

A RevCent AI Assistant is an autonomous AI automation inside RevCent.

Instead of a user chatting directly with the AI, the assistant runs in the background based on trigger settings. When triggered, RevCent creates an AI Thread and guides the AI through a configured workflow.

High-level process:

1. The AI Assistant is triggered.
2. RevCent creates an AI Thread.
3. The AI follows the workflow built in the Thread Builder.
4. RevCent handles orchestration with the AI model.
5. The assistant can analyze data, use system tools, create notes, send emails, run functions, trigger other assistants, or create AI Memos depending on the thread design.

---

## Why Ecommerce Businesses Use AI Assistants

AI Assistants are useful when an ecommerce business wants reasoning-driven automation rather than simple rule-based automation.

Common use cases:

- Analyze declined sales.
- Detect chargeback threats in customer notes.
- Create AI Memos for urgent business events.
- Summarize customer behavior.
- Review refund, chargeback, or subscription activity.
- Analyze failed gateway responses.
- Filter futile payment recovery attempts by decline reason.
- Trigger Functions with inferred arguments.
- Send AI-personalized Email Templates.
- Run scheduled business analysis.
- Trigger other assistants for specialized workflows.
- Assist support, risk, finance, retention, fulfillment, or operations teams.
- Measure assistant-driven revenue, payment actions, refunds, notes, metadata, and system-action performance through BigQuery reporting.

---

## What AI Assistants Can Do

Depending on enabled system tools and instructions, AI Assistants can perform tasks such as:

| Capability | Ecommerce Example |
|---|---|
| Analyze records | Review a failed sale and determine likely decline reason. |
| Create notes | Add a note summarizing a customer issue. |
| Create AI Memos | Alert admins that a gateway appears down. |
| Trigger Functions | Run a custom analysis Function with generated custom arguments. |
| Send Email Templates | Send a customized apology or recovery email. |
| Use BigQuery | Analyze revenue, declines, refunds, or transaction patterns. |
| Report on assistant performance | Use BigQuery to analyze `api_call.ai_assistant`, revenue actions, payment attempts, refunds, notes, metadata, and outcomes. |
| Trigger another assistant | Hand off a specialized task to another AI Assistant. |
| Branch workflows | Choose different paths based on AI-evaluated conditions. |
| Wait and continue | Delay a thread to wait for more related events. |

---

# Getting Started

Before creating an AI Assistant:

1. Create an account with a supported AI provider.
2. Add a payment method in the third-party AI account to increase limits.
3. Create a RevCent third-party integration for the AI provider.
4. Enter the required credentials.
5. Save the integration and choose the model.
6. Create an AI Assistant in RevCent.
7. Configure trigger settings.
8. Build the assistant thread flow.
9. Set usage limits.
10. Test before enabling production automation.

Supported AI providers include:

- OpenAI
- Google Gemini
- OpenRouter
- xAI

---

# Pricing and Cost Controls

AI Assistants may involve two types of cost.

## Third-Party AI Model Cost

The selected AI provider may charge for model usage. RevCent does not control the AI provider’s pricing.

The cost depends on:

- Selected provider
- Selected model
- Input tokens
- Output tokens
- Number of thread steps
- Tool calls
- AI response length

## RevCent AI Time Cost

The KB states RevCent charges `$0.02 per minute` of AI time consumed.

AI time consumed is the total time RevCent spends communicating back and forth with the AI model.

Cost can increase with:

- More thread steps
- Slow model responses
- Complex prompts
- Many tool calls
- Long conversations
- Branching workflows
- Scheduled runs
- High-volume event triggers

## Usage Limits

RevCent provides usage limits to help control cost.

Recommended limits:

| Limit | Purpose |
|---|---|
| Max Tokens Per Day | Caps daily assistant usage. |
| Max Tokens Per Thread | Prevents one thread from consuming too many tokens. |
| Max Tokens Per User | Applies to web-triggered assistant use. |

Setting at least one usage limit is highly recommended.

---

# Core Concepts

## AI Integration

An AI Assistant requires a third-party AI integration.

This integration determines which AI provider and model powers the assistant.

Use a model appropriate for the workflow:

| Workflow | Model Consideration |
|---|---|
| Simple classification | Lower-cost model may be enough. |
| Complex reasoning | Use stronger reasoning model. |
| Long customer history review | Use model with higher context/token support. |
| Tool-heavy workflows | Use model that handles tool instructions reliably. |
| High-volume automation | Balance cost, latency, and accuracy. |

---

## AI Instructions

AI Instructions are the assistant’s base system instructions.

They should describe the assistant’s broad purpose.

Good:

```text
You are an AI Assistant that analyzes declined ecommerce sales and determines whether recovery actions are appropriate.
```

Good:

```text
You are an AI Assistant that reviews customer notes and identifies potential chargeback threats.
```

Avoid putting specific step-by-step actions in AI Instructions. Specific actions belong in Thread Builder steps.

---

## AI Threads

Each time an assistant is triggered, RevCent creates an AI Thread.

An AI Thread is a specific run of an AI Assistant.

Thread details include:

- Messages exchanged with the AI
- Timing
- Token usage
- Tool calls
- Step results
- Thread history
- Related item context

AI Threads are useful for:

- Debugging assistant behavior
- Reviewing what the AI saw
- Understanding why a branch was chosen
- Auditing tool calls
- Fine-tuning prompts and flow steps

---

# Trigger Types

The trigger determines when the assistant starts.

Available triggers:

| Trigger | Purpose |
|---|---|
| Event | Run when a RevCent account event occurs. |
| On Demand | Run via API, web app, or another AI Assistant. |
| Schedule | Run on a fixed schedule. |

---

# Trigger: Event

Event-triggered AI Assistants run automatically when a specific RevCent account event occurs.

This is the most common trigger for ecommerce automation.

## Ecommerce Event Examples

| Event | Example Assistant |
|---|---|
| Sale declined | Analyze recovery opportunity and send follow-up. |
| Sale success | Create a note summarizing what was purchased. |
| Chargeback created | Create AI Memo and notify risk team. |
| Customer note created | Detect chargeback threats or sentiment. |
| Subscription renewal failed | Recommend retention action. |
| Shipment shipped | Summarize shipment status or notify team. |
| Fraud detection created | Analyze fraud details and create risk memo. |
| Invoice created | Review invoice details and send follow-up. |
| Pending refund created | Summarize refund reason for support/accounting. |

## Event Notation

Each event has a notation.

Examples:

```text
sale.created.failed.declined
sale.created.success.paid
chargeback.created
customer.created
shipping.updated.shipped
subscription_renewal.updated.failed
trial.updated.expired.success
ai_memo.created
```

Use the most specific event notation possible.

Example:

For declined-sale recovery, use:

```text
sale.created.failed.declined
```

instead of:

```text
sale.created
```

## Event Delay

Event-triggered assistants can be delayed.

The KB notes:

- Default minimum is 1 minute.
- Maximum delay is 30 days.

Use delays when related data may appear shortly after the event.

Examples:

- Wait after a failed sale to see if a salvage transaction occurs.
- Wait after shipment created to see if tracking is updated.
- Wait after note created to allow more customer context to arrive.
- Wait after pending refund created before escalation.

## Event Filters

Filters limit whether the assistant should run.

Common filters:

| Filter | Purpose |
|---|---|
| Campaign filter | Only run for selected campaigns. |
| Status filter | Only run for selected statuses. |
| Metadata filter | Only run if metadata name/value pairs match. |

Use filters to prevent unnecessary or costly assistant runs.

## Filter Function

A filter Function can further decide whether the assistant should run.

The Function receives item data, typically through:

```javascript
event.data.item_details
```

It must return one of two strings:

```javascript
callback(null, "pass");
```

or:

```javascript
callback(null, "fail");
```

Meaning:

- `pass`: the assistant runs.
- `fail`: the assistant does not run.

Filter Functions are useful for complex eligibility logic that normal filters cannot express.

## Max Runs Per Item

Max Runs Per Item limits how many times a specific assistant can run for the same item.

Recommended:

```text
1
```

This is important because AI actions can create additional events.

Example:

If an assistant runs on a declined sale and reprocesses that sale, a second decline could trigger the same assistant again. Max Runs Per Item prevents unintended loops.

## Min Run Interval

Min Run Interval only applies if Max Runs Per Item is greater than 1.

Use it when repeated runs are intentional but should be spaced out.

Example:

```text
Max Runs Per Item: 2
Min Run Interval: 1 day
```

---

# Trigger: On Demand

On-demand assistants run only when explicitly triggered.

They can be triggered by:

- API
- RevCent web app
- Another AI Assistant

## API Trigger

Use API triggering for external systems or MCP-driven automation.

Examples:

- Trigger a customer summary assistant from an external dashboard.
- Trigger a sale review assistant from a support workflow.
- Trigger an AI assistant after a custom Function completes.

## Web App Trigger

Web access lets logged-in RevCent users trigger an assistant from item detail pages.

Use cases:

- Support rep triggers a customer analysis.
- Risk analyst triggers a chargeback review.
- Finance user triggers refund analysis.
- Manager triggers sale summary.

Web settings can control:

- Whether web access is enabled.
- Which item types show the assistant button.
- Which user types can trigger it.
- Max tokens per user per 24 hours.

## Trigger From Another Assistant

One AI Assistant can trigger another AI Assistant.

This allows modular AI workflows.

Example:

1. A general risk assistant detects a chargeback threat.
2. It triggers a specialized chargeback mitigation assistant.
3. The second assistant reviews the customer and creates an AI Memo.

Descriptions are important because another AI Assistant may use them to choose which assistant to trigger.

---

# Trigger: Schedule

Scheduled assistants run on a fixed cron schedule.

Use scheduled assistants for recurring business analysis.

## Ecommerce Schedule Use Cases

- Daily revenue summary.
- Daily decline-rate review.
- Weekly subscription renewal report.
- Daily refund/chargeback monitoring.
- Hourly high-risk sale review.
- Scheduled customer segmentation.
- Morning operations summary.
- End-of-day fulfillment summary.

## Cron Expression

Scheduled assistants use a standard five-part cron expression:

```text
minute hour day-of-month month day-of-week
```

Example:

```text
0 9 * * *
```

Meaning: every day at 9:00 AM in the selected timezone.

## Schedule Notes

The KB notes:

- Cron intervals cannot be less than 1 hour apart.
- Scheduled assistants are checked every 10 minutes.
- Exact minute execution may vary by up to 10 minutes.
- Only standard five-part cron expressions are supported.
- `@daily`, `@hourly`, and shortcut syntax are not supported.

## Timezone

Choose a valid timezone for the cron expression.

Examples:

```text
UTC
America/New_York
America/Los_Angeles
Europe/London
```

---

# Web Settings

Web settings allow users in the RevCent web app to trigger assistants from item detail pages.

This is useful when the assistant performs a specific task for a selected item.

Examples:

- Send an email.
- Issue or analyze a refund.
- Summarize a customer.
- Analyze a chargeback.
- Review transaction history.
- Create an AI Memo.
- Run a custom Function.

## Web Access

Enables or disables web app triggering.

## Item Types

Controls which item detail pages show the AI Assistant button.

Examples:

- Sale
- Customer
- Chargeback
- Subscription
- Shipping
- Trial

## User Types

Controls which user roles can trigger the assistant from the web app.

## Max Tokens Per User

Limits how many tokens a web user can consume in a 24-hour period.

Use this to control costs when multiple users can trigger assistants.

---

# Thread Builder

The Thread Builder defines how the assistant runs.

Every triggered assistant creates a thread. The thread follows connected nodes in the Thread Builder.

The Thread Builder is where the real workflow logic lives.

Node types:

| Node | Purpose |
|---|---|
| Start Thread | Starting point of the thread. |
| Thread Step | Sends an instruction/message to the AI. |
| Thread Branch | AI chooses a path based on conditions. |
| Time Delay | Pauses the thread. |
| End Thread | Ends the thread. |

---

## Start Thread

The Start Thread node is the beginning of every assistant thread.

It runs once when the assistant is triggered.

For event-triggered assistants, the start node provides the AI with initial item context.

Example:

If a sale triggers the assistant, the start thread asks the AI to retrieve sale details and keep those details in thread history for later steps.

This means later steps can refer to “the sale” without needing to repeatedly retrieve it.

---

## Thread Step

A Thread Step sends a message to the AI.

This is where action-specific instructions belong.

Good step message:

```text
Review the sale and create a note indicating what was purchased. Then determine whether the sale appears eligible for recovery.
```

Good step message:

```text
Read the existing customer notes. If the notes indicate the customer has called more than 3 times about an order issue, create an AI Memo explaining the escalation risk.
```

Step messages should be:

- Clear
- Specific
- Written like instructions to a human
- Focused on one logical task where possible

Thread Steps can instruct the AI to use available tools, such as:

- Create a note
- Send an SMTP message
- Trigger a Function
- Query data
- Create an AI Memo
- Trigger another assistant

---

## Thread Branch

A Thread Branch lets the AI choose one output path.

Branching is useful when the workflow depends on AI reasoning.

The branch node works like:

```text
if condition 1
else if condition 2
else if condition 3
else fallback
```

The KB explains that RevCent formats the branch output messages into a conditional statement for the AI. The AI chooses the output path.

Outputs:

| Output | Meaning |
|---|---|
| Output 1 | First condition. |
| Output 2 | Second condition. |
| Output 3 | Third condition. |
| Output 4 | Catch-all else path. |

Example branch:

```text
Output 1: The customer purchased a USB.
Output 2: The customer purchased a laptop.
Output 3: The customer did not purchase a laptop or USB.
Output 4: Else / fallback.
```

Branch use cases:

- Separate high-risk vs low-risk customers.
- Choose refund vs follow-up email.
- Decide whether to create an AI Memo.
- Determine whether to trigger a second assistant.
- Route based on product purchased.
- Route based on customer sentiment.
- Route based on gateway decline reason.

---

## Time Delay

A Time Delay pauses the thread before moving to the next node.

KB notes:

- Minimum delay is 1 minute.
- Maximum delay is 3 days.
- Threads are stored for a maximum of 7 days after creation, regardless of delays.

Use cases:

- Wait before checking for a related event.
- Wait before sending a follow-up.
- Wait for payment retry/salvage result.
- Wait for support action before escalation.
- Delay re-analysis to avoid acting too early.

---

## End Thread

End Thread explicitly ends the assistant thread.

A thread can also self-end when there are no more connected nodes.

Use explicit End Thread nodes for clarity, especially after branch outputs.

---

# AI Memos

AI Assistants can create AI Memos when instructed to do so in a Thread Step.

AI Memos are alerts or instant notifications.

## Why Use AI Memos?

AI Memos are useful when the AI identifies something important that a human should review.

Examples:

- Gateway appears down.
- Customer threatened a chargeback.
- Renewal failed due to expired card.
- Refund volume is unusually high.
- Decline rate exceeds threshold.
- Fraud pattern detected.
- Support escalation needed.

## AI Memo Notifications

The KB notes:

- New AI Memos show as live instant notices.
- Unread AI Memo alerts appear in the left navigation.
- AI Memos can be viewed under AI > Memos.

## Extending AI Memos

When an AI Memo is created, it spawns an AI Memo Created account event.

That event can trigger:

- A Function
- An Email Template
- Another AI Assistant

This allows AI-detected issues to become part of broader automation.

---

# Developer Data Objects

When AI Assistants trigger Functions or send Email Templates, AI-generated custom arguments are available.

## Custom Arguments Object

Custom arguments contain the argument name and AI-generated output.

Example:

```json
{
  "custom_arguments": {
    "customer_card_id": "XKob65Bn8qfqmWggp99B",
    "customer_card_type": "VISA"
  }
}
```

## Function Event Data

When an AI Assistant triggers a Function, the Function event data contains item details and custom arguments.

Typical structure:

```json
{
  "event": {
    "data": {
      "item_details": {
        "id": "Q4nGRNpLgpS92QqGLwlX",
        "first_name": "George",
        "last_name": "Washington"
      },
      "custom_arguments": {
        "...": "..."
      }
    }
  }
}
```

In Function code:

```javascript
event.data.item_details
event.data.custom_arguments
```

## Email Template Input Data

When an AI Assistant sends an SMTP message using an Email Template, the template input data contains item details and custom arguments.

Example:

```json
{
  "id": "Q4nGRNpLgpS92QqGLwlX",
  "first_name": "George",
  "last_name": "Washington",
  "custom_arguments": {
    "...": "..."
  }
}
```

In Email Template Handlebars:

```handlebars
{{custom_arguments.some_argument}}
```

---

# Ecommerce Workflow Examples

## Declined Sale Recovery Assistant

Trigger:

```text
Event: sale.created.failed.declined
```

Flow:

1. Start thread and retrieve sale details.
2. Review decline reason.
3. Branch:
   - Recoverable decline
   - Fraud/high-risk decline
   - Unknown decline
4. If recoverable, send recovery email.
5. Create note summarizing action.
6. End thread.

Recommended settings:

- Max Runs Per Item: `1`
- Delay: `5-10 minutes`
- Token limit enabled
- Optional filter Function for eligibility

---

## Chargeback Threat Detection

Trigger:

```text
Event: note.created
```

Flow:

1. Start thread and retrieve note/customer context.
2. Analyze note for chargeback threat.
3. Branch:
   - Threat detected
   - No threat
4. If threat detected:
   - Create AI Memo.
   - Optionally trigger Function or Email Template.
5. End thread.

---

## Gateway Failure Monitoring

Trigger:

```text
Schedule
```

Flow:

1. Run daily or hourly analysis.
2. Query recent transaction decline data.
3. Analyze whether decline rate is abnormal.
4. If abnormal, create AI Memo.
5. End thread.

---

## Subscription Renewal Failure Assistant

Trigger:

```text
Event: subscription_renewal.updated.failed
```

Flow:

1. Retrieve renewal and customer details.
2. Determine likely failure reason.
3. Branch:
   - Expired card
   - Insufficient funds
   - Gateway issue
   - Other
4. Send appropriate follow-up or create note.
5. End thread.

---

## Support Escalation Assistant

Trigger:

```text
On Demand from web app
```

Flow:

1. User triggers assistant from customer detail page.
2. AI reviews customer notes and recent purchases.
3. AI summarizes issue and recommends next action.
4. AI creates a note or memo.
5. End thread.

---

## AI Assistant Chain

Trigger:

```text
On Demand or Event
```

Flow:

1. Primary assistant analyzes the record.
2. Branch identifies specialty area.
3. Primary assistant triggers another assistant:
   - Chargeback assistant
   - Refund assistant
   - Subscription assistant
   - Fraud assistant
4. Specialized assistant completes its workflow.

---

---

# AI Assistant Metrics, API Calls, Revenue Performance, and BigQuery Reporting

AI Assistants become much more valuable when their work is measured.

RevCent stores AI Assistant-related API activity in BigQuery, which allows ecommerce businesses to run reports on AI Assistant performance, system-action usage, payment-related actions, refunds, revenue workflows, and operational outcomes.

For reporting, metrics, analytics, aggregations, dashboards, or data mining, MCP/AI should use:

```text
BigQueryRunQuery
```

Do not use paginated retrieval operations for metrics, counts, dashboards, aggregations, or data mining.

---

## Core BigQuery Tables for AI Assistant Reporting

The most important tables are:

| Table | Purpose |
|---|---|
| `revcent.user.ai_assistant` | Contains AI Assistants created by the user. Useful for assistant names, descriptions, enabled status, and assistant-level reporting. |
| `revcent.user.api_call` | Contains API/system actions. Includes `ai_assistant` when an API call was made by or associated with an AI Assistant. |
| `revcent.user.sale` | Useful when measuring revenue outcomes related to AI Assistant workflows. |
| `revcent.user.transaction` | Useful when measuring credit-card transaction outcomes, captures, refunds, or payment-related results. |
| `revcent.user.pending_refund` | Useful when analyzing refunds created or influenced by AI Assistant workflows. |
| `revcent.user.salvage_transaction` | Useful when analyzing decline recovery and salvage outcomes. |
| `revcent.user.note` | Useful when AI Assistants create or analyze notes. |
| `revcent.user.metadata` / repeated `metadata` fields on item tables | Useful when AI Assistants insert structured outcomes for later reporting. |

The two core reporting relationships are:

```text
api_call.ai_assistant → ai_assistant.id
```

and, for revenue analysis:

```text
api_call.ai_assistant → ai_assistant.id
api_call.type / api_call.method / api_call.code → action category and success/failure
AI-created or AI-related actions → sale / transaction / refund / metadata / note outcomes
```

Important:

```text
Before writing production SQL, MCP/AI should call GetBigQueryTables to confirm the current table schemas and exact field names.
```

---

## Why `api_call.ai_assistant` Matters

The `api_call` table can include:

```text
api_call.ai_assistant
```

This identifies API/system actions associated with an AI Assistant.

That allows RevCent users to report on what AI Assistants actually did, not just that they existed.

Examples:

```text
How many API actions did each AI Assistant perform?
Which AI Assistants created notes?
Which AI Assistants inserted metadata?
Which AI Assistants triggered Functions?
Which AI Assistants sent emails?
Which AI Assistants attempted sale/payment/refund actions?
Which AI Assistants had API errors?
Which AI Assistants are driving revenue-related activity?
```

This is especially important when AI Assistants are being used for revenue workflows such as:

```text
Declined sale recovery.
Subscription renewal recovery.
Trial conversion.
Abandoned checkout follow-up.
Refund triage.
Chargeback prevention.
Customer winback.
VIP/high-value customer follow-up.
```

---

# Discover AI Assistant API Action Types

Before writing a final report, MCP/AI should discover which `api_call.type` and `api_call.method` values exist for AI Assistant-driven actions.

```sql
SELECT
  ac.type,
  ac.method,
  COUNT(*) AS api_call_count,
  SUM(IF(ac.code = 1, 1, 0)) AS success_count,
  SUM(IF(ac.code != 1, 1, 0)) AS failure_count
FROM `revcent.user.api_call` ac
WHERE ac.created_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND ac.ai_assistant IS NOT NULL
GROUP BY ac.type, ac.method
ORDER BY api_call_count DESC
```

This helps identify the exact values used for actions such as:

```text
CreateNote
InsertMetadata
TriggerFunction
SendSMTPMessage
CreateSale
ProcessPendingSale
RefundTransaction
RefundProductSale
RefundShipment
RefundSubscriptionRenewal
VoidSale
CreateAIMemo
TriggerAIAssistant
BigQueryRunQuery
```

The exact `type` and `method` values should be based on the user's account data.

---

# AI Assistant System Action Performance

This report shows action counts, success counts, failure counts, and success rate by AI Assistant.

```sql
SELECT
  aa.id AS ai_assistant_id,
  aa.name AS ai_assistant_name,
  ac.type AS api_call_type,
  ac.method AS api_call_method,
  COUNT(*) AS api_action_count,
  SUM(IF(ac.code = 1, 1, 0)) AS success_count,
  SUM(IF(ac.code != 1, 1, 0)) AS failure_count,
  ROUND(SUM(IF(ac.code = 1, 1, 0)) * 100.0 / COUNT(*), 2) AS success_rate_percent
FROM `revcent.user.api_call` ac
LEFT JOIN `revcent.user.ai_assistant` aa
  ON ac.ai_assistant = aa.id
WHERE ac.created_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND ac.ai_assistant IS NOT NULL
GROUP BY
  ai_assistant_id,
  ai_assistant_name,
  api_call_type,
  api_call_method
ORDER BY api_action_count DESC
```

This report helps answer:

```text
Which AI Assistant is taking the most actions?
Which assistant has the highest success rate?
Which assistant has the most failed API calls?
Which assistant is creating notes, metadata, emails, Functions, or revenue actions?
```

---

# Revenue-Related AI Assistant Actions

If AI Assistants are being used for revenue purposes, the `api_call` table can help measure payment, sale, refund, and recovery-related activity.

Revenue-related system actions may include:

```text
CreateSale
ProcessPendingSale
AddCardToCustomer
EstimateSale
VoidSale
RefundTransaction
RefundProductSale
RefundShipment
RefundSubscriptionRenewal
RenewSubscription
SendSMTPMessage
TriggerFunction
InsertMetadata
CreateNote
```

Not all of these actions directly create revenue, but they can be part of revenue workflows.

Examples:

```text
Send recovery email after declined sale.
Trigger Function that calculates salvage eligibility.
Create note summarizing recovery attempt.
Insert metadata outcome such as ai_recovery_outcome = email_sent.
Create sale or process pending sale.
Renew subscription after customer updates payment.
Refund transaction/product/shipment/subscription renewal.
```

---

## Payment / Revenue Action Success-Failure by AI Assistant

This query uses keyword matching to identify likely payment, sale, refund, card, and pending-sale actions.

MCP/AI should refine this after discovering exact `type` and `method` values.

```sql
SELECT
  aa.id AS ai_assistant_id,
  aa.name AS ai_assistant_name,
  ac.type AS api_call_type,
  ac.method AS api_call_method,
  COUNT(*) AS revenue_action_count,
  SUM(IF(ac.code = 1, 1, 0)) AS successful_revenue_actions,
  SUM(IF(ac.code != 1, 1, 0)) AS failed_revenue_actions,
  ROUND(SUM(IF(ac.code = 1, 1, 0)) * 100.0 / COUNT(*), 2) AS success_rate_percent
FROM `revcent.user.api_call` ac
LEFT JOIN `revcent.user.ai_assistant` aa
  ON ac.ai_assistant = aa.id
WHERE ac.created_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND ac.ai_assistant IS NOT NULL
  AND REGEXP_CONTAINS(
    LOWER(CONCAT(ac.type, ' ', ac.method)),
    r'sale|payment|transaction|refund|card|pending|renew|subscription|smtp|metadata|note|function'
  )
GROUP BY
  ai_assistant_id,
  ai_assistant_name,
  api_call_type,
  api_call_method
ORDER BY revenue_action_count DESC
```

Use this for:

```text
Revenue workflow action counts.
Payment-related action success/failure.
Refund action success/failure.
Recovery email activity.
Function-triggered recovery workflows.
Metadata/note outcome creation.
```

---

# AI Assistant Revenue Performance Reporting

Revenue performance usually requires joining AI Assistant API activity to sales, transactions, subscription renewals, salvage transactions, or metadata outcomes.

Because revenue attribution depends on the workflow, there is no single universal query.

Possible attribution models include:

```text
Direct action attribution:
Revenue is attributed to an AI Assistant when an AI Assistant directly creates or processes the sale/payment action.

Follow-up attribution:
Revenue is attributed to an AI Assistant when a sale/payment succeeds within X hours after the assistant sends an email, inserts recovery metadata, triggers a Function, or creates a recovery note.

Item-based attribution:
Revenue is attributed to an AI Assistant when the assistant was triggered by or acted on a specific sale, subscription renewal, salvage transaction, customer, or other item.

Metadata attribution:
Revenue is attributed to an AI Assistant when the assistant inserts structured metadata that later identifies the recovery or campaign outcome.
```

MCP/AI should choose the attribution model based on the user’s question.

---

## Example: AI Assistant API Revenue Workflow Activity

This report summarizes AI Assistant activity that is likely tied to revenue workflows.

```sql
SELECT
  aa.id AS ai_assistant_id,
  aa.name AS ai_assistant_name,
  COUNT(*) AS total_api_actions,
  SUM(IF(ac.code = 1, 1, 0)) AS successful_api_actions,
  SUM(IF(ac.code != 1, 1, 0)) AS failed_api_actions,
  SUM(IF(REGEXP_CONTAINS(LOWER(CONCAT(ac.type, ' ', ac.method)), r'sale|payment|transaction|card|pending|renew'), 1, 0)) AS payment_or_sale_actions,
  SUM(IF(REGEXP_CONTAINS(LOWER(CONCAT(ac.type, ' ', ac.method)), r'refund|void'), 1, 0)) AS refund_or_void_actions,
  SUM(IF(REGEXP_CONTAINS(LOWER(CONCAT(ac.type, ' ', ac.method)), r'smtp|email'), 1, 0)) AS email_actions,
  SUM(IF(REGEXP_CONTAINS(LOWER(CONCAT(ac.type, ' ', ac.method)), r'metadata'), 1, 0)) AS metadata_actions,
  SUM(IF(REGEXP_CONTAINS(LOWER(CONCAT(ac.type, ' ', ac.method)), r'note'), 1, 0)) AS note_actions,
  SUM(IF(REGEXP_CONTAINS(LOWER(CONCAT(ac.type, ' ', ac.method)), r'function'), 1, 0)) AS function_actions
FROM `revcent.user.api_call` ac
LEFT JOIN `revcent.user.ai_assistant` aa
  ON ac.ai_assistant = aa.id
WHERE ac.created_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND ac.ai_assistant IS NOT NULL
GROUP BY
  ai_assistant_id,
  ai_assistant_name
ORDER BY payment_or_sale_actions DESC, total_api_actions DESC
```

This is a good starting report for answering:

```text
Which AI Assistants are doing the most revenue-related work?
Which assistants are sending recovery emails?
Which assistants are triggering Functions?
Which assistants are inserting metadata outcomes?
Which assistants are creating notes?
Which assistants are attempting payment/refund actions?
```

---

## Example: Revenue Associated With AI Assistant Actions

The following is a schema-dependent example showing how a business might analyze sales after AI Assistant activity.

MCP/AI must confirm the `sale` table fields with `GetBigQueryTables`, including the correct amount/status/customer fields.

```sql
SELECT
  aa.id AS ai_assistant_id,
  aa.name AS ai_assistant_name,
  COUNT(DISTINCT ac.id) AS ai_api_actions,
  COUNT(DISTINCT s.id) AS related_sales,
  SUM(s.amount) AS related_sale_amount
FROM `revcent.user.api_call` ac
LEFT JOIN `revcent.user.ai_assistant` aa
  ON ac.ai_assistant = aa.id
LEFT JOIN `revcent.user.sale` s
  ON s.created_at >= ac.created_at
WHERE ac.created_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND ac.ai_assistant IS NOT NULL
  AND s.created_at < TIMESTAMP_ADD(ac.created_at, INTERVAL 24 HOUR)
GROUP BY
  ai_assistant_id,
  ai_assistant_name
ORDER BY related_sale_amount DESC
```

Important:

```text
This is only a starting attribution pattern.
It should be refined to join on customer, sale ID, metadata, API call outputs, or item-specific workflow data where available.
If the sale table uses a field other than amount, replace s.amount with the confirmed revenue field.
If the report should only count paid/successful sales, add the confirmed sale status/payment filters.
```

A better production report should usually define:

```text
Which assistant action counts as influence.
Which customer/item/sale relationship proves attribution.
What time window counts as recovery.
Which sale statuses count as successful revenue.
Whether refunds/chargebacks should be deducted.
```

---

# AI Assistant Payment Attempt and Refund Reporting

AI Assistants can be used in workflows that attempt, recover, refund, void, or analyze payment activity.

Use the `api_call` table to report on the success/failure of these actions.

Useful questions:

```text
How many payment-related actions did each AI Assistant attempt?
How many payment actions succeeded?
How many payment actions failed?
Which assistant has the highest failed action rate?
Which assistant attempted refunds?
Which assistant attempted sale creation or pending-sale processing?
Which assistant created metadata or notes after payment workflows?
```

Example:

```sql
SELECT
  aa.name AS ai_assistant_name,
  ac.type AS api_call_type,
  ac.method AS api_call_method,
  ac.code AS response_code,
  COUNT(*) AS action_count
FROM `revcent.user.api_call` ac
LEFT JOIN `revcent.user.ai_assistant` aa
  ON ac.ai_assistant = aa.id
WHERE ac.created_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND ac.ai_assistant IS NOT NULL
  AND REGEXP_CONTAINS(
    LOWER(CONCAT(ac.type, ' ', ac.method)),
    r'sale|payment|transaction|refund|void|card|pending|renew'
  )
GROUP BY
  ai_assistant_name,
  api_call_type,
  api_call_method,
  response_code
ORDER BY action_count DESC
```

---

# Notes, Metadata, and Revenue Outcome Tracking

For revenue-focused AI Assistants, notes and metadata are often the best way to make outcomes reportable.

Example:

```text
Assistant analyzes declined sale.
Assistant sends recovery email.
Assistant inserts metadata:
ai_assistant_recovery_outcome = recovery_email_sent
```

Later, BigQuery can report on:

```text
Sales with recovery metadata.
Customers with assistant recovery actions.
Revenue after recovery_email_sent.
Recovery outcome by assistant.
Refund/chargeback rate after assistant action.
```

Recommended pattern:

```text
API Call = what the assistant did.
Metadata = structured durable outcome.
Note = concise human-readable explanation.
Sale/transaction/subscription tables = revenue result.
BigQuery = cross-table reporting.
```

Metadata should be controlled and not flooded.

Do not insert metadata for every internal reasoning step. Insert only actionable/reportable outcomes.

---

# AI Assistant Performance KPIs for Ecommerce

Useful KPIs include:

```text
Total API actions by AI Assistant.
API success rate by AI Assistant.
API failure rate by AI Assistant.
Revenue-related actions by AI Assistant.
Payment action success/failure.
Refund action count and success/failure.
Emails sent by AI Assistant.
Functions triggered by AI Assistant.
Notes created by AI Assistant.
Metadata inserted by AI Assistant.
AI Memos created by AI Assistant.
Sales/revenue within a defined window after assistant action.
Recovered revenue from declined-sale assistant workflows.
Subscription renewals recovered after assistant workflows.
Chargeback or refund rate after assistant intervention.
```

These KPIs help ecommerce businesses evaluate whether AI Assistants are improving:

```text
Revenue recovery.
Customer retention.
Subscription renewal salvage.
Support efficiency.
Refund handling.
Chargeback prevention.
Risk monitoring.
Operational automation.
```

---

# MCP/AI BigQuery Guidance for AI Assistant Metrics

When the user asks for AI Assistant performance or revenue reporting:

1. Use `BigQueryRunQuery`, not paginated list operations, for metrics.
2. Call `GetBigQueryTables` first to confirm schemas.
3. Use `revcent.user.ai_assistant` for assistant names, descriptions, and enabled status.
4. Use `revcent.user.api_call` for AI Assistant system actions.
5. Use `api_call.ai_assistant` to identify API calls associated with an AI Assistant.
6. Use `api_call.type`, `api_call.method`, and `api_call.code` to classify actions and success/failure.
7. Join sale, transaction, subscription renewal, salvage transaction, pending refund, metadata, and note tables as needed for the business question.
8. Use date filters to reduce query cost and avoid timeouts.
9. Discover actual `type` and `method` values before writing highly specific reports.
10. Define a clear attribution model before claiming revenue was caused by an AI Assistant.
11. Treat revenue reports as attribution analysis unless the assistant directly created/processed the sale/payment.

# Best Practices

## Naming

Use names that explain trigger and purpose.

Good:

```text
Declined Sale - Recovery Analysis
Chargeback Created - Risk Memo
Daily Revenue - AI Summary
Customer Note - Chargeback Threat Detection
Subscription Renewal Failed - Retention Assistant
```

Poor:

```text
AI 1
Test Bot
Ryan Assistant
```

## Descriptions

Descriptions are highly recommended.

Include:

- What triggers the assistant.
- What the assistant analyzes.
- What actions it may take.
- Whether it creates notes, memos, emails, or Functions.
- Whether another assistant may trigger it.

## Instructions

Use AI Instructions for broad behavior.

Use Thread Steps for specific actions.

## Triggers

Use the narrowest safe trigger.

Prefer:

```text
sale.created.failed.declined
```

over:

```text
sale.created
```

## Limits

Set limits to control cost and prevent runaway automation.

Recommended:

- Max Tokens Per Thread
- Max Tokens Per Day
- Max Runs Per Item
- Max Tokens Per User for web access

## Reporting and Measurement

Use `BigQueryRunQuery` with `api_call.ai_assistant` to measure AI Assistant performance, system-action success/failure, and revenue workflow outcomes.

For revenue-focused assistants, define the attribution model clearly before claiming revenue was caused by an assistant. Use API calls, metadata, notes, sales, transactions, salvage transactions, and subscription renewal tables together when needed.

## Testing

Before enabling:

1. Create assistant disabled.
2. Test on a controlled item.
3. Review AI Thread details.
4. Check token usage.
5. Confirm branches behave correctly.
6. Confirm tool calls are safe.
7. Confirm memos/emails/notes are correct.
8. Enable only after validation.

---

# Common Pitfalls

## Putting Actions in AI Instructions

Avoid putting detailed workflow actions in base instructions.

Better:

- AI Instructions: broad role.
- Thread Steps: specific actions.

## Too-Broad Event Triggers

Avoid triggering on broad events unless the flow can handle all subtypes.

For example, `sale.created` may include success, failure, pending, fraud, and other sale outcomes.

## Not Setting Max Runs Per Item

Failing to set this can cause repeated runs for the same item.

Recommended:

```text
Max Runs Per Item = 1
```

## Branch Conditions Too Vague

Bad:

```text
Output 1: good
Output 2: bad
```

Better:

```text
Output 1: The declined sale appears recoverable because the decline reason is soft or customer-actionable.
Output 2: The declined sale appears high risk or fraud-related and should not be retried.
```

## No Cost Limits

Without token limits, scheduled or event-driven assistants can consume more AI tokens than expected.

## Not Reviewing AI Threads

AI Threads show what the AI did and why. Use them to refine prompts and branch logic.

---

# Quick Decision Guide

| Goal | Recommended Trigger / Feature |
|---|---|
| React to a sale, refund, shipment, chargeback, or customer event | Event trigger |
| Let a user manually run AI from RevCent | On Demand + Web Access |
| Let an API or MCP trigger AI | On Demand + API |
| Let one assistant trigger another | On Demand + System Tool |
| Run daily or periodic analysis | Schedule trigger |
| Limit event-triggered runs to specific campaigns/statuses/metadata | Filters |
| Use custom logic to decide whether AI should run | Filter Function |
| Split workflow based on AI reasoning | Thread Branch |
| Wait before continuing workflow | Time Delay |
| Alert users to important findings | AI Memo |
| Control cost | Usage limits |

---

# Summary

AI Assistants are RevCent’s AI automation layer for ecommerce.

They can watch events, run on schedules, be triggered manually, or be triggered by other assistants. Once triggered, they run a configurable thread that can analyze data, branch based on AI reasoning, use tools, create notes, send emails, run Functions, create AI Memos, and automate complex business workflows.

For ecommerce businesses, AI Assistants are most valuable when they are focused, well-triggered, limited for cost and safety, and designed with clear thread steps.


---
Document Parent Directory
* [Operations](https://revcent.com/documentation/markdown/mcp/operation/index.md) - AI/MCP details and overviews for operations available within the RevCent MCP.