How to Build AI-Driven Customer Support Intelligence with Estuary and Snowflake Cortex
Is your business sitting on a treasure trove of customer support data? Learn how to build an AI-powered pipeline using Estuary and Snowflake Cortex to turn that data into actionable intelligence.
Customer support data is one of the richest but most underutilized operational signals. While companies collect massive volumes of complaint tickets, chats, transcripts and product reviews, most pipelines still process this data in batches, leaving support teams reacting hours—or days—too late. Streaming ingestion combined with native AI inference opens the door to a fundamentally different model: continuous support intelligence. Understanding the nature of customer issues, their frequency, and emerging patterns can directly inform product improvements, operational fixes, and customer experience strategy.
In this article, we’ll build an AI-powered customer support intelligence pipeline that ingests, enriches, and operationalizes support case data. To simulate a production-scale environment, we first apply prompt engineering with OpenAI in Python script to generate high-fidelity synthetic support tickets that reflect realistic customer language, urgency, and issue diversity. By combining Estuary for right-time ingestion with Snowflake Cortex AI to automatically summarize, classify, and recommend next-best actions on support cases, this solution demonstrates how modern data platforms can transform raw support interactions into structured, actionable intelligence.
On Snowflake Cortex AI
Recent advances in data engineering and AI are transforming how organizations operationalize customer support data. Traditional pipelines primarily support retrospective reporting, but platforms like Snowflake now enable AI inference directly where the data resides. With native capabilities such as Snowflake Cortex AI, teams can summarize, classify, and semantically analyze large volumes of support interactions without exporting data to external ML systems.
Because Cortex runs within Snowflake’s secure compute environment, it reduces architectural complexity while improving latency, governance, and scalability. Data teams can invoke LLM-powered functions directly in SQL to enrich support cases in near real time—turning the warehouse from passive storage into an active intelligence engine for faster operational decisions.
Cortex Search and RAG Foundations
Retrieval Augmented Generation (RAG) is a pattern that enhances large language model responses by grounding them in relevant enterprise data. Rather than relying solely on the model’s pretrained knowledge, RAG retrieves semantically similar records from a curated knowledge base and injects that context into the generation step. This is particularly powerful for customer support scenarios, where historical cases, resolution notes, and product-specific issues provide critical context for accurate recommendations.
One example of this is Snowflake Cortex Search. It provides the semantic retrieval layer needed to implement this pattern natively within the data platform. By indexing unstructured support text and enabling vector-based similarity search, Cortex Search allows applications and agents to quickly locate relevant past cases. When combined with Cortex LLM functions (such as COMPLETE or SUMMARIZE), this creates a foundation for enterprise support copilots that can retrieve similar incidents, generate agent-ready summaries, and recommend next-best actions.
In this project, you’ll learn how to leverage Snowflake Cortex to:
Automatically summarize incoming support tickets.
Perform sentiment and issue analysis.
Generate AI-driven next-step recommendations for agents.
Where Estuary Fits - Webhook Based Ingestion
While Snowflake Cortex provides the intelligence layer, the effectiveness of any real-time AI system depends on how quickly fresh data arrives. This is where Estuary plays a critical role as the right-time data movement platform in the architecture.
In this pipeline, Estuary is responsible for continuously ingesting customer support case events and delivering them into Snowflake with low latency and high reliability. Rather than relying on batch uploads or scheduled ETL jobs, Estuary enables a streaming-first pattern where support interactions become available for AI enrichment within seconds of being generated. This ensures that Cortex models always operate on the most current customer signals.
Webhooks are used as the ingestion mechanism because customer support systems are inherently event-driven. Each new ticket, update, or customer message represents a discrete event that should be processed immediately. Compared to polling-based ingestion, webhooks provide:
Lower latency - events are pushed as they occur
Greater efficiency — no need for constant polling
Simpler integration with SaaS support platforms
Better scalability for bursty ticket volumes
By pairing webhook-based ingestion with Estuary’s exactly-once delivery and schema evolution handling, the pipeline achieves a robust foundation for real-time support intelligence. The result is an architecture where customer support data flows continuously from source to warehouse to AI enrichment, enabling faster detection of risk, quicker agent response, and more proactive customer experience management.
Overview of the Pipeline
This architecture shows how synthetic customer feedback is generated with Python and the OpenAI API, streamed to Snowflake via Estuary, and analyzed using Snowflake Cortex AI for AI-powered support workflows.
Prompt-engineered support cases stream through Estuary into Snowflake, where Cortex AI continuously analyzes, classifies, and operationalizes customer support intelligence in near real time.
The Architecture:
Data Generation Layer: Prompt Engineering (Python + OpenAI)
Right-Time Ingestion Layer: Estuary Webhooks to continuously stream support events into Snowflake
Data Platform Layer: Snowflake (Storage + Modeling)
Intelligence Layer: Snowflake Cortex AI
Semantic Layer: Cortex Search/AI Functions
Pre-requisites
Before we jump in, make sure you have the following:
Estuary: Sign up for a free trial of Estuary, which will be used to ingest API data via HTTP/Webhooks and stream it into Snowflake.
Snowflake: Sign up for a 30-day free trial of Snowflake Trial, which will serve as the analytical warehouse and used for Cortex AI features.
Any Python IDE: Any IDE capable of running Python scripts (e.g., VS Code, PyCharm) for generating data and interacting with APIs.
OpenAI API Key: An OpenAI API key is required to simulate events using LLM-powered prompt engineering.
Step-by-Step Guide Implementation
Step 1: Generate Support Case Records via Prompt Engineering (Python Script + OpenAI)
You’ll generate structured support case JSON records that resemble real support systems (billing, shipping, product defects, etc.), including lifecycle timestamps and resolution states.
importosimportjsonimportrequestsfromdatetimeimportdatetimefromopenaiimportOpenAIimportreimporttimeOPENAI_API_KEY = <YOUR_OPENAPI_KEY>
ESTUARY_WEBHOOK = <YOUR_WEBHOOK_LINK>
ESTUARY_API_KEY = <BEARER_TOKEN>
BATCH_SIZE = 30DEBUG = Trueclient = OpenAI(api_key=OPENAI_API_KEY)defgenerate_interactions(batch_size=30):
prompt = f"""
Generate {batch_size} realistic customer support CASE records for an eCommerce platform.
IMPORTANT CONTEXT:
These are full support cases (not chat turns). Each record represents one customer support ticket from creation to resolution.
Each record is ONE support case.
CUSTOMER DISTRIBUTION (VERY IMPORTANT):
• Approximately 70% of customers should appear in ONLY ONE case.
• Approximately 30% of customers should appear in 2-3 cases.
• DO NOT assign all cases to the same customer.
• DO NOT create a unique customer for every case.
• The dataset must contain a realistic mix of repeat and one-time customers.
WRITING STYLE:
- Use natural, messy human language in descriptions.
- Include frustration, urgency, politeness, and occasional mild sarcasm.
- Make scenarios realistic (delivery delays, billing issues, product defects, etc.).
- Do NOT repeat templates.
TIMESTAMP RULES:
- Use ISO 8601 UTC format.
- date_closed must be AFTER date_created.
- If status = "open" then date_closed = null.
ID RULES:
- case_id format: CASE-##### (unique)
- customer_id format: CUST-###### (realistic)
VALID TAXONOMY
query_type → intent:
invoice: check_invoice, get_invoice
order: cancel_order, change_order, place_order, track_order
payment: check_payment_method, payment_issue
refund: refund_policy, get_refund
shipping: change_shipping_address, setup_shipping
review_feedback: complaint, review
contact: customer_service, human_agent
issue_category options:
- billing
- delivery
- product_defect
- account_access
- general_inquiry
priority options:
- low
- medium
- high
- urgent
status options:
- open
- in_progress
- resolved
- escalated
handled_by options:
- bot
- agent
channel options:
- chat
- email
- phone
- web
REQUIRED FIELDS (STRICT):
- case_id
- customer_id
- timestamp
- date_created
- date_closed
- status
- required_escalation
- query_type
- intent
- issue_category
- priority
- handled_by
- response_time_min (integer 1-120)
- number_of_calls (integer 0-5)
- concerns_addressed (boolean)
- interaction_cost (float USD)
- product_sku
- category
- price
- channel
- location
- case_title
- case_description
- last_update_note
DATA REALISM RULES:
- urgent cases more likely to escalate
- product_defect often negative tone
- delivery issues common
- some cases unresolved
- vary locations across US
- price must match realistic ecommerce ranges
- response_time_min higher for escalations
- NOT all cases should be resolved
Return ONLY valid JSON in this exact format:
{{
"records": [ ... ]
}}
No markdown. No explanations. Only JSON.
"""response = client.chat.completions.create(model="gpt-4o-mini",temperature=0.7,response_format={"type": "json_object"},messages=[{"role": "user","content": prompt}],)content = response.choices[0].message.contentifnotcontent:
raiseValueError("Empty model response")# --- robust JSON parsing ---try:
data = json.loads(content)exceptjson.JSONDecodeError:
ifDEBUG:
print("⚠️ Raw model output (first 1000 chars):")print(content[:1000])# Try to extract JSON object safelymatch = re.search(r"\{.*\}",content,re.DOTALL)ifnotmatch:
raiseValueError("Failed to locate JSON object")data = json.loads(match.group())records = data.get("records")ifnotisinstance(records,list):
raiseValueError("JSON missing 'records' array")returnrecordsdefbuild_estuary_payload(records):
ifnotrecords:
raiseValueError("No records to build payload")forrinrecords:
priority = (r.get("priority")or"").lower()status = (r.get("status")or"").lower()return[{**r,"is_high_priority": priorityin("high","urgent"),"needs_escalation": (priority == "urgent"orstatus == "escalated"orr.get("required_escalation")isTrue),}forrinrecords]defsend_to_estuary(records: list) -> None:
headers = {"Content-Type": "application/json","Authorization": "Bearer " + ESTUARY_API_KEY,}forrinrecords:
try:
response = requests.post(ESTUARY_WEBHOOK,headers=headers,json=r,timeout=10,)ifresponse.status_codein(200,201,202):
print(f"✅ Estuary ingest success ({response.status_code})")else:
print(f"❌ Failed ({response.status_code}): {response.text}")exceptrequests.exceptions.RequestExceptionase:
print("🚨 Network error:",str(e))defrun_once():
records = generate_interactions(BATCH_SIZE)ifnotisinstance(records,list)ornotrecords:
raiseValueError("Generator returned invalid data")print(f"📊 Generated {len(records)} records")documents = build_estuary_payload(records)ifDEBUG:
print("\n=== SAMPLE DOCUMENT ===")print(json.dumps(documents[0],indent=2))print("\nSending to Estuary...")send_to_estuary(documents)print("Batch complete\n")if__name__ == "__main__":
whileTrue:
run_once()# time.sleep(30)
importosimportjsonimportrequestsfromdatetimeimportdatetimefromopenaiimportOpenAIimportreimporttimeOPENAI_API_KEY = <YOUR_OPENAPI_KEY>
ESTUARY_WEBHOOK = <YOUR_WEBHOOK_LINK>
ESTUARY_API_KEY = <BEARER_TOKEN>
BATCH_SIZE = 30DEBUG = Trueclient = OpenAI(api_key=OPENAI_API_KEY)defgenerate_interactions(batch_size=30):
prompt = f"""
Generate {batch_size} realistic customer support CASE records for an eCommerce platform.
IMPORTANT CONTEXT:
These are full support cases (not chat turns). Each record represents one customer support ticket from creation to resolution.
Each record is ONE support case.
CUSTOMER DISTRIBUTION (VERY IMPORTANT):
• Approximately 70% of customers should appear in ONLY ONE case.
• Approximately 30% of customers should appear in 2-3 cases.
• DO NOT assign all cases to the same customer.
• DO NOT create a unique customer for every case.
• The dataset must contain a realistic mix of repeat and one-time customers.
WRITING STYLE:
- Use natural, messy human language in descriptions.
- Include frustration, urgency, politeness, and occasional mild sarcasm.
- Make scenarios realistic (delivery delays, billing issues, product defects, etc.).
- Do NOT repeat templates.
TIMESTAMP RULES:
- Use ISO 8601 UTC format.
- date_closed must be AFTER date_created.
- If status = "open" then date_closed = null.
ID RULES:
- case_id format: CASE-##### (unique)
- customer_id format: CUST-###### (realistic)
VALID TAXONOMY
query_type → intent:
invoice: check_invoice, get_invoice
order: cancel_order, change_order, place_order, track_order
payment: check_payment_method, payment_issue
refund: refund_policy, get_refund
shipping: change_shipping_address, setup_shipping
review_feedback: complaint, review
contact: customer_service, human_agent
issue_category options:
- billing
- delivery
- product_defect
- account_access
- general_inquiry
priority options:
- low
- medium
- high
- urgent
status options:
- open
- in_progress
- resolved
- escalated
handled_by options:
- bot
- agent
channel options:
- chat
- email
- phone
- web
REQUIRED FIELDS (STRICT):
- case_id
- customer_id
- timestamp
- date_created
- date_closed
- status
- required_escalation
- query_type
- intent
- issue_category
- priority
- handled_by
- response_time_min (integer 1-120)
- number_of_calls (integer 0-5)
- concerns_addressed (boolean)
- interaction_cost (float USD)
- product_sku
- category
- price
- channel
- location
- case_title
- case_description
- last_update_note
DATA REALISM RULES:
- urgent cases more likely to escalate
- product_defect often negative tone
- delivery issues common
- some cases unresolved
- vary locations across US
- price must match realistic ecommerce ranges
- response_time_min higher for escalations
- NOT all cases should be resolved
Return ONLY valid JSON in this exact format:
{{
"records": [ ... ]
}}
No markdown. No explanations. Only JSON.
"""response = client.chat.completions.create(model="gpt-4o-mini",temperature=0.7,response_format={"type": "json_object"},messages=[{"role": "user","content": prompt}],)content = response.choices[0].message.contentifnotcontent:
raiseValueError("Empty model response")# --- robust JSON parsing ---try:
data = json.loads(content)exceptjson.JSONDecodeError:
ifDEBUG:
print("⚠️ Raw model output (first 1000 chars):")print(content[:1000])# Try to extract JSON object safelymatch = re.search(r"\{.*\}",content,re.DOTALL)ifnotmatch:
raiseValueError("Failed to locate JSON object")data = json.loads(match.group())records = data.get("records")ifnotisinstance(records,list):
raiseValueError("JSON missing 'records' array")returnrecordsdefbuild_estuary_payload(records):
ifnotrecords:
raiseValueError("No records to build payload")forrinrecords:
priority = (r.get("priority")or"").lower()status = (r.get("status")or"").lower()return[{**r,"is_high_priority": priorityin("high","urgent"),"needs_escalation": (priority == "urgent"orstatus == "escalated"orr.get("required_escalation")isTrue),}forrinrecords]defsend_to_estuary(records: list) -> None:
headers = {"Content-Type": "application/json","Authorization": "Bearer " + ESTUARY_API_KEY,}forrinrecords:
try:
response = requests.post(ESTUARY_WEBHOOK,headers=headers,json=r,timeout=10,)ifresponse.status_codein(200,201,202):
print(f"✅ Estuary ingest success ({response.status_code})")else:
print(f"❌ Failed ({response.status_code}): {response.text}")exceptrequests.exceptions.RequestExceptionase:
print("🚨 Network error:",str(e))defrun_once():
records = generate_interactions(BATCH_SIZE)ifnotisinstance(records,list)ornotrecords:
raiseValueError("Generator returned invalid data")print(f"📊 Generated {len(records)} records")documents = build_estuary_payload(records)ifDEBUG:
print("\n=== SAMPLE DOCUMENT ===")print(json.dumps(documents[0],indent=2))print("\nSending to Estuary...")send_to_estuary(documents)print("Batch complete\n")if__name__ == "__main__":
whileTrue:
run_once()# time.sleep(30)
importosimportjsonimportrequestsfromdatetimeimportdatetimefromopenaiimportOpenAIimportreimporttimeOPENAI_API_KEY = <YOUR_OPENAPI_KEY>
ESTUARY_WEBHOOK = <YOUR_WEBHOOK_LINK>
ESTUARY_API_KEY = <BEARER_TOKEN>
BATCH_SIZE = 30DEBUG = Trueclient = OpenAI(api_key=OPENAI_API_KEY)defgenerate_interactions(batch_size=30):
prompt = f"""
Generate {batch_size} realistic customer support CASE records for an eCommerce platform.
IMPORTANT CONTEXT:
These are full support cases (not chat turns). Each record represents one customer support ticket from creation to resolution.
Each record is ONE support case.
CUSTOMER DISTRIBUTION (VERY IMPORTANT):
• Approximately 70% of customers should appear in ONLY ONE case.
• Approximately 30% of customers should appear in 2-3 cases.
• DO NOT assign all cases to the same customer.
• DO NOT create a unique customer for every case.
• The dataset must contain a realistic mix of repeat and one-time customers.
WRITING STYLE:
- Use natural, messy human language in descriptions.
- Include frustration, urgency, politeness, and occasional mild sarcasm.
- Make scenarios realistic (delivery delays, billing issues, product defects, etc.).
- Do NOT repeat templates.
TIMESTAMP RULES:
- Use ISO 8601 UTC format.
- date_closed must be AFTER date_created.
- If status = "open" then date_closed = null.
ID RULES:
- case_id format: CASE-##### (unique)
- customer_id format: CUST-###### (realistic)
VALID TAXONOMY
query_type → intent:
invoice: check_invoice, get_invoice
order: cancel_order, change_order, place_order, track_order
payment: check_payment_method, payment_issue
refund: refund_policy, get_refund
shipping: change_shipping_address, setup_shipping
review_feedback: complaint, review
contact: customer_service, human_agent
issue_category options:
- billing
- delivery
- product_defect
- account_access
- general_inquiry
priority options:
- low
- medium
- high
- urgent
status options:
- open
- in_progress
- resolved
- escalated
handled_by options:
- bot
- agent
channel options:
- chat
- email
- phone
- web
REQUIRED FIELDS (STRICT):
- case_id
- customer_id
- timestamp
- date_created
- date_closed
- status
- required_escalation
- query_type
- intent
- issue_category
- priority
- handled_by
- response_time_min (integer 1-120)
- number_of_calls (integer 0-5)
- concerns_addressed (boolean)
- interaction_cost (float USD)
- product_sku
- category
- price
- channel
- location
- case_title
- case_description
- last_update_note
DATA REALISM RULES:
- urgent cases more likely to escalate
- product_defect often negative tone
- delivery issues common
- some cases unresolved
- vary locations across US
- price must match realistic ecommerce ranges
- response_time_min higher for escalations
- NOT all cases should be resolved
Return ONLY valid JSON in this exact format:
{{
"records": [ ... ]
}}
No markdown. No explanations. Only JSON.
"""response = client.chat.completions.create(model="gpt-4o-mini",temperature=0.7,response_format={"type": "json_object"},messages=[{"role": "user","content": prompt}],)content = response.choices[0].message.contentifnotcontent:
raiseValueError("Empty model response")# --- robust JSON parsing ---try:
data = json.loads(content)exceptjson.JSONDecodeError:
ifDEBUG:
print("⚠️ Raw model output (first 1000 chars):")print(content[:1000])# Try to extract JSON object safelymatch = re.search(r"\{.*\}",content,re.DOTALL)ifnotmatch:
raiseValueError("Failed to locate JSON object")data = json.loads(match.group())records = data.get("records")ifnotisinstance(records,list):
raiseValueError("JSON missing 'records' array")returnrecordsdefbuild_estuary_payload(records):
ifnotrecords:
raiseValueError("No records to build payload")forrinrecords:
priority = (r.get("priority")or"").lower()status = (r.get("status")or"").lower()return[{**r,"is_high_priority": priorityin("high","urgent"),"needs_escalation": (priority == "urgent"orstatus == "escalated"orr.get("required_escalation")isTrue),}forrinrecords]defsend_to_estuary(records: list) -> None:
headers = {"Content-Type": "application/json","Authorization": "Bearer " + ESTUARY_API_KEY,}forrinrecords:
try:
response = requests.post(ESTUARY_WEBHOOK,headers=headers,json=r,timeout=10,)ifresponse.status_codein(200,201,202):
print(f"✅ Estuary ingest success ({response.status_code})")else:
print(f"❌ Failed ({response.status_code}): {response.text}")exceptrequests.exceptions.RequestExceptionase:
print("🚨 Network error:",str(e))defrun_once():
records = generate_interactions(BATCH_SIZE)ifnotisinstance(records,list)ornotrecords:
raiseValueError("Generator returned invalid data")print(f"📊 Generated {len(records)} records")documents = build_estuary_payload(records)ifDEBUG:
print("\n=== SAMPLE DOCUMENT ===")print(json.dumps(documents[0],indent=2))print("\nSending to Estuary...")send_to_estuary(documents)print("Batch complete\n")if__name__ == "__main__":
whileTrue:
run_once()# time.sleep(30)
importosimportjsonimportrequestsfromdatetimeimportdatetimefromopenaiimportOpenAIimportreimporttimeOPENAI_API_KEY = <YOUR_OPENAPI_KEY>
ESTUARY_WEBHOOK = <YOUR_WEBHOOK_LINK>
ESTUARY_API_KEY = <BEARER_TOKEN>
BATCH_SIZE = 30DEBUG = Trueclient = OpenAI(api_key=OPENAI_API_KEY)defgenerate_interactions(batch_size=30):
prompt = f"""
Generate {batch_size} realistic customer support CASE records for an eCommerce platform.
IMPORTANT CONTEXT:
These are full support cases (not chat turns). Each record represents one customer support ticket from creation to resolution.
Each record is ONE support case.
CUSTOMER DISTRIBUTION (VERY IMPORTANT):
• Approximately 70% of customers should appear in ONLY ONE case.
• Approximately 30% of customers should appear in 2-3 cases.
• DO NOT assign all cases to the same customer.
• DO NOT create a unique customer for every case.
• The dataset must contain a realistic mix of repeat and one-time customers.
WRITING STYLE:
- Use natural, messy human language in descriptions.
- Include frustration, urgency, politeness, and occasional mild sarcasm.
- Make scenarios realistic (delivery delays, billing issues, product defects, etc.).
- Do NOT repeat templates.
TIMESTAMP RULES:
- Use ISO 8601 UTC format.
- date_closed must be AFTER date_created.
- If status = "open" then date_closed = null.
ID RULES:
- case_id format: CASE-##### (unique)
- customer_id format: CUST-###### (realistic)
VALID TAXONOMY
query_type → intent:
invoice: check_invoice, get_invoice
order: cancel_order, change_order, place_order, track_order
payment: check_payment_method, payment_issue
refund: refund_policy, get_refund
shipping: change_shipping_address, setup_shipping
review_feedback: complaint, review
contact: customer_service, human_agent
issue_category options:
- billing
- delivery
- product_defect
- account_access
- general_inquiry
priority options:
- low
- medium
- high
- urgent
status options:
- open
- in_progress
- resolved
- escalated
handled_by options:
- bot
- agent
channel options:
- chat
- email
- phone
- web
REQUIRED FIELDS (STRICT):
- case_id
- customer_id
- timestamp
- date_created
- date_closed
- status
- required_escalation
- query_type
- intent
- issue_category
- priority
- handled_by
- response_time_min (integer 1-120)
- number_of_calls (integer 0-5)
- concerns_addressed (boolean)
- interaction_cost (float USD)
- product_sku
- category
- price
- channel
- location
- case_title
- case_description
- last_update_note
DATA REALISM RULES:
- urgent cases more likely to escalate
- product_defect often negative tone
- delivery issues common
- some cases unresolved
- vary locations across US
- price must match realistic ecommerce ranges
- response_time_min higher for escalations
- NOT all cases should be resolved
Return ONLY valid JSON in this exact format:
{{
"records": [ ... ]
}}
No markdown. No explanations. Only JSON.
"""response = client.chat.completions.create(model="gpt-4o-mini",temperature=0.7,response_format={"type": "json_object"},messages=[{"role": "user","content": prompt}],)content = response.choices[0].message.contentifnotcontent:
raiseValueError("Empty model response")# --- robust JSON parsing ---try:
data = json.loads(content)exceptjson.JSONDecodeError:
ifDEBUG:
print("⚠️ Raw model output (first 1000 chars):")print(content[:1000])# Try to extract JSON object safelymatch = re.search(r"\{.*\}",content,re.DOTALL)ifnotmatch:
raiseValueError("Failed to locate JSON object")data = json.loads(match.group())records = data.get("records")ifnotisinstance(records,list):
raiseValueError("JSON missing 'records' array")returnrecordsdefbuild_estuary_payload(records):
ifnotrecords:
raiseValueError("No records to build payload")forrinrecords:
priority = (r.get("priority")or"").lower()status = (r.get("status")or"").lower()return[{**r,"is_high_priority": priorityin("high","urgent"),"needs_escalation": (priority == "urgent"orstatus == "escalated"orr.get("required_escalation")isTrue),}forrinrecords]defsend_to_estuary(records: list) -> None:
headers = {"Content-Type": "application/json","Authorization": "Bearer " + ESTUARY_API_KEY,}forrinrecords:
try:
response = requests.post(ESTUARY_WEBHOOK,headers=headers,json=r,timeout=10,)ifresponse.status_codein(200,201,202):
print(f"✅ Estuary ingest success ({response.status_code})")else:
print(f"❌ Failed ({response.status_code}): {response.text}")exceptrequests.exceptions.RequestExceptionase:
print("🚨 Network error:",str(e))defrun_once():
records = generate_interactions(BATCH_SIZE)ifnotisinstance(records,list)ornotrecords:
raiseValueError("Generator returned invalid data")print(f"📊 Generated {len(records)} records")documents = build_estuary_payload(records)ifDEBUG:
print("\n=== SAMPLE DOCUMENT ===")print(json.dumps(documents[0],indent=2))print("\nSending to Estuary...")send_to_estuary(documents)print("Batch complete\n")if__name__ == "__main__":
whileTrue:
run_once()# time.sleep(30)
importosimportjsonimportrequestsfromdatetimeimportdatetimefromopenaiimportOpenAIimportreimporttimeOPENAI_API_KEY = <YOUR_OPENAPI_KEY>
ESTUARY_WEBHOOK = <YOUR_WEBHOOK_LINK>
ESTUARY_API_KEY = <BEARER_TOKEN>
BATCH_SIZE = 30DEBUG = Trueclient = OpenAI(api_key=OPENAI_API_KEY)defgenerate_interactions(batch_size=30):
prompt = f"""
Generate {batch_size} realistic customer support CASE records for an eCommerce platform.
IMPORTANT CONTEXT:
These are full support cases (not chat turns). Each record represents one customer support ticket from creation to resolution.
Each record is ONE support case.
CUSTOMER DISTRIBUTION (VERY IMPORTANT):
• Approximately 70% of customers should appear in ONLY ONE case.
• Approximately 30% of customers should appear in 2-3 cases.
• DO NOT assign all cases to the same customer.
• DO NOT create a unique customer for every case.
• The dataset must contain a realistic mix of repeat and one-time customers.
WRITING STYLE:
- Use natural, messy human language in descriptions.
- Include frustration, urgency, politeness, and occasional mild sarcasm.
- Make scenarios realistic (delivery delays, billing issues, product defects, etc.).
- Do NOT repeat templates.
TIMESTAMP RULES:
- Use ISO 8601 UTC format.
- date_closed must be AFTER date_created.
- If status = "open" then date_closed = null.
ID RULES:
- case_id format: CASE-##### (unique)
- customer_id format: CUST-###### (realistic)
VALID TAXONOMY
query_type → intent:
invoice: check_invoice, get_invoice
order: cancel_order, change_order, place_order, track_order
payment: check_payment_method, payment_issue
refund: refund_policy, get_refund
shipping: change_shipping_address, setup_shipping
review_feedback: complaint, review
contact: customer_service, human_agent
issue_category options:
- billing
- delivery
- product_defect
- account_access
- general_inquiry
priority options:
- low
- medium
- high
- urgent
status options:
- open
- in_progress
- resolved
- escalated
handled_by options:
- bot
- agent
channel options:
- chat
- email
- phone
- web
REQUIRED FIELDS (STRICT):
- case_id
- customer_id
- timestamp
- date_created
- date_closed
- status
- required_escalation
- query_type
- intent
- issue_category
- priority
- handled_by
- response_time_min (integer 1-120)
- number_of_calls (integer 0-5)
- concerns_addressed (boolean)
- interaction_cost (float USD)
- product_sku
- category
- price
- channel
- location
- case_title
- case_description
- last_update_note
DATA REALISM RULES:
- urgent cases more likely to escalate
- product_defect often negative tone
- delivery issues common
- some cases unresolved
- vary locations across US
- price must match realistic ecommerce ranges
- response_time_min higher for escalations
- NOT all cases should be resolved
Return ONLY valid JSON in this exact format:
{{
"records": [ ... ]
}}
No markdown. No explanations. Only JSON.
"""response = client.chat.completions.create(model="gpt-4o-mini",temperature=0.7,response_format={"type": "json_object"},messages=[{"role": "user","content": prompt}],)content = response.choices[0].message.contentifnotcontent:
raiseValueError("Empty model response")# --- robust JSON parsing ---try:
data = json.loads(content)exceptjson.JSONDecodeError:
ifDEBUG:
print("⚠️ Raw model output (first 1000 chars):")print(content[:1000])# Try to extract JSON object safelymatch = re.search(r"\{.*\}",content,re.DOTALL)ifnotmatch:
raiseValueError("Failed to locate JSON object")data = json.loads(match.group())records = data.get("records")ifnotisinstance(records,list):
raiseValueError("JSON missing 'records' array")returnrecordsdefbuild_estuary_payload(records):
ifnotrecords:
raiseValueError("No records to build payload")forrinrecords:
priority = (r.get("priority")or"").lower()status = (r.get("status")or"").lower()return[{**r,"is_high_priority": priorityin("high","urgent"),"needs_escalation": (priority == "urgent"orstatus == "escalated"orr.get("required_escalation")isTrue),}forrinrecords]defsend_to_estuary(records: list) -> None:
headers = {"Content-Type": "application/json","Authorization": "Bearer " + ESTUARY_API_KEY,}forrinrecords:
try:
response = requests.post(ESTUARY_WEBHOOK,headers=headers,json=r,timeout=10,)ifresponse.status_codein(200,201,202):
print(f"✅ Estuary ingest success ({response.status_code})")else:
print(f"❌ Failed ({response.status_code}): {response.text}")exceptrequests.exceptions.RequestExceptionase:
print("🚨 Network error:",str(e))defrun_once():
records = generate_interactions(BATCH_SIZE)ifnotisinstance(records,list)ornotrecords:
raiseValueError("Generator returned invalid data")print(f"📊 Generated {len(records)} records")documents = build_estuary_payload(records)ifDEBUG:
print("\n=== SAMPLE DOCUMENT ===")print(json.dumps(documents[0],indent=2))print("\nSending to Estuary...")send_to_estuary(documents)print("Batch complete\n")if__name__ == "__main__":
whileTrue:
run_once()# time.sleep(30)
A few notes on this script:
generate_interactions(): Creates realistic synthetic customer support cases using an OpenAI language model. It constructs a highly structured prompt that enforces schema rules, realistic customer distributions. The function then calls the model (gpt-4o-mini) with JSON-only output enforced. The function ultimately returns a clean Python list of support case records ready for downstream processing.
build_estuary_payload(records): Enriches the raw generated cases with derived operational signals that are useful for analytics and automation. Specifically, it computes two boolean flags: is_high_priority, which identifies high-urgency tickets based on priority, and needs_escalation, which combines urgency, workflow status, and explicit escalation indicators into a unified escalation signal.
send_to_estuary(records): Handles real-time delivery of each enriched support case to Estuary via an authenticated webhook. It builds the required headers, iterates through the records, and sends each event individually to simulate a streaming workload.
Step 2: Create Estuary Webhook to Ingest the Data
Click on New Capture and search for HTTP Webhook.
Create a new capture to connect your source and start ingesting data into the pipeline.
Name your Capture: For example, customer_support_tickets. Then, create your own Authentication Bearer token.
Name the endpoint config as: customer-support-tickets
Once your changes are saved, click on your capture and you can now see the following Public Endpoint:
Query results for customer support tickets loaded into Snowflake for analytics, showing case description, intent, and issue category.
In the output, we have the following columns that we will focus on:
Case Description: Containing the customer’s detailed message about the issue
Case Title: Provides a quick overview of the case
Intent: A normalized label representing what the customer is trying to accomplish (for example, track an order or request a refund)
Issue Category: Higher-level classification of the underlying problem area (such as billing, delivery, or product defect)
Needs Escalation: A boolean flag indicating whether the case likely requires priority handling or human intervention.
Status: The current lifecycle state of the support case (for example, open, in_progress, resolved, escalated). It’s used to track resolution progress, monitor backlog health, and measure support performance.
Next, we’ll use these columns by applying various Cortex AI functions for the following use cases in Step 5.
Step 5: Explore Cortex AI Use Cases
Sentiment Scoring
Sentiment score quantifies the emotional tone of a customer’s message (from very negative to very positive). In a support intelligence pipeline, it turns unstructured text into a measurable signal that teams can act on in real time.
Run the following query to compute the sentiment score using the CORTEX.SENTIMENT function. Scores greater than 0.6 indicate relatively positive customer feedback, while scores below -0.4 signal customers who may be at risk of churn due to a negative product experience. By automatically scoring each case, support teams can proactively surface the most at-risk customers instead of relying solely on manual priority tags.
The following query uses Snowflake Cortex AI to generate an executive summary across all customer support cases. Instead of analyzing tickets one by one, it aggregates the full dataset and produces a structured, AI-written narrative highlighting major themes, recurring pain points, and operational risks.
AI_AGG is the key Cortex function here, and does the following:
Reads multiple rows
Converts them into a single aggregated context
Sends that context to the LLM
Returns one synthesized summary
AI_AGG enables Snowflake to synthesize thousands of support interactions into a single executive narrative, dramatically reducing manual analysis effort while surfacing hidden customer pain points.
CREATEORREPLACETABLEAGGREGATED_SUPPORT_CASES_SUMMARYASSELECTAI_AGG(
/* One"document"percase */
CONCAT('--- SUPPORT CASE ---\n','Case ID: ',CASE_ID,'\n','Customer ID: ',CUSTOMER_ID,'\n','Title: ',CASE_TITLE,'\n','Description: ',CASE_DESCRIPTION,'\n','Issue Category: ',ISSUE_CATEGORY,'\n','Intent: ',INTENT,'\n','Priority: ',PRIORITY,'\n','Needs Escalation: ',NEEDS_ESCALATION,'\n','Status: ',STATUS,'\n','Channel: ',CHANNEL,'\n','Response Time (min): ',RESPONSE_TIME_MIN,'\n','Number of Calls: ',NUMBER_OF_CALLS,'\n','Concerns Addressed: ',CONCERNS_ADDRESSED,'\n','Sentiment Label: ',SENTIMENT_LABEL,'\n','Sentiment Score: ',SENTIMENT_SCORE,'\n','Last Update Note: ',COALESCE(LAST_UPDATE_NOTE,'N/A'),'\n'),
/* Instructionpromptfortheaggregate */
'You are analyzing a batch of customer support cases.Identify major themes and recurring customer pain points.
In your executive summary, include:
1) Top issue categories and the most frequent intents.
2) Common root causes and where customers get stuck.
3) Escalation drivers: what patterns correlate with NEEDS_ESCALATION = true.
4) Channel patterns (chat/email/phone/web) and whether certain channels show higher negativity or slower response times.
5) Operational friction signals (high RESPONSE_TIME_MIN, high NUMBER_OF_CALLS, CONCERNS_ADDRESSED = false).
6) Suggested actions: product fixes, process improvements, and support playbooks.
Write a comprehensive executive summary (500-800 words) with headings and bullet points for key findings.'
) AS summary
FROM SUPPORT_WITH_SENTIMENT;
CREATEORREPLACETABLEAGGREGATED_SUPPORT_CASES_SUMMARYASSELECTAI_AGG(
/* One"document"percase */
CONCAT('--- SUPPORT CASE ---\n','Case ID: ',CASE_ID,'\n','Customer ID: ',CUSTOMER_ID,'\n','Title: ',CASE_TITLE,'\n','Description: ',CASE_DESCRIPTION,'\n','Issue Category: ',ISSUE_CATEGORY,'\n','Intent: ',INTENT,'\n','Priority: ',PRIORITY,'\n','Needs Escalation: ',NEEDS_ESCALATION,'\n','Status: ',STATUS,'\n','Channel: ',CHANNEL,'\n','Response Time (min): ',RESPONSE_TIME_MIN,'\n','Number of Calls: ',NUMBER_OF_CALLS,'\n','Concerns Addressed: ',CONCERNS_ADDRESSED,'\n','Sentiment Label: ',SENTIMENT_LABEL,'\n','Sentiment Score: ',SENTIMENT_SCORE,'\n','Last Update Note: ',COALESCE(LAST_UPDATE_NOTE,'N/A'),'\n'),
/* Instructionpromptfortheaggregate */
'You are analyzing a batch of customer support cases.Identify major themes and recurring customer pain points.
In your executive summary, include:
1) Top issue categories and the most frequent intents.
2) Common root causes and where customers get stuck.
3) Escalation drivers: what patterns correlate with NEEDS_ESCALATION = true.
4) Channel patterns (chat/email/phone/web) and whether certain channels show higher negativity or slower response times.
5) Operational friction signals (high RESPONSE_TIME_MIN, high NUMBER_OF_CALLS, CONCERNS_ADDRESSED = false).
6) Suggested actions: product fixes, process improvements, and support playbooks.
Write a comprehensive executive summary (500-800 words) with headings and bullet points for key findings.'
) AS summary
FROM SUPPORT_WITH_SENTIMENT;
CREATEORREPLACETABLEAGGREGATED_SUPPORT_CASES_SUMMARYASSELECTAI_AGG(
/* One"document"percase */
CONCAT('--- SUPPORT CASE ---\n','Case ID: ',CASE_ID,'\n','Customer ID: ',CUSTOMER_ID,'\n','Title: ',CASE_TITLE,'\n','Description: ',CASE_DESCRIPTION,'\n','Issue Category: ',ISSUE_CATEGORY,'\n','Intent: ',INTENT,'\n','Priority: ',PRIORITY,'\n','Needs Escalation: ',NEEDS_ESCALATION,'\n','Status: ',STATUS,'\n','Channel: ',CHANNEL,'\n','Response Time (min): ',RESPONSE_TIME_MIN,'\n','Number of Calls: ',NUMBER_OF_CALLS,'\n','Concerns Addressed: ',CONCERNS_ADDRESSED,'\n','Sentiment Label: ',SENTIMENT_LABEL,'\n','Sentiment Score: ',SENTIMENT_SCORE,'\n','Last Update Note: ',COALESCE(LAST_UPDATE_NOTE,'N/A'),'\n'),
/* Instructionpromptfortheaggregate */
'You are analyzing a batch of customer support cases.Identify major themes and recurring customer pain points.
In your executive summary, include:
1) Top issue categories and the most frequent intents.
2) Common root causes and where customers get stuck.
3) Escalation drivers: what patterns correlate with NEEDS_ESCALATION = true.
4) Channel patterns (chat/email/phone/web) and whether certain channels show higher negativity or slower response times.
5) Operational friction signals (high RESPONSE_TIME_MIN, high NUMBER_OF_CALLS, CONCERNS_ADDRESSED = false).
6) Suggested actions: product fixes, process improvements, and support playbooks.
Write a comprehensive executive summary (500-800 words) with headings and bullet points for key findings.'
) AS summary
FROM SUPPORT_WITH_SENTIMENT;
CREATEORREPLACETABLEAGGREGATED_SUPPORT_CASES_SUMMARYASSELECTAI_AGG(
/* One"document"percase */
CONCAT('--- SUPPORT CASE ---\n','Case ID: ',CASE_ID,'\n','Customer ID: ',CUSTOMER_ID,'\n','Title: ',CASE_TITLE,'\n','Description: ',CASE_DESCRIPTION,'\n','Issue Category: ',ISSUE_CATEGORY,'\n','Intent: ',INTENT,'\n','Priority: ',PRIORITY,'\n','Needs Escalation: ',NEEDS_ESCALATION,'\n','Status: ',STATUS,'\n','Channel: ',CHANNEL,'\n','Response Time (min): ',RESPONSE_TIME_MIN,'\n','Number of Calls: ',NUMBER_OF_CALLS,'\n','Concerns Addressed: ',CONCERNS_ADDRESSED,'\n','Sentiment Label: ',SENTIMENT_LABEL,'\n','Sentiment Score: ',SENTIMENT_SCORE,'\n','Last Update Note: ',COALESCE(LAST_UPDATE_NOTE,'N/A'),'\n'),
/* Instructionpromptfortheaggregate */
'You are analyzing a batch of customer support cases.Identify major themes and recurring customer pain points.
In your executive summary, include:
1) Top issue categories and the most frequent intents.
2) Common root causes and where customers get stuck.
3) Escalation drivers: what patterns correlate with NEEDS_ESCALATION = true.
4) Channel patterns (chat/email/phone/web) and whether certain channels show higher negativity or slower response times.
5) Operational friction signals (high RESPONSE_TIME_MIN, high NUMBER_OF_CALLS, CONCERNS_ADDRESSED = false).
6) Suggested actions: product fixes, process improvements, and support playbooks.
Write a comprehensive executive summary (500-800 words) with headings and bullet points for key findings.'
) AS summary
FROM SUPPORT_WITH_SENTIMENT;
CREATEORREPLACETABLEAGGREGATED_SUPPORT_CASES_SUMMARYASSELECTAI_AGG(
/* One"document"percase */
CONCAT('--- SUPPORT CASE ---\n','Case ID: ',CASE_ID,'\n','Customer ID: ',CUSTOMER_ID,'\n','Title: ',CASE_TITLE,'\n','Description: ',CASE_DESCRIPTION,'\n','Issue Category: ',ISSUE_CATEGORY,'\n','Intent: ',INTENT,'\n','Priority: ',PRIORITY,'\n','Needs Escalation: ',NEEDS_ESCALATION,'\n','Status: ',STATUS,'\n','Channel: ',CHANNEL,'\n','Response Time (min): ',RESPONSE_TIME_MIN,'\n','Number of Calls: ',NUMBER_OF_CALLS,'\n','Concerns Addressed: ',CONCERNS_ADDRESSED,'\n','Sentiment Label: ',SENTIMENT_LABEL,'\n','Sentiment Score: ',SENTIMENT_SCORE,'\n','Last Update Note: ',COALESCE(LAST_UPDATE_NOTE,'N/A'),'\n'),
/* Instructionpromptfortheaggregate */
'You are analyzing a batch of customer support cases.Identify major themes and recurring customer pain points.
In your executive summary, include:
1) Top issue categories and the most frequent intents.
2) Common root causes and where customers get stuck.
3) Escalation drivers: what patterns correlate with NEEDS_ESCALATION = true.
4) Channel patterns (chat/email/phone/web) and whether certain channels show higher negativity or slower response times.
5) Operational friction signals (high RESPONSE_TIME_MIN, high NUMBER_OF_CALLS, CONCERNS_ADDRESSED = false).
6) Suggested actions: product fixes, process improvements, and support playbooks.
Write a comprehensive executive summary (500-800 words) with headings and bullet points for key findings.'
) AS summary
FROM SUPPORT_WITH_SENTIMENT;
This query will give you an aggregated support case summary, like the one below:
Aggregated support case summary report generated from customer support data using prompt engineering and Snowflake Cortex AI_AGG.
The Output:
**ExecutiveSummary: CustomerSupportCaseAnalysis**
**Top Issue Categories andMost Frequent Intents**
Our analysis reveals that the top issue categories are:
* **Delivery** (34% of cases),withtop intents being **track_order** (43%),**change_shipping_address** (21%),and**cancel_order** (15%)
* **Billing** (26% of cases),withtop intents being **get_refund** (35%),**refund_policy** (23%),and**payment_issue** (17%)
* **Product Defect** (15% of cases),withtop intents being **complaint** (53%),**get_refund** (26%),and**replacement** (15%)
* **General Inquiry** (12% of cases),withtop intents being **customer_service** (35%),**place_order** (23%),and**review** (15%)
* **Account Access** (5% of cases),withtop intents being **account_access** (60%)and**password_reset** (20%)
**Common Root Causes andWhere Customers Get Stuck**
* **DeliveryIssues**: Delays,incorrect shipping addresses,andlack of tracking information are common pain points.
* **PaymentProcessing**: Failed payments,declined cards,andunclear payment methods cause frustration.
* **ProductDefects**: Damagedordefective products lead to complaints andrequestsforrefundsorreplacements.
***LackofTransparency**: Unclearrefundpolicies,unresponsivecustomerservice,andlackofupdatesonorderstatuscausecustomerdissatisfaction.
**Channel Patterns**
* **Phone**: 40% of cases,withanaverageresponsetimeof25minutesandasentimentscoreof -0.35.
***Email**: 30% ofcases,withanaverageresponsetimeof20minutesandasentimentscoreof -0.25.
***Web**: 20% ofcases,withanaverageresponsetimeof10minutesandasentimentscoreof -0.15.
***Chat**: 10% ofcases,withanaverageresponsetimeof15minutesandasentimentscoreof -0.20.
**SuggestedActions**
***ProductFixes**:
*Improvequalitycontroltoreduceproductdefects.
*Enhanceproductdescriptionstoreducemisunderstandings.
* **ProcessImprovements**:
* Streamline payment processing to reduce failed payments.
* Implement a more efficient refund process.
* Improve communication around order status andtracking information.
* **Support Playbooks**:
* Develop a comprehensive refund policy andcommunicate it clearly to customers.
* Create a knowledge base forcommonissuesandsolutions.
* Establish a clear escalation process forurgent cases.
**ExecutiveSummary: CustomerSupportCaseAnalysis**
**Top Issue Categories andMost Frequent Intents**
Our analysis reveals that the top issue categories are:
* **Delivery** (34% of cases),withtop intents being **track_order** (43%),**change_shipping_address** (21%),and**cancel_order** (15%)
* **Billing** (26% of cases),withtop intents being **get_refund** (35%),**refund_policy** (23%),and**payment_issue** (17%)
* **Product Defect** (15% of cases),withtop intents being **complaint** (53%),**get_refund** (26%),and**replacement** (15%)
* **General Inquiry** (12% of cases),withtop intents being **customer_service** (35%),**place_order** (23%),and**review** (15%)
* **Account Access** (5% of cases),withtop intents being **account_access** (60%)and**password_reset** (20%)
**Common Root Causes andWhere Customers Get Stuck**
* **DeliveryIssues**: Delays,incorrect shipping addresses,andlack of tracking information are common pain points.
* **PaymentProcessing**: Failed payments,declined cards,andunclear payment methods cause frustration.
* **ProductDefects**: Damagedordefective products lead to complaints andrequestsforrefundsorreplacements.
***LackofTransparency**: Unclearrefundpolicies,unresponsivecustomerservice,andlackofupdatesonorderstatuscausecustomerdissatisfaction.
**Channel Patterns**
* **Phone**: 40% of cases,withanaverageresponsetimeof25minutesandasentimentscoreof -0.35.
***Email**: 30% ofcases,withanaverageresponsetimeof20minutesandasentimentscoreof -0.25.
***Web**: 20% ofcases,withanaverageresponsetimeof10minutesandasentimentscoreof -0.15.
***Chat**: 10% ofcases,withanaverageresponsetimeof15minutesandasentimentscoreof -0.20.
**SuggestedActions**
***ProductFixes**:
*Improvequalitycontroltoreduceproductdefects.
*Enhanceproductdescriptionstoreducemisunderstandings.
* **ProcessImprovements**:
* Streamline payment processing to reduce failed payments.
* Implement a more efficient refund process.
* Improve communication around order status andtracking information.
* **Support Playbooks**:
* Develop a comprehensive refund policy andcommunicate it clearly to customers.
* Create a knowledge base forcommonissuesandsolutions.
* Establish a clear escalation process forurgent cases.
**ExecutiveSummary: CustomerSupportCaseAnalysis**
**Top Issue Categories andMost Frequent Intents**
Our analysis reveals that the top issue categories are:
* **Delivery** (34% of cases),withtop intents being **track_order** (43%),**change_shipping_address** (21%),and**cancel_order** (15%)
* **Billing** (26% of cases),withtop intents being **get_refund** (35%),**refund_policy** (23%),and**payment_issue** (17%)
* **Product Defect** (15% of cases),withtop intents being **complaint** (53%),**get_refund** (26%),and**replacement** (15%)
* **General Inquiry** (12% of cases),withtop intents being **customer_service** (35%),**place_order** (23%),and**review** (15%)
* **Account Access** (5% of cases),withtop intents being **account_access** (60%)and**password_reset** (20%)
**Common Root Causes andWhere Customers Get Stuck**
* **DeliveryIssues**: Delays,incorrect shipping addresses,andlack of tracking information are common pain points.
* **PaymentProcessing**: Failed payments,declined cards,andunclear payment methods cause frustration.
* **ProductDefects**: Damagedordefective products lead to complaints andrequestsforrefundsorreplacements.
***LackofTransparency**: Unclearrefundpolicies,unresponsivecustomerservice,andlackofupdatesonorderstatuscausecustomerdissatisfaction.
**Channel Patterns**
* **Phone**: 40% of cases,withanaverageresponsetimeof25minutesandasentimentscoreof -0.35.
***Email**: 30% ofcases,withanaverageresponsetimeof20minutesandasentimentscoreof -0.25.
***Web**: 20% ofcases,withanaverageresponsetimeof10minutesandasentimentscoreof -0.15.
***Chat**: 10% ofcases,withanaverageresponsetimeof15minutesandasentimentscoreof -0.20.
**SuggestedActions**
***ProductFixes**:
*Improvequalitycontroltoreduceproductdefects.
*Enhanceproductdescriptionstoreducemisunderstandings.
* **ProcessImprovements**:
* Streamline payment processing to reduce failed payments.
* Implement a more efficient refund process.
* Improve communication around order status andtracking information.
* **Support Playbooks**:
* Develop a comprehensive refund policy andcommunicate it clearly to customers.
* Create a knowledge base forcommonissuesandsolutions.
* Establish a clear escalation process forurgent cases.
**ExecutiveSummary: CustomerSupportCaseAnalysis**
**Top Issue Categories andMost Frequent Intents**
Our analysis reveals that the top issue categories are:
* **Delivery** (34% of cases),withtop intents being **track_order** (43%),**change_shipping_address** (21%),and**cancel_order** (15%)
* **Billing** (26% of cases),withtop intents being **get_refund** (35%),**refund_policy** (23%),and**payment_issue** (17%)
* **Product Defect** (15% of cases),withtop intents being **complaint** (53%),**get_refund** (26%),and**replacement** (15%)
* **General Inquiry** (12% of cases),withtop intents being **customer_service** (35%),**place_order** (23%),and**review** (15%)
* **Account Access** (5% of cases),withtop intents being **account_access** (60%)and**password_reset** (20%)
**Common Root Causes andWhere Customers Get Stuck**
* **DeliveryIssues**: Delays,incorrect shipping addresses,andlack of tracking information are common pain points.
* **PaymentProcessing**: Failed payments,declined cards,andunclear payment methods cause frustration.
* **ProductDefects**: Damagedordefective products lead to complaints andrequestsforrefundsorreplacements.
***LackofTransparency**: Unclearrefundpolicies,unresponsivecustomerservice,andlackofupdatesonorderstatuscausecustomerdissatisfaction.
**Channel Patterns**
* **Phone**: 40% of cases,withanaverageresponsetimeof25minutesandasentimentscoreof -0.35.
***Email**: 30% ofcases,withanaverageresponsetimeof20minutesandasentimentscoreof -0.25.
***Web**: 20% ofcases,withanaverageresponsetimeof10minutesandasentimentscoreof -0.15.
***Chat**: 10% ofcases,withanaverageresponsetimeof15minutesandasentimentscoreof -0.20.
**SuggestedActions**
***ProductFixes**:
*Improvequalitycontroltoreduceproductdefects.
*Enhanceproductdescriptionstoreducemisunderstandings.
* **ProcessImprovements**:
* Streamline payment processing to reduce failed payments.
* Implement a more efficient refund process.
* Improve communication around order status andtracking information.
* **Support Playbooks**:
* Develop a comprehensive refund policy andcommunicate it clearly to customers.
* Create a knowledge base forcommonissuesandsolutions.
* Establish a clear escalation process forurgent cases.
**ExecutiveSummary: CustomerSupportCaseAnalysis**
**Top Issue Categories andMost Frequent Intents**
Our analysis reveals that the top issue categories are:
* **Delivery** (34% of cases),withtop intents being **track_order** (43%),**change_shipping_address** (21%),and**cancel_order** (15%)
* **Billing** (26% of cases),withtop intents being **get_refund** (35%),**refund_policy** (23%),and**payment_issue** (17%)
* **Product Defect** (15% of cases),withtop intents being **complaint** (53%),**get_refund** (26%),and**replacement** (15%)
* **General Inquiry** (12% of cases),withtop intents being **customer_service** (35%),**place_order** (23%),and**review** (15%)
* **Account Access** (5% of cases),withtop intents being **account_access** (60%)and**password_reset** (20%)
**Common Root Causes andWhere Customers Get Stuck**
* **DeliveryIssues**: Delays,incorrect shipping addresses,andlack of tracking information are common pain points.
* **PaymentProcessing**: Failed payments,declined cards,andunclear payment methods cause frustration.
* **ProductDefects**: Damagedordefective products lead to complaints andrequestsforrefundsorreplacements.
***LackofTransparency**: Unclearrefundpolicies,unresponsivecustomerservice,andlackofupdatesonorderstatuscausecustomerdissatisfaction.
**Channel Patterns**
* **Phone**: 40% of cases,withanaverageresponsetimeof25minutesandasentimentscoreof -0.35.
***Email**: 30% ofcases,withanaverageresponsetimeof20minutesandasentimentscoreof -0.25.
***Web**: 20% ofcases,withanaverageresponsetimeof10minutesandasentimentscoreof -0.15.
***Chat**: 10% ofcases,withanaverageresponsetimeof15minutesandasentimentscoreof -0.20.
**SuggestedActions**
***ProductFixes**:
*Improvequalitycontroltoreduceproductdefects.
*Enhanceproductdescriptionstoreducemisunderstandings.
* **ProcessImprovements**:
* Streamline payment processing to reduce failed payments.
* Implement a more efficient refund process.
* Improve communication around order status andtracking information.
* **Support Playbooks**:
* Develop a comprehensive refund policy andcommunicate it clearly to customers.
* Create a knowledge base forcommonissuesandsolutions.
* Establish a clear escalation process forurgent cases.
Cortex Search: Semantic search for next best action
Cortex Search transforms support data from a passive log into an active intelligence layer, allowing teams to detect emerging product issues, prioritize high-risk cases, and accelerate customer resolution — all directly inside Snowflake.
In high-volume support environments, product teams and support leads often need to quickly investigate emerging issues — for example, when customers begin reporting defective products. Traditional keyword searches are brittle and miss semantically similar complaints written in different ways.
Using Snowflake Cortex Search, support teams can perform semantic retrieval across unstructured support tickets to rapidly surface relevant cases, even when customers describe problems differently.
In this example, the query searches for cases related to a “defective toy”. Cortex Search scans the indexed support text and returns the most semantically relevant tickets, along with key operational metadata such as issue category and escalation signals.
The above image shows how Snowflake Cortex Search is used to query indexed support text and return the most semantically relevant tickets for a “defective toy”, using cosine similarity and reranker scores.
Two terms to highlight here:
Cosine Similarity: Semantically cluster similar complaints even when customers use different wording. For example, queries about “defective toys” can surface cases. This enables faster detection of emerging product defects or service failures.
Reranker Score: Support copilots use the reranker score to ensure the most contextually relevant past tickets appear first for agents. This improves answer quality when generating responses using Retrieval Augmented Generation (RAG). It reduces noise from loosely related matches that embedding search alone might retrieve.
Based on what we have learned so far, we can use SNOWFLAKE.CORTEX.COMPLETE to classify support cases as resolved, unresolved, or needs_followup, and then generate the next best action.
The following query uses Cortex LLM functions to recommend the next best action for support agents by combining customer sentiment, escalation risk, and case status into a single AI-driven triage decision.
CREATEORREPLACEVIEWSUPPORT_AI_TRIAGEASSELECTCASE_ID,CUSTOMER_ID,CASE_DESCRIPTION,STATUS,SENTIMENT_SCORE,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,SNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('Classify this support case into one of three labels: ','resolved, unresolved, needs_followup.\n\n','Case description:\n',CASE_DESCRIPTION,'\n\n','Status: ',STATUS,'\n','Concerns addressed: ',CONCERNS_ADDRESSED,'\n','Return ONLY the label.'))ASai_resolution_labelFROMSUPPORT_WITH_SENTIMENT;CREATEORREPLACEVIEWSUPPORT_AI_ACTIONSASSELECTCASE_ID,CUSTOMER_ID,ai_resolution_label,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,CASEWHENai_resolution_label != 'resolved'THENSNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('You are a senior customer support agent.\n\n','Customer issue:\n',CASE_DESCRIPTION,'\n\n','Risk signals:\n','- Sentiment: ',SENTIMENT_LABEL,'\n','- High priority: ',IS_HIGH_PRIORITY,'\n','- Needs escalation: ',NEEDS_ESCALATION,'\n','- Concerns addressed: ',CONCERNS_ADDRESSED,'\n\n','Write the next best action for the agent.\n','Rules:\n','- Be professional and empathetic\n','- Maximum 2 sentences\n','- Recommend one of: refund, replace, escalate, or request info\n','- Be specific and actionable\n','- Do NOT repeat the customer text\n'))ENDASai_next_stepFROMSUPPORT_AI_TRIAGE;
CREATEORREPLACEVIEWSUPPORT_AI_TRIAGEASSELECTCASE_ID,CUSTOMER_ID,CASE_DESCRIPTION,STATUS,SENTIMENT_SCORE,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,SNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('Classify this support case into one of three labels: ','resolved, unresolved, needs_followup.\n\n','Case description:\n',CASE_DESCRIPTION,'\n\n','Status: ',STATUS,'\n','Concerns addressed: ',CONCERNS_ADDRESSED,'\n','Return ONLY the label.'))ASai_resolution_labelFROMSUPPORT_WITH_SENTIMENT;CREATEORREPLACEVIEWSUPPORT_AI_ACTIONSASSELECTCASE_ID,CUSTOMER_ID,ai_resolution_label,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,CASEWHENai_resolution_label != 'resolved'THENSNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('You are a senior customer support agent.\n\n','Customer issue:\n',CASE_DESCRIPTION,'\n\n','Risk signals:\n','- Sentiment: ',SENTIMENT_LABEL,'\n','- High priority: ',IS_HIGH_PRIORITY,'\n','- Needs escalation: ',NEEDS_ESCALATION,'\n','- Concerns addressed: ',CONCERNS_ADDRESSED,'\n\n','Write the next best action for the agent.\n','Rules:\n','- Be professional and empathetic\n','- Maximum 2 sentences\n','- Recommend one of: refund, replace, escalate, or request info\n','- Be specific and actionable\n','- Do NOT repeat the customer text\n'))ENDASai_next_stepFROMSUPPORT_AI_TRIAGE;
CREATEORREPLACEVIEWSUPPORT_AI_TRIAGEASSELECTCASE_ID,CUSTOMER_ID,CASE_DESCRIPTION,STATUS,SENTIMENT_SCORE,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,SNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('Classify this support case into one of three labels: ','resolved, unresolved, needs_followup.\n\n','Case description:\n',CASE_DESCRIPTION,'\n\n','Status: ',STATUS,'\n','Concerns addressed: ',CONCERNS_ADDRESSED,'\n','Return ONLY the label.'))ASai_resolution_labelFROMSUPPORT_WITH_SENTIMENT;CREATEORREPLACEVIEWSUPPORT_AI_ACTIONSASSELECTCASE_ID,CUSTOMER_ID,ai_resolution_label,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,CASEWHENai_resolution_label != 'resolved'THENSNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('You are a senior customer support agent.\n\n','Customer issue:\n',CASE_DESCRIPTION,'\n\n','Risk signals:\n','- Sentiment: ',SENTIMENT_LABEL,'\n','- High priority: ',IS_HIGH_PRIORITY,'\n','- Needs escalation: ',NEEDS_ESCALATION,'\n','- Concerns addressed: ',CONCERNS_ADDRESSED,'\n\n','Write the next best action for the agent.\n','Rules:\n','- Be professional and empathetic\n','- Maximum 2 sentences\n','- Recommend one of: refund, replace, escalate, or request info\n','- Be specific and actionable\n','- Do NOT repeat the customer text\n'))ENDASai_next_stepFROMSUPPORT_AI_TRIAGE;
CREATEORREPLACEVIEWSUPPORT_AI_TRIAGEASSELECTCASE_ID,CUSTOMER_ID,CASE_DESCRIPTION,STATUS,SENTIMENT_SCORE,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,SNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('Classify this support case into one of three labels: ','resolved, unresolved, needs_followup.\n\n','Case description:\n',CASE_DESCRIPTION,'\n\n','Status: ',STATUS,'\n','Concerns addressed: ',CONCERNS_ADDRESSED,'\n','Return ONLY the label.'))ASai_resolution_labelFROMSUPPORT_WITH_SENTIMENT;CREATEORREPLACEVIEWSUPPORT_AI_ACTIONSASSELECTCASE_ID,CUSTOMER_ID,ai_resolution_label,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,CASEWHENai_resolution_label != 'resolved'THENSNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('You are a senior customer support agent.\n\n','Customer issue:\n',CASE_DESCRIPTION,'\n\n','Risk signals:\n','- Sentiment: ',SENTIMENT_LABEL,'\n','- High priority: ',IS_HIGH_PRIORITY,'\n','- Needs escalation: ',NEEDS_ESCALATION,'\n','- Concerns addressed: ',CONCERNS_ADDRESSED,'\n\n','Write the next best action for the agent.\n','Rules:\n','- Be professional and empathetic\n','- Maximum 2 sentences\n','- Recommend one of: refund, replace, escalate, or request info\n','- Be specific and actionable\n','- Do NOT repeat the customer text\n'))ENDASai_next_stepFROMSUPPORT_AI_TRIAGE;
CREATEORREPLACEVIEWSUPPORT_AI_TRIAGEASSELECTCASE_ID,CUSTOMER_ID,CASE_DESCRIPTION,STATUS,SENTIMENT_SCORE,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,SNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('Classify this support case into one of three labels: ','resolved, unresolved, needs_followup.\n\n','Case description:\n',CASE_DESCRIPTION,'\n\n','Status: ',STATUS,'\n','Concerns addressed: ',CONCERNS_ADDRESSED,'\n','Return ONLY the label.'))ASai_resolution_labelFROMSUPPORT_WITH_SENTIMENT;CREATEORREPLACEVIEWSUPPORT_AI_ACTIONSASSELECTCASE_ID,CUSTOMER_ID,ai_resolution_label,SENTIMENT_LABEL,IS_HIGH_PRIORITY,NEEDS_ESCALATION,CONCERNS_ADDRESSED,CASEWHENai_resolution_label != 'resolved'THENSNOWFLAKE.CORTEX.COMPLETE('snowflake-arctic',CONCAT('You are a senior customer support agent.\n\n','Customer issue:\n',CASE_DESCRIPTION,'\n\n','Risk signals:\n','- Sentiment: ',SENTIMENT_LABEL,'\n','- High priority: ',IS_HIGH_PRIORITY,'\n','- Needs escalation: ',NEEDS_ESCALATION,'\n','- Concerns addressed: ',CONCERNS_ADDRESSED,'\n\n','Write the next best action for the agent.\n','Rules:\n','- Be professional and empathetic\n','- Maximum 2 sentences\n','- Recommend one of: refund, replace, escalate, or request info\n','- Be specific and actionable\n','- Do NOT repeat the customer text\n'))ENDASai_next_stepFROMSUPPORT_AI_TRIAGE;
That query will give you an output that looks something like this:
Output from the support_ai_actions table showing Cortex AI recommendations for resolving customer cases based on sentiment, priority, and ticket status.
Conclusion
Customer support systems generate massive volumes of unstructured data every day, yet much of it remains underutilized due to challenges in real-time ingestion and analysis. With Estuary as a right-time data movement layer, teams can continuously stream support interactions into Snowflake with minimal latency. While webhooks provide a simple ingestion path, the same pattern extends to CRM systems, contact center platforms, and review pipelines. Once the data is centralized, Snowflake Cortex AI enables multiple intelligent workflows, including sentiment scoring, automated ticket summarization, semantic search for retrieval-augmented generation (RAG), root cause analysis, and resolution classification.
The next step is to operationalize these capabilities into real applications and decision workflows. Teams can build AI-powered copilots and self-service assistants using Streamlit on top of Snowflake, enabling support agents and customers to query data, retrieve insights, and generate responses using natural language. Additionally, Snowflake’s managed Model Context Protocol (MCP) server and Cortex Agents can power more advanced AI agents that automatically connect to enterprise data, retrieve relevant context using tools like Cortex Search, and generate reliable, context-aware answers without manual querying.
Ultimately, this architecture shifts customer support from a reactive process to a proactive, AI-driven system, where insights are generated in real time and directly embedded into workflows that drive faster resolution, better decision-making, and improved customer experience.
FAQs
Right-time data means treating latency as a per-pipeline decision rather than a single organizational setting. Snowflake supports ingestion methods across the full latency spectrum, from sub-second Snowpipe Streaming to scheduled COPY INTO batch loads. Right-time is choosing the appropriate tier for each pipeline, not defaulting to the fastest or simplest option across the board.
Ruhee has a background in Computer Science and Economics and has worked as a Data Engineer for SaaS providing tech startups, where she has automated ETL processes using cutting-edge technologies and migrated data infrastructures to the cloud with AWS/Azure services. She is currently pursuing a Master’s in Business Analytics with a focus on Operations and AI at Worcester Polytechnic Institute.