adloop 0.37.0__tar.gz → 0.37.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. {adloop-0.37.0 → adloop-0.37.1}/PKG-INFO +2 -2
  2. {adloop-0.37.0 → adloop-0.37.1}/README.md +1 -1
  3. {adloop-0.37.0 → adloop-0.37.1}/pyproject.toml +1 -1
  4. {adloop-0.37.0 → adloop-0.37.1}/pyproject.toml.orig +1 -1
  5. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/conversion_actions.py +61 -12
  6. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/pmax.py +255 -1
  7. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/write.py +144 -0
  8. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/adloop.md +3 -2
  9. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/server.py +17 -1
  10. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/__init__.py +0 -0
  11. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/__main__.py +0 -0
  12. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/_mcp_patches.py +0 -0
  13. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/__init__.py +0 -0
  14. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/ai_max.py +0 -0
  15. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/assets.py +0 -0
  16. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/audiences.py +0 -0
  17. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/brands.py +0 -0
  18. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/campaign_settings.py +0 -0
  19. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/client.py +0 -0
  20. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/currency.py +0 -0
  21. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/custom_conversion_goals.py +0 -0
  22. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/enums.py +0 -0
  23. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/forecast.py +0 -0
  24. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/gaql.py +0 -0
  25. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/image_fetch.py +0 -0
  26. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/read.py +0 -0
  27. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/recommendation_subscriptions.py +0 -0
  28. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/recommendations.py +0 -0
  29. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/shopping.py +0 -0
  30. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/snippet_headers.py +0 -0
  31. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ads/validate_only.py +0 -0
  32. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/auth.py +0 -0
  33. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/cli.py +0 -0
  34. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/config.py +0 -0
  35. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/crossref.py +0 -0
  36. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/diagnostics.py +0 -0
  37. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ga4/__init__.py +0 -0
  38. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ga4/client.py +0 -0
  39. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ga4/reports.py +0 -0
  40. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ga4/tracking.py +0 -0
  41. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/ga4/write.py +0 -0
  42. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gsc/__init__.py +0 -0
  43. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gsc/client.py +0 -0
  44. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gsc/reports.py +0 -0
  45. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gtm/__init__.py +0 -0
  46. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gtm/client.py +0 -0
  47. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gtm/entities.py +0 -0
  48. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gtm/read.py +0 -0
  49. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/gtm/write.py +0 -0
  50. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/merchant/__init__.py +0 -0
  51. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/merchant/client.py +0 -0
  52. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/merchant/read.py +0 -0
  53. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/pagespeed.py +0 -0
  54. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/reddit/__init__.py +0 -0
  55. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/reddit/auth.py +0 -0
  56. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/reddit/client.py +0 -0
  57. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/reddit/read.py +0 -0
  58. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/reddit/schedule.py +0 -0
  59. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/reddit/write.py +0 -0
  60. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/__init__.py +0 -0
  61. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/commands/analyze-performance.md +0 -0
  62. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/commands/budget-plan.md +0 -0
  63. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/commands/create-ad.md +0 -0
  64. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/commands/create-campaign.md +0 -0
  65. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/commands/diagnose-tracking.md +0 -0
  66. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules/commands/optimize-campaign.md +0 -0
  67. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/rules_install.py +0 -0
  68. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/runtime.py +0 -0
  69. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/safety/__init__.py +0 -0
  70. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/safety/approval.py +0 -0
  71. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/safety/approval_card.html +0 -0
  72. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/safety/audit.py +0 -0
  73. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/safety/guards.py +0 -0
  74. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/safety/preview.py +0 -0
  75. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/tracking.py +0 -0
  76. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/upload_card.html +0 -0
  77. {adloop-0.37.0 → adloop-0.37.1}/src/adloop/uploads.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: adloop
3
- Version: 0.37.0
3
+ Version: 0.37.1
4
4
  Summary: The AI command center for Google Ads, Reddit Ads, GA4, and tracking code.
5
5
  Keywords: mcp,google-ads,reddit-ads,google-analytics,ga4,cursor,marketing
6
6
  Author: Daniel Klose
@@ -303,7 +303,7 @@ All write operations follow a **draft → preview → confirm** workflow. Nothin
303
303
  | `draft_asset_group_assets` | Add and remove Performance Max assets (text, images incl. uploads, YouTube videos) in one change, so replacing an asset never drops a group below Google's minimums |
304
304
  | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group |
305
305
  | `draft_pmax_product_exclusions` | Exclude products from a retail PMax asset group by item id, brand or custom label |
306
- | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
306
+ | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, campaign-level broad match (Smart Bidding only), Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
307
307
  | `draft_ad_group` | Create a paused SEARCH_STANDARD ad group inside an existing campaign, with optional MANUAL_CPC `max_cpc`. |
308
308
  | `update_ad_group` | Update an ad group name and/or MANUAL_CPC `max_cpc`. Use `pause_entity` / `enable_entity` for ad-group status changes. |
309
309
  | `draft_responsive_search_ad` | Create RSA preview (3-15 headlines ≤30 chars, 2-4 descriptions ≤90 chars). Warns if headline/description count is below best practice. |
@@ -275,7 +275,7 @@ All write operations follow a **draft → preview → confirm** workflow. Nothin
275
275
  | `draft_asset_group_assets` | Add and remove Performance Max assets (text, images incl. uploads, YouTube videos) in one change, so replacing an asset never drops a group below Google's minimums |
276
276
  | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group |
277
277
  | `draft_pmax_product_exclusions` | Exclude products from a retail PMax asset group by item id, brand or custom label |
278
- | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
278
+ | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, campaign-level broad match (Smart Bidding only), Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
279
279
  | `draft_ad_group` | Create a paused SEARCH_STANDARD ad group inside an existing campaign, with optional MANUAL_CPC `max_cpc`. |
280
280
  | `update_ad_group` | Update an ad group name and/or MANUAL_CPC `max_cpc`. Use `pause_entity` / `enable_entity` for ad-group status changes. |
281
281
  | `draft_responsive_search_ad` | Create RSA preview (3-15 headlines ≤30 chars, 2-4 descriptions ≤90 chars). Warns if headline/description count is below best practice. |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.37.0"
3
+ version = "0.37.1"
4
4
  description = "The AI command center for Google Ads, Reddit Ads, GA4, and tracking code."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.37.0"
3
+ version = "0.37.1"
4
4
  description = "The AI command center for Google Ads, Reddit Ads, GA4, and tracking code."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -598,6 +598,29 @@ def _sha256_hex(value: str) -> str:
598
598
  return hashlib.sha256(value.encode("utf-8")).hexdigest()
599
599
 
600
600
 
601
+ _SHA256_HEX_RE = re.compile(r"[0-9a-fA-F]{64}")
602
+ _SHA256_OF_NOTHING = hashlib.sha256(b"").hexdigest()
603
+
604
+
605
+ def _prehashed(value: str) -> str:
606
+ """A cell that already holds a SHA-256 hex digest, lowercased; else "".
607
+
608
+ A CRM export can hash before it writes, so raw values never reach disk.
609
+ Hashing such a digest again, or reading it as a malformed address, would
610
+ upload an identifier that matches nobody.
611
+ """
612
+ text = (value or "").strip()
613
+ return text.lower() if _SHA256_HEX_RE.fullmatch(text) else ""
614
+
615
+
616
+ def _blank_if_hash_of_nothing(value: str) -> str:
617
+ """An export that hashes every cell turns a blank one into the digest of "".
618
+
619
+ That digest identifies nobody, so it counts as the blank it was.
620
+ """
621
+ return "" if _prehashed(value) == _SHA256_OF_NOTHING else value
622
+
623
+
601
624
  def _normalize_email(email: str) -> str:
602
625
  """Normalize an email the way Enhanced Conversions expect it hashed.
603
626
 
@@ -2348,7 +2371,9 @@ def _parse_ec_for_leads_csv(
2348
2371
  Each is normalized (email→trim+lowercase, phone→E.164, names→trim+
2349
2372
  lowercase) and then SHA-256-hashed here. Returned rows contain ONLY the
2350
2373
  hashes (``*_sha256`` keys) plus non-PII fields — the raw values never
2351
- leave this function.
2374
+ leave this function. A cell that already is a SHA-256 hex digest is used
2375
+ as it is (``prehashed_cells`` counts those), and the digest of an empty
2376
+ string counts as a blank cell.
2352
2377
  """
2353
2378
  records, errors, timezone = _read_upload_csv(csv_path)
2354
2379
  if errors:
@@ -2394,16 +2419,22 @@ def _parse_ec_for_leads_csv(
2394
2419
  if "Order ID" in optional_col:
2395
2420
  order_id = raw[optional_col["Order ID"]].strip()
2396
2421
  # Normalize THEN hash. Raw values are discarded immediately.
2397
- raw_email = raw[col["Email"]]
2422
+ raw_email = _blank_if_hash_of_nothing(raw[col["Email"]])
2423
+ email_hash = _prehashed(raw_email)
2398
2424
  email_norm = _normalize_email(raw_email)
2399
- raw_phone = raw[col["Phone Number"]]
2400
- phone_norm = _normalize_phone_e164(raw_phone, default_region)
2425
+ raw_phone = _blank_if_hash_of_nothing(raw[col["Phone Number"]])
2426
+ phone_hash = _prehashed(raw_phone)
2427
+ phone_norm = _normalize_phone_e164(raw_phone, default_region) if not phone_hash else ""
2401
2428
  # A phone that is not E.164 hashes to a value Google can never match —
2402
2429
  # sending it would only pad the payload. Keep the row (email/address
2403
2430
  # may still match) but drop the identifier and say so.
2404
- phone_usable = phone_norm.startswith("+")
2405
- first_norm = _normalize_name(raw[col["First Name"]])
2406
- last_norm = _normalize_name(raw[col["Last Name"]])
2431
+ phone_usable = bool(phone_hash) or phone_norm.startswith("+")
2432
+ raw_first = _blank_if_hash_of_nothing(raw[col["First Name"]])
2433
+ raw_last = _blank_if_hash_of_nothing(raw[col["Last Name"]])
2434
+ first_hash = _prehashed(raw_first)
2435
+ last_hash = _prehashed(raw_last)
2436
+ first_norm = _normalize_name(raw_first)
2437
+ last_norm = _normalize_name(raw_last)
2407
2438
 
2408
2439
  def _optional(name: str) -> str:
2409
2440
  return raw[optional_col[name]].strip() if name in optional_col else ""
@@ -2446,13 +2477,14 @@ def _parse_ec_for_leads_csv(
2446
2477
  postal = ""
2447
2478
  out.append({
2448
2479
  "source_line": source_line,
2449
- "email_sha256": _sha256_hex(email_norm),
2480
+ "email_sha256": email_hash or _sha256_hex(email_norm),
2450
2481
  "email_was_given": bool((raw_email or "").strip()),
2451
- "phone_sha256": _sha256_hex(phone_norm) if phone_usable else "",
2482
+ "phone_sha256": phone_hash or (_sha256_hex(phone_norm) if phone_usable else ""),
2452
2483
  "phone_was_given": bool((raw_phone or "").strip()),
2453
2484
  "phone_usable": phone_usable,
2454
- "first_name_sha256": _sha256_hex(first_norm),
2455
- "last_name_sha256": _sha256_hex(last_norm),
2485
+ "first_name_sha256": first_hash or _sha256_hex(first_norm),
2486
+ "last_name_sha256": last_hash or _sha256_hex(last_norm),
2487
+ "prehashed_cells": sum(map(bool, (email_hash, phone_hash, first_hash, last_hash))),
2456
2488
  "postal_code": postal,
2457
2489
  "country_code": country,
2458
2490
  "conversion_name": raw[col["Conversion Name"]].strip(),
@@ -2483,6 +2515,7 @@ def _match_warnings(
2483
2515
  address_without_names: list[int],
2484
2516
  unusable_phones: list[int],
2485
2517
  unusable_emails: list[int],
2518
+ prehashed: list[int] | None = None,
2486
2519
  ) -> list[str]:
2487
2520
  """Warnings about identifiers that will not match, said up front.
2488
2521
 
@@ -2522,6 +2555,13 @@ def _match_warnings(
2522
2555
  "match. Those rows are uploaded without the email identifier; "
2523
2556
  f"first affected rows: {unusable_emails[:5]}."
2524
2557
  )
2558
+ if prehashed:
2559
+ warnings.append(
2560
+ f"{len(prehashed)} row(s) carry identifiers that already are SHA-256 "
2561
+ "digests, used as they are. They match only if the values were normalized "
2562
+ "the way Google asks before hashing, which cannot be checked from a "
2563
+ f"digest; first affected rows: {prehashed[:5]}."
2564
+ )
2525
2565
  return warnings
2526
2566
 
2527
2567
 
@@ -2540,7 +2580,9 @@ def draft_upload_enhanced_conversions_for_leads(
2540
2580
  Email / Phone / First Name / Last Name columns, and previews what will
2541
2581
  be pushed via ConversionUploadService.UploadClickConversions with
2542
2582
  user_identifiers populated. Only the hashes are stored in the plan —
2543
- raw PII never lands in plan.changes or the audit log.
2583
+ raw PII never lands in plan.changes or the audit log. A cell that already
2584
+ is a SHA-256 hex digest (a CRM export that hashes before writing) is used
2585
+ as it is, and the preview says how many rows carry one.
2544
2586
 
2545
2587
  The target conversion action must be of type UPLOAD_CLICKS (EC for Leads
2546
2588
  layers user-identifier matching on top of click conversions). Works
@@ -2684,6 +2726,11 @@ def draft_upload_enhanced_conversions_for_leads(
2684
2726
  for index, r in enumerate(rows, start=1)
2685
2727
  if r["email_was_given"] and not r["email_sha256"]
2686
2728
  ]
2729
+ prehashed_rows = [
2730
+ _source_line(r, index)
2731
+ for index, r in enumerate(rows, start=1)
2732
+ if r.get("prehashed_cells")
2733
+ ]
2687
2734
  names_without_address = [
2688
2735
  _source_line(r, index)
2689
2736
  for index, r in enumerate(rows, start=1)
@@ -2761,6 +2808,7 @@ def draft_upload_enhanced_conversions_for_leads(
2761
2808
  "rows_with_phone": with_phone,
2762
2809
  "rows_with_order_id": with_order_id,
2763
2810
  "rows_with_address": with_address,
2811
+ **({"rows_with_prehashed_identifiers": len(prehashed_rows)} if prehashed_rows else {}),
2764
2812
  "skipped_count": len(skipped),
2765
2813
  "skipped_rows": skipped,
2766
2814
  # Say it in prose too: the count is easy to miss in a JSON blob.
@@ -2782,6 +2830,7 @@ def draft_upload_enhanced_conversions_for_leads(
2782
2830
  address_without_names,
2783
2831
  unusable_phones,
2784
2832
  unusable_emails,
2833
+ prehashed_rows,
2785
2834
  ),
2786
2835
  "sample_rows": [
2787
2836
  {
@@ -1,4 +1,4 @@
1
- """Performance Max asset groups: add and remove assets — draft → preview → apply.
1
+ """Performance Max: read tools, and asset group writes (draft → preview → apply).
2
2
 
3
3
  ``draft_asset_group_assets`` changes the assets of one existing asset group
4
4
  in one atomic GoogleAdsService.Mutate: new assets are created with temp ids
@@ -16,6 +16,9 @@ from __future__ import annotations
16
16
 
17
17
  from typing import TYPE_CHECKING, Any
18
18
 
19
+ from adloop.ads.currency import get_currency_code
20
+ from adloop.ads.read import _date_clause, _enrich_cost_fields
21
+
19
22
  if TYPE_CHECKING:
20
23
  from adloop.config import AdLoopConfig
21
24
 
@@ -719,3 +722,254 @@ def apply_pmax_product_filter(client: object, cid: str, changes: dict) -> dict:
719
722
  "newly_excluded": changes.get("newly_excluded", []),
720
723
  "no_longer_excluded": changes.get("no_longer_excluded", []),
721
724
  }
725
+
726
+
727
+ # ---------------------------------------------------------------------------
728
+ # Read tools
729
+ # ---------------------------------------------------------------------------
730
+
731
+
732
+ def get_pmax_performance(
733
+ config: AdLoopConfig,
734
+ *,
735
+ customer_id: str = "",
736
+ date_range_start: str = "",
737
+ date_range_end: str = "",
738
+ ) -> dict:
739
+ """Get Performance Max campaign metrics with network breakdown and asset group ad strength."""
740
+ from adloop.ads.gaql import execute_query
741
+
742
+ date_clause = _date_clause(date_range_start, date_range_end)
743
+
744
+ campaign_query = f"""
745
+ SELECT campaign.id, campaign.name, campaign.status,
746
+ campaign.bidding_strategy_type,
747
+ metrics.impressions, metrics.clicks, metrics.cost_micros,
748
+ metrics.conversions, metrics.conversions_value,
749
+ metrics.ctr, metrics.average_cpc,
750
+ segments.ad_network_type
751
+ FROM campaign
752
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
753
+ AND campaign.status != 'REMOVED'
754
+ {date_clause}
755
+ ORDER BY metrics.cost_micros DESC
756
+ """
757
+
758
+ campaigns = execute_query(config, customer_id, campaign_query)
759
+ currency_code = get_currency_code(config, customer_id)
760
+ _enrich_cost_fields(campaigns, currency_code)
761
+
762
+ asset_group_query = f"""
763
+ SELECT asset_group.id, asset_group.name, asset_group.status,
764
+ asset_group.ad_strength, asset_group.campaign,
765
+ metrics.impressions, metrics.clicks, metrics.cost_micros,
766
+ metrics.conversions, metrics.conversions_value
767
+ FROM asset_group
768
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
769
+ {date_clause}
770
+ ORDER BY metrics.cost_micros DESC
771
+ """
772
+
773
+ asset_groups = execute_query(config, customer_id, asset_group_query)
774
+ _enrich_cost_fields(asset_groups, currency_code)
775
+
776
+ insights: list[str] = []
777
+
778
+ poor_strength = [
779
+ ag for ag in asset_groups
780
+ if ag.get("asset_group.ad_strength") in ("POOR", "AVERAGE")
781
+ ]
782
+ if poor_strength:
783
+ names = ", ".join(
784
+ ag.get("asset_group.name", "?") for ag in poor_strength[:5]
785
+ )
786
+ insights.append(
787
+ f"{len(poor_strength)} asset group(s) have POOR or AVERAGE ad strength: "
788
+ f"{names}. Add more diverse assets (headlines, descriptions, images) to improve."
789
+ )
790
+
791
+ zero_conv_groups = [
792
+ ag for ag in asset_groups
793
+ if (ag.get("metrics.clicks", 0) or 0) > 10
794
+ and (ag.get("metrics.conversions", 0) or 0) == 0
795
+ ]
796
+ if zero_conv_groups:
797
+ names = ", ".join(
798
+ ag.get("asset_group.name", "?") for ag in zero_conv_groups[:5]
799
+ )
800
+ insights.append(
801
+ f"{len(zero_conv_groups)} asset group(s) have clicks but zero conversions: {names}."
802
+ )
803
+
804
+ network_counts: dict[str, int] = {}
805
+ for c in campaigns:
806
+ net = c.get("segments.ad_network_type", "UNKNOWN")
807
+ network_counts[net] = network_counts.get(net, 0) + (
808
+ c.get("metrics.impressions", 0) or 0
809
+ )
810
+ if network_counts:
811
+ total_impr = sum(network_counts.values()) or 1
812
+ dist = {
813
+ k: f"{round(v / total_impr * 100, 1)}%"
814
+ for k, v in sorted(network_counts.items(), key=lambda x: -x[1])
815
+ }
816
+ insights.append(f"PMax network distribution by impressions: {dist}")
817
+
818
+ if not campaigns:
819
+ insights.append("No Performance Max campaigns found in this account.")
820
+
821
+ return {
822
+ "campaigns": campaigns,
823
+ "asset_groups": asset_groups,
824
+ "total_campaigns": len(campaigns),
825
+ "total_asset_groups": len(asset_groups),
826
+ "insights": insights,
827
+ }
828
+
829
+
830
+ def get_asset_performance(
831
+ config: AdLoopConfig,
832
+ *,
833
+ customer_id: str = "",
834
+ campaign_id: str = "",
835
+ ) -> dict:
836
+ """Get per-asset details for Performance Max asset groups.
837
+
838
+ Returns each asset's field type, status, primary serving status, and
839
+ content. ``primary_status`` shows whether the asset is eligible to serve
840
+ (ELIGIBLE, NOT_ELIGIBLE, PAUSED, PENDING).
841
+
842
+ Note: the Google Ads API does not expose per-asset performance labels
843
+ (BEST/GOOD/LOW) for PMax assets via GAQL. Use ``get_detailed_asset_performance``
844
+ to see which asset *combinations* Google selects most — that's the closest
845
+ proxy for individual asset quality.
846
+ """
847
+ from adloop.ads.gaql import execute_query
848
+
849
+ campaign_filter = ""
850
+ if campaign_id:
851
+ campaign_filter = f"AND campaign.id = {campaign_id}"
852
+
853
+ query = f"""
854
+ SELECT asset_group_asset.asset, asset_group_asset.field_type,
855
+ asset_group_asset.status, asset_group_asset.primary_status,
856
+ asset_group.id, asset_group.name,
857
+ campaign.id, campaign.name,
858
+ asset.name, asset.type,
859
+ asset.text_asset.text,
860
+ asset.image_asset.full_size.url
861
+ FROM asset_group_asset
862
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
863
+ {campaign_filter}
864
+ """
865
+
866
+ rows = execute_query(config, customer_id, query)
867
+
868
+ status_counts: dict[str, int] = {}
869
+ field_type_counts: dict[str, int] = {}
870
+ for row in rows:
871
+ status = row.get("asset_group_asset.primary_status", "UNSPECIFIED")
872
+ status_counts[status] = status_counts.get(status, 0) + 1
873
+ ftype = row.get("asset_group_asset.field_type", "UNSPECIFIED")
874
+ field_type_counts[ftype] = field_type_counts.get(ftype, 0) + 1
875
+
876
+ insights: list[str] = []
877
+ if not rows:
878
+ insights.append(
879
+ "No PMax assets found. This account has no Performance Max campaigns, "
880
+ "or the specified campaign_id does not match a PMax campaign."
881
+ )
882
+ else:
883
+ not_eligible = [
884
+ r for r in rows
885
+ if r.get("asset_group_asset.primary_status") == "NOT_ELIGIBLE"
886
+ ]
887
+ if not_eligible:
888
+ insights.append(
889
+ f"{len(not_eligible)} asset(s) are NOT_ELIGIBLE to serve — "
890
+ f"check policy status or asset quality."
891
+ )
892
+
893
+ return {
894
+ "assets": rows,
895
+ "total_assets": len(rows),
896
+ "by_status": status_counts,
897
+ "by_field_type": field_type_counts,
898
+ "insights": insights,
899
+ }
900
+
901
+
902
+ def get_detailed_asset_performance(
903
+ config: AdLoopConfig,
904
+ *,
905
+ customer_id: str = "",
906
+ campaign_id: str = "",
907
+ ) -> dict:
908
+ """Get top-performing asset combinations for Performance Max campaigns.
909
+
910
+ Uses the ``asset_group_top_combination_view`` resource directly (not
911
+ ``execute_query``) because the nested proto structure requires custom
912
+ extraction.
913
+ """
914
+ from adloop.ads.client import get_ads_client, normalize_customer_id
915
+
916
+ client = get_ads_client(config)
917
+ service = client.get_service("GoogleAdsService")
918
+ cid = normalize_customer_id(customer_id)
919
+
920
+ campaign_filter = ""
921
+ if campaign_id:
922
+ campaign_filter = f"AND campaign.id = {campaign_id}"
923
+
924
+ query = f"""
925
+ SELECT asset_group_top_combination_view.asset_group_top_combinations,
926
+ campaign.id, campaign.name,
927
+ asset_group.id, asset_group.name
928
+ FROM asset_group_top_combination_view
929
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
930
+ {campaign_filter}
931
+ """
932
+
933
+ combinations: list[dict] = []
934
+ for row in service.search(customer_id=cid, query=query):
935
+ campaign_name = row.campaign.name
936
+ campaign_id_val = row.campaign.id
937
+ ag_name = row.asset_group.name
938
+ ag_id = row.asset_group.id
939
+
940
+ top_combos = row.asset_group_top_combination_view.asset_group_top_combinations
941
+ for combo in top_combos:
942
+ assets_in_combo: list[dict] = []
943
+ for served_info in getattr(combo, "asset_combination_serving_infos", []):
944
+ for asset_usage in getattr(served_info, "served_assets", []):
945
+ field_type = getattr(asset_usage, "served_asset_field_type", None)
946
+ assets_in_combo.append({
947
+ "asset": getattr(asset_usage, "asset", ""),
948
+ "field_type": (
949
+ field_type.name
950
+ if hasattr(field_type, "name")
951
+ else str(field_type)
952
+ ),
953
+ })
954
+
955
+ if assets_in_combo:
956
+ combinations.append({
957
+ "campaign.id": campaign_id_val,
958
+ "campaign.name": campaign_name,
959
+ "asset_group.id": ag_id,
960
+ "asset_group.name": ag_name,
961
+ "assets": assets_in_combo,
962
+ })
963
+
964
+ insights: list[str] = []
965
+ if not combinations:
966
+ insights.append(
967
+ "No top asset combinations found. This account has no Performance Max "
968
+ "campaigns, or the specified campaign_id does not match a PMax campaign."
969
+ )
970
+
971
+ return {
972
+ "top_combinations": combinations,
973
+ "total_combinations": len(combinations),
974
+ "insights": insights,
975
+ }
@@ -2275,6 +2275,7 @@ def update_campaign(
2275
2275
  tracking_url_template: str | None = None,
2276
2276
  final_url_suffix: str | None = None,
2277
2277
  url_custom_parameters: list[dict] | None = None,
2278
+ keyword_match_type: str = "",
2278
2279
  ) -> dict:
2279
2280
  """Draft an update to an existing campaign — returns preview, does NOT execute.
2280
2281
 
@@ -2283,6 +2284,8 @@ def update_campaign(
2283
2284
  A location option change shows the current value next to the new one.
2284
2285
  URL options: None leaves one unchanged, an empty string or list clears it;
2285
2286
  the preview shows the current values and an example click URL.
2287
+ keyword_match_type BROAD (campaign-level broad match on) needs Smart
2288
+ Bidding and a double confirmation; UNSPECIFIED turns it off.
2286
2289
  """
2287
2290
  from adloop.safety.guards import (
2288
2291
  SafetyViolation,
@@ -2315,6 +2318,13 @@ def update_campaign(
2315
2318
  )
2316
2319
  errors.extend(url_errors)
2317
2320
 
2321
+ keyword_match_type = (keyword_match_type or "").strip().upper()
2322
+ if keyword_match_type and keyword_match_type not in _CAMPAIGN_KEYWORD_MATCH_TYPES:
2323
+ errors.append(
2324
+ "keyword_match_type must be BROAD (campaign-level broad match on) or "
2325
+ f"UNSPECIFIED (off), got '{keyword_match_type}'"
2326
+ )
2327
+
2318
2328
  campaign_id = str(campaign_id or "").strip()
2319
2329
  if not campaign_id:
2320
2330
  errors.append("campaign_id is required")
@@ -2373,6 +2383,7 @@ def update_campaign(
2373
2383
  location_option,
2374
2384
  negative_location_option,
2375
2385
  url_options,
2386
+ keyword_match_type,
2376
2387
  ])
2377
2388
  if not has_any_change:
2378
2389
  errors.append("No changes specified — provide at least one parameter to update")
@@ -2446,6 +2457,33 @@ def update_campaign(
2446
2457
  }
2447
2458
  url_example = _example_click_urls(current_urls["final_url"], effective)
2448
2459
 
2460
+ current_match: dict = {}
2461
+ broad_on = False
2462
+ leaves_smart = bool(bs) and bs not in _SMART_BIDDING_STRATEGIES
2463
+ if keyword_match_type or leaves_smart:
2464
+ current_match = _current_keyword_match_type(config, customer_id, campaign_id)
2465
+ if current_match is None:
2466
+ return {"error": f"Campaign {campaign_id} was not found in this account"}
2467
+ is_broad = current_match["keyword_match_type"] == "BROAD"
2468
+ broad_on = keyword_match_type == "BROAD" and not is_broad
2469
+ # Same rule as BROAD keywords: no broad match without Smart Bidding. A
2470
+ # bidding change in the same plan counts, since both apply in one mutate.
2471
+ broad_error = _broad_match_bidding_error(
2472
+ keyword_match_type, bs, current_match["bidding_strategy"], is_broad
2473
+ )
2474
+ if broad_error:
2475
+ return {"error": "Validation failed", "details": [broad_error]}
2476
+ if broad_on:
2477
+ warnings.append(_BROAD_ON_WARNING)
2478
+ if keyword_match_type == "UNSPECIFIED" and is_broad:
2479
+ warnings.append(_BROAD_OFF_WARNING)
2480
+ if leaves_smart:
2481
+ warnings.append(
2482
+ f"Under {bs} the keywords already converted to broad match "
2483
+ "keep matching broadly without Smart Bidding. Replace them with "
2484
+ "phrase or exact match keywords."
2485
+ )
2486
+
2449
2487
  # A budget can be shared by several campaigns, and a portfolio bid
2450
2488
  # strategy too: say who else a budget change reaches, and that a bidding
2451
2489
  # change takes the campaign out of its portfolio. Both need a double
@@ -2517,6 +2555,12 @@ def update_campaign(
2517
2555
  changes[f"current_{field}"] = current_urls[field]
2518
2556
  changes[field] = url_options[field]
2519
2557
 
2558
+ if keyword_match_type:
2559
+ changes["current_keyword_match_type"] = current_match["keyword_match_type"]
2560
+ changes["keyword_match_type"] = keyword_match_type
2561
+ if broad_on:
2562
+ requires_double_confirm = True
2563
+
2520
2564
  plan = ChangePlan(
2521
2565
  operation="update_campaign",
2522
2566
  entity_type="campaign",
@@ -3811,6 +3855,97 @@ def _example_click_urls(final_url: str, options: dict) -> dict:
3811
3855
  return example
3812
3856
 
3813
3857
 
3858
+ # campaign.keyword_match_type: BROAD makes every keyword in the campaign match
3859
+ # as broad; UNSPECIFIED (the default) leaves each keyword's own match type.
3860
+ _CAMPAIGN_KEYWORD_MATCH_TYPES = {"BROAD", "UNSPECIFIED"}
3861
+
3862
+ _BROAD_ON_WARNING = (
3863
+ "Turning campaign-level broad match on CONVERTS every existing phrase and exact "
3864
+ "match keyword in this campaign into broad match; Google shows the originals as "
3865
+ "Removed, and turning the setting off later does not restore them. Since "
3866
+ "September 2026 Google also upgrades campaigns with this setting to AI Max. "
3867
+ "Ads can show on searches the keyword list never named: check search terms "
3868
+ "daily after this goes live."
3869
+ )
3870
+ _BROAD_OFF_WARNING = (
3871
+ "Turning campaign-level broad match off stops further keywords being converted, "
3872
+ "but keywords already converted stay broad match and the original phrase and "
3873
+ "exact keywords are not restored; re-add them by hand. If Google upgraded the "
3874
+ "campaign to AI Max, check get_campaign_settings: this does not turn it off."
3875
+ )
3876
+
3877
+
3878
+ def _current_keyword_match_type(
3879
+ config: AdLoopConfig, customer_id: str, campaign_id: str
3880
+ ) -> dict | None:
3881
+ """The campaign's keyword match type and bidding strategy; None when it does not exist."""
3882
+ from adloop.ads.gaql import execute_query
3883
+
3884
+ rows = execute_query(config, customer_id, (
3885
+ "SELECT campaign.keyword_match_type, campaign.bidding_strategy_type "
3886
+ f"FROM campaign WHERE campaign.id = {campaign_id}"))
3887
+ if not rows:
3888
+ return None
3889
+ return {
3890
+ "keyword_match_type": rows[0].get("campaign.keyword_match_type") or "UNSPECIFIED",
3891
+ "bidding_strategy": rows[0].get("campaign.bidding_strategy_type") or "",
3892
+ }
3893
+
3894
+
3895
+ def _broad_match_bidding_error(
3896
+ keyword_match_type: str, new_strategy: str, current_strategy: str, is_broad: bool
3897
+ ) -> str:
3898
+ """Why this combination would leave broad match without Smart Bidding, or ""."""
3899
+ strategy = new_strategy or current_strategy
3900
+ if keyword_match_type == "BROAD" and strategy not in _SMART_BIDDING_STRATEGIES:
3901
+ return (
3902
+ "Campaign-level broad match requires Smart Bidding "
3903
+ f"(tCPA/tROAS/Maximize Conversions); this campaign uses {strategy}. "
3904
+ "Broad match without Smart Bidding leads to irrelevant matches and "
3905
+ "wasted budget. Switch the campaign to Smart Bidding first."
3906
+ )
3907
+ if (
3908
+ new_strategy and new_strategy not in _SMART_BIDDING_STRATEGIES
3909
+ and is_broad and keyword_match_type != "UNSPECIFIED"
3910
+ ):
3911
+ return (
3912
+ "This campaign has campaign-level broad match on, which needs Smart "
3913
+ f"Bidding. To move it to {new_strategy}, turn broad match off in the same "
3914
+ 'call (keyword_match_type="UNSPECIFIED") so both change in one mutate.'
3915
+ )
3916
+ return ""
3917
+
3918
+
3919
+ def _check_broad_match_bidding(service, cid: str, changes: dict) -> None:
3920
+ """Re-check the broad match / Smart Bidding rule against the account at apply.
3921
+
3922
+ The draft checked it, but two plans applied in reverse order, or a bidding
3923
+ change in the UI, could otherwise leave broad match on a non-Smart strategy.
3924
+ Runs in the dry run too: the validate-only client passes reads through.
3925
+ """
3926
+ match_type = changes.get("keyword_match_type") or ""
3927
+ new_strategy = changes.get("bidding_strategy") or ""
3928
+ leaves_smart = bool(new_strategy) and new_strategy not in _SMART_BIDDING_STRATEGIES
3929
+ if match_type != "BROAD" and not (leaves_smart and match_type != "UNSPECIFIED"):
3930
+ return
3931
+ campaign_id = changes["campaign_id"]
3932
+ rows = list(service.search(customer_id=cid, query=(
3933
+ "SELECT campaign.bidding_strategy_type, campaign.keyword_match_type "
3934
+ f"FROM campaign WHERE campaign.id = {campaign_id}")))
3935
+ if not rows:
3936
+ raise ValueError(f"Campaign {campaign_id} not found")
3937
+ campaign = rows[0].campaign
3938
+ current_strategy = getattr(campaign.bidding_strategy_type, "name", campaign.bidding_strategy_type)
3939
+ current_match = getattr(campaign.keyword_match_type, "name", campaign.keyword_match_type)
3940
+ error = _broad_match_bidding_error(
3941
+ match_type, new_strategy, str(current_strategy), str(current_match) == "BROAD"
3942
+ )
3943
+ if error:
3944
+ raise RuntimeError(
3945
+ f"Campaign {campaign_id} changed after this preview; nothing was sent. {error}"
3946
+ )
3947
+
3948
+
3814
3949
  def _validate_campaign(
3815
3950
  config: AdLoopConfig,
3816
3951
  *,
@@ -4698,6 +4833,7 @@ def _apply_update_campaign(client: object, cid: str, changes: dict) -> dict:
4698
4833
  campaign_id = changes["campaign_id"]
4699
4834
  resource_name = campaign_service.campaign_path(cid, campaign_id)
4700
4835
  _check_budget_and_bidding_unchanged(service, cid, changes)
4836
+ _check_broad_match_bidding(service, cid, changes)
4701
4837
 
4702
4838
  # Bid strategy and campaign-level setting changes
4703
4839
  bs = changes.get("bidding_strategy")
@@ -4706,6 +4842,7 @@ def _apply_update_campaign(client: object, cid: str, changes: dict) -> dict:
4706
4842
  location_option = changes.get("location_option")
4707
4843
  negative_location_option = changes.get("negative_location_option")
4708
4844
  url_fields = [field for field in _URL_OPTION_FIELDS if field in changes]
4845
+ keyword_match_type = changes.get("keyword_match_type")
4709
4846
  if (
4710
4847
  bs
4711
4848
  or search_partners_enabled is not None
@@ -4714,6 +4851,7 @@ def _apply_update_campaign(client: object, cid: str, changes: dict) -> dict:
4714
4851
  or location_option
4715
4852
  or negative_location_option
4716
4853
  or url_fields
4854
+ or keyword_match_type
4717
4855
  ):
4718
4856
  campaign_op = client.get_type("MutateOperation")
4719
4857
  campaign = campaign_op.campaign_operation.update
@@ -4778,6 +4916,12 @@ def _apply_update_campaign(client: object, cid: str, changes: dict) -> dict:
4778
4916
  for param in changes.get("url_custom_parameters") or []:
4779
4917
  campaign.url_custom_parameters.append(_custom_parameter(client, param))
4780
4918
  field_paths.extend(url_fields)
4919
+ if keyword_match_type:
4920
+ # UNSPECIFIED under the mask clears the setting.
4921
+ campaign.keyword_match_type = getattr(
4922
+ client.enums.CampaignKeywordMatchTypeEnum, keyword_match_type
4923
+ )
4924
+ field_paths.append("keyword_match_type")
4781
4925
 
4782
4926
  if field_paths:
4783
4927
  campaign_op.campaign_operation.update_mask.CopyFrom(
@@ -262,7 +262,7 @@ Conversions that happen offline (a sales call, a lead that turned into a deal) g
262
262
  | `draft_upload_enhanced_conversions_for_leads` | Form leads that became a conversion; matched by hashed email, phone or name and address | exactly one of `csv_path` or `upload_id`; `default_region`; `consent` |
263
263
 
264
264
  - The conversion action named in the CSV's `Conversion Name` column must exist and be of type UPLOAD_CALLS (calls) or UPLOAD_CLICKS (leads); the draft checks it against the account.
265
- - **The CSV holds personal data** (phone numbers, emails, names). An uploaded file lasts two hours at most and is deleted as soon as a draft has read it, so a second draft needs a new upload; a failed draft keeps it for a retry (for example with `default_region`). Lead identifiers are hashed while drafting. Never ask the user to paste rows into the chat.
265
+ - **The CSV holds personal data** (phone numbers, emails, names). An uploaded file lasts two hours at most and is deleted as soon as a draft has read it, so a second draft needs a new upload; a failed draft keeps it for a retry (for example with `default_region`). Lead identifiers are hashed while drafting; a cell that already is a SHA-256 hex digest is used as it is. Never ask the user to paste rows into the chat.
266
266
  - EEA traffic needs consent signals: pass `consent` or fill the CSV's `Ad User Data` / `Ad Personalization` columns. Present the preview's `consent_summary`, `skipped_rows` and `dedup_warnings`.
267
267
  - Apply sends batches of 2,000 rows. `PARTIAL_UPLOAD` means some batches are already in the account: the plan is retired, and a new draft continues at `resume_from_line`. Don't re-upload rows that went through.
268
268
 
@@ -285,7 +285,7 @@ Conversions that happen offline (a sales call, a lead that turned into a deal) g
285
285
  | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group, or remove signals | `asset_group_id`, `add_search_themes` (≤80 chars, up to 50 per group), `audience_id` (one per group), `remove_signal_ids` |
286
286
  | `draft_pmax_product_exclusions` | Set the full list of products a retail PMax asset group excludes, on one dimension; everything else stays included | `asset_group_id`, `exclude_values` (the COMPLETE list; `[]` includes everything again), `dimension` item_id (default) / brand / custom_label_0–4 |
287
287
  | `draft_ad_group` | Create a new ad group within an existing campaign (does NOT publish) | `campaign_id` (REQUIRED), `ad_group_name` (REQUIRED), `keywords` (optional list of {text, match_type}), `cpc_bid_micros` (optional) |
288
- | `update_campaign` | Modify existing campaign settings — bid strategy, budget, geo targets, language targets, location options, Search partners, display expansion, URL options | `campaign_id` (REQUIRED), plus any of: `bidding_strategy`, `daily_budget`, `geo_target_ids`, `language_ids`, `location_option`, `negative_location_option`, `search_partners_enabled`, `display_network_enabled`, TARGET_SPEND `max_cpc`, `tracking_url_template`, `final_url_suffix`, `url_custom_parameters` |
288
+ | `update_campaign` | Modify existing campaign settings — bid strategy, budget, geo targets, language targets, location options, Search partners, display expansion, URL options, campaign-level broad match | `campaign_id` (REQUIRED), plus any of: `bidding_strategy`, `daily_budget`, `geo_target_ids`, `language_ids`, `location_option`, `negative_location_option`, `search_partners_enabled`, `display_network_enabled`, TARGET_SPEND `max_cpc`, `tracking_url_template`, `final_url_suffix`, `url_custom_parameters`, `keyword_match_type` |
289
289
  | `update_ad_group` | Update ad group name and/or MANUAL_CPC `max_cpc` | `ad_group_id`, optional `ad_group_name`, optional `max_cpc` |
290
290
  | `draft_responsive_search_ad` | Create RSA preview (does NOT publish) | 3-15 headlines (≤30 chars), 2-4 descriptions (≤90 chars), final_url required, path1/path2 (≤15 chars each). Each headline/description may be a plain string (unpinned) or `{"text": "...", "pinned_field": "HEADLINE_1"}` (pinned). Valid pin slots: `HEADLINE_1/2/3`, `DESCRIPTION_1/2`. Several assets may pin to one slot (they rotate there), but every slot must stay fillable: by an asset pinned to it or by a distinct unpinned asset. |
291
291
  | `draft_callouts` | Create callout assets for an ad group, a campaign or the account (does NOT publish) | `campaign_id` or `ad_group_id` (the scope follows the id), or `scope="account"`; `callouts` list with 1-25 chars each |
@@ -370,6 +370,7 @@ Same draft → preview → `confirm_and_apply` gate; the plan carries `platform:
370
370
  - `update_campaign` budget changes show the current amount (`current_daily_budget`). A shared budget (`budget_shared_with` lists the other campaign IDs) or a portfolio bid strategy makes the plan require double confirmation, and apply refuses if the budget, its sharing or the portfolio changed after the preview.
371
371
  - Location options: `location_option` is who the geo targets reach — `PRESENCE` (people in or regularly in the locations), `PRESENCE_OR_INTEREST` (Google's default; also people elsewhere who show interest in them) or `SEARCH_INTEREST`. `negative_location_option` (`PRESENCE` or `PRESENCE_OR_INTEREST`) is who the exclusions exclude. Empty leaves the value as it is. The preview warns when a change widens reach: for `location_option` that is anything but `PRESENCE`, for `negative_location_option` it is `PRESENCE`, because then the exclusions only keep out people physically there, not people interested in the excluded places; `update_campaign` shows the current value as `current_location_option` / `current_negative_location_option`. Read back with `get_campaign_settings`.
372
372
  - Campaign URL options (`tracking_url_template`, `final_url_suffix`, `url_custom_parameters`): omitted leaves a value unchanged, `""` or `[]` removes it, and `url_custom_parameters` replaces the whole list. The template must contain `{lpurl}` or a variant (`{lpurl+2}`, `{unescapedlpurl}`, `{escapedlpurl+3}`, ...). Custom parameter keys are alphanumeric, at most 8 characters. The `update_campaign` preview shows each current value (`current_tracking_url_template` etc.), warns on a removal, and gives `example_click`: one of the campaign's final URLs with the campaign's options applied. It is approximate: a template on the ad group, ad or keyword overrides the campaign's, and ValueTrack parameters are filled at click time. Check it for typos before approving. Read back with `get_campaign_settings`.
373
+ - Campaign-level broad match: `update_campaign` `keyword_match_type="BROAD"` CONVERTS every existing phrase and exact keyword in the campaign into broad match. Google shows the originals as Removed, turning the setting off does not restore them, and since September 2026 Google also upgrades such campaigns to AI Max. It is refused unless the campaign (or the `bidding_strategy` in the same call) is Smart Bidding — the same rule as BROAD keywords — checked again at apply, and needs a double confirmation. `keyword_match_type="UNSPECIFIED"` turns it off (single confirmation): no further conversions, but converted keywords stay broad and must be re-added as phrase/exact by hand. Moving a broad-match campaign to a non-Smart `bidding_strategy` is refused unless the same call passes `UNSPECIFIED`. Never turn it on to "get more traffic" on an exact/phrase campaign; read it back with `get_campaign_settings`, which lists it in `widening_settings`.
373
374
  - `update_campaign` replaces POSITIVE geo/language targets entirely (not append). Pass the full desired list. NEGATIVE geo exclusions (criteria with `negative=TRUE`) are **preserved** across a positive-geo replacement — they survive the swap. The preview surfaces preserved negative geo IDs in `preserved_negative_geo_target_ids` so the change is auditable. To ADD negative geo exclusions (e.g. exclude a city inside a targeted state), use `add_negative_locations` — do not try to express exclusions through `geo_target_ids`. To remove a negative geo exclusion explicitly, use `remove_entity` with `entity_type="campaign_criterion"`.
374
375
  - **Asset scope:** callouts and snippets link where the id points (`ad_group_id` → ad group, `campaign_id` → campaign). Account-wide (`scope="account"`) reaches every campaign without assets of its own; use it only when the user asks for account level. **Asset edits** (`update_callout`, `update_sitelink`, `update_structured_snippet`) change the asset everywhere it is linked; check with GAQL (`campaign_asset`, `ad_group_asset`, `customer_asset`) where else it is used before editing a shared asset. If the apply reports the asset changed in Google Ads since the preview, draft again.
375
376
  - **Call assets, schedules, promotions and prices.** Never guess `country_code` or `language_code`: take them from the number and the landing page, and ask when unclear. Money amounts are in the account currency (the preview names it); pass `currency_code` only for a different one. Ad schedule hours are in the **account time zone** (the previews show it), not the searcher's: convert the user's local hours first. A campaign without a schedule serves at all hours, so its first `add_ad_schedule` windows switch off every other hour and day: say so, the preview needs a double confirmation. To change a window, remove the old one with `remove_entity` (`entity_type="campaign_criterion"`, the `remove_id` from the preview), then add the new one. Prices must match the landing page or Google disapproves them.
@@ -3468,6 +3468,7 @@ def update_campaign(
3468
3468
  tracking_url_template: str | None = None,
3469
3469
  final_url_suffix: str | None = None,
3470
3470
  url_custom_parameters: _DictListOpt = None,
3471
+ keyword_match_type: str = "",
3471
3472
  ) -> dict:
3472
3473
  """Draft an update to an existing campaign — returns a PREVIEW, does NOT apply.
3473
3474
 
@@ -3531,6 +3532,18 @@ def update_campaign(
3531
3532
  removal, and gives example_click: one of the campaign's final URLs
3532
3533
  with the campaign's options applied. It is approximate: a template
3533
3534
  on the ad group, ad or keyword overrides the campaign's.
3535
+ keyword_match_type: Campaign-level broad match. BROAD turns it on and
3536
+ CONVERTS every existing phrase and exact keyword in the campaign to
3537
+ broad match (the originals show as Removed; turning it off does not
3538
+ restore them), and since September 2026 Google upgrades such
3539
+ campaigns to AI Max. Refused unless the campaign uses Smart Bidding
3540
+ (MAXIMIZE_CONVERSIONS, MAXIMIZE_CONVERSION_VALUE, TARGET_CPA,
3541
+ TARGET_ROAS), checked again at apply; needs a double confirmation.
3542
+ UNSPECIFIED turns it off: no further conversions, but converted
3543
+ keywords stay broad. Moving a campaign with broad match on to a
3544
+ non-Smart bidding_strategy is refused unless the same call passes
3545
+ UNSPECIFIED. The preview shows the current value. Empty leaves it
3546
+ unchanged.
3534
3547
  """
3535
3548
  from adloop.ads.write import update_campaign as _impl
3536
3549
 
@@ -3553,6 +3566,7 @@ def update_campaign(
3553
3566
  tracking_url_template=tracking_url_template,
3554
3567
  final_url_suffix=final_url_suffix,
3555
3568
  url_custom_parameters=url_custom_parameters,
3569
+ keyword_match_type=keyword_match_type,
3556
3570
  )
3557
3571
 
3558
3572
 
@@ -7060,7 +7074,9 @@ def draft_upload_enhanced_conversions_for_leads(
7060
7074
 
7061
7075
  PII is normalized and SHA-256-hashed AT PREVIEW TIME — only the hashes are
7062
7076
  stored in the plan. Raw email/phone/name never land in the plan or the
7063
- audit log. The target conversion action must be UPLOAD_CLICKS-type.
7077
+ audit log. A cell that already is a SHA-256 hex digest (a CRM export that
7078
+ hashes before writing) is used as it is. The target conversion action must
7079
+ be UPLOAD_CLICKS-type.
7064
7080
 
7065
7081
  An Order ID column makes re-uploads dedup instead of double-counting.
7066
7082
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes