GrepBoard/Manuals
605 manuals ·

Validate AI-generated UTM links with a Python check

·Tested on Claude Sonnet (--model sonnet) · Claude Code 2.1.302 · Python 3.12 · Ubuntu 24.04 · 2026-10·Test scope ↓·10 steps

Generate UTM links for 20 campaigns with an AI, check required parameters, case, spaces, duplicates and medium names in Python, then re-ask failing rows only.

One changed letter in a UTM link and GA4 reports a different source. Links an AI writes all look alike, so a wrong one is easy to miss by eye. Let a script count the rules and have the AI rewrite only the rows that fail. The same approach for meta descriptions is in Check AI-written meta descriptions.

[1] Check where the rules come from. The Google Analytics help page Collect campaign data with custom URLs says two things:

utm_term and utm_content are optional. The page says nothing about spaces, URL encoding or the format of campaign names. So "lowercase only", "no spaces" and "medium names from a fixed list" below are team rules, not Google rules.

[2] Put the campaign list in a tab-separated file: id, source, medium, campaign description, landing URL. The shop and campaigns are made up. c11 and c16 already have a query string on the landing URL (ref=blog, order=1) to see whether the links get a second ?.

campaigns.tsv
c01	newsletter	email	spring arrivals notice	https://shop.example.com/springc02	newsletter	email	cart reminder	https://shop.example.com/cartc03	google	cpc	brand search ads	https://shop.example.com/c04	google	cpc	winter sale search ads	https://shop.example.com/winter-salec05	instagram	paid_social	reels new product teaser	https://shop.example.com/newc06	instagram	social	profile link	https://shop.example.com/c07	facebook	paid_social	revisit retargeting	https://shop.example.com/cartc08	naver	cpc	shopping search ads	https://shop.example.com/productsc09	kakao	social	channel message coupon	https://shop.example.com/couponc10	youtube	video	review video description	https://shop.example.com/reviewc11	blog	referral	affiliate blog review	https://shop.example.com/products?ref=blogc12	partner-a	affiliate	partner banner	https://shop.example.com/partnersc13	newsletter	email	membership tier notice	https://shop.example.com/membershipc14	popup	banner	10% off first purchase	https://shop.example.com/welcomec15	qr	offline	store poster QR	https://shop.example.com/storec16	sms	sms	post-delivery review request	https://shop.example.com/review?order=1c17	linkedin	paid_social	B2B bulk order notice	https://shop.example.com/b2bc18	x	social	new product announcement	https://shop.example.com/newc19	podcast	audio	sponsor mention	https://shop.example.com/podcastc20	google	display	banner remarketing	https://shop.example.com/cart#top

[3] Write the prompt header. It fixes the output format only. Case and naming rules are left out on purpose, to see what comes back without them.

head.txt
Below are 20 marketing campaigns. Columns are tab-separated: id, source, medium, campaign description, landing URL.Build the UTM link for each campaign. Rules:- One complete URL: the landing URL with utm parameters added.- Output one JSON object per line (JSON Lines): {"id": "...", "url": "..."}- No other text, no code fences. 

[4] Join the header and the list, then run claude -p. It answers once and exits, and --max-turns 1 allows a single turn.

console
$ cat head.txt campaigns.tsv > prompt.1.txt$ claude -p --model sonnet --max-turns 1 < prompt.1.txt > out.1.jsonl$ head -3 out.1.jsonl{"id": "c01", "url": "https://shop.example.com/spring?utm_source=newsletter&utm_medium=email&utm_campaign=spring_new_arrivals"}{"id": "c02", "url": "https://shop.example.com/cart?utm_source=newsletter&utm_medium=email&utm_campaign=cart_reminder"}{"id": "c03", "url": "https://shop.example.com/?utm_source=google&utm_medium=cpc&utm_campaign=brand_search"}

[5] Write the checker. urlsplit separates the query and parse_qsl reads the parameters. It checks the three required ones, repeated keys, uppercase in utm_ keys and values, spaces, links with identical source/medium/campaign, and (optionally) a medium allowlist.

check_utm.py
#!/usr/bin/env python3"""usage: check_utm.py out.jsonl [medium,medium,...]"""import sys, json, re, collectionsfrom urllib.parse import urlsplit, parse_qsl REQ = ("utm_source", "utm_medium", "utm_campaign")ALLOWED = set(sys.argv[2].split(",")) if len(sys.argv) > 2 else Nonerows = [json.loads(l) for l in open(sys.argv[1], encoding="utf-8") if l.strip()]q = {r["id"]: parse_qsl(urlsplit(r["url"]).query, keep_blank_values=True) for r in rows}combo = lambda p: tuple(dict((k.lower(), v) for k, v in p).get(k, "") for k in REQ)seen = collections.defaultdict(list)for i, p in q.items():    seen[combo(p)].append(i)bad = 0for r in rows:    i, p, errs = r["id"], q[r["id"]], []    for k in REQ:        if not dict(p).get(k, "").strip():            errs.append(f"missing {k}")    for k, n in collections.Counter(k for k, _ in p).items():        if n > 1:            errs.append(f"repeated {k}")    for k, v in p:        if k.lower().startswith("utm_") and k != k.lower():            errs.append(f"key case {k}")        if k.startswith("utm_") and v != v.lower():            errs.append(f"value case {k}={v}")        if k.startswith("utm_") and re.search(r"\s", v):            errs.append(f"space in {k}")    m = dict(p).get("utm_medium", "")    if ALLOWED and m and m.lower() not in ALLOWED:        errs.append(f"medium {m} not in list")    if " " in r["url"]:        errs.append("raw space in url")    dup = [x for x in seen[combo(p)] if x != i]    if dup and all(combo(p)):        errs.append("same source/medium/campaign as " + ",".join(dup))    print(f"{i} {'FAIL ' + '; '.join(errs) if errs else 'ok'}")    bad += bool(errs)print(f"{len(rows)} urls, {bad} failed")sys.exit(1 if bad else 0)

[6] Run it without a medium list first. All 20 passed in this run.

console
$ python3 -I check_utm.py out.1.jsonl | tail -1; echo "exit ${PIPESTATUS[0]}"20 urls, 0 failedexit 0

All three values were lowercase with underscores instead of spaces, and ref=blog and order=1 were joined with &. A second run with the channel names changed to a mix of Korean and mixed-case English (뉴스레터, Google Ads) also came back clean.

[7] A valid format can still drift in naming. Two runs over the same 20 rows gave youtube the medium video once and social once, and split linkedin between paid_social and social. Fix the list of names and pass it as the second argument.

console
$ M=email,cpc,paid_social,social,display,affiliate,referral,sms,offline$ python3 -I check_utm.py out.1.jsonl $M | grep -v ' ok$'; echo "exit ${PIPESTATUS[0]}"c10 FAIL medium video not in listc14 FAIL medium banner not in listc19 FAIL medium audio not in list20 urls, 3 failedexit 1

[8] Re-ask for the three failing rows only. Attach the previous links and the check result, and say that only the medium may change.

prompt.3.txt
The UTM links below break the medium (utm_medium) rule. Rebuild only the ids listed.- utm_medium must be one of: email, cpc, paid_social, social, display, affiliate, referral, sms, offline.- Keep utm_source and utm_campaign exactly as in the previous link; change only utm_medium.- Output one JSON object per line: {"id": "...", "url": "..."} No other text. Previous links and check results:{"id": "c10", "url": "https://shop.example.com/review?utm_source=youtube&utm_medium=video&utm_campaign=review_video_description"}{"id": "c14", "url": "https://shop.example.com/welcome?utm_source=popup&utm_medium=banner&utm_campaign=first_purchase_10off"}{"id": "c19", "url": "https://shop.example.com/podcast?utm_source=podcast&utm_medium=audio&utm_campaign=sponsor_mention"}c10 FAIL medium video not in listc14 FAIL medium banner not in listc19 FAIL medium audio not in list
console
$ claude -p --model sonnet --max-turns 1 < prompt.3.txt > out.3.jsonl$ cat out.3.jsonl{"id": "c10", "url": "https://shop.example.com/review?utm_source=youtube&utm_medium=referral&utm_campaign=review_video_description"}{"id": "c14", "url": "https://shop.example.com/welcome?utm_source=popup&utm_medium=display&utm_campaign=first_purchase_10off"}{"id": "c19", "url": "https://shop.example.com/podcast?utm_source=podcast&utm_medium=referral&utm_campaign=sponsor_mention"}

[9] Merge the two files by id (the later file overwrites the earlier one), save as merged.jsonl, and check again.

console
$ python3 -I check_utm.py merged.jsonl $M | tail -1; echo "exit ${PIPESTATUS[0]}"20 urls, 0 failedexit 0

It passes, but the script cannot tell whether a video description or a podcast sponsorship really belongs under referral. Which name from the list to use is a human call.

[10] The model produced no format defects this time, so test the remaining checks on bad.jsonl, a hand-damaged copy of out.1.jsonl: uppercase in the c02 source, spaces in the c04 campaign, medium removed from c06, a second utm_source on c08, c12 key changed to UTM_source, c18 given the same source, medium and campaign as c01. These are not model errors.

console
$ python3 -I check_utm.py bad.jsonl $M | grep -v ' ok$'; echo "exit ${PIPESTATUS[0]}"c01 FAIL same source/medium/campaign as c18c02 FAIL value case utm_source=Newsletterc04 FAIL space in utm_campaign; raw space in urlc06 FAIL missing utm_mediumc08 FAIL repeated utm_source; value case utm_source=Naverc10 FAIL medium video not in listc12 FAIL missing utm_source; key case UTM_sourcec14 FAIL medium banner not in listc18 FAIL same source/medium/campaign as c01c19 FAIL medium audio not in list20 urls, 10 failedexit 1

c10, c14 and c19 are medium-list violations from the untouched original rows.

#utm#ga4#python#claude