Deal Notes Sentiment Analysis with Zia Assistant API, Workflow, Deluge in Zoho CRM

Deal Notes Sentiment Analysis with Zia Assistant API, Workflow, Deluge in Zoho CRM



Hello all! 
Welcome back to a fresh Kaizen week. 
In this post, we will explore how to detect negative sentiment in notes added to a deal in Zoho CRM using the Zia Assistant API with Workflow and Custom Functions.

Introduction

Sales teams capture every interaction in notes such as calls, emails, meetings, and feedback. These notes contain important signals that indicate whether a deal is progressing or at risk.
As deals grow, manually tracking every note becomes difficult. Important signals are often missed, leading to delayed actions.
This solution builds an automated system that reads notes, detects sentiment, assigns a risk score, tracks changes over time, sends alerts, and highlights high-risk deals.

Final output

Here is how the system automatically analyses and updates the deal when a negative sentiment note is added.


Let us look at an example scenario to understand the challenge.

Example Scenario

A team manages around 50 active deals, each with 8 to 10 notes. This results in hundreds of notes to review. It is not practical for a manager to read all of them. Signals like “customer is evaluating competitors” can easily go unnoticed, and by the time they are identified, the deal is already at risk.

The real cost of missed signals

When negative sentiment goes undetected:

What Happens

Business Impact

Customer says "too expensive" in a note

Deal lost to competitor offering lower price

Customer cancels 2 meetings in a row

Prevent deals from going cold by detecting repeated meeting cancellations early and triggering timely follow-ups.

Customer mentions "evaluating other options"

Identify when customers start evaluating other options and respond quickly before they finalize their decision.

Customer says "not a priority right now"

Deal sits in pipeline for months, inflating forecasts

The common thread? The warning signs were there in the notes, but no one caught them in time.

What sales teams need?
  1. Automatic monitoring of every deal note as it's added.
  2. Zia Assistant's analysis that understands context, not just keywords.
  3. Risk scoring that quantifies how much danger a deal is in.
  4. Trend tracking to see if things are getting better or worse.The system retrieves the existing risk from the deal and compares it with the new risk calculated by Zia. Based on this comparison, it sets the trend as Increasing, Decreasing, or Stable.
  5. Instant alerts via mail when a deal crosses into dangerous territory.

Solution

Using three native Zoho CRM capabilities with the Workflow Rule, Custom Functions, and Zia Assistant API, we built an end-to-end automation with 9 steps:
  1. Fetches deal details: Name, Stage, Amount, Close date, Owner, Existing risk.
  2. Collects all deal notes: Every note linked to the deal.
  3. Sends to Zia Assistant: With enhanced prompt and classification guidelines.
  4. Extracts AI response: Structured sentiment, Risk score, and AI Analysis.
  5. Parses & normalizes: Cleans up AI output to match exact field values.
  6. Calculates risk trend: Compares current risk vs previous risk.
  7. Updates deal record: Writes all 6 custom fields.
  8. Sends email alert: Notifies deal owner if risk > 8.
  9. Manages tags: Adds/removes High Risk Deal tag automatically.
The entire flow runs automatically in the background every time a note is added or modified. Zero manual effort from the sales team.

Prerequisites

Before implementing this solution, ensure you have:
  1. Zia Enabled:
    1. Follow these steps:
      1. Go to Setup.
      2. Navigate to Zia > Smart Prompt.
      3. Enable any one of the available LLM vendors. Please note that, except for Zia LLM, other vendors require a valid API key
                        

  1. CRM Connection: Connections with appropriate scopes.

Implementation steps

Step 1: Create custom fields

Navigate to Settings → Customization → Modules and Fields → Deals and create these 6 custom fields:

S.No

Field Label

API Name

Data Type

values

1

Risk

Risk

Picklist

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Risk: 1 = low risk, Risk 10 = high risk

2

Sentiment

Sentiment

Picklist

Positive, Neutral, Negative

3

AI Analysis

AI_Analysis

Multi-line Text

4

Previous Risk

Previous_Risk

Number

5

Risk Trend

Risk_Trend

Picklist

Increasing, Stable, Decreasing

6

Alert Sent

Alert_Sent

Checkbox


Note: After creating each field, verify the API Name matches exactly. Zoho sometimes appends numbers (example, Sentiment1) if a field name conflicts with existing or deleted fields. 

Step 2: Set up Zoho CRM Connection

  1. Go to Settings → Developer Space → Connections.
  2. Click Create Connection
  3. Select your services.
  4. Name the connection: zohocrm (used in this post)
  5. Add the required scopes
  6. Click Create and Connect
  7. Authorize the connection

Step 3: Create the custom function

  1. Go to Settings → Developer Space → Functions
  2. Click Create Function
  3. Display Name: Deal Notes Sentiment Analysis
  4. Function Name: DealNotesSentimentAnalysis
  5. Category: Automation
  6. Return Type: void
  7. Add Argument: dealId: Deals.Deal Id Type: int
  8. Click Save
      Note: The complete custom function code is provided at the end of this post.

Step 4: Configure the Workflow Rule

  1. Go to Settings → Automation → Workflow Rules
  2. Click Create Rule
  3. Module: Deals
  4. Rule Name: Deal Notes Sentiment Trigger
  5. When: A note is added or modified
  6. Condition: All Deals (or customize as needed)
  7. Instant Action: Associate the custom function →DealNotesSentimentAnalysis
  8. Map the dealId argument to the Deal's Record ID
  9. Click Save

What happens inside the custom function?

At this point, the workflow is fully set up. Whenever a note is added or modified in a deal, the workflow triggers the custom function. But what exactly happens inside this function?
Instead of going through the code line by line, let’s break it down into logical stages to understand how the system works end-to-end.
The snippets below highlight only the core logic for each step.

Note: The complete function code is provided in the next section for reference. You can use and adapt it based on your use case.

Step 1: Gathering complete deal context

The function begins by collecting key details about the deal:
  1.  Deal Name 
  2.  Stage 
  3.  Amount 
  4.  Close Date 
  5.  Deal Owner 
  6.  Existing Risk Score 
This ensures that the analysis is not done in isolation.
 The AI receives full deal context, which improves the accuracy of sentiment and risk evaluation.

dealData = zoho.crm.getRecordById("Deals", dealIdLong);
dealName   = ifnull(dealData.get("Deal_Name"), "");
dealStage  = ifnull(dealData.get("Stage"), "");
dealAmount = ifnull(dealData.get("Amount"), "0");
closeDate  = ifnull(dealData.get("Closing_Date"), "Not defined");
// Existing Risk
existingRisk = ifnull(dealData.get("Risk"), "0").toString().toNumber();
// Owner Info
owner = dealData.get("Owner");
ownerName  = ifnull(owner.get("name"), "");
ownerEmail = ifnull(owner.get("email"), "");


Step 2: Reading All deal notes

Next, the function fetches all notes associated with the deal.
Instead of analyzing only the latest note, it:
  1.  Collects every note.
  2.  Combines them into a structured format.
This allows the system to:
  1.  Identify repeated concerns.
  2.  Detect patterns across conversations.
  3.  Understand the overall direction of the deal.

dealNotes = zoho.crm.getRelatedRecords("Notes", "Deals", dealIdLong);

notesContext = "";
for each note in dealNotes
{
 notesContext = notesContext + "- " + ifnull(note.get("Note_Content"), "") + "\n";
}


Step 3: Sending data to Zia Assistant

The collected deal data and notes are sent to Zia Assistant using a carefully designed prompt.
The prompt includes:
  1.  Definitions of positive, negative, and neutral signals. 
  2.  Real-world sales scenarios (pricing concerns, delays, objections).
  3.  Clear risk scoring guidelines (1 to 10 scale).
This ensures that the AI response is:
  1.  Consistent.
  2.  Context-aware.
  3.  Aligned with real sales behavior.

chatEntry = Map();
chatEntry.put("role", "user");
chatEntry.put("content",
 "Deal Name: " + dealName +
 "\nStage: " + dealStage +
 "\nAmount: " + dealAmount +
 "\nClose Date: " + closeDate +
 "\n\n=== DEAL NOTES ===\n" + notesContext
);

assistantMap.put("chat_history", {chatEntry});
assistantMap.put("prompt", "<custom sentiment + scoring prompt>");

response = invokeurl
[
 type :POST
 parameters: payload.toString()
 connection:"zohocrm"
];

This is where AI transforms raw notes into structured insights.

Step 4: Interpreting the AI response

Zia Assistant analyzes the input and returns a structured response containing:
  1. Overall Sentiment (Positive / Neutral / Negative) 
  2.  Risk Score (1–10) 
  3.  AI Analysis (brief reasoning) 
The function extracts these values for further processing.


aiText = "";

if(response.get("assistant") != null)
{
 aiText = response.get("assistant").get("details").get("data");
}


Step 5: Normalizing the output

Since AI responses can vary slightly in format, the function standardizes the output:
  1. Ensures sentiment matches exact CRM field values 
  2.  Validates risk score within the 1–10 range 
  3.  Cleans up any extra characters or formatting 
This step ensures clean and consistent data inside the CRM.


// Extract & clean risk
riskLine = riskLine.replaceAll("[^0-9]", "", false);
riskScore = riskLine.toNumber();
if(riskScore > 10) riskScore = 10;
if(riskScore < 1)  riskScore = 1;

// Normalize sentiment
sentimentLower = sentiment.toLowerCase();
if(sentimentLower.contains("negative")) sentiment = "Negative";
else if(sentimentLower.contains("positive")) sentiment = "Positive";
else sentiment = "Neutral";


Step 6: Calculating risk trend

The system then compares:
  1. Previous Risk Score 
  2.  Current Risk Score 
Based on this, it determines whether the deal is:
  1. Increasing in risk
  2. Decreasing in risk
  3. Stable
This adds an important layer of intelligence and not just what the risk is, but how it is changing over time.


riskTrend = "Stable";

if(riskScore > existingRisk)
{
    riskTrend = "Increasing";
}
else if(riskScore < existingRisk)
{
    riskTrend = "Decreasing";
}



Step 7: Updating the deal record

Once all values are processed, the function updates the deal with:
  1. Risk 
  2.  Sentiment 
  3.  AI Analysis 
  4.  Previous Risk 
  5.  Risk Trend 
  6.  Alert Sent Flag 
At this stage, the deal record becomes a live reflection of customer sentiment.


updateMap = Map();
updateMap.put("Risk", riskScore.toString());
updateMap.put("Sentiment", sentiment);
updateMap.put("AI_Analysis", analysis);
updateMap.put("Previous_Risk", existingRisk.toString());
updateMap.put("Risk_Trend", riskTrend);
zoho.crm.updateRecord("Deals", dealIdLong, updateMap);


Step 8: Smart email alerting

If the risk score crosses a threshold (Risk > 8), the system triggers an alert to the record owner to take immediate action.
An email is sent to the Deal Owner with:
  1. Deal details 
  2. Risk score 
  3. Sentiment 
  4. Risk trend 
  5. AI analysis 
To avoid alert:
  1. The system checks whether an alert has already been sent. 
  2.  A new alert is triggered only if the risk increases further.
previousAlertSent = ifnull(dealData.get("Alert_Sent"), false);

if(riskScore > 8 && (previousAlertSent == false || riskScore > existingRisk) && ownerEmail != "")
{
    // Send alert email
    mailPayload = {
        "from": {"user_name": ownerName, "email": zoho.crm.getOrgVariable("defaultMail")},
        "to": {{"user_name": ownerName, "email": ownerEmail}},
        "subject": "🚨 Deal At Risk: " + dealName,
        "content": "Risk Score: " + riskScore + "/10<br>Sentiment: " + sentiment + "<br><br>" + analysis,
        "mail_format": "html"
    };

    invokeurl
    [
        url :"https://www.zohoapis.com/crm/v8/Deals/" + dealIdLong + "/actions/send_mail"
        type :POST
        parameters: {"data": {mailPayload}}.toString()
        headers: {"Content-Type":"application/json"}
        connection: "zohocrm"
    ];

    zoho.crm.updateRecord("Deals", dealIdLong, {"Alert_Sent": true});
}
else if(riskScore <= 8)
{
    // Reset alert flag
    zoho.crm.updateRecord("Deals", dealIdLong, {"Alert_Sent": false});
}

Step 9: Dynamic tag management

Finally, the system visually marks high-risk deals:
  1.  If Risk > 8 → Adds tag “High Risk Deal”
  2.  If Risk reduces → Removes the tag automatically 
This makes it easy for users to:
  1.  Identify risky deals instantly 
  2.  Prioritize follow-ups 

if(riskScore > 8)
{
 invokeurl
 [
 url :"https://www.zohoapis.com/crm/v8/Deals/" + dealIdLong + "/actions/add_tags"
 type :POST
 parameters: tagPayload.toString()
 connection:"zohocrm"
 ];
}
else
{
 invokeurl
 [
 url :"https://www.zohoapis.com/crm/v8/Deals/" + dealIdLong + "/actions/remove_tags"
 type :POST
 parameters: tagPayload.toString()
 connection:"zohocrm"
 ];



Complete custom function code
The complete Deluge script used in this implementation is provided below for reference and direct use:

Notes
  1. To get better sentiment detection, use a clear and strong prompt in the Zia Assistant API.
  2. The output depends on how well the prompt defines positive, negative, and neutral signals.
  3. Zia looks at the overall trend of notes, not just one note.
  4. If a deal had negative notes earlier but recent notes are positive, the risk (Risk field ) will decrease
  5. If new negative notes are added, the risk will increase.
  6. Sometimes Zia Assistant may not detect sentiment perfectly, as it is AI-based

Conclusion

This automation transforms deal notes from passive text into actionable intelligence. Instead of relying on sales managers to read hundreds of notes manually, Zia Assistant does it automatically detecting sentiment, scoring risk, tracking trends, alerting owners, and tagging high-risk deals all in real time.

We trust that this post meets your needs and is helpful. Let us know your thoughts in the comment section or reach out to us at support@zohocrm.com

Stay tuned for more insights in our upcoming Kaizen posts!

Happy coding!!!

Related Links:
  1. Kaizen Index
  2. Kaizen Directory
  3. API Directory
  4. Zoho CRM API Document