# A/B testing
A/B testing shows different versions of the AI agent's behavior to different customers, so you measure what works instead of guessing. Test whether a generous retention offer keeps more customers than a conservative one, or whether a casual tone earns better satisfaction scores than a formal one.
Each customer is assigned to a group once and stays in it for the whole conversation. The assignment is tagged on the conversation, so you can compare the groups in Metrics and in the help desk.
The quickest way to set one up is to ask Copilot or your own AI agent:
Set up an A/B test on the returns workflow: half of customers get a casual
tone, half a formal one. Tag the groups so I can compare resolution rate and
CSAT in two weeks.
Copilot writes and tests the setup for you. The technical details are in [For developers and AI agents](#for-developers-and-ai-agents) at the end of this page.
How it works [#how-it-works]
A/B tests combine two building blocks:
* A [condition provider](/docs/developers/condition-providers): a short piece of code that runs when a workflow is loaded. It assigns the customer to a group at random, remembers the choice for the conversation and tags the conversation with the group.
* [Workflow variants](/docs/ai-agent/workflows#variants): different instructions for the same workflow. Octocom picks the first variant whose required conditions are all true, so each customer gets the instructions for their group.
For example, to test whether a warm, casual tone leads to better outcomes than a formal one when handling returns, the "Return request" workflow gets two variants:
| Variant | Condition | Instructions |
| ------- | ---------- | ------------------------------------------------------------------------------------------------------ |
| Casual | `isCasual` | Use a warm, conversational tone. Use first names. Say things like "No worries, let's get this sorted!" |
| Formal | `isFormal` | Use a professional tone. Address the customer formally. Say "We apologize for the inconvenience." |
Both variants follow the same steps (collect the order details, confirm the return) with different wording. Customers in each group are tagged `ab:return-tone:casual` or `ab:return-tone:formal`.
A split doesn't have to be even. To be cautious, you can show a new flow to only 20% of customers and keep everyone else on the current one. A test can also sit alongside checks on live data, for example testing two retention offers only for orders that have already shipped.
Measure the results [#measure-the-results]
Once enough conversations have run, compare the two groups:
* **In Metrics,** add a **Tags** filter for `ab:return-tone:casual`, note the numbers, then switch the filter to `ab:return-tone:formal`. Compare resolution rate, handoffs and CSAT. The **Workflow Usage** chart on the **AI performance** tab can also be grouped by variant.
* **In the help desk,** filter or build a [view](/docs/help-desk/views) on each tag to read conversations from each group side by side.
Tips [#tips]
* **Start with equal weights.** Skew the split only if you're worried about the new version's impact. You can change it later.
* **Test one thing at a time.** If you change the tone *and* the refund amount in the same test, you won't know which made the difference.
* **Give it time.** A test needs enough conversations to be meaningful. Don't draw conclusions from 20 conversations.
* **Use descriptive test names.** `"refund-strategy-v2"` is better than `"test1"`. The name appears in tags and metadata, so make it easy to find.
* **Test both versions before you start.** Groups are assigned at random. To test a specific group, ask Copilot to start a [test conversation](/docs/ai-agent/testing) with the conversation metadata `ab_test:your-test-name` set to that group's name (the `metadata` option of `start_conversation`). `get_ab_test_variant` then returns that group instead of picking one.
* **Clean up when you're done.** Once you've picked a winner, keep the winning variant's instructions in the workflow and remove the condition provider.
For developers and AI agents [#for-developers-and-ai-agents]
The code is short, and Copilot or your own agent through [Octocom MCP](/docs/developers/mcp) can write and test it for you. The helper is documented in [`get_ab_test_variant`](/docs/developers/python-helpers/get-ab-test-variant).
A simple test: two response styles [#a-simple-test-two-response-styles]
The tone test from [How it works](#how-it-works), step by step.
Create a condition provider [#create-a-condition-provider]
```python
def evaluate_conditions(context):
variant = get_ab_test_variant(context, "return-tone", ["casual", "formal"])
return {
"conditions": {
"isCasual": variant == "casual",
"isFormal": variant == "formal",
},
"data": {},
}
```
That's the whole condition provider. `get_ab_test_variant` picks a group at random (50/50 by default), remembers it for this conversation, and tags the conversation with `ab:return-tone:casual` or `ab:return-tone:formal`.
Set up workflow variants [#set-up-workflow-variants]
In the "Return request" workflow, create the two variants from [How it works](#how-it-works): **Casual** requires `isCasual` and **Formal** requires `isFormal`. Each customer gets the variant that matches their group.
Control the split with weights [#control-the-split-with-weights]
By default, `get_ab_test_variant` splits traffic evenly. To be cautious, for example showing a new flow to only 20% of customers, give the groups weights:
```python
def evaluate_conditions(context):
variant = get_ab_test_variant(
context,
"new-cancel-flow",
[
{"name": "control", "weight": 4}, # 80%
{"name": "new_flow", "weight": 1}, # 20%
],
)
return {
"conditions": {
"isNewFlow": variant == "new_flow",
},
"data": {},
}
```
Weights are relative: `4` and `1` mean 80/20. `80` and `20` give the same result.
With two groups you only need one condition. The control variant is the default (last in the variant list, with no conditions), and the new flow's variant requires `isNewFlow`.
| Variant | Condition | Instructions |
| -------- | ----------- | ------------------------------ |
| New flow | `isNewFlow` | The new cancellation flow |
| Control | *(none)* | The existing cancellation flow |
Combine an A/B test with real data [#combine-an-ab-test-with-real-data]
A condition provider can also check the state of another system, so one provider can handle both. For example: test two refund offers, but only for orders that haven't been refunded already.
```python
import requests
def evaluate_conditions(context):
order_id = context["args"]["orderId"]
# Fetch order state 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()
# Determine A/B variant
variant = get_ab_test_variant(context, "refund-strategy", ["standard", "generous"])
return {
"conditions": {
"orderNotFound": False,
"isRefunded": order.get("refundedAt") is not None,
"isShipped": order.get("shippedAt") is not None,
"isGenerous": variant == "generous",
},
"data": {
"orderTotal": order.get("total"),
},
}
```
The workflow variants handle both the state checks and the split:
| # | Variant | Conditions | Instructions |
| - | ---------------- | ------------------------- | ------------------------------------------ |
| 0 | Not found | `orderNotFound` | Ask customer to double-check order ID |
| 1 | Already refunded | `isRefunded` | Inform customer, no further action |
| 2 | Generous offer | `isShipped`, `isGenerous` | Offer 30% partial refund to keep the order |
| 3 | Standard offer | `isShipped` | Offer 15% partial refund to keep the order |
| 4 | Default | *(none)* | Process cancellation normally |
The state checks (not found, already refunded) come first, so they always take priority. The split only matters in the "shipped" case, where you're testing two retention offers.
What get_ab_test_variant records [#what-get_ab_test_variant-records]
The first time `get_ab_test_variant` runs for a test in a conversation, it:
1. Picks a group at random, using the weights
2. Saves the choice as conversation metadata (`ab_test:your-test-name`)
3. Tags the conversation with `ab:your-test-name:variant-name`
4. Adds an event to the conversation timeline
Later calls with the same test name in the same conversation return the saved group, so the customer always sees the same version.
# Actions
An action is how the AI agent does things in your systems. Because an action can be any code, the AI agent can do anything your systems allow: refund an order, update a policy, book a technician. That is the difference between "I'll pass this to the team" and "Done, your new address is saved."
What you can do [#what-you-can-do]
If your team can do it in one of your systems, the AI agent can do it with an action. A few examples:
| Business | Example actions |
| -------------------------- | --------------------------------------------------------------------------------------------------------------- |
| Retail and brands | Look up an order and its tracking, change the delivery address, cancel an unshipped order, start a return |
| Subscriptions | Pause, skip or cancel a subscription, move the next delivery date, apply the retention offer your rules allow |
| Insurance | Report a claim's status, check what a policy covers, resend policy documents, record a new claim |
| Telecom | Check a data balance or a SIM's activation, change a plan, check for an outage at an address, book a technician |
| B2B and services | Look up an invoice or an account balance, create a quote as a PDF, open a ticket in your CRM or ERP |
| Marketplaces and platforms | Check a payout, restore a member's access, look up an order across sellers |
| Any business | Tag and route the conversation, notify a team channel, email a supplier, save details for reporting |
One action can also do several things in order. A refund action can find the order in your store, apply your 30-day rule, issue the refund in your payment system and log it in a spreadsheet, all in one step. The AI agent gets back only what the action returns.
Any system, even without an API [#any-system-even-without-an-api]
* **Anything with an API.** Order systems, CRMs, ERPs, billing, policy and booking systems, and internal tools. Python actions read API keys and passwords from an encrypted secret store, so credentials stay out of the code.
* **Websites with no API.** Browser automation signs in to a portal or back office and makes the clicks a person would. It checks the page before and after every step, and stops instead of guessing when something looks different.
* **Databases and spreadsheets.** An action can run read-only queries against a SQL Server database, and read and update Google Sheets.
* **Platforms you connected in Octocom.** For Shopify, Stripe, Recharge and other connected platforms, actions call the platform's own API through the connection you already set up.
* **Systems that only accept known IP addresses.** Requests can come from a fixed Octocom IP address that you add to the system's allowlist.
See [Connect any system](/docs/overview/connect-any-system) for the full picture.
Set it up [#set-it-up]
Describe what the action should do, which system it talks to and when the AI agent may use it. Copilot or your own AI agent builds the action, tests it against your system, adds it to the right workflow and runs a test conversation to check the result.
Connect our order system's API so the AI agent can look up an order by order
number and email. If the order hasn't shipped, let it cancel the order once
the customer confirms. Test it on one of our test orders first.
Our claims portal has no API. Teach the AI agent to look up a claim's status
there by claim number, and use it in our claim status workflow.
When Copilot learns a website's steps with you, you approve each click and form entry. [Connect a system that has no API](/docs/guides/connect-a-system-without-an-api) walks through it. For complex or high-stakes integrations, Octocom's solution engineers can review the actions and test them with you.
To build an action yourself, go to **Settings -> Automation -> Custom Actions**. An action is shared by all businesses in your organization by default, or you can limit it to specific ones.
How actions work [#how-actions-work]
Actions are switched on inside workflows [#actions-are-switched-on-inside-workflows]
An action does nothing until a [workflow](/docs/ai-agent/workflows) includes it. Each workflow lists the actions the AI agent may use in that situation, under **Available Actions** in the workflow editor, chosen per variant. The workflow's instructions say when to call each one:
> 1. Ask for the order number and the email address used for the order.
> 2. Call `lookupOrder` with both.
> 3. If the order has not shipped, summarize the cancellation and ask the customer to confirm.
> 4. After they confirm, call `cancelOrder`.
> 5. If the order has shipped, explain the return process instead.
This ties every action to the situation and the steps it was built for. A refund action included only in your refund workflow is only offered there, together with that workflow's eligibility checks. Instructions in a bot rule or an article cannot switch an action on. [How the AI agent works](/docs/ai-agent/how-it-works#workflows-and-where-tools-come-from) explains when a workflow's actions become available during a conversation.
Three ways to reach your systems [#three-ways-to-reach-your-systems]
* **API actions** call one endpoint of your system's API, with values the AI agent fills in, such as an order number. No code is involved.
* **Python actions**, called **Code Action** in the dashboard, run general-purpose Python. One action can call several systems, check eligibility and return only what matters.
* **Browser automation** lets a Python action work in a website or back office that has no usable API.
Built-in and custom actions [#built-in-and-custom-actions]
Some capabilities are built in and need no setup: searching your knowledge base and products, reading files the customer attaches, and handing the conversation to your team. Some connected platforms add built-in actions of their own. Everything specific to your business is a **custom action**: you create it once and can use it in any workflow.
Confirmation and human approval [#confirmation-and-human-approval]
Actions that change something, such as a cancellation, a refund or a plan change, deserve care. You decide how much a person is involved, from the customer's yes to a teammate's sign-off.
* **Ask the customer first.** Write a confirmation step into the workflow, as in the example above. The AI agent summarizes exactly what will happen and acts only after the customer agrees. In web chat with [widget elements](/docs/channels/web-chat/configuration#widget-elements) on, it shows a card with two buttons, such as **Yes, cancel it** and **No, keep it**. On other channels it asks in text.
* **Enforce the rules in the action itself.** Instructions guide the AI agent. Code enforces. When something must hold every time, such as "the order must belong to this email address" or "refunds only within 30 days", the action checks it and refuses otherwise. See [Customer authentication](/docs/security/customer-authentication).
* **Ask your team to decide.** For a policy exception or a review of damage photos, an action can send a decision request to your team. The AI agent keeps the conversation and continues once someone answers. See [Human-in-the-loop decisions](/docs/developers/human-in-the-loop).
* **Review email replies.** With [AI reply approval](/docs/ai-agent/ai-reply-approval), an agent approves each AI email reply before it is sent. The AI agent runs its actions while it drafts, so approval covers the reply, not the action. Use a decision request when a person must approve the change itself.
* **Check replies automatically.** [Bot QA](/docs/ai-agent/bot-qa) can flag a reply that, for example, confirms a refund no action actually made. On supported channels it can stop the reply and hand the conversation to your team.
When a customer asks for a refund over 200 euros, send the request to our team
for approval first. Keep the conversation with the AI agent, and issue the
refund only after someone approves.
Whatever an action returns, the AI agent can read and may repeat to the customer. Return only what the customer is allowed to see.
Test actions [#test-actions]
1. **Test the action on its own.** Open it and use **Test Action** with sample inputs, or ask Copilot to test it. The test makes the real request, so use test records when the action changes data.
2. **Test it in a conversation.** Run a test conversation that goes through the workflow, including the paths where the order isn't found or the customer declines. See [Test your AI agent](/docs/ai-agent/testing).
3. **Check what happened.** The debug view of any AI reply shows which actions ran, with their inputs and results. See [How the AI agent works](/docs/ai-agent/how-it-works#debugging-the-loop-is-fully-observable).
Actions keep a version history, so you can restore an earlier version if a change misbehaves.
For developers and AI agents [#for-developers-and-ai-agents]
[Custom actions](/docs/developers/custom-actions) is the technical contract: naming, arguments, API action configuration, the Python `execute_action` function, timeouts, testing and security. Related references:
* [Python helpers](/docs/developers/python-helpers): built-in functions for orders, messages, sheets, credentials and more.
* [Chat UI from actions](/docs/developers/chat-ui-from-actions): cards, confirmations and quick replies in web chat.
* [Browser automation](/docs/developers/browser-automation): guarded website steps for systems without an API.
* [Secrets](/docs/developers/secrets): credentials your code reads at runtime.
* [Condition providers](/docs/developers/condition-providers): code that picks a workflow variant from live data.
* [Integration patterns](/docs/developers/integration-patterns): how the building blocks combine.
# AI reply approval
AI reply approval holds every AI email reply as a draft until someone on your team approves it. The AI agent still drafts a reply for each customer email, but nothing reaches the customer until an agent selects **Approve & send**.
Use it when your team wants to read every AI reply before customers see it: in your first days live, for a sensitive inbox, or while you tune a new workflow. Rejected drafts and your team's reasons show what to improve.
Turn it on [#turn-it-on]
Reply approval is a setting on each email inbox, so you can require it for one address and let another reply on its own.
* **Dashboard:** **Settings -> Channels -> Email**, open the address and, under **AI replies**, switch on **Approve replies before sending**.
* **Copilot, MCP or REST:** set `aiReplyApprovalRequired: true` with `update_email_inbox` or `PATCH /rest/v1/email-inboxes/{inboxId}`. See [Email inbox settings](/docs/channels/email/settings).
[Contact form](/docs/channels/contact-form) conversations follow the inbox they reply from, which is the business's primary inbox when the form did not arrive by email.
The AI agent calls its actions while it drafts the reply, before anyone
approves it. If it can refund, cancel or change orders, those changes happen
even when you later reject the reply. Before turning on approval, make sure
every action the AI agent can take is safe to run unreviewed: lookups, or a
request your team processes by hand (for example a row added to a sheet)
instead of the change itself. To have a person approve a specific action
before it runs, use [human-in-the-loop
decisions](/docs/developers/human-in-the-loop).
Review a draft [#review-a-draft]
A draft shows in the conversation with a dashed border, marked **Draft · Not sent yet**. The customer sees nothing until it is approved.
| Action | What happens |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Approve & send** | The reply is sent as written. If the AI meant to hand the conversation to your team after this reply, the handoff happens now. |
| **Reject** | You can say what's wrong with the reply. It is never sent, it stays in the thread marked **Rejected · Not sent**, and the conversation is [handed off](/docs/ai-agent/human-escalation) to your team. |
AI replies can't be edited, here or anywhere else in the help desk. Approve the reply as the AI wrote it, or reject it and reply yourself, so the thread always shows what the AI actually produced.
Approving or rejecting is recorded in the conversation's activity with the agent's name, and a rejection reason appears there too. A draft that someone else already handled cannot be approved or rejected again.
Why reasons matter [#why-reasons-matter]
Rejecting a draft and taking over a conversation from the header both ask why. The reason is optional, but every one given there is stored, so your team can see what the AI gets wrong and fix it with workflows, rules or knowledge. The more specific the reason, the more useful it is: "it promised an address change, but we can't change addresses after an order is placed" beats "wrong".
When the conversation changes first [#when-the-conversation-changes-first]
* **The customer writes again:** the AI drafts a new reply that covers the new message, and the old draft is removed. If the old draft's turn changed something (such as an order) or was going to hand off, it is kept next to the new one instead, so you can see what happened. Lookups alone don't count as a change.
* **An agent takes over, hands off or closes the conversation:** waiting drafts are cancelled and never sent.
* **Auto-close:** a conversation with a waiting draft is not closed for inactivity. The inactivity timer starts again when you approve the reply.
A queue for drafts and decisions [#a-queue-for-drafts-and-decisions]
Conversations that wait on a person match the **Awaiting input** filter. That covers:
* an AI reply draft waiting for approval, and
* a pending [decision card](/docs/guides/approvals-from-outside-octocom) that someone has to answer.
Save it as a [view](/docs/help-desk/views), for example **Needs approval**: `Awaiting input = Yes`, `Status = Open`. A conversation leaves the view as soon as the draft is approved or rejected and every card is answered. In the conversation list, these conversations show a small clipboard mark instead of the AI agent mark.
Limits [#limits]
* Drafts don't expire, unlike decision cards. A conversation with a waiting draft stays open and in your queue until someone approves or rejects it, so make sure someone works the view.
* Approval applies to AI replies on email, including replies to contact forms. On other channels the AI agent replies immediately. [Bot QA](/docs/ai-agent/bot-qa) can check replies on web chat, Instagram and Messenger.
* Test and playground conversations are not held for approval. See [Test your AI agent](/docs/ai-agent/testing).
* The response delay set on the inbox still applies before the AI drafts. Once approved, the reply is sent right away.
# Bot QA
Bot QA automatically checks the AI agent's work against your quality rules. It flags the mistakes that matter, such as an unsupported refund confirmation or a promise outside your policy, so you don't have to read every conversation to find them. On email, Instagram and Messenger, a check can stop a bad reply before the customer sees it.
Each check runs in one of two ways, chosen when you create it:
* **Each reply** checks a proposed AI reply before it reaches the customer, and can stop it. Most of this page is about reply checks.
* **Whole conversation** checks the whole conversation once, after it ends, including phone calls. See [Whole-conversation checks](#whole-conversation-checks).
You decide what each check looks for and what happens when it finds an issue: **record the finding and continue**, or **cancel the reply and [hand the conversation to a person](/docs/ai-agent/human-escalation)**. You can also ask Copilot to set up alerts for your team.
Bot QA is available to every business. **Automatic checks start off**, so you can review the rules and test them before turning them on. Configuration is separate for each business.
When to use Bot QA [#when-to-use-bot-qa]
| Use case | Example check | Possible response |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| Unsupported action confirmations | The bot says a refund, cancellation or shipment change is complete, but the available action results do not support that claim. | Cancel and hand off. |
| Policy compliance | The reply offers a remedy or guarantee that contradicts your documented policy. | Cancel and hand off for important violations. |
| Sensitive product claims | The reply makes health or product claims outside the approved information you provided. | Use a focused custom check and route confirmed violations to your team. |
| Workflow compliance | A returns reply omits a required step from the returns workflow. | Apply a check specifically to that workflow. |
| Language and presentation | The reply ignores an explicit language or formatting instruction. | Record the finding and continue, then use the results to improve your instructions. |
QA is an additional review of the reply. Keep your [knowledge](/docs/ai-agent/knowledge-base), [bot rules](/docs/ai-agent/bot-rules) and [workflows](/docs/ai-agent/workflows) accurate too. A QA check can flag a claim against the approved information available to it; it cannot establish that all of your source material is correct or certify regulatory compliance.
What gets checked [#what-gets-checked]
QA checks replies written by the AI model. Fixed messages are not checked, because they are deterministic and there is nothing for QA to judge: web chat greetings, messages sent by your automations with [`send_bot_message`](/docs/developers/python-helpers/send-bot-message), and other hard-coded text. These messages have no QA result and do not fire the **Bot Message QA Completed** event.
How it works [#how-it-works]
1. **The bot prepares a reply.** It may already have run actions as part of handling the request.
2. **QA reviews the proposed message.** It uses the preceding conversation, the bot's instructions, applicable workflows, available action results and the conversation's activity log. Global checks apply to every supported message. Workflow checks apply when their workflow was used, including workflows embedded in the bot's instructions.
3. **Potential failures receive a verification review.** The review checks the same evidence before deciding whether a suspected violation is supported.
4. **Your configured reaction determines delivery.** A confirmed violation on a check set to **Hand off to a person** cancels the proposed message and hands the conversation to your team. Otherwise, delivery continues.
5. **Results become available for reporting and alerts.** Confirmed findings include an explanation and supporting evidence. Event handlers can notify your team after the result is stored.
QA checks the message **before an email's configured sending delay**, rather than rechecking it when that delay expires. Turning QA on affects new messages; it does not review or retract previously sent messages.
Supported channels [#supported-channels]
| Channel | When QA runs | What **Hand off to a person** does |
| --------------------------- | ----------------------------- | -------------------------------------------------------------------- |
| Email, Instagram, Messenger | Before the reply is delivered | Cancels the reply and hands the conversation off. |
| Web chat | Right after the reply is sent | Hands the conversation off. The customer has already seen the reply. |
Web chat customers are waiting live, so QA does not hold their reply. It checks each reply in the background as soon as it is sent, including streamed replies once they finish. A confirmed violation on a check set to **Hand off to a person** hands the conversation to your team, who can follow up with a correction.
Reply checks don't run on phone calls: a call can't be held or cancelled mid-call. Use [whole-conversation checks](#whole-conversation-checks) for calls. Bot QA doesn't check WhatsApp or public social comments. The same channel limits apply when testing an existing message.
Checks and reactions [#checks-and-reactions]
Octocom supplies universal checks covering instruction compliance, action confirmations, factual grounding, usable output, language and presentation. They always run, because they are how quality is measured the same way across every bot. You decide what happens with the result: choose each check's reaction and which results reach your alerts. You can also add global checks for your business or checks for a particular workflow.
The usable output check judges who a reply is written to, not only whether it reads well. A note about the customer, such as "I've sent Sean a reply explaining the two orders", is flagged even when a correct reply follows it. Replies written to the customer that mention sending or emailing them something pass.
It also flags leaked model reasoning: the bot talking to itself about its instructions, such as "Wait, I must not invent product details", "I should follow the cancellation workflow" or "Let me rewrite", or several drafts of the same reply in one message. One such sentence is enough, even when a correct reply is also there. Talking to the customer passes, including empathy ("Oh no, I'm sorry your parcel arrived damaged") and what can or can't be done ("I need to verify your email first", "I'm not able to change the address once the order has shipped").
Octocom refines how universal checks are applied for every business without changing their wording. Report a missed issue or false positive instead of recreating a universal check.
Each check has independent settings:
| Setting | Options | What it controls |
| ------------ | ---------------------------------------------------------------- | ------------------------------------------------ |
| **Severity** | Critical or Improvement | How a finding is classified in results. |
| **Reaction** | Record and continue, or Hand off to a person | Whether a confirmed violation can stop delivery. |
| **Channels** | All channels, or any of email, Instagram, Messenger and web chat | Which bot messages the check applies to. |
Use channels for rules that only make sense somewhere, such as an email sign-off or short replies on web chat. Universal checks are reply checks and always run on every reply channel. Changing a check's channels does not change its wording or revision; it applies to new messages.
**Critical does not automatically mean blocked.** A critical check set to **Record and continue** records the finding and lets the message proceed. Universal checks default to **Record and continue**. If several checks fail, any confirmed violation on a check set to **Hand off to a person** is enough to cancel the reply.
Edit checks [#edit-checks]
You can edit the title, wording and severity of your own global and workflow checks at any time. The check keeps its key (for example G3), its settings and its history, so trend charts and alerts that filter on the key keep working. Each edit creates a new revision:
* New messages are checked against the latest wording.
* Past results keep the revision they were checked against and are not re-evaluated. Copilot can show the wording of any earlier revision.
A check's workflow scope is fixed. To check a different workflow, add a new check. Archive one of your checks only when the rule no longer applies; its past results remain available.
Universal checks are maintained by Octocom, which improves them for every business. They cannot be paused, edited or archived. If you do not want to act on one, set its reaction to **Record and continue** and leave it out of your alerts: it keeps running and nothing happens. If one flags valid replies or misses a problem, send us the cases and we will improve it. To check something different, add your own check, or duplicate a universal check as a starting point.
What cancellation does [#what-cancellation-does]
The proposed reply is not sent, and the conversation is handed off through your normal human-support routing. QA does not automatically rewrite the reply. On web chat the reply has already been sent, so only the handoff happens; the conversation's activity log notes which checks caused it.
**Actions that already ran are not undone.** For example, cancelling a reply does not reverse a refund that an action has already issued. QA evaluates the message and its claims; it is not an approval step before business actions run.
A successful handoff action supports saying that a request was passed to the team. It does not support saying that a person has reviewed it, or that a refund or cancellation has completed. Those claims need their own evidence.
An activity log event can provide that evidence. If an automation records that it completed a refund, QA accepts a message confirming that refund, even though the bot did not run the action itself. The event has to exist before the reply is checked; events written afterwards cannot support it.
Limits and incomplete checks [#limits-and-incomplete-checks]
QA uses bounded review time so it does not hold replies indefinitely. The initial check has a two-second budget. Suspected failures get a second, verifying review. On email it reasons more carefully and can take up to two minutes, which doesn't matter for an email reply. On other channels it takes at most seven more seconds.
If the initial check cannot complete, QA records a skipped attempt and delivery continues. A suspected failure that could not be verified can remain visible as an **unverified finding**, but it cannot cancel delivery. Other confirmed violations in the same review can still trigger their configured reaction.
Treat QA as an additional safeguard. Review real examples and tune your checks: it can miss problems or flag valid replies, and a technical failure does not automatically stop a message.
Whole-conversation checks [#whole-conversation-checks]
A whole-conversation check judges how the bot handled a conversation once it is over, rather than one reply at a time. Use it for phone calls, which can't be checked reply by reply, and for outcomes that only show across a whole conversation:
| Example check | Why it needs the whole conversation |
| -------------------------------------------------------------------------------- | ------------------------------------------------- |
| Was the caller's identity verified before any order details were shared? | The order of steps matters, not any single reply. |
| Was the customer's issue resolved, or transferred to the team when it should be? | The outcome is only known at the end. |
| Did the bot loop or repeat itself instead of moving forward? | Repetition spans several turns. |
| Did every action the bot said it took actually run? | Claims and actions can be several turns apart. |
How they run:
* **Once per conversation.** Phone calls are checked right after the call ends. Other conversations are checked two days after they close, so a quick reopen is part of what's judged. A conversation is never checked twice, even if it reopens later.
* **A separate switch.** Turn on **Conversation checks** in Bot QA settings. Only conversations that end after you turn it on are checked; older ones are not backfilled. Each checked conversation costs about as much as checking one more reply.
* **Findings are recorded, never acted on.** The conversation is already over, so there is nothing to cancel. Use alerts to bring findings to your team.
* **Same review as reply checks.** Suspected failures are verified by a second review, which has to quote the evidence. Confirmed findings include a summary, an explanation and quotes from the conversation, its instructions and action results.
* **Phone calls are judged from the transcript.** The review allows for speech-to-text errors and spoken replies, and uses the call's instructions and the actions the bot ran during the call.
Octocom doesn't supply universal whole-conversation checks: write the ones that matter to you. Severity, channels and workflow scope work the same way as for reply checks. **Runs on** can't change after a check is created; add a new check instead.
Test a whole-conversation check on a past conversation, such as a call your team already reviewed, before relying on it: in the dashboard, select **Test checks -> Whole conversation**, or ask Copilot. Tests store nothing and trigger no alerts.
Set up with Copilot [#set-up-with-copilot]
Tell Copilot which business to configure, what you want to catch, and what should happen. Copilot can inspect the existing checks, add or edit focused checks, change reactions, test messages and turn automatic checking on or off.
For example:
> Review our Bot QA checks for this business. Add a critical check for product claims that contradict our approved knowledge. Set confirmed violations to cancel the reply and hand off. Keep automatic checking off while we test.
> Check whether our existing action-confirmation rule covers refunds, cancellations and shipment changes. Use it if it already covers the requirement. Test it against conversation ABC123 without changing delivery or handing anything off.
> G4 flagged conversation XYZ789 although the refund was already processed by an agent. Update G4 so earlier refunds by our team count, then test it on that conversation again.
> Add a whole-conversation check for our phone calls: the bot must verify the caller before sharing any order details. Make it critical, test it on call ABC123, then turn on conversation checks.
After reviewing the tests:
> Turn on automatic Bot QA for this business. Keep language and presentation checks on record and continue, and hand off to a person for confirmed unsupported action confirmations.
Tests check **one bot reply in the selected conversation**: the latest by default, or any earlier reply you choose, such as a known bad answer from the middle of a conversation. Each is evaluated using only what came before it. They do not send messages, store QA results, trigger alerts or hand off the conversation. Tests can run while automatic checking is off.
Automate with the REST API [#automate-with-the-rest-api]
Everything above is also available in the [REST API](/docs/developers/rest-api) under **Bot QA**: settings, checks (including their `scope` and channels) and their revisions, dry-run tests for replies and whole conversations, per-conversation results and violation listings. List checks for one channel with the `channel` filter, or one kind with `scope`; list whole-conversation failures with `scope=conversation` on the violations listing. Use it to keep checks in version control or to feed violations into your own reporting. Updates accept `If-Match` with the check's `updatedAt`, so an automated push cannot overwrite a newer edit.
Reading settings and results needs the `bot:read` scope. A dry-run test is a paid model call that reads the conversation you name, so in the dashboard, REST and MCP alike it needs `bot:write` and `conversations:read`.
Manage in the dashboard [#manage-in-the-dashboard]
Open **Settings**, choose your business, then **Automation -> Bot QA**.
1. **Review Checks.** Universal checks are provided by Octocom. Select **Add check**, choose whether it runs on **Each reply** or the **Whole conversation**, and apply it to everything or to one workflow. Choose its channels in the same dialog. The **Runs on** column shows each check's kind. Select a universal check to read it.
2. **Choose the reaction for each reply check.** Start with **Record and continue** while assessing the results, or choose **Hand off to a person** for checks you want to block on. Whole-conversation checks show **Record only**.
3. **Test your checks.** Select **Test checks**. For a reply check, enter a conversation ID or public ID, select **Find messages**, choose the bot reply (the latest is preselected) and select **Run test**. For a whole-conversation check, switch to **Whole conversation**, enter the conversation and select **Run test**.
4. **Turn on the switches** when the checks and reactions are ready: **Reply checks** for each reply, **Conversation checks** for whole conversations.
You can turn automatic checking off again without losing your checks or historical results. To pause one of your own checks, use its individual switch. To change the wording or severity of one of your checks, select its edit button.
In **Metrics -> AI quality**, review message counts and breakdowns by check for your selected businesses and date range. If you have hidden this tab in your personal Metrics layout, show it again. Ask Copilot to list individual findings with conversation links, filter to confirmed violations, or summarize recurring issues.
Get alerted [#get-alerted]
Alerts are configured separately from checks. Ask Copilot to create an [event handler](/docs/developers/event-handlers#bot-message-qa) for **Bot Message QA Completed**, with your preferred destination and filters. You do not need to write the handler yourself.
For whole-conversation checks, use the **Bot Conversation QA Completed** event instead. It fires once per checked conversation, with the same check fields.
The event is available for completed and skipped QA attempts. For alerts about verified problems, ask for **confirmed violations only**. Filtering only on the overall Critical grade can also include unverified findings.
Slack alerts [#slack-alerts]
> Set up a Slack alert for confirmed critical Bot QA violations for this business. Include the check name, explanation, supporting evidence and a link to the conversation. Send one notification per checked message, even if several checks fail. Ask me for the Slack destination details you need.
This works well for a shared quality or support channel. Ask Copilot to use a dedicated channel and filter out routine improvements if you want a low-volume alert feed.
Email alerts [#email-alerts]
> Create an event handler that emails our support lead when Bot QA cancels a reply and hands off. Include the business, failed checks, explanations and a conversation link. Help me connect an email destination if needed.
Email alerts can use your business's configured email integration. This sends an outbound email and creates a separate handed-off conversation for it. Copilot can help configure the handler and check the required connection. Choose the recipients explicitly so QA alerts go to your team.
Other useful patterns [#other-useful-patterns]
* **Alert on one important rule:** notify your compliance team only when a particular product-claims check has a confirmed violation.
* **Separate urgent and routine findings:** alert immediately for cancelled replies, and ask Copilot to summarize improvement findings during your regular quality review.
* **Track review health:** notify an owner about repeated skipped or unverified checks, separately from confirmed quality problems.
* **Feed an existing process:** use event handlers or [webhooks](/docs/developers/webhooks) to send QA results to your reporting or incident system.
Notifications run after the QA result is stored. They do not block or cancel the current reply. Set the check's own reaction to **Hand off to a person** when you want to stop delivery; an alert handler is for telling your team what happened.
Write checks that are useful [#write-checks-that-are-useful]
Keep each check focused on one observable issue. Describe what counts as a violation and include the exceptions your business allows.
For example:
> Does the proposed reply claim that a refund or cancellation has completed without supporting execution evidence? Earlier successful actions count. Do not flag a conditional offer to help or a statement that a request has only been passed to the team. Flag an explicit failed action that the reply describes as successful.
Before enabling cancellation, test both replies that should fail and replies that should pass. Include valid exceptions, successful earlier actions, incomplete context and messages where the rule should not apply. Use findings to improve the underlying knowledge or workflow as well as the check. For how Bot QA fits with test conversations and other tests, see [Test your AI agent](/docs/ai-agent/testing).
# Bot rules
A bot rule is a short instruction the AI agent keeps in mind in every conversation, such as "never promise a specific delivery date" or "never give legal advice about a claim". Rules sit in the system prompt on every turn, so they hold whatever the conversation is about. That makes them the right place for a handful of guardrails, and the wrong place for almost everything else.
What you can do [#what-you-can-do]
* **Set hard limits that apply everywhere.** Never confirm that a claim will be paid, never share details of another customer's account, never quote a price the catalog doesn't show.
* **Protect your brand** with a few always-on principles, such as never commenting on competitors.
* **Scope a rule to channels**, such as a "keep replies short" rule for web chat only.
* **Restore an earlier version** of any rule from its version history.
Set it up [#set-it-up]
Add a bot rule for every channel: never confirm that a claim will be paid or
say how much it will pay. Only our claims team decides that.
The most useful request is often a review rather than a new rule:
Review our bot rules. Move facts into knowledge articles and scenario-specific
steps into workflows, and keep only the guardrails that must hold in every
conversation.
In the dashboard, go to **Settings -> Automation -> Knowledge -> Bot Rules**.
How it works [#how-it-works]
A rule is part of the AI agent's instructions on every turn. That always-on quality is what makes a rule effective, and also what makes it costly. A bot rule should be the *last* tool you reach for, not the first. [How the AI agent works](/docs/ai-agent/how-it-works) explains why the system prompt is the AI agent's always-present memory.
Behavior and knowledge can live in three places, and they differ in *when* the AI agent sees them:
* **[Knowledge base](/docs/ai-agent/knowledge-base)** entries are looked up on demand: the AI agent searches for them only when they're relevant.
* **[Workflows](/docs/ai-agent/workflows)** are loaded when a matching situation arises: their instructions appear only when needed.
* **Bot rules** are never loaded on demand. They sit in the system prompt for **every single message**, relevant or not.
Every rule you add is rent the AI agent pays on every turn. Think of bot rules as the few things you'd pin to a new agent's monitor on their first day, not their entire training manual.
The core question: does the AI agent need to always know this? [#the-core-question-does-the-ai-agent-need-to-always-know-this]
Before adding a rule, ask that one question. It's the whole discipline in a sentence:
> **If the AI agent doesn't need it in mind all the time, don't put it in a rule.** Context is valuable, finite space.
Most things you're tempted to add belong somewhere else:
| If what you're adding is... | Put it in... | Because... |
| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| A **fact** the AI agent only needs sometimes (a policy detail, a product or plan nuance, an edge-case answer) | The **[knowledge base](/docs/ai-agent/knowledge-base)**: add or update an article | The AI agent searches for it exactly when it's relevant, and not before |
| **Behavior tied to a specific scenario** ("when a customer wants a refund, do X") | A **[workflow](/docs/ai-agent/workflows)** | The AI agent loads those instructions only when that situation comes up |
| A **genuinely global behavior** the AI agent must follow everywhere (safety, hard prohibitions, brand-critical tone) | A **bot rule** | This really does need to be always on |
A few examples to make the boundary concrete:
* *"Our return window is 30 days."* or *"Roaming is included in the Plus plan."* -> **Knowledge base.** It's a fact, looked up when a customer asks.
* *"When a customer reports a damaged item, collect photos before offering a refund."* -> **Workflow.** It's a procedure for one scenario.
* *"Never promise specific delivery dates."*, *"Never confirm that a claim will be paid."* -> **Bot rule.** These are always-on guardrails that apply whatever the conversation is about.
The best test for a candidate rule: *would I want the AI agent thinking about this during a conversation that has nothing to do with it?* If not, it's not a rule.
Why rules are limited [#why-rules-are-limited]
Bot rules have hard limits:
| Limit | Value |
| ---------------------- | -------------------- |
| Bot rules per channel | **30** |
| Length of a rule | **1,200 characters** |
| Length of a rule title | **200 characters** |
The 30-rule cap counts every rule that applies on a channel: rules for all channels plus the rules scoped to that channel. A rule for all channels therefore counts toward every channel.
The limits exist because of how the AI agent works:
* **LLMs follow fewer instructions better.** Overload the AI agent with always-on rules and it follows *all* of them less precisely. This is a well-understood property of large language models. When every rule is declared important, the AI agent can't tell which one matters most.
* **Rules compete with the real work.** They share the context the AI agent uses to reason, read retrieved knowledge and run workflows. A wall of rules crowds out the actual job.
There is **no priority or ordering** among rules. The AI agent treats them as one flat set, all equally and always in force. That is also why contradictions between rules do so much damage: there's no tie-breaker to fall back on.
The anti-pattern: turning every idea into a rule [#the-anti-pattern-turning-every-idea-into-a-rule]
The most common mistake is turning every new idea, complaint or piece of feedback into another bot rule. It feels productive, and it quietly degrades the AI agent.
As rules pile up, they start to **contradict each other**, and the sheer volume makes the AI agent follow each one less faithfully. You end up with *more* rules and *worse* adherence, the opposite of what you wanted.
Strong setups typically run on about **15 to 20 sharp rules**, each clearly earning its always-on slot. The cap of 30 is a ceiling, not a goal: racing toward it is a warning sign.
This doesn't limit you to simple setups. Octocom runs complex AI agents for large retailers, insurers and telecoms, and they work within about 20 rules. The complexity doesn't disappear. It moves to where it belongs. Scenario-specific behavior goes into [workflows](/docs/ai-agent/workflows), which can do far more and load on demand, and factual depth goes into the knowledge base. Rules stay reserved for the handful of things that must always hold.
It's the same with people. Hand someone a hundred-page rulebook and they'll follow it poorly; give them a handful of clear principles and they'll live by them. A small, sharp set of rules is *easier to follow*, for an LLM exactly as for a person.
> **A bot rule should be your last resort.** Before adding one, ask whether a workflow or a knowledge base article does the job better. If it can, use that. Reach for a rule only when the behavior is genuinely global and must always hold.
Common gotchas [#common-gotchas]
Most failed bot rules aren't badly written. They ask for something a rule can't deliver. These are the five we see most often. The first three come straight from how the [core loop](/docs/ai-agent/how-it-works) works.
1. A rule can't give the AI agent a new capability [#1-a-rule-cant-give-the-ai-agent-a-new-capability]
People write rules like *"call the order lookup tool when a customer asks about an order"*, expecting the rule to *enable* that tool. It won't.
**Actions are switched on only by workflows.** See [where tools come from](/docs/ai-agent/how-it-works#workflows-and-where-tools-come-from). If the workflow that includes an action isn't in play, no rule can summon it. A rule can shape *how* the AI agent uses a capability it already has, never *whether* it has one.
2. A rule can't make the AI agent act outside the core loop [#2-a-rule-cant-make-the-ai-agent-act-outside-the-core-loop]
A classic: *"if you don't have the answer now, follow up in a few hours."* Scheduling, waiting and acting between messages can't be governed by a bot rule, because they happen *outside* the per-message loop.
Octocom does these things through dedicated features instead: [follow-ups](/docs/ai-agent/follow-ups-and-auto-resolve), [event handlers](/docs/developers/event-handlers) and [recurring jobs](/docs/developers/recurring-jobs).
3. A rule can't forbid intrinsic LLM behavior [#3-a-rule-cant-forbid-intrinsic-llm-behavior]
*"Never make mistakes"*, *"never hallucinate"*, *"always be 100% accurate"*: these don't work. They aren't behaviors the model can switch off. They're properties of how language models work.
A rule like this mostly burns a slot. Accuracy comes from better knowledge and workflows, from putting must-hold logic in code, and from checks such as [Bot QA](/docs/ai-agent/bot-qa), not from forbidding errors in prose.
4. Vague rules get vaguely followed [#4-vague-rules-get-vaguely-followed]
The AI agent fills any gap with its own judgment. *"If the customer is aggressive, do X"* works, but "aggressive" is left for the AI agent to define, and that is often culturally loaded.
If precision matters, **define your terms.** Is all-caps aggressive? Are explicit threats? Spell it out. The same goes for fuzzy style instructions: *"write shorter"* is much weaker than *"keep paragraphs under about three sentences."* The more measurable the instruction, the more reliably it's followed.
5. You can't micro-control phrasing [#5-you-cant-micro-control-phrasing]
You *can* steer the AI agent away from specific words, and you *can* set a general tone in the [writing style](/docs/ai-agent/writing-style). You *can't* dictate the exact structure of every sentence.
A rule written to fix one sentence you didn't like, such as *"don't phrase it like this, phrase it like that"*, spends a slot on a single example and usually won't generalize. **Give abstract principles** about how you want the AI agent to write, not one-off corrections.
> A useful filter: if a rule tries to grant a capability, cancel an LLM trait or pin down something you haven't defined, it probably won't do what you hope.
Writing good bot rules [#writing-good-bot-rules]
Once you're sure something belongs in a rule, keep it sharp:
* **One rule, one purpose.** If a rule needs an "and" to do two jobs, it's probably two rules, or it belongs in a workflow.
* **Give it a clear, specific title.** It's how both you and the AI agent tell rules apart.
* **Avoid overlap and contradiction** with other rules and with your workflows.
* **Scope by channel instead of writing per-channel prose.** A rule with no channels set applies everywhere; otherwise it applies only on the channels you choose, for example a "keep replies short" rule for web chat. Don't cram "on email do X, on chat do Y" into one rule.
* **Stay well inside the length limit.** A rule close to 1,200 characters is likely knowledge base material in disguise.
* **Be explicit, not impressionistic.** See gotchas 4 and 5.
* **Put voice in the writing style.** Tone and formatting preferences belong in the [writing style](/docs/ai-agent/writing-style), not in rules.
Managing bot rules [#managing-bot-rules]
* **In the dashboard:** **Settings -> Automation -> Knowledge -> Bot Rules**. Create, edit, scope to channels and archive rules there.
* **With Copilot or MCP:** `list_bot_rules`, `create_bot_rule`, `update_bot_rule` and `archive_bot_rule` through [Octocom MCP](/docs/developers/mcp).
* **With the REST API:** `GET`, `POST`, `PATCH` and `DELETE /rest/v1/bot-rules`. See the [REST API](/docs/developers/rest-api).
* **Version history:** rules keep their versions. Use `list_bot_rule_versions` and `restore_bot_rule_version` to recover an earlier version or undo an archive. Review the current rule before restoring a version that replaces later edits.
# Knowledge documents
Knowledge documents are files the AI agent searches for answers: policy terms, product or service manuals, price lists, coverage tables, spreadsheets of reference data. Upload a file once and the AI agent finds the relevant passage when a customer asks, with no need to rewrite it as articles. Documents are one of the three sources of the [knowledge base](/docs/ai-agent/knowledge-base), next to articles and website pages.
Upload a document [#upload-a-document]
In the dashboard, open **Settings -> Automation -> Knowledge -> Documents** and choose **Upload a new document**. You can also ask [Copilot](/docs/developers/copilot) or your MCP agent to upload or replace a document for you.
Supported formats are TXT, CSV, Markdown, PDF, DOCX, XLSX and XLS. Files must be non-empty and at most 25 MiB. CSV imports support up to 1,000 rows and spreadsheet imports up to 10,000 rows. A text document becomes one searchable entry, while each spreadsheet or CSV row becomes its own entry.
A new document is searchable once it is indexed. The **Learned** column shows the progress. It usually takes seconds, longer for large PDFs. Uploads from the dashboard, MCP and REST are all processed the same way.
Documents are always active on every channel. When a fact needs a date window or should apply to one channel only, put it in an [article](/docs/ai-agent/knowledge-base#controlling-what-the-ai-agent-can-see) instead.
The rest of this page is a reference for developers and AI agents that manage documents through MCP or the REST API, for example to keep a price list in step with a source system.
MCP tools [#mcp-tools]
Use `list_documents` to find current documents with file IDs and indexing status;
pass `includeArchived: true` to include retained archives. `upload_document` accepts inline
text for TXT, CSV and Markdown. For a real file, call
`create_document_upload_url`, PUT the original bytes to its temporary URL,
then call `finalize_document_upload` with the returned `fileId`.
`archive_document` removes the document from search while keeping its file and
index, so it can be restored. Find archived documents with
`list_archived_configuration_resources` using `resourceType: "document"`, and
recover them with `restore_document`.
REST operations [#rest-operations]
All paths below start with `/rest/v1` and require `X-API-Key`. Use the
[REST reference](https://api-docs.octocom.ai/) for complete request and response
schemas. Copilot and MCP can discover these endpoints in the **Documents**
group with `list_rest_api_operations`.
| Method | Path | Purpose |
| ------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| GET | `/documents?businessSlug=shop` | List active documents; add `includeArchived=true` to include retained archives |
| GET | `/documents/{id}?businessSlug=shop` | Read one document, its download URL and indexing status, including archives |
| POST | `/documents` | Upload inline `{businessSlug, filename, content}` for TXT, CSV or Markdown, up to 500,000 characters |
| POST | `/documents/uploads` | Reserve a direct upload with `{businessSlug, filename}` |
| POST | `/documents/uploads/{fileId}/finalize` | Validate and ingest uploaded bytes; body is `{businessSlug}` |
| DELETE | `/documents/{id}?businessSlug=shop` | Recoverably archive the exact document |
| POST | `/documents/{id}/restore` | Restore the retained document and its previous context enablement; body is `{businessSlug}` |
Documents are scoped to the API key's organization and requested business.
Cross-business files cannot be finalized or used to archive another business's
knowledge. Archived businesses remain readable but reject mutations. Python
recurring jobs can use their injected `OCTOCOM_ORG_API_KEY` and
`OCTOCOM_API_BASE_URL` with the same endpoints.
Upload reservations return `{data: {fileId, presignedUrl, uploadHeaders}}`.
PUT the **original bytes**, without an Octocom API key, to `presignedUrl` using
exactly the returned `uploadHeaders`. Do not encode
a PDF, Word document or spreadsheet as inline text. Finalization checks size,
format and file safety before ingestion. Repeated finalization of the same
`fileId` returns its existing document, even if it was archived; it does not
create a second document or restore it.
Upload and download URLs are credentials. Keep them out of logs and version
control. Private download links expire at `urlExpiresAt`; request document
details again when you need a fresh one. Responses containing these links use
`Cache-Control: no-store`.
Safely refresh a document [#safely-refresh-a-document]
Uploading the same filename creates a **new document**. There is no implicit
overwrite or deletion. Keep the old document active until the new one is ready:
1. Fetch and validate the complete new source content. Save the old document ID.
2. Upload the replacement and save its returned document ID. Binary uploads
require the direct-byte upload and finalization steps above.
3. Poll the replacement with GET until `data.status` is `ready`.
4. Archive the saved old document ID. Do not select it by filename alone.
Ingestion parses the file before returning, but indexing continues
asynchronously. Document status has four possible values:
| Status | Meaning |
| ---------- | -------------------------------------------------------------- |
| `indexing` | Extracted content is not fully indexed yet |
| `ready` | All extracted content is indexed and searchable |
| `empty` | The file produced no searchable content; keep the old document |
| `archived` | The document is kept but excluded from search |
`indexing` includes work that has not completed, including failed background
indexing. Use a bounded polling deadline and inspect failures if it does not
become ready. A timeout or ingestion error is not a reason to archive the old
snapshot. Record IDs in durable organization storage so a later run can resume
or inspect an uncertain upload, rather than creating another replacement.
For example, after uploading a replacement through REST:
```python
import requests
import time
def wait_for_document(business_slug, document_id, timeout=40):
url = f"{OCTOCOM_API_BASE_URL}/rest/v1/documents/{document_id}"
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
response = requests.get(
url,
params={"businessSlug": business_slug},
headers={"X-API-Key": OCTOCOM_ORG_API_KEY},
timeout=10,
)
response.raise_for_status()
document = response.json()["data"]
if document["status"] == "ready":
return document
if document["status"] in {"empty", "archived"}:
raise RuntimeError("Replacement is not searchable; keep the old document")
time.sleep(1)
raise TimeoutError("Replacement is not ready; keep the old document")
```
Archiving and restoring are idempotent. Restoring brings back each entry of
the document exactly as it was before archiving, including entries that were
switched off, and reuses the existing index, so nothing is downloaded or
indexed again. Document changes are recorded in
[change history](/docs/developers/change-history), without file contents or signed
URLs.
# Follow-ups and auto-resolve
import { Accordions, Accordion } from "fumadocs-ui/components/accordion";
Follow-ups and auto-resolve decide what happens when an email conversation goes quiet. Usually either the customer's issue is done, or they still owe you something, such as a confirmation, an order number or a photo. Instead of closing every idle conversation on a timer, the AI agent reviews it first:
* **Resolved?** It closes the conversation. This is the *auto-resolve* part: your inbox stays clean without closing conversations that still need attention.
* **Not resolved?** It follows up with the customer. By default that's a short, friendly nudge, but through your bot rules and workflows a follow-up can do real work: ask again for a missing detail, go ahead with a request the customer never confirmed, or hand off to your team.
Follow-ups and auto-resolve apply to **email** conversations. Turn them on per business in **Settings -> Automation -> Follow-Ups**. On other channels, idle conversations close on the normal [auto-close timer](/docs/help-desk/ticket-states).
How it works [#how-it-works]
When an email conversation has been idle long enough to auto-close, and the AI agent sent the last message, the AI agent runs a short review:
1. **Is it resolved?** The AI agent judges the conversation against your **Resolution criteria**.
* **Resolved:** the conversation is closed.
* **Not resolved:** it moves on to a follow-up.
2. **Follow up.** If follow-ups remain, the AI agent receives an internal **follow-up event**. It says the customer has gone quiet, *why* the conversation counts as unresolved, and which follow-up this is (for example "follow-up 1 of 2", with the last one marked as final). The customer never sees this event; it starts a normal AI agent turn. On that turn the AI agent first checks **your bot rules and workflows**: if any describe what to do when following up on a quiet customer, it follows them. Otherwise it sends one brief, friendly nudge. See [The follow-up playbook](#the-follow-up-playbook).
3. **When the follow-ups run out.** Once the maximum number of follow-ups has been sent and the conversation is still unresolved, the **final action** you chose runs automatically: close the conversation, or hand it off to your team.
The follow-up count **starts over whenever the customer replies**, so a customer who replies and then goes quiet again gets the full number of follow-ups again.
Each follow-up also adds an event to the conversation timeline, saying which follow-up was sent and why the conversation counts as unresolved, so your team can see what happened.
Settings [#settings]
Configure these per business in **Settings -> Automation -> Follow-Ups**.
| Setting | What it does |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Enable auto-resolve** | The main switch. Off (the default): idle conversations are closed. On: idle email conversations are reviewed and followed up as described here. |
| **Resolution criteria** | What counts as resolved. Conversations that match are closed; the rest get a follow-up. **Reset** restores the default criteria. |
| **Maximum follow-ups** | How many follow-ups the AI agent may send before the final action, from 0 to 10 (default 1). `0` skips follow-ups entirely. The count starts over when the customer replies. |
| **Hand off when follow-ups are exhausted** | The final action once follow-ups run out and the conversation is still unresolved: **on** hands off to your team, **off** (the default) closes the conversation. |
There is deliberately no "follow-up message" setting. The default follow-up is built in, and anything beyond it lives where the rest of the AI agent's behavior lives: in bot rules and workflows. That's the [playbook](#the-follow-up-playbook).
Copilot and other AI agents can change the same settings. See [Configure with Copilot, MCP or the API](#configure-with-copilot-mcp-or-the-api).
Resolution criteria [#resolution-criteria]
**Resolution criteria** answer one question: *is this conversation done?* Keep them focused on that. For example:
> A conversation is resolved if the customer's question has been fully answered and nothing further is needed from us. It is not resolved if the customer still needs to confirm or provide something before their issue can be completed.
Keep the default unless your business has its own definition of "done", for example treating "awaiting a refund confirmation" as unresolved.
The follow-up playbook [#the-follow-up-playbook]
A follow-up is a normal AI agent turn, started by an internal event instead of a customer message. That's the key design decision: everything you already use to shape the AI agent's behavior (bot rules, workflows, actions) works on follow-ups too.
What the AI agent is told [#what-the-ai-agent-is-told]
On each follow-up turn, the AI agent receives an event like this. It is internal; the customer never sees it.
> The customer has gone quiet and the conversation looks unresolved, so an automated follow-up was triggered.
>
> Why it's considered unresolved: *The customer was asked to confirm the cancellation but has not responded.*
>
> This is automated follow-up 1 of 2 (1 more allowed after this one).
>
> How to handle this: if your workflows or additional rules describe what to do when following up on a quiet customer, follow them. Otherwise, send one brief, friendly nudge that references the last topic discussed and asks the customer for whatever is still needed to move their request forward. Never claim an action has been taken, and do not treat the conversation as resolved.
On the last follow-up, the event says so explicitly: *"the FINAL allowed follow-up. After this, no more follow-ups will be sent."*
So your playbook can rely on three things: **that** this is a follow-up, **why** the conversation is unresolved, and **which** follow-up it is, including whether it's the last one.
The default behavior [#the-default-behavior]
With no rules or workflows for follow-ups, the AI agent sends one brief, friendly nudge: it refers to the last topic, asks the customer for whatever is still needed, and never claims an action has been taken. It does **not** hand the conversation off. A guaranteed handoff is what **Hand off when follow-ups are exhausted** is for.
Customize with bot rules [#customize-with-bot-rules]
[Bot rules](/docs/ai-agent/bot-rules) apply to every turn, follow-ups included, so they're the lightest way to steer follow-ups. For example:
> When following up on a quiet customer, always write in the same language the customer used, and offer a direct link to our returns portal if the conversation was about a return.
> If you are following up and the customer never confirmed a subscription cancellation they asked for: on the second follow-up, proceed with the cancellation, tell them it's done, and let them know they can reach out to undo it.
The second example shows the pattern: the customer asked for something, went quiet before confirming, and your playbook decides that silence after two nudges means *go ahead*. The AI agent can do it because a follow-up turn can use any action the AI agent normally has.
When resolution depends on another system [#when-resolution-depends-on-another-system]
The resolution check judges the conversation from its messages. It can't see the state of another system, for example whether a subscription was cancelled after the AI agent sent a self-service link.
If a workflow can leave the conversation waiting on a change in another system, put the follow-up instructions in the **same workflow variant** that created that situation. You don't need a separate follow-up workflow: when the follow-up arrives, the AI agent still has the instructions it loaded earlier. Tell it to check the state again, and define a reply for every possible result.
For example, after sending a subscription cancellation link, the variant could say:
> If you receive an automated follow-up event after sending the cancellation link, check the subscription status again. If it is cancelled, politely confirm that we can see the cancellation, explain that access continues until the end of the current subscription period, and ask whether the customer needs anything else. If it is still active, cancel it using the available action, confirm the cancellation only after the action succeeds, and offer further help. If the check or cancellation fails, do not claim it succeeded; follow the workflow's escalation instructions instead.
Never instruct the AI agent to "not respond", "do nothing" or only "consider
the ticket resolved" during a follow-up. A follow-up is a reply turn. Even
when the other system shows the request is already complete, the AI agent must
write a suitable reply, such as politely confirming the completed cancellation
and offering further help.
Customize with workflows [#customize-with-workflows]
For a fuller playbook that applies across situations, write a dedicated [workflow](/docs/ai-agent/workflows) that matches the follow-up event. In **When to follow**, describe the event:
> Follow this when you receive an automated conversation event saying the customer has gone quiet and the conversation is unresolved (an automated follow-up).
Then write your playbook in the instructions, for example a two-step ladder:
> On the first follow-up, send a short friendly reminder referencing the last topic. On the final follow-up, summarize what we're still waiting for, set the expectation that we'll close the conversation if we don't hear back, and if the request can be completed without the customer's input, complete it and say so.
Because it's a regular workflow, it can do anything a workflow can: call actions, look up an order, collect data or hand off to your team.
Playbook handoff or guaranteed handoff [#playbook-handoff-or-guaranteed-handoff]
A follow-up can end with a person in two ways, and they behave differently:
* **From your playbook** (for example *"on the final follow-up, hand off"* in a bot rule or workflow): the AI agent decides in the moment. This is flexible and conditional, but like any AI instruction it is followed *most* of the time, not *every* time.
* **With Hand off when follow-ups are exhausted:** guaranteed. Once the follow-ups are used up and the conversation is still unresolved, it is handed off (or closed) automatically, without the AI agent.
Follow-ups never hand off on their own: the AI agent is told not to unless your rules or workflows say so. Use the **setting** when you need a guarantee ("these must always reach a person"). Use the **playbook** for nuanced, conditional behavior. They work together: the playbook handles each follow-up, and the setting is the backstop once the follow-ups run out.
Example setups [#example-setups]
**Close quietly, no follow-ups.** **Enable auto-resolve** on, **Maximum follow-ups** `0`, handoff off. Resolved and unresolved idle conversations are both closed. The simplest setup.
**One nudge, then close.** **Maximum follow-ups** `1`, handoff off. The AI agent sends one follow-up. If the customer still doesn't reply, the conversation is closed.
**One nudge, then hand off.** **Maximum follow-ups** `1`, handoff **on**. The AI agent sends one follow-up. If the customer still doesn't reply, the conversation goes to your team instead of closing. Good for high-touch queues.
**Hand off instead of nudging.** **Maximum follow-ups** `0`, handoff **on**. Unresolved conversations go straight to your team, with no follow-up message.
**Two nudges with a playbook.** **Maximum follow-ups** `2`, plus a bot rule or workflow such as *"On the final follow-up, if this looks like a billing dispute, hand off to a human; otherwise send a final reminder."* Turn handoff **on** as well if anything still unresolved after two nudges must reach a person.
**Silence means yes.** **Maximum follow-ups** `2`, plus a rule such as *"If the customer requested a cancellation but never confirmed it, proceed with the cancellation on the second follow-up and tell them it's done."* The AI agent nudges once, then completes the request instead of letting it stall.
FAQ [#faq]
**Does the customer see the follow-up event?** No. Only the follow-up message the AI agent writes is sent to the customer.
**Do I need a workflow for follow-ups to work?** No. The default nudge is built in. Bot rules and workflows are only for changing what a follow-up does.
**Do I need a separate follow-up workflow?** No. If a workflow created the unresolved situation, for example by sending the customer a link and waiting for them to use it, that workflow's variant can include the follow-up instructions. A separate workflow is useful for behavior shared across many situations.
**What if I turn auto-resolve off later?** Idle conversations are closed again, without a review. Follow-up rules and workflows stay in place but aren't used; delete them if you won't need them again.
**Why isn't the AI agent following up?** Check that (1) **Enable auto-resolve** is on for the business, (2) the conversation is on email, and (3) the AI agent sent the last message. If the customer spoke last, there's nothing to nudge and the conversation is closed. With Zendesk, a conversation an agent already answered in Zendesk is closed without a follow-up. If all of that holds and follow-ups still don't arrive, contact Octocom support.
Configure with Copilot, MCP or the API [#configure-with-copilot-mcp-or-the-api]
Read the settings with the MCP tool `get_follow_up_settings` or `GET /rest/v1/follow-up-settings`, and change them with `update_follow_up_settings` or `PATCH /rest/v1/follow-up-settings`. Only the fields you send change:
| Field | What it sets |
| ----------------------- | ------------------------------------------------------------------------------------- |
| `autoResolveEnabled` | Whether idle email conversations are checked and followed up |
| `resolutionPrompt` | When a conversation counts as resolved; `null` restores the default criteria |
| `maxFollowups` | How many follow-ups to send, 0 to 10; the count starts over when the customer replies |
| `handoffOnMaxFollowups` | Hand off (`true`) or close (`false`) once the follow-ups are used up |
Reads return the resolution criteria in use, and `customizedFields` says whether they are your own. Every change is recorded in the configuration history.
To write a follow-up playbook programmatically, use `create_bot_rule` for always-on guidance or `create_workflow` for a fuller playbook. For a workflow, make sure its **When to follow** describes the follow-up event so the AI agent picks it, for example:
> Follow this when you receive an automated conversation event saying the customer has gone quiet and the conversation is unresolved (an automated follow-up).
When no bot rule or workflow covers follow-ups, the follow-up event itself instructs the AI agent:
> Send one brief, friendly nudge that references the last topic discussed and asks the customer for whatever is still needed to move their request forward. Never claim an action has been taken, and do not treat the conversation as resolved. Do NOT hand the conversation off. A handoff is not needed for a follow-up unless your workflows or rules explicitly instruct it.
Handing off when the follow-ups are used up belongs to the **Hand off when follow-ups are exhausted** setting, never to the follow-up turn itself.
# How the AI agent works
Every reply from the AI agent comes from one loop. A language model reads its instructions, the conversation and the tools it may use, looks things up when it needs to, then replies. Knowing this loop explains almost everything the AI agent does, and tells you which setting to change when a reply surprises you.
What this page answers [#what-this-page-answers]
Read this page before you configure anything complex. It is written for the people who set up the AI agent, and for the AI agents that do it for them, such as Copilot or an [MCP](/docs/developers/mcp) client. It answers questions like these:
* **Does the AI agent know my whole catalog?** No. It searches for products and knowledge when it needs them. See [Products](#products).
* **Can a rule tell it to follow up in two hours?** No. The loop only runs when a message arrives, so follow-ups are a separate feature. See [What the AI agent can't do on its own](#what-the-ai-agent-cant-do-on-its-own).
* **Why didn't it use my refund action?** An action is only available once a workflow that includes it is in play. See [Workflows and where tools come from](#workflows-and-where-tools-come-from).
* **Why did it reply this way?** Every reply is fully traceable. See [Debugging](#debugging-the-loop-is-fully-observable).
Trace any reply [#trace-any-reply]
When a reply surprises you, ask Copilot or your own AI agent to explain it:
A customer chatted with us yesterday from [anna@example.com](mailto:anna@example.com) and got the wrong
return window. Find that conversation, explain why the AI agent answered that
way, and fix the cause.
The agent reads the exact instructions behind the reply, the searches it ran and the actions it called, then changes the setting that caused the problem. In the dashboard, open the conversation, hover over an AI reply and click the bug icon to see the same details.
The core loop [#the-core-loop]
1. A customer sends a message.
2. Octocom calls a large language model (LLM) with three things: the **system prompt** (its instructions), the **conversation so far** and the **tools** it may use.
3. The model may **call one or more tools**, for example to look up an order, search products or search the knowledge base. Each tool's result is fed back to the model.
4. It can call more tools based on what it learned, looping until it has what it needs.
5. It writes a **text reply** to the customer. That ends the turn.
There is no hidden machinery beyond this loop. The model reasons over its instructions and the conversation, gathers information through tools when needed, and replies.
```
customer message
│
▼
┌─────────────────────────────────────────┐
│ LLM call │
│ • system prompt (instructions) │
│ • conversation history │
│ • available tools │ ◄────┐
└─────────────────────────────────────────┘ │
│ │
├── wants to call tool(s)? ── run them ─────┘
│ (loops, up to a limit)
│
└── writes text reply ──► sent to customer (turn ends)
```
Three consequences follow from this shape:
* **The AI agent only runs when a message arrives.** Between messages, nothing happens inside it. There is no background process watching the clock or waiting for events.
* **The loop is bounded.** The AI agent can chain several tool calls in one reply, up to about ten rounds. It cannot loop forever.
* **The model decides what to do.** Within your instructions, it chooses which tools to call and what to say. You shape that behavior through the system prompt. You don't script it line by line.
What's in the system prompt [#whats-in-the-system-prompt]
The system prompt is where you control the AI agent. Octocom builds it fresh for every reply from a fixed sequence of sections. Some come from your settings, and others are filled in from the conversation. [System prompt](/docs/ai-agent/system-prompt) lists every section in order. These are the ones that matter most when you configure the AI agent.
Instructions and writing style [#instructions-and-writing-style]
The first sections say who the AI agent is and how it writes. Each starts from a tuned Octocom default that you can override:
* **Task:** who the AI agent is and its core job, for example "You are a support agent for *Acme*".
* **Safety:** high-level guardrails, such as staying on topic and not making unauthorized commitments.
* **Instruction following:** which source of truth wins, for example workflow instructions over articles.
* **Tool calling:** how and when to use tools.
* **Tone, writing style and language:** the voice, separate styles for chat and email, and which language to reply in.
* **Output syntax:** formatting rules, such as Markdown and no raw HTML.
* **Business description:** a short overview of your company. It is empty until you write one.
Tone, writing style and language are on **Settings -> Automation -> Writing Style**. See [Writing style](/docs/ai-agent/writing-style). The other sections are expert settings on **Settings -> Automation -> System Prompt**. See [System prompt](/docs/ai-agent/system-prompt). **Reset to default** brings back Octocom's default for any section.
Bot rules [#bot-rules]
Bot rules are short, always-on guidelines written into the system prompt on every turn, such as "always mention the newsletter discount to first-time buyers" or "never promise next-day delivery". Each rule is a title plus a block of instructions, and rules can be scoped to specific channels.
Rules are pure instructions. They guide the model, but they don't run code and they don't give the AI agent new capabilities. See [Bot rules](/docs/ai-agent/bot-rules) for when a rule is the right tool and when a workflow is.
Workflows and where tools come from [#workflows-and-where-tools-come-from]
Workflows are playbooks for specific situations, such as "customer wants to cancel an order". [Workflows](/docs/ai-agent/workflows) covers them in depth, but one point is essential to the operating model and easy to miss:
> **Workflow actions come from workflows.** A workflow declares which actions it makes available. Built-in capabilities, such as searching the knowledge base, reading customer attachments and loading workflows, are available independently.
A workflow reaches the AI agent in one of two ways:
* **Embedded workflows** are written into the system prompt in full on every turn. Their instructions are always visible and their actions are always available. They must have exactly one variant, no condition provider and no required conditions.
* **Non-embedded workflows** are listed in the system prompt by name, with a one-line "when to follow this". When the model decides one applies, it calls the built-in `getWorkflowInstructions` tool to **load** it. Only then are that workflow's instructions, and its actions, added to what the AI agent can use.
A non-embedded workflow can have one variant or several. The variant is chosen by conditions evaluated at load time. When the workflow loads, **the AI agent gains the actions of the selected variant**.
Loading happens **once per conversation, not once per turn.** A loaded workflow's instructions and actions stay available for the rest of the conversation, so the AI agent doesn't reload it on later messages. The set of available tools tends to grow over a conversation as more workflows are loaded.
In practice: at the start of a conversation, the AI agent can use its built-in tools and the actions of embedded workflows. Actions from other workflows become available when those workflows load. This keeps the prompt small and focused, and it is why a new conversation doesn't have every action in front of the model. Deciding what to load is part of what makes the AI agent **agentic**: it pulls in what it needs instead of being handed everything up front.
Knowledge base [#knowledge-base]
The knowledge base is the AI agent's reference material: **articles** you write, **website pages** Octocom scrapes and **documents** you upload, all in one searchable pool.
None of it is memorized or written into the prompt. The AI agent gets one tool, `searchKnowledgeBase`, and a note about how much content exists. When it needs a fact, it searches, reads the returned passages and answers from them, the same way a person searches a help center. The AI agent is only as good as what it can find: if the answer isn't in the knowledge base, searching won't invent it.
> **This section is automatic.** As soon as there is at least one active knowledge base entry, the AI agent gets this section and the `searchKnowledgeBase` tool. There is nothing to switch on and no workflow is needed. With an empty knowledge base, neither the section nor the tool exists.
See [Knowledge base](/docs/ai-agent/knowledge-base) for its sources, how search selects passages and how to write content that gets found.
Products [#products]
When you sync a product catalog, product handling follows one of two styles, depending on its size:
* **Small catalog, roughly a hundred in-stock products or fewer:** a compact index of every product is written into the system prompt, with its id, name, price, a few flags and a short summary. The AI agent still calls `getProductsByIds` to get full details before it talks about a specific product.
* **Larger catalog:** nothing is listed in the prompt. The AI agent gets `searchProducts`, which searches by meaning, by keyword or SKU, or by URL, plus `getProductsByIds` for full details. It searches, then fetches the details.
> **The AI agent does not "know" your products.** This is one of the most common misconceptions. Beyond a small catalog, it has no memorized product list. It only knows the products it has found through a search in the current conversation. If a search doesn't return a product, the AI agent effectively doesn't know it exists.
Like the knowledge base, the product section and the product tools appear automatically once at least one product has synced through [product sync](/docs/commerce/product-catalog). If no products have synced, they don't exist for the AI agent.
Conversation context [#conversation-context]
The rest of the prompt is filled in automatically for the current conversation, when the information exists: the current date and time in your business time zone, the channel, the customer's email address and phone number, the page they wrote to on Messenger or Instagram, and their browsing history and recently viewed products in Octocom web chat. In email conversations it also lists the customer's recent previous email conversations, which the AI agent can open with a built-in tool when they help. You don't configure these.
To add your own context, such as the customer's latest orders or account status from your systems, use a [custom Python prompt section](/docs/developers/prompt-sections).
Customer attachments [#customer-attachments]
The AI agent can read supported customer attachments without a custom action or workflow. It receives a file ID, filename and content type, then reads the attachment when its contents are relevant. Attachment notices do not expose private download URLs.
| Attachment | Built-in reader | What the AI agent receives |
| -------------------------------------------- | ------------------------------- | ------------------------------------------------ |
| Images | `viewImage({fileId, question})` | A vision model's answer to the specific question |
| PDFs, including scanned pages | `readFile({fileId})` | Extracted text with OCR where needed |
| Word documents (`.docx`) | `readFile({fileId})` | Document text |
| TXT, Markdown, CSV, TSV, JSON, XML, and YAML | `readFile({fileId})` | Text content |
| Forwarded emails (`.eml`) | `readFile({fileId})` | Sender, recipients, date, subject and body text |
Both readers check that the attachment belongs to the current conversation and passes the applicable access and safety checks. Image inspection follows the same checked path whether or not the AI agent's main model supports vision. Files and filenames are customer data, not instructions that can override the AI agent's rules.
Document reading accepts files up to 10 MB and PDFs of up to 30 pages. Larger PDFs need to be reduced to the relevant pages. It retains up to 100,000 extracted characters. Each call returns 12,000 characters by default, or up to 20,000 with `limit`. When a result includes `nextOffset`, the AI agent continues with `readFile({fileId, offset: nextOffset})`. Results disclose extraction limits, so the AI agent can tell a complete read from a partial one. A document's embedded images are not inspected separately by the text reader.
To find something in a long document, the AI agent searches it with `readFile({fileId, query})`, for example for an order or tracking number. Search is case- and accent-insensitive and returns up to 10 snippets with their offsets. The AI agent then reads around a match with `readFile({fileId, offset})`. If the whole phrase does not appear, it matches any of the phrase's words.
Forwarded emails are read as plain text: the sender, recipients, date, subject and body, including any quoted reply chain. HTML is reduced to its visible text. Scripts, styles and images are dropped, links keep only their visible label with long or marketing URLs shortened, and nothing in the email is loaded or run. Emails forwarded as attachments inside the email are read inline, up to three levels deep. Other attachments inside a forwarded email are listed by name but not read. The AI agent asks the customer to send any that matter as separate files. Outlook `.msg` files are not supported.
Extracted text is cached for 3 days, so follow-up questions about the same attachment don't repeat the download, OCR or safety check. Access to the attachment is still verified on every read.
Unsupported file types produce a clear error. For example, `readFile` cannot read an image, so the AI agent uses `viewImage` instead. If a file cannot be read, the AI agent explains the limitation and asks for a supported format, the relevant text pasted into the conversation, or a clearer image.
These readers belong to the customer-facing AI agent. To read a PDF from your own Python code, use the [`transcribe_pdf(url)` helper](/docs/developers/python-helpers/transcribe-pdf).
What the AI agent can't do on its own [#what-the-ai-agent-cant-do-on-its-own]
The AI agent is a model, a system prompt and tools in a loop, so its limits follow directly. They trip people up often, so here they are plainly.
**It has no sense of elapsed time and can't act on its own schedule.** A rule or workflow that says "if the customer doesn't reply, follow up in two hours" does nothing in the core loop. The AI agent only runs when a message comes in. It has no timer and no way to wake itself up later, so telling it to "wait" or "check back" has nothing to carry it out.
**It can only do what its tools allow.** It cannot browse your admin panel or "go look it up" anywhere it has no tool for. If there's no tool for an action, no instruction can make it happen. Its entire ability to *do* things, as opposed to *say* things, is the set of tools currently available to it.
**It can't reach the open web.** It has no general internet access. It knows what's in its prompt and what its tools return.
**It doesn't have your catalog or knowledge base memorized.** It searches, and its knowledge of your products and articles is limited to what it retrieves in the moment.
**It can make mistakes.** Like any LLM, it can occasionally get something wrong or state something its sources don't support. This is called a hallucination. Good instructions and knowledge reduce it, but they don't make it impossible.
**Instructions are guidance, not code.** Rules and workflow steps strongly shape behavior, but they are natural-language directions to a model, not deterministic program logic. Written clearly, they are followed reliably. Treated as exact if-this-then-that code, they surprise you at the edges.
> **When something must be guaranteed, move it out of the prompt and into code.** For anything that must hold every single time, such as strict identity checks, verifying state in another system, or exact time, money or eligibility logic, don't rely on instructions. Use [condition providers](/docs/developers/condition-providers), code that evaluates external state and decides which workflow variant the AI agent follows. Use [Python actions](/docs/developers/custom-actions), code the AI agent calls to do the work. The model still runs the conversation, but the parts that must be exact run as code.
Features around the loop [#features-around-the-loop]
The limits above describe the core loop on its own, so you have an accurate mental model of the engine. Octocom adds features *around* the loop that extend or safeguard it, so several of those limits don't apply to the product as a whole:
* **Acting later.** The loop can't follow up on its own, but [follow-ups](/docs/ai-agent/follow-ups-and-auto-resolve), [event handlers](/docs/developers/event-handlers) and [recurring jobs](/docs/developers/recurring-jobs) can make the AI agent reach out or act when time passes or something happens.
* **Catching mistakes.** The model can hallucinate, so Octocom checks replies around the loop. Built-in checks catch and correct a class of errors before a reply reaches the customer, such as a reply in the wrong language (see [Check the reply language](/docs/ai-agent/writing-style#language)). [Bot QA](/docs/ai-agent/bot-qa) adds your own checks, for example flagging a refund confirmation that no action result supports.
The rule to remember: **don't solve a loop-level limitation with a prompt instruction.** A rule that says "respond later" can't work, because the loop has no concept of later. Use the feature built for that job instead.
Debugging: the loop is fully observable [#debugging-the-loop-is-fully-observable]
Because a reply is this loop and nothing more, nothing is hidden. Octocom records the complete picture of every AI turn, so when a reply surprises you, you can see exactly what the model saw and did.
In the dashboard [#in-the-dashboard]
Open a conversation, hover over an AI message and click the **bug icon** ("Debug this message"). The **Response debugging information** panel shows:
* **System prompt:** the exact system prompt sent to the model for that turn, with its token count and build time.
* **Tool calls:** every tool the AI agent called, with its arguments, the result, execution timing and any logs from the call.
* **Reasoning:** the model's reasoning trace for each LLM call, when the model provides one.
* **Available actions:** every tool the AI agent could use on that turn, with each tool's description and parameters.
* **Response metadata:** the message content and response time.
If the AI agent "didn't know" about a product, you can check whether it searched at all. If it ignored a workflow, you can check whether that workflow's instructions and tools were present.
Through MCP [#through-mcp]
With [Octocom MCP](/docs/developers/mcp) or Copilot, the same information is available for any AI message:
* **`get_response_system_prompt`** returns the full system prompt that went into the LLM for that message.
* **`get_response_tool_calls`** returns the available actions, the tool calls (with arguments, results and logs) and the reasoning traces.
To find the message, use `get_conversation`, which lists the conversation's messages with their debug information. An AI agent can then inspect a real turn end to end: read the exact prompt, see which tools were available and trace what was called, to diagnose behavior or verify a configuration change.
> **You can see the full input.** The system prompt plus the conversation messages are the complete input the LLM received. There is no opaque step between what the customer said and what the AI agent replied.
Putting it together [#putting-it-together]
To configure the AI agent well:
1. **Shape how it sounds** with the [writing style](/docs/ai-agent/writing-style). The [system prompt](/docs/ai-agent/system-prompt) page shows every section it reads.
2. **Set the few standing guardrails** with [bot rules](/docs/ai-agent/bot-rules).
3. **Give it playbooks and capabilities** with [workflows](/docs/ai-agent/workflows) and [actions](/docs/ai-agent/actions), remembering that actions arrive *with* workflows.
4. **Let it find facts and products** through the knowledge base and product search, rather than expecting it to "just know".
5. **Use the dedicated features, not prompt instructions,** for anything the core loop can't do on its own, such as acting later or guaranteeing correctness.
Almost every "why did it do that?" or "why won't it do that?" comes back to one fact on this page: it's an LLM, looping over a system prompt and a set of tools, one message at a time.
# Human escalation
import { Accordions, Accordion } from "fumadocs-ui/components/accordion";
Human escalation is how the AI agent passes a conversation to your team when a person should take over: the customer asks for one, the request falls outside your policy, or the AI agent can't complete it. Octocom calls this a **handoff**. Good escalation is what makes an AI agent safe to put in front of customers.
A handoff is a firm change of ownership, not a suggestion. From that moment the conversation belongs to your team, and the AI agent stops replying in it. The one exception is web chat, where you can let the AI agent keep answering new questions until an agent replies.
What you can do [#what-you-can-do]
* **Hand off when a customer asks**, right away or after finding out what they need.
* **Hand off when a workflow reaches its limits**, such as a policy exception or a step that fails.
* **Collect a way to reach the customer first**, so your team can reply after they leave the chat.
* **Route to the right team** by language, topic, sentiment, channel or details collected in the conversation.
* **Put a phone caller through** to a department, a phone number or your team in the help desk.
* **Tell customers what happens next**, such as when your team will reply.
* **Hand off only during opening hours**, with an action that checks the time first.
This page covers the AI agent's side. For what your team sees and how replies reach the customer afterwards, see [Handed-off conversations](/docs/help-desk/handoff).
To have a teammate approve or decide something while the AI agent keeps the
conversation, use [human-in-the-loop
decisions](/docs/developers/human-in-the-loop), or [external
decisions](/docs/guides/approvals-from-outside-octocom) when another system
decides. To review every AI email reply before it is sent, use [AI reply
approval](/docs/ai-agent/ai-reply-approval).
Set it up [#set-it-up]
When a customer asks for a person, find out what they need first, then hand
off. Route German conversations to our German team and strongly negative ones
to our senior agents.
In the dashboard, the handoff options are in **Settings -> Automation -> Handoff**, the escalation steps are in your [workflows](/docs/ai-agent/workflows), and routing is in **Settings -> Help Desk -> Assignment Rules**. See [Settings](#settings) for the full list.
How the AI agent hands off [#how-the-ai-agent-hands-off]
The AI agent hands off by calling the built-in **`transferConversation`** action. You don't create this action, but like every action, it is only available where a [workflow](/docs/ai-agent/workflows) enables it. A business whose workflows don't enable `transferConversation` has no way to hand off on purpose.
New businesses start with two workflows that enable it: **Escalation request**, which hands off when a customer asks for a person, and **Other queries**, which offers a handoff when the AI agent can't resolve a question. A minimal escalation workflow looks like this:
* **When to follow:** *"When a customer asks to talk to a human or a supervisor"*
* **Actions:** `transferConversation`
* **Instructions:** ask what the customer needs so the team has context, then call `transferConversation`.
The AI agent only signals that a person is needed. It doesn't choose the team. **Routing is a separate, predictable step** that runs after the handoff. See [Routing to the right team](#routing-to-the-right-team).
What the AI agent collects first [#what-the-ai-agent-collects-first]
Before it hands off, the AI agent makes sure your team has a way to reach the customer, so they can reply even after the customer has left. What it needs depends on the channel and on the **Before handoff** options in your [handoff settings](/docs/help-desk/handoff#before-handoff):
| Channel | What the AI agent needs before handing off |
| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Web chat | An email address, when **Ask for an email address** is on (the default). A phone number too, when **Also ask for a phone number** is on. |
| Email, social media, contact forms and other channels | An email address, when **Ask for an email address** is on. |
| WhatsApp | The customer's phone number. |
| Web chat embedded in another help desk | Nothing. The handoff is immediate. |
| Phone calls | Nothing, or a destination. See [Phone calls](#phone-calls). |
When the customer's email address is already on their profile, as it always is on email, the AI agent doesn't need to ask. Otherwise the address has to come from the conversation: one the customer gave, or one an action returned. The AI agent can't invent one or use your own support address.
The address is kept on the conversation as the `octocom:handoffContactEmail` metadata, shown in the conversation sidebar under **Metadata**. Help desk tickets, handoff emails and the first email reply for that conversation go to it. It never replaces an email already on the customer's profile and never merges customers.
Automatic handoffs [#automatic-handoffs]
Not every handoff comes from the AI agent's decision. These hand off on their own:
| Trigger | What happens |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Follow-ups exhausted** | With **Hand off when follow-ups are exhausted** on, an unresolved email conversation is handed off once its follow-ups are used up. See [Follow-ups and auto-resolve](/docs/ai-agent/follow-ups-and-auto-resolve). |
| **Bot QA cancels a reply** | A confirmed violation on a [Bot QA](/docs/ai-agent/bot-qa) check set to **Hand off to a person** hands the conversation to your team. |
| **A reply draft is rejected** | With [AI reply approval](/docs/ai-agent/ai-reply-approval), rejecting a draft hands the conversation to your team. |
| **The AI agent can't produce a reply** | If a reply fails three times, the AI agent stops retrying and hands off rather than leaving the customer waiting. |
| **An agent takes over** | **Take over conversation** in the help desk hands the conversation off to that agent. |
What happens at a handoff [#what-happens-at-a-handoff]
1. **The AI agent sends its closing message.** It is told the conversation will be transferred after its message, so the customer always hears what happens next. Octocom tells it where your team will reply, and your [handoff settings](/docs/help-desk/handoff) shape what it says about response times.
2. **The conversation is marked handed off.** A closed conversation is reopened and AI messages still scheduled for later are canceled. On the Octocom help desk, auto-close stops, so the conversation stays open until a person closes it. The reason is recorded on the conversation timeline.
3. **The conversation is analyzed.** Topics, sentiment, language and [data collection](/docs/analytics/data-collection) fields are computed from the transcript.
4. **The `Conversation Handed Off` event fires,** running any [event handlers](/docs/developers/event-handlers) you set up, such as a Slack alert.
5. **The conversation is routed.** On the Octocom help desk, [assignment rules](/docs/help-desk/assignment) pick a team or agent. With an [external help desk](/docs/help-desk/third-party-help-desk), Octocom creates or updates a ticket there and that help desk handles routing.
Because analysis runs before assignment, assignment rules can use topics, sentiment, language and data collection values from the whole conversation.
After the handoff, the AI agent stays quiet in that conversation. The exception is web chat with the after-handoff behavior set to **Keep answering**: the AI agent then keeps helping with new questions until an agent replies. [Handed-off conversations](/docs/help-desk/handoff) covers where your team replies, the live chat timeout and what the customer sees while waiting.
Write escalation instructions [#write-escalation-instructions]
How readily the AI agent should hand off is a business decision. Three approaches cover most setups.
**Hand off on request.** The AI agent asks what the customer needs, then hands off. Your team gets context without making the customer work for it.
> If the customer wishes to talk to a human or a supervisor, first find out what they need help with, so the team can pick it up. Don't transfer the conversation if it's not clear what the customer wants. Once the customer has explained their request, call `transferConversation`.
**Hand off without questions.** The fastest path to a person. Lowest friction, highest handoff rate.
> If the customer wishes to talk to a human or a supervisor, call `transferConversation` right away. Don't ask them to explain their request first.
**Try once, then hand off.** The AI agent attempts the request before escalating. Lowest handoff rate, and the most likely to frustrate a customer who really wants a person.
> If the customer asks to talk to a human or supervisor, explain that you can help with most requests and ask what they need. If you can't resolve it, or the customer insists on a person, call `transferConversation`.
**Tips for any approach:**
* **Add a fail-safe to every workflow.** End each workflow with a step such as *"If you are blocked or the request needs a policy exception, call `transferConversation`."* Most handoffs should come from workflows that reach their limits, not from a dedicated escalation workflow.
* **Don't instruct the AI agent to collect the email.** When **Ask for an email address** is on, the action itself requires it, and the AI agent asks the customer.
* **Don't script the closing message.** The action already tells the AI agent where the team will reply and to end with a goodbye. Put response-time expectations in the [handoff settings](/docs/help-desk/handoff) (**Expected response time** and **What to tell the customer**) instead of workflow instructions.
* **Make the handoff an explicit step.** If the AI agent says "let me transfer you" without calling the action, the customer waits for nothing. A numbered step that calls `transferConversation` prevents this, and Octocom can turn on a safeguard that rewrites any reply promising a transfer the AI agent didn't make.
* **Say what to collect, not where to route.** Routing happens after the AI agent is done.
Routing to the right team [#routing-to-the-right-team]
`transferConversation` says that a person is needed, not which person. **[Assignment rules](/docs/help-desk/assignment)** decide that. They run right after the handoff and can match on:
* business, channel and email inbox
* tags and priority
* topics, language and sentiment
* [data collection](/docs/analytics/data-collection) values
Each rule has conditions (all must match) and a target: a team or a specific person. Rules are checked in priority order and the first full match wins. A rule that targets a team narrows the pool, then your round-robin or balanced assignment picks the agent.
Many routes need no code at all, because topics, language and sentiment are computed during the handoff. For example, language `de` routes to your German team, and sentiment `Strongly Negative` routes to senior agents.
When the AI agent itself should choose the department, give it a custom action that tags the conversation and then hands off, and add an assignment rule for each tag. See [Route by department](#route-by-department) in the developer section.
If you use an external help desk, routing and assignment happen there. Octocom creates the ticket according to **Settings -> Help Desk -> Ticket Routing**. See [Third-party help desk](/docs/help-desk/third-party-help-desk).
Phone calls [#phone-calls]
On a phone call, `transferConversation` puts the caller through to a person. What it does depends on the **transfer destinations** in the [voice AI settings](/docs/channels/voice/voice-ai-settings#transfers):
| Destinations | What `transferConversation` does |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| One | Transfers the live call to it. |
| Several | Transfers the live call to the destination the AI agent chooses. It can only choose from the names you configured, such as "Sales" or "Billing". |
| None | Doesn't transfer. The conversation is handed to your team in the help desk, the caller stays with the AI agent until the call ends, and the AI agent tells them someone will be in touch. |
A destination can be a phone number, a SIP address or `your_team`, which rings your available agents in the Octocom help desk. For a fixed menu of departments, destinations are all you need. To pick the destination with your own logic, such as opening hours, the account owner or an API lookup, see [Transfer calls with your own logic](#transfer-calls-with-your-own-logic). For tips on transfers that always connect, see [Voice AI best practices](/docs/channels/voice/voice-ai-best-practices#transfers-that-work).
Choose an approach [#choose-an-approach]
| You need | Use |
| ----------------------------------------------- | ------------------------------------------------------------------- |
| A person when the customer asks | `transferConversation` in an escalation workflow |
| A handoff when a workflow reaches its limits | A `transferConversation` fail-safe step in that workflow |
| Different teams by language, topic or sentiment | Assignment rules, no code |
| Different teams chosen by the AI agent | A custom action that tags, then an assignment rule |
| Escalation only during opening hours | A custom action that checks the time before handing off |
| A live call put through to a fixed set of teams | Transfer destinations in the voice AI settings |
| A live call routed by your own logic | A custom action with `hand_off_conversation(phone_destination=...)` |
| Something to happen after every handoff | An event handler on `Conversation Handed Off` |
FAQ [#faq]
**Why isn't the AI agent handing off?** In order of likelihood: no workflow enables `transferConversation`; the workflow isn't selected for that kind of request; or the customer hasn't given an email address and **Ask for an email address** is on. Open the conversation in the help desk and select **Debug this message** on the AI agent's reply to see which actions it had and called.
**The AI agent said it would transfer, but nothing happened.** It promised the transfer without calling the action. Make the action call an explicit numbered step in the workflow instructions. Octocom can also turn on a safeguard that catches these replies and writes them again.
**Can the AI agent hand off without an email address?** Yes. Turn off **Ask for an email address** in **Settings -> Automation -> Handoff**. Consider first how your team will reach a customer who has left the chat.
**Does a handoff close the conversation?** No, the opposite. A closed conversation is reopened, and on the Octocom help desk auto-close stops, so it stays open until a person closes it.
**Can a handed-off conversation go back to the AI agent?** No. A handoff is permanent for that conversation. On web chat, the **Keep answering** option lets the AI agent keep answering new questions until an agent replies.
**How do I see why a conversation was handed off?** The reason is recorded on the conversation timeline. [Conversation topics](/docs/analytics/conversation-topics) shows which subjects lead to handoffs over time.
Settings [#settings]
Most handoff behavior is self-service:
* **Settings -> Automation -> Handoff:** asking for an email address or phone number, live chat, response times, what the AI agent tells the customer, and what it does after the handoff. See [Handed-off conversations](/docs/help-desk/handoff#handoff-settings). Copilot and MCP use `get_handoff_settings` and `update_handoff_settings`.
* **Settings -> Automation -> Follow-Ups:** **Hand off when follow-ups are exhausted**. See [Follow-ups and auto-resolve](/docs/ai-agent/follow-ups-and-auto-resolve).
* **Settings -> Help Desk -> Assignment Rules:** where handed-off conversations go. See [Assignment and routing](/docs/help-desk/assignment).
Two options are set by Octocom on request: turning off `transferConversation` entirely, so the AI agent can never hand off on purpose, and the safeguard that rewrites replies promising a transfer that didn't happen.
For developers: custom escalation actions [#for-developers-custom-escalation-actions]
When escalation needs a decision ("are we open?", "which team?", "which number?"), put that logic in a [custom Python action](/docs/developers/custom-actions) that calls [`hand_off_conversation`](/docs/developers/python-helpers/hand-off-conversation), rather than in instructions.
**The action decides whether the handoff happens.** If it returns without calling `hand_off_conversation`, nothing is handed off, and its return value tells the AI agent what to say instead. When it does hand off, Octocom sets the reply channel as for `transferConversation` and tells the AI agent where the team will reply (by email, in the chat, in Messenger), so your action's text shouldn't promise a channel. If your team needs the customer's email first, collect it in the action (for example with an `email` argument) and hand off only once you have it.
`hand_off_conversation` can only be called from an action the AI agent runs, not from a condition provider, event handler or sidebar widget. It has no effect when you test the action on its own.
Route by department [#route-by-department]
Tag the conversation, then hand off. Tags written before the handoff are already on the conversation when assignment rules run, so one rule per tag sends each department to its team.
```python
def execute_action(context):
args = context["args"]
department = args["department"] # "billing" | "technical" | "sales"
add_conversation_tag(context, f"dept:{department}")
set_conversation_metadata(context, "escalation_reason", args["reason"])
hand_off_conversation(context, reason=args["reason"][:500])
return {
"success": True,
"message": "Tell the customer the right team will follow up shortly.",
}
```
Constrain the AI agent to your exact values in the argument description. The AI agent picks the department, but only from a list you control:
> The `department` argument MUST be one of these exact values: "billing", "technical", "sales". If you don't know which one the customer needs, ask before calling this action.
Gate on working hours [#gate-on-working-hours]
The most common custom escalation. An action named, for example, `tryEscalateToHuman` (the name tells the AI agent it might not succeed) checks the clock and public holidays before handing off, and returns an explanation for the customer when the team is closed.
```python
from datetime import datetime
from zoneinfo import ZoneInfo
def execute_action(context):
now = datetime.now(ZoneInfo("Europe/Berlin"))
today = is_holiday("DE", check_date=now.strftime("%Y-%m-%d"))
open_now = (
now.weekday() < 5
and 9 <= now.hour < 18
and not today.get("isHoliday")
)
if not open_now:
return {
"success": False,
"reason": "outside_working_hours",
"message_to_customer": (
"Our team is available Monday to Friday, 9:00–18:00 CET. "
"Leave your question here and we'll reply on the next working day."
),
}
hand_off_conversation(context, reason="Customer requested a human agent")
return {"success": True, "message_to_customer": "Connecting you to an agent now."}
```
Describe the closed-hours behavior in the action description too, so the AI agent knows what a refusal means and doesn't retry in a loop.
Two habits worth copying:
* **Say explicitly what did not happen.** If the return value doesn't say the handoff was refused, the AI agent may still tell the customer they're being connected.
* **Fail open.** If your gating logic itself errors, hand off anyway. A brief outage in another system should never stop a customer from reaching a person.
For hours that differ by customer type, take an argument such as `is_b2b`, apply a different schedule to each, and tag the conversation (for example `customer:b2b`) so an assignment rule can route it to the right team.
Transfer calls with your own logic [#transfer-calls-with-your-own-logic]
Use a custom action when the call's destination depends on logic rather than a fixed list: opening hours, the agent who owns the account, or an API lookup. Pass `phone_destination` to `hand_off_conversation` and the live call is transferred to that number:
```python
DESTINATIONS = {
"Sales": "+15551230001",
"Support": "+15551230002",
"Accounting": "+15551230003",
}
def execute_action(context):
destination = context["args"].get("destination")
if destination not in DESTINATIONS:
valid = ", ".join(f'"{d}"' for d in DESTINATIONS)
return {
"success": False,
"message": f"Invalid destination. Valid values are: {valid}. Try again.",
}
hand_off_conversation(context, phone_destination=DESTINATIONS[destination])
return {"success": True}
```
* **Put the menu in the action description,** listing every valid destination, and tell the AI agent to ask the caller when it isn't sure. Rejecting an invalid value with the valid list in the message lets the AI agent recover on its next turn.
* **`phone_destination` is ignored outside phone calls,** so the same action works for chat, where it becomes a normal handoff. Combine it with a working-hours check so calls outside hours become a regular handoff (a callback the next working day) instead of ringing an empty office.
Override the built-in action [#override-the-built-in-action]
A custom Python action named `transferConversation` **replaces the built-in one**. On a name clash, Python actions win over API actions, which win over built-in actions. Override when you want the same role with different mechanics (extra arguments, your own validation, tags on the way out) without changing every workflow that already uses `transferConversation`.
```python
def execute_action(context):
email = context["args"].get("email")
reason = context["args"].get("reason")
if not email:
return {"success": False, "message": "Email is required to transfer the conversation."}
upsert_customer(context, email=email)
hand_off_conversation(context, reason=reason)
return "The team will reach out by email as soon as possible."
```
Your override does not inherit what the built-in action does:
* the channel-aware arguments (phone on WhatsApp, none on web chat embedded in another help desk) and the email checks
* the closing-message guidance from your handoff settings
A clear instruction in your return value covers most of the second point. If you only need to **add** behavior (a tag, a metadata field, a Slack message), prefer a separate action with its own name, or an [event handler](/docs/developers/event-handlers) on `Conversation Handed Off`, and keep the built-in action.
| Helper | Role in escalation |
| ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
| [`hand_off_conversation(context, reason=None, phone_destination=None)`](/docs/developers/python-helpers/hand-off-conversation) | Performs the handoff. `reason` is capped at 500 characters. |
| [`add_conversation_tag(context, tag)`](/docs/developers/python-helpers/add-conversation-tag) | Tags applied before the handoff are visible to assignment rules. |
| [`set_conversation_metadata(context, key, value)`](/docs/developers/python-helpers/set-conversation-metadata) | Records structured context for the agent picking the conversation up. |
| [`is_holiday(country, check_date=None)`](/docs/developers/python-helpers/is-holiday) | Public-holiday checks in working-hour gates. |
| [`send_slack_notification(webhook_url, text)`](/docs/developers/python-helpers/send-slack-notification) | Alerting your team about high-priority escalations. |
The full list is in [Python helpers](/docs/developers/python-helpers).
# AI agent overview
The Octocom AI agent talks to your customers and resolves their requests end to end. It answers from your knowledge, follows your procedures and does the work in your own systems. When a person should decide or take over, it brings in your team, in the same help desk.
What it does [#what-it-does]
* **Answers from your knowledge.** Return windows, what a policy covers, which plan includes roaming, how to set up a device. It searches your articles, documents and website the way a person searches a help center.
* **Does the work.** It cancels an unshipped order, pauses a subscription, reports a claim's status or changes a mobile plan. Actions can run any code, so it can do anything your systems allow. See [Actions](/docs/ai-agent/actions).
* **Follows your processes.** Workflows tell it what to check, what to ask and when to hand over, situation by situation.
* **Works on every channel.** Web chat, email, phone calls, SMS, WhatsApp, Facebook, Instagram and [more](/docs/channels). You configure it once per [business](/docs/overview/organizations-and-businesses) and adjust it per channel where needed.
* **Speaks your customer's language.** By default it replies in the language of the customer's latest message.
* **Knows when to step back.** It hands the conversation to your team when a customer asks for a person, a request falls outside your policy, or it can't finish the job.
What shapes it [#what-shapes-it]
Six building blocks shape the AI agent. Each has one job:
| Building block | What it does |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [Knowledge base](/docs/ai-agent/knowledge-base) | The facts it looks up: articles, [documents](/docs/ai-agent/documents) and [website pages](/docs/ai-agent/website-sources) |
| [Bot rules](/docs/ai-agent/bot-rules) | A few always-on guardrails, such as "never promise a delivery date" |
| [Workflows](/docs/ai-agent/workflows) | Step-by-step playbooks for situations such as a cancellation, a damaged item or a claim |
| [Actions](/docs/ai-agent/actions) | What it can do in your systems, switched on inside workflows |
| [Writing style](/docs/ai-agent/writing-style) | How it sounds: tone, chat and email style, reply language |
| [System prompt](/docs/ai-agent/system-prompt) | Every section of its instructions in order, including expert sections you can edit |
Most setup problems come from putting something in the wrong place. A fact belongs in the knowledge base, a procedure in a workflow, a guardrail that must always hold in a bot rule, and the voice in the writing style.
Every reply comes from one loop: a language model reads its instructions, the conversation and its tools, looks up what it needs, then replies. [How the AI agent works](/docs/ai-agent/how-it-works) explains that loop and what follows from it. Read it before you configure anything complex.
People stay in the loop [#people-stay-in-the-loop]
You decide where a person takes part:
* **Handoff.** The AI agent passes a conversation to your team with the full history, and assignment rules route it to the right person. See [Human escalation](/docs/ai-agent/human-escalation).
* **Decisions without a handoff.** A teammate approves an exception or reviews damage photos while the AI agent keeps the conversation. See [Human-in-the-loop decisions](/docs/developers/human-in-the-loop).
* **Approval of email replies.** AI email replies wait as drafts until an agent approves them. See [AI reply approval](/docs/ai-agent/ai-reply-approval).
* **Follow-ups.** The AI agent nudges quiet email customers and closes conversations that are done. See [Follow-ups and auto-resolve](/docs/ai-agent/follow-ups-and-auto-resolve).
Quality you can verify [#quality-you-can-verify]
* **Test before customers see it.** Chat with the AI agent in the playground, or have Copilot run whole sets of test conversations on web chat, email and phone. See [Test your AI agent](/docs/ai-agent/testing).
* **Check replies automatically.** [Bot QA](/docs/ai-agent/bot-qa) checks replies against your rules and can stop a bad email, Instagram or Messenger reply before it is sent.
* **See exactly why it replied.** For any reply, you can see the instructions it read, the actions it called and what they returned.
* **Compare and roll back.** [A/B testing](/docs/ai-agent/ab-testing) measures which version performs better. Workflows, actions, bot rules and articles keep a version history you can restore.
Set it up [#set-it-up]
You don't have to configure any of this by hand. Describe the outcome to Copilot in the dashboard, or to your own AI agent through [Octocom MCP](/docs/developers/mcp):
Set up our AI agent for the five requests customers send us most, based on
last month's conversations. Add the knowledge it needs, build a workflow for
each request, then run test conversations and show me what needs fixing.
The agent writes the articles and workflows, builds and tests the actions, then runs test conversations to check the result. It explains each change before making it and records every change. Workflows, actions, bot rules and articles keep earlier versions you can restore. For complex setups, Octocom's solution engineers review the configuration and test it with you. See [Set up Octocom with AI](/docs/overview/set-up-with-ai).
If you prefer to click through it yourself, most of these settings live under **Settings -> Automation**.
Recommended setup order [#recommended-setup-order]
Add your knowledge [#add-your-knowledge]
Write articles for your most common questions, upload policy documents and add your help center pages. The AI agent can answer from them as soon as they are indexed. See [Knowledge base](/docs/ai-agent/knowledge-base).
Set the writing style [#set-the-writing-style]
Check the tone and the chat and email styles. The defaults work for most businesses. See [Writing style](/docs/ai-agent/writing-style).
Build workflows for your top requests [#build-workflows-for-your-top-requests]
Start from the requests your team handles most, such as order status, cancellations, address changes, claim status or billing questions. New businesses already have two default workflows: one hands off when a customer asks for a person, and one answers general questions. See [Workflows](/docs/ai-agent/workflows).
Connect actions [#connect-actions]
Give the workflows the actions they need to look things up and make changes in your systems. See [Actions](/docs/ai-agent/actions).
Decide how handoff works [#decide-how-handoff-works]
Set when the AI agent hands over and what it tells customers when it does. See [Human escalation](/docs/ai-agent/human-escalation) and [Handed-off conversations](/docs/help-desk/handoff).
Add a few bot rules [#add-a-few-bot-rules]
Add only the guardrails that must hold in every conversation. Strong setups typically run on about 15 to 20. See [Bot rules](/docs/ai-agent/bot-rules).
Test, then go live [#test-then-go-live]
Run test conversations for your main scenarios and set up [Bot QA](/docs/ai-agent/bot-qa) checks. Consider [AI reply approval](/docs/ai-agent/ai-reply-approval) for email while you start out. See [Test your AI agent](/docs/ai-agent/testing).
Once the AI agent is live, [Raise your resolution rate](/docs/guides/improve-resolution-rate) shows how to find what it still hands off and close the biggest gaps first.
Explore [#explore]
# Knowledge base
The knowledge base is the AI agent's reference material: return and cancellation policies, coverage terms, plan details, opening hours, troubleshooting steps. The AI agent searches it whenever a customer asks something factual. The more of your answers it can find there, the more questions it resolves without your team.
What you can do [#what-you-can-do]
* **Write articles** for policies, procedures and the answers to common questions, organized in folders with a version history.
* **Upload documents** such as policy terms, manuals, price lists and spreadsheets of reference data. See [Knowledge documents](/docs/ai-agent/documents).
* **Add your website** or help center by URL or sitemap, and keep it refreshed. See [Website sources](/docs/ai-agent/website-sources).
* **Time-limit an article** for a promotion, a seasonal policy or a planned closure.
* **Limit an article to some channels**, so a phone call never reads out a long URL.
* **Publish articles to your help center**, independently of what the AI agent uses.
* **Keep articles in sync** with a CMS, a feed or a spreadsheet. See [Syncing articles from another system](#syncing-articles-from-another-system).
Set it up [#set-it-up]
Hand your agent the material you already have and let it do the writing:
Add our help center at help.example.com to the knowledge base, and turn the
attached returns policy PDF into articles, one topic per article, written the
way customers ask. Then test that the AI agent answers our ten most common
return questions correctly.
In the dashboard, open **Settings -> Automation -> Knowledge** and choose **Articles**, **Documents** or **Websites**.
How it works [#how-it-works]
The AI agent does not know your knowledge base. It searches it.
Your knowledge base is never written into the system prompt. Instead, the AI agent gets:
1. A one-line note that a knowledge base exists and roughly how much content is in it.
2. A single tool, **`searchKnowledgeBase`**, that takes a search query and returns the matching passages.
When a customer asks something factual, the AI agent writes a search query, reads what comes back and answers from it. It works like a support agent who searches a help center instead of reciting it from memory. If it needs more, it searches again: up to nine searches in one reply, and again on later messages.
> **The AI agent is only as good as what it can find.** If the answer isn't in the knowledge base, searching won't invent it. And if the answer is there but phrased so differently from how customers ask that search doesn't surface it, the AI agent effectively doesn't have it either.
It turns on by itself [#it-turns-on-by-itself]
`searchKnowledgeBase` is **not** something you enable, and it is **not** tied to a workflow. Unlike [actions](/docs/ai-agent/actions), which only become available inside a [workflow](/docs/ai-agent/workflows) that includes them, it is always available as long as there is something to search:
| Knowledge base state | What the AI agent gets |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| At least one active entry (an article, webpage or document) | The tool and the knowledge base note, from the first message |
| Completely empty, or everything inactive | Neither. The tool doesn't exist for the AI agent |
A new business with one article can already look it up, with no workflow, rule or configuration. Equally, if your knowledge base is empty, instructing the AI agent to "check the knowledge base" does nothing: there is no tool for it to call.
Where knowledge comes from [#where-knowledge-comes-from]
Articles [#articles]
Articles are the primary source, and the one you'll use most. An article is a titled entry in Markdown that you write under **Settings -> Automation -> Knowledge -> Articles**, organized in folders. Use articles for anything you want deliberate control over: policies, procedures and canonical answers to common questions.
Articles support folders, version history, archive and restore, translations for the help center, and JSON import and export for bulk editing.
If you have Zendesk connected, its Help Center articles can be synced in and become ordinary articles here, marked with their source. Other synced sources work the same way: once imported, they behave like any other article. To keep articles in step with a system of your own, such as a CMS or an XML feed, see [Syncing articles from another system](#syncing-articles-from-another-system).
Websites [#websites]
Point Octocom at a URL or a sitemap and it scrapes the pages into the knowledge base. Sitemap mode previews the URL tree and takes include and exclude patterns with wildcards, so you can pull in `/help/*` without your entire blog. Sitemaps are re-checked on a schedule, and single pages can be rescraped on demand. To manage pages programmatically or keep them in sync with an external feed of links, see [Website sources](/docs/ai-agent/website-sources).
Websites work well for a help center or documentation site you already maintain elsewhere. They are weaker as your only source: scraped marketing pages tend to be long and vague, which makes for poor search results.
Documents [#documents]
Upload files directly. Accepted formats: **`.pdf`, `.docx`, `.txt`, `.md`, `.csv`, `.xlsx`, `.xls`**.
A text document becomes one knowledge base entry with its extracted text. Spreadsheets and CSVs are handled row by row: **each row becomes its own entry**, which suits structured reference data such as a list of branches, a size chart, a price list or shipping rates per country.
After upload, a file is processed before the AI agent can find it. The documents table shows a **Learned** percentage while that happens. It usually takes seconds, longer for large PDFs. See [Knowledge documents](/docs/ai-agent/documents) for uploading through MCP and the REST API, indexing status and safe automated refreshes.
How search works [#how-search-works]
This explains most "why didn't it find that?" situations.
**Everything is chunked.** Content is stored as passages, not whole articles. Anything up to about 6,000 characters stays as a single chunk. Longer content is split into 5,000-character windows that overlap by half, so a fact near a split point still appears whole in at least one chunk. For articles, the title is stored with the body, so a clear, descriptive title helps the entry get found.
**Search is by meaning, not keywords.** The AI agent's query is compared with every chunk by semantic similarity, so "can I send this back?" can match an article titled "Return policy" with no shared words.
**Results are filtered before they reach the AI agent.** The most similar chunks are gathered as candidates, then a language model reviews them against the query and keeps only the ones that answer it. The AI agent receives a focused set of passages, not a pile of loose matches, and there is a hard cap on the total volume returned per search.
Controlling what the AI agent can see [#controlling-what-the-ai-agent-can-see]
Each article has its own controls in the **AI agent** section of the article editor:
| Control | What it does |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Use in answers** | When off, the article is invisible to the AI agent. It still exists and stays editable. Use this when an answer is temporarily wrong |
| **From** / **Until** | An optional date window. Outside it, the article is invisible to the AI agent. Useful for seasonal policies, a promotion's terms, planned closures or a temporary service change |
| **Channels** | Restricts the article to specific channels. Leave it empty and the article applies everywhere (the default) |
Channel scoping is for facts that are true on one channel and wrong on another: a phone call shouldn't read out a long URL, and web chat shouldn't quote phone-queue wait times.
> **These controls exist for articles only.** Scraped webpages and uploaded documents are always active on every channel. If a fact needs a date window or channel scoping, put it in an article.
Website pages can be removed and documents archived. Archived documents and articles are excluded from search and can be restored.
Help center visibility is separate [#help-center-visibility-is-separate]
An article can also be **Published** (in the **Help center** section of the editor), which shows it in your customer-facing [help center](/docs/channels/customer-portal/help-center). That is independent of whether the AI agent uses it: the AI agent follows **Use in answers**, not **Published**. Most articles are for the AI agent only. New articles start unpublished, in the dashboard, through MCP (`create_article`) and through the REST API, so publishing one is a deliberate extra step. Internal escalation criteria or margin thresholds should stay unpublished.
The reverse does not hold: an article with **Use in answers** switched off is never shown in the help center or its public APIs, even when it is published. Switching off a temporarily wrong answer takes it away from customers everywhere.
Folders cap what their articles can do [#folders-cap-what-their-articles-can-do]
Folders group articles in the dashboard and become the sections of your help center. Each folder has the same two switches as an article, **AI agent** and **Help center**, and they act as a ceiling:
| Folder switch | Effect on the articles inside |
| --------------- | -------------------------------------------------------------------------------------- |
| AI agent off | None of its articles reach the AI agent, whatever their own **Use in answers** setting |
| Help center off | The folder and all its articles are hidden from the help center and its public APIs |
Each article keeps its own settings. Moving an unpublished article into a published folder does not publish it, and switching a folder back on restores exactly the articles that are themselves on. A folder with both switches off holds internal, team-only knowledge. Deleting a folder moves its articles to the top level and carries any switch that was off over to them, so nothing becomes visible by accident.
Translations are for the help center [#translations-are-for-the-help-center]
An article's own title and content are its **main-language** version, and that is what the AI agent searches. To offer the help center in more languages, add the languages in the help center settings, then add a translation of each article. Translations are written by you or your AI agent through MCP; nothing is translated automatically. A translation is marked **outdated** when the main-language text changes after it was written.
Writing knowledge the AI agent can find [#writing-knowledge-the-ai-agent-can-find]
The knowledge base is a search index, and content that reads well to a person isn't automatically content that retrieves well. A few habits make a large difference:
**Write in the customer's words, not your internal ones.** An article titled "RMA process, tier 2" won't match "I want to return my order", and "FNOL procedure" won't match "I need to report an accident". Titles and opening sentences should read like the question a customer would ask.
**One topic per article.** A single sprawling "Policies" article gets chunked arbitrarily, and a search about delivery times may surface the chunk about warranty claims. Separate articles retrieve far more precisely.
**Make each article self-contained.** The AI agent may see one chunk with no surrounding context. "As mentioned above, this also applies here" means nothing on its own. Repeat the necessary context instead of referring to it.
**State facts plainly.** "Returns are accepted within 30 days of delivery, provided the item is unused and in its original packaging" is usable. "We aim to be flexible about returns wherever possible" gives the AI agent nothing to answer with, and it will either hedge or hand off.
**Cover the phrasings customers use.** If people ask about "refunds", "money back" and "cancelling" for the same underlying policy, mention those terms in the article. Semantic search is good, but it isn't telepathic.
> **Articles are searched in the language they're written in.** If you maintain translations for your help center, the AI agent still searches the main-language text and answers the customer in their own language. You do not need a translated copy of every article for the AI agent to work in several languages.
When to use the knowledge base, and when not to [#when-to-use-the-knowledge-base-and-when-not-to]
Knowledge and behavior can live in three places. Choosing the right one matters more than how well you write any single entry.
| What you're adding | Where it belongs |
| --------------------------------------------------------------------------- | ------------------------------------------ |
| A **fact** the AI agent needs only when it's relevant | **Knowledge base** |
| A **procedure** for a specific situation, especially one that takes actions | A [**workflow**](/docs/ai-agent/workflows) |
| A **global constraint** that must hold in every conversation | A [**bot rule**](/docs/ai-agent/bot-rules) |
Most of your content belongs in the knowledge base. It costs nothing when it isn't relevant, and there's no practical limit on how much you can have. Bot rules, by contrast, are deliberately capped because they occupy the system prompt on every turn.
One boundary to be explicit about: **the knowledge base is read-only reference material.** It tells the AI agent things. It cannot make the AI agent do things. An article that says "when a customer asks for a refund, issue it" will not cause a refund: the AI agent has no refund tool unless a workflow gives it one. Anything that involves an action belongs in a workflow.
Troubleshooting: the AI agent didn't find the answer [#troubleshooting-the-ai-agent-didnt-find-the-answer]
Work down this list:
1. **Is the entry active?** Check **Use in answers**, the **From** and **Until** dates and the folder's **AI agent** switch. An expired **Until** date silently removes the article from search.
2. **Is it channel-scoped?** An article restricted to web chat is invisible on email.
3. **Has it finished processing?** New documents and newly scraped pages take a moment to become searchable. Check the **Learned** column.
4. **Would you find it by searching?** Read the customer's message, imagine the search phrase the AI agent would write, and ask whether your article's title and opening line resemble it. This is by far the most common cause: the content is there, phrased in internal language.
5. **Is it buried in a long article?** A fact deep inside a general article competes with everything around it. Split it out.
6. **Is it a workflow problem?** If the AI agent found the right information but did the wrong thing with it, that's not a knowledge gap. See [Workflows](/docs/ai-agent/workflows).
The conversation's debug view shows exactly what the AI agent searched for and what came back. Every `searchKnowledgeBase` call is logged with its query and how many passages it returned, which usually settles the question. See [How the AI agent works](/docs/ai-agent/how-it-works#debugging-the-loop-is-fully-observable).
For developers and AI agents [#for-developers-and-ai-agents]
Date windows [#date-windows]
Through MCP (`create_article`, `update_article`) and the REST API (`POST` and `PATCH /rest/v1/articles`), the **From** and **Until** window is `activeFrom` and `activeTo`: ISO 8601 date-times with a time zone, such as `2026-12-01T00:00:00Z`. `null` means no date, and on an update an omitted field keeps the current date. A window that ends before it starts is rejected. `get_article` and `GET /rest/v1/articles/{id}` return the current dates.
Syncing articles from another system [#syncing-articles-from-another-system]
A [recurring job](/docs/developers/recurring-jobs) can keep articles in step with a feed, CMS or spreadsheet through the REST API. Recurring jobs get `OCTOCOM_API_BASE_URL` and `OCTOCOM_ORG_API_KEY` injected, so no API key secret is needed.
| Method | Path | Use |
| ------ | ------------------------------------------------------ | ---------------------------------------------------------------------- |
| GET | `/rest/v1/articles?businessSlug=shop&limit=500&page=1` | Page through live articles: `id`, `title`, `externalId`, `contentHash` |
| POST | `/rest/v1/articles` | Create `{businessSlug, title, content, externalId}` |
| PATCH | `/rest/v1/articles/{id}` | Update `{businessSlug, title, content}` or claim with `externalId` |
| DELETE | `/rest/v1/articles/{id}?businessSlug=shop` | Archive an article the source no longer has (restorable) |
| GET | `/rest/v1/articles/{id}?businessSlug=shop` | Read one article's full `content` |
* **`externalId`** is your stable key for the source item, such as its URL or record ID. It is unique among the business's live articles: a second article with the same key is rejected with `409` and the existing article's id. Keyed articles are matched only by key, so several source items may share a title. Articles without a key are left to people.
* **`contentHash`** is the MD5 hex digest of the UTF-8 content. The list returns it instead of the content, so a job can find changes without downloading every body: `hashlib.md5(content.encode("utf-8")).hexdigest()`.
A reliable sync recomputes the difference on every run instead of keeping a cursor:
1. Fetch the source and build each item's exact title and content.
2. List all articles and keep the ones whose `externalId` belongs to this source.
3. Create missing keys, update keys whose title or `contentHash` differ, and archive keys the source no longer has.
4. Stop starting writes well before the 5-minute limit. Each content change recomputes search embeddings, so writes take a second or more. The next run lists again and continues with whatever is still different, so a source-wide change converges over several runs and an unchanged source costs no writes.
Guard archival against a broken or truncated source: if the source suddenly has far fewer items than you already own, skip archiving and report it. Archived articles can be restored from their version history.
The MCP tools `create_article`, `update_article`, `list_articles` and `get_article` accept and return the same `externalId` and `contentHash`. To change part of an article through MCP or Copilot, read it with `get_article` and pass `contentEdits` with its `contentRevision` to `update_article`; see [Targeted code and instruction edits](/docs/developers/targeted-edits).
# System prompt
The system prompt is the full set of instructions your AI agent reads before every reply. It is a fixed sequence of sections that say who the AI agent is, how it behaves and what it knows about the conversation. Reading it explains why the AI agent behaves the way it does, and which setting to change. **Settings -> Automation -> System Prompt** lists every section in order and shows where each one comes from.
Most sections come from other settings or are built in. The sections you can edit here start from tuned defaults and rarely need changing. Try the [writing style](/docs/ai-agent/writing-style), [bot rules](/docs/ai-agent/bot-rules) and [workflows](/docs/ai-agent/workflows) first.
For how the AI agent uses its prompt and tools, see [How the AI agent works](/docs/ai-agent/how-it-works).
***
The sections, in order [#the-sections-in-order]
| # | Section | Comes from |
| -- | ------------------------ | ---------------------------------------------------------------------------------------------- |
| 1 | Task | Edited here |
| 2 | Time & Channel | Built in: conversation start, current time and the customer's channel |
| 3 | Safety | Edited here |
| 4 | Internal confidentiality | Built in |
| 5 | Instruction following | Edited here |
| 6 | Tool calling | Edited here |
| 7 | Customer attachments | Built in: how to read images and files |
| 8 | How to write | [Writing style](/docs/ai-agent/writing-style), plus output syntax edited here |
| 9 | Business description | Edited here |
| 10 | Additional rules | [Bot rules](/docs/ai-agent/bot-rules) |
| 11 | Workflows | [Workflows](/docs/ai-agent/workflows) |
| 12 | Articles | [Knowledge base](/docs/ai-agent/knowledge-base) |
| 13 | Handoff | [Handoff settings](/docs/help-desk/handoff), when the AI agent keeps answering after a handoff |
| 14 | Social media page | Built in, for Messenger and Instagram DMs |
| 15 | Customer Email | Built in, when known |
| 16 | Previous conversations | Built in, in email conversations with a known customer |
| 17 | Customer Phone | Built in, when known |
| 18 | Browser History | Built in, for Octocom web chat |
| 19 | Recently viewed products | Built in, for Octocom web chat when product sync is set up |
| 20 | Products | Built in, from the synced catalog |
| 21 | Custom instructions | Your [Python prompt section](/docs/developers/prompt-sections) |
Sections with nothing to say for a conversation are left out. For example, Additional rules is missing when the business has no bot rules for the customer's channel.
***
The sections you can edit here [#the-sections-you-can-edit-here]
Each one shows **Default** or **Customized**. **Your text replaces the default; it doesn't add to it.** For Safety and Instruction following that means you are now responsible for the guardrails the default provided, so carry over what you still need. **Reset to default** brings the default back.
Task [#task]
Who the AI agent is: a customer service agent for your business, and how it answers whether it is an AI. The default names your business, or leaves it unnamed when the business is anonymized. Your own text does neither, so only replace it when you need to rewrite that foundation.
Safety [#safety]
The guardrails it always keeps: staying on topic and not making commitments the business hasn't approved.
Instruction following [#instruction-following]
Which sources of truth win, for example that workflow instructions outrank articles.
Tool calling [#tool-calling]
How and when the AI agent uses tools. The default adapts to your live workflows on the customer's channel (embedded or loaded on demand) and is left out when there are none. Your own text is used on every channel and replaces that adaptation, so a bad override can stop the AI agent from calling tools correctly.
Output syntax [#output-syntax]
The formatting rules for replies: markdown, no raw HTML, no tables. Web chats that show widget elements also get the chat window rules, which win where the two disagree. Change it only when your channel has specific rendering limits.
Business description [#business-description]
A short overview of your company, as context for every reply. It's empty by default and left out until you write one. Keep it an overview: the AI agent searches your catalog and knowledge base on demand, so a product list here only makes every prompt longer.
Custom instructions (Python) [#custom-instructions-python]
Python you write once per business. It runs before every reply on the channels you choose (once at the start of an inbound phone call) and adds its result as the last section. Editing it needs permission to edit automations. See [Custom system prompt sections](/docs/developers/prompt-sections).
***
See the prompt behind a reply [#see-the-prompt-behind-a-reply]
The settings show how the prompt is built for a business. To see the exact prompt a reply used, with every section filled in for that conversation, ask Copilot to show the system prompt of that message (`get_response_system_prompt`).
***
Managing [#managing]
* **In the dashboard:** Settings -> Automation -> System Prompt.
* **With Copilot or MCP:** `get_system_prompt` returns every section in order with its `source`, the text of the editable sections and `systemPromptSectionCode`. `update_system_prompt` patches them: send a text to override a section, `null` to reset it, or leave it out to keep it. Code supports [targeted edits](/docs/developers/targeted-edits).
* **With the REST API:** `GET` and `PATCH /rest/v1/system-prompt`, with the same fields. Sending `systemPromptSectionCode` needs the `automations:write` scope, and responses include it only for keys with `automations:read`.
| Field | Section |
| ------------------------- | ---------------------------- |
| `task` | Task |
| `safety` | Safety |
| `instructionFollowing` | Instruction following |
| `toolCalling` | Tool calling |
| `outputSyntax` | How to write: output syntax |
| `businessDescription` | Business description |
| `systemPromptSectionCode` | Custom instructions (Python) |
Reads return the text the AI agent uses, and `customizedFields` lists the sections your business set. Every change is recorded in the configuration history.
# Test your AI agent
Testing shows you how the AI agent handles real requests before your customers see it. Test before you launch, and again after every change to knowledge, rules, workflows or actions. A change that fixes one case can affect a similar one, so rerun the scenarios that matter most each time.
What you can do [#what-you-can-do]
* **Chat with the AI agent** in the playground, exactly as a customer would on web chat.
* **Run whole sets of scenarios** through Copilot or your own AI agent, on web chat, email and phone calls.
* **Test each action and piece of code** on its own, with inputs you choose.
* **See why it replied** the way it did, down to every search and action.
* **Check replies against your rules** with Bot QA, before and after launch.
* **Compare versions and roll back** when a change makes things worse.
Test conversations are marked as tests and kept out of your reports, but the
AI agent's actions run for real. If a workflow can issue a refund, cancel a
subscription or update a record in another system, testing that path does it.
Use test accounts or test records for those paths, or test the action on its
own first.
Set it up [#set-it-up]
Ask Copilot or your own AI agent to run your scenarios and report back:
Run test conversations for our refund workflow: a customer inside the refund
window, one outside it, one we can't identify, and one who asks for a person.
Use web chat for the first three and email for the last. Summarize which ones
went wrong and why.
After a change, rerun the same set:
We changed the cancellation workflow. Rerun the cancellation scenarios from
the last test run on email, and tell me which replies changed and whether they
got better.
To chat with the AI agent yourself, open the **Bot Playground** from the navigation bar.
A testing routine that works [#a-testing-routine-that-works]
Write down the scenarios [#write-down-the-scenarios]
List the requests your customers actually send, with what a correct outcome looks like for each: the answer, the action, or a handoff to your team. Include edge cases: missing details, a request your policy refuses, a customer who changes their mind, and someone who asks for a person straight away.
Chat with the agent in the playground [#chat-with-the-agent-in-the-playground]
Try the most common scenarios yourself in the [playground](#chat-with-the-ai-agent-in-the-playground). Check the answers, and open the conversation in the help desk to see which actions ran.
Run the full set with Copilot [#run-the-full-set-with-copilot]
Ask [Copilot](#run-test-conversations-with-copilot-or-mcp) to run every scenario as a test conversation and summarize what failed. Fix the cause, then run the set again.
Test each action and piece of code [#test-each-action-and-piece-of-code]
Run every action, condition provider and event handler on its own with realistic inputs, including inputs that should fail. See [Test actions and code on their own](#test-actions-and-code-on-their-own).
Add Bot QA checks [#add-bot-qa-checks]
Write [Bot QA](/docs/ai-agent/bot-qa) checks for the mistakes that would hurt most, test them on known good and bad replies, then turn them on. They keep checking every reply after launch.
Review real conversations after launch [#review-real-conversations-after-launch]
Read a sample of real conversations in the first days, especially handoffs and Bot QA findings. Turn each problem you find into a fix and a new test scenario.
For extra assurance before a launch, Octocom's solution engineers can review your configuration and test plan with you.
Chat with the AI agent in the playground [#chat-with-the-ai-agent-in-the-playground]
The **Bot Playground** lets you chat with the AI agent exactly as a customer would on web chat. Open it from the navigation bar, or from **Settings -> Automation -> Bot Playground**.
* **Pick the business.** If your organization has several businesses, choose one next to **Previewing**.
* **Always available.** The playground ignores your web chat support hours, so you can test at any time.
* **Copy the conversation ID.** The ID under the chat identifies the test conversation. Use it to test an action or Bot QA check against this conversation, or give it to Copilot to inspect. The conversation also appears in the help desk with a **Playground** tag.
* **Share it.** **Share link** copies a link anyone can open to chat with the AI agent, without logging in. Conversations from that link are test conversations too. Use it to let colleagues try the agent before launch.
* **Check the look.** **Appearance** opens the web chat settings, where you change how the widget looks.
See why the AI agent replied the way it did [#see-why-the-ai-agent-replied-the-way-it-did]
Open the test conversation in the help desk and select **Debug this message** (the bug icon) on any AI reply. It shows the system prompt the AI agent received, the actions it could use, each action it called with its arguments and result, and its reasoning when available. This is the fastest way to tell whether a wrong answer came from missing knowledge, the wrong workflow, or an action result.
Run test conversations with Copilot or MCP [#run-test-conversations-with-copilot-or-mcp]
Copilot and other AI agents connected through [Octocom MCP](/docs/developers/mcp) can hold test conversations with your AI agent, read every reply and the actions it took, and repeat the run after each change. This is how you test many scenarios quickly, and how you test email and phone calls, which the playground doesn't cover. See the example requests in [Set it up](#set-it-up).
These conversations appear in the help desk as **Agent playground**, separately from the **Human playground** conversations people start in the playground. Both carry a **Playground** tag in the conversation list.
The agent can recreate the customer's situation. In web chat, it sets the page they are on, their device and their country. On email, it sets the subject line and which inbox's signature the reply uses. On a phone test, it picks the line they called or tests an outbound campaign call. On every channel, it can set the customer's name, contact details and language, and add context a channel or integration would normally provide.
What runs and what doesn't [#what-runs-and-what-doesnt]
* **Runs as in production:** knowledge, bot rules, workflows, actions and their effects on external systems, handoffs (recorded on the test conversation).
* **Doesn't run:** delivery to a real customer, tickets in an external help desk, notifications to your team, event handlers and webhooks. Test conversations are also left out of analytics.
* **Not covered:** how real emails are received and threaded (test [email rules](/docs/channels/email/rules) with `test_email_rules`), and speech on phone calls (use a [test call](/docs/channels/voice/voice-ai-best-practices#test-before-going-live)).
**Limits:** 60 test conversations per hour per organization and 15 messages per conversation. A test conversation can be continued for seven days after its last message.
Test actions and code on their own [#test-actions-and-code-on-their-own]
Test each piece on its own before you test it inside a conversation. A focused test shows exactly what the code returns, so a failing conversation is easier to trace. Each test runs the code with inputs you choose.
| What you test | In the dashboard | Copilot and MCP |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | ------------------------- |
| [Python action](/docs/developers/custom-actions) | **Settings -> Automation -> Custom Actions**, open the action, **Test Action** | `test_python_action` |
| [API action](/docs/developers/custom-actions) | Same page, **Test Action** | `test_api_action` |
| [Condition provider](/docs/developers/condition-providers) | **Settings -> Automation -> Custom Conditions**, open the provider, **Test Provider** | `test_condition_provider` |
| [Event handler](/docs/developers/event-handlers) | **Settings -> Automation -> Event Handlers**, open the handler, **Test Handler** | `test_event_handler` |
| [Webhook](/docs/developers/webhooks) | **Settings -> Automation -> Event Handlers**, open the webhook, **Send test event** | `test_webhook` |
| [Recurring job](/docs/developers/recurring-jobs) | **Settings -> Automation -> Recurring Jobs**, **Test Job** (runs once now, not recorded in run history) | `test_recurring_job` |
| [Custom HTTP endpoint](/docs/developers/custom-http-endpoints) | **Settings -> Advanced -> HTTP Endpoints**, **Test request** | `test_http_endpoint` |
| [Sidebar widget](/docs/help-desk/sidebar-widgets) | **Settings -> Help Desk -> Sidebar Widgets**, **Test Widget** | `test_sidebar_widget` |
| [Phone line router](/docs/channels/voice/call-routing) | **Settings -> Voice & SMS -> Phone line routers**, **Run test** | `test_phone_line_router` |
| [Email rules](/docs/channels/email/rules) | **Settings -> Help Desk -> Email Rules**, **Run test** | `test_email_rules` |
| [Spam filter](/docs/channels/email/spam-filter) | **Settings -> Help Desk -> Spam Filter**, **Run test** | `test_spam_filter` |
| [Comment workflows](/docs/channels/social-media/comment-workflows) | **Settings -> Channels -> Comments**, **Test Comment** | `test_comment_workflow` |
| [Review workflows](/docs/channels/reviews/review-workflows) | **Settings -> Channels -> Reviews**, **Test a review** | `test_review_workflow` |
| [Data collection](/docs/analytics/data-collection) | Ask Copilot | `test_data_collection` |
A few things to know:
* **Add a conversation ID** to an action, condition provider, event handler or sidebar widget test to give the code a real conversation in `context["conversation"]`. A playground conversation works well.
* **Code tests run for real.** Testing an action, event handler, webhook, recurring job, HTTP endpoint or phone line router calls your external systems exactly as a live run would, so any writes happen. The email rules, spam filter, data collection, comment workflow and review workflow tests only preview the result: they send nothing and change no conversations.
* **A handoff has no effect in an action test.** [`hand_off_conversation`](/docs/developers/python-helpers/hand-off-conversation) only hands off when the AI agent runs the action in a conversation.
* **Test every path.** For a condition provider, use inputs that produce each condition, for example a customer who exists, one who doesn't, and one whose request was already handled. Check that each comes back as expected.
Check replies with Bot QA [#check-replies-with-bot-qa]
[Bot QA](/docs/ai-agent/bot-qa) checks the AI agent's replies against your quality rules, such as "never confirm a refund the actions didn't complete". During testing, use it two ways:
* **Test a check on a known reply.** In **Settings -> Automation -> Bot QA**, select **Test checks**, enter a conversation ID and pick a reply. Use replies that should fail and replies that should pass. Copilot and MCP use `test_bot_message_qa` and `test_bot_conversation_qa`. Tests store nothing and trigger no alerts.
* **Keep checking after launch.** Turn on reply checks with the **Record and continue** reaction first, review the findings, then switch the checks you trust to **Hand off to a person**.
Compare versions and roll back [#compare-versions-and-roll-back]
Octocom saves a version every time you change a workflow, action, condition provider, bot rule, article or other code, so you can see what changed between two test runs and go back if a change made things worse.
* **See what changed.** Select **View history** on a workflow, custom action, condition provider, bot rule or article to see each version and what it changed. Copilot and MCP use `list_workflow_versions` and `diff_workflow_versions` for a line-by-line diff of a workflow, and `list_configuration_changes` for every change made across your configuration, with who made it and any note on why. See [Change history and restore](/docs/developers/change-history).
* **Rerun the same scenarios.** After a change, run the same test conversations as before and compare the replies. Keep your scenario list so you can ask Copilot to rerun it after every change.
* **Roll back.** If the new version is worse, restore the previous one from **View history**, or with the matching restore tool, such as `restore_workflow_version` or `restore_action_version`.
* **Compare on live traffic.** To measure which version performs better with real customers, run an [A/B test](/docs/ai-agent/ab-testing).
Other ways to stay safe while you test [#other-ways-to-stay-safe-while-you-test]
* **Approve email replies first.** With [AI reply approval](/docs/ai-agent/ai-reply-approval), every AI email reply waits for an agent to approve it. Turn it on for your first days live if you want a person to read every reply. Test and playground conversations are never held for approval.
* **Keep test traffic out of your systems.** Webhooks skip playground conversations unless you turn on **Include playground conversations** in the webhook's filters. With an external help desk, playground handoffs create no ticket unless **Create Ticket for Playground Handoffs** is on in **Settings -> Help Desk -> Ticket Routing**. Event handlers don't run for Copilot and MCP tests, but they do run for conversations started in the playground. A handler that writes to another system can check whether the conversation is a test (see `isPlayground` and `testOrigin` in [Python context](/docs/developers/python-context#contextconversation)).
* **Talk to the voice AI.** Use **Test call** in **Settings -> Voice & SMS -> Voice agents** to talk to the voice AI from your browser, as a caller would. See [Voice AI best practices](/docs/channels/voice/voice-ai-best-practices#test-before-going-live).
For developers and AI agents [#for-developers-and-ai-agents]
Test conversation tools [#test-conversation-tools]
| Tool | What it does |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start_conversation` | Starts a test conversation with a first customer message, on web chat (`web`, the default), `email` or `phone-call`. Returns `conversationId` and `messageId`. |
| `send_message` | Sends the next customer message. Returns a `messageId`. |
| `get_response` | Waits for the AI agent's complete turn after a message and returns it. Call it before sending the next message. |
| `send_conversation_event` | Phone tests only. Sends something other than speech: `customer-silent` (the caller says nothing) or `max-call-time` (the call reaches its time limit). |
| `close_conversation` | Closes the test conversation. On a phone test, this is the caller hanging up. |
`get_response` returns the AI agent's messages in order (including product cards, quick replies and charts), the actions it called, and how the turn ended: `reply`, `silent`, `handed-off` or `closed`. Email replies include the rendered email (from, to, subject, text and HTML) with your signature. On phone tests it also reports how long the voice AI took to start answering.
To dig into a single reply, read the conversation with `get_conversation`, then pass a reply's message ID to `get_response_tool_calls` (actions, arguments, results and reasoning) or `get_response_system_prompt` (the full prompt the AI agent received).
Simulate the customer's situation [#simulate-the-customers-situation]
| Channel | Options |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Web chat | `browserSession` sets the current page, recently visited pages, browser, device and country, so you can test page-aware answers. `webChatConfigId` picks a web chat configuration. |
| Email | `customerEmail` is required. `subject` sets the subject line. `emailConfigId` picks which inbox's signature the preview uses. Test emails go through a hidden test inbox and are never sent. |
| Phone | `customerPhone` (the caller's number) is required. `phoneLineId` or `timeSlotId` choose which voice AI answers. `campaignId` tests an outbound campaign call, with you as the recipient. See [voice AI testing](/docs/channels/voice/voice-ai-best-practices#test-before-going-live). |
| All | `customerName`, `customerEmail` and `customerPhone` attach a customer. `language` sets the language. `metadata` (up to 20 keys) simulates context a channel or integration would normally provide. |
Required scopes [#required-scopes]
Starting and continuing test conversations needs the `conversations:write` scope, and reading replies needs `conversations:read`. Testing code needs `automations:write`: actions, condition providers, event handlers, webhooks, recurring jobs, HTTP endpoints, sidebar widgets and phone line routers.
# Website sources
Website sources are the web pages Octocom scrapes into a business's knowledge base. They let the AI agent answer from content you already publish, such as a help center, an FAQ or a documentation site. Each source is one URL, and removing a source also removes the knowledge scraped from it.
Add pages from the dashboard [#add-pages-from-the-dashboard]
Open **Settings -> Automation -> Knowledge -> Websites** and choose **Add a new website**. Add a single page, or a sitemap to pull in many pages at once. With a sitemap you can review the pages before syncing, exclude URLs and add pages the sitemap doesn't list. Copilot or your MCP agent can do the same, and can keep the list in sync with a feed of links. See [Keep website knowledge in sync with a feed](#keep-website-knowledge-in-sync-with-a-feed).
Scraped marketing pages tend to be long and vague, which makes for weaker search results than focused articles. Prefer help and policy pages, and see [Knowledge base](/docs/ai-agent/knowledge-base#writing-knowledge-the-ai-agent-can-find) for what makes content easy to find.
The rest of this page is a reference for developers and AI agents that manage website sources through MCP or the REST API.
Origin and status [#origin-and-status]
Every source has an `origin`:
| Origin | Meaning |
| --------- | ----------------------------------------------------------------------------------------------------------- |
| `manual` | Added one by one, from the dashboard, MCP, REST or a feed sync. Once scraped, it refreshes about once a day |
| `sitemap` | Belongs to a sitemap configured in the dashboard. Its weekly sitemap check adds, removes and rescrapes them |
And a `status`:
| Status | Meaning |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scraped` | The last scrape succeeded at `lastScrapedAt` |
| `not_scraped` | No scrape has succeeded yet. The page may still be in the queue, or fetching it failed (for example a 403, a 404 or a redirect loop). A page that has never scraped is not retried until you rescrape it |
URLs are stored exactly as given. `https://shop.example/a` and
`https://shop.example/a/` are two different sources. Only `http` and `https`
URLs are accepted.
MCP tools [#mcp-tools]
| Tool | Purpose |
| -------------------------- | -------------------------------------------------------------------------------------------- |
| `list_website_sources` | List sources by URL with origin and status. Pass `nextCursor` back as `cursor` to page |
| `add_website_sources` | Add up to 500 pages and queue a scrape for each new one. Existing URLs are not rescraped |
| `set_website_sources` | Make the manual sources exactly this list (up to 2,000) in one call; `dryRun: true` previews |
| `remove_website_sources` | Remove sources by `ids` and/or exact `urls`, with their scraped knowledge |
| `rescrape_website_sources` | Queue a fresh scrape of up to 100 existing sources |
REST operations [#rest-operations]
All paths below start with `/rest/v1` and require `X-API-Key`. Use the
[REST reference](https://api-docs.octocom.ai/) for complete schemas. Copilot and
MCP can discover these endpoints in the **Website Sources** group with
`list_rest_api_operations`.
| Method | Path | Purpose |
| ------ | ------------------------------------ | ----------------------------------------------------------------------- |
| GET | `/website-sources?businessSlug=shop` | List sources; optional `origin`, `limit` (up to 500) and `cursor` |
| POST | `/website-sources` | Add `{businessSlug, urls}`; returns `added` and `alreadyPresent` URLs |
| PUT | `/website-sources` | Set the exact manual list `{businessSlug, urls, dryRun?}` |
| POST | `/website-sources/remove` | Remove `{businessSlug, ids?, urls?}`; returns `removed` and `notFound` |
| POST | `/website-sources/rescrape` | Rescrape `{businessSlug, ids?, urls?}`; returns `queued` and `notFound` |
Sources are scoped to the API key's organization and the requested business.
IDs or URLs from another business are reported as `notFound` and never touched.
Archived businesses remain readable but reject changes with `409`, and their
pages are not refreshed.
Scrapes run in a shared, rate-limited queue. A `manual` page that fails during
its daily refresh keeps its last good content and is tried again a day later.
Add or rescrape only pages whose content you actually need refreshed.
Keep website knowledge in sync with a feed [#keep-website-knowledge-in-sync-with-a-feed]
The set operation (`PUT /website-sources` or `set_website_sources`) compares
the list you send with the business's current manual sources:
* URLs that are new are added and scraped.
* Manual sources missing from the list are removed, together with their
scraped knowledge.
* Everything else is left untouched and is **not** rescraped.
Sitemap sources are never added or removed by this call. A URL that already
exists as a sitemap source counts as present. An empty list is rejected, so a
failed feed download cannot wipe the knowledge base by accident.
A Python [recurring job](/docs/developers/recurring-jobs) can run
the sync daily with its injected `OCTOCOM_ORG_API_KEY` and
`OCTOCOM_API_BASE_URL`; no extra secret is needed. Fetch and validate the whole
feed first, and stop without changing anything when it looks wrong:
```python
import xml.etree.ElementTree as ET
import requests
FEED_URL = "https://shop.example/feeds/links.xml"
BUSINESS_SLUG = "shop"
def run_job(context):
response = requests.get(FEED_URL, timeout=30)
response.raise_for_status()
links = [el.text.strip() for el in ET.fromstring(response.content).iter("LINK") if el.text and el.text.strip()]
if not links:
raise RuntimeError("Feed returned no links; keeping the current sources")
result = requests.put(
f"{OCTOCOM_API_BASE_URL}/rest/v1/website-sources",
headers={"X-API-Key": OCTOCOM_ORG_API_KEY},
json={"businessSlug": BUSINESS_SLUG, "urls": links},
timeout=60,
)
result.raise_for_status()
diff = result.json()["data"]
return {"added": len(diff["added"]), "removed": len(diff["removed"]), "unchanged": diff["unchanged"]}
```
Run it once with `"dryRun": True` to check the difference before the first
real sync. A second run against an unchanged feed reports zero additions and
removals.
# Workflows
A workflow is a playbook the AI agent follows in a specific situation: a cancellation, a claim, a plan change, a damaged product. It says which details to collect, which [actions](/docs/ai-agent/actions) to call, how to handle each outcome and when to hand off. Workflows are where most of your AI agent's real work is defined.
What you can do [#what-you-can-do]
* **Follow your process step by step.** Collect the order number and email, check the order, then cancel it or explain the return process.
* **Act in your systems.** A workflow switches on the actions the AI agent may use in that situation, such as a refund or a plan change.
* **Adapt to live data.** Variants give different instructions depending on the state of an order, a subscription or a policy: shipped or not, active or paused, in force or lapsed.
* **Handle each channel its own way.** Run an invoice workflow on email only, or a call transfer workflow on phone calls only.
* **Draft first, restore any time.** A draft workflow is ignored until you switch it on, and every change keeps a version you can restore.
* **Compare approaches.** Split customers between two variants with an [A/B test](/docs/ai-agent/ab-testing).
Set it up [#set-it-up]
Create a workflow for subscription cancellations. Offer a one-month pause
first, cancel if the customer still wants to, and hand off if they mention a
billing dispute. Then run test conversations on web chat and email for each
path.
In the dashboard, go to **Settings -> Automation -> Workflows**. Run test conversations after every new or changed workflow. See [Test your AI agent](/docs/ai-agent/testing).
Workflows, articles and bot rules [#workflows-articles-and-bot-rules]
Each holds a different kind of instruction:
* **Articles** provide information the AI agent can look up, like an FAQ. See [Knowledge base](/docs/ai-agent/knowledge-base).
* **Bot rules** set a few short, always-on guidelines, like "never promise a delivery date". See [Bot rules](/docs/ai-agent/bot-rules).
* **Workflows** define step-by-step processes for specific situations, often with actions that connect to your systems.
> **Priority:** when workflow instructions and articles contradict each other, the AI agent follows the workflow. Keep bot rules free of scenario-specific steps so they don't conflict with your workflows.
When to use a workflow [#when-to-use-a-workflow]
Use a workflow when the AI agent needs to:
* Follow a defined process, such as "customer reports a damaged order" or "customer wants to report a claim"
* Trigger an action, such as cancelling an order, fetching tracking or account details, or processing a refund
* Make decisions based on data, such as checking an order's or account's status before responding
Don't use a workflow when:
* You only want to add information the AI agent can reference: use an **article**
* You need a short, always-on behavioral rule: use a **bot rule**
How the AI agent uses workflows [#how-the-ai-agent-uses-workflows]
A workflow reaches the AI agent in one of two ways:
* **Embedded workflows** are written into the system prompt in full, so their instructions and actions are available from the first message. They must have exactly one variant, no condition provider and no required conditions.
* **Non-embedded workflows** are listed in the system prompt by title and trigger only. The AI agent loads one with the built-in `getWorkflowInstructions` tool when the situation matches.
When the AI agent loads a non-embedded workflow:
1. It recognizes that the situation matches the workflow's trigger.
2. If the workflow has a **condition provider**, it runs to evaluate external state. Is the order shipped? Is the subscription active? Is the policy in force?
3. Octocom picks the first matching **variant** based on those conditions.
4. The AI agent follows that variant's instructions, calling **actions** as needed.
A loaded workflow stays available for the rest of the conversation. [How the AI agent works](/docs/ai-agent/how-it-works#workflows-and-where-tools-come-from) explains loading in more depth.
Most workflows are simple: one set of instructions and no condition provider. Add variants and a condition provider only when the same situation needs different handling depending on external state.
To embed a workflow, switch on **Embedded** in the workflow editor. Embed only short workflows that apply to almost any conversation, such as the two defaults below: every embedded workflow adds its full instructions to the prompt on every turn. Keep workflows non-embedded when they need variant selection or condition evaluation. A change that would break the embedded requirements is rejected without removing existing data.
Live and draft workflows [#live-and-draft-workflows]
The AI agent only uses **live** workflows. A draft workflow is ignored until you switch on **Live Flow**, so you can prepare and review a workflow before customers meet it.
Default workflows for a new business [#default-workflows-for-a-new-business]
New businesses start with two live, embedded workflows, available on every channel:
* **Escalation request** calls `transferConversation` when a customer asks for a human.
* **Other queries** searches available knowledge or product information, answers from verified results, and offers a human handoff when the request cannot be resolved. More specific workflows take precedence.
Both expose `transferConversation` immediately and require no integration. These defaults do not provide order or account lookups, cancellations, updates or subscription operations. Ask Copilot to configure those workflows and actions for your connected systems, then run test conversations for each one.
Structure of a workflow [#structure-of-a-workflow]
Create and edit workflows under **Settings -> Automation -> Workflows**. Each field below matches the workflow editor.
Title [#title]
**Flow Title**: a short, descriptive name anyone can understand at a glance.
* Order tracking
* Cancel order
* Damaged product
* Claim status
* Change mobile plan
* Invoice copy request
Avoid vague names like "Order issue" or "Customer request".
Trigger: "When should this flow be followed?" [#trigger-when-should-this-flow-be-followed]
Describe when the AI agent should use this workflow. Write it like directions to a teammate: short, plain and based on what the customer says or does.
* When a customer asks to cancel their order.
* When a customer reports receiving a damaged product.
* When a customer asks about the status of an insurance claim they already submitted.
* When a business customer asks for a copy of an invoice.
Keep it to a few sentences. Be specific, and avoid overlaps with other workflows. If two workflows could match the same message, say in each trigger which situations it covers and which belong to the other.
Available channels (optional) [#available-channels-optional]
**Available Channels** restricts the workflow to specific channels, such as web chat, email, WhatsApp, Instagram or phone calls. When the customer's current channel is not in the list, the workflow is hidden from the AI agent entirely.
Leave it empty, the default, to make the workflow available on every channel.
Use this when the same situation should be handled differently per channel, for example a "Request invoice" workflow that only runs on email, or a "Transfer to live agent" workflow for phone calls.
Actions (optional) [#actions-optional]
Actions let the AI agent do things, not only reply. They connect the workflow to your systems so the AI agent can fetch order or account details, process refunds, check stock or coverage, calculate shipping costs and more. See [Actions](/docs/ai-agent/actions) for what actions are and how they get built.
Choose the actions in **Available Actions**. Each variant has its own list. In the instructions, reference actions by name on the step where they should run. The AI agent sees custom actions by a camelCase name: an action saved as `lookup_order` is called `lookupOrder`.
Actions come in two main types: **API actions** for simple HTTP calls, and **Python actions** for anything that needs logic. See the technical reference in [Custom actions](/docs/developers/custom-actions).
Bot instructions [#bot-instructions]
**Bot Instructions** is the playbook the AI agent follows. Write it like directions to a teammate: short, explicit and step by step.
**How to write great instructions:**
* **Be linear.** Number each step. One action or decision per step.
* **Confirm first.** Collect the minimum details before acting, for example an email address and an order or policy number.
* **Name actions.** On the step where work happens, include the action name, for example `getOrderDetails`.
* **Handle branches.** Use clear if/else for common cases: found or not found, in or out of policy.
* **Ask before changing anything.** Before an action that cancels, refunds or changes something, summarize what will happen and act only after the customer confirms.
* **Close the loop.** Tell the customer what you did or what will happen next.
* **Fail safe.** If blocked or facing a policy exception, hand off with `transferConversation`. See [Human escalation](/docs/ai-agent/human-escalation).
Instructions are guidance to a language model, not code. When something must hold every time, such as an ownership check or a refund limit, enforce it in the action or a condition provider. See [How the AI agent works](/docs/ai-agent/how-it-works#what-the-ai-agent-cant-do-on-its-own).
Variants [#variants]
By default, a workflow has one variant: one set of instructions that always runs. That is enough for most cases.
Sometimes the same situation needs different handling depending on external state. For example, a "Cancel order" workflow might need different responses depending on whether:
* The order has already shipped
* The order was already refunded
* The payment went through a specific provider
Variants let you define several instruction sets within a non-embedded workflow. Each variant has a **Variant Title** and **Variant Conditions**: boolean flags that must all be true for that variant to be selected.
Variants are ordered by priority. Octocom checks them top to bottom and picks the first match. The last variant typically has no conditions and acts as the fallback.
**Example: Cancel subscription**
| Variant | Condition | What happens |
| ---------------------- | ---------------------- | ---------------------------------- |
| Subscription not found | `subscriptionNotFound` | Ask customer to double-check email |
| Already refunded | `isRefunded` | Inform customer, no further action |
| Default | *(none)* | Proceed with normal cancellation |
To power variants with real data, you need a **condition provider**: a script that evaluates external state and returns the boolean conditions used to pick a variant. See [Condition providers](/docs/developers/condition-providers).
Examples [#examples]
Simple: Escalation to a human [#simple-escalation-to-a-human]
A minimal workflow: no actions besides the handoff, no condition provider, only instructions.
* **Trigger:** Customer explicitly asks to speak to a person
* **Variants:** 1 (default)
* **Instructions:**
1. Collect the customer's email address
2. Ask for a brief summary of their issue
3. Call `transferConversation`
See [Human escalation](/docs/ai-agent/human-escalation).
Medium: Order tracking [#medium-order-tracking]
A workflow that calls an external API to fetch data.
* **Trigger:** Customer asks about their order status
* **Variants:** 1 (default)
* **Actions:** `getOrderDetails`
* **Instructions:**
1. Ask for the order ID, or the email if no ID is available
2. Call `getOrderDetails` with the order ID
3. Share the order status, items and tracking link
4. If no tracking info is available yet, explain that the order is being processed
5. If the order can't be found, ask the customer to double-check the ID
The same shape works for any status lookup: a claim's status at an insurer, a ticket in a B2B customer's account, or a SIM activation at a telecom. Swap the identifier and the action.
Advanced: Cancel order with retention [#advanced-cancel-order-with-retention]
A multi-variant workflow that adapts to the order's state.
* **Trigger:** Customer wants to cancel their order
* **Condition provider:** Checks order status through your API
* **Actions:** `cancelOrder`, `processPartialRefund`
* **Variants:**
| # | Variant | Condition | Instructions |
| - | ---------------- | --------------- | ------------------------------------------------------------------ |
| 0 | Order not found | `orderNotFound` | Ask customer to verify order ID |
| 1 | Already refunded | `isRefunded` | Inform customer the order has already been refunded |
| 2 | Already shipped | `isShipped` | Explain the order has shipped, suggest waiting or returning |
| 3 | Default | *(none)* | Confirm intent -> offer partial refund to retain -> cancel if firm |
For more worked patterns, such as discounts before cancelling, refunds with policy checks, B2B quotes and decisions from a supplier, see [Common patterns](/docs/developers/common-patterns).
Managing workflows [#managing-workflows]
* **In the dashboard:** **Settings -> Automation -> Workflows**. Each workflow keeps a version history you can restore from.
* **With Copilot or MCP:** `list_workflows`, `get_workflow`, `create_workflow`, `update_workflow`, `add_workflow_variant`, `update_workflow_variant`, `reorder_workflow_variants`, `delete_workflow_variant` and `archive_workflow`. For history, use `list_workflow_versions`, `get_workflow_version`, `diff_workflow_versions` and `restore_workflow_version`.
* **With the REST API:** `GET`, `POST`, `PATCH` and `DELETE /rest/v1/workflows`, plus versions and restore. See the [REST API](/docs/developers/rest-api).
For developers and AI agents [#for-developers-and-ai-agents]
Action names and loading arguments [#action-names-and-loading-arguments]
The AI agent calls a custom action by its camelCase tool name (`lookup_order` becomes `lookupOrder`). MCP `list_actions` / `get_action_details` and REST action responses include this identifier as `toolName`. Use `toolName` in workflow instructions. Workflow `actionNames` accept either the saved name or the tool name, including for embedded workflows. Non-embedded workflows make their actions available immediately after loading, within the same reply.
`list_actions` lists custom actions, including the editable order lookups a store connector installs, such as `getOrderDetailsByOrderId`. Built-in actions such as `transferConversation` are not listed there.
MCP and REST workflow reads include `loadingRequirements`, with the required Python condition-provider argument names and their source. These are arguments to `getWorkflowInstructions`, separate from custom action inputs. Workflows without a condition provider load without arguments. Order, account and subscription lookups belong in Python actions or condition providers; workflow loading does not perform a built-in lookup.
Workflows, providers and versions [#workflows-providers-and-versions]
`list_workflows` and `get_workflow` return the owning `businessId`, the attached `conditionProviderId` and its `conditionProviderName`. A null provider ID means no Python provider is attached, so only variants without required conditions can match.
Variant conditions always come from the attached Python provider: put condition logic in a Python condition provider, and share one provider across workflows that evaluate the same input (see [Condition providers](/docs/developers/condition-providers#sharing-one-provider-across-workflows-and-brands)).
Creating multi-variant workflows or adding variants through Copilot requires an attached Python provider. Check the provider relationship before changing a shared provider or diagnosing variant selection.
Workflow version listings, individual versions and version diffs include both `workflowId` and `businessId`, so results remain attributable when inspecting several businesses together. Use `get_workflow` for current configuration and version tools for historical configuration.
# Writing style
The writing style decides how your AI agent sounds: its tone, how it shapes chat and email replies, and which language it replies in. It makes the AI agent sound like your company, whether that is a playful consumer brand, a formal insurer or a direct B2B supplier. Find it under **Settings -> Automation -> Writing Style**.
Every field starts from Octocom's default, and the defaults work well for most businesses. The page shows **Default** or **Customized** next to each field, and **Reset to default** brings the default back.
> **Your text replaces the default for that field. It doesn't add to it.** When you write your own tone, it becomes the whole tone instruction. Carry over anything from the default you still want.
The writing style is one part of the AI agent's instructions. To see every part, in the order the AI agent reads them, open the [system prompt](/docs/ai-agent/system-prompt).
***
Tone [#tone]
The AI agent's voice on every channel: warm or formal, playful or neutral, and whether it uses emojis. The default is friendly and warm, with the occasional emoji. Describe the voice you want rather than writing example replies.
Writing style: chat and email [#writing-style-chat-and-email]
How replies are put together: length, structure and formatting habits. There are two styles:
* **Chat** applies to every channel except email: web chat, WhatsApp, Messenger, Instagram, SMS and so on. The default keeps messages short, without greetings or signatures.
* **Email** applies to email. The default opens with a greeting that uses the customer's name when known and closes with a signature for your support team.
Only one is used at a time, so customize the one for the channel you want to change.
Language [#language]
**Language and grammar** decides which language the AI agent replies in. By default it replies in the language of the customer's latest message, never guessing from their name or address, and writes it in the correct alphabet.
**Check the reply language** checks each reply before it is sent and corrects a reply written in the wrong language. It adds a little time to each reply, so turn it on when wrong-language replies are a real problem.
***
Where does it belong: writing style, bot rule or workflow? [#where-does-it-belong-writing-style-bot-rule-or-workflow]
| If you're setting... | Use... |
| ----------------------------------------------------------------------------- | ------------------------------------------------------- |
| The AI agent's **voice** on every conversation | The **writing style** (this page) |
| A discrete, always-on **guardrail** ("never promise specific delivery dates") | A **[bot rule](/docs/ai-agent/bot-rules)** |
| Behavior tied to a **specific scenario** | A **[workflow](/docs/ai-agent/workflows)** |
| A **fact** the AI agent looks up when relevant | The **[knowledge base](/docs/ai-agent/knowledge-base)** |
For example, *"be warm and concise"* belongs in the tone, not a bot rule. Voice instructions in bot rules use up scarce rule slots and split the AI agent's character across two places.
Tips [#tips]
* **Be explicit.** *"Keep paragraphs under about three sentences"* works better than *"write shorter"*.
* **It's guidance, not code.** The writing style strongly shapes replies, but it is an instruction to a language model. For anything that must hold every time, use [condition providers](/docs/developers/condition-providers) and [custom actions](/docs/developers/custom-actions).
* **For channel-specific behavior beyond voice**, use channel-scoped [bot rules](/docs/ai-agent/bot-rules).
***
Managing [#managing]
* **In the dashboard:** Settings -> Automation -> Writing Style.
* **With Copilot or MCP:** `get_writing_style` and `update_writing_style`. Send a text to override a field, `null` to reset it, or leave it out to keep it.
* **With the REST API:** `GET` and `PATCH /rest/v1/writing-style`, with the same fields.
| Field | What it sets |
| -------------------- | ----------------------------------------------- |
| `tone` | The voice on every channel |
| `chatWritingStyle` | How replies are written everywhere except email |
| `emailWritingStyle` | How email replies are written |
| `languageAndGrammar` | Which language the AI agent replies in |
| `checkReplyLanguage` | Whether each reply's language is checked first |
Reads return the text the AI agent uses, and `customizedFields` lists the fields your business set. Every change is recorded in the configuration history.
# Conversation topics
Conversation topics tell you what customers contact you about. You define a list of topics per business, such as order status, billing question or password reset, and Octocom tags each conversation with the ones that match.
Topics show where your volume comes from, which subjects the AI agent resolves on its own and which still need your team. That tells you where to improve knowledge, workflows or actions next.
How topics are assigned [#how-topics-are-assigned]
* **When:** the first time a conversation is handed off to your team or closed. A conversation is tagged once; later replies or reopening don't change its topics.
* **What:** the most relevant topic from your list. If the customer raised several subjects, the conversation gets several topics. If none fit, it gets **other**.
* **Which channels:** email, web chat, Messenger, Instagram messages, WhatsApp, SMS, Telegram, Whop and API conversations.
Topics you add apply to conversations tagged from then on. Conversations that already have topics keep them.
Set up your topics [#set-up-your-topics]
Topics are configured per business in **Settings -> Analytics & Insights -> Conversation Topics**.
1. Click **Add Topic**.
2. Enter one or more topics separated by commas, for example `Order status, Return request, Billing question`.
3. Click **Save**.
Octocom stores each topic in lowercase with hyphens, so `Order status` becomes `order-status`. A business starts with a list of common online retail and subscription topics, such as order status, return request and payment issues. Edit it to fit your business: remove the topics that don't apply and add the subjects your own customers raise, such as `claim-status` and `policy-change` for an insurer or `roaming-charges` and `sim-activation` for a telecom. At least one topic must remain.
Choose good topics [#choose-good-topics]
The topic name is the only guidance the classifier gets, so the list itself does the work:
* **Make names specific and self-explanatory.** `damaged-item-on-arrival` classifies more reliably than `issue`.
* **Keep topics distinct.** Overlapping topics such as `shipping` and `delivery-status` split the same conversations between them.
* **Match the decisions you want to make.** A topic is useful when its resolution rate or handoff volume would change what you do, for example adding an action for order changes.
* **Watch `other`.** If `other` grows, read a sample of those conversations and add the topics they reveal.
* **Keep the list focused.** A few dozen clear topics beat hundreds of near-duplicates.
Where topics appear [#where-topics-appear]
* **On the conversation:** the **Topics** section of the [conversation sidebar](/docs/help-desk/conversation-sidebar).
* **In the help desk:** the **Topics** filter in [views](/docs/help-desk/views), for queues such as all refund conversations.
* **In routing:** [assignment rules](/docs/help-desk/assignment#assignment-rules) can send conversations with a topic to a specific team or person. Topics are assigned before handed-off conversations are routed.
* **In Metrics:** the **AI performance** tab and the **Topics** filter on every built-in tab.
* **In reports and the API:** topics are available to [custom reports](/docs/analytics/reports), Copilot and the REST API's conversation data.
Read the topic charts [#read-the-topic-charts]
The **AI performance** tab on the **Metrics** page has two topic charts. See the [Metrics reference](/docs/analytics/metrics#ai-performance) for every chart on the tab.
Topics [#topics]
A treemap of your topics in the selected period.
| Element | Meaning |
| ---------- | ------------------------------------------------------------------------------------------- |
| Tile size | How many conversations had the topic. A conversation with several topics counts under each. |
| Tile color | The topic's resolution rate: lighter means more conversations resolved without a handoff. |
| Tile text | The conversation count and the resolution rate for the topic. |
Use it to find large topics with a low resolution rate. Those are where better knowledge, a [workflow](/docs/ai-agent/workflows) or an [action](/docs/ai-agent/actions) pays off most.
Handoff Topics [#handoff-topics]
The topics of handed-off conversations over time, as a bar chart or a **Breakdown**. It shows which subjects still need your team and whether a change you made is reducing handoffs.
Related [#related]
* [Sentiment analysis](/docs/analytics/sentiment-analysis): how customers feel, alongside what they ask about.
* [Data collection](/docs/analytics/data-collection): ask your own questions about every conversation, such as the cancellation reason.
* [Human escalation](/docs/ai-agent/human-escalation): what happens when the AI agent hands off.
# Data collection
Data collection answers your own questions about every conversation. Why did the customer cancel? Which product failed? Did the retention offer work? Did the AI agent handle the issue well? You write each question in plain language, and Octocom answers it for every conversation and stores the answer as structured data.
You can then filter, route and report on those answers like any other conversation field. Because the questions are yours, you can capture almost anything: product defects, purchasing power, security concerns and patterns you haven't thought of yet.
***
How to think about data collection [#how-to-think-about-data-collection]
Each data collection field is an AI prompt that runs against the full conversation the first time it is closed or handed off. You tell the AI what to look for, give it the possible values, and it classifies every conversation automatically.
For a one-off analysis of older conversations, ask Copilot or an AI agent to investigate the period and questions you care about.
A field is not limited to what the customer said: the AI can analyze the *entire* interaction, including how the bot responded. Some examples:
* **What happened:** What product issue did the customer report? What was the cancellation reason?
* **What the customer wanted:** Were they looking for a refund? A specific product category? A payment link?
* **How it was resolved:** Was the subscription saved? Did the bot offer the right solution? Did the customer accept it?
* **Who the customer is:** What language do they speak? What's their budget range? Are they a first-time buyer?
* **How the bot performed:** Did the bot offer partial refunds when it shouldn't have? Did it leak another customer's data?
Think of each field as a question you'd want answered about every conversation. Then let the AI answer it at scale.
***
Setting up data collection fields [#setting-up-data-collection-fields]
Create and manage data fields per business in **Settings -> Analytics & Insights -> Data Collection**. You can also ask Copilot to create, test and update fields for you:
Add a data collection field that records why customers cancel their
subscription: too expensive, not using it enough, product quality or other.
Test it on a few real cancellation conversations first.
Each field has these settings:
| Setting | What it does |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Name | How the field appears in analytics. Choose something clear and descriptive. |
| Prompt | Natural language instructions that tell the AI what to look for and how to classify it. See [writing good prompts](#writing-good-prompts) below. |
| Possible values | The specific values the AI can assign. Can be detailed categories, simple Yes/No, or anything in between. |
| Optional field | When enabled, the AI only assigns a value if it finds relevant information. *(Recommended for most fields, since many won't apply to every conversation.)* |
| Channels | The channels the field runs on. Leave it empty to run on every channel, including social media comments. |
To try a field before relying on it, ask Copilot to test it on example messages (`test_data_collection`); nothing is stored. Archiving a field stops it from classifying new conversations and keeps its definition, so Copilot can restore it later. The settings page can also export selected fields to a file and import them again, for example into another business.
***
How it works [#how-it-works]
The first time a conversation is closed or handed off, the AI:
1. Reviews the conversation transcript as it stands at that moment: every message exchanged so far (see [when classification runs](#when-classification-runs) for details on timing)
2. Evaluates each data collection field against the conversation
* Required fields are always classified
* Optional fields are only classified when the conversation contains relevant information
3. Assigns the most appropriate value for each field
4. Saves the results for reporting, filtering, and analysis
***
What the classifier sees, and what it doesn't [#what-the-classifier-sees-and-what-it-doesnt]
This is the single most important thing to understand, and the most common source of surprising results.
When a field runs, the AI receives exactly two things:
1. **The conversation transcript**: every message, each tagged as either `customer` or `agent`, with timestamps.
2. **Your prompt and possible values.**
That's it. The classifier does **not** see any of your bot's configuration. It has no knowledge of:
* Your workflows, bot rules, or instructions
* Your knowledge base or help articles
* Your refund / return / escalation policy
* Which actions or tools the bot was allowed to use
* *Why* the bot did what it did
**The prompt is the classifier's entire universe.** If a correct judgment depends on a policy, the classifier only knows that policy if you write it into the prompt.
Worked example: the "policy-blind" false negative [#worked-example-the-policy-blind-false-negative]
A business created a field:
> *"Classify the AI's answer quality as Excellent / Good / Poor / Incorrect-Risky…"*
A customer demanded a **full refund**. This business's actual policy is to offer a **partial refund (keep the item)** instead, and the bot did exactly that, correctly. The classifier marked the conversation **Poor**, because the customer asked for a full refund and the agent offered a partial refund instead.
The bot behaved **correctly by design**. But nobody told the classifier that partial-instead-of-full is the intended policy, so it judged the conversation against the customer's demand and flagged correct behavior as a failure.
The fix is always the same: **put the rule in the prompt:**
> *"Offering a partial refund instead of a full refund is correct company policy and must NOT be marked down. Only mark 'Poor' if the bot invented a policy, gave factually wrong information, or ignored the customer entirely."*
It cannot reliably tell the bot apart from a human agent [#it-cannot-reliably-tell-the-bot-apart-from-a-human-agent]
Every non-customer message, whether written by your AI bot or a human agent, is labeled `agent` in the transcript the classifier sees. A prompt like *"judge only the bot's messages, not the human agent's"* therefore can't be honored reliably: the classifier has no dependable way to tell them apart. If a conversation was also touched by a human, expect noise on any bot-only quality field.
***
Avoid vague "was it correct?" fields [#avoid-vague-was-it-correct-fields]
It's tempting to write one field that asks *"Did the bot follow the process correctly?"* or *"Was the answer correct?"*. These are the **least reliable** fields you can create, for two reasons:
1. **No ground truth.** As above, the classifier doesn't have your process or policy, so "correct" collapses into the model's own opinion. Across many conversations that reads as close to random.
2. **It's self-grading.** The same kind of AI that produced the bot's behavior is being asked to judge whether that behavior was right. If the bot's decision looked reasonable, the judge tends to bless it, even when it quietly broke a rule the judge can't see.
**Prefer specific, factual, observable questions**: things the classifier can answer straight from the transcript without knowing your policy:
* *"Did the bot offer a partial refund? Yes / No"*
* *"Did the bot escalate to a human when the customer threatened a chargeback? Yes / No"*
* *"Did the bot mention the 30-day return window? Yes / No"*
You then compare those facts against your policy yourself, in analytics, which is where the policy knowledge actually lives. Fine-grained fields take more work to set up, but they produce data you can trust.
***
When classification runs [#when-classification-runs]
A conversation is classified **once**, the first time it is either **closed** or **handed off to a human**, whichever happens first. Voice AI calls are classified after the call ends, from the call transcript. The result is stored, and that classification is not recomputed later:
* Editing a field's prompt only affects conversations classified **after** the change. It does not re-grade conversations that were already scored.
* Reopening a conversation, a reply added after a handoff, or closing it a second time does **not** trigger re-classification.
* Newly added fields take a short while to appear in analytics as conversations are indexed.
Because classification happens at that first close or handoff, the transcript the classifier reads reflects the conversation **as it stood at that moment**. When a conversation is handed off, this is typically the exchange between the customer and the bot up to the point of handoff. Keep this in mind when designing fields: they work best when they ask about the customer and the bot's handling, rather than about what happens later in the conversation.
***
Writing good prompts [#writing-good-prompts]
The prompt is the most important part of a data collection field. It tells the AI *what* to look for and *how* to decide between values. The AI is capable of following nuanced, multi-step logic, so don't be afraid to write detailed instructions.
Be specific about when to classify [#be-specific-about-when-to-classify]
The most common mistake is not telling the AI when to *skip* classification. If a field only applies to certain conversations, say so explicitly:
> *"This categorization should only be performed if the customer has requested a subscription cancellation. If no subscription cancellation was requested, output null."*
> *"If the customer is not reporting a technical issue, don't output a value."*
Without this guidance, the AI may force-fit a value to conversations where the field doesn't apply.
Tell the AI how to handle edge cases [#tell-the-ai-how-to-handle-edge-cases]
Good prompts anticipate ambiguity:
> *"If no reason was provided, output 'No reason provided'. If none of the cancellation reasons match, output 'Other'."*
> *"If the concern does not match any known values, classify as 'Others'. If the conversation is not product-related, leave blank."*
You can analyze the bot's behavior, not just customer messages [#you-can-analyze-the-bots-behavior-not-just-customer-messages]
The AI reads the whole transcript, including the bot's own responses. This means you can use data collection to audit how the bot behaved, not only what the customer said:
> *"Return 'Yes' if the bot offered partial refunds, otherwise output 'No'."*
> *"If the bot provided information about the wrong person and the customer complained about it, output 'Yes'. Otherwise, output 'No'."*
(See [when classification runs](#when-classification-runs) for how timing affects which messages are available to the classifier.)
Complex logic works [#complex-logic-works]
The AI can follow multi-step reasoning. You can combine multiple conditions into a single field:
> *"Q1: Did the customer ask for money back? Q2: Did the customer ask to cancel their subscription? Q3: What was the outcome? Classify as 'SS Saved' if subscription was retained, 'Refund Saved' if refund was avoided, or the appropriate combination. IMPORTANT: A subscription being cancelled is NOT a 'refund not saved'."*
***
Use case ideas [#use-case-ideas]
Concrete ways to learn more from the conversations you already have:
Product and service issues [#product-and-service-issues]
The most common use case: classify what went wrong so you can spot trends and fix root causes.
| Field name | What to track | Example values |
| ----------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Product issues | The specific defect or complaint the customer reports | Damaged, Defect, Missing Items, Not as Advertised, Wrong Size, Adverse Reaction, Others |
| Packaging issues | Whether the product arrived in poor condition | Broken seal, Damaged container, Missing parts, Leaks |
| Delivery problems | What went wrong with shipping | Delay, Lost shipment, Damaged on arrival |
Tailor the possible values to your own products and services. A knife brand tracks "Bent Blade, Blunt Blade, Broken Tip, Chipped Blade, Rust, Loose Handle." A telecom tracks "No Signal, Slow Data, Billing Error, Device Fault." An insurer tracks the claim type or the policy question asked. The more specific your values, the more actionable your data.
Cancellation and retention [#cancellation-and-retention]
Understand why customers leave, and whether your retention efforts work.
| Field name | What to track | Example values |
| -------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Cancellation reason | Why the customer wants to cancel their subscription | Too expensive, Not using the service, Didn't meet expectations, Technical issues, Personal reasons, No reason provided |
| Cancellation outcome | Whether the customer was retained | Cancelled, Paused, Customer changed their mind |
| Retention outcome | Whether a refund or subscription cancellation was prevented | Subscription Saved, Subscription Not Saved, Refund Saved, Refund Not Saved |
| Return reason | Why the customer is returning a product | Allergic reaction, Bad quality, Better alternative, Damaged, Financial reasons, No results, Too much product |
Customer insights [#customer-insights]
Learn about who your customers are and what they want.
| Field name | What to track | Example values |
| --------------------- | ------------------------------------------------ | -------------------------------------------------------------- |
| Language | What language the customer communicates in | English, Spanish, French, German, Portuguese, Italian |
| Purchasing power | The customer's stated budget range | Under $10k, $10k-$20k, $20k-$40k, $40k+ |
| Product interest | What type of product the customer is looking for | Computers, Individual components, Protein powder, Multivitamin |
| Customer satisfaction | How the customer felt after receiving advice | Very satisfied, Neutral, Not satisfied |
Bot quality and behavior [#bot-quality-and-behavior]
Monitor how the **bot** performs, without manual QA.
| Field name | What to track | Example values |
| ------------------------ | -------------------------------------------------- | ------------------------------------------------------------------ |
| Bot behavior audit | Whether the bot did something it shouldn't have | Offered partial refund, Leaked customer data, Behaved correctly |
| Troubleshooting outcome | Which step resolved the customer's technical issue | Restart device, Factory reset, APN change, Not resolved |
| Technical issue solution | What solution the bot proposed | No data left, Device is defective, Restore network settings, Other |
Payment and order status [#payment-and-order-status]
Track operational patterns in how customers interact with orders.
| Field name | What to track | Example values |
| ------------------------ | -------------------------------------------------------- | ---------------------------------------------------------- |
| Payment issues | Whether the customer had trouble paying | Payment problem, No problem |
| Order status | Current state of the customer's order | In preparation, In transit, Delivered, Returned, Cancelled |
| Package opened on return | Whether the customer opened the package before returning | Yes, No |
| Payment method provided | Whether the customer shared bank details | Yes, No |
Security and compliance [#security-and-compliance]
Catch concerning behavior automatically.
| Field name | What to track | Example values |
| ---------------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Bad intent detection | Whether the customer is trying to exploit the bot | Attempting to steal information, Trying to break security |
| Off-topic response detection | Whether the bot replied to questions unrelated to your business or support | Yes, No |
| Refund threat tracking | What leverage the customer used to demand a refund | Dispute/Chargeback, Scam accusation, Report to authorities, Bad review |
***
Where collected data appears [#where-collected-data-appears]
Collected values show up wherever you work with conversations:
* **On the conversation:** each value appears in the [conversation sidebar](/docs/help-desk/conversation-sidebar).
* **In the help desk:** the **Collected data** filter in [views](/docs/help-desk/views) finds every conversation with a given value, for example every conversation where the cancellation reason is Too expensive.
* **In routing:** [assignment rules](/docs/help-desk/assignment#assignment-rules) can route on a collected value.
* **In Metrics:** the **Data Collection** filter narrows every built-in chart, and the **Custom data** tab (hidden by default, shown through **Manage reports**) breaks down the values of each field.
* **In reports:** ask Copilot for a [custom report](/docs/analytics/reports) to compare trends by channel, product or period, spot rising issues early (for example "packaging leaks" spiking this month) or combine fields (cancellation reason *and* retention outcome).
* **In a third-party help desk:** when conversations are handed off to a [connected help desk](/docs/help-desk/third-party-help-desk), collected values are added to the ticket as tags such as `octocom:cancellation-reason:too-expensive`.
This turns raw conversations into clear, structured data you can use to improve products, operations, and customer experience.
For developers: Python actions and event handlers can store a value directly with [`set_data_collection_result`](/docs/developers/python-helpers/set-data-collection-result), and report charts can use the toolbar's **Data Collection** filter (see [Analytics SQL](/docs/developers/analytics-sql#toolbar-filters)).
***
Examples [#examples]
# Analytics overview
Octocom measures every conversation on every channel, whether the AI agent or your team handled it. You see how much the AI agent resolves on its own, how fast your team responds, how customers feel and why they get in touch.
When a number moves, ask Copilot or your own AI agent why. You can also open the conversations behind a chart, or set an alert for the next time it happens.
Show me why customers were handed off last week, grouped by reason, and
compare it with the week before.
Ask your data a question [#ask-your-data-a-question]
Copilot and your own AI agent, connected through [Octocom MCP](/docs/developers/mcp), can query your analytics data directly. They read the numbers, look at the conversations behind them and explain what they found. Copilot can also draw a chart in the chat and save a useful analysis as a report.
Good questions name the period and what you want to see:
Which products are mentioned most in conversations tagged damaged-items this
month?
Export last quarter's CSAT by team and channel as a CSV.
Built-in metrics [#built-in-metrics]
The **Metrics** page opens with ready-made tabs for the questions every support team asks. One toolbar sets the period, the timezone and filters such as business, channel, tag, team or topic. Many charts export as CSV.
| Question | Where to look |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| How many conversations do we get, and how many does the AI agent resolve? | **Metrics -> Overview** ([details](/docs/analytics/metrics#overview)) |
| Which topics lead to handoffs? Which actions and workflows run? | **Metrics -> AI performance** ([details](/docs/analytics/metrics#ai-performance)) |
| How fast does my team reply and close? | **Metrics -> Team performance** ([details](/docs/analytics/metrics#team-performance)) |
| Are customers satisfied? | **Metrics -> Customer experience** ([details](/docs/analytics/metrics#customer-experience)) |
| How much revenue follows a chat? | **Metrics -> Sales** ([details](/docs/analytics/metrics#sales)) |
| Are we meeting our response targets? | **Metrics -> SLA** ([details](/docs/analytics/metrics#sla)) |
| Something specific to our business, such as cancellation reasons by plan | A [custom report](/docs/analytics/reports), built by asking Copilot |
| A one-off question about last month | Ask Copilot or your own AI agent, as [above](#ask-your-data-a-question) |
Some tabs, such as **SLA** and **Team quality**, appear once you use the feature. Others, such as **Voice** and **Social comments**, are hidden until you show them from **...** -> **Manage reports**. The [Metrics reference](/docs/analytics/metrics) defines every number, for example what counts as resolved and when the first response clock starts.
Reports and charts [#reports-and-charts]
When the built-in tabs don't answer your question, build a report: your own tab on the Metrics page with the charts you choose. Describe it to Copilot, and it writes the queries, checks the numbers with you and saves the charts.
Build a shared report called Weekly support review with resolution rate by
channel, first response time by team and the ten topics with the most
handoffs.
Reports can be personal or shared with your organization. Shared reports can feed your own BI tool or spreadsheet through the REST API. See [Reports and charts](/docs/analytics/reports).
AI insights from every conversation [#ai-insights-from-every-conversation]
Octocom reads each conversation the first time it is handed off or closed, and records structured insights you can filter, route and report on:
* **[Conversation topics](/docs/analytics/conversation-topics)** record what the customer asked about, from your own topic list, such as order status or a billing question.
* **[Sentiment analysis](/docs/analytics/sentiment-analysis)** records how the customer felt, from strongly negative to strongly positive, and the main reason.
* **[Data collection](/docs/analytics/data-collection)** answers your own questions, such as why a customer cancelled, which product had a defect or whether a retention offer worked.
These values appear on the conversation, work as help desk view filters and [assignment rule](/docs/help-desk/assignment#assignment-rules) conditions, and feed the Metrics page and your reports.
Record whether customers who ask to cancel accept our retention offer. Test it
on a few of last week's cancellation conversations before you turn it on.
Alerts [#alerts]
A [metric alert](/docs/analytics/metric-alerts) watches a chart in a shared report. It fires when a value crosses a threshold or changes sharply, for example when damaged-item conversations grow 25% week over week. The alert decides when. Your own automation decides what happens next, such as posting to Slack or emailing a team lead.
Alert the CX team in Slack when any topic in the Topics report grows more than
25% week over week, as long as it had at least 20 conversations.
Copilot tests the rule on recent weeks before it creates the alert.
Who can see analytics [#who-can-see-analytics]
* **View metrics** lets someone open the Metrics page, see shared reports and create personal reports.
* **Edit shared reports** lets someone create, change and delete reports and alerts shared with the organization.
* **Export conversations** is also needed to write or change a chart's query, or to have Copilot or an MCP client query analytics data directly, because queries can read conversation content.
* **View human QA** is needed for the Team quality tab.
See [Roles and permissions](/docs/security/roles-and-permissions) for how permissions are assigned.
Explore [#explore]
For developers and AI agents [#for-developers-and-ai-agents]
* [Analytics SQL](/docs/developers/analytics-sql): the tables, template variables and filters behind report charts and `execute_index_sql`.
* [REST API: Metrics report data](/docs/developers/rest-api#metrics-report-data): pull shared report charts into other systems.
* [Event handlers](/docs/developers/event-handlers#reacting-to-metric-alerts) and [webhooks](/docs/developers/webhooks): react to metric alerts.
# Metric alerts
A metric alert watches one saved chart and notices when something changes: a topic doubles week over week, API failures pass 20 a day, a brand's refund requests jump. The alert decides **when**. What happens next is up to you: post to Slack, email a team lead, open a ticket or anything else Python can do. A [Python event handler](/docs/developers/event-handlers#reacting-to-metric-alerts) or a [webhook](/docs/developers/webhooks) listening to the `metric_alert` event does the work.
The easiest way to set one up is to ask Copilot:
Alert us in Slack when any topic in the Topics report grows more than 25% week
over week, as long as it had at least 20 conversations.
Copilot creates the chart if needed, tests the rule on recent weeks, creates the alert and writes the handler.
You can also create one in the dashboard: on a chart in a shared [report](/docs/analytics/reports), open the chart menu, choose **Alerts**, then **New alert**. Pick the value to watch, whether to watch each value of a column separately, the condition and the period, then click **Test on recent data** before **Create alert**. Once a chart has alerts, a bell next to its title shows how many and whether any are firing. Your own AI agent can do the same through [Octocom MCP](/docs/developers/mcp), and other systems through the [REST API](/docs/developers/rest-api#metric-alerts). The tools are listed [below](#for-developers-and-ai-agents).
***
How a check works [#how-a-check-works]
Each alert has a **period**: `hour`, `day`, `week` (Monday to Monday) or `month`, in the alert's **timezone**.
1. When a period closes, the alert waits **`delayMinutes`** (default 60) so late classification and indexing land.
2. It runs the chart for that period: `{{from}}` and `{{to}}` are the period's start and end, and `{{bucket}}` is the period. Change conditions also run the period before, as the baseline.
3. It reads **`valueColumn`** from the result. With **`splitBy`**, each value of that column (each topic, channel or brand) is its own series. Without it, the whole result is one series. Rows that share a series are summed, so a chart with daily rows still yields a weekly total.
4. It compares each series with the condition and with what was firing after the previous check.
5. If any series **started** or **stopped** meeting the condition, it publishes one `metric_alert` event listing those series. A series that keeps firing is not repeated, so a handler hears about a problem once and again when it clears.
A new alert checks for the first time after the current period closes. `businessIds` limits the chart to some businesses; empty means every business.
Conditions [#conditions]
| Type | Fires while | Fields |
| ------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `threshold` | The value is above (`>`) or below (`<`) a number | `operator` (`above`, `below`), `value` |
| `change` | The value moved by at least `percent` and/or `absolute` vs the previous period (both if both set) | `direction` (`increase`, `decrease`, `either`), `percent`, `absolute`, `minBaseline` |
| `every_check` | Always. Every check publishes every series with its value and previous-period baseline | none |
* A series missing from one period counts as 0 there, which suits counts.
* A `percent` change is never met when the previous period was 0. Use `absolute` to catch something new.
* `minBaseline` ignores series whose previous period was below it.
* `every_check` keeps no state. Use it when Python should decide, for example an anomaly check against your own history kept in the [organization store](/docs/developers/organization-store).
Choosing rules that stay quiet [#choosing-rules-that-stay-quiet]
An alert is only useful if people act on it. A flat "+10% week over week" rule fires constantly: on one ordinary week of a large account it matched 229 of 613 brand-and-topic series, mostly small numbers moving by chance.
* **Set a floor.** Combine `percent` with `absolute` and a `minBaseline`, such as +25% and +10 conversations from at least 20. In the same week that cut 229 matches to 53.
* **Alert on shares when volume moves.** During a sale every count grows. A chart column like "damaged-item conversations as a share of all conversations" only rises when the problem does.
* **Use thresholds for rare, serious things.** Legal threats, adverse reactions or devices overheating: `threshold` `above` `0` on a daily period.
* **Test before saving.** `test_metric_alert` (or `POST /rest/v1/metric-alerts/test`) replays a rule over up to 12 recent periods and shows each check that would publish. Tune until it fires only when someone should act.
The event [#the-event]
Handlers read `context["args"]["metric_alert"]`. Webhooks receive the same object under `args.metric_alert`. Both have no conversation.
| Field | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `alert_id` | The alert |
| `alert_name` | Its name |
| `chart` | `id`, `title`, `report_id` and `url` (opens the report on the Metrics page) |
| `value_column` | The column watched |
| `split_by` | The split column, or `None` |
| `condition` | The condition, with snake\_case keys (`min_baseline`) |
| `period` | `unit`, `timezone`, `start`, `end`, and `previous_start`/`previous_end` for the baseline (`None` for thresholds) |
| `business_ids` | Businesses the chart ran over; empty means all |
| `checked_at` | When the check ran |
| `firing_count` | Series firing after this check, including ones that were already firing |
| `series_total` | How many series this event covers. `series` holds at most 500 of them |
| `series` | The series that changed state (every series for `every_check`), each with `key`, `value`, `baseline`, `change_abs`, `change_pct` and `state` (`firing`, `resolved` or `checked`) |
`key` is the split value, or `None` without a split. `change_pct` is `None` when the baseline is 0.
```json
{
"alert_id": "6f1c…",
"alert_name": "Topic spikes",
"chart": {
"id": "…",
"title": "Conversations by topic",
"report_id": "…",
"url": "https://app.octocom.ai/organization/acme/metrics?report=…"
},
"value_column": "conversations",
"split_by": "topic",
"condition": {
"type": "change",
"direction": "increase",
"percent": 25,
"absolute": 10,
"min_baseline": 20
},
"period": {
"unit": "week",
"timezone": "Europe/Vilnius",
"start": "2026-11-08T22:00:00.000Z",
"end": "2026-11-15T22:00:00.000Z",
"previous_start": "2026-11-01T22:00:00.000Z",
"previous_end": "2026-11-08T22:00:00.000Z"
},
"business_ids": [],
"checked_at": "2026-11-15T23:03:12.000Z",
"firing_count": 1,
"series_total": 1,
"series": [
{
"key": "damaged-items",
"value": 412,
"baseline": 301,
"change_abs": 111,
"change_pct": 36.88,
"state": "firing"
}
]
}
```
Handlers scoped to every business receive every alert. A handler limited to specific businesses receives only alerts whose `businessIds` is exactly one of its businesses. For an alert over several businesses, the webhook's `business` field and Python's `context["business"]` name a business of your organization only so helpers work; read `business_ids` to see what the alert covered. See [Reacting to metric alerts](/docs/developers/event-handlers#reacting-to-metric-alerts) for a Slack example.
To try a handler without waiting for a real alert, pass `test_metric_alert`'s `eventArgs` to `test_event_handler` as `{"metric_alert": ...}`.
Status and history [#status-and-history]
Every alert reports a `status`:
| `state` | Meaning |
| ------------- | -------------------------------------------------------- |
| `not_checked` | No check has run yet |
| `ok` | Checked; nothing is firing |
| `firing` | At least one series meets the condition (`firingSeries`) |
| `error` | The last check failed; `lastError` says why |
| `inactive` | Switched off |
A failed check is retried after 15 minutes, up to three times per period, and a check that doesn't finish runs again 30 minutes later. After 10 failures in a row the alert switches itself off; switching it back on clears the error. Common causes are a renamed result column or chart SQL that times out.
Checks that published an event are kept for 90 days (`get_metric_alert`, `GET /rest/v1/metric-alerts/{alertId}/events`).
Changing what an alert watches (chart, columns, condition, period, timezone, delay or businesses) clears its firing state, so the next check reports from scratch. Renaming or switching it off does not.
Limits [#limits]
* Alerts watch charts in **shared** reports only. Personal reports stay private.
* Up to 100 alerts per organization.
* Each check runs the chart once, plus once for a change baseline, with a 20-second limit per query. Checks run in the background, a few at a time, so a slow chart delays only its own alerts. Keep alert charts aggregated to the period, like any [report chart](/docs/developers/analytics-sql).
* Viewing and testing alerts needs the **View metrics** permission (`metrics:read`). Creating, changing and deleting them needs **Edit shared reports** (`reports:write`).
For developers and AI agents [#for-developers-and-ai-agents]
* MCP tools: `list_metric_alerts`, `get_metric_alert`, `create_metric_alert`, `update_metric_alert`, `delete_metric_alert` and `test_metric_alert`.
* [REST API: Metric alerts](/docs/developers/rest-api#metric-alerts) for the same operations from other systems.
* [Event handlers](/docs/developers/event-handlers#reacting-to-metric-alerts) and [webhooks](/docs/developers/webhooks) to act on the `metric_alert` event.
# Metrics reference
The **Metrics** page shows how your AI agent, your team and your channels perform. This page defines every built-in tab and chart exactly as Octocom calculates it, so you know what a number means before you act on it. Your own [custom reports](/docs/analytics/reports) appear after the built-in tabs.
How the Metrics page works [#how-the-metrics-page-works]
Period, timezone and filters [#period-timezone-and-filters]
One toolbar applies to every chart on the tab you are viewing:
* **Period**: Today, This week, This month, Last 2, 7, 14, 30 or 90 days, or a custom range.
* **Report timezone**: decides where each day starts and ends.
* **Add filter**: narrow every chart to conversations that match. Filters cover conversation status (handed off, open or closed, snoozed), businesses, email inboxes, channels, languages, assignees, teams, tags, [data collection](/docs/analytics/data-collection) values, topics, function calls, workflows and variants, senders, conversation type, priorities, handoff reasons and, for stores, order details such as status, amount, shipping method and destination.
Most charts place a conversation on the day it **started**. Charts about closing, such as **Resolved Tickets**, **CSAT surveys sent** and **Resolution within SLA**, place it on the day it was **closed**. Message and call charts use the time of the message or call.
Tabs, order and visibility [#tabs-order-and-visibility]
Some tabs appear only when you use the feature (for example **SLA** once SLA targets exist). **Voice**, **Social comments** and **Custom data** are hidden by default. Open the **...** menu next to the tabs and choose **Manage reports** to show, hide or reorder tabs, or **Hide from my tabs** to hide the one you are on. These choices apply only to you.
Exporting [#exporting]
Many built-in charts have an **Export CSV** button. To feed a number into another system on a schedule, rebuild it as a chart in a shared [report](/docs/analytics/reports) and fetch it over the [REST API](/docs/developers/rest-api#metrics-report-data). For a one-off export, ask Copilot.
Key definitions [#key-definitions]
These terms are used across the tabs.
| Term | Definition |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Handoff** | The conversation was passed from the AI agent to your team. See [Handed-off conversations](/docs/help-desk/handoff). |
| **Resolution rate** | The percentage of conversations that were **not** handed off to a human (100% minus the handoff rate). A conversation counts as resolved when it was never handed off, whether or not it has been closed yet. |
| **First response time** | For a handed-off conversation, the time from the handoff to the first reply from a human agent. When your team starts a Messenger conversation, the clock starts when the customer replies. |
| **Next response time** | After the first reply, the time from a customer's latest message to the agent reply that answers it. Each such reply is one measurement. |
| **Time to close** | For a handed-off conversation that is closed, the time from the handoff to the close. |
| **Ticket** | In **Team performance**, a handed-off conversation: the work your team handles. |
Resolution rate covers inbound customer conversations on email, web chat,
WhatsApp, Messenger, Instagram messages, Telegram, Whop, eBay, Amazon, SMS,
phone calls and the API. It leaves out social media comments, outbound
conversations, spam and other conversations not from a customer, and emails
that skip the AI agent by design (replies to threads started outside Octocom,
or emails an [email rule](/docs/channels/email/rules) hands straight to your
team). The headline number is calculated over the whole period, not averaged
across days.
Tabs at a glance [#tabs-at-a-glance]
| Tab | Shows | When it appears |
| ----------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------- |
| **Overview** | Conversation volume, resolution and channel mix | Always |
| **AI performance** | Topics, handoff topics, workflows and actions | Always |
| **Team performance** | Response times, workload and resolution by agent | Always |
| **Customer experience** | CSAT and, when enabled, sentiment | Always |
| **Sales** | Revenue and conversions linked to chats | Always |
| **SLA** | Compliance with your response and resolution targets | When a business has [SLA targets](/docs/help-desk/sla) |
| **Voice** | Calls, minutes, outcomes and voice workflows | Hidden by default |
| **Social comments** | Facebook, Instagram and TikTok comment handling | Hidden by default |
| **Virtual try-on** | Try-on usage | When [virtual try-on](/docs/commerce/virtual-tryon) is enabled |
| **AI quality** | [Bot QA](/docs/ai-agent/bot-qa) results | Always |
| **Team quality** | [Human QA](/docs/help-desk/human-qa) results | When a Human QA scorecard exists and you can view Human QA |
| **Custom data** | A breakdown of [data collection](/docs/analytics/data-collection) values | Hidden by default |
Overview [#overview]
| Chart | What it shows |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Conversations** | Conversations started each day. With several businesses, the bars are split by business; switch to **Breakdown** for each business's share. |
| **Resolution Rate** | The [resolution rate](#key-definitions) for conversations started each day, and for the whole period. |
| **Bot & Agent Messages** | Messages sent by the AI agent compared with messages sent by human agents. |
| **Bot Productivity** | The AI agent's share of all replies: AI agent messages divided by AI agent plus human agent messages. Outbound [campaign](/docs/channels/voice/campaigns) calls are left out. |
| **Channels Distribution** | Conversations per channel over time, or as a breakdown. A conversation that spans several channels counts once for each. |
AI performance [#ai-performance]
| Chart | What it shows |
| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Topics** | A treemap of [conversation topics](/docs/analytics/conversation-topics). Tile size is the number of conversations with that topic; the label and color show the topic's resolution rate. A conversation with several topics counts under each. |
| **Handoff Topics** | Topics of handed-off conversations, by the day the conversation started. Shows which subjects still need your team. |
| **Workflow Usage** | How many times the AI agent used each [workflow](/docs/ai-agent/workflows), grouped by workflow or by [A/B test variant](/docs/ai-agent/ab-testing). |
| **Function Calls** | How many times the AI agent called each function, such as your [actions](/docs/ai-agent/actions), by function name. |
| **Average Bot Messages per Conversation** | The average number of messages the AI agent sent per conversation, each day. |
Team performance [#team-performance]
Agents Performance Table [#agents-performance-table]
A row per agent, in two modes:
* **By Conversation** covers conversations **created** in the period: assigned, resolved and unresolved conversations, messages sent, average first response time, next response time, time to close, snooze time and messages per conversation.
* **By Activity** covers what each agent **did** in the period, whenever the conversation started: unique conversations replied to, written messages sent across channels (call transcripts excluded) and calls handled, each call counted once per agent.
Charts [#charts]
| Chart | What it shows |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| **Agent Messages by Hour** | Agent messages per hour of each day. |
| **Agent Productivity by Weekday** | Messages sent, tickets resolved, average first response time and average time to close, by day of the week. |
| **Average Daily First Response Time** | The average [first response time](#key-definitions) of handed-off conversations started each day. |
| **Average Daily First Response Time (Working Hours Only)** | The same, counting only time inside your organization's working hours. Shown when working hours are set. |
| **Average Daily Next Response Time** | The average [next response time](#key-definitions), per day. |
| **Average Time to Close** | The average [time to close](#key-definitions) of handed-off conversations started each day. |
| **Average Snooze Time** | How long conversations stay [snoozed](/docs/help-desk/snooze-options) before they are unsnoozed or closed. |
| **Agent Messages** | Messages sent by each agent over time. |
| **Customer Replies** | Replies from customers in handed-off conversations. |
| **Notes by Agent** | Internal [notes](/docs/help-desk/notes) agents added in handed-off conversations. |
| **Average Messages Per Day by Agent** | The average number of messages each agent sent per day. |
| **Resolved Tickets** | Handed-off conversations closed in the period, by the day they were closed. |
| **Reopened Tickets** | Handed-off conversations that were closed and then reopened, by the day they were reopened. |
| **Unresolved Tickets** | Handed-off conversations that are still open, by the day they started. |
The headline number on the response time and time to close charts is the average of the daily averages, so each day counts equally regardless of its volume.
Customer experience [#customer-experience]
Every CSAT chart has an **All / Bot / Human** toggle. **Bot** shows conversations the AI agent handled without a handoff; **Human** shows handed-off conversations. See [CSAT surveys](/docs/help-desk/csat) for how surveys are sent.
| Chart | What it shows |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Average CSAT** | The average rating from 1 to 5 for conversations started in the period. |
| **CSAT ratings per day** | How many 1, 2, 3, 4 and 5 ratings came in, by the day the rated conversation started. |
| **CSAT surveys sent** | Conversations that requested a rating, by the day they were closed. |
| **CSAT Response Rate** | Ratings received divided by surveys sent, by the day the conversation was closed. |
| **Customer Sentiment** | Conversations per [sentiment](/docs/analytics/sentiment-analysis) level, from Strongly Negative to Strongly Positive. Shown when sentiment analysis is on. |
| **Negative Sentiment Reasons** | Slightly and strongly negative conversations by sentiment reason. Filter to all negative, slightly negative or strongly negative. Shown when sentiment analysis is on. |
Sales [#sales]
The **Sales** tab links revenue to conversations. A purchase is attributed to chat when it happens within 7 days of a conversation in the same browser session. Connected Shopify stores record these purchases automatically (see [Shopify revenue tracking](/docs/integrations/shopify/chat-widget-tutorial#revenue-tracking)); any other store can send them from its checkout with [browser session purchases](/docs/commerce/browser-session-purchases). A business without its own purchase tracking can use [Google Analytics 4](/docs/commerce/google-analytics-4#connect-ga4-to-octocom) instead, which attributes any purchase by a visitor who ever chatted, so its totals run higher.
| Metric | What it shows |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| **Attributed Revenue** | Total revenue from orders placed by visitors who chatted. |
| **Conversion Lift** | How many times more likely visitors who chatted are to buy than visitors who didn't. |
| **AOV Uplift** | How much higher (or lower) the average order value is for chat-attributed purchases than for other purchases. |
| **Incremental Buyers** | Buyers beyond what you would expect if visitors who chatted converted at the same rate as everyone else. |
| **Daily Attributed Revenue** | Chat-attributed revenue per day. |
| **Conversion Funnel Comparison** | Conversion rates of visitors who chatted side by side with all other visitors. |
| **Daily Average Order Value** | Average order value per day, chat-attributed compared with other purchases. |
| **Attributed Sales** | Each attributed purchase, linked to the conversation that preceded it. |
SLA [#sla]
The **SLA** tab measures your [SLA targets](/docs/help-desk/sla). Each conversation is measured against the targets for its business and priority.
| Chart | What it shows |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| **First Response Compliant Tickets** | Handed-off conversations whose [first response time](#key-definitions) was within the first response target. |
| **First Response within SLA** | The same as a percentage of handed-off conversations that received a reply, by the day the conversation started. |
| **Response Compliant Tickets** | Agent replies after the first one that came within the next response target, measured from the customer's latest message. |
| **Response within SLA** | The same as a percentage of those replies. |
| **Resolution Compliant Tickets** | Closed conversations, handed off or not, whose time from creation to close was within the resolution target. |
| **Resolution within SLA** | The same as a percentage of conversations closed, by the day they were closed. |
Voice [#voice]
| Chart | What it shows |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| **Voice Conversations** | Phone conversations started each day, by business. |
| **Workflow Usage** | Workflows the voice AI used during calls, grouped by workflow or variant. |
| **Voice Resolution Rate** | The percentage of phone conversations that were not handed off to a human. |
| **Total Call Minutes** | Total length of all phone calls each day. |
| **Average Call Length** | Average call length in minutes each day. |
| **Outbound Calls** | Outbound calls placed each day, including [campaign](/docs/channels/voice/campaigns) calls. |
| **Missed Calls** | Inbound calls that no human agent joined. Calls the voice AI handled on its own count here too, so read it alongside **Voice Resolution Rate**. |
| **Declined Calls** | How many times an agent declined an incoming call. |
| **Voicemails** | Calls routed to voicemail. |
Test calls are left out of the call charts.
Social comments [#social-comments]
These charts cover public comments on Facebook, Instagram and TikTok. See [Comment workflows](/docs/channels/social-media/comment-workflows).
| Chart | What it shows |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Comments by Channel** | Comment conversations per day on Facebook, Instagram and TikTok. |
| **Bot Action Distribution** | What the AI agent did with each Facebook and Instagram comment: public reply, private message, hide, delete, hand off or no action. |
| **Bot Public Reply Rate** | The share of Facebook and Instagram comments that got a public reply from the AI agent. Private-message replies, hides, handoffs and no action count as not replied. Deleted comments and TikTok are left out. |
| **Bot Comment Workflows** | Which comment workflows matched Facebook and Instagram comments. |
| **Agent Replies** | Messages human agents sent on comment conversations each day. Every reply counts. |
| **Agent Handle Rate** | The share of comment conversations with at least one human agent message, whether or not the AI agent also replied. |
Virtual try-on [#virtual-try-on]
| Chart | What it shows |
| ------------------------------ | ------------------------------------------------------------- |
| **Virtual Try-on Generations** | Successful try-on images generated per day. |
| **Top Try-on Pages** | The product pages where customers generated the most try-ons. |
AI quality [#ai-quality]
Results from [Bot QA](/docs/ai-agent/bot-qa), which checks the AI agent's messages against your quality checks. Skipped evaluations are left out of every chart.
| Chart | What it shows |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Critical messages** | Messages with at least one critical violation, counted once per message, by the day the message was sent. |
| **Improvement breakdown** | For each check, how many messages it flagged as an improvement opportunity. |
| **Critical breakdown** | For each check, how many messages it flagged as critical. A message can appear under several checks. |
| **Messages with no QA flags** | Messages that passed every evaluated check. This measures rule compliance, not customer satisfaction or resolution. |
Team quality [#team-quality]
Results from [Human QA](/docs/help-desk/human-qa) scorecards that grade your human agents. With several scorecards, switch between them at the top of the tab. The tab opens with summary figures: evaluations, average score, pass rate, critical fails and flagged evaluations for the period.
| Chart | What it shows |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| **Average score by day** | The average score of evaluations, by the day the conversation was closed. |
| **Agents** | One evaluation per agent who replied in a graded conversation. Select an agent to see their checks and conversations. |
| **Checks** | How often each check was answered each way. Select a check or answer to list the matching conversations. |
| **Flagged conversations** | Evaluations with at least one flagged answer. Open one to read the conversation in full. |
Custom data [#custom-data]
A breakdown of the values each [data collection](/docs/analytics/data-collection) field recorded. For trends, comparisons or combinations of fields, build a [report](/docs/analytics/reports) instead; Copilot can chart any collected field.
Go further [#go-further]
* **[Reports and charts](/docs/analytics/reports)**: build your own tabs for the questions specific to your business.
* **[Metric alerts](/docs/analytics/metric-alerts)**: get notified when a number in a report crosses a line.
* **Ask Copilot**: *"Why did the resolution rate drop on Tuesday?"* Copilot reads the same data and can open the conversations behind a number.
* **[Analytics SQL](/docs/developers/analytics-sql)**: the tables behind these charts, for developers and AI agents.
# Reports and charts
A report is your own tab on the **Metrics** page, with the charts your business needs: weekly resolution rate by channel, first response time by team, handoffs by reason, refund requests by product. Describe what you want to see, and Copilot builds the report for you.
Each chart is a saved query over your analytics data, drawn as a line, bar, area or pie chart, a single KPI number or a table. Reports share the toolbar of the built-in tabs, so changing the period, businesses or filters updates every chart at once.
The built-in tabs are described in the [Metrics reference](/docs/analytics/metrics). Build a report when you need something they don't show.
Build a report with Copilot [#build-a-report-with-copilot]
The fastest way to a good report is to describe it to [Copilot](/docs/developers/copilot) in plain language:
Create a shared report called Weekly support review with resolution rate by
channel, first response time by team and the ten topics with the most
handoffs.
Other requests that work well:
* *"Add a chart to the Returns report showing return requests per product per week."*
* *"Make me a personal report comparing CSAT for AI-resolved and handed-off conversations by month."*
Copilot writes each query, runs it against your data to check the numbers and the speed, shows you a preview of the chart, then saves it. It can add a plain-language explanation of how the chart is calculated, which anyone can read behind the chart's help icon. If you ask for a report without saying who it is for, Copilot asks whether it should be personal or shared.
Your own AI agent can do the same through [Octocom MCP](/docs/developers/mcp), using the tools listed [below](#for-developers-and-ai-agents).
Build a report in the dashboard [#build-a-report-in-the-dashboard]
Create the report [#create-the-report]
On the **Metrics** page, click **+** (**Create report**) next to the tabs. Enter a **Report name** and choose who can see it: **Only you** or **Organization**.
Add a chart [#add-a-chart]
Click **Create first chart** (or **Add chart** once the report has charts). The chart editor opens.
Write and run the query [#write-and-run-the-query]
Write the query in SQL and click **Run** (Ctrl+Enter or Cmd+Enter) to preview the rows. **Available tables** lists the tables and columns you can use. The [Analytics SQL](/docs/developers/analytics-sql) reference explains the tables and how to connect a chart to the toolbar's period and filters.
Shape the chart [#shape-the-chart]
Set the **Title**, an optional **Description** shown under the title, the **Chart type** (Line, Bar, Area, Pie, KPI or Table) and the **Width on the report**. Pick the columns for the X axis and series, and the **Value format**: Number, Percent, Currency or Duration (seconds). Options include **Stacked bars** for bar charts, **Fill missing periods** and, for tables, **Clickable columns** that link cells to a conversation or a URL. Under **How it's calculated**, explain the calculation in plain language for your readers.
Save [#save]
Click **Save chart**. In a shared report, the chart updates for everyone in your organization.
Personal and shared reports [#personal-and-shared-reports]
| Report type | Who sees it | Who can change it |
| ---------------- | -------------------------------------------------- | ------------------------------------------------------------------------------- |
| **Only you** | Only you. A lock icon marks it in your tabs. | You |
| **Organization** | Everyone in your organization who can view metrics | People with the **Edit shared reports** permission. Changes apply for everyone. |
Only shared reports can be fetched over the REST API and watched by [metric alerts](/docs/analytics/metric-alerts).
Work with reports [#work-with-reports]
* **Filters and periods.** Reports use the same period, timezone and filters as the built-in tabs. A report also has a **Chart interval** (Daily, Weekly or Monthly) for its time series. A chart that doesn't use a selected filter says so with a **Not filtered by** note. Copilot can also add filters specific to one report, such as a product category or a plan.
* **Chart menu.** Each chart's menu offers **Refresh** and **Export CSV**, **Alerts** in shared reports, and **Edit**, **Width**, **Move earlier**, **Move later** and **Delete** for people who can edit the report.
* **Fresh data.** Results are kept for up to five minutes. **Refresh** runs the chart again.
* **Row limit.** A chart returns at most 1,000 rows. When it reaches the limit, the chart warns that the result may be incomplete: narrow the period or aggregate the query further.
* **Share a view.** The page link keeps the open report, period and filters, so you can send a colleague exactly what you are looking at. They need access to the report.
* **Arrange your tabs.** **...** -> **Manage reports** shows, hides and reorders built-in tabs and reports for you only. **Hide from my tabs** hides the current one without deleting it.
* **Rename or delete.** From the **...** menu, **Rename report** and **Delete report** (or **Delete for everyone** for a shared report). Deleting removes the report and all its charts permanently.
Get report data elsewhere [#get-report-data-elsewhere]
* **CSV.** Export any chart from its menu.
* **REST API.** Pull the rows of any chart in a shared report into a BI tool, data warehouse or spreadsheet on a schedule. See [Metrics report data](/docs/developers/rest-api#metrics-report-data).
* **Alerts.** A [metric alert](/docs/analytics/metric-alerts) watches a chart in a shared report and triggers your own automation when a value crosses a threshold or changes sharply.
Permissions [#permissions]
* **View metrics** opens the Metrics page and shared reports, and lets you create personal reports.
* **Edit shared reports** lets you create, change and delete shared reports and their alerts.
* **Export conversations** is required to write or change a chart's query, because a query can read conversation content.
If your organization uses [restricted inboxes](/docs/help-desk/restricted-inboxes), report charts that read conversation data only run in the dashboard for people who can see every restricted inbox.
For developers and AI agents [#for-developers-and-ai-agents]
Report charts are SQL over your organization's analytics tables. [Analytics SQL](/docs/developers/analytics-sql) documents the tables, the template variables that connect a chart to the toolbar (`{{from}}`, `{{to}}`, `{{business_ids}}`, `{{conversation_filters}}` and others), custom report filters and how to keep queries fast.
MCP tools for reports:
| Tool | Use |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `list_metric_reports` | List shared reports and your personal reports, with each chart's query and settings. |
| `preview_metric_query` | Run an unsaved query with toolbar parameters, bypassing the result cache. Use before saving. |
| `run_saved_metric_chart` | Run a saved chart and return its rows. |
| `create_metric_report`, `update_metric_report`, `delete_metric_report` | Create (shared, or personal with `personal: true`), rename or permanently delete a report. |
| `save_metric_chart`, `update_metric_chart`, `delete_metric_chart` | Add, change or delete a chart. |
| `reorder_metric_charts`, `reorder_metric_reports` | Set chart order within a report, or your own order of report tabs. |
| `get_metrics_layout`, `update_metrics_layout` | Read or change your tab order and hidden tabs, including built-in tabs. |
For one-off questions that don't need a saved chart, `execute_index_sql` runs a read-only query over the same tables.
# Sentiment analysis
Sentiment analysis tells you how customers feel. Octocom reads each conversation and records the customer's overall sentiment on a five-level scale, with the main reason behind it, such as product quality, delivery or price.
Use it to spot frustration early, route upset customers to experienced agents and see which parts of your business drive negative experiences.
Turn it on [#turn-it-on]
Open **Settings -> Analytics & Insights -> Sentiment Analysis** and switch on **Enable sentiment analysis**. The switch applies to every business in your organization. Sentiment reasons, described below, are set per business.
How conversations are scored [#how-conversations-are-scored]
Each conversation gets one of five levels:
| Level | Typical conversation |
| --------------------- | ---------------------------------------------- |
| **Strongly Positive** | Very satisfied, praising, excited |
| **Slightly Positive** | Generally satisfied, minor complaints resolved |
| **Neutral** | Informational questions, no clear sentiment |
| **Slightly Negative** | Minor complaints, some dissatisfaction |
| **Strongly Negative** | Very upset, angry, major issues |
The score reflects the customer's overall tone and how they felt by the end, including whether their issue was resolved. Every level except **Neutral** also gets a **reason** from your list. When no reason fits, the reason is **Other**.
* **When:** the first time a conversation is handed off to your team or closed. Voice AI calls are scored after the call ends, from the call transcript.
* **Which channels:** email, web chat, Messenger, Instagram messages, WhatsApp, SMS, Telegram, Whop, API conversations and voice AI calls.
* **Once per conversation:** a conversation keeps its score; later replies or reopening don't change it. Turning sentiment analysis on doesn't go back and score conversations that were already closed.
Sentiment reasons [#sentiment-reasons]
Reasons explain why a conversation was positive or negative. Each business starts with seven:
| Reason | Description |
| --------------------- | ----------------------------------------------------------- |
| **Customer Service** | Issues with service quality, response times, agent behavior |
| **Product** | Problems with product quality, features, or functionality |
| **Price/Value** | Concerns about product price, value, or pricing |
| **Shipping/Delivery** | Shipping delays, damaged packages, delivery issues |
| **Returns/Refunds** | Problems with return process, refunds, exchanges |
| **Payments/Checkout** | Billing issues, payment problems, checkout concerns |
| **Other** | Other issues not covered by the above categories |
Edit them to match your business. An insurer might use **Claims**, **Policy changes** and **Billing**; a software company **Bugs**, **Onboarding** and **Pricing**. With sentiment analysis on, the settings page lets you add, edit and delete reasons. Each reason has:
* **Name**: the category shown in reports.
* **Description** (optional): guidance that helps the AI decide when a conversation belongs to this reason. Write what is in and what is out.
* **Channels** (optional): limit the reason to conversations on specific channels. Leave empty to use it on every channel.
At least one reason must remain.
Where sentiment appears [#where-sentiment-appears]
* **On the conversation:** the **Sentiment Analysis** section of the [conversation sidebar](/docs/help-desk/conversation-sidebar) shows the level and reason.
* **In the help desk:** the **Sentiment** and **Sentiment reasons** filters in [views](/docs/help-desk/views), for example a queue of strongly negative conversations.
* **In routing:** [assignment rules](/docs/help-desk/assignment#assignment-rules) can match on sentiment, for example to send strongly negative conversations to senior agents. Sentiment is scored before handed-off conversations are routed.
* **In Metrics:** two charts on the **Customer experience** tab, below.
* **In reports and the API:** sentiment and its reason are available to [custom reports](/docs/analytics/reports), Copilot and the REST API's conversation data.
Read the sentiment charts [#read-the-sentiment-charts]
With sentiment analysis on, the **Customer experience** tab on the **Metrics** page shows two charts next to CSAT. See the [Metrics reference](/docs/analytics/metrics#customer-experience).
Customer Sentiment [#customer-sentiment]
Conversations per sentiment level over time, as a stacked bar chart or a **Breakdown**.
Negative Sentiment Reasons [#negative-sentiment-reasons]
Slightly and strongly negative conversations split by reason. Use the selector to show **All Negative**, **Slightly Negative** or **Strongly Negative** only. This is the chart to check first when you want to know what is driving frustration.
Sentiment and CSAT [#sentiment-and-csat]
Sentiment and [CSAT](/docs/help-desk/csat) answer the same question in different ways. CSAT is what customers who answer a survey tell you; sentiment is read from every scored conversation, including customers who never answer a survey. Use sentiment for coverage and trends, and CSAT for the customer's own verdict.
Related [#related]
* [Conversation topics](/docs/analytics/conversation-topics): what customers ask about.
* [Data collection](/docs/analytics/data-collection): your own questions about every conversation, such as whether a retention offer worked.
* [Metrics reference](/docs/analytics/metrics): every built-in chart and how it is calculated.
# Amazon
Amazon buyers contact sellers through Amazon's **Buyer-Seller Messaging Service**, which delivers each message by email. Route those emails to an address connected to Octocom, and they become conversations like any other. The AI agent answers them like any email, following Amazon's messaging rules once they are in its instructions. With Amazon order data connected, it answers order questions too.
***
How Amazon support works [#how-amazon-support-works]
Amazon deliberately keeps buyers and sellers at arm's length. When a customer contacts a seller, Amazon does not share the customer's real email address. Instead:
1. The buyer writes a message through Amazon, from the order page or your storefront.
2. Amazon forwards it as an **email** to the customer service address configured in your Seller Central account. The sender is an anonymized relay address like `xyz123+abc@marketplace.amazon.com`, unique to that buyer-seller relationship.
3. You reply to that relay address by email, and Amazon delivers your reply to the buyer's Amazon account and their real inbox.
This email relay is the **default** channel for buyer-seller communication, and the only one available without enrolling in additional programs (see live chat below). Amazon offers no API for reading buyer messages, so dedicated marketplace help desk tools work exactly this way, over email. That keeps setup simple: connecting Amazon to Octocom needs no special integration.
Does Amazon have live chat? [#does-amazon-have-live-chat]
Not by default. Out of the box, the only way a customer can reach a seller is Buyer-Seller Messaging, the asynchronous email flow described above. The live chat buyers see on Amazon is Amazon's own customer service, which handles marketplace-side issues (Prime, payments, deliveries, FBA returns) and directs product questions to "contact the seller".
Real-time contact with your brand exists only through **Brand Integration (Call & Chat)**, an **opt-in** Amazon program. Enrolled brands get a "Chat with Manufacturer" (and optionally "Request a Call from Manufacturer") button on the customer's order page after delivery. Enrollment is a free application in Seller Central where you submit your service details, support hours, and (for calls) a dedicated phone line, and commit to a strict **two-minute response SLA** during those hours.
For Octocom, the program's channels work like this:
* **Chat** is answered inside Amazon's own agent platform. Amazon doesn't offer external customer support platforms a way to receive or respond to these chats, so unlike Buyer-Seller Messaging emails, they stay in Amazon.
* **Calls** are transferred to the phone number the brand provides, so that number could be answered by an [AI voice agent](/docs/channels/voice). Amazon's program terms don't state whether automated agents are permitted, and its SLA and staffing expectations are designed around human teams, so check the terms before automating these calls.
If you're enrolled or considering it, talk to an Octocom solution engineer about how to handle these calls alongside your Amazon messages.
***
Getting Amazon messages into Octocom [#getting-amazon-messages-into-octocom]
Because Amazon delivers buyer messages by email, the setup happens entirely in **Seller Central**: you point Amazon at an email address that's already [connected to Octocom](/docs/channels/email/setup).
1. **Route buyer messages to your connected inbox.** In Seller Central, open **Settings -> Notification Preferences -> Messaging** and set the **Buyer Messages** notification email to the address connected to Octocom (for example `help@yourbrand.com`). Make sure all buyer message types are routed there. If some types go to a different address, those tickets won't reach Octocom.
2. **Authorize outbound replies.** In **Settings -> Fulfillment by Amazon -> Buyer-Seller Messaging** (or **Messaging Permissions**, depending on your account), add the same address as an **Approved Sender**. Amazon silently drops replies from addresses that aren't approved: the email appears to send, but the buyer never receives it. This step is easy to miss and is the most common cause of "our replies aren't getting through".
Once both are in place, every Amazon inquiry becomes a normal Octocom conversation: it lands in the inbox, can be tagged, assigned, answered by your team or by the AI agent, and your replies are relayed back to the buyer by Amazon.
Amazon usually includes the order ID in the subject line (for example "Product
details inquiry from Amazon customer Alex (Order: 112-0624927-4792268)").
Agents can use it to look the order up in Seller Central, and the AI agent can
use it too if you connect order data (see below).
***
Can the AI agent respond to Amazon messages? [#can-the-ai-agent-respond-to-amazon-messages]
Yes. Amazon conversations are regular email conversations in Octocom, so the same choice you make for email in general applies here: route everything to human agents, or let the AI agent handle what it can. Many merchants start with human-only handling and enable AI responses once order data is connected.
If you enable AI responses for Amazon messages, a few Amazon-specific rules matter:
* **No links or marketing.** Amazon's messaging policy prohibits promotional content, review solicitation, and links to external websites in buyer-seller messages. Messages that violate the policy can be blocked and count against your account. Reflect this in the AI agent's instructions, for example with a [bot rule](/docs/ai-agent/bot-rules) for Amazon conversations.
* **24-hour response SLA.** Amazon expects sellers to respond to buyer messages within 24 hours, including weekends and holidays, and tracks this in your account health. An AI agent that responds within minutes is a natural fit.
* **Anonymized customers.** The buyer's email is a relay address, so the AI agent can't match the customer to your store data by email. Order lookups work through the order ID instead, which is usually right in the subject line.
***
Connecting Amazon order data [#connecting-amazon-order-data]
Amazon orders live in Seller Central, not in your store platform, so Octocom reaches them through Amazon's API. Without order data the AI agent can still answer product and policy questions, but anything order-specific ("where is my order?", "was I refunded?") needs a connection to Amazon's **Selling Partner API (SP-API)**.
Getting API access [#getting-api-access]
Amazon lets sellers create a **private, self-authorized application**: an API credential that can only access your own account, with no app review process:
1. In Seller Central, register as a **private developer** (requires a Professional selling account; approval typically takes a day or two).
2. Create a private application in the Developer Console.
3. **Self-authorize** it. This generates a long-lived refresh token.
4. That refresh token, together with the app's client credentials, is everything needed to call the SP-API.
Store those credentials as [secrets](/docs/developers/secrets), and Octocom can pull order data through [custom actions](/docs/developers/custom-actions). For example, a Python action takes an order ID and returns the order status, items and shipping progress for the AI agent to use in its answer.
You don't need to build this yourself. [Octocom Copilot](/docs/developers/copilot) or an agent connected through [Octocom MCP](/docs/developers/mcp) can build and test the actions, Octocom's solution engineers can set it up with you, or your own IT team can do it using the credentials above.
What data is available [#what-data-is-available]
* **Standard order data** (status, items, totals, fulfillment channel, ship dates) is available with no special permissions. This covers the large majority of support questions.
* **Buyer personal data** (name, shipping address, contact details) is restricted. Accessing it requires Amazon's restricted data roles and a data protection audit, which takes weeks and imposes ongoing security obligations. For support automation it's rarely needed, and we recommend skipping it.
***
Refunds and cancellations [#refunds-and-cancellations]
Whether you need (or can have) refund and cancellation automation depends on who fulfills your orders:
FBA (Fulfilled by Amazon) [#fba-fulfilled-by-amazon]
**You don't need it.** Amazon handles the entire post-purchase money flow for FBA orders itself: it auto-approves return requests within the return window, sends the buyer a prepaid label, receives the item and issues the refund, all without seller involvement. Cancellation requests are likewise handled by Amazon. Your support (human or AI) only needs to answer informational questions. When a buyer asks for a refund on an FBA order, the right answer is to point them to Amazon's return process, and the AI agent can be instructed to do exactly that.
FBM (Fulfilled by Merchant) [#fbm-fulfilled-by-merchant]
**It's possible.** For seller-fulfilled orders, refunds and cancellations are your responsibility, and both can be automated through the SP-API:
* **Refunds** are issued programmatically via Amazon's Feeds API (the payment adjustment feed).
* **Cancellations** of unshipped orders go through the order acknowledgement feed.
These are asynchronous feed submissions rather than simple API calls, so they're a natural fit for Python actions with guardrails: for example, only allowing the AI agent to refund within limits you define, or requiring [human approval](/docs/developers/human-in-the-loop) before the action runs. If you're an FBM seller and want this, Octocom's solution engineers can scope it with you.
***
Summary [#summary]
| Question | Answer |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| How do Amazon tickets reach Octocom? | Amazon forwards buyer messages by email to your connected inbox. No special integration needed |
| Does Amazon have live chat? | Not by default. Only through the opt-in Brand Integration (Call & Chat) program (2-minute SLA), whose chat stays inside Amazon |
| Can the AI agent respond? | Yes, as on any email channel, with Amazon's messaging rules in its instructions |
| Can the AI agent see Amazon orders? | Yes, through a self-authorized SP-API credential and custom actions |
| Can it refund or cancel orders? | FBA: not needed, Amazon does it. FBM: yes, through SP-API feeds with guardrails |
# Contact form
A contact form lets customers reach you from your website without opening their email app. Every submission becomes a conversation in the help desk, and the AI agent answers it by email from your support address. Your team sees form submissions next to everything else, and can tag and route them by form.
You can publish a hosted form with **no code**, keep the form you already have if it sends submissions by email, or send submissions from your own form to Octocom's API.
Before you start [#before-you-start]
* **A connected email inbox.** Replies to form submissions go out by email, from the business's primary inbox unless you [choose another](#choosing-an-email-inbox). See [Connect email](/docs/channels/email/setup).
* **AI replies on that inbox**, if you want the AI agent to answer submissions. See [Email inbox settings](/docs/channels/email/settings).
* **Your business slug**, for the API options. Find it under **Settings -> Channels -> Contact Forms**.
Options for launching a contact form [#options-for-launching-a-contact-form]
You can set up a contact form in **four ways**:
| Option | Best when |
| ----------------------------------------------------------------- | -------------------------------------------------------- |
| [1. Hosted form](#1-hosted-form-on-your-customer-portal) | You want the fastest setup, with no coding |
| [2. JSON API](#2-submitting-inquiries-via-json-api) | You already manage file uploads and want full UI control |
| [3. Multipart form](#3-multipart-form-with-file-upload-support) | You want Octocom to handle file uploads for you |
| [4. Existing form, by email](#4-keep-your-existing-form-by-email) | Your form already emails submissions; no website changes |
Options 2 and 3 are for developers. Whichever you choose, each submission becomes an email conversation that follows the receiving inbox's [settings](/docs/channels/email/settings), and it can join the customer's ongoing email conversation through [conversation merging](/docs/channels/email/conversation-merging).
1. Hosted form on your customer portal [#1-hosted-form-on-your-customer-portal]
The easiest way to get started is a contact form hosted on your [customer portal](/docs/channels/customer-portal).
* Publish the form as a [custom page](/docs/channels/customer-portal/custom-pages), for example at `https://your-business.octocom.page/contact`. Ask Copilot or your AI agent to build and publish it for you.
* The page submits to the JSON or multipart endpoint described below.
* Link your site's **Contact us** button to the page.
* Optionally serve the portal from your own hostname, such as `help.example.com`, with a [custom domain](/docs/channels/customer-portal/custom-domains).
Build a contact form page at /contact on our portal with name, email, order
number and message fields, tag submissions "contact-page", show me a preview
and publish it.
2. Submitting inquiries via JSON API [#2-submitting-inquiries-via-json-api]
If you prefer embedding your own form, you can send inquiries directly to Octocom with a JSON `POST` request.
Endpoint [#endpoint]
```
POST https://api.octocom.ai/contact-forms/submit-inquiry
```
Example [#example]
```js
fetch("https://api.octocom.ai/contact-forms/submit-inquiry", {
method: "POST",
body: JSON.stringify({
businessSlug: "your-business-slug",
customerEmail: values.email,
customerName: values.fullName,
inquiryText: values.message,
tags: ["contact-page"],
}),
headers: {
"Content-Type": "application/json",
},
});
```
Request schema [#request-schema]
Octocom validates incoming JSON payloads using this schema:
```ts
body: {
businessSlug: string, // Required. Found in Contact Form settings.
customerEmail: string, // Required. Must be a valid email.
emailConfigId?: string, // Optional inbox UUID. Defaults to the business's primary inbox.
customerName?: string,
subject?: string,
inquiryText: string, // Required. Min 1 character.
orderId?: string,
additionalFields?: Record,
tags?: string[], // Up to 10 tags, max 50 characters each. See "Tagging submissions".
handedOff?: boolean, // If true, skips AI auto-response and routes directly to a human agent.
files?: Array<{ // Up to 3 files, 10 MB in total.
name?: string,
url: string, // Must be a direct, public file URL
contentType: string,
}>
}
```
`orderId` is stored as the `octocom:orderId` conversation metadata key (up to 255 characters). Each `additionalFields` entry is stored as conversation metadata under a `contactForm:` prefix, so `{"product": "Kettle"}` becomes `contactForm:product`. Python actions and workflows can read them from `context["conversation"]["metadata"]`. Treat these values as unverified customer input. Up to 50 fields are kept; keys can be up to 188 characters and values up to 50,000 characters. When a submission continues an existing conversation, only keys that conversation does not already have are written.
**Files:** for JSON API submissions, files must already be uploaded to your own hosting. You pass their URLs to Octocom. Octocom downloads them only after the submission passes your ignore rules and rate limits, with a 20-second limit for all files together. For larger or more files, use the multipart form below.
3. Multipart form (with file upload support) [#3-multipart-form-with-file-upload-support]
If you want Octocom to handle file uploads directly, use the **multipart form endpoint**.
Endpoint [#endpoint-1]
```
POST https://api.octocom.ai/contact-forms/submit-inquiry-multipart
```
* **Files** are included as standard multipart attachments.
* The **business slug** is passed via the `x-octocom-business-slug` header.
Schema (form fields) [#schema-form-fields]
```ts
{
customerEmail: string, // Required
emailConfigId?: string, // Optional inbox UUID. Defaults to the business's primary inbox.
customerName?: string,
subject?: string,
inquiryText: string, // Required
orderId?: string,
reason?: string,
handedOff?: "true" | "false", // Multipart fields are strings. "true" routes to a human.
tags?: string // See "Tagging submissions"
}
```
Example HTML form [#example-html-form]
Here's a ready-to-use form that submits directly to Octocom with file upload support:
```html
```
4. Keep your existing form, by email [#4-keep-your-existing-form-by-email]
If your website form already sends each submission by email, you can keep it as it is. Point it at an inbox connected to Octocom and add one [email rule](/docs/channels/email/rules#use-reply-to-as-the-customer). Your website doesn't change.
The rule is needed because most forms send every submission from one fixed address, with the customer only in the `Reply-To` header. Without it, Octocom treats that fixed address as the customer: different customers' submissions merge into one conversation, replies go to the form's address instead of the customer, and the per-sender limits can stop new conversations being created. The **Use Reply-To as the customer** action makes the customer in `Reply-To` the sender of the conversation.
Set it up [#set-it-up]
The quickest way is to ask [Copilot](/docs/developers/copilot), for example: *"Our website contact form emails us from `shop@example.com`, so all submissions end up in one conversation. Make each customer get their own conversation."* Your Octocom account manager can also set it up for you. To do it yourself:
1. Make sure form submissions reach an inbox [connected to Octocom](/docs/channels/email/setup).
2. Submit your form once and open the email. Note the **From** address and the subject, and check that **Reply-To** shows the address you entered in the form.
3. Open **Settings -> Help Desk -> Email Rules** and create a rule:
* Use the **Email** condition with the From address if that address only sends form submissions.
* Use the **Subject** condition with the form's subject if the same address also sends other mail, such as order notifications. Otherwise that mail would also be treated as coming from its `Reply-To`.
* Set the action to **Use Reply-To as the customer**.
* Optionally choose an inbox under **Only on inbox**.
4. Choose **Test email** on the same page, enter the From, Reply-To and subject from step 2, and check that the rule matches.
5. Submit the form again and confirm that a conversation appears under the customer's address.
What to expect [#what-to-expect]
* **The form must set `Reply-To` to the customer.** If it is missing, or on the same domain as the From address, the email keeps its original sender. A form that only writes the customer's address in the email body can't use this method: change the form to set `Reply-To`, or use the API.
* **Submissions are handled as normal email.** [Auto-merging](/docs/channels/email/conversation-merging), spam detection and your AI reply settings all apply, and attachments come through with the email.
* **The `contact-form` tag is not added automatically.** To tag these conversations, add a **Subject** rule with the **Add tag** action.
* **Match other rules on the subject.** Hand off and tag rules that match on the sender see the customer's address, not the form's. Sender-based **Ignore** and **Forward** rules run first, so they see the form's address and stop the email before this rule applies.
PrestaShop [#prestashop]
PrestaShop's standard contact form works with this method. It sends from your store's email address to the address of the contact the customer selects, and sets `Reply-To` to the customer. Its subject is `Message from contact form [no_sync]`, translated into your store's language, so copy the exact text from a real submission.
Keep the module's notification email turned on, and set the contact's address to your Octocom inbox or forward it there. Custom themes and third-party form modules can behave differently, so always check a real submission as in step 2.
Choosing an email inbox [#choosing-an-email-inbox]
By default, both API endpoints use your business's primary email inbox. Pass
`emailConfigId` to route a particular form to a different connected inbox within
that same business. Use the inbox's email configuration UUID, supplied by your
integration administrator, rather than its email address or an inbox view ID.
For JSON submissions, add it to the request body:
```js
{
businessSlug: "your-business-slug",
emailConfigId: "11111111-1111-4111-8111-111111111111",
customerEmail: "customer@example.com",
inquiryText: "Please help with my order",
}
```
For multipart submissions, add a field:
```html
```
The selected inbox determines the conversation's email integration, reply address
and AI response settings. A submission can merge into an existing conversation
only within that inbox. `handedOff: true` still creates a fresh conversation for a
human agent without an automatic AI reply.
An invalid UUID returns HTTP 400. A missing, archived, or other-business inbox
returns HTTP 404 without falling back to the primary inbox. If you omit the field,
the existing primary-inbox behavior is preserved. Inbox IDs are public routing
configuration, not API keys, so keep your existing anti-spam protections in place.
Tagging submissions [#tagging-submissions]
Both API endpoints accept custom tags, which are applied to the conversation the submission creates. Tags are useful when you run several forms (a warranty claim form, a wholesale enquiry form, a dispute form) and want to tell them apart in the inbox, filter views by them, or drive routing and automation.
Every contact form conversation is automatically tagged `contact-form`, whether or not you pass tags of your own. If the submission includes a `reason` field, its value is added as a tag too.
JSON API [#json-api]
Pass an array of strings:
```js
fetch("https://api.octocom.ai/contact-forms/submit-inquiry", {
method: "POST",
body: JSON.stringify({
businessSlug: "your-business-slug",
customerEmail: values.email,
inquiryText: values.message,
tags: ["warranty-form", "priority"],
}),
headers: { "Content-Type": "application/json" },
});
```
Multipart form [#multipart-form]
Multipart fields are plain text, so `tags` accepts either a comma-separated value or repeated fields. Both of these send the same two tags:
```html
```
```html
```
Rules and limits [#rules-and-limits]
* Up to **10 tags** per submission, each up to **50 characters**.
* Tags you haven't used before are **created automatically** in your organization's tag list. Watch your spelling: a typo creates a new tag rather than matching the intended one, so it's best to hardcode tag values in your form rather than build them from user input.
* Tag values are trimmed, and duplicates within one submission are ignored.
* On the multipart endpoint, tags that are empty or over 50 characters are **skipped** and the submission still goes through. On the JSON endpoint they're rejected with a validation error, so the whole request fails.
* If a submission is [merged into the customer's existing email conversation](/docs/channels/email/conversation-merging), the tags are applied to that conversation.
The multipart endpoint also accepts a single `tag` field. Use `tags` for new
forms.
Protecting your form from spam [#protecting-your-form-from-spam]
A contact form is public, so it attracts automated submissions. Octocom limits how much a single source can send, and you add the protections that fit your site.
* **Rate limits.** One visitor IP address can send at most 30 submissions per minute across all contact form endpoints. Further submissions in that minute get HTTP `429` with a `Retry-After` header (seconds until the limit resets), and nothing is created. Real visitors stay far below this limit. Submissions also count toward the same per-sender limits as email.
* **Ignore rules.** Sender and domain [email rules](/docs/channels/email/rules) with the **Ignore** action drop matching submissions before a conversation is created.
* **No API keys, by design.** The form's code is visible in your page source, so a key in it would protect nothing. The business slug and inbox ID are routing details, not secrets.
* **Captchas and bot protection.** Add a captcha to the form, and use your firewall or bot protection provider (such as Cloudflare) to block automated traffic before it reaches Octocom.
If a form keeps attracting spam despite these measures, contact Octocom support and we'll help you add stronger protection.
# Channels overview
Octocom runs one AI agent and one help desk across every channel. A chat on your website, an email, a phone call, a WhatsApp message and an Instagram comment all become conversations in the same inbox. You write a policy once, and the AI agent applies it wherever the customer writes or calls.
Most channels connect with one sign-in, one script tag or one API key. You then decide per channel how much the AI agent handles and when your team steps in.
What each channel lets you do [#what-each-channel-lets-you-do]
| Channel | What you get | What connecting takes |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- |
| [Web chat](/docs/channels/web-chat) | The AI agent answers on your site with product cards, order tracking and buttons. Your team takes over live. | One script tag, or a Shopify app embed with no code |
| [Email](/docs/channels/email) | Every support address answered by the AI agent or your team, from your own address. | A Gmail or Outlook sign-in, or email forwarding |
| [Phone calls](/docs/channels/voice) | The voice AI answers and makes calls, takes actions and transfers callers to your team. | Buy a US number, or bring your own |
| [SMS](/docs/channels/sms) | Customers text you and get answers by text, from the AI agent or your team. | A number on your own Twilio account |
| [WhatsApp](/docs/channels/whatsapp) | Text, photos and voice messages answered in the customer's WhatsApp chat. | Meta's signup, opened from the dashboard |
| [Facebook and Instagram](/docs/channels/social-media) | Direct messages answered like any chat. Comments and mentions handled by comment workflows. | Log in with Facebook and pick your pages |
| [TikTok ad comments](/docs/channels/social-media/comment-workflows#tiktok-ad-comments) | Comment workflows reply publicly or hand comments to your team. | Approve access on TikTok |
| [Telegram](/docs/channels/telegram) | Private chats with your Telegram bot, answered in the same chat. | A bot token from Telegram's BotFather |
| [Whop](/docs/channels/whop) | Your Whop support chats, answered as a team member you choose. | A Whop API key |
| [Amazon](/docs/channels/amazon) | Buyer messages answered by email, with order lookups once you connect Amazon's API. | Point Seller Central at a connected email address |
| [Contact forms](/docs/channels/contact-form) | Every form submission becomes a conversation, answered by email. | A hosted form Copilot builds, or the form you have |
| [Reviews](/docs/channels/reviews) | Review workflows reply publicly, email the reviewer privately or hand off to your team. | A one-time connection to each platform |
| [Help center and portal](/docs/channels/customer-portal) | A searchable help center built from your articles, on your own domain. | Switch it on and mark articles public |
| [Any other messaging system](/docs/developers/rest-api#two-way-messaging-over-http) | Conversations you push in over the REST API, with replies delivered to your webhook. | An API call and a webhook |
Reviews cover Trustpilot, Google, Facebook, Judge.me, Okendo, the App Store and Google Play. If your team already works in another help desk, such as Zendesk, Gorgias or Freshdesk, the AI agent can work inside it instead. See [Use Octocom with another help desk](/docs/help-desk/third-party-help-desk).
Set it up [#set-it-up]
Show our chat widget on example.com with the greeting "Hi! Need help with an
order?". Then connect [support@example.com](mailto:support@example.com) by email forwarding and tell me
which DNS records to add.
[Copilot](/docs/developers/copilot) or any AI agent connected through [Octocom MCP](/docs/developers/mcp) sets up most channels for you and tests the result. It builds web chat configurations, email forwarding and rules, phone lines and campaigns, comment and review workflows, and help center pages. It also connects SMS numbers, Whop and Trustpilot.
Connections that need a sign-in to another platform, such as Gmail, Outlook, Meta or WhatsApp, start in the dashboard. Channel settings live in three places:
* **Settings -> Channels:** web chat, email, contact forms, Facebook and Instagram, comments and reviews.
* **Settings -> Voice & SMS:** phone numbers, voice agents, campaigns and SMS.
* **Settings -> Workspace -> Integrations:** WhatsApp, Telegram, Whop, TikTok Ads, review platforms and other help desks.
Each channel's page has the exact steps, and [Launch an AI phone line](/docs/guides/launch-an-ai-phone-line) walks through a voice line from test call to go-live. Octocom's solution engineers can review a channel setup before you go live.
One setup for every channel [#one-setup-for-every-channel]
Every conversational channel uses the same configuration. That includes web chat, email, phone calls, SMS, WhatsApp, direct messages, Telegram, Whop, Amazon and contact forms.
* **Knowledge:** the [knowledge base](/docs/ai-agent/knowledge-base), documents and website sources.
* **Behavior:** [bot rules](/docs/ai-agent/bot-rules), [workflows](/docs/ai-agent/workflows), [actions](/docs/ai-agent/actions) and the [writing style](/docs/ai-agent/writing-style).
* **People in the loop:** [human escalation](/docs/ai-agent/human-escalation) and [handoff settings](/docs/help-desk/handoff).
An action that looks up an order works in a chat, an email and a phone call alike, with nothing to rebuild per channel.
Public comments and reviews work differently. A public reply is a single response, not a back-and-forth, so they have their own [comment workflows](/docs/channels/social-media/comment-workflows) and [review workflows](/docs/channels/reviews/review-workflows), written for that format.
Per-channel control [#per-channel-control]
Where a channel needs different handling, you scope it without duplicating your setup:
* **Workflows, bot rules and articles** can each be limited to specific channels. A "keep replies short" rule can apply to web chat only, and an article about phone-queue wait times can stay off web chat. See [workflows](/docs/ai-agent/workflows), [bot rules](/docs/ai-agent/bot-rules) and the [knowledge base](/docs/ai-agent/knowledge-base).
* **Each email address** chooses between AI replies, agents only or send only, with its own reply delay, approval step and signatures. See [Email inbox settings](/docs/channels/email/settings).
* **SMS** runs in AI or agent mode. See [SMS](/docs/channels/sms#human-or-ai-replies).
* **Phone numbers** each carry their own voice AI settings. See [Voice AI settings](/docs/channels/voice/voice-ai-settings).
* **Live chat** with your team is turned on per business in the [handoff settings](/docs/help-desk/handoff#live-chat).
For developers and AI agents [#for-developers-and-ai-agents]
* [Octocom MCP](/docs/developers/mcp) lists the tools an AI agent uses to configure each channel.
* The [REST API](/docs/developers/rest-api#two-way-messaging-over-http) connects any other messaging system: push customer messages in and receive replies on your webhook.
* [Webhooks](/docs/developers/webhooks) send replies, handoffs, closed conversations and finished calls to your own systems.
# SMS
SMS lets customers text your business and get answers by text. Incoming messages become SMS conversations in the help desk, answered by the AI agent or by your team, and every reply goes out from the number the customer texted. Supported numbers also carry picture messages, known as MMS.
Octocom can also send texts:
* **The AI agent** can text a customer during another conversation, for example a link during a phone call.
* **Your agents** can start a text conversation from the help desk, or text a caller back after a call.
* **Your own systems** can text customers through the REST API, for example a shipping or appointment update.
SMS runs on numbers from [your own Twilio account](/docs/channels/voice/custom-twilio). Numbers you buy through Octocom are for calls.
Set up SMS [#set-up-sms]
Connect my Twilio number to this business for SMS handled by our agents.
Copilot connects your Twilio account, lists its numbers, checks that the one you pick can receive texts and connects it to the business. Connecting a number for SMS leaves its call routing as it is. You need the **Edit channels** permission. Any [MCP client](/docs/developers/mcp) can do the same; the tools are listed [below](#for-developers-and-ai-agents).
Then open **Settings -> Voice & SMS -> SMS** to see the connected numbers and whether each one answers with AI replies or human agents, turn receiving on or off per number and manage blocked senders.
Texting US and Canadian customers from a US toll-free number needs approved
toll-free verification with your carrier. A number that supports SMS is not
automatically approved to send. Octocom reports the verification status when
Twilio provides it, but registration happens in Twilio. Other destinations and
number types have their own provider requirements. See [Twilio's toll-free
verification
guide](https://www.twilio.com/docs/messaging/compliance/toll-free/console-onboarding).
Human or AI replies [#human-or-ai-replies]
Each business answers SMS in one of two modes:
* **Human agents:** incoming texts create or update an SMS conversation in the help desk for your team.
* **AI replies:** the AI agent answers with the business's knowledge, rules and workflows, and hands off to your team when needed.
New connections start with human agents. To switch, ask Copilot, or set the mode through MCP or the REST API. Replies always use the number the customer texted. A number with receiving turned off discards incoming texts before a conversation is created.
Texting customers from the help desk [#texting-customers-from-the-help-desk]
Agents can text customers from connected numbers that receive texts, since that is where the reply arrives:
* **A new conversation:** click **+** beside **Help Desk** and choose **SMS**. See [Starting a new conversation](/docs/help-desk/managing-conversations#starting-a-new-conversation).
* **A phone call conversation:** choose **Reply via SMS** to text the caller, for example after a missed call. It goes from the number they called when that number can text. Their reply joins the same conversation. See [Replying by text or email](/docs/help-desk/phone-calls#replying-by-text-or-email).
Texts from the AI agent [#texts-from-the-ai-agent]
The AI agent's `sendSms` action texts a customer during another conversation, such as a web chat or a phone call. To turn it on, choose which connected number it sends from (ask Copilot, or set `outboundPhoneNumber` with `update_sms_settings`). Choosing the number doesn't send anything: add the action to the [workflows](/docs/ai-agent/workflows) where a text is appropriate.
* **On a phone call**, `sendSms` texts the person on the call: the caller on an inbound call, the number dialed on an outbound one. The AI agent doesn't need the number in its instructions. A caller who withheld their number can't be texted this way.
* **Without your own Twilio number**, ask Octocom to set up a sender name for you, such as your brand name. Customers can't reply to a text sent from a name.
* **Through another service**, such as Viber, WhatsApp or a different SMS gateway: `sendSms` always sends a plain SMS through Twilio, so use a [custom Python action](/docs/developers/custom-actions) that calls the other service.
This action is separate from replying in an SMS conversation. To text customers from your own systems, use the REST API's [outbound SMS](/docs/developers/rest-api#starting-an-sms-conversation).
Troubleshooting [#troubleshooting]
* **The number is in Twilio but not in Octocom:** it hasn't been connected to a business yet. Ask Copilot to connect it.
* **Messages don't appear:** check that receiving is on for the number in **Settings -> Voice & SMS -> SMS** and that the sender isn't blocked. A Twilio Messaging Service or application can override the number's own webhook; see [Numbers in a Messaging Service](/docs/channels/voice/custom-twilio#numbers-in-a-messaging-service).
* **Sending fails:** check the saved credentials, the selected sender, carrier registration and Twilio's delivery errors. Turning receiving on doesn't approve a sender with a carrier.
* **The business already receives SMS through Postscript or another Twilio account:** connecting another number is refused, so the existing setup is never replaced without notice.
* **Receiving stopped after you rotated your Twilio Auth Token:** Octocom uses the saved token to check that incoming texts come from Twilio. Update the saved token to match Twilio and test both directions.
For developers and AI agents [#for-developers-and-ai-agents]
**Connect a number.** You need the `channels:write` scope.
1. Connect the Twilio account and list its numbers with `create_twilio_account` and `list_twilio_phone_numbers`. See [Your own Twilio account](/docs/channels/voice/custom-twilio).
2. Inspect the selected number with `get_twilio_phone_number`. Check SMS capability, current routing and any toll-free verification requirements.
3. Call `connect_twilio_phone_number` with the business, explicit account ID, number SID and `channels: ["sms"]`. Leave voice out to preserve call routing. Use `smsMode: "agent"` for human replies or `"bot"` for AI replies; without it, a first connection uses human agents and an existing mode is kept.
4. If a Messaging Service overrides the number's webhook, follow [Numbers in a Messaging Service](/docs/channels/voice/custom-twilio#numbers-in-a-messaging-service).
5. Inspect again and check `sms.pointsToOctocom`, `sms.configuredInOctocom` and `sms.receivingEnabled`. These confirm configuration, not delivery.
`list_twilio_phone_numbers` is the live Twilio inventory; `list_phone_numbers` shows the numbers connected to Octocom.
**Settings.** `get_sms_settings` returns the mode, connected numbers, receiving state, blocked senders and the `sendSms` sender. `update_sms_settings` changes `mode`, the complete `disabledRecipientNumbers` list (an empty list enables receiving on every connected number) or `outboundPhoneNumber`. Omitted fields stay unchanged. The same settings are available through `GET` and `PATCH /rest/v1/sms-settings?businessSlug=your-business`.
**The `sendSms` action.** On a phone call, leave out `to` and the text goes to the person on the call. Pass `to` only to text a different number.
No inspection or configuration tool sends a test message.
# Telegram
Connect a Telegram bot to Octocom and customers can message your business on Telegram. Each private chat with the bot becomes a conversation in the Octocom help desk. The AI agent answers with the same knowledge, rules and workflows as on your other channels, and your team takes over in the same chat when needed.
You need a Telegram bot token, and the **Manage integrations** and **Edit channels** permissions in Octocom. If you don't have a bot yet, create one with Telegram's **@BotFather** first.
Connect your bot [#connect-your-bot]
Create a bot in Telegram [#create-a-bot-in-telegram]
Open [@BotFather](https://t.me/botfather) in Telegram and send `/newbot`. Follow the prompts to choose the bot's name and username. BotFather replies with the bot's token.
To connect a bot you already have, send `/token` to BotFather and choose the bot to get its token again.
Paste the token into Octocom [#paste-the-token-into-octocom]
In the Octocom dashboard, select the business that should receive the Telegram conversations. Open **Settings -> Workspace -> Integrations -> Telegram**, paste the token into **Bot token** and click **Connect**.
Octocom registers itself with Telegram as the bot's message receiver. Nothing else needs configuring on the Telegram side. If Telegram rejects the token, the dashboard says so: check that you copied the whole token and try again.
Test it [#test-it]
Open your bot in Telegram, press **Start** and send a message. The conversation appears in the help desk on the **Telegram** channel, and the AI agent replies in the chat.
Use a bot dedicated to Octocom. Telegram delivers a bot's messages to one receiver, so another system that used the same bot stops receiving them once it is connected here. Treat the token like a password: anyone who has it can control the bot.
What customers experience [#what-customers-experience]
* **Private chats only.** Customers talk to the bot one to one. If someone adds the bot to a group, it leaves the group.
* **Text and photos.** Text messages and photos (with their captions) come through. For other message types, such as voice messages, files, stickers or locations, the conversation notes which type the customer sent, so the AI agent or your team can ask for the details in text.
* **One conversation at a time.** Messages continue the customer's open conversation. Once it is closed, the next message starts a new one. Sending `/start` always starts a fresh conversation and closes the open one.
* **Text replies.** Replies from the AI agent and your team arrive as text messages in the same chat. Images and file attachments are not sent on Telegram, so agents reply in text.
What the AI agent and your team can do [#what-the-ai-agent-and-your-team-can-do]
The AI agent handles Telegram conversations like any other messaging channel: it answers from your [knowledge base](/docs/ai-agent/knowledge-base), follows [bot rules](/docs/ai-agent/bot-rules) and [workflows](/docs/ai-agent/workflows), and runs [actions](/docs/ai-agent/actions). To handle Telegram differently, limit a workflow, bot rule or article to the **Telegram** channel, or leave Telegram out of its channel list.
When the AI agent [hands off](/docs/ai-agent/human-escalation), it tells the customer the team will reply in Telegram. Your agents open the conversation in the help desk and reply there. The reply goes to the customer's Telegram chat. Notes, tags, assignment and views work as on every other channel. See [Managing conversations](/docs/help-desk/managing-conversations).
Disconnect [#disconnect]
Open **Settings -> Workspace -> Integrations -> Telegram** and choose **Disconnect**. Octocom stops receiving the bot's messages and removes itself as the bot's receiver in Telegram. Existing conversations stay in the help desk. To switch to a different bot, disconnect the current one first, then connect the new token.
Related [#related]
* [Channels overview](/docs/channels): every channel and how it connects.
* [Handed-off conversations](/docs/help-desk/handoff): when and where your team replies.
# Whop
Connect Whop to let Octocom's AI agent answer the support chats customers open with your
shop in Whop. Each chat becomes a conversation on the Whop channel in Octocom, and
the AI agent's replies appear in the same Whop chat under a team member you choose.
When someone on your team replies in Whop, the AI agent steps back.
Each Whop shop is a separate Whop account with its own API key. Connect each shop
in the Octocom business that handles it. One Whop shop can be connected to one
Octocom business.
Create an API key in Whop [#create-an-api-key-in-whop]
1. In your shop's Whop dashboard, open **Developer -> Account API Keys** and
select **Create**.
2. Choose a custom permission set and enable:
* `support_chat:read`: read support chats.
* `support_chat:message:create`: reply in support chats.
* `support_chat:create`: resolve chats when Octocom closes a conversation.
* `company:authorized_user:read`: identify your shop and list the team members
Octocom can reply as.
* `developer:manage_webhook`: receive new messages in real time.
* Optional: `payment:basic:read`, so your
[custom actions](/docs/developers/custom-actions) can look up
payments and refunds.
3. Create the key and copy it.
A Whop API key cannot send chat messages on its own. Octocom uses it to create a
short-lived login for the team member you choose, limited to support chats, and
replies as that person. Use a dedicated team member such as "Support" so your team
can tell the AI's replies apart. The same Whop user can reply for several shops
if they are on each shop's team.
Connect in Octocom [#connect-in-octocom]
1. Open **Settings -> Workspace -> Integrations -> Whop**, paste the key and select
**Connect**.
2. Choose the team member Octocom replies as.
3. Turn on **AI replies** and save. Octocom subscribes to new Whop messages and
the AI starts answering new customer messages right away. Existing chats are
picked up when the customer next writes.
4. Select **Check setup** at any time. It checks the key, support chat access,
the reply user and webhook delivery, and names any missing permission.
Turn **AI replies** off to pause the Whop channel without losing the connection:
Octocom stops receiving Whop messages and sending replies, including your agents'
replies from the Octocom inbox.
**Uninstall** removes the key and Octocom's webhook in Whop. Conversations stay
in Octocom.
How conversations work [#how-conversations-work]
* Each Whop support chat maps to one Octocom conversation. When a conversation is
closed, the next customer message starts a new one.
* Closing a conversation in Octocom resolves the chat in Whop.
* When someone on your team replies in Whop, the conversation is handed off and
the AI stops. Their reply is saved in the Octocom conversation.
* Replies your agents send from the Octocom inbox are posted in Whop as the chosen
team member.
* Whop's automated messages, such as order receipts and welcome messages, are
ignored.
* Octocom stores the customer's Whop user ID, username and chat ID as conversation
metadata (`whopUserId`, `whopUsername`, `whopChannelId`), so actions can look up
their payments.
* Attachments, GIFs and polls stay in Whop. In Octocom the message says the customer
sent one, so the AI agent and your team know to check the Whop chat.
Use Whop in custom actions [#use-whop-in-custom-actions]
[`get_integration_credentials`](/docs/developers/python-helpers/get-integration-credentials)
returns the `whop` entry with `apiKey` and `accountId`. Call
`https://api.whop.com/api/v1` with `Authorization: Bearer {apiKey}`, for example
`GET /payments?account_id={accountId}&user_id={whopUserId}` to find a customer's
payments and refunds.
For developers and AI agents [#for-developers-and-ai-agents]
Copilot and MCP clients can use `connect_whop`, `list_whop_team_members`,
`configure_whop`, `check_whop_setup`, `get_whop_connection` and `disconnect_whop`.
The REST API offers the same under
`/rest/v1/businesses/{businessId}/integrations/whop`.
# AI suggestion buttons
import { Accordions, Accordion } from "fumadocs-ui/components/accordion";
AI suggestion buttons show a row of clickable questions on your product pages, right where shoppers decide whether to buy. Tapping one opens your Octocom chat with that question already filled in. The shopper starts a conversation about the product in one click, instead of facing an empty chat box.
Use them to surface the questions shoppers most likely have, such as fit, materials, shipping or compatibility, and turn them into conversations that help the sale. The questions come from one of two places:
* **AI-generated:** written automatically for the product the shopper is viewing.
* **A fixed list:** the exact questions you choose, shown on every matching page.
You decide where the buttons appear, how they look, and whether they run on desktop, mobile or both. They ship with the web chat widget, so there is no extra script to install. Make sure the [chat widget is deployed](/docs/channels/web-chat/launch-chat-widget) first.
How it works [#how-it-works]
When a shopper opens a product page, the widget adds your suggestion buttons next to the element you choose, for example just under the **Add to cart** button. With AI suggestions on, the questions are written for that exact product from its details in your [product catalog](/docs/commerce/product-catalog), so they appear on pages Octocom can match to a synced product. Each product's questions are generated once and reused for later visitors until you change the prompts. With a fixed list, your chosen questions appear instead.
Tapping a button opens the chat with the question filled in, ready to send. If you turn on **Ask something else**, an extra button opens the chat empty so the shopper can type their own question.
Set it up [#set-it-up]
Ask [Copilot](/docs/developers/copilot) or your own AI agent through [Octocom MCP](/docs/developers/mcp), for example:
Add AI suggestion buttons under the Add to cart button on our product pages,
desktop only, with questions about fit and materials for clothing.
The agent finds a stable place on your product template, tries the AI suggestions against a few of your real product pages before saving, and switches the buttons on when you're happy with them. Octocom's solution engineers can also set them up and tune them with you.
Most stores only need two choices to start: where the buttons go and where the questions come from.
Configuration reference [#configuration-reference]
The settings below are for whoever sets the feature up, usually an AI agent working through the MCP tools.
Almost every setting has a desktop and a mobile version, so you can configure each device independently: placement, page targeting, labels, styling and on/off switches.
When **mirror desktop to mobile** (`mirrorDesktopConfigToMobile`) is on, mobile reuses every desktop setting and the mobile-specific fields are ignored. This is the default and the common case. Turn it off to give mobile its own placement and labels.
The desktop and mobile switches (`enabled` and `mobileEnabled`) are independent. Running the buttons on desktop only, where there is more room, is common.
**Placement:** `selectorDesktop` (required) and `selectorMobile` are CSS selectors for the element to place the buttons next to. Separate several selectors with commas and the first match wins. Pick something stable across your product templates. `insertionPositionDesktop` and `insertionPositionMobile` set the placement relative to that element:
* `before`: as a sibling immediately before the target.
* `after`: as a sibling immediately after the target.
* `inside`: as the last child of the target.
* `replace`: replaces the target element entirely.
**Page targeting:** `pathRegexDesktop` and `pathRegexMobile` are optional regular expressions matched against the page path. When set, buttons only appear on matching pages, for example `^/products/` for product pages or `^/en/` for a locale. Leave them empty to show the buttons on every page. See [supported regular expressions](/docs/channels/web-chat/configuration#supported-regular-expressions).
**Suggestion source:** `generateButtonsFromPageContext` on means questions are AI-generated for each product. Off means your fixed list is used.
**AI suggestion prompts** (AI mode): `suggestionPrompts` is an ordered list of `{ urlPattern, prompt }` entries. The first entry whose `urlPattern` matches the current page is used, and an entry with an empty `urlPattern` is a catch-all. The prompt is the instruction sent to the model along with the product details, and it should ask for a short list of questions. Use separate entries to tailor questions per category, for example dimensions and material for furniture, fit and care for apparel.
**Fixed labels** (manual mode): `staticButtonTextValuesDesktop` and `staticButtonTextValuesMobile` are plain lists of strings. Each string becomes one button.
**Ask something else:** `includeAskSomethingElse` adds an extra button that opens the chat with no question filled in, so the shopper can type anything.
**Sparkle icon:** `showSparkleIcon` and `showSparkleIconMobile` add a ✨ in front of AI-generated labels. Fixed labels are left as they are.
**Minimum price:** `minimumPriceUsd` hides the buttons on products priced below this amount, so AI suggestions aren't generated for a long tail of low-value items. It applies to a fixed list too: with a minimum set, buttons only appear on pages that match a catalog product at or above it.
By default the buttons use a built-in template. For full control over the markup, turn on custom HTML (`htmlIsCustomDesktop` and `htmlIsCustomMobile`) and supply your own in `htmlTemplateDesktop` and `htmlTemplateMobile`.
You don't write any JavaScript. The widget wires everything up by looking for these markers:
| Marker | Element | Purpose |
| --------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-octocom-button-template` | any element | Cloned once per suggestion. Its text is set to the question (with a `✨ ` prefix when the sparkle icon is on). Include more than one to split the buttons across containers. |
| `data-octocom-ask-something-else` | `
Each business has one buttons configuration (not a list of variants). Three tools manage it:
| Tool | Purpose |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `get_interaction_buttons_config` | Fetch the business's configuration. Returns null if it has never been configured. |
| `upsert_interaction_buttons_config` | Create or partially update it. Only the fields you pass change. The first write requires `selectorDesktop`. |
| `preview_interaction_buttons_for_url` | Run the AI suggestions against a sample product URL without saving, to iterate on `suggestionPrompts`. |
A typical setup flow:
1. Make sure web chat is set up for the business.
2. Call `upsert_interaction_buttons_config` with `enabled: false` and a stable `selectorDesktop`, leaving the rest at the defaults.
3. Iterate on `suggestionPrompts` with `preview_interaction_buttons_for_url` against a few representative product URLs.
4. Save the final `suggestionPrompts`, then adjust the styling and the desktop and mobile split.
5. Set `enabled: true` (and `mobileEnabled` if you want the buttons on mobile) to go live.
# Browser session purchases
Browser session purchases link a completed checkout to the visitor who chatted with your AI agent in the same browser. That is how Octocom shows the revenue your conversations bring in, under **Metrics -> Sales**.
A purchase counts toward chat when it happens within 7 days of a conversation in the same browser session. The **Sales** tab is available to everyone with metrics access, whatever your ecommerce platform.
**Shopify stores don't need to do anything.** Connecting or reconnecting the Octocom app activates checkout tracking automatically. See [Shopify revenue tracking](/docs/integrations/shopify/chat-widget-tutorial#revenue-tracking) for consent and browser-session requirements.
**For any other store**, your developer adds one call to your order confirmation step. It sends the purchase to a public Octocom endpoint that needs no API key. Instead, a per-session **purchase token**, which the chat widget stores in the visitor's browser, proves the purchase comes from that visitor's own session. The rest of this page is the reference for that call.
To compare shoppers who chatted with those who didn't using Google Analytics instead, see [Revenue attribution with GA4](/docs/commerce/google-analytics-4).
***
What is a browser session? [#what-is-a-browser-session]
When a visitor opens the Octocom chat widget, the widget creates a **browser session**. It is identified by a UUID stored in the visitor's `localStorage`, so it persists across page navigations and later visits in the same browser. A session expires after 180 days without the visitor opening the chat. No session is created for a visitor who never opens the chat, so those visits have no session ID to report a purchase against.
A browser session is how Octocom links activity across a visitor's journey: it connects chat conversations, page visits and (with this integration) purchases to a single anonymous visitor profile.
***
Prerequisites [#prerequisites]
Before you record purchases through the API, make sure the Octocom **chat widget** is installed on your site. See [Launch the chat widget](/docs/channels/web-chat/launch-chat-widget).
***
Getting the browser session ID [#getting-the-browser-session-id]
The browser session ID is stored in `localStorage` under the key:
```
octocom-browser-session-id:{configId}
```
where `{configId}` is the ID of your web chat configuration (under **Settings -> Channels -> Web Chat** in the Octocom dashboard). The value is the session UUID itself: read it and send it as it is.
If you don't know your `configId`, scan `localStorage` for any key with the `octocom-browser-session-id:` prefix:
```js
function getOctocomBrowserSessionId() {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key?.startsWith("octocom-browser-session-id:")) {
return localStorage.getItem(key);
}
}
return null;
}
const browserSessionId = getOctocomBrowserSessionId();
```
This returns `null` if the widget script has not run yet, or if the visitor has never opened the chat in this browser. In private or incognito windows the session exists for as long as the tab is open, and does not carry over once it is closed.
Without a valid browser session ID, the API returns **404 Browser session not found** and the purchase is not stored.
***
Getting the purchase token [#getting-the-purchase-token]
The chat widget also stores a **purchase token** for the session under:
```
octocom-purchase-token:{browserSessionId}
```
Send it as `purchaseToken` with the purchase. It proves the purchase comes from the visitor's own session, so nobody who only knows a session ID can add purchases to your revenue metrics. It authorizes nothing else, so it is safe to use in checkout code. Never send the separate `octocom-session-credential:` value.
```js
const purchaseToken = localStorage.getItem(
`octocom-purchase-token:${browserSessionId}`,
);
```
Purchases without a valid token are recorded but marked **unverified**, and each browser session accepts at most 60 unverified purchases an hour. Always send the token so your purchases count as verified. If no token is stored for a session, send the purchase without one: it is recorded as unverified, and the widget stores a token the next time it loads.
***
Recording a purchase through the API [#recording-a-purchase-through-the-api]
Endpoint [#endpoint]
```
POST https://api.octocom.ai/rest/v1/browser-sessions/:browserSessionId/purchases
```
* **No API key** is required. The purchase token and rate limits protect the endpoint.
* **Rate limit:** at most **100 requests per minute per IP address**. Exceeding it returns **429** with an error message.
Example [#example]
```js
const browserSessionId = getOctocomBrowserSessionId(); // see above
if (browserSessionId) {
try {
const response = await fetch(
`https://api.octocom.ai/rest/v1/browser-sessions/${browserSessionId}/purchases`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
lineItems: [
{
id: "product-123",
quantity: 2,
},
{
id: "product-456",
quantity: 1,
variant: { variantId: "variant-789" },
},
],
totalPrice: 99.99,
currencyCode: "USD",
provider: "shopify",
orderId: "1042",
purchaseToken: localStorage.getItem(
`octocom-purchase-token:${browserSessionId}`,
),
}),
},
);
if (!response.ok) {
console.error(
"Failed to record purchase",
response.status,
await response.text(),
);
}
} catch (err) {
console.error("Failed to record purchase", err);
}
}
```
Full checkout integration example [#full-checkout-integration-example]
A complete example to call at the end of a checkout flow:
```js
async function recordOctocomPurchase({
lineItems,
totalPrice,
currencyCode,
provider,
orderId,
}) {
function getOctocomBrowserSessionId() {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key?.startsWith("octocom-browser-session-id:")) {
return localStorage.getItem(key);
}
}
return null;
}
const browserSessionId = getOctocomBrowserSessionId();
if (!browserSessionId) {
// Widget hasn't initialised yet or Octocom isn't installed — skip silently.
return;
}
try {
const response = await fetch(
`https://api.octocom.ai/rest/v1/browser-sessions/${browserSessionId}/purchases`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
lineItems,
totalPrice,
currencyCode,
provider,
orderId,
purchaseToken: localStorage.getItem(
`octocom-purchase-token:${browserSessionId}`,
),
}),
},
);
if (!response.ok) {
console.error(
"Octocom: failed to record purchase",
response.status,
await response.text(),
);
}
} catch (err) {
console.error("Octocom: failed to record purchase", err);
}
}
// Call this after a successful checkout:
recordOctocomPurchase({
lineItems: [
{ id: "product-123", quantity: 2 },
{ id: "product-456", quantity: 1, variant: { variantId: "variant-789" } },
],
totalPrice: 99.99,
currencyCode: "USD",
provider: "shopify",
orderId: "1042",
});
```
Request schema [#request-schema]
The request body must be valid JSON with this shape:
```ts
{
lineItems: Array<{
id: string, // Required. The purchased item's (product) ID.
quantity: number, // Required. Quantity purchased.
variant?: { // Optional. Include only when the item is a variant.
variantId: string, // The variant's ID.
},
// You may include other fields; they are stored as JSON.
}>,
totalPrice: number, // Required. Total price of the purchase. Must be positive.
currencyCode: string, // Required. e.g. "USD", "EUR".
provider?: string, // Optional. e.g. "shopify", "api". Default: "api".
orderId?: string, // Optional. Your own order identifier, used for reconciliation. Any string you choose.
purchaseToken?: string, // Recommended. Read from localStorage `octocom-purchase-token:{browserSessionId}`.
}
```
Limits: up to 1,000 line items, a request body of up to 1 MB, a `currencyCode` of up to 16 characters, a `provider` of up to 100 characters and an `orderId` of up to 256 characters.
**Line items:**
* **`lineItems`** must be an **array**. Each element is one purchased item.
* Each item must include:
* **`id`**: the purchased product or item ID.
* **`quantity`**: how many of this item were purchased.
* If the item is a **variant** (for example a size or color), add a **`variant`** object with a **`variantId`** field.
Example for a simple product and a variant product:
```ts
lineItems: [
{ id: "prod_abc", quantity: 2 },
{ id: "prod_xyz", quantity: 1, variant: { variantId: "var_123" } },
];
```
**Order ID:**
* **`orderId`** is optional and accepts **any string** you choose, for example your store's order number (`"1042"`, `"#1042"`) or the platform's order ID (`"order_abc123"`, `"gid://shopify/Order/123"`). It is stored as it is, so you can later match chat-attributed sessions to orders in your own system.
* If you omit it, the purchase is still recorded, but without a direct link to your order record.
* Sending the same `orderId` again for the same session does not record the order twice. The API returns the existing record.
Response [#response]
| Status | Meaning |
| ------- | -------------------------------------------------------------------------------------------------------------------------------- |
| **201** | Purchase recorded. The response body includes `success: true`, `message` and `id` (the UUID of the purchase record). |
| **400** | Invalid request body (for example, validation failed). |
| **404** | Browser session not found. Check that `browserSessionId` is a valid, existing session UUID. |
| **429** | Rate limit exceeded. At most 100 requests per minute per IP, or 60 purchases without a valid token per browser session per hour. |
| **500** | Server error (for example, the purchase could not be stored). |
***
Security considerations [#security-considerations]
* **No API keys:** the endpoint is meant to be called from the browser after checkout. Because the URL and payload are visible in client-side code, it does not use API keys. Instead, the `purchaseToken` proves the purchase comes from the visitor's own session, and rate limits apply (100 requests a minute per IP, 60 purchases without a valid token an hour per session).
* **Abuse:** if you see spam purchases in your metrics, contact Octocom support to investigate and limit them.
* **CORS:** the API allows browser-based calls from your storefront.
***
Summary [#summary]
| What you need | Description |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Browser session ID** | Read from `localStorage` using the key `octocom-browser-session-id:{configId}`, or scan for any key with the `octocom-browser-session-id:` prefix. |
| **Line items** | Array of objects with `id`, `quantity` and an optional `variant: { variantId }` for variants. |
| **totalPrice / currencyCode** | Total amount and currency of the order. |
| **provider** | Optional identifier (for example `"shopify"` or `"api"`) for where the purchase came from. |
| **orderId** | Optional. Any string identifying the order in your own system (for example `"1042"` or `"order_abc123"`). Used for reconciliation. |
| **purchaseToken** | Recommended. Read from the `localStorage` key `octocom-purchase-token:{browserSessionId}`. Purchases without it are marked unverified. |
Call `POST /rest/v1/browser-sessions/:browserSessionId/purchases` on `https://api.octocom.ai` with this body to record a purchase for that session.
# Revenue attribution with GA4
The Octocom chat widget reports chat activity to Google Analytics 4, or GA4, and marks every visitor who sends a message. That shows you what your chat is worth, in two ways:
* **Chat engagement in GA4.** See how many visitors open the chat and send messages, and build funnels from chat to purchase, alongside the rest of your traffic.
* **Revenue attribution in Octocom.** Connect your GA4 property to Octocom to compare revenue, order value and conversion between shoppers who chatted and shoppers who didn't, in **Metrics -> Sales**.
Setup takes three steps:
1. Make sure the widget's events reach GA4. With gtag.js this is automatic. With Google Tag Manager, add a few triggers and tags.
2. Register the `octocom_chatted` user property as a custom dimension in GA4.
3. Optionally, connect GA4 to Octocom to see the revenue split in your Octocom metrics.
Octocom also records purchases itself and links each one to the visitor who
chatted: automatically for [Shopify
stores](/docs/integrations/shopify/chat-widget-tutorial#revenue-tracking), and
through [browser session purchases](/docs/commerce/browser-session-purchases)
for any other checkout, counting purchases within 7 days of a conversation.
GA4 instead compares shoppers who ever chatted with those who didn't, so its
totals run higher. When Octocom has no attributed revenue of its own for a
view, **Metrics -> Sales** shows GA4's revenue instead.
Which setup do you have? [#which-setup-do-you-have]
There are two common ways to install GA4:
| Method | How to identify | Setup required |
| ---------------------------- | ------------------------------------------------ | ------------------------------------- |
| **gtag.js** (direct) | You have a `gtag.js` script snippet on your site | **None**: events appear automatically |
| **Google Tag Manager (GTM)** | You have a GTM container script on your site | Create triggers and tags in GTM |
Not sure which one you have? Open your browser's developer console on your site and run:
```javascript
// Check for gtag.js (direct)
!!document.querySelector('script[src*="gtag/js?id=G-"]');
// true = gtag.js is installed → events work automatically
// Check for GTM
!!document.querySelector('script[src*="gtm.js?id=GTM-"]');
// true = GTM is installed → you need to set up triggers
```
You can also check your site's HTML source:
* A script loading from `googletagmanager.com/gtag/js?id=G-XXXXXX` means **gtag.js**.
* A script loading from `googletagmanager.com/gtm.js?id=GTM-XXXXXX` means **GTM**.
What if I have both? [#what-if-i-have-both]
The widget sends each event one way, never both. If the page loads gtag.js for a GA4 property (a `gtag/js?id=G-` script and the `gtag` function), it sends the Option A events through gtag. Otherwise it pushes the Option B events to the `dataLayer` for GTM.
* If gtag.js on the page is configured with the GA4 property where you want chat events, **you're all set**. Events go to the properties configured in gtag.js.
* If you want the events in a GA4 property that gtag.js on the page doesn't send to, add that property to your gtag.js or Google tag configuration.
* GTM triggers on the `UserAction` event (Option B) don't fire on pages with gtag.js, because the widget sends through gtag there instead.
Option A: gtag.js (automatic) [#option-a-gtagjs-automatic]
**No setup required.** The chat widget detects gtag.js on your page and sends events directly to GA4.
These events appear in your GA4 property under **Reports -> Engagement -> Events**:
| Event name | When it fires |
| --------------------------- | ------------------------------ |
| `octocom_chat_open` | Visitor opens the chat widget |
| `octocom_chat_close` | Visitor closes the chat widget |
| `octocom_chat_message_sent` | Visitor sends a message |
All events include the parameter `event_category: "Octocom Chat Widget"`.
Events can take 24 to 48 hours to appear in standard GA4 reports. Open
**Reports -> Realtime** to see them within seconds.
Next, [register the chat user property](#register-the-chat-user-property).
Option B: Google Tag Manager [#option-b-google-tag-manager]
If GA4 is managed through GTM, create triggers and tags that forward the chat widget's events to GA4.
How it works [#how-it-works]
The chat widget pushes events to `window.dataLayer` in this format:
```javascript
window.dataLayer.push({
event: "UserAction",
eventCategory: "Octocom Chat Widget",
eventAction: "Open", // or "Close" / "Send Message"
});
```
The widget pushes these events when the page has no gtag.js for a GA4 property. GTM can listen for them and forward them to GA4, or to any other tag such as the Meta Pixel or LinkedIn.
Events reference [#events-reference]
| eventAction | Description | When it fires |
| -------------- | ------------------ | ------------------------------------------------------- |
| `Open` | Chat window opened | User clicks the launcher or chat opens programmatically |
| `Close` | Chat window closed | User clicks the close button |
| `Send Message` | Message sent | Any user message (first and subsequent) |
Create Data Layer Variables [#create-data-layer-variables]
In GTM, create two Data Layer Variables so you can use the event data in your tags:
1. Go to **Variables -> New -> Data Layer Variable**.
2. Create `eventCategory` with Data Layer Variable Name `eventCategory`.
3. Create `eventAction` with Data Layer Variable Name `eventAction`.
Create triggers [#create-triggers]
Create one trigger per event (or a single trigger for all).
**Example: trigger for "Chat Open"**
1. Go to **Triggers -> New**.
2. Name: `Octocom - Chat Open`
3. Trigger type: **Custom Event**
4. Event name: `UserAction`
5. Fire on: **Some Custom Events**, with the conditions:
* `eventCategory` equals `Octocom Chat Widget`
* `eventAction` equals `Open`
Repeat for:
* `Octocom - Chat Close` (eventAction = `Close`)
* `Octocom - Send Message` (eventAction = `Send Message`)
Create GA4 Event tags [#create-ga4-event-tags]
**Example: GA4 tag for "chat\_open"**
1. Go to **Tags -> New**.
2. Name: `GA4 - chat_open (Octocom)`
3. Tag type: **Google Analytics: GA4 Event**
4. Measurement ID: your GA4 measurement ID (`G-XXXXXXX`).
5. Event name: `chat_open`
6. Optionally, add event parameters:
* `chat_category` = `{{eventCategory}}`
* `chat_action` = `{{eventAction}}`
7. Trigger: `Octocom - Chat Open`
Repeat for:
* `GA4 - chat_close`: event name `chat_close`, trigger `Octocom - Chat Close`
* `GA4 - chat_message_sent`: event name `chat_message_sent`, trigger `Octocom - Send Message`
Forward the chat user property [#forward-the-chat-user-property]
Besides the three events above, the widget pushes a separate dataLayer event when a visitor first sends a message:
```javascript
window.dataLayer.push({
event: "octocom_user_property",
octocom_chatted: "true",
});
```
This sets a **user property** (not an event parameter) called `octocom_chatted`. It persists across sessions and is what revenue attribution uses to separate shoppers who chatted from those who didn't. Without this step, the custom dimension you register below stays empty.
1. **Add a Data Layer Variable** for the property value:
* **Variables -> New -> Data Layer Variable**
* Name: `octocom_chatted`
* Data Layer Variable Name: `octocom_chatted`
2. **Add a trigger** for the user-property push:
* **Triggers -> New**
* Name: `Octocom - User Property`
* Trigger type: **Custom Event**
* Event name: `octocom_user_property`
* Fire on: **All Custom Events**
3. **Add a GA4 Event tag** that sets the user property:
* **Tags -> New**
* Name: `GA4 - octocom_chatted (Octocom)`
* Tag type: **Google Analytics: GA4 Event**
* Measurement ID: your GA4 measurement ID (`G-XXXXXXX`).
* Event name: `octocom_user_property` (any name works; this tag exists to carry the user property)
* Under **User Properties**, add `octocom_chatted` = `{{octocom_chatted}}`
* Trigger: `Octocom - User Property`
Publish [#publish]
Publish your GTM container. Events and the user property start flowing to GA4.
Register the chat user property [#register-the-chat-user-property]
The widget sets a user property called `octocom_chatted` on visitors who send a message. It persists across sessions, so you can compare conversion rates and revenue between visitors who used the chat and those who didn't.
The widget pushes the property into the `dataLayer`, but it only reaches GA4
once you complete [Forward the chat user
property](#forward-the-chat-user-property) in Option B. Registering the custom
dimension alone is not enough.
For GA4 to make the property available in reports and to Octocom, register it as a custom dimension (a one-time setup):
1. In Google Analytics, go to **Admin -> Custom definitions -> Custom dimensions**.
2. Click **Create custom dimension**.
3. Configure it:
* Dimension name: `Octocom Chatted`
* Scope: **User**
* User property: `octocom_chatted`
4. Click **Save**.
The custom dimension can take 24 to 48 hours to appear in reports. Data is
collected from the moment you register it, not before.
Connect GA4 to Octocom [#connect-ga4-to-octocom]
Connecting your GA4 property lets Octocom read your revenue data and show it in **Metrics -> Sales**, split between shoppers who chatted and shoppers who didn't. No code is required.
**Before you start:** your GA4 property must receive ecommerce `purchase` events (see [below](#what-if-i-dont-have-ga4-ecommerce-tracking)), and the `octocom_chatted` custom dimension must be registered.
Give Octocom read access in GA4 [#give-octocom-read-access-in-ga4]
1. Open [Google Analytics](https://analytics.google.com/) and select the property that tracks your website and checkout.
2. Click **Admin** (the gear icon in the bottom left).
3. Under your property settings, click **Property access management**.
4. Click **+** in the top right corner and select **Add users**.
5. Enter this email address:
```
octocom-ga4-reader@octocom.iam.gserviceaccount.com
```
6. Set the role to **Analyst**. The **Viewer** role can't read revenue metrics.
7. Click **Add**.
Find your GA4 Property ID [#find-your-ga4-property-id]
In GA4, go to **Admin -> Property settings** and copy the numeric **Property ID**, for example `251601386`. This is not the `G-XXXXXXX` measurement ID.
Connect it in Octocom [#connect-it-in-octocom]
In Octocom, open **Settings -> Workspace -> Integrations -> Google Analytics 4**, paste the number into **GA4 Property ID** and click **Connect**.
Octocom tests the connection before saving and tells you exactly what to fix if something is missing: the property ID can't be found, the service account has no access or only the Viewer role, or the `octocom_chatted` dimension isn't registered. Right after setup it may report that it is connected but hasn't seen any visitors who chatted yet. Revenue appears once shoppers chat and the widget reports them.
What Octocom reads [#what-octocom-reads]
With Analyst access, Octocom runs read-only reports on your property. It reads daily totals of users, purchasers, purchase revenue and transactions, split by whether the visitor chatted (`octocom_chatted`). It does not read data about individual visitors, and it does not change your property's settings, events or tags.
Octocom refreshes these numbers every hour for the last 30 days up to yesterday, so purchases that GA4 reports late still correct earlier days. In **Metrics -> Sales** you can then compare:
* revenue from shoppers who chatted and from those who didn't,
* conversion rate for both groups,
* average order value for both groups.
What if I don't have GA4 ecommerce tracking? [#what-if-i-dont-have-ga4-ecommerce-tracking]
Revenue attribution needs your GA4 property to receive ecommerce events, specifically `purchase`. To check, go to **Reports -> Monetization -> Ecommerce purchases** in GA4. If you see data there, you're all set.
**Shopify stores:** ecommerce tracking is usually enabled through Shopify's built-in GA4 integration. If you don't see purchase data in GA4, make sure GA4 is connected in your Shopify admin under **Online Store -> Preferences**.
**Other platforms (WooCommerce, Magento, custom and so on):** ecommerce tracking is set up manually or through a plugin. Your platform may offer a GA4 integration: check its documentation for "GA4 ecommerce". With a custom checkout, your development team needs to implement the GA4 [ecommerce events](https://developers.google.com/analytics/devguides/collection/ga4/ecommerce), specifically `purchase`.
Using events in GA4 [#using-events-in-ga4]
Once events are flowing, through gtag.js or your GTM setup, here's how to use them.
Track chat engagement [#track-chat-engagement]
* Go to **Reports -> Engagement -> Events** to see event counts.
* Example metric: chat engagement rate = (chat opens / page views) x 100.
* Break it down by page, device or traffic source.
Build a conversation funnel [#build-a-conversation-funnel]
Use **Explore -> Funnel exploration**:
1. Step 1: `chat_open` (or `octocom_chat_open` with gtag.js)
2. Step 2: `chat_message_sent` (or `octocom_chat_message_sent`)
3. Step 3: your main conversion (purchase, lead submission and so on)
This shows the drop-off between opening the chat, engaging and converting.
Mark as a key event [#mark-as-a-key-event]
If you treat chat engagement as a micro-conversion, mark the chat event as a **key event** (GA4's name for a conversion):
1. Go to **Admin -> Data display -> Events**.
2. Find your chat event.
3. Mark it as a key event.
Custom reports [#custom-reports]
Useful dimensions to combine with chat events:
* **Page URL:** which pages drive the most chat interactions.
* **Traffic source:** which channels (Google Ads, social, email) engage most with chat.
* **Device:** desktop and mobile chat usage.
Use **Explore -> Free form** with `eventName`, `pageLocation` and `sessionSourceMedium` as dimensions.
Using events for other tags in GTM [#using-events-for-other-tags-in-gtm]
With GTM, you can reuse the same triggers to fire other tags:
* **Meta Pixel:** fire a `Lead` event when `Send Message` fires.
* **LinkedIn Insight Tag:** create a custom conversion for chat engagement.
* **Remarketing:** build audiences of visitors who opened the chat but didn't send a message.
Technical notes [#technical-notes]
* The chat widget sends the events automatically. No code changes are needed on your site.
* When the page loads gtag.js for a GA4 property, events are sent through `window.gtag()`. Otherwise they are pushed to `window.dataLayer`.
* The `octocom_chatted` user property is set once per page load, on the visitor's first message.
* With the web chat `logLevel` set to `debug` (see [Configure the chat widget](/docs/channels/web-chat/configuration)), the widget logs each event to the browser console, which helps when verifying the setup.
# Commerce overview
Commerce is what Octocom adds for selling online. The AI agent knows your product catalog and your customers' orders, so it can recommend the right product, say where a parcel is and cancel an order that hasn't shipped. Storefront tools put the same catalog to work on your own pages, and revenue reporting shows what your conversations earn.
Online stores and subscription brands run on the same AI agent, help desk and channels as every other business. This section covers what they get on top.
Orders, returns and cancellations [#orders-returns-and-cancellations]
Most store support comes down to a few questions: "Where is my order?", "Can I change or cancel it?" and "How do I return this?". The AI agent answers them end to end. It looks up the order during the conversation, then replies with its status, items and tracking link.
Changes are actions too: cancelling an unshipped order, changing the delivery address, starting a return or issuing a refund. Each one runs inside the [workflow](/docs/ai-agent/workflows) for that situation. The workflow can ask the customer to confirm first, and the action checks your eligibility rules in code before anything changes.
Let customers cancel Shopify orders that haven't shipped yet. Ask them to
confirm first, then tag the conversation order-cancelled.
Connecting Shopify, WooCommerce, Magento 2, BigCommerce, Shoptet Premium or PrestaShop adds ready-made order lookups and an Orders panel in the help desk sidebar. Any other order system works through [actions](/docs/ai-agent/actions). On Shopify, an action can do anything the Shopify Admin API allows. See [Order tracking](/docs/commerce/order-tracking) and [Shopify custom actions](/docs/integrations/shopify/custom-actions).
To turn refund requests into exchanges, store credit or a pause, follow [Reduce refunds with retention offers](/docs/guides/refund-retention).
Products and recommendations [#products-and-recommendations]
Octocom keeps a searchable copy of your product catalog. The AI agent uses it to recommend products from a customer's own description, such as "a warm waterproof jacket for hiking", and to answer questions about price, stock, sizes and specifications. In web chat, it shows products as cards with a photo, price and link.
Connecting Shopify, WooCommerce, BigCommerce, Shoptet Premium or PrestaShop syncs the catalog automatically. Any other source syncs through a short parser that an AI agent writes for you: a product feed, an ERP, a PIM or any API.
Our products are in a feed at [https://example.com/feeds/products.xml](https://example.com/feeds/products.xml). Write a
product sync for it and show me a dry run before you turn it on.
See [Product catalog](/docs/commerce/product-catalog).
Subscriptions [#subscriptions]
Connecting Recharge, Loop or WooCommerce Subscriptions adds ready-made actions to look up and cancel subscriptions. It also adds a Subscriptions panel in the help desk sidebar with a **Cancel subscription** button that asks for confirmation. Kaching, CheckoutChamp and any other subscription system connect through actions, so the AI agent can pause, skip, reschedule or cancel wherever your platform's API allows it.
See [Subscription widgets](/docs/help-desk/subscription-widgets) and the [Recharge](/docs/developers/python-helpers/recharge-subscriptions), [Loop](/docs/developers/python-helpers/loop-subscriptions) and [WooCommerce Subscriptions](/docs/developers/python-helpers/woocommerce-subscriptions) helpers.
On your storefront [#on-your-storefront]
Three features put Octocom on your store's own pages, using the same catalog as the AI agent:
* **AI suggestion buttons** show product-specific questions next to **Add to cart**. One tap opens the chat with the question filled in.
* **Storefront search** replaces your store's search bar with search that understands synonyms, translations and product specs, with voice and photo search.
* **Virtual try-on** lets shoppers upload a photo and see a product on themselves or in their room.
Add a virtual try-on button next to Add to cart on our product pages, but not
for swimwear.
Revenue from conversations [#revenue-from-conversations]
Octocom links purchases to the visitors who chatted, so you can see the revenue that conversations influence under **Metrics -> Sales**. A purchase counts when it happens within 7 days of a conversation in the same browser.
Shopify checkouts are tracked automatically once the store is connected. Other stores record purchases from their checkout page. You can also connect Google Analytics 4 to compare revenue from shoppers who chatted with those who didn't.
Connect your store [#connect-your-store]
Ready-made connectors give your actions each platform's own API, not a fixed menu of functions:
* **Store platforms:** [Shopify](/docs/integrations/shopify), [WooCommerce](/docs/integrations/woocommerce), [BigCommerce](/docs/integrations/bigcommerce), [Magento](/docs/integrations/magento/installation), [PrestaShop](/docs/integrations/prestashop/installation), [Shoptet Premium](/docs/developers/python-helpers/shoptet-orders) and [CheckoutChamp](/docs/integrations/checkoutchamp).
* **Subscriptions and payments:** [Kaching](/docs/integrations/kaching), [Stripe](/docs/integrations/stripe), Recharge and Loop.
* **Marketplaces:** [Amazon](/docs/channels/amazon) and [Whop](/docs/channels/whop) connect as channels.
Your store doesn't need a connector at all. Custom storefronts, ERPs, warehouse and shipping systems connect through the same building blocks as any other system. See [Connect any system](/docs/overview/connect-any-system), or browse every connector under [Integrations](/docs/integrations).
Set it up [#set-it-up]
Copilot in the dashboard, or your own AI agent through [Octocom MCP](/docs/developers/mcp), can configure everything in this section. It writes the catalog sync, builds and tests order actions, adds them to workflows and places storefront features on your pages. Octocom's solution engineers can review the setup, test it with you and help design complex flows. See [Set up Octocom with AI](/docs/overview/set-up-with-ai).
Explore [#explore]
For developers and AI agents [#for-developers-and-ai-agents]
* [Product sync parsers](/docs/developers/product-sync-parsers): sync a catalog from any product feed or API.
* [Python helpers](/docs/developers/python-helpers): order lookups for each store platform, plus subscription and parcel tracking helpers.
* [Storefront search SDK](/docs/commerce/storefront-search-sdk): build your own search interface on Octocom's search.
* [Browser session purchases](/docs/commerce/browser-session-purchases): record checkouts from any store for revenue attribution.
# Order tracking
Order tracking lets the AI agent answer questions such as *"Where's my order?"*, *"Has #12345 shipped?"* or *"What did I order with this email?"* on its own. It looks the order up in your system during the conversation, then replies with the status, the items and the tracking link. Order questions are often the largest share of a store's support volume, so this is usually the first thing to automate.
The AI agent gets order data through [actions](/docs/ai-agent/actions). Store platforms come with ready-made lookup actions, and any other order system works the same way through an action that calls the API you already have.
Store platforms: ready-made lookups [#store-platforms-ready-made-lookups]
Connecting **Shopify**, **WooCommerce**, **Magento 2**, **BigCommerce**, **Shoptet Premium** or **PrestaShop** adds two order lookup actions to the business:
* `getOrderDetailsByOrderId` finds an order by its order number.
* `getOrderDetailsByEmail` finds a customer's orders by email address.
It also adds an **Orders** panel to the help desk sidebar, so your team sees the same order data next to each conversation. See [Order widgets](/docs/help-desk/order-widgets).
To use the lookups, add them to the [workflow](/docs/ai-agent/workflows) that handles order questions. Both are editable copies, not a fixed integration. Copilot can change what they return, combine them with your shipping provider's tracking, or require the email used for the order before sharing any details.
Add the order lookups to the workflow that handles order questions. Before
sharing any details, check that the email the customer gives matches the
order.
On Shopify, an action can read anything the Shopify Admin API exposes. See [Shopify custom actions](/docs/integrations/shopify/custom-actions).
Any other order system [#any-other-order-system]
Orders that live somewhere else work just as well: an ERP, an order management system, a warehouse system or your own backend. **You don't need to build a special endpoint or match any schema.** Whatever API you already have for orders is enough, whether it is REST, GraphQL, a partner feed or anything else reachable over HTTPS. A short [action](/docs/ai-agent/actions) wraps it:
1. It receives a lookup value from the AI agent, such as an email address, order number or phone number.
2. It calls your API the way your API expects, with its own authentication, headers and query parameters.
3. It returns the fields you want the AI agent to know about.
The AI agent then uses that data however the conversation needs: a status update, a summary of the items, a tracking link. You control what comes back and can change it at any time without touching your own system. If a back office has no usable API, [browser automation](/docs/developers/browser-automation) can look the order up the way a person would.
Ask [Copilot](/docs/developers/copilot) or your own AI agent through [Octocom MCP](/docs/developers/mcp) to build it. Describe your order API, and it creates the actions, tests them with real order numbers and adds them to your workflow.
Our orders live in our ERP. The API docs are at
[https://erp.example.com/api-docs](https://erp.example.com/api-docs) and the key is saved as the secret
ERP\_API\_KEY. Build order lookups by email and by order number, test them with
order 58213 and add them to the order status workflow.
Octocom's solution engineers can also review your order API with you and help design multi-step lookups.
One action per lookup type [#one-action-per-lookup-type]
Instead of one large action with optional filters, use a **separate action for each way of looking an order up**. It makes it obvious to the AI agent which one applies, and keeps each action simple.
| Action | Argument | Priority | Why |
| ------------------ | -------- | ----------- | -------------------------------------------------------------------------------------------- |
| `getOrdersByEmail` | email | **Minimum** | Most customers can give you their email. Cover this and you can answer most order questions. |
| `getOrderById` | orderId | Bonus | Faster, more specific lookup when the customer has their order number handy. |
| `getOrdersByPhone` | phone | Bonus | Useful for phone calls or when customers can't remember which email they used. |
Each action returns the same kind of data, just looked up a different way. The AI agent picks the right one based on what the customer provides.
What to return [#what-to-return]
The minimum useful fields are the order ID, its status, the customer's email or phone, the items, the total and the currency. High-value extras are the tracking number and tracking link (for "where is it?"), the shipping address (for delivery questions) and the last update time (for status timelines).
Always return a **list** of orders, even for a lookup that finds one order. It keeps every lookup consistent for the AI agent and your workflows.
To match phone numbers reliably, normalize both the customer's input and the stored value to the full international format before comparing them. For developers, [`normalize_phone_number`](/docs/developers/python-helpers/normalize-phone-number) does this.
Protect customers' order details [#protect-customers-order-details]
Order details include names and addresses, so decide what a customer must prove before the AI agent shares them. A common rule is to require the order number together with the email or phone number used for the order, and to check that match inside the action rather than only in the workflow's instructions. See [Customer authentication](/docs/security/customer-authentication).
Return only what the customer is allowed to see. Whatever an action returns, the AI agent can read and may repeat.
Parcel tracking [#parcel-tracking]
Some order systems only know that a parcel was handed to a carrier. For supported carriers, such as DHL and USPS, an action can also check the carrier's live tracking, so the AI agent can answer "has it arrived?" with the latest scan. See [`track_shipment`](/docs/developers/python-helpers/track-shipment).
For developers and AI agents [#for-developers-and-ai-agents]
The rest of this page is a starting point for a Python action against your own order API. For how Python actions work, declare arguments, connect to workflows and handle errors, see [Custom actions](/docs/developers/custom-actions).
Suggested return shape [#suggested-return-shape]
You can return any fields you find useful. This is a reasonable starting point; add, remove or rename fields to match your business.
```python
# Example return from getOrdersByEmail / getOrderById / getOrdersByPhone
[
{
"id": "ORD-12345",
"status": "shipped", # pending | processing | shipped | delivered | cancelled
"created_at": "2024-10-10T14:21:00Z",
"updated_at": "2024-10-11T09:00:00Z",
"customer": {
"email": "jane@example.com",
"phone": "+14151234567",
"name": "Jane Doe",
},
"shipping_address": {
"line1": "123 Main Street",
"city": "San Francisco",
"postal_code": "94103",
"country": "US",
},
"items": [
{
"sku": "ABC123",
"name": "Wireless Earbuds",
"quantity": 1,
"price": 59.99,
},
],
"total": 59.99,
"currency": "USD",
"tracking_number": "1Z999999",
"tracking_url": "https://www.ups.com/track?tracknum=1Z999999",
},
]
```
Skeleton: getOrdersByEmail [#skeleton-getordersbyemail]
```python
import urllib.request, urllib.parse, json
def execute_action(context):
email = context["args"]["email"]
url = "https://api.your-store.com/orders?" + urllib.parse.urlencode({"email": email})
req = urllib.request.Request(url, headers={
"Authorization": "Bearer YOUR_API_KEY",
"Accept": "application/json",
})
with urllib.request.urlopen(req, timeout=10) as resp:
raw_orders = json.loads(resp.read())
# Reshape into whatever you want the bot to see.
return [
{
"id": o["order_number"],
"status": o["fulfillment_status"],
"created_at": o["created_at"],
"customer": {"email": o["email"], "name": o.get("customer_name")},
"items": [
{"name": li["title"], "quantity": li["qty"], "price": li["price"]}
for li in o["line_items"]
],
"total": o["total_price"],
"currency": o["currency"],
"tracking_number": o.get("tracking_number"),
"tracking_url": o.get("tracking_url"),
}
for o in raw_orders
]
```
In a real action, don't write the API key into the code. Store it as an organization [secret](/docs/developers/secrets) and read it with [`get_secret`](/docs/developers/python-helpers/get-secret), for example `get_secret("ORDERS_API_KEY")`.
`getOrderById` and `getOrdersByPhone` follow the same pattern with a different filter. For phone lookups, normalize the number first with [`normalize_phone_number`](/docs/developers/python-helpers/normalize-phone-number).
For store platforms, the order helpers return orders in the platform's own format: [Shopify](/docs/developers/python-helpers/shopify-orders), [WooCommerce](/docs/developers/python-helpers/woocommerce-orders), [Magento](/docs/developers/python-helpers/magento-orders), [BigCommerce](/docs/developers/python-helpers/bigcommerce-orders), [Shoptet](/docs/developers/python-helpers/shoptet-orders) and [PrestaShop](/docs/developers/python-helpers/prestashop-orders).
# Product catalog
Octocom keeps a searchable copy of each business's product catalog. The AI agent uses it to recommend products, answer questions about price, stock, sizes and specifications, and send customers straight to the right product page. [Storefront search](/docs/commerce/storefront-search) and [virtual try-on](/docs/commerce/virtual-tryon) work from the same catalog.
The catalog comes from wherever your product data already lives. Connecting a supported store platform syncs it automatically. Any other source syncs the same way once an AI agent has written a short parser for it, whether it is a product feed, an ERP, a PIM or any API.
What the AI agent does with your catalog [#what-the-ai-agent-does-with-your-catalog]
* **Recommends products from a description.** A customer can ask for "a warm waterproof jacket for hiking in the rain" and get matching products, not only exact name matches.
* **Finds exact products.** It looks products up by name, SKU, product code or a pasted product link.
* **Answers from your product data.** Price, sale price, stock, variants, sizes, ingredients, dimensions: anything your product data contains.
* **Respects stock.** By default it recommends only products that are in stock. See [Stock and availability](#stock-and-availability).
* **Filters on request.** When the customer asks for a price range, sale items or a label such as "vegan", it narrows the search accordingly.
* **Shows product cards in web chat.** Each card has the product's photo, name, price and a link, taken straight from the catalog.
Before it mentions a product, the AI agent reads that product's full details, so prices and links come from your data, not from memory. When [storefront search](/docs/commerce/storefront-search) is enabled, the AI agent searches through it too, so the chat recommends products in the same order your search bar shows them.
How your catalog gets into Octocom [#how-your-catalog-gets-into-octocom]
Connect a store platform [#connect-a-store-platform]
Connecting **Shopify**, **WooCommerce**, **BigCommerce**, **Shoptet Premium** or **PrestaShop** installs a ready-made catalog sync for that platform and turns on automatic syncing. The first sync starts within minutes, with nothing else to set up.
The ready-made sync is a starting point, not a fixed integration. Copilot can change it for your store, for example to read extra product fields, add [product tags](#product-tags) or skip products you don't want the AI agent to recommend. On Shopify, an active product that is not published to the Online Store sales channel stays out of storefront search, while the AI agent can still answer questions about it.
See [Integrations](/docs/integrations) for how to connect each platform.
Any other source: a feed, an API or your own system [#any-other-source-a-feed-an-api-or-your-own-system]
Every other source syncs through a **product sync parser**: a short script that reads your source and maps each product into Octocom's catalog. You don't need to write it. Ask [Copilot](/docs/developers/copilot) or your own AI agent through [Octocom MCP](/docs/developers/mcp), and point it at your source:
* a product feed URL in XML, JSON or CSV, such as an export from your e-commerce system, Google Merchant Center or Meta Commerce Manager,
* a store platform without a ready-made sync, such as Magento,
* an ERP, PIM or inventory system with an API,
* a SQL Server database your systems already use.
Our products are in a feed at [https://yourstore.com/feeds/products.xml](https://yourstore.com/feeds/products.xml). Write
a product sync for it and show me a dry run before you turn it on.
The agent reads a sample of your data, writes the parser and runs a dry run that shows exactly which products would be imported, without touching your live catalog. Once the output looks right, it saves the parser and automatic syncing starts. Every change to a parser is versioned and can be restored. If your server only accepts requests from known IP addresses, Octocom can fetch your data through a fixed outbound IP.
A **feed** is a URL that returns a structured file with up-to-date data about your products, usually all of them. For example: `https://yourstore.com/feeds/products.xml`.
[Product sync parsers](/docs/developers/product-sync-parsers) documents the
parser contract, the product schema, runtime helpers, dry runs and worked
examples for static feeds and paginated APIs.
What to include in your product data [#what-to-include-in-your-product-data]
The AI agent can only answer from the data you give it. If a piece of information isn't in your product data, the AI agent cannot infer or guess it, so be as complete as you can.
The essentials [#the-essentials]
Every product needs the following for useful recommendations:
| Information | What it is |
| ----------- | ------------------------------ |
| Name | Product name |
| Description | Product description |
| Price | Current price |
| URL | Link to the product page |
| Images | At least one product image URL |
Your field names don't need to match these. A column called `product_name` or `name` is fine, as long as it contains the right data.
More detail means better answers [#more-detail-means-better-answers]
Additional fields improve recommendations and let the AI agent answer more detailed questions. Include them as dedicated fields or as custom attributes (often called metafields).
| Field | Useful for, for example |
| ------------------ | ------------------------------------------ |
| Ingredients | Supplements, cosmetics, food |
| Usage instructions | Electronics, health products, beauty items |
| Dimensions | Furniture, apparel |
A suggested structure [#a-suggested-structure]
You don't need to follow this exactly, but data structured along these lines is the quickest to sync and gives the best results:
* Product name
* Product URLs
* Variants, each with:
* SKU
* Variant URL
* Stock quantity
* Whether it can be sold when out of stock
* Whether it is in stock
* Short and long description
* Current price, regular price (if any) and whether it is on sale
* Custom attributes (metafields) as key-value pairs
* Images, each with its URL, optional alt text and whether it is the primary image
* Collections or categories the product belongs to, each with a name, URL-friendly slug, URL (if any) and optional descriptions
* Product-level custom attributes (metafields)
* Product tags (optional, see below)
* Product images, each with its URL, optional alt text and whether it is the primary image
Product tags [#product-tags]
If your data already labels products in ways customers ask about (`vegan`, `clearance`, `made in italy`, `prescription required`), the sync can map those labels to **product tags**. The AI agent uses tags as an exact filter: asked for "something vegan", it narrows the catalog to products tagged `vegan` instead of hoping the word appears in the descriptions.
Before you decide what to tag:
* **Keep the list short and shopper-facing.** Tags work best when there are a handful and each one names something a customer would say out loud. Your full category tree doesn't need tags; the AI agent already reads categories and descriptions.
* **Name tags the way a shopper would.** The AI agent sees the tag names, so `gift-suitable` works and `flag_7` doesn't. For anything that isn't self-explanatory, such as tags for markets or membership tiers, add a [bot rule](/docs/ai-agent/bot-rules) that says what each tag means and when to use it.
* **Keep the spelling stable.** Tags are matched exactly, ignoring case and extra spaces, so `gluten-free` and `gluten free` are two different tags.
* **They apply from the next sync.** Tags become filterable once your catalog has synced with them.
Each product can carry up to 32 tags of up to 64 characters. The AI agent is offered the 150 most-used tags in your catalog.
Keeping the catalog fresh [#keeping-the-catalog-fresh]
Catalog settings are on the **Products** page (**Settings -> Automation -> Knowledge**, then **View Products**), under **Settings**:
* **Automatic sync** refreshes products, prices and stock from your source on a schedule. Turning it off keeps the existing catalog.
* **Sync interval** sets the minimum time between automatic syncs: 3, 6, 12 or 24 hours. Each sync is scheduled between that interval and twice its length. Catalogs with more than 100,000 products sync at most every 12 hours.
The **Products** page shows the status of the last sync and lets you start one straight away. Copilot can also start a sync, or a dry run that checks the output without changing your live catalog. To see exactly how your products are read and mapped, open **Advanced · Sync code** on the **Settings** page; ask Copilot to make any change to it.
If you disconnect a store platform, the products already synced stay in the catalog, except on BigCommerce, where uninstalling the app also removes them. Reconnecting the store turns automatic syncing back on.
Stock and availability [#stock-and-availability]
By default, the AI agent searches only products that are in stock. Two settings on the same **Settings** page change this:
* **Always treat products as in stock** ignores stock status entirely. Use it for digital products or services without limited inventory.
* **Include out-of-stock products in text search** lets searches by name, brand or SKU find unavailable products, so the AI agent can tell a customer that the item they asked about is out of stock. Recommendations from a description still use stock status.
[Storefront search](/docs/commerce/storefront-search) has its own **Hide out-of-stock products** switch for shoppers on your store.
Check what the AI agent sees [#check-what-the-ai-agent-sees]
The **Products** page lets you search the synced catalog the way the AI agent does (semantic or text search) and filter it by stock, sale status and price. If a product is missing or its details look wrong, the fix is in the source data or the sync, not in the AI agent's instructions.
To test real questions end to end, run a [test conversation](/docs/ai-agent/testing). Octocom's solution engineers can also review a sample of your product data and help you get the sync right: [contact us](mailto:info@octocom.ai).
# Storefront search SDK
import { Accordions, Accordion } from "fumadocs-ui/components/accordion";
The storefront search SDK is a JavaScript client for Octocom's [storefront search](/docs/commerce/storefront-search). Use it when you render search results in your own code, such as a React storefront, a custom results page or a headless front end. You get Octocom's search without its page rendering. It ships inside the Octocom script already on your store, so there is no package to install and no credential in your code.
Storefront search has two ways in:
* **The widget** is the no-code path: you write HTML, mark it up with `data-octocom-*` attributes, and the Octocom script binds it to the search pipeline and renders into it. Most stores want this. It's covered on the [Storefront search](/docs/commerce/storefront-search) page.
* **The SDK**, on this page, is the same search client exposed as a JavaScript object you call yourself.
Both talk to the same endpoints and both are already on the page.
Getting the client [#getting-the-client]
The SDK ships **inside the Octocom embed script** you already have on your store. Once it loads on a business with storefront search configured, it publishes the client at `window.octocomSearch`.
The script loads asynchronously, so your code may run first. Handle both cases:
```js
function withSearch(fn) {
if (window.octocomSearch) return fn(window.octocomSearch);
window.addEventListener("octocom:search-ready", (e) => fn(e.detail), {
once: true,
});
}
withSearch(async (search) => {
const { results } = await search.search("black office chair");
console.log(results);
});
```
In React, the same thing as a hook:
```jsx
function useOctocomSearch() {
const [client, setClient] = useState(() => window.octocomSearch ?? null);
useEffect(() => {
if (client) return;
const onReady = (e) => setClient(e.detail);
window.addEventListener("octocom:search-ready", onReady, { once: true });
return () => window.removeEventListener("octocom:search-ready", onReady);
}, [client]);
return client;
}
```
The client is delivered with the embed script rather than published separately, and that's deliberate: the key handling, the API origin and the version are all managed for you. You never hold a credential, never configure a base URL, and never have an SDK version that has drifted from the API.
The trade is that the client is only available where the embed script is: in a browser, on a page of your store. If you need search **server-side** (server-rendered pages, a mobile app backend, a scheduled job), use the [REST API](/docs/developers/rest-api#product-search) instead. It exposes the same pipeline and is authenticated with your organization's API key.
**Don't reach for the REST API from browser code.** Its key is a secret that grants access to your whole organization, and anything shipped to a browser is public. In the browser, use this SDK: its publishable key is restricted to your websites and designed to be readable in page source.
`window.octocomSearch` appears only when:
* the Octocom embed script is on the page, **and**
* the business has storefront search **enabled** (**Show search on your store** on the **Overview** tab), **and**
* a **publishable search key** has been created for it (**Search key** on the **API access** tab under **Settings -> Storefront -> Storefront Search**), and your storefront allowed under **Allowed websites** (an empty list allows any website). Your own portal pages (`https://.octocom.page`) are always allowed and need no entry.
If the global never shows up, one of those three is missing. A request from an origin that isn't on the key's allowlist gets a `403` (`Origin not allowed`), so check the allowlist after moving to a new domain, adding a staging subdomain or switching to HTTPS.
Put one website on each line of **Allowed websites**: an origin (`https://shop.example.com`), a bare host (`shop.example.com`, treated as HTTPS) or a wildcard subdomain (`https://*.example.com`, which doesn't cover `example.com` itself). Paths are dropped. Entries that could never match, such as `*` or two websites on one line, are refused when you save. To allow any website, leave the list empty.
You don't have to use the widget to use the SDK. Leave every injection point's selector empty, so nothing is injected, and you still get a client.
A [storefront preview link](/docs/commerce/storefront-search#preview-on-your-live-store) also makes the client available while search is disabled. The preview must belong to the same business as the installed widget. It does not switch the client to another business's templates or catalog, and its saved state is scoped to that business in the current browser tab.
Methods [#methods]
Every method except `trackClick` returns a promise and takes an optional `signal` (an `AbortSignal`) so you can cancel on unmount. `trackClick` is fire-and-forget and returns nothing.
| Method | What it does | Cost |
| -------------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------- |
| `suggest(query, opts)` | The search-as-you-type panel. Query completions, a few top products, category/brand chips, a count. | Cheap, safe per keystroke. |
| `search(query, opts)` | Full pipeline for a submitted query. Ranked results only. | A full search. |
| `searchPanel(query, opts)` | Full pipeline, answered in `suggest`'s shape: results **and** chips, count, refinements. | Same as `search`. |
| `voiceSearch(blob, opts)` | Transcribe a recorded utterance and search for it, in one round trip. | A search + transcription. |
| `transcribe(blob, opts)` | Transcript only, for dictate-and-review. | Transcription. |
| `imageSearch(blob, opts)` | Search by photo. | A search + a vision call. |
| `similarProducts(product, opts)` | "You may also like" for a product page. Pass `{ url: location.href }` or a result's `id`. | Cheapest, no AI call. |
| `getUiConfig(opts)` | The business's dashboard-configured widget HTML. Only needed if you're doing your own binding. | One indexed read. |
| `trackClick(click)` | Reports that the shopper opened one of a search's results. Returns nothing, never throws. | Free, no AI call. |
Search-as-you-type [#search-as-you-type]
`suggest()` is built to run on every (debounced) keystroke. It's a keyword probe, not a full search, and makes no AI call, so it's cheap and fast. Its job is to produce a **dropdown of query strings**, not results.
```js
input.addEventListener("input", async () => {
const panel = await search.suggestLatest(input.value);
if (!panel) return; // superseded by a newer keystroke
render(panel); // { suggestions, products, categories, brands, totalCount }
});
```
`suggestions` are full query strings ready to submit. `products` is a preview handful from the same probe: enough for a dropdown column, not a results page. `categories` and `brands` are navigable chips. `totalCount` is how many products match the typed words at all.
Submitted searches [#submitted-searches]
When the shopper hits Enter, you have two choices.
`search()` gives you the ranked results and nothing else:
```js
const { results, relaxed } = await search.search(query, { topK: 24 });
```
`searchPanel()` runs the **same pipeline** but answers in the shape `suggest()` uses: the results plus the chips, the count and refinements, all describing the results you're about to show:
```js
const panel = await search.searchPanel(query, { topK: 24 });
// { products, suggestions, categories, brands, totalCount, relaxed }
```
Use `searchPanel()` when your results page has a facet rail, a "N results" headline, or "narrow your search" chips. Getting them this way is one request. The alternative, calling `search()` and `suggest()` together, costs a wasted search's worth of latency, and its chips would describe the probe's result set rather than the ranked one you're displaying.
Two things to know about it:
* **It is a full search.** Same cost, same rate limit, same latency as `search()`. It does not belong on a keystroke; that's what `suggest()` is for.
* **`totalCount` is not `products.length`.** The ranked list is capped by `topK`; `totalCount` answers "how many products match at all", which is what a results headline wants. It agrees with the page: it is 0 when low-confidence results were hidden, it never exceeds what a relevance cut kept, and it is `null` (hide the number) when it can't be counted reliably.
`relaxed: true` on either means exact retrieval came back thin and the results were recovered by relaxing the query. Label them "similar products" rather than presenting them as exact matches.
Reporting clicks [#reporting-clicks]
Every search response carries a `searchId`. Pass it back when the shopper opens one of that search's results, so your search stats show which queries lead somewhere and which ones shoppers look at and abandon:
```js
const { results, searchId } = await search.search(query, { topK: 24 });
// …in your result card's click handler:
search.trackClick({ searchId, productId: hit.id, position: index });
```
`position` is the result's 0-based index **in the response that produced it**. Pass it wherever you can: "shoppers click things" and "shoppers click the first thing" are different findings, and `position` is what separates them. If you filter or reorder results in the browser, still send the index from the response rather than the on-screen one, so every click is measured against the same ranking.
`trackClick` is deliberately undemanding. It returns immediately, never throws, and is sent with `keepalive` so it survives the page navigating away. Call it and then let your link do what it was going to do. Reporting the same product twice for one search is harmless; it counts once. A click quoting a `searchId` older than 14 days is ignored silently.
If you use the injected widget rather than binding results yourself, this is already wired for you.
Declare searches a shopper did not submit [#declare-searches-a-shopper-did-not-submit]
Every `search()` and `searchPanel()` call counts as a shopper's search in your daily search stats. If your code runs one without a shopper submitting anything, say so with `intent`, otherwise it lowers your click-through rate and fills your top queries with partial words:
```js
// Filling a "popular products" row when the page opens:
const { products } = await search.searchPanel("dresses", {
topK: 8,
intent: "preload",
});
// A dropdown driven by the full pipeline on each keystroke:
const panel = await search.searchPanelLatest(input.value, {
intent: "typeahead",
});
```
| `intent` | Use it for |
| ------------------ | ----------------------------------------- |
| `submit` (default) | A shopper asking for results. |
| `typeahead` | Results that update as the shopper types. |
| `preload` | Content the page loads by itself. |
`typeahead` and `preload` mainly change the reporting. To keep them cheap per keystroke, a query your store has not seen before is ranked without the slower AI query understanding, so its first results can differ slightly from the same query submitted. Those searches stay out of the daily stats tables (`search_daily_stats` and `search_query_daily_stats`), and a merchant redirect never navigates from them. They are still logged, so a report chart that reads the raw `search_query_logs` or `search_click_logs` tables counts them until it filters them out: see [Storefront search tables](/docs/developers/analytics-sql#storefront-search-tables). For a dropdown, prefer `suggest()`: it is built for keystrokes, costs far less, and is not counted.
Merchant redirects [#merchant-redirects]
A merchant can point a keyword straight at a page: "black friday" should land on `/black-friday/`, not on a search for products whose names happen to contain those words. When one matches, submitted searches carry a `redirect` field.
```js
const { results, relaxed, redirect } = await search.search(query, { topK: 24 });
if (redirect?.action === "navigate") {
window.location.href = redirect.url;
return;
}
render(results);
if (redirect) showBanner(`Looking for ${redirect.trigger}?`, redirect.url);
```
**Handle this even if you never render a banner.** On `action: "navigate"` the search does not run and `results` arrives **empty by design**: `redirect` is the only thing separating "we sent them somewhere" from "nothing matched". A client that ignores the field shows a shopper who searched "black friday" an empty state instead of the campaign page.
Read `action` rather than deciding for yourself. It is resolved server-side against the merchant's configuration *and* what your surface is permitted to do, so the same client works for a merchant who wants a banner and one who wants the jump:
| Method | Possible `action` | Why |
| ---------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `search()` | `navigate` or `banner` | The shopper submitted, so sending them somewhere is an answer. Which one is the merchant's call. |
| `searchPanel()` | `banner` only | A renderer built for the dropdown may be driving this per keystroke. Taking over the page mid-word isn't recoverable. |
| `suggest()`, `voiceSearch()`, image and similar-product searches | never present | Redirects aren't resolved on these at all, so there's no `redirect` field to check. |
`banner` is the default for a business that hasn't chosen. The two failure modes aren't symmetric: a banner nobody wanted is ignorable, while a wrong jump throws the shopper off the page with no way back. So the reversible one is what a merchant gets until they ask for the other.
`matchMode` tells you how the rule fired: `exact` matched the whole query, `contains` matched a phrase inside it. `trigger` is the merchant's own spelling, which is what a banner should say back.
Avoiding stale results [#avoiding-stale-results]
Every ranking method has a `*Latest` twin (`searchLatest`, `suggestLatest`, `searchPanelLatest`) that aborts whatever request was in flight and resolves `null` for a response that has since been superseded:
```js
const response = await search.searchPanelLatest(query);
if (response === null) return; // a newer query is already running
```
They share **one** slot, so a keystroke's `suggestLatest` and an Enter's `searchPanelLatest` supersede each other, which is the right behavior for a single search box. Render every non-null result unconditionally and out-of-order responses can't flash over fresh ones.
Errors [#errors]
Failures throw `OctocomSearchError` with a `kind`:
| `kind` | Meaning |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `rateLimited` | HTTP 429. Back off: the caps are per IP and per business. |
| `http` | Any other non-2xx. `403` usually means the origin allowlist. `503` means search is briefly unavailable: retry after a few seconds. |
| `network` | The request never completed. |
Aborts (yours, or a superseded `*Latest` call) surface as a `DOMException` named `AbortError`, not as an `OctocomSearchError`, so "the shopper typed another character" stays distinguishable from "search is down".
On a live storefront, prefer leaving the previous results on screen to clearing them on error.
Panel data on your results page [#panel-data-on-your-results-page]
If you're using the **widget** rather than the SDK, you can still have the chips and count beside your results: add their markers to your Results template (or your Overlay template) and the widget switches to the panel request automatically. No markers, no extra request: templates that don't ask for the data don't pay for it.
| Marker | Behavior |
| ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `data-octocom-panel-categories-container` + `-category-template` | Category chips for the current results. `data-octocom-field="text"` / `"count"` / `"url"`. |
| `data-octocom-panel-brands-container` + `-brand-template` | Brand chips, same fields. |
| `data-octocom-panel-total-count` | Single element: total keyword matches for the query, hidden while unknown. Not the number of cards shown. |
| `data-octocom-refinements-container` + `-refinement-template` | "Narrow your search" chips. `data-octocom-field="text"` / `"role"`. Clicking one runs the refined query. |
| `data-octocom-panel-categories-section` / `-brands-section` / `-refinements-section` | Optional wrapper around a section's heading + container, hidden as a unit when that section is empty. |
| `data-octocom-redirect` | Keyword-redirect banner, shown only when the search matched one. `data-octocom-field="trigger"` / `"url"`. |
The refinement markers are deliberately named differently from the dropdown's `data-octocom-suggestion-*` pair, so a results template can carry both without the widget mistaking one for the other.
Chips are only ever shown for values your catalog feed gives a navigable URL for. If `categories` comes back empty, your feed carries category names but no category links. The same vocabulary still reaches shoppers through refinements, which need no URL.
Choosing a surface [#choosing-a-surface]
| You're building | Use |
| ---------------------------------------------------- | -------------------------------------------------------------------------- |
| A search bar styled with your own HTML | The [widget](/docs/commerce/storefront-search), with no JavaScript at all. |
| A React/Vue results page in the browser | This SDK. |
| Server-rendered results, a mobile app, a backend job | The [REST API](/docs/developers/rest-api#product-search). |
# Storefront search
import { Accordions, Accordion } from "fumadocs-ui/components/accordion";
Storefront search replaces the search on your own store with Octocom's product search. Shoppers get query suggestions as they type, and results that understand synonyms, translations and product specs instead of only exact keyword matches. Filters, voice search and photo search are built in, and everything is styled with your own HTML, so it looks like part of your store.
It's for stores whose search box should do better than "type a word and hope it matches a product title". Think of catalogs with many variants, several languages, or shoppers who don't type your exact product names. It searches the same [product catalog](/docs/commerce/product-catalog) as your AI agent. When it is enabled, the AI agent in chat searches through it too, so chat and search bar recommend products in the same order.
You set it up per **business** under **Settings -> Storefront -> Storefront Search**, which has four tabs: **Overview**, **Design**, **Synonyms** and **API access**. Search reaches your pages through the Octocom script you already use for the chat widget: no separate widget to learn, no iframe.
Rendering results in your own code instead? The same script publishes a JavaScript client you can call directly. See the [Storefront search SDK](/docs/commerce/storefront-search-sdk).
How it works [#how-it-works]
What happens depends on what the shopper is doing:
* **While typing**, an instant panel shows query suggestions, a handful of top-matching products and category and brand chips, all from one lightweight lookup. No AI call runs at this stage, so it stays fast and cheap on every keystroke.
* **On submit** (Enter, the search button or picking a suggestion), the full search runs. It matches keywords, understands what was searched for (synonyms, translations, specs such as color or brand), ranks by both text and meaning, and combines the two into one ranked list.
A few behaviors worth knowing:
* **Smart matching, not just exact keywords.** Search understands synonyms, cross-language names (for example Greeklish and Greek) and normalized specs once your catalog has been through **enrichment** (see below). A catalog that hasn't been enriched still searches well on its existing text: enrichment widens what search finds, it doesn't gate it.
* **Rarely zero results.** If a query is too narrow (a typo or an overly specific phrase) and finds too few matches, search relaxes it and returns the closest matches instead of an empty page. The SDK flags these as `relaxed`, so a template can label them "Similar products" instead of presenting them as exact hits: add a `data-octocom-results-state-label` element to your Results or Overlay template (see **Results** below).
* **Filters re-run the last search.** In-stock and price filters apply to whatever was last searched, not to your full catalog.
* **No results beats wrong results, by default.** When search can't confirm that any product really matches a query, it returns an empty page, so your store shows its own "no results" message instead of loosely related products. Turn **Show nothing when no product clearly matches** off on the **Overview** tab (or set `hideLowConfidenceResults: false` with the `set_search_ui_config` MCP tool or `PATCH /rest/v1/search/ui-config`) to always show the closest products.
* **Only show relevant results** (off by default) trims the other end of the list: it stops once products no longer match the search, instead of paging on through loosely related ones.
Installing on your store [#installing-on-your-store]
Choose how your store gets search:
* **Octocom injects it.** If the [chat widget](/docs/channels/web-chat/launch-chat-widget) is on your store, enabling storefront search is all it takes: the script places search into your pages, with no theme or code changes.
* **Your developers build it.** Call search from your own code and render the results yourself. Nothing is injected into your pages. See the [Storefront search SDK](/docs/commerce/storefront-search-sdk) and the [REST API](/docs/developers/rest-api#product-search).
To try the injected search on your store before shoppers see it, use **Preview on your store** on the **Overview** tab. See [Preview on your live store](#preview-on-your-live-store).
You can also ask [Copilot](/docs/developers/copilot) or your own AI agent through [Octocom MCP](/docs/developers/mcp) to set it up. It prepares the catalog, finds the right places on your theme, configures the templates and checks result quality before you switch search on for shoppers.
Set up storefront search on our store so it matches the look of our current
search bar. Check the result quality on a few typical searches before we
switch it on for shoppers.
Configuration reference [#configuration-reference]
Open **Settings -> Storefront -> Storefront Search** for a business. **Show search on your store**, at the top of the **Overview** tab, is the master switch. When it's off, the configuration API returns nothing and nothing is injected on your site, whatever is set up on the other tabs.
**Prepare the catalog first.** Search can only be enabled once your catalog has been prepared. Preparation is one background run that enriches your products, builds the type and spec indexes (and the **Match by meaning** index, if it's on), mines the search vocabulary, generates test queries and tunes the ranking weights against them. Start it with **Prepare catalogue** on the **Overview** tab, the `start_search_preparation` MCP tool, or `POST /rest/v1/search/preparation`, and follow it with `get_search_preparation_status` or `GET /rest/v1/search/preparation`. It takes minutes on a small catalog and can take hours on a very large one. Until the status is `ready`, turning **Show search on your store** on is refused with a message saying what to do next. A failed run resumes from the step that failed when you start it again. Search that is already enabled stays live while a later re-preparation runs.
**Finding your selectors.** You don't have to dig through your theme for them. **Find on store**, next to the CSS selector, opens your storefront in a real browser, reads the page as it actually renders, and proposes selectors for the search box, results grid and filter rail, each with the reasoning and a snippet of the matched HTML. **Check saved** does the reverse: it loads your store and reports whether every selector you've saved still matches anything. Use it after any theme change, because a selector that matches nothing looks exactly like search being switched off.
The **Design** tab has one section per injection point: **Search bar**, **Mobile bar**, **Suggestions**, **Filters** and **Results** (plus **Overlay**, when results appear in a full-screen overlay). Each has:
* **Template:** the HTML you want rendered, edited in a code editor. Each one starts pre-filled with a working example, so there's always something functional to start from. The example is only live once you save it: a point is injected when it has both a saved template and a CSS selector, and a point whose template is cleared isn't injected at all (there is no built-in fallback). The same applies to templates set through MCP or the REST API.
* **CSS selector:** where this element is injected on your storefront. Comma-separated selectors are tried in order and the first match wins; commas inside quotes, `[]` or `()` don't count as separators. Leave it empty to skip injecting that element entirely. A part that isn't valid CSS is skipped, and **Check saved** names it so you can fix it.
* **Position:** **Before target**, **After target**, **Inside target** or **Replace target** (`before`, `after`, `inside`, `replace` through MCP and the API). Replace is the usual choice: it takes over your store's native element.
The **live preview** next to the editor runs against your business's real catalog as you type. It is not a mockup.
**Style isolation.** Each injection point renders inside its own shadow root, so your store's CSS can't leak into the search UI and its CSS can't leak onto your store. Your template renders exactly as authored, everywhere. Because of that, style the injected element's own wrapper with the `:host` selector (e.g. `:host { display: block; width: 480px; }`) rather than expecting your store's stylesheet to reach it. The suggestions dropdown is automatically pinned directly under the search input, so its target selector/position only decides where it mounts in the DOM, not where it visually appears.
Set in the **Results** section of the **Design** tab, this decides what submitting a search actually does:
* **In place** (default): results render into the Results target, on whatever page the shopper is already on. Simplest, and right when your store already has somewhere sensible to put a grid.
* **Full-screen overlay:** results open in a full-screen search experience over your store. Nothing to build on your side: no page to create, no selector to get right. The URL gains `?octocom-q=` while it's open, so the back button closes it and a search can be linked to or reloaded. A search refined inside the overlay updates that URL in place, so closing it always returns to the store in one step. Its markup lives in the **Overlay** section and mounts on ``, which is why it has no selector or position of its own. If someone asks you for "a search results page", this is usually what they actually want.
* **Separate page:** submitting sends shoppers to a page of your own, with the query in a URL parameter you choose (`q` by default). A real, bookmarkable, reloadable results URL. It needs that page to exist on your store, and the Results CSS selector has to match a container on it. Arriving on that URL, freshly or by reload, re-runs the search automatically.
Voice and photo searches in page mode render into the results page when the shopper is already on it. Anywhere else they open the overlay if you've filled in the **Overlay** template, and a spoken query otherwise goes to the results page. A photo has no query to put in a URL, so **page mode needs an Overlay template for photo search to show results off the results page**.
Overlay and page mode both reuse the markers you already know: the Overlay template takes the same `data-octocom-results-container` / `-result-template` pair as the Results template, plus an optional `data-octocom-search-close` on whatever should dismiss it (Escape and the back button work regardless). The page behind the overlay stops scrolling while it's open. The example Overlay template switches to a single column on phones; keep a similar `@media` rule if you write your own.
In page mode, set the **Results page address** to the page's final address. On arrival the search runs only when the page's path matches it; a trailing slash is ignored, so `/search` and `/search/` both work, but a server redirect to any other path means the search never runs (the browser console says so).
Beyond the built-in in-stock and price filters, you can offer your own catalog vocabulary (color, size, material, brand, whatever your products actually carry) as shopper-facing filters.
Pick them in the **Filters** section of the **Design** tab. The list is drawn from the vocabulary search preparation mined from your catalog, with sample values shown, so you're choosing fields that genuinely exist rather than typing a name and hoping. Give each a shopper-facing label.
They render through these markers, which go in your Filters template (and, if you use it, your Overlay template):
| Marker | Purpose |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data-octocom-facet-group-container` | Holds the groups; one is rendered per facet you configured. |
| `data-octocom-facet-group-template` | Cloned once per facet. Inside it, `data-octocom-field="label"` gets the label you set. |
| `data-octocom-facet-option-container` | Inside a group. Holds that facet's values. |
| `data-octocom-facet-option-template` | Cloned per value. `data-octocom-field="text"` gets the value, `"count"` how many results carry it. An `` anywhere inside is kept in sync; clicking anywhere on the option toggles it. |
Two things worth knowing about how they behave. Counts are live: each one is how many results would remain if you ticked it, given everything else already ticked, so an option never promises results it can't deliver. And filtering happens in the shopper's browser over the results already fetched, so toggling is instant and costs no request; the trade is that facets narrow the top \~300 results rather than re-querying the whole catalog.
Options are listed by count and stay in place when ticked, so the next click lands where the shopper expects, and keyboard focus stays on the option they just toggled. Each facet shows up to its limit (8 by default), plus any ticked value beyond it. A facet with no values in the current results is hidden.
The search input. Typing feeds the suggestions panel; Enter or the submit button runs the full search.
| Marker | Element | Behavior |
| ---------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `data-octocom-search-input` | `` (required) | Keystrokes trigger suggestions; Enter runs the full search; picking a suggestion writes it back into the input. |
| `data-octocom-search-submit` | any clickable element (optional) | Clicking runs the full search with the input's current value. |
| `data-octocom-search-mic` | any clickable element (optional) | Records a spoken query, transcribes it, and searches for it. See **Voice search** below. |
| `data-octocom-search-image` | any clickable element (optional) | Opens a file picker and searches by photo. See **Photo search** below. |
A second search bar, for themes whose desktop header and mobile header each have their own search element. The search bar's selector only ever takes over its first match, so on such a theme the other bar would keep the store's native search. This section targets it. Leave its selector empty if your store has a single search bar.
It uses the **same markers as the search bar**, and both bars are bound to the same search: a suggestion picked or a spoken query transcribed in one is written into both. One extra marker makes a collapsed bar possible:
| Marker | Element | Behavior |
| ---------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-octocom-search-toggle` | any clickable element (optional) | Opens and closes the bar. Clicking sets `data-octocom-search-open="true"` / `"false"` on the toggle and on the bar's shadow host, and focuses the input on open; Escape closes it again. What "open" looks like is up to your template's CSS, for example `:host([data-octocom-search-open="true"]) .row { display: flex; }`. |
The default template is a magnifier icon that expands into the full input row when tapped, and hides itself above 992px (Bootstrap's `lg` breakpoint). Match that breakpoint to your theme's own, and give the main search bar the mirror-image rule, so desktop visitors don't see two bars.
A camera button in your search bar: the shopper picks or takes a photo, and the products that look like it come back. Include a `data-octocom-search-image` element in your template; the SDK opens the file picker for it (or drives it directly if it's an `` itself), downscales the photo in the browser, and searches.
Photo search needs your catalog's **image index**, which Octocom builds for you on request. Until it exists, the element is **removed from the template**, like the mic when voice is off, so it's safe to leave in your markup permanently.
While bound, the element carries a `data-octocom-image-state` attribute (`idle`, `reading`, `searching`, `error`) that your CSS can target; the default template styles it.
To show the shopper's photo (for example in an "analyzing your photo" popup, or above the results), add a `data-octocom-image-preview` element to the search bar or Overlay template. An `` gets the photo as its `src`; any other element gets it as a CSS `background-image`. It's `hidden` until the shopper picks a photo and again after their next typed or spoken search, so it can stay in your markup permanently. Pair it with the state attribute, e.g. show a popup containing the preview while `data-octocom-image-state` is `reading` or `searching`.
A mic button in your search bar: the shopper speaks, and the spoken query runs through the same search as a typed one. Turn it on with the **Voice search** switch on the **Overview** tab, and include a `data-octocom-search-mic` element in your search bar template. Both are required; with either one missing, shoppers simply don't get a mic. Each voice search is billed in addition to the search itself.
The element is **removed from the template** when voice is off, when the shopper's browser can't record, or on insecure (non-HTTPS) pages, so it's safe to leave in your markup permanently. You never end up with a button that does nothing when clicked.
**Styling the states.** While bound, the element carries a `data-octocom-mic-state` attribute that your CSS can target:
| State | Meaning |
| -------------- | ----------------------------------------------------------------------------------------- |
| `idle` | Ready. Clicking starts recording. |
| `requesting` | Waiting on the browser's microphone permission prompt (first use on your domain). |
| `warmup` | Recording, but the microphone is still starting up. |
| `listening` | Recording. Clicking again stops early; otherwise it stops on its own after a short pause. |
| `stopping` | Finishing the recording. |
| `transcribing` | Recording sent, waiting for the transcript. |
| `error` | The microphone was refused or unavailable, or nothing recognizable was said. |
The default search bar template includes a styled example (a mic that turns red and pulses while listening), which is a good starting point to copy.
**What shoppers experience.** Recording stops automatically about a second after they stop talking, with a 10-second cap. The transcript is written into the search input and the results appear together, so a mis-heard word can be corrected and re-submitted like any typed query. If nothing recognizable was said, the mic goes to `error` and no search runs.
**Languages.** Voice listens for your business's configured language plus English, so a shopper browsing your store in a second language is still understood. No configuration needed.
**Microphone permission** is requested by the browser against *your* domain, and only when a shopper first clicks the mic, never on page load. Recordings are transcribed and discarded; they are never stored.
Two more ways to query the same catalog, available to storefronts you render yourself:
* **Photo search:** the shopper photographs an item and gets your closest matching products. Retrieval runs on everything the model reads off the photo (item type plus color, material, size and setting), and the shortlist is then compared against your own product images, so a product that *is* the photographed item outranks ones merely described like it. The response reports the item type on its own ("office chair"), short enough to label the results with, so a misread photo reads as a misread rather than as an empty catalog. The search bar's camera button (see **Photo search** above) uses the same search.
* **Similar products:** a "you may also like" row for a product page, from the page URL or a search result's id. It costs no AI call at all (the product's embedding is already indexed), so it's cheap enough to call on every page view.
Both are available over the [REST API](/docs/developers/rest-api#product-search) and the [SDK](/docs/commerce/storefront-search-sdk), together with voice, typed search and suggestions, so a storefront you render yourself can use the whole pipeline. Similar products is not part of the injected search UI; wire it into your own storefront code.
The dropdown shown while typing: query suggestions, plus optionally a few top-matching products and category and brand chips, all from the same lightweight lookup with no extra requests. Only the suggestions list is required; the product/category/brand sections render only when you include their markers. It closes when the shopper clicks or tabs away from the search or presses Escape, and comes back when they return to the box.
| Marker | Behavior |
| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-octocom-suggestions-container` | Marks the whole panel (required). Shown and hidden as a unit, like a dropdown. |
| `data-octocom-suggestion-template` | Cloned once per suggestion (required). Clicking a clone submits it as the search query. |
| `data-octocom-field="text"` / `"role"` | Suggestion text (e.g. "black chair leather") / what kind of match produced it (`category`, `brand`, or `attribute`). |
| `data-octocom-panel-products-container` + `-product-template` | Optional column of top-matching products, with the same fields as Results below. |
| `data-octocom-panel-categories-container` / `-brands-container` + `-category-template` / `-brand-template` | Optional facet chips. `data-octocom-field="text"` (name) / `"count"` / `"url"`. Only facets that have a URL from your feed are ever shown. |
| `data-octocom-panel-total-count` | Optional single element: the total keyword-match count for the typed query, hidden while unknown. |
| `data-octocom-panel-suggestions-section` / `-products-section` / `-categories-section` / `-brands-section` | Optional wrapper around a section's heading + container, hidden as a unit when that section has zero items. The dropdown itself stays open while any section has items. |
**Which fields suggestions come from.** Suggestions are visible to anyone on your store, so they only use catalog fields shoppers can already see. On Shopify stores, values found only in product **metafields** are left out by default: Shopify keeps metafields Admin-only unless your theme shows them, and they often hold supplier names, margins or internal labels. Search still matches those values; they just never appear as a suggestion. To change this per field, set `suggestFieldVisibility` in the search config (via Copilot, `set_search_ui_config` or `PATCH /rest/v1/search/ui-config`):
* `{ "field": "supplier", "visibility": "hidden" }` keeps a field you consider confidential out of suggestions, whatever its source.
* `{ "field": "fabric", "visibility": "public" }` lets a metafield your storefront does show feed suggestions.
Field keys come from `list_search_lexicon_fields`, which also shows how many of each field's values came only from metafields. Fields you use as filter facets count as public. If that count is `null`, the lexicon doesn't record which values came from metafields: when your Shopify product sync reads metafields, suggestions then use only categories, product types, brands and filter-facet fields until you rebuild the lexicon with `rebuild_search_lexicon`.
Any layout works: search finds inputs by their `data-octocom-filter` value and re-runs the last search whenever one changes.
| Marker | Element | Behavior |
| ----------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------- |
| `data-octocom-filter="inStock"` | checkbox | Checked = in-stock products only. |
| `data-octocom-filter="minPrice"` / `"maxPrice"` | numeric input | Empty = unbounded. Applied when the shopper presses Enter or leaves the field, not on every digit. |
**Hiding out-of-stock products entirely.** The checkbox above is the shopper's choice: it starts unticked, and they can untick it again. If you don't want unavailable products findable at all, use the **Hide out-of-stock products** switch on the **Overview** tab instead. Octocom applies it to every response (search, the suggestions dropdown and "more like this" recommendations), so nothing on the page, and no direct API call, can ask for them back. With it on, the in-stock checkbox is hidden from your filter markup automatically, since ticking it can no longer change the results.
The AI agent in chat uses the same search, and this switch applies there too, with one exception: if your [product catalog settings](/docs/commerce/product-catalog#stock-and-availability) turn on **Always treat products as in stock** or **Include out-of-stock products in text search**, the AI agent follows that more specific setting. It then still tells the customer when a product it found is out of stock.
**Products you haven't published.** A product the store doesn't show the public never appears in storefront search: results, the suggestions dropdown, "more like this", voice and photo search, and the search API. On Shopify that means an active product that isn't published to the Online Store sales channel. Its preview link is never used. The AI agent in chat can still find and discuss it. Custom product sync parsers mark such products with `hiddenFromStorefront` (see [Product sync parsers](/docs/developers/product-sync-parsers)).
The results grid. One template element is cloned per product.
| Marker | Element | Behavior |
| -------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-octocom-results-container` | required | Cloned cards are appended here; previous contents are cleared on every render. |
| `data-octocom-result-template` | required | Cloned once per product. |
| `data-octocom-field="name"` / `"shortDescription"` | text | Product name / short description. |
| `data-octocom-field="price"` | text | Formatted price the shopper pays (the discounted one on a sale product), or a price range when variants differ. No currency symbol. |
| `data-octocom-field="regularPrice"` | text | The pre-discount price to strike through, formatted the same way. Hidden when the product isn't discounted, so it's safe to put in every card. |
| `data-octocom-field="discountPercent"` | text | The discount, e.g. "-25%". Hidden when the product isn't discounted; the raw number is also written to `data-octocom-value`. |
| `data-octocom-field="image"` | `` or any element | Sets `src`/`alt` (hidden when there's no image), or a CSS `background-image` on any other element. |
| `data-octocom-field="url"` | `` | Product page link. |
| `data-octocom-field="inStock"` / `"onSale"` | any element | Shown only when true; also gets `data-active="true\|false"` for CSS hooks. `onSale` steps aside on cards that also show `discountPercent`. |
| `data-octocom-results-close` | optional | Clicking it empties the results. Pair with `:has(...:empty)` to collapse a panel/overlay; it re-appears on the next search. |
| `data-octocom-results-backdrop` | optional | Same as close, but only when the click lands on the element itself, for example click-outside on a modal backdrop wrapping the results. |
| `data-octocom-redirect` | optional | Keyword-redirect banner, shown only when the search matched a redirect in `banner` mode. See "Keyword redirects" below. |
| `data-octocom-results-more` | optional | A "show more" control. Results render 24 at a time and each click reveals the next 24; it hides itself once all are shown. |
| `data-octocom-results-state-label` | optional | Shown only while the results are in one of the space-separated states it lists: `relaxed`, `partial` or `uncertain` (see below). Give it `hidden`. |
**Showing the size of the discount.** `regularPrice` and `discountPercent` let a card say "€44.92, was €59.90, -25%" instead of just flagging "Sale". Both hide themselves on a full-price product, so one template covers both cases:
```html
```
Themes that render results their own way can listen for the `octocom:search-results` event on `window`. Its `detail` carries `query` (null for a photo search), `searchId`, `relaxed`, `confidence` and `count`.
Two background steps make search understand your catalog rather than just string-match it:
* **Lexicon:** mined from your product catalog's own fields: any value that recurs across products (colors, brands, categories, materials, ...) becomes searchable vocabulary, which powers facet suggestions and grounds query understanding. Rebuild it after a product sync changes your catalog meaningfully, or before tuning search. It's a full catalog scan, but safe to re-run any time.
* **Enrichment:** an AI pass over your catalog that writes synonyms, cross-language names, and normalized specs onto each product, so a search for a synonym or a translation still finds the right products. Once preparation has started, new and changed products are enriched automatically after each product sync, including products synced while preparation is still running; products whose text didn't change (a price or stock update) aren't re-processed. Products the AI couldn't enrich are retried automatically, and if a large share of the catalog fails (for example during an AI provider outage), preparation stops at the enrichment step so you can resume it.
Catalog preparation runs both. To re-run one on its own, use the MCP tools below.
Two settings in the **Matching** section of the **Overview** tab change how search compares a shopper's words with your products:
* **Catalog language:** matches different forms of the same word, so a search for "φόρεμα" also finds products that say "φορέματα". Pick the language your product titles and descriptions are written in; **Exact words only** is the default. Changing it re-indexes your catalog in the background, and search keeps working with the old setting until that finishes (seconds for a small catalog, minutes for a large one). Available languages: Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil and Turkish. Catalogs in other languages (for example Lithuanian or Czech) should stay on **Exact words only**.
* **Match by meaning:** also finds products by what they are, not only by the words in their listing. Each product gets a short summary of its name, type and attributes that search compares with the shopper's words, which helps short searches like "red dress" find the right products even when the listing is long or worded differently. Turning it on indexes your catalog in the background and it switches on when that finishes. New and changed products are added each time your catalog is prepared. Works best after enrichment.
The words shoppers use that your catalog doesn't. If your feed says "Denim" and shoppers type "τζιν", a synonym makes the second find everything filed under the first.
On the **Synonyms** tab, search for a word your catalog actually carries. The list is your own mined vocabulary, so you're picking a real word rather than typing one and hoping. Open it, add the words shoppers use (Enter or a comma between them), and save. Words that already have synonyms show up in the same list when the search box is empty.
Two things worth knowing:
* **They apply on the next search.** No reindexing, no lexicon rebuild, no waiting.
* **A synonym has to attach to a word your feed uses.** Search for the catalog's word, not the shopper's. If a word later disappears from your catalog (a rename, a feed change), its entry is kept and flagged **not in catalogue** rather than deleted, because moving those synonyms to the new word is your call.
Synonyms widen what a keyword search can find; they don't reorder anything. They're the right fix for "we get nothing for this word", not for "the right product ranks third".
Two advanced settings tune search per business. Both are set through MCP, usually by Copilot or your own AI agent:
* **Rerank weights:** adjust how much category, attribute, price, and stock signals influence result ordering, without retraining anything. `set_search_weight_override` changes only the weights you pass and keeps the rest (set one to `null` to drop it back to the default). Catalog preparation re-tunes these weights, so running **Prepare catalogue** again resets every hand-set weight except the newest-first tilt (`recency`). Re-apply any other manual weight afterwards.
* **Query-understanding grace period:** how long a search waits for the full AI-powered understanding of a query before falling back to fast, catalog-only matching. The default favors storefront speed; raise it per business when you want AI understanding prioritized over latency, e.g. while evaluating search quality.
Some searches aren't looking for a product. For "black friday", "size guide" or "returns", the shopper wants a page, and no amount of ranking will produce one, because the product catalog is all search has to answer with.
A redirect points a keyword at a URL. It's resolved before any searching happens, so it costs no AI call and nothing on your search bill. It applies to **submitted** typed searches only, not to the as-you-type panel or to voice and photo searches. Redirects are managed through MCP and the REST API, usually by Copilot or your own AI agent.
**Two match modes.** `exact` fires only when the whole query matches. `contains` fires when the keyword appears as a whole word anywhere in the query. Start with `exact`: a `contains` rule on "black" also fires on "black leggings", the most common redirect mistake. (It won't fire inside "blackberry": matching is whole words, not substrings.)
**Two behaviors, chosen per business:**
| Mode | What a shopper sees |
| ---------- | ---------------------------------------------------------------------------------------------- |
| `banner` | The search runs normally, with the link offered above the results: "Looking for Black Friday?" |
| `navigate` | The search is skipped entirely and the shopper goes straight to the URL. |
`banner` is the default, and it's the one to keep unless you're sure. A banner nobody wanted is ignorable; a wrong `navigate` throws a shopper off the page with no way back to what they were typing toward. `navigate` is reachable only from the shopper pressing Enter on your search bar. Anything that could be driving a dropdown gets `banner` regardless of this setting, because a mid-keystroke page takeover isn't recoverable.
**Matching ignores case, accents, extra spaces and punctuation around the query**, so one "black friday" entry answers "Black Friday", "BLACK FRIDAY" and "black friday!". Other languages are separate entries on purpose: a Greek store wanting "μαύρη παρασκευή" adds two, which is more predictable than guessing they're the same campaign.
**Use a full URL or a path on your store.** The URL must start with `https://` (or `http://`), or be a path on your store starting with `/`, such as `/black-friday`. Anything else, like `www.shop.com/black-friday`, is refused when you save it, because the browser would read it as a page under your search page.
**Give campaign redirects an end date.** `startsAt` / `endsAt` make a redirect expire on its own, which is the only thing that reliably stops a Black Friday redirect still firing in March. Set `timezone` (e.g. `Europe/Athens`) or a window written as "midnight" opens at the wrong local hour.
**Showing the banner with the widget.** Add a `data-octocom-redirect` element to your Results template (or your Overlay template). It's shown only while the current search matched a redirect, and hidden otherwise. Inside it, `data-octocom-field="trigger"` gets your keyword as written and `data-octocom-field="url"` on an `` gets the link. Give it the `hidden` attribute so it starts closed:
```html
```
Without that element a `banner` redirect still matches, but nothing shows on the page. `navigate` needs no markup: the widget sends the shopper to the URL.
Rendering results in your own code? Handle the `redirect` field; see [the SDK guide](/docs/commerce/storefront-search-sdk#merchant-redirects). On `navigate` the results come back empty on purpose, and a client that ignores the field will show an empty state instead of the campaign page.
Merchandising rules put your thumb on the scale: promote a brand you're pushing, or demote a line you're clearing, globally, only on certain searches or only between two dates. Rules are managed through MCP, usually by Copilot or your own AI agent.
A rule is three answers:
* **When** it's considered: every search, specific queries, or searches the AI places in a category.
* **Which** products it applies to: a brand, a category, or a list of product IDs.
* **What** it does: a **boost**, signed: `0.3` promotes by "+30%", `-0.2` demotes.
**Rules boost or demote.** A rule changes a product's rank within the results it already earned. Pin, bury and hide actions are refused when you save, rather than stored as rules that look active but do nothing. To send a search straight to a page, use a keyword redirect (see **Keyword redirects** above) instead.
**A boost reorders within relevance; it can't inject irrelevance.** The percentage is taken of the score a product already earned, so a +30% brand boost tilts the ranking of things that already matched. It cannot drag a protein bar into a creatine search, because 30% of nothing is nothing. That's deliberate: it's what makes a boost safe to leave running.
**Overlapping rules add up, then stop.** Four +30% rules on one product combine to +100%, not +120%: the total multiplier is capped at 2× and floored at 0.5×, so no stack of rules can flatten your catalog into a single brand.
**Brand targeting reads the product's actual brand**, not its description. A third-party cable that names Apple 44 times is not an Apple product and won't be caught by a rule boosting Apple.
**Scheduling works exactly as it does for redirects:** `startsAt`, `endsAt` and `timezone`, with expiry that needs no scheduled job. Windows don't repeat, so set a new window for each year's campaign.
Merchandising applies to **submitted** searches: the storefront search bar on Enter and the `/products/search` and `/products/search/panel` REST endpoints. It doesn't reach the as-you-type panel, voice or photo searches, which rank on their own. It also applies to the AI agent in chat when storefront search is enabled, so the chat recommends products in the order your search bar shows them. It deliberately does **not** apply to search-quality evaluations: a quality score measured with boosts running would be measuring the boosts.
| Tool | Purpose |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start_search_preparation` / `get_search_preparation_status` | Start (or resume) catalog preparation and follow its progress. `enabled: true` in `set_search_ui_config` is refused until the status is `ready`. |
| `get_search_ui_config` / `set_search_ui_config` | Read and write the same configuration as the dashboard pages above. |
| `rebuild_search_lexicon` | (Re)mine the facet vocabulary from the product catalog. Run after a product sync, or before tuning. |
| `list_search_lexicon_fields` / `find_search_lexicon_values` | Read the mined vocabulary: its fields (keys for filter facets and `suggestFieldVisibility`, with how many values came only from metafields) and the exact catalog spelling of values, for synonyms and merchandising targets. |
| `run_search_enrichment` | Generate the AI enrichment pass (synonyms, translations, normalized specs) described above. Pass `productIds` to redo specific products only, e.g. one mistyped item. |
| `get_search_weight_override` / `set_search_weight_override` | Read/set per-business rerank weight overrides. |
| `get_search_qu_grace_override` / `set_search_qu_grace_override` | Read/set the per-business query-understanding grace period. |
| `search_products_hybrid` | Run a search directly, to test without touching the storefront. |
| `run_search_eval` / `generate_search_eval_queries` / `get_search_eval_results` | Generate a synthetic query set for a catalog and evaluate search quality against it. |
| `get_search_job_status` | Check progress of a lexicon rebuild, enrichment run or eval. These all run as background jobs. |
| `set_search_text_analysis` | Read or set the catalog language for keyword matching (and BM25 length normalization `b`), described under **Matching** above. |
| `build_search_passage_index` | Build or update the **Match by meaning** index. Optional `maxPassages` adds description chunks; progress under `get_search_job_status` -> `passageIndex`. |
| `list_search_redirects` / `set_search_redirect` / `archive_search_redirect` | Read/write keyword redirects. Re-saving an existing trigger changes only the fields you pass, so a paused redirect stays paused and keeps its end date. Archiving retains the redirect for `restore_search_redirect`. `list_` takes an optional `testQuery` to see which rule a query hits. |
| `list_merchandising_rules` | Read the rule set. Takes an optional `testQuery`; flags rules that are enabled but outside their window. |
| `create_merchandising_rule` / `update_merchandising_rule` / `archive_merchandising_rule` | Write merchandising rules. Archiving retains the rule for `restore_merchandising_rule`. Use `enabled: false` to pause a campaign without losing it. |
A typical setup flow: `start_search_preparation` -> poll `get_search_preparation_status` until `ready` -> `probe_storefront_search_selectors` and `set_search_ui_config` to configure the widget -> `verify_search_ui_selectors` -> `set_search_ui_config` with `enabled: true` -> `run_search_eval` to check result quality. The individual steps (`run_search_enrichment`, `rebuild_search_lexicon`, `build_search_*`, weight overrides) remain available for fine-grained tuning.
The same operations are available over the REST API: `GET`/`PATCH /rest/v1/search/ui-config` for the widget configuration, `GET`/`POST /rest/v1/search/preparation` for preparation (`POST` returns 409 while a run is already in progress), and `GET /rest/v1/search/lexicon/fields` and `GET /rest/v1/search/lexicon/values` for the mined vocabulary.
Testing storefront search [#testing-storefront-search]
Before enabling search on a live storefront, use the **live preview** on the **Design** tab. It's wired to the real search pipeline for your business, so typing and submitting a search queries your actual catalog. Sample product cards fill the results grid until you run your first search, so you can check the visual design without needing a working query yet.
If a template is missing a required marker, the preview shows a warning underneath it (e.g. "Search bar template is missing `data-octocom-search-input`") so you can catch mistakes before saving.
**Selectors** can be checked against the real thing rather than guessed at: see **Find on store** and **Check saved** under **Enabling search** above. Both open your storefront in a browser and read the rendered page, which is the only reliable way to see a client-rendered store's DOM.
**Voice** can be tried the same way: the mic in the preview records and transcribes exactly as it will for shoppers, and works even while the **Voice search** switch is off, so you can hear how it handles your product names before turning it on. A note under the preview tells you when shoppers *wouldn't* get a mic and why (switch off, no `data-octocom-search-mic` in your template, or a browser that can't record).
Preview on your live store [#preview-on-your-live-store]
The **Design** tab's preview renders your templates in Octocom's layout. To see them in your own header, on your own theme, before shoppers do, create a **preview link** under **Preview on your store** on the **Overview** tab (**Create preview link**): your storefront URL plus a token that switches the search UI on for whoever opens it, and for nobody else.
The link needs the Octocom widget script already installed for the **same business**, and it works whether or not **Show search on your store** is on. A preview cannot switch the installed widget to another business's search templates or catalog. Same-business previews also work on staging and alternate domains without changing your live search origin allowlist.
It lasts 24 hours and stays active for that business as you click around the store in the same browser tab, so you can check the search bar on a product page and a collection page in one sitting. The browser remembers a token only after the server accepts it for the installed business. An expired or mismatched token stops the preview and clears the remembered token; create a fresh link for the correct business if this happens.
Treat it as a password rather than a share link: opening it runs real searches billed to your account. Create a fresh one instead of passing an old one on. Links expire, and nothing has to be switched back off afterwards.
Best practices [#best-practices]
* **Start from the examples.** Every template starts pre-filled with a working example. Tweak colors and spacing rather than starting from a blank editor, so you don't accidentally drop a required marker.
* **Templates are cloned, not rendered directly.** Don't rely on the original template element being visible on the page. It stays hidden and detached; only its clones are shown.
* **Rebuild the lexicon after catalog changes.** Facet suggestions and query understanding go stale otherwise.
* **Enrich before judging search quality.** An un-enriched catalog looks weaker on synonym and translation queries, so run enrichment before concluding search "doesn't find" something.
* **Use `replace` for the search bar and results grid** unless you specifically want to keep your store's native element alongside ours. Most setups replace the native search box/grid entirely.
* **Prefer the overlay when you're asked for a "results page".** It needs nothing built on your store, is shareable and back-button-able, and avoids the most common failure of page mode: a results page whose target selector doesn't match anything.
* **Re-run Check saved after a theme update.** Themes rename classes, and a selector that stops matching fails silently: nothing errors, the element simply never appears.
* **Test filters together with a search**, not in isolation. Filters re-run whatever was last searched, so an empty query with a filter applied returns nothing.
# Virtual try-on
import { Accordions, Accordion } from "fumadocs-ui/components/accordion";
Virtual try-on lets shoppers see a product on themselves or in their space before they buy: a jacket in a photo of themselves, a sofa in a photo of their living room. A **Try it on** button on the product page, typically next to **Add to cart**, opens a window where the shopper uploads a photo. A few seconds later they see an AI-generated preview of the product in that photo, made from the product's cleanest catalog image.
It's for stores where "how will it look on me?" or "will it fit my room?" holds back a purchase. Try-on ships as part of the web chat widget, so there is no extra script to add. Make sure the [chat widget is deployed](/docs/channels/web-chat/launch-chat-widget) first.
How it works [#how-it-works]
On a product page, the shopper sees a **Try it on** button next to **Add to cart**. Clicking it opens a window where they upload a photo of themselves (for apparel and accessories) or their room (for furniture and decor) and give consent. A few seconds later they see the product on themselves or in their space, and they can try again with a different photo whenever they like.
You choose which pages show the button, how the button and window look, and how the AI is instructed, all covered below. Try-on usage and generations appear in **Metrics -> Virtual try-on**.
Try-on can also work the other way round. Instead of trying on the one product on the page, an **outfit builder** lets the shopper pick several products from your catalog (a top, trousers and shoes, say) and see them worn together as one look. This is set per variant, so one business can run classic try-on on its product pages and an outfit builder on a dedicated page at the same time.
Set it up [#set-it-up]
Ask [Copilot](/docs/developers/copilot) or your own AI agent through [Octocom MCP](/docs/developers/mcp), for example:
Add a virtual try-on button next to Add to cart on our product pages, but not
for swimwear.
The agent creates a variant that starts switched off or limited to a test page, sets its placement and prompts, matches the button and window to your brand, and opens it to all product pages once you've checked the results. Octocom's solution engineers can also design and test try-on with you, especially for outfit builders and multi-language stores.
Configuration reference [#configuration-reference]
A business can have several **variants**: for example an English variant gated to `/en` and a Greek variant gated to `/el`, or a furniture variant gated to `/products/sofa-` with one prompt and an apparel variant gated to `/products/` with another. Each variant controls where its button appears, how it looks, and how the AI is prompted.
At runtime the widget walks the variants in priority order and uses the first one whose page-targeting rule matches the current URL. So priority matters:
* Variants are ordered by priority, and the **highest wins**.
* Reordering them swaps their priorities; new variants are appended at the bottom of the list, so they don't shadow anything you've already arranged.
* A variant with no page-targeting rule (`pathRegex`) is a catch-all that matches every page. Catch-alls should usually sit at the bottom so they don't shadow more-specific variants.
* Variants marked **disabled** are skipped entirely. Use this to stage changes before going live.
Creating the first variant turns try-on on for the business. Each variant's own `enabled` setting decides whether it is used, and URL matching selects among the enabled ones. Archiving a variant removes it from selection: the widget uses a remaining active variant, or stops showing try-on when none remain.
**Variant name (`name`):** an internal label for the variant. Not visible to shoppers.
**Target selector (`selector`):** a CSS selector for where to inject the button on the product page, for example `.product-form__buttons`, `#product-addtocart-button`, or `button[name="add"]`. You can pass several comma-separated selectors; the first one that matches wins. Pick something stable across your product templates.
**Render mode (`renderMode`):** each variant injects in one of two modes:
* `button` (default): injects a button at the selector; clicking it opens the try-on experience in a modal overlay. Uses `buttonHtmlTemplate` for the button and `modalHtmlTemplate` for the overlay.
* `inline`: injects the try-on experience **directly into the page** at the selector, with no button and no overlay (no backdrop or close button). Uses `modalHtmlTemplate` for the embedded markup; leave it empty to fall back to the built-in inline default (a plain card rather than a fixed full-screen overlay).
Both modes share the same `data-octocom-tryon-*` markers. If you switch a variant with a customized overlay `modalHtmlTemplate` to inline, rewrite the template so it isn't `position:fixed` with a backdrop, and check how it renders on a test page before enabling the variant for shoppers.
**Insertion position (`insertionPosition`):** how to insert the button (or, in inline mode, the embedded experience) relative to the matched element:
* `before`: inserts the button as a sibling immediately before the target.
* `after`: inserts the button as a sibling immediately after the target.
* `inside`: appends the button as the last child of the target.
* `replace`: replaces the target element entirely with the button.
**Page targeting (`pathRegex`):** a regular expression matched against the page's URL path (no host, no query string). Variants are tried from top to bottom by priority; the first one whose regex matches wins. Common examples: `^/products/` to scope to product pages only, `^/el/` to scope to a locale prefix. See [supported regular expressions](/docs/channels/web-chat/configuration#supported-regular-expressions) for the patterns new rules can use.
Leave `pathRegex` empty or null to make the variant a catch-all. Catch-alls should usually sit at the bottom of the priority list so they don't shadow more-specific variants.
**Try-on prompt (`prompt`):** sent to the AI image model alongside the customer's photo and the chosen product image. Use this to nudge the model toward your preferred output style, brand voice, or category-specific instructions (e.g. furniture variants typically tell the model to keep the customer's room as-is and only add the product; apparel variants tell it to keep the customer's pose and face). Leave it empty or null to use the built-in default.
**Image picker prompt (`imagePickerPrompt`):** before generating the try-on image, the system automatically picks the cleanest catalog image for the product: one that shows the product **in isolation** (plain or studio background) rather than in a lifestyle scene with rooms, people or props. You can adjust this prompt to match the catalog. For example, for furniture you want "neutral white background, no people" treated as isolation; for apparel you want "garment on a mannequin or laid flat" treated as isolation. Leave it empty or null to use the built-in default.
**Category blacklist (`categoryBlacklist`):** a list of product category slugs or IDs to **exclude** the variant from. If the product on the current page belongs to any blacklisted category, the button is not injected. Common uses: hide try-on for swimwear, underwear or beauty products that don't work well with the model. Leave empty to apply to all categories.
**Use full, specific category slugs.** Blacklist matching can be broad, so a short, generic entry like `men`, `home`, `body`, or `face` can match unrelated products (for example `men` matches inside `women`) and silently hide the button where you didn't intend it to. Prefer complete category slugs and avoid short, ambiguous tokens. If the button is unexpectedly missing on a valid product page even though the path matches, the category blacklist (or the product gate) is the usual cause, not the `pathRegex`.
**Standalone pages (`bypassProductGate`):** by default a variant only renders on pages that resolve to a real catalog product. That product check is what keeps the button off category pages, blog posts, and other URLs that happen to match a loose `pathRegex`. On a **standalone try-on landing page** with no backing product, such as a dedicated `/virtual-try-on` page where the shopper uploads their own garment, that check would hide the button even when the path matches.
Enable `bypassProductGate` on such a variant to skip the product lookup (and, with it, the category blacklist) and render purely on the `pathRegex` match.
Only use it on dedicated standalone variants. On normal product-page variants, leave it off. Otherwise you lose the category blacklist and the protection that keeps the button off non-product pages.
By default a variant dresses the shopper in **the product on the page**. Set **Garment source (`garmentSource`)** to `outfitBuilder` and it does something different: the variant runs on a page with no product of its own, the shopper picks one product per **slot** from your catalog, and everything they picked is generated as one look.
The two are alternatives per variant, not a mode for the whole business. A store can have a classic `/products/` variant and an `/outfit-builder` variant side by side.
**Slots (`outfitSlots`):** the positions in the look, in the order the shopper sees them (which is also the order the items are described to the image model). A typical builder has three: Top, Trousers, Shoes. Up to eight. Each slot has:
* **Label (`label`):** what the shopper sees, for example "Shoes".
* **Key (`key`):** an internal identifier, unique within the variant. Letters, numbers, `-` and `_` only, up to 40 characters. The shopper's pick is posted back under this key.
* **Required (`required`):** when on, the shopper can't generate a look until the slot is filled.
* **Catalog query (`query`):** what this slot offers, searched against your catalog (in-stock products only). The shopper can narrow it by typing in the slot's search box; what they type is **added** to your query rather than replacing it, so a "Shoes" slot can't be turned into a sofa from the browser. The one exception is a **product code**: typing a SKU, MPN or style code (e.g. `004KA0001`) puts the in-stock products carrying that code at the top of the grid, whichever slot it was typed in.
* **Fixed list of products (`productUrls`):** up to 60 product URLs. When this is filled in, the slot shows exactly these products, the query is ignored, and the slot isn't searchable. Use it when you want to curate the shortlist yourself.
**Choosing the photo.** Tapping a product in a slot picker selects it and lets the image picker choose which of its photos to dress the shopper in, the same automatic behavior a classic try-on has. When a product has more than one photo, the picker offers them instead, so the shopper can say *which* photo. That extra tap is worth it twice over: the look uses the photo the shopper actually meant, and it skips the automatic image picker, which is the slowest step in preparing each item, so the look is generated sooner.
Only a product's own photos can be chosen. A photo that isn't in the catalog for that product is ignored and the automatic picker runs instead.
**Stand-in photo (`baseImageUrl`):** a model or mannequin shot the look is rendered onto when the shopper uploads no photo of their own. Leave it empty to require an upload, which is what a classic try-on does. Either way the shopper can still upload their own photo and get the look on themselves.
Two things happen automatically on an outfit-builder variant, because they follow from what it is:
* The **product gate is skipped**: a builder page has no catalog product behind it, so there's nothing to check. You don't need to also turn on `bypassProductGate`.
* The **category blacklist doesn't apply**, for the same reason. Scope what a slot can offer with its query or its fixed product list instead.
Set up a builder page like this:
1. Create a variant, set its garment source to `outfitBuilder`, and point its **page targeting** at the page you'll build, for example `^/pages/outfit-builder`.
2. Use `inline` render mode with a selector pointing at an empty container on that page, so the builder renders as part of the page rather than behind a button.
3. Add your slots and give each one a catalog query. Check on a test page what each slot offers, and which photo it picks, before enabling the variant for shoppers.
4. Optionally set a stand-in photo so a shopper gets a look without uploading anything.
5. If your storefront isn't in English, translate the slot picker's wording in your modal template (see **Translating the slot picker** below).
6. Tune the **try-on prompt** for outfits. The default is written for a single garment. Something that tells the model to dress the person in every item together, keeping each one's appearance, works better than the stock wording.
**Opening a builder from your own buttons, with a look already picked.** A builder doesn't have to be inline. In `button` render mode it opens as a popup, and besides the injected button, **any element on the page carrying `data-octocom-tryon-open`** opens it too, so a banner and a tile in your product grid can both be entry points without either being an injection point. Elements added later (an infinite-scroll grid, a lazy banner) work as well.
Add `data-octocom-tryon-look` to such an element to open the builder with products already in their slots, written as `slot:code` pairs: `See it on you`. A link can do the same with the `octocom-look` URL parameter (`?octocom-look=top:8601.1120,bottom:8607.2007`), which opens the popup on arrival, or pre-fills an inline builder. Each code is looked up the way a code typed into a slot is (SKU, MPN or style code, in-stock products only). A code that matches nothing, or a slot key the variant doesn't have, leaves that slot empty for the shopper to fill, and the shopper can change every pre-filled pick.
The page still needs an outfit-builder variant whose page targeting matches it, ordered above any classic variant that also matches (e.g. a product-page variant targeting your whole `/el` section).
**Translating the slot picker.** The slot labels are yours, but the picker's own wording (buttons, search placeholder, loading and empty states, the photo step) is English by default. Override any of it with `data-octocom-tryon-text-*` attributes on the template's `data-octocom-tryon-outfit` element. Each variant has its own template, so each can have its own language. `{label}` is replaced with the slot label in lower case and `{n}` with a photo count.
| Attribute | Default |
| ------------------------------------------ | ------------------------------------------- |
| `data-octocom-tryon-text-choose` | `Choose {label}` |
| `data-octocom-tryon-text-change` | `Change` |
| `data-octocom-tryon-text-optional` | `(optional)` |
| `data-octocom-tryon-text-search` | `Search {label}…` |
| `data-octocom-tryon-text-loading` | `Loading…` |
| `data-octocom-tryon-text-empty` | `Nothing to show here yet.` |
| `data-octocom-tryon-text-load-error` | `Couldn't load products. Please try again.` |
| `data-octocom-tryon-text-back` | `‹ Back` |
| `data-octocom-tryon-text-pick-for-me` | `Pick for me` |
| `data-octocom-tryon-text-pick-for-me-hint` | `Best photo, chosen automatically` |
| `data-octocom-tryon-text-photos` | `{n} photos` |
```html
```
**Adding the look to the bag (`cartPlatform`).** Set `cartPlatform` to your store platform and the result step lists every item the shopper picked, each with its image, price, SKU and a size picker, followed by one **Add whole look to bag** button. The supported cart platform is `magento` (Magento and Adobe Commerce stores). Leave it off and the result is the picture alone.
Everything runs in the shopper's browser, against your store's own cart and with their own session, so nothing needs to change on your store:
* Sizes and the SKU are read from each product page, the same configurable-product data your own size swatches use. Sizes with nothing left in stock are shown as sold out, and a product with a single size has it chosen already.
* The button adds the items one by one through your store's normal add-to-cart, then refreshes the minicart in the header. An item that can't be added (it sold out in the meantime, say) is flagged on its row and the others still go in.
* The shopper can untick items they don't want before adding.
Because the cart uses the shopper's store cookies, the builder page must be on the same domain as your products. A product on another domain is listed with a link, but can't be added.
The list goes right under the result image. To place it yourself, put an empty `data-octocom-tryon-cart` element in the result step. Its wording is English by default and is translated the same way as the slot picker, with `data-octocom-tryon-text-*` attributes on that element: `-title` (`Shop the look`), `-add-all` (`Add whole look to bag`), `-add-one`, `-add-some` (`Add {n} items to bag`), `-adding`, `-added`, `-added-partial` (`Added {n} of {total}. Check the items marked below.`), `-view-bag`, `-choose` (`Choose {label}`, where `{label}` is the store's own name for the attribute, such as size), `-sold-out`, `-loading-options`, `-options-error`, `-missing-options`, `-item-error`, `-item-added`, `-sku` (`SKU {sku}`) and `-price` (`{price}`, for example `{price} €`).
```html
```
The button and modal are HTML templates you write (`buttonHtmlTemplate` and `modalHtmlTemplate`). Style them however you want; the widget doesn't inject any default CSS. Leave either field empty to use the built-in default, a minimal, brand-neutral starting point.
You don't write any JavaScript. The widget finds elements by their `data-octocom-tryon-*` attributes at runtime and binds state and event handlers to them. Anything without a marker is treated as decoration and rendered as-is.
**Button template markers**
| Marker | Element | Purpose |
| ---------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-octocom-tryon-trigger` | `