Architecting Bot Handoff Context Packages that Include Sentiment, Intent History, and Entities

Architecting Bot Handoff Context Packages that Include Sentiment, Intent History, and Entities

What This Guide Covers

This guide details the configuration of Genesys Cloud CX Architect flows to persist conversational state from a Conversational AI bot to human agents during handoff. You will configure a structured Context Package JSON schema to capture sentiment scores, intent stacks, and extracted entities without payload bloat. The end result is an agent interaction card that displays rich context immediately upon call or chat acceptance, eliminating the need for manual data gathering.

Prerequisites, Roles & Licensing

  • Licensing Tier: Genesys Cloud CX Enterprise (CCX) with Conversational AI add-on enabled. Standard CCX licenses do not support Context Package persistence beyond session boundaries.
  • Granular Permissions: The user configuring the flow requires ConversationalAI > Bot > Edit and Architect > Flow > Edit. For agent-side rendering, the queue must have Telephony > Queue > Edit access to modify interaction card layouts.
  • OAuth Scopes: If enriching context via API post-handoff, scopes include conversation.read, contextPackage.write, and contactcenter.conversation.read.
  • External Dependencies: A CRM integration is recommended for external entity resolution (e.g., mapping customer ID to account balance), though not strictly required for the Context Package itself.

The Implementation Deep-Dive

1. Defining the Context Package Schema

The foundation of a successful handoff is a robust JSON schema that defines what data travels with the interaction. In Genesys Cloud Architect, this occurs within the Set Context Package Variable node. Do not use raw string concatenation for complex data structures; this leads to parsing errors on the agent side and increases serialization latency.

You must define a hierarchical object structure where keys represent specific domains of conversation state. A recommended schema separates sentiment from factual entities to allow routing logic to react differently to emotional distress versus transactional data.

Architect Flow Node Configuration:

  1. Drag a Set Context Package Variable node into your flow after the final bot interaction step but before the Transfer Conversation or Assign To Queue node.
  2. Select Conversation Context Package as the variable type.
  3. Construct the JSON payload using the following structure. This ensures backward compatibility with agent screen pops that expect standard fields while allowing custom data injection.
{
  "botContext": {
    "version": "1.0",
    "timestamp": "$now.timestamp.iso8601",
    "sessionDurationSeconds": "$conversation.sessionDurationSeconds"
  },
  "sentimentAnalysis": {
    "score": "$conversationalAI.sentimentScore",
    "label": "$conversationalAI.sentimentLabel",
    "confidence": "$conversationalAI.confidence"
  },
  "intentHistory": [
    {
      "intentId": "$currentIntent.intentId",
      "timestamp": "$now.timestamp.iso8601",
      "utterance": "$conversation.lastUtterance"
    }
  ],
  "entities": {
    "customerId": "$entities.customerId",
    "orderNumber": "$entities.orderNumber",
    "accountStatus": "$entities.accountStatus"
  },
  "handoffMetadata": {
    "botName": "$flow.name",
    "handoffReason": "Agent Escalation",
    "priorityScore": "$conversationalAI.priorityScore"
  }
}

The Trap: The most common failure occurs when developers attempt to nest complex JSON arrays or objects within the intentHistory array without a defined limit. Genesys Cloud imposes a maximum payload size for Context Packages (typically 20KB per package instance). If the intent history grows indefinitely, the flow will throw a serialization error during the transfer node, causing the handoff to fail and the conversation to drop or loop in the bot.

Architectural Reasoning: We use a flat structure for entities but a constrained array for intentHistory. This is because agents primarily need current state (entities) for immediate action, while intent history is secondary context for case review. Limiting the intentHistory to the last 5 intents prevents payload bloat while retaining enough context for the agent to understand the conversation trajectory. We use $conversation.lastUtterance rather than full transcript storage because the transcript is already available in the interaction record; storing it again in the Context Package wastes bandwidth and increases parsing time on the Agent Desktop.

2. Populating Sentiment and Entity Data

Once the schema is defined, you must map flow variables to the JSON keys. This requires precise variable resolution at runtime. In Genesys Cloud Architect, variables populated by the Conversational AI node are prefixed with conversationalAI or entities.

Sentiment Mapping:
Use the Set Context Package Variable node to extract the sentiment score generated by the NLU engine. Ensure you handle cases where sentiment analysis fails (e.g., short text inputs).

// Architect Flow Expression for Sentiment Score
IF($conversationalAI.sentimentScore != null, $conversationalAI.sentimentScore, 0)

Entity Extraction Mapping:
Entities extracted by the bot must be mapped explicitly. If an entity is missing (e.g., the user has not provided a customer ID yet), do not leave it as null. Instead, use a default value or omit the key entirely to reduce payload size.

// Architect Flow Expression for Entity Handling
IF($entities.customerId != null, $entities.customerId, "UNKNOWN_ID")

The Trap: A frequent error involves passing raw flow variables that contain HTML tags or special characters without sanitization into the Context Package JSON. If a user inputs text like <script>alert(1)</script> during a chat session, and you pass this directly into the intentHistory array without escaping, it can break the JSON parser on the agent side. This results in an “Invalid JSON” error within the interaction card, leaving the agent with a blank screen.

Architectural Reasoning: We sanitize data at the variable mapping stage rather than relying on downstream parsers. The IF conditionals ensure that null values do not propagate as null strings but are handled gracefully. By defaulting to “UNKNOWN_ID”, we maintain the schema integrity so the agent UI does not crash. This approach assumes that the Agent Desktop application handles the display logic for “UNKNOWN” states, which is standard behavior in Genesys Cloud CX Interaction Cards.

3. The Handoff Action and Variable Persistence

The final step involves ensuring the Context Package survives the transfer event. You must configure the Transfer Conversation or Assign To Queue node to explicitly include the context package variable in the handoff payload. In Architect, this is often implicit for Context Packages, but explicit configuration ensures data integrity during cross-queue transfers.

Configuration Steps:

  1. Add a Transfer Conversation node immediately following the variable setting node.
  2. Set the Destination to your target Queue or specific Agent Group.
  3. In the Context Package field within the Transfer node configuration, ensure the variable name matches the one set in Step 1. If using multiple context packages, verify that the priority does not conflict.

API Payload Example for Programmatic Verification:
If you are validating this flow via API during a test deployment, you can inspect the Context Package data being attached to the contact object. This is useful for debugging why an agent is not seeing the data.

GET https://api.mypurecloud.com/api/v2/conversations/contacts/{contactId}/contextPackage HTTP/1.1
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "filter": "botContext, sentimentAnalysis, intentHistory"
}

The Trap: Developers often assume that setting the Context Package Variable makes it immediately visible on the Agent Desktop without queue configuration. The Context Package data exists in the backend, but the Agent Desktop Interaction Card must be configured to render specific fields from that package. If the queue does not have an associated interaction card layout that references these fields, the data is stored but invisible to the agent.

Architectural Reasoning: We separate the data persistence (Context Package) from the presentation layer (Interaction Card). This decoupling allows you to update the UI layout without touching the flow logic. The transfer node acts as a serialization point; it converts the in-memory variable structure into a persistent JSON blob attached to the contact record. If the destination queue does not support Context Packages, the data will be dropped silently unless error handling is implemented. Therefore, we verify that all target queues have ConversationContext enabled in their settings before deploying the flow.

4. Agent Side Consumption and Interaction Card Configuration

For this architecture to function, the agent interface must consume the package data. This requires configuring the Interaction Card layout for the specific queue receiving the handoff. You must add a “Custom JSON” or “Context Package” widget to the card layout that references the keys defined in your schema.

Configuration Steps:

  1. Navigate to Admin > Interaction Cards.
  2. Select the Queue receiving bot handoffs.
  3. Add a new widget of type Context Package.
  4. Map the widget fields to the JSON keys: botContext.version, sentimentAnalysis.label, etc.

The Trap: A common misconfiguration is mapping the entire Context Package object to a single text field, which renders raw JSON as readable text to the agent. This makes the data difficult to parse visually and wastes screen real estate. The correct approach is to map individual leaf nodes (e.g., sentimentAnalysis.label) to specific UI components like badges or status indicators.

Architectural Reasoning: We enforce field-level mapping to ensure consistent rendering across different device types (desktop vs. mobile agent). If you render raw JSON, the Agent Desktop may truncate long strings differently depending on the viewport width, leading to a poor user experience. By mapping specific fields to widgets, we control the layout and ensure that critical data points like sentimentAnalysis.label are always visible regardless of screen size. This also reduces the parsing load on the agent browser, as only the necessary DOM elements are rendered rather than a full JSON dump.

Validation, Edge Cases & Troubleshooting

Edge Case 1: Null Sentiment Values Due to NLU Failure

The failure condition: The bot flow executes successfully, but the conversation is transferred before sentiment analysis completes. The agent sees null or a default value that misrepresents user frustration.
The root cause: Asynchronous processing of sentiment scores sometimes lags behind the intent resolution. If the handoff occurs immediately after an utterance, the sentiment score may not be finalized in the conversationalAI object.
The solution: Implement a timeout or retry logic within the flow. Add a Wait node for 500 milliseconds after the last NLU interaction before setting the Context Package variable. Alternatively, check the confidence threshold. If confidence is below 0.6, flag the sentiment as “Unverified” in the package rather than displaying a score.

// Check Confidence Threshold
IF($conversationalAI.confidence > 0.6, $conversationalAI.sentimentScore, -1)

Edge Case 2: Intent History Stack Overflow

The failure condition: The flow loops multiple times (e.g., the user re-asks a question), causing the intentHistory array to exceed the 20KB Context Package limit.
The root cause: Unbounded array appending in the flow logic without size constraints.
The solution: Implement a truncation logic when setting the variable. Ensure the array never exceeds 10 items.

// Truncate History Array
IF($intentHistory.length > 10, $intentHistory.slice(0, 10), $intentHistory)

Edge Case 3: Cross-Queue Context Package Inheritance

The failure condition: The bot transfers the conversation to Queue A, which then transfers it to Queue B. The agent in Queue B does not see the original context package data.
The root cause: Some queue configurations reset or overwrite context packages during internal transfer events if inheritance is not explicitly enabled.
The solution: Ensure both queues have Context Package Inheritance enabled in their settings. This ensures that when a contact moves between queues, the Context Package payload travels with it rather than being cleared. Verify this setting under Admin > Queues > [Queue Name] > Advanced Settings.

Official References