Week 3 Day 1-2: CCAI Platform Setup¶
Enable CCAI APIs¶
Python Script: CCAI Configuration¶
File: scripts/ccai_setup.py
#!/usr/bin/env python3
"""Configure Contact Center AI (CCAI) Platform"""
from google.cloud import aiplatform
from google.cloud import speech_v1
import os
PROJECT_ID = os.environ.get('GCP_PROJECT_ID')
REGION = "us-east4"
def configure_speech_to_text():
"""Configure Speech-to-Text for CCAI"""
client = speech_v1.SpeechClient()
# Configure telephony model (optimized for phone calls)
config = speech_v1.RecognitionConfig(
encoding=speech_v1.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=8000, # Telephony standard
language_code="en-US",
model="phone_call",
use_enhanced=True,
enable_automatic_punctuation=True,
enable_speaker_diarization=True,
diarization_speaker_count=2, # Agent + Customer
audio_channel_count=2
)
print("โ
Speech-to-Text configured for telephony")
return config
def setup_vertex_ai():
"""Initialize Vertex AI"""
aiplatform.init(
project=PROJECT_ID,
location=REGION
)
print(f"โ
Vertex AI initialized: {PROJECT_ID} / {REGION}")
if __name__ == "__main__":
print("๐ง Configuring CCAI Platform...")
setup_vertex_ai()
configure_speech_to_text()
print("โ
CCAI Configuration Complete")
Deployment¶
Week 3 Day 3: Dialogflow CX Configuration¶
Create Dialogflow Agent¶
## Enable Dialogflow API
gcloud services enable dialogflow.googleapis.com --project=$PROJECT_ID
## Create agent using gcloud or Console
## This is typically done via Console UI for complex flows
Console Steps: 1. Navigate to Dialogflow CX Console 2. Create new agent: "WxCC IVR Agent" 3. Set location: us-east4 4. Configure intents, entities, and flows based on IVR requirements
Week 3 Day 4-5: Custom ML Models¶
Python Script: Churn Prediction Model¶
File: scripts/train_churn_model.py
#!/usr/bin/env python3
"""Train customer churn prediction model"""
from google.cloud import aiplatform, bigquery
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import joblib
import os
PROJECT_ID = os.environ.get('GCP_PROJECT_ID')
REGION = "us-east4"
BUCKET = f"gs://{PROJECT_ID}-vertex-models"
def extract_training_data():
"""Extract historical data from BigQuery"""
client = bigquery.Client(project=PROJECT_ID)
query = """
SELECT
agent_id,
avg_sentiment_score,
transfer_rate,
avg_handle_time_seconds,
first_call_resolution_rate,
-- Target: customer churned in next 30 days
CASE
WHEN next_call_date IS NULL
OR DATE_DIFF(next_call_date, metric_date, DAY) > 30
THEN 1
ELSE 0
END as churned
FROM `wxcc_analytics.agent_metrics`
WHERE metric_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 180 DAY)
"""
df = client.query(query).to_dataframe()
print(f"โ
Extracted {len(df)} training records")
return df
def train_model(df):
"""Train churn prediction model"""
X = df.drop(['churned', 'agent_id'], axis=1)
y = df['churned']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f"โ
Model trained - Accuracy: {accuracy:.2%}")
return model
def upload_to_vertex(model):
"""Upload model to Vertex AI"""
aiplatform.init(project=PROJECT_ID, location=REGION)
## Save model locally
model_path = "/tmp/churn_model.pkl"
joblib.dump(model, model_path)
## Upload to GCS
from google.cloud import storage
storage_client = storage.Client()
bucket = storage_client.bucket(f"{PROJECT_ID}-vertex-models")
blob = bucket.blob("churn_model/model.pkl")
blob.upload_from_filename(model_path)
model_uri = f"{BUCKET}/churn_model"
print(f"โ
Model uploaded: {model_uri}")
## Register in Vertex AI Model Registry
vertex_model = aiplatform.Model.upload(
display_name="wxcc-churn-prediction",
artifact_uri=model_uri,
serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.1-0:latest"
)
print(f"โ
Model registered: {vertex_model.resource_name}")
return vertex_model
if __name__ == "__main__":
print("๐ค Training Churn Prediction Model...")
df = extract_training_data()
model = train_model(df)
vertex_model = upload_to_vertex(model)
print("โ
Model training complete")
Deployment¶
Week 4: WxCC Integration & Testing¶
Week 4 Day 1-2: Cloud Functions Deployment¶
Cloud Function: Process Call Events¶
File: functions/process_call_event/main.py
import functions_framework
from google.cloud import bigquery, storage, dlp_v2, speech_v1
import json
import base64
from datetime import datetime
PROJECT_ID = "abhavtech-wxcc-prod"
DATASET_ID = "wxcc_analytics"
@functions_framework.cloud_event
def process_call_event(cloud_event):
"""Process WxCC call event from Pub/Sub"""
## Decode Pub/Sub message
pubsub_message = base64.b64decode(cloud_event.data["message"]["data"]).decode()
call_data = json.loads(pubsub_message)
print(f"Processing call: {call_data['call_id']}")
## Store CDR
store_cdr(call_data)
## Process recording if available
if call_data.get('recording_uri'):
process_recording(call_data)
print(f"โ
Call processed: {call_data['call_id']}")
def store_cdr(call_data):
"""Store Call Detail Record in BigQuery"""
client = bigquery.Client(project=PROJECT_ID)
table_id = f"{PROJECT_ID}.{DATASET_ID}.call_detail_records"
row = {
"call_id": call_data["call_id"],
"call_start_time": call_data["start_time"],
"call_end_time": call_data.get("end_time"),
"queue_id": call_data["queue_id"],
"agent_id": call_data.get("agent_id"),
"call_duration_seconds": call_data.get("duration"),
## ... other fields
"created_at": datetime.utcnow().isoformat()
}
errors = client.insert_rows_json(table_id, [row])
if errors:
raise Exception(f"BigQuery insert failed: {errors}")
def process_recording(call_data):
"""Transcribe and analyze call recording"""
recording_uri = call_data['recording_uri']
## Transcribe audio
transcript = transcribe_audio(recording_uri)
## Redact PII
redacted_transcript = redact_pii(transcript)
## Analyze sentiment
sentiment = analyze_sentiment(redacted_transcript)
## Store results
store_transcript(call_data['call_id'], redacted_transcript, transcript)
store_sentiment(call_data['call_id'], sentiment)
def transcribe_audio(audio_uri):
"""Transcribe audio using Speech-to-Text"""
client = speech_v1.SpeechClient()
audio = speech_v1.RecognitionAudio(uri=audio_uri)
config = speech_v1.RecognitionConfig(
encoding=speech_v1.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=8000,
language_code="en-US",
model="phone_call",
use_enhanced=True,
enable_automatic_punctuation=True
)
operation = client.long_running_recognize(config=config, audio=audio)
response = operation.result(timeout=600)
transcript = " ".join([
result.alternatives[0].transcript
for result in response.results
])
return transcript
def redact_pii(text):
"""Redact PII using Cloud DLP"""
dlp = dlp_v2.DlpServiceClient()
inspect_template = f"projects/{PROJECT_ID}/inspectTemplates/wxcc-pii-detection"
deidentify_template = f"projects/{PROJECT_ID}/deidentifyTemplates/wxcc-pii-redaction"
response = dlp.deidentify_content(
request={
"parent": f"projects/{PROJECT_ID}",
"inspect_template_name": inspect_template,
"deidentify_template_name": deidentify_template,
"item": {"value": text}
}
)
return response.item.value
def store_transcript(call_id, redacted, raw_uri):
"""Store transcript in BigQuery"""
client = bigquery.Client(project=PROJECT_ID)
table_id = f"{PROJECT_ID}.{DATASET_ID}.call_transcripts"
## Implementation here
pass
def analyze_sentiment(text):
"""Analyze sentiment using Natural Language API"""
from google.cloud import language_v1
client = language_v1.LanguageServiceClient()
document = language_v1.Document(
content=text,
type_=language_v1.Document.Type.PLAIN_TEXT
)
sentiment = client.analyze_sentiment(
request={"document": document}
).document_sentiment
return {
"score": sentiment.score,
"magnitude": sentiment.magnitude
}
def store_sentiment(call_id, sentiment):
"""Store sentiment analysis in BigQuery"""
## Implementation here
pass
File: functions/process_call_event/requirements.txt
functions-framework==3.*
google-cloud-bigquery==3.*
google-cloud-storage==2.*
google-cloud-dlp==3.*
google-cloud-speech==2.*
google-cloud-language==2.*
Deploy Cloud Function¶
cd ~/gcp-wxcc-deployment/functions/process_call_event
gcloud functions deploy process-call-event \
--gen2 \
--runtime=python311 \
--region=us-east4 \
--source=. \
--entry-point=process_call_event \
--trigger-topic=wxcc-call-events \
--service-account=$CF_SA \
--memory=512MB \
--timeout=540s \
--project=$PROJECT_ID
## Verify deployment
gcloud functions describe process-call-event \
--region=us-east4 \
--project=$PROJECT_ID
Week 4 Day 3: WxCC Webhook Configuration¶
Configure WxCC to Send Events¶
WxCC Console Configuration:
- Log in to WxCC Control Hub
- Navigate to: Settings โ Webhooks
- Create new webhook:
- Name: "GCP Pub/Sub Integration"
- URL:
https://pubsub.googleapis.com/v1/projects/{PROJECT_ID}/topics/wxcc-call-events:publish - Authentication: Service Account (upload wxcc-sa-key.json)
- Events: Call Started, Call Ended, Call Recorded
Test Webhook¶
## Simulate WxCC event
gcloud pubsub topics publish wxcc-call-events \
--message='{
"call_id": "test-123",
"start_time": "2025-01-20T10:00:00Z",
"queue_id": "support",
"agent_id": "agent@abhavtech.com"
}' \
--project=$PROJECT_ID
## Check Cloud Function logs
gcloud functions logs read process-call-event \
--region=us-east4 \
--project=$PROJECT_ID \
--limit=10
Week 4 Day 4-5: End-to-End Validation¶
Validation Checklist¶
#!/bin/bash
## validation_suite.sh - Comprehensive validation
echo "๐งช Running End-to-End Validation..."
## Test 1: Pub/Sub Message Flow
echo "Test 1: Pub/Sub..."
gcloud pubsub topics publish wxcc-call-events \
--message='{"test":"validation"}' \
--project=$PROJECT_ID
sleep 5
gcloud functions logs read process-call-event --limit=1 | grep "validation" && echo "โ
Pub/Sub OK"
## Test 2: BigQuery Write
echo "Test 2: BigQuery..."
bq query --use_legacy_sql=false "SELECT COUNT(*) FROM wxcc_analytics.call_detail_records" && echo "โ
BigQuery OK"
## Test 3: Cloud Storage Access
echo "Test 3: Cloud Storage..."
gsutil ls gs://$PROJECT_ID-call-recordings && echo "โ
Storage OK"
## Test 4: DLP Templates
echo "Test 4: DLP..."
gcloud dlp inspect-templates describe wxcc-pii-detection --project=$PROJECT_ID && echo "โ
DLP OK"
## Test 5: VPC Service Controls
echo "Test 5: VPC-SC..."
gcloud access-context-manager perimeters describe wxcc_production --policy=$ACCESS_POLICY && echo "โ
VPC-SC OK"
echo "โ
All Tests Passed"
Production Cutover¶
## Enable WxCC webhook
## Point webhook to production Pub/Sub topic
## Monitor for 24 hours
## Monitor metrics
gcloud monitoring dashboards list --project=$PROJECT_ID
Appendices¶
APPENDIX A: Complete Terraform Structure¶
terraform/
โโโ 01-project/ # Project and APIs
โโโ 02-iam/ # Service accounts
โโโ 03-bigquery/ # Dataset and tables
โโโ 04-storage/ # GCS buckets
โโโ 05-pubsub/ # Topics and subscriptions
โโโ 06-vpc-sc/ # VPC Service Controls
APPENDIX B: Troubleshooting Guide¶
Issue: VPC Service Controls Blocking Access¶
## Check perimeter status
gcloud access-context-manager perimeters describe wxcc_production \
--policy=$ACCESS_POLICY
## Verify source IP is allowed
curl ifconfig.me # Check your current IP
## Add IP temporarily for testing
gcloud access-context-manager levels update wxcc_trusted_sources \
--add-ip-subnetworks=YOUR_IP/32 \
--policy=$ACCESS_POLICY
Issue: Cloud Function Failing¶
## Check logs
gcloud functions logs read process-call-event \
--region=us-east4 \
--limit=50
## Test locally
cd functions/process_call_event
functions-framework --target=process_call_event --debug
APPENDIX C: Validation Checklist¶
Week 1 Validation: - [ ] Project created with all APIs enabled - [ ] Service accounts created with proper IAM roles - [ ] BigQuery dataset and tables created - [ ] Cloud Storage buckets created with lifecycle policies - [ ] Pub/Sub topics and subscriptions created
Week 2 Validation: - [ ] VPC Service Controls perimeter active - [ ] DLP templates created and tested - [ ] KMS keys created for encryption - [ ] Security validation passed
Week 3 Validation: - [ ] CCAI Platform configured - [ ] Dialogflow CX agent created - [ ] Custom models trained and deployed - [ ] Model serving endpoint active
Week 4 Validation: - [ ] Cloud Functions deployed and triggered - [ ] WxCC webhook configured - [ ] End-to-end data flow validated - [ ] Production cutover completed
Implementation Complete¶
Total Duration: 4 Weeks (80 Hours)
Deliverables: - โ Production-ready GCP infrastructure - โ CCAI Platform integrated with WxCC - โ Security controls (VPC-SC, DLP, KMS) - โ Automated data pipelines - โ ML models deployed - โ Comprehensive documentation
Next Steps: 1. Monitor for 30 days 2. Optimize based on usage patterns 3. Train additional ML models 4. Implement advanced features (Agent Assist, etc.)