When you’re managing hundreds or thousands of keywords across multiple Google Ads campaigns, manual bid adjustments become a bottleneck fast. That’s where an automated keyword bid management script changes the game—letting you respond to performance shifts in real-time without burning hours every day on tedious optimizations. In this walkthrough, we’re sharing a complete Claude Code script that connects to the Google Ads API, analyzes keyword ROI, and automatically adjusts bids based on performance triggers you define.
Our team has deployed variations of this approach for clients spending anywhere from $15,000 to $500,000 per month on paid search, and the time savings alone—never mind the performance lift—make it indispensable. We’ll walk through the entire script architecture, error handling, API authentication, and how to calculate your actual cost-per-hour savings when you automate this piece of your workflow.
Why Automated Keyword Bid Management Scripts Matter in 2026
Manual bid management was viable when accounts had 50 keywords and you checked in twice a week. But modern paid search accounts are complex ecosystems. Your average e-commerce client runs 2,000+ keywords across shopping, search, and dynamic campaigns. Your B2B SaaS client juggles branded, competitor, and intent-based keyword groups with wildly different conversion values. Making informed bid decisions at that scale—daily or even hourly—is impossible without automation.
Google’s Smart Bidding does some of this work, but it operates as a black box. You surrender control over bid logic, can’t inject your own business rules (like “never bid above $12 for this keyword because our margin doesn’t support it”), and you’re at the mercy of Google’s optimization goals, which don’t always align perfectly with yours. An automated keyword bid management script built on Claude Code or similar AI frameworks gives you the best of both worlds: machine speed and intelligence, but with full transparency and custom logic tailored to your business model.
The ROI case is straightforward. If a PPC manager spends eight hours per week manually reviewing keyword performance and adjusting bids, that’s roughly 35 hours per month. At a blended agency rate of $150/hour, you’re looking at $5,250 in labor costs monthly—or $63,000 annually—just for bid management. A script handles 90% of that work in minutes, freeing your team to focus on strategy, creative testing, and higher-leverage optimizations. For clients who want to see how AI and automation can transform their paid media operations, this is one of the clearest proof points.
Setting Up the Claude Code Google Ads API Connection
Before we dive into the logic, you need to authenticate with the Google Ads API. This involves setting up a developer token, OAuth2 credentials, and a customer ID. Google’s documentation is dense, but the core steps are: create a Google Cloud project, enable the Google Ads API, generate OAuth2 credentials (client ID and secret), and request a developer token from your Google Ads manager account. Store these securely—never hardcode credentials in your script.
Once you have credentials, the script uses a library like google-ads-api (for Node.js) or google-ads-python to authenticate and pull data. Here’s the skeleton of the authentication block in a Node.js environment using Claude Code to assist with setup:
const { GoogleAdsApi } = require('google-ads-api');
const client = new GoogleAdsApi({
client_id: process.env.GOOGLE_ADS_CLIENT_ID,
client_secret: process.env.GOOGLE_ADS_CLIENT_SECRET,
developer_token: process.env.GOOGLE_ADS_DEVELOPER_TOKEN,
});
const customer = client.Customer({
customer_id: process.env.GOOGLE_ADS_CUSTOMER_ID,
refresh_token: process.env.GOOGLE_ADS_REFRESH_TOKEN,
});
This structure keeps secrets in environment variables, which is critical for security and portability. Claude Code can help generate the boilerplate and handle error cases like expired tokens or malformed credentials. Once authenticated, you’re ready to query keyword performance data.
The script will query the keyword_view report, pulling metrics like impressions, clicks, conversions, cost, and conversion value over your chosen lookback window—typically seven or 14 days for enough statistical significance without being stale. Here’s a simplified query structure:
const query = `
SELECT
campaign.id,
ad_group.id,
ad_group_criterion.criterion_id,
ad_group_criterion.keyword.text,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.conversions,
metrics.conversions_value
FROM keyword_view
WHERE segments.date DURING LAST_14_DAYS
AND campaign.status = 'ENABLED'
AND ad_group.status = 'ENABLED'
AND ad_group_criterion.status = 'ENABLED'
`;
const keywordData = await customer.query(query);
This pulls active keywords only and grabs the core metrics you need to calculate ROI and performance triggers. From here, we move into the logic engine that decides which bids to adjust and by how much.
Building the ROI-Based Bid Adjustment Logic
The heart of any AI bid optimization script is the decision engine: the rules and thresholds that determine when to increase, decrease, or leave a bid alone. Start by defining your target ROI or target CPA. For e-commerce, you might aim for a 4:1 return on ad spend (ROAS). For lead generation, you might target a $50 cost per lead. These thresholds are your north star.
Loop through each keyword and calculate its current performance. If a keyword’s ROAS is above your target—say, 6:1 when you need 4:1—that’s a signal to increase the bid and capture more volume. If the ROAS is below target—say, 2:1—you either decrease the bid to improve efficiency or pause the keyword if it’s chronically underperforming. Here’s the logic in pseudocode:
for (const row of keywordData) {
const cost = row.metrics.cost_micros / 1_000_000; // Convert micros to currency
const revenue = row.metrics.conversions_value;
const conversions = row.metrics.conversions;
const currentBid = row.ad_group_criterion.cpc_bid_micros / 1_000_000;
if (conversions === 0 || cost === 0) continue; // Skip if no data
const roas = revenue / cost;
const targetRoas = 4.0;
let newBid = currentBid;
if (roas > targetRoas * 1.2) {
// Strong performer: increase bid by 15%
newBid = currentBid * 1.15;
} else if (roas < targetRoas * 0.8) {
// Underperformer: decrease bid by 15%
newBid = currentBid * 0.85;
}
// Apply bid floors and ceilings
newBid = Math.max(0.50, Math.min(newBid, 20.00));
if (newBid !== currentBid) {
await updateKeywordBid(customer, row, newBid);
}
}
This example uses a 20% buffer around the target ROAS to avoid over-reacting to small variance, and it caps bids between $0.50 and $20 to prevent runaway spending or bids so low they never show. You can refine these rules endlessly—add keyword-level profit margins, factor in conversion lag, weight recent performance more heavily, or segment by device and geographic performance. The flexibility is the point.
Claude Code shines here because you can describe your business logic in plain language (“increase bids by 10% if ROAS is above 5 and the keyword has at least 20 conversions in the past 14 days”), and the AI drafts the conditional logic for you. It’s faster than writing from scratch and catches edge cases you might miss. For agencies offering digital advertising services, this kind of custom automation becomes a differentiator—clients see you’re not just running standard Google Smart Bidding but engineering bespoke solutions that respect their unit economics.
Error Handling, Rate Limits, and Safe Execution
An automated keyword bid management script running in production must handle errors gracefully. The Google Ads API has rate limits (typically 15,000 operations per day for standard access), and you’ll encounter transient network errors, malformed queries, or keywords that have been paused or removed since your last run. Wrap your API calls in try-catch blocks and implement retry logic with exponential backoff.
Here’s a simplified error-handling wrapper:
async function updateKeywordBid(customer, keywordRow, newBid) {
const operation = {
update: {
resource_name: keywordRow.ad_group_criterion.resource_name,
cpc_bid_micros: Math.round(newBid * 1_000_000),
},
update_mask: { paths: ['cpc_bid_micros'] },
};
try {
await customer.adGroupCriteria.update([operation]);
console.log(`Updated ${keywordRow.ad_group_criterion.keyword.text} to ${newBid}`);
} catch (error) {
if (error.code === 'RATE_LIMIT_EXCEEDED') {
console.warn('Rate limit hit, sleeping 60 seconds...');
await sleep(60000);
return updateKeywordBid(customer, keywordRow, newBid); // Retry
} else {
console.error(`Failed to update bid for ${keywordRow.ad_group_criterion.keyword.text}:`, error.message);
// Log to monitoring service, don't crash
}
}
}
Always log failures to a monitoring service like Sentry or Datadog. In production, we run these scripts on a schedule (daily or hourly via cron or AWS Lambda), and we want alerts if the script fails repeatedly or if bid changes fall outside expected bounds (e.g., a bug that sets all bids to $0.01). Build in sanity checks: if the script wants to change more than 30% of bids in a single run, flag it for manual review before applying.
Another critical safeguard: simulate changes first. Before your script goes live, run it in “dry-run” mode where it calculates new bids and logs them without actually updating the account. Export the recommendations to a CSV and review them. You can use our free file converter tool to quickly transform the API output JSON into a spreadsheet format for easier analysis—keeping your data private and local rather than uploading to a third-party service. Once you’re confident the logic is sound, flip the switch to live execution.
How Much Time and Money Does Automated Bid Management Actually Save?
Let’s get specific. A mid-sized e-commerce account with 1,500 active keywords and daily budget adjustments takes our team roughly six hours per week to manage manually—reviewing performance, adjusting bids, checking for budget pacing issues, and documenting changes. Over a year, that’s 312 hours. At an internal cost of $100/hour (blended rate for an analyst), you’re spending $31,200 annually on this task.
An automated keyword bid management script runs daily in about two minutes (API queries and bid updates for 1,500 keywords). Human oversight—reviewing the script’s log, handling edge cases, tweaking thresholds—drops to one hour per week. That’s 52 hours annually, or $5,200 in labor. Net savings: $26,000 per year per account. Scale that across ten clients, and you’ve saved $260,000 in labor costs while likely improving performance because the script reacts faster than any human can.
Beyond time savings, automated bidding typically improves campaign efficiency by 10-20% within the first month as it eliminates the lag between performance shifts and bid adjustments. Keywords that spike in conversion rate get more budget immediately; underperformers get throttled before they waste significant spend. Over a $100,000 monthly ad budget, a 15% efficiency gain is $15,000 in either saved cost or additional revenue per month—$180,000 annually. The ROI on building and maintaining the script is massive.
Extending the Script: Multi-Account Management and Advanced Triggers
Once your core keyword bid automation script is humming, you can extend it in powerful ways. If you manage multiple Google Ads accounts (common for agencies), refactor the script to loop through an array of customer IDs. The authentication pattern stays the same; you just iterate over clients and apply the same bid logic to each. Store client-specific thresholds (target ROAS, bid floors, bid ceilings) in a configuration file or database so you’re not hardcoding values.
Advanced triggers take the logic beyond simple ROAS thresholds. For example, you might integrate weather data for a client selling seasonal products and boost bids on “patio furniture” keywords when the forecast is sunny and warm. Or connect to inventory APIs and automatically reduce bids when stock is low to avoid driving traffic you can’t fulfill. Claude Code for Google Ads bidding can help scaffold these integrations quickly—describe the data source and the conditional logic, and the AI generates the webhook calls and conditional branches.
Another extension: dayparting and geo-based bid modifiers. Pull performance by hour-of-day and geographic region, then apply bid multipliers. If your conversion rate is 50% higher between 10 AM and 2 PM, the script can increase bids during that window. If California converts at twice the rate of other states, apply a geographic bid adjustment. These compound optimizations—stacking automated keyword bids with automated modifiers—create a level of granularity that’s impossible to maintain manually.
For agencies looking to productize this capability, consider building a dashboard that visualizes which keywords were adjusted, by how much, and the resulting performance change. Tools like Retool or a custom React app can pull logs from your script’s database and present them to clients in real time. Transparency builds trust, and clients love seeing the “machine” work on their behalf. If you’re exploring how to operationalize these kinds of solutions at scale, our AI and automation practice can help architect and deploy production-ready systems.
Practical Next Steps: Deploying Your First Automated Bid Management Script
Start small. Pick one campaign or ad group with 50-100 keywords and well-established performance data. Build the script to pull data, calculate new bids, and log recommendations without applying them. Run it daily for a week and compare its suggestions to what you would have done manually. Refine your thresholds and logic based on that comparison. Once you’re confident, enable live bid updates for that test group and monitor performance closely for two weeks.
Document everything: your target metrics, your bid adjustment formulas, your error-handling strategy, and your rollback plan if something goes wrong. Treat this script like production infrastructure, because that’s what it is. Version control it in Git, write tests for your core functions (especially ROI calculations), and set up monitoring alerts. If you’re new to deploying scripts in production, consider hosting on AWS Lambda or Google Cloud Functions for easy scheduling and scalability.
Claude Code (available through Anthropic’s API or integrated development environments) can accelerate every stage of this process—from writing the initial API queries to generating error-handling logic to suggesting optimizations based on your account structure. The AI doesn’t replace your strategic thinking, but it handles the repetitive coding and catches bugs you might miss at 11 PM when you’re rushing to finish.
Finally, remember that automation is not “set it and forget it.” Your business changes, your margins shift, your product mix evolves. Review your script’s logic quarterly and adjust thresholds as needed. The goal is not to eliminate human oversight but to elevate it—spending your time on strategy, creative, and high-impact optimizations rather than grinding through spreadsheets.
Automated keyword bid management scripts are no longer a luxury reserved for enterprise advertisers with engineering teams. With tools like Claude Code, accessible APIs, and the frameworks we’ve outlined here, any performance marketer or agency can deploy sophisticated, ROI-driven bid automation in a matter of days. The efficiency gains, cost savings, and performance improvements make it one of the highest-leverage investments you can make in your paid search operations. Start building yours today, and watch your campaigns—and your margins—improve week over week.