Optimize a campaign
An outbound campaign written by Amdahl from a spreadsheet of recipients, with no data connected: a script that builds the context for each row, writes one message per recipient, survives being stopped, and stays inside the monthly cap.
Level: a script. Call: messages.optimize, once per recipient, or messages.optimize_batch for a big campaign. You need: a Customer agent key in AMDAHL_KEY, Python 3.9 or later, and your recipients in a CSV. No connected data.
Amdahl writes each message from the context you send. A draft is optional. So a campaign is not a list of drafts to improve: it is a list of recipients, and for each one, what you know about them. The script below turns each row of a spreadsheet into that context, and writes one message per recipient. Nothing is sent and nothing in your tools changes: the output is a second CSV.
Your recipients as a CSV
One row per recipient. Each column is something you know about that person, and each one becomes a fact. A recipients.csv with two rows:
id,channel,name,title,company,why_now,notes
lead-001,email,Sam Ortiz,Head of RevOps,Brightpath,"Brightpath posted three SDR roles last week.","Moved from Salesforce to HubSpot in August."
lead-002,linkedin,Priya Shah,VP Sales,Northwind Labs,"Northwind raised a Series B in July.",""why_nowmatters most. It is the reason to write to this person today: a hire, a launch, a funding round, a post. A row without one gets a generic message.notesis anything else you know, such as a line from your CRM or from a call. Leave it empty when you have nothing.channelisemailorlinkedin. It sets the length and format of the message. Send it: with no draft, there is nothing to infer it from.- Export real values, not merge fields. The message is written for one person, so
{{first_name}}has nothing to stand for. Each row gets its own message.
What is the same for every row, such as what you sell, the proof you may cite and the ask, goes in the script once. Context says what counts as enough.
The script
It uses only the Python standard library. It sends one recipient at a time, appends each result to messages.csv as it lands, and skips any id already there, so you can stop it and start it again without paying twice. Save it as optimize_campaign.py:
#!/usr/bin/env python3
"""Write one message per recipient in a CSV with the Amdahl Message Optimizer.
Usage: AMDAHL_KEY=amdhl_... python3 optimize_campaign.py recipients.csv messages.csv
Input columns: id, name, title, company, why_now, notes, and optionally channel.
Re-runnable: an id already in the output file is skipped.
"""
import csv, json, os, sys, time, urllib.error, urllib.request
API = "https://app.amdahl.ai/api/platform/v1/messages/optimize"
KEY = os.environ["AMDAHL_KEY"]
SRC = sys.argv[1] if len(sys.argv) > 1 else "recipients.csv"
OUT = sys.argv[2] if len(sys.argv) > 2 else "messages.csv"
# True for every recipient: what you sell and the proof you may cite. One fact per entry.
CAMPAIGN_FACTS = [
"We sell Rampwise, which gives every new sales rep a guided first 30 days.",
"A 150-person sales team cut new-rep ramp from 90 to 45 days with Rampwise.",
]
# Applied to every message. Say the ask here.
RULES = ["Ask for a 20-minute call next week.", "Never mention pricing."]
VOICE_EXAMPLES = [] # up to 5 messages the sender wrote themselves
COLUMNS = ["id", "channel", "outcome", "facts_sent", "returned", "summary",
"omitted", "notes", "reason", "run_id"]
def facts_for(row):
"""The facts for one recipient: who they are, why now, what else you know."""
facts = []
who = ", ".join(v for v in (row.get("title", "").strip(), row.get("company", "").strip()) if v)
if row.get("name", "").strip():
facts.append(f"The recipient is {row['name'].strip()}" + (f", {who}." if who else "."))
for column in ("why_now", "notes"):
if row.get(column, "").strip():
facts.append(row[column].strip())
return (facts + CAMPAIGN_FACTS)[:10] # at most 10 facts per call
def post(body):
"""POST one request. Returns (HTTP status, parsed body, seconds to wait on a 429)."""
req = urllib.request.Request(
API, data=json.dumps(body).encode("utf-8"), method="POST",
headers={"X-API-Key": KEY, "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=310) as res:
return res.status, json.load(res), 0
except urllib.error.HTTPError as err:
raw = err.read().decode("utf-8", "replace")
retry_after = err.headers.get("Retry-After") or ""
wait = int(retry_after) if retry_after.isdigit() else 60
try:
return err.code, json.loads(raw), wait
except ValueError: # the per-IP limiter answers in plain text
return err.code, {"error": {"code": f"http_{err.code}", "message": raw}}, wait
def body_for(row):
context = {"facts": facts_for(row), "rules": RULES, "voice_examples": VOICE_EXAMPLES}
body = {"context": {k: v for k, v in context.items() if v}}
if (row.get("channel") or "").strip():
body["channel"] = row["channel"].strip()
return body
def optimize(row):
body = body_for(row)
while True:
try:
status, payload, wait = post(body)
except OSError as err: # no answer within 310 seconds, or the network failed
return {"ok": False, "reason": f"no_answer: {err}"}
data = payload.get("data", payload)
error = data.get("error") if isinstance(data.get("error"), dict) else {}
code = error.get("code")
if code == "quota_exceeded":
sys.exit("Monthly Optimizer cap reached. Re-run next month; finished rows are kept.")
if status in (401, 403):
sys.exit(f"{status}: {error.get('message') or payload}. Mint a Customer agent key.")
if status == 429: # a rate limit, not the cap: wait and retry this row
time.sleep(wait)
continue
if status != 200:
return {"ok": False, "reason": code or f"http_{status}"}
return data
def main():
fresh = not os.path.exists(OUT) or os.path.getsize(OUT) == 0
done = set()
if not fresh:
with open(OUT, newline="", encoding="utf-8") as f:
done = {r["id"] for r in csv.DictReader(f)}
with open(SRC, newline="", encoding="utf-8") as f:
rows = [r for r in csv.DictReader(f) if r["id"] not in done]
with open(OUT, "a", newline="", encoding="utf-8") as f:
out = csv.DictWriter(f, fieldnames=COLUMNS)
if fresh:
out.writeheader()
for n, row in enumerate(rows, 1):
r = optimize(row)
if r.get("reason") in ("optimizer_error", "optimizer_timeout"):
# The Optimizer may be down. Wait, try this row once more, then stop.
time.sleep(r.get("retry_after_seconds") or 60)
r = optimize(row)
if r.get("reason") in ("optimizer_error", "optimizer_timeout"):
sys.exit(f"Stopped at {row['id']}: {r['reason']}. Run it again later; finished rows are kept.")
outcome = r.get("outcome") or ("failed" if not r.get("ok") else "rewritten")
out.writerow({
"id": row["id"],
"channel": row.get("channel", ""),
"outcome": outcome,
"facts_sent": (r.get("context") or {}).get("facts", ""),
"returned": r.get("message", ""),
"summary": r.get("summary", ""),
"omitted": " | ".join(f"{o['what']}: {o['why']}" for o in r.get("omitted") or []),
"notes": " ".join(note["code"] for note in r.get("notes") or []),
"reason": r.get("reason", ""),
"run_id": r.get("run_id", ""),
})
f.flush()
print(f"[{n}/{len(rows)}] {row['id']}: {outcome}")
if __name__ == "__main__":
main()Run it:
export AMDAHL_KEY="amdhl_your_key_here"
python3 optimize_campaign.py recipients.csv messages.csvCreate the key with amdahl keys create --name "Campaign" --preset agent (see CLI), or in the console with Access set to Customer agent. Before a long run, check that the key can optimize and that the month has room for every row:
curl -s "https://app.amdahl.ai/api/platform/v1/setup/status" -H "X-API-Key: $AMDAHL_KEY" | jq '.data.optimize'allowed must be true, and quota.remaining must cover the rows in your CSV. When allowed is false, blocker names the fix; see Check your setup.
Each message usually takes 1 to 2 minutes, so a 100-row campaign takes 2 to 3 hours. Start it and come back.
What it does on each outcome
| Outcome | What the script does | Why |
|---|---|---|
rewritten | Writes the message to returned with the summary, and what it left out to omitted | The returned text is the whole result. Keep it as is. A row in omitted names a fact the row's context could not back. |
optimizer_error or optimizer_timeout | Waits retry_after_seconds (60 when the response gives none), tries that row once more, then stops | Amdahl may be down, and the next rows would fail the same way. The row is not written, so the next run starts at it. |
Any other ok: false | Writes the reason, moves on | Nothing was written. |
429 with quota_exceeded | Stops | The workspace used this month's API and connector optimizations (1,000 by default). Rows already written are kept. |
Any other 429 | Waits for Retry-After, retries that row | A rate limit, or the workspace's own optimize limits (3 running at once, 12 started a minute). Not the cap. |
401 or 403 | Stops | The key is wrong, expired, Read only, or older than the optimize call, or your role is Viewer. GET /setup/status names which. |
| No answer in 310 seconds | Records it, moves on | It does not retry: every attempt is a fresh run. |
It runs one row at a time on purpose: each answer comes back on the same call, and a workspace may run 3 single optimizes at once and start 12 a minute. That suits a campaign you want to watch row by row. For a big one, do not loop faster: send a batch.
A big campaign: send it as a batch
For a few hundred recipients, the loop above is slow, and a faster loop only collects 429s. A batch is one request: you send every row, get a batch_id back at once, and collect the results when they are ready. A batch is never refused as busy. Its items run behind single calls, so it does not hold up the people writing one message at a time, and it does not use your workspace's own 3 at once.
Each item carries what you know about its recipient in the facts in its context, exactly as the loop does. An item also takes the recipient fields, as a single call does. This script takes the same recipients.csv and writes the same messages.csv. It reuses facts_for and body_for from the script above, so save both in one folder:
#!/usr/bin/env python3
"""Write one message per recipient in a CSV as Amdahl Message Optimizer batches.
Usage: AMDAHL_KEY=amdhl_... python3 optimize_campaign_batch.py recipients.csv messages.csv
Safe to run again: the same rows are the same batch, not a second one.
"""
import csv, hashlib, json, os, sys, time, urllib.error, urllib.request
API = "https://app.amdahl.ai/api/platform/v1/messages/optimize"
KEY = os.environ["AMDAHL_KEY"]
SRC = sys.argv[1] if len(sys.argv) > 1 else "recipients.csv"
OUT = sys.argv[2] if len(sys.argv) > 2 else "messages.csv"
COLUMNS = ["id", "channel", "outcome", "facts_sent", "returned", "summary",
"omitted", "notes", "reason", "run_id"]
BATCH_SIZE = 500 # the most items one batch takes
from optimize_campaign import body_for # the same CAMPAIGN_FACTS and RULES
def call(method, url, body=None):
"""One request. Returns (HTTP status, parsed body)."""
req = urllib.request.Request(
url, method=method,
data=json.dumps(body).encode("utf-8") if body is not None else None,
headers={"X-API-Key": KEY, "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=60) as res:
return res.status, json.load(res)
except urllib.error.HTTPError as err:
raw = err.read().decode("utf-8", "replace")
try:
return err.code, json.loads(raw)
except ValueError: # the per-IP limiter answers in plain text
return err.code, {"error": {"code": f"http_{err.code}", "message": raw}}
def stop(status, payload):
data = payload.get("data") or {}
error = data.get("error") or payload.get("error") or {}
sys.exit(f"{status} {error.get('code')}: {error.get('message')}")
def submit(rows):
"""Queue one batch and return its id."""
items = [{"item_id": row["id"], **body_for(row)} for row in rows]
# The same rows always make the same key. If the connection drops and you
# run this again, you get the batch already queued instead of a second one.
key = hashlib.sha256(json.dumps(items, sort_keys=True).encode("utf-8")).hexdigest()
status, payload = call("POST", f"{API}/batch", {"items": items, "idempotency_key": key})
if status != 202:
stop(status, payload)
return payload["data"]["batch_id"]
def read(batch_id, query):
"""Read the batch, waiting out a rate limit."""
while True:
status, payload = call("GET", f"{API}/batches/{batch_id}?{query}")
if status == 200:
return payload["data"]
if status != 429:
stop(status, payload)
time.sleep(30)
def collect(batch_id):
"""Wait until the batch completes, then return every item in order."""
while True:
batch = read(batch_id, "limit=1")
counts, eta = batch["counts"], batch.get("eta")
left = f", about {eta['seconds'] // 60 + 1} min left (an estimate)" if eta else ""
print(f"{counts['done'] + counts['failed']}/{counts['total']} finished{left}")
if batch["status"] == "completed":
break
time.sleep(20)
items, cursor = [], None
while True:
page = read(batch_id, "limit=100" + (f"&cursor={cursor}" if cursor else ""))
items += page["items"]
cursor = page["next_cursor"]
if not cursor:
return items
with open(SRC, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
by_id = {row["id"]: row for row in rows}
with open(OUT, "w", newline="", encoding="utf-8") as f:
out = csv.DictWriter(f, fieldnames=COLUMNS)
out.writeheader()
for start in range(0, len(rows), BATCH_SIZE):
batch_id = submit(rows[start:start + BATCH_SIZE])
print(f"batch {batch_id} queued")
for item in collect(batch_id):
row, r = by_id[item["item_id"]], item["result"] or {}
out.writerow({
"id": row["id"],
"channel": row.get("channel", ""),
"outcome": r.get("outcome") or ("failed" if not r.get("ok") else "rewritten"),
"facts_sent": (r.get("context") or {}).get("facts", ""),
"returned": r.get("message", ""),
"summary": r.get("summary", ""),
"omitted": " | ".join(f"{o['what']}: {o['why']}" for o in r.get("omitted") or []),
"notes": " ".join(note["code"] for note in r.get("notes") or []),
"reason": r.get("reason", ""),
"run_id": r.get("run_id", ""),
})
f.flush()export AMDAHL_KEY="amdhl_your_key_here"
python3 optimize_campaign_batch.py recipients.csv messages.csv- It prints an estimate, not a promise. The batch's
etais the recent median run time, times the items ahead of yours and your own, divided by the places batches may use. Single calls go first, so a busy hour makes it longer. - Running it again is safe. The
idempotency_keyis made from the rows, so the same file is the same batch. A second run waits for the batch that is already queued and does not start another. Change a row and it is a new batch. - Every
idmust be different. Each one is sent as the item'sitem_id, which is how a result is matched to its row. - A failed row is not charged.
optimizer_timeoutandoptimizer_errorrows were already tried up to 3 times. Put them in a new CSV and run that. - The cap still applies. A batch larger than what is left of the month is refused whole with
429 quota_exceeded, anderror.details.remainingsays how many rows would fit. - To be told when it is done, send a
webhook_urlwith the batch instead of polling: see Completion webhook.
Read the results
Open messages.csv in a spreadsheet and sort by facts_sent.
- Few facts, generic message. A row with
facts_sentof 2 or 3 is usually only the campaign facts and a name. Its message has little to say about the recipient. Add awhy_nowand run that row again. rewritten: read each message against the row it came from. Every specific line should come from a fact. These runs are evaluated without your data. They do not evaluate claims against your customers' own conversations, so a fact that was wrong in the CSV is still wrong in the message. Thenotescolumn carriesstyle_pass_onlyon every row for that reason.omitted: what a message left out because its row could not back it, each aswhat: why. The script sends noon_missing_input, so every row runsbest_effortand gets a message. Add the missing facts to the row'snotesinrecipients.csv, then run it again.failed: run the script again later; it only retries what is not yet in the file. To retry a failed row, delete its line frommessages.csvfirst.
If the messages close in a way you do not want, change RULES and run again; see Keep your voice, rules and facts.
Put the approved ones back
Put the returned text of the rows you approve into your sequencer, one message per recipient. Use it as it came back: do not polish it with another model, which undoes the evaluation that kept your facts exact. To change a row, add a fact or a rule and run that row again, or edit it by hand.
Your agent can do the putting back in one sentence: "Send these to my lemlist campaign." Send to your sequencer is the recipe, for lemlist, Instantly, HeyReach, Reply.io, Smartlead, Woodpecker, La Growth Machine, Outreach, Salesloft, HubSpot and Apollo. The agent adds each lead to a paused campaign with its message as a variable, and shows you what it will add first. Without an agent, copy the text over by hand. The script above writes to none of your tools, and nothing should until a person has read the rows.
The same row returns the same message. Do not run it again unchanged. Add what you know, then run it again.
Budget
- The cap. Calls made with an API key or a connected agent count toward 1,000 optimizations a month per workspace, counted only when a result comes back. A 300-row campaign uses 300 of them. Calls from the console do not count.
- Time. 1 to 2 minutes a message is typical; one can take up to 300 seconds. A batch runs several items at a time, behind single calls: read its
eta, which is an estimate.
Without code
- Up to ten recipients: ask your agent. More than that belongs on the script above: a chat agent that loops over a long list is slow and hits the workspace's limits. Paste
Load and follow https://docs.amdahl.ai/skills/amdahl-optimizer/SKILL.mdinto Claude, ChatGPT, Codex or Claude Code with Amdahl connected. It finds the people you are about to write to in the tools it can reach, including a spreadsheet, gathers what it knows about each one, and shows each message with every try it scored. - One recipient: use the Outbound optimization tool on the console's Developers page.
Next: Optimize before you send puts the same call in front of every message your code sends.