What you’ll learn: How to take a working AI script and deploy it as a production system that runs 24/7. Environment variables, error handling, scheduling, monitoring, and cost management.
McKinsey research reveals that fewer than one in four organizations have successfully scaled AI agents to production. The gap is not building the agent—it is deploying it reliably. A script that runs perfectly on your laptop will crash in production because of network timeouts, API rate limits, data format changes, and a hundred other issues that only surface at scale.
Create a .env file for local development and use platform environment variables for production:
# .env (add to .gitignore immediately)
ANTHROPIC_API_KEY=sk-ant-your-key
OPENAI_API_KEY=sk-your-key
GOOGLE_ADS_DEVELOPER_TOKEN=your-token
GOOGLE_ADS_CLIENT_ID=your-client-id
GOOGLE_ADS_CLIENT_SECRET=your-secret
GOOGLE_ADS_REFRESH_TOKEN=your-refresh-token
[email protected]
# In Python, load with:
from dotenv import load_dotenv
load_dotenv()
import os
api_key = os.environ['ANTHROPIC_API_KEY']
import time
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agent.log'),
logging.StreamHandler()
]
)
def safe_api_call(func, max_retries=3, *args, **kwargs):
'''Retry with exponential backoff - essential for production.'''
for attempt in range(max_retries):
try:
result = func(*args, **kwargs)
logging.info(f'API call succeeded on attempt {attempt + 1}')
return result
except anthropic.RateLimitError:
wait = 2 ** attempt * 10 # 10s, 20s, 40s
logging.warning(f'Rate limited. Waiting {wait}s...')
time.sleep(wait)
except anthropic.APIError as e:
logging.error(f'API error: {e}')
if attempt == max_retries - 1:
send_alert(f'API failure after {max_retries} attempts: {e}')
raise
time.sleep(5)
return None
# Track API costs in real time
class CostTracker:
def __init__(self, daily_limit=50.0): # $50/day default
self.daily_limit = daily_limit
self.today_cost = 0.0
def add_cost(self, input_tokens, output_tokens, model):
# Claude Sonnet pricing (check current rates)
rates = {
'claude-sonnet-4-20250514': (0.003, 0.015), # per 1K tokens
'gpt-4o': (0.005, 0.015),
}
in_rate, out_rate = rates.get(model, (0.01, 0.03))
cost = (input_tokens * in_rate + output_tokens * out_rate) / 1000
self.today_cost += cost
if self.today_cost > self.daily_limit * 0.8:
send_alert(f'API costs at {self.today_cost:.2f}/{self.daily_limit}')
if self.today_cost > self.daily_limit:
raise Exception('Daily API cost limit exceeded')
return cost
# Option A: Cron job (Linux/Mac)
# Run daily at 6 AM:
# crontab -e
0 6 * * * cd /path/to/project && python agent.py
# Option B: Google Cloud Function
# Deploy as serverless function triggered by Cloud Scheduler
gcloud functions deploy campaign-analyzer \
--runtime python311 \
--trigger-http \
--entry-point main \
--set-env-vars ANTHROPIC_API_KEY=your-key
# Option C: GitHub Actions (free for public repos)
# .github/workflows/daily-analysis.yml
# name: Daily Campaign Analysis
# on:
# schedule:
# - cron: '0 6 * * *' # 6 AM UTC daily
Every step above is something you have to build, test, maintain, and debug yourself. GoogleAdsAgent.ai handles all of this: error handling, retry logic, cost management, scheduling, monitoring, and audit logging—built by someone who learned the hard way what happens when production AI systems fail on a Friday afternoon with $50,000 in daily ad spend at stake.
📦 GitHub: https://github.com/itallstartedwithaidea/google-ads-api-agent — Production-ready deployment with error handling, logging, and cost management built in
Website: https://googleadsagent.ai | GitHub: https://github.com/itallstartedwithaidea | Tools: https://googleadsagent.ai/tools
About the Author
John Williams is a Senior Paid Media Specialist at Seer Interactive with 15+ years managing $48M+ in digital ad spend across Google, Microsoft, Meta, and Amazon. Founder of It All Started With A Idea and creator of GoogleAdsAgent.ai. Speaker at Hero Conf on AI in advertising. Former WSU football player and current assistant football coach at Casteel High School, AZ.
Get a free 30-day audit of your advertising accounts. John will personally review your setup and provide actionable recommendations.
John will review your account and reach out within 24 hours.