# WABA AI Flow

This file explains the AI side of the WhatsApp Business message system in plain English.

Use this file when you want to understand:

- what AI models are used
- what each model is responsible for
- how AI decisions are combined with code rules
- how the final reply is generated

If you want the full message pipeline, read [WABA_MESSAGE_FLOW.md](/e:/Coding/api.Insale.ai/WABA_MESSAGE_FLOW.md).

## Big Picture

The WABA AI flow is not one single model doing everything.

It is a multi-step process:

1. detect the user's language
2. classify route signals
3. classify lead intent
4. parse dates when needed
5. translate fixed replies when needed
6. generate the final reply using business knowledge

The code still controls the final business actions.

## AI Models Used

## `OPENAI_WHATSAPP_LANGUAGE_MODEL`

Purpose:

- detect the language of the latest user message
- detect whether the user is writing in native script or Latin script

Examples:

- English
- Urdu
- Roman Urdu
- Arabic
- Persian
- Chinese

This allows the system to answer in the same language as the latest user message.

## `OPENAI_WHATSAPP_ROUTER_MODEL`

Purpose:

- return structured route signals about the message

Examples of signals:

- affirmative
- negative
- wants meeting
- wants offers
- asks for more details
- wants company profile
- knowledge question
- asks human
- service refocus

This model does not directly update the database. It only helps route the message.

## `OPENAI_INTENT_CLASSIFIER_MODEL`

Purpose:

- decide the lead's high-level intent

Main labels:

- `qualification`
- `not_interested`
- `human_intervention`
- `none`

This is different from route signals. It is used for lead-level outcomes.

## `OPENAI_WHATSAPP_MEETING_PARSER_MODEL`

Purpose:

- understand meeting time and date when normal parsing is not enough

This is especially useful when:

- the user writes in another language
- the date format is informal
- the time phrase is not simple English

## `OPENAI_WHATSAPP_TRANSLATION_MODEL`

Purpose:

- translate fixed business replies into the user's language

Used for things like:

- meeting prompts
- meeting errors
- human intervention replies
- static business-rule messages

## Final reply generation model

The final text reply is also produced through OpenAI chat completion.

This final prompt is the largest AI step because it uses:

- agent role
- agent style
- custom instructions
- company website
- uploaded user files
- offer data
- known customer name
- conversation history

## Step-by-Step AI Flow

### Step 1: The system receives the latest user message

The AI flow only starts after the webhook has already:

- received the Meta message
- found the lead
- loaded the company
- saved the inbound message

### Step 2: The system detects the latest user language

The language detector is asked to identify:

- `language_code`
- `language_name`
- `script_mode`

This is open-ended. It is not limited to only a few languages.

This is important because the whole AI flow uses the latest user message as the language source of truth.

### Step 3: The system runs the router model

The router model looks at the latest user message and returns structured signal flags.

Examples:

- Is this a meeting request?
- Is this a request for offers?
- Is the user saying yes?
- Is the user saying no?
- Is this a request for documents?
- Is this an out-of-scope question?

The router is helpful because it turns a natural language message into machine-usable decisions.

### Step 4: The system runs the lead intent classifier

This model answers a different question:

What is the customer's high-level sales intent?

It tries to decide:

- qualified
- not interested
- human intervention
- none

This result is used for things like lead status updates.

### Step 5: The system reads recent conversation history

The history itself is not AI, but the AI uses it for continuity.

The system especially uses history to understand:

- what the bot asked last
- what topic is currently active
- what the user may be referring to with short replies like `yes`, `no`, or `that one`

Important rule:

History is not supposed to be the source of truth for company knowledge.

## AI-Assisted Special Behaviors

## Language Matching

The AI is instructed to always reply in the language of the latest user message.

That means if the user switches language mid-chat, the system should follow the new latest message language.

## Name Recall

AI is not supposed to guess the user's name.

The prompt tells the assistant:

- first use the saved lead or history name if available
- if no name is available, ask politely
- do not forward this kind of question to the supervisor

## Service Refocus

If the user asks off-topic questions or asks about internal AI/system details, the AI is told to redirect back to the company's services.

The purpose is to keep the conversation focused on business.

## Meeting Understanding

AI helps in meeting flow by:

- understanding date/time in different languages
- understanding that the message is about booking a meeting
- localizing meeting replies into the user's language

But AI does not decide alone whether the meeting is truly booked.

Real booking still depends on:

- schedule rules
- availability
- meeting creation success

## Offer Understanding

AI helps by:

- understanding whether the user is asking about offers or normal services
- understanding negotiation language
- answering naturally from real offer data

But AI should not invent:

- fake discounts
- fake promo codes
- product-specific offer matches that are not in the data

## Company and Knowledge Questions

The AI is told that company facts must come only from allowed business sources:

- uploaded user files
- website content
- offer data

This rule is important because without it the model might invent facts.

## How the Final Prompt Works

The final prompt is built only after the system decides that no earlier hard branch should return first.

The prompt includes:

- agent name
- agent role
- agent style
- custom instructions
- company name
- official website
- reply language instruction
- known customer name
- user file content
- website content
- offer data
- conversation history

The prompt also contains strict business rules.

Examples of those rules:

- reply like a real person on WhatsApp
- do not volunteer that you are AI
- if asked directly, answer truthfully that you are the virtual assistant
- use only approved business sources for facts
- do not invent meeting links
- do not invent product-specific offer matches
- use history for continuity, not for company truth

## Knowledge Priority Order

The final AI is told to read information in this order:

1. user file content
2. website content
3. offer data
4. conversation history

This is done so the model does not answer company questions from random old chat text first.

## When the AI Is Blocked

The AI is not always allowed to answer freely.

The code can stop or override the AI when:

- there is no knowledge source for a factual company question
- documents were requested but no sendable files exist
- the user needs human intervention
- the user is clearly not interested
- the meeting flow requires a rule-based reply
- a saved meeting link should be returned directly

This is important.

The AI is a helper inside the flow. It is not the only decision-maker.

## What AI Can Do Well Here

The current design expects AI to be good at:

- language detection
- route classification
- intent classification
- multilingual date understanding
- translation
- natural final replies
- natural offer explanations
- staying conversational and human-like

## What AI Should Not Do Alone

The current design does not want AI alone to decide:

- whether a meeting really exists
- whether a meeting slot is free
- whether a document file actually exists
- whether an offer actually exists in the database
- whether a lead status should be written without threshold checks
- which WhatsApp account should send the reply

These are handled by code and database state.

## Translation Flow

Not every message is generated directly in the target language.

For some fixed replies, the system:

1. creates the fixed business reply in English
2. sends that text to the translation model
3. returns the translated result to the user

This allows business-rule branches to stay structured while still replying in the user's language.

## Confidence Thresholds

The AI results are not blindly trusted.

The code uses confidence thresholds for important classifications.

Examples:

- lead intent threshold
- router signal threshold
- offer intent threshold
- company intent threshold
- meeting intent threshold

This helps reduce random low-confidence routing mistakes.

## AI Flow for Meetings

For meeting-related messages, the AI role is:

1. detect that the user wants a meeting
2. understand the user's date/time
3. localize meeting replies into the same language

Then code takes over for:

4. schedule rules
5. slot conflict checks
6. 30-minute buffer
7. saving pending meetings
8. saving real meetings
9. sending meeting links

## AI Flow for Offers

For offer-related messages, the AI role is:

1. detect whether the message is about offers
2. understand negotiation language
3. answer naturally from real offer data
4. keep the sales conversation moving

But the AI should not invent offer records.

## AI Flow for Documents

For company document requests, the AI role is limited.

The code first checks whether real external files exist.

If real files exist:

- the system sends them directly

If not:

- the AI may answer using website and file knowledge if allowed
- otherwise the code returns the fallback

## Short Summary

The WABA AI flow works like this:

1. detect the language of the latest message
2. run a router model for message signals
3. run an intent model for lead intent
4. use AI date parsing when needed
5. use code rules for meetings, files, offers, and lead status updates
6. build a final prompt from business knowledge
7. generate the final human-like reply
8. translate fixed replies when required

If you want the full non-AI message pipeline, read [WABA_MESSAGE_FLOW.md](/e:/Coding/api.Insale.ai/WABA_MESSAGE_FLOW.md).
