Skip to content
GMISWEPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🤖 AI Chatbot - Google Cloud Run Deployment

One-click deployment solution for Google Cloud Run with automatic infrastructure provisioning.

🚀 Quick Start

Prerequisites

  • Google Cloud Platform account with billing enabled
  • gcloud CLI installed and configured
  • Required API keys (see Configuration section)

Step 1: Configure API Keys

⚠️ IMPORTANT: You MUST configure all required API keys in config.env before deployment.

# Navigate to cloudrun directory
cd cloudrun

# Copy the template
cp config.env.template config.env

# Edit the configuration file with your API keys
nano config.env

Step 2: Fill in Required Configuration

Open config.env and configure the following required fields:

# ✅ REQUIRED - GMI API Key for LLM services
GMI_API_KEY=your-actual-gmi-api-key-here

# ✅ REQUIRED - Your Google Cloud Project ID
GOOGLE_CLOUD_PROJECT=your-gcp-project-id

# ✅ REQUIRED - Tavily API Key for web search functionality
# Free tier available at https://tavily.com/ (1,000 searches/month)
TAVILY_API_KEY=your-tavily-api-key-here

# ✅ REQUIRED - Langtrace API Key for monitoring
# Sign up at https://langtrace.com/
LANGTRACE_API_KEY=your-langtrace-api-key-here

📝 Note: config.env.template is provided as an example. Do NOT edit the template directly - always copy it to config.env and edit that file.

Step 3: Deploy to Cloud Run

# Execute deployment script
./deploy-cloudrun.sh

The deployment script will automatically:

  • ✅ Enable required GCP APIs
  • ✅ Create Cloud Memorystore Redis instance
  • ✅ Create GCS storage bucket
  • ✅ Configure VPC connector
  • ✅ Create service accounts with minimal permissions
  • ✅ Deploy backend and frontend services
  • ✅ Configure CORS and networking

Step 4: Access Your Application

After successful deployment, you'll see:

🎉 Deployment Complete!
==========================
🤖 Chatbot Frontend: https://chatbot-frontend-xxx.a.run.app
📚 API Documentation: https://chatbot-backend-xxx.a.run.app/docs
🔍 Health Check: https://chatbot-backend-xxx.a.run.app/

📋 Configuration Reference

Required Configuration

All API keys and URLs must be configured in config.env:

Configuration Description How to Obtain
GMI_API_KEY GMI LLM service API key GMI Console
GOOGLE_CLOUD_PROJECT Your GCP project ID GCP Console
TAVILY_API_KEY Web search API key Tavily - Free tier: 1K searches/month
LANGTRACE_API_KEY Conversation tracing & monitoring Langtrace

Optional Configuration

Configuration Description Default Value
GCS_BUCKET Storage bucket name chatbot-vectordb-{project-id}
REGION Deployment region us-central1
GMI_BASE_URL GMI service base URL https://api.gmi-serving.com
OPENAI_BASE_URL OpenAI-compatible API URL https://api.gmi-serving.com/v1

Configuration File Structure

cloudrun/
├── config.env.template  ← Example template (DO NOT EDIT)
└── config.env          ← Your actual configuration (EDIT THIS)

⚠️ Security Note:

  • config.env contains sensitive API keys - NEVER commit this file to Git
  • It's already in .gitignore for your protection
  • Only config.env.template should be committed as documentation

🧪 Testing Deployment

For testing without affecting production, use the test deployment script:

# Deploy test environment (separate services)
./deploy-test-cloudrun.sh --region us-central1

# This creates:
# - chatbot-backend-test (test backend)
# - chatbot-frontend-test (test frontend)
# (Production services remain untouched)

# Clean up test resources when done
./deploy-test-cloudrun.sh --cleanup

🛠️ Management Commands

View Service Status

# List all Cloud Run services
gcloud run services list --region=us-central1

# Describe specific service
gcloud run services describe chatbot-backend --region=us-central1

View Logs

# Real-time logs (backend)
gcloud run services logs read chatbot-backend --region=us-central1 --limit=100

# Real-time logs (frontend)
gcloud run services logs read chatbot-frontend --region=us-central1 --limit=100

# Filter for errors only
gcloud run services logs read chatbot-backend --region=us-central1 --log-filter='severity>=ERROR'

Update Deployment

# Redeploy with latest code changes
./deploy-cloudrun.sh

# Update environment variables only (no rebuild)
gcloud run services update chatbot-backend \
  --region=us-central1 \
  --set-env-vars="NEW_VAR=value"

Clean Up Resources

# Remove all deployed resources
./cleanup.sh

# This will delete:
# - Cloud Run services (frontend & backend)
# - Redis instance
# - VPC connector
# - Service accounts
# (GCS bucket is preserved by default)

🏗️ Architecture

┌─────────────────┐         ┌─────────────────┐
│   Frontend      │ ──────► │   Backend       │
│  (Cloud Run)    │  HTTPS  │  (Cloud Run)    │
│   Next.js       │         │    FastAPI      │
└─────────────────┘         └─────────────────┘
                                    │
                    ┌───────────────┼───────────────┐
                    ▼               ▼               ▼
            ┌──────────────┐ ┌──────────┐  ┌──────────┐
            │    Redis     │ │   GCS    │  │ GMI API  │
            │ Memorystore  │ │ Storage  │  │ (External)│
            │  (Sessions)  │ │ (Vectors)│  │          │
            └──────────────┘ └──────────┘  └──────────┘

Components

  • Frontend: Next.js application providing chat interface
  • Backend: FastAPI application handling AI requests
  • Redis: Cloud Memorystore for session storage and caching
  • GCS: Google Cloud Storage for vector databases and uploaded files
  • VPC Connector: Enables secure communication between Cloud Run and Redis

✨ Features

Supported Capabilities

  • ✅ Multi-modal RAG: Upload and query PDF, audio (WAV/MP3), images (PNG/JPG)
  • ✅ Web Search: Real-time information retrieval via Tavily API
  • ✅ Multiple Output Formats: Text, Audio (TTS), PDF, Image (Stable Diffusion), Video
  • ✅ Voice-to-Voice: Real-time voice conversation via WebSocket
  • ✅ Streaming: Server-sent events for real-time text streaming
  • ✅ Session Management: Redis-backed persistent sessions with rate limiting
  • ✅ Tool Router: Intelligent ReAct agent for web search integration

Model Support

  • LLM Models: Meta-Llama, DeepSeek, and other GMI-supported models
  • Embedding: SentenceTransformer (all-MiniLM-L6-v2)
  • TTS: Kokoro (multi-language support)
  • Image Generation: Stable Diffusion 2.1
  • Video Generation: Veo3, and other T2V models via GMI IE API

💰 Cost Estimation

Monthly Costs (Approximate)

Service Configuration Est. Cost
Cloud Run (Backend) 16GB RAM, 4 CPU, min=0 $20-40
Cloud Run (Frontend) 1GB RAM, 1 CPU, min=0 $5-10
Cloud Memorystore Redis Basic tier, 1GB $45
Cloud Storage Vector databases $1-5
VPC Connector Standard $9

Total: ~$80-110/month (varies with usage)

Cost Optimization Tips

  1. Set min-instances=0 for auto-scaling to zero during idle periods
  2. Use Basic tier Redis (not High Availability)
  3. Set up lifecycle policies to delete old GCS objects
  4. Monitor usage with Cloud Billing reports

🔒 Security

Automatic Security Features

  • ✅ API keys stored in Secret Manager (never in environment variables)
  • ✅ Service accounts with least-privilege IAM roles
  • ✅ VPC-based private network communication
  • ✅ HTTPS-only with automatic SSL certificates
  • ✅ Session cookies with secure and httponly flags

Production Recommendations

  1. Configure Custom Domain: Use your own domain with Cloud Run
  2. Enable Cloud Armor: DDoS protection and WAF
  3. Set Up Monitoring: Cloud Monitoring alerts for errors and latency
  4. Implement Backups: Regular Redis snapshots and GCS versioning
  5. Audit Logs: Enable Cloud Audit Logs for compliance

🐛 Troubleshooting

Common Issues

1. Deployment Fails: "APIs not enabled"

# Manually enable required APIs
gcloud services enable run.googleapis.com \
  redis.googleapis.com \
  vpcaccess.googleapis.com \
  secretmanager.googleapis.com \
  storage.googleapis.com

2. Redis Connection Errors

# Check VPC connector status
gcloud compute networks vpc-access connectors describe chatbot-connector \
  --region=us-central1

# Verify Redis instance
gcloud redis instances describe chatbot-redis --region=us-central1

3. Frontend Can't Reach Backend (CORS)

  • Verify NEXT_PUBLIC_API_URL is correctly set during build
  • Check backend CORS middleware includes frontend origin
  • Test backend directly: curl https://your-backend.run.app/

4. Container Startup Timeout

This usually happens when models are being downloaded on first startup:

  • Solution: Use lazy loading (models download on first use)
  • Wait 2-3 minutes for models to download
  • Increase startup timeout if needed: --timeout=1800

5. "Invalid API Key" Errors

  • Verify API keys in config.env have no trailing spaces/newlines
  • Test API key validity: curl the GMI API directly
  • Check Secret Manager contains correct values

Debug Commands

# View revision status
gcloud run revisions list --service=chatbot-backend --region=us-central1

# Check environment variables
gcloud run services describe chatbot-backend --region=us-central1 \
  --format="value(spec.template.spec.containers[0].env)"

# View recent build logs
gcloud builds list --limit=5

# Test backend health
curl https://chatbot-backend-xxx.a.run.app/

📦 What Gets Deployed

Cloud Run Services

  1. chatbot-backend

    • Image: Built from chatbot_project/
    • Memory: 16GB
    • CPU: 4
    • Port: 8000
    • Timeout: 30 minutes
  2. chatbot-frontend

    • Image: Built from chatbot_project/chatbot-nextjs/
    • Memory: 1GB
    • CPU: 1
    • Port: 3000

Infrastructure

  • VPC Connector: chatbot-connector (for Cloud Run → Redis communication)
  • Redis Instance: chatbot-redis (1GB Basic tier)
  • GCS Bucket: chatbot-vectordb-{project-id}
  • Service Accounts:
    • chatbot-backend-sa: Backend service identity
    • chatbot-frontend-sa: Frontend service identity (if needed)

Secret Manager Secrets

  • gmi-api-key: GMI API key
  • tavily-api-key: Tavily search API key (if configured)
  • langtrace-api-key: Langtrace monitoring key (if configured)
  • hf-token: Hugging Face token (for model downloads)

🔄 Update Workflow

Code Changes

# 1. Make changes to code in chatbot_project/
# 2. Test locally (optional)
# 3. Deploy to test environment first
./deploy-test-cloudrun.sh

# 4. Verify test deployment works
# 5. Deploy to production
./deploy-cloudrun.sh

Configuration Changes

# 1. Edit config.env with new values
nano config.env

# 2. Update secrets in Secret Manager
source config.env
printf '%s' "$GMI_API_KEY" | gcloud secrets versions add gmi-api-key --data-file=-

# 3. Redeploy to pick up new configuration
./deploy-cloudrun.sh

📞 Support & Documentation

Additional Resources

Getting Help

If you encounter issues:

  1. ✅ Verify all required fields in config.env are filled
  2. ✅ Check GCP permissions and billing status
  3. ✅ Review deployment logs for specific errors
  4. ✅ Consult the Troubleshooting section above
  5. ✅ Test individual components (Redis, GCS) separately

📝 Important Notes

Configuration Files

  • config.env.template: Example configuration file - DO NOT edit directly
  • config.env: Your actual configuration - MUST be created and filled before deployment
  • All API keys and sensitive values MUST be specified in config.env
  • The config.env file is .gitignored for security

First Deployment

  • Initial deployment takes 15-20 minutes (infrastructure provisioning)
  • Subsequent deployments take 5-10 minutes (code updates only)
  • Models are lazy-loaded on first use (expect slower first request)

Production Checklist

Before going to production:

  • All API keys configured in config.env
  • Custom domain configured (optional)
  • Monitoring and alerts set up
  • Backup strategy defined
  • Budget alerts configured
  • CORS origins reviewed and restricted

Happy Deploying! 🎉

For questions or issues, please refer to the troubleshooting section or consult the main project documentation.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages