Write a campaign
An outbound campaign written by Amdahl from a spreadsheet of recipients: one batch request for the whole list (up to 500), or a resumable one-at-a-time loop for a short list.
Level: a script. Call: messages.optimize_batch for the whole list, or messages.optimize once per recipient for a short list. You need: a key that can write messages in AMDAHL_KEY (Search and Outbound, or Customer agent), 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 scripts below turn each row of a spreadsheet into that context, and write 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. The email, name, company and domain columns become the call's recipient, and the others become facts. A recipients.csv with two rows:
id,channel,email,name,title,company,domain,why_now,notes
lead-001,email,[email protected],Sam Ortiz,Head of RevOps,Brightpath,brightpath.example,"Brightpath posted three SDR roles last week.","Moved from Salesforce to HubSpot in August."
lead-002,linkedin,,Priya Shah,VP Sales,Northwind Labs,northwind.example,"Northwind raised a Series B in July.",""email,name,companyanddomaingo inrecipient. With them, Amdahl finds the person in your workspace's CRM and calls and adds what it finds. A fact that names the recipient does not do this. Fill every one you have.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. It names one sender company: the company whose domain sends these emails. Context says what counts as enough.
A row that follows an earlier email, such as step 2 of a sequence, also needs that email. See Follow-up steps.
A big campaign: send it as a batch
For a list of recipients, a one-at-a-time loop 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.
Leave out any recipient Amdahl already wrote to in a test. Amdahl adds the messages it wrote earlier to a later call for the same recipient, and a batch item cannot take content_spec to stop that, so that row would come back as a follow-up to the test message.
Each item carries what you know about its recipient in the facts in its context, and the person in recipient, exactly as the loop does. An item takes every field a single call takes, the recipient fields and a follow-up's thread, prior_touches and stage included. This script takes the same recipients.csv and writes the same messages.csv. It reuses facts_for and body_for from optimize_campaign.py in One at a time, for a short list, so save both in one folder:
#!/usr/bin/env python3
"""Write one message per recipient in a CSV as Amdahl Outbound 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/outbound"
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",
"incomplete", "omitted", "context_hint", "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, again=False):
"""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.
# A second try of failed rows needs its own key, or it returns the first batch.
seed = json.dumps(items, sort_keys=True) + ("again" if again else "")
key = hashlib.sha256(seed.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
def run(rows, again=False):
"""Queue the rows as one batch and return each row's result by id."""
batch_id = submit(rows, again)
print(f"batch {batch_id} queued")
return {item["item_id"]: item["result"] or {} for item in collect(batch_id)}
with open(SRC, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
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):
chunk = rows[start:start + BATCH_SIZE]
results = run(chunk)
# Nothing was written or charged for these, and the draft was not the cause.
retry = [row for row in chunk if results[row["id"]].get("retryable")]
if retry:
print(f"{len(retry)} rows can be sent again; sending them once more in 2 min")
time.sleep(120)
results.update(run(retry, again=True))
for row in chunk:
r = results[row["id"]]
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", ""),
"incomplete": " ".join(r.get("failed_rules") or ["yes"]) if r.get("incomplete") else "",
"omitted": " | ".join(f"{o['what']}: {o['why']}" for o in r.get("omitted") or []),
"context_hint": " | ".join(r.get("context_hint") 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. A failed row whose result has
retryable: true(read_timeout,optimizer_timeout,optimizer_error) is sent once more, in a new batch, two minutes later. If it fails again,messages.csvkeeps itsreason. A row with any otherreasonfails the same way if you send it unchanged: fix what thereasonnames. See Submit failed items again. - 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.
One at a time, for a short list
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 Amdahl Outbound.
Usage: AMDAHL_KEY=amdhl_... python3 optimize_campaign.py recipients.csv messages.csv
Input columns: id, email, name, title, company, domain, why_now, notes, and optionally
channel, earlier_email, earlier_sent_at and stage (for a follow-up step).
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/outbound"
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.
# One sender company: the company whose domain sends these emails, and no other.
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",
"incomplete", "omitted", "context_hint", "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 recipient_for(row):
"""Who the message is for. Amdahl finds this person in the workspace's CRM and calls."""
fields = {k: (row.get(k) or "").strip() for k in ("email", "name", "company", "domain")}
return {k: v for k, v in fields.items() if v}
def earlier_for(row):
"""For a follow-up step: the earlier email as thread and prior_touches, and the stage."""
body, sent_at = (row.get("earlier_email") or "").strip(), (row.get("earlier_sent_at") or "").strip()
if not (body and sent_at):
return {}
return {
"thread": [{"direction": "sent", "sent_at": sent_at, "body": body}],
"prior_touches": [{"on": sent_at[:10], "channel": (row.get("channel") or "").strip() or "email",
"summary": body[:500]}],
"stage": (row.get("stage") or "").strip() or "cold", # cold until they reply
}
def body_for(row):
context = {"facts": facts_for(row), "rules": RULES, "voice_examples": VOICE_EXAMPLES,
**earlier_for(row)}
body = {"context": {k: v for k, v in context.items() if v}}
recipient = recipient_for(row)
if recipient:
body["recipient"] = recipient
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 Outbound 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"):
# Outbound 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", ""),
"incomplete": " ".join(r.get("failed_rules") or ["yes"]) if r.get("incomplete") else "",
"omitted": " | ".join(f"{o['what']}: {o['why']}" for o in r.get("omitted") or []),
"context_hint": " | ".join(r.get("context_hint") 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 optimize (see CLI), which makes a Search and Outbound key. Use --preset agent (Customer agent) only when the same job also starts research. The console offers no Search and Outbound level: there, set Access to Customer agent. Before a long run, check that the key can write messages 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 10 rows take 10 to 20 minutes.
Use this loop for a first run where a person reads each result, up to 10 rows. For a longer list, use the batch above.
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 Outbound runs (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 Outbound 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 Outbound call, or your role is Viewer. GET /setup/status names which. |
| No answer in 310 seconds | Records it, moves on | It does not retry. A failed call does not count toward the monthly cap; a retry that returns a result counts as one 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 Outbound runs at once and start 12 a minute. That suits a short list you want to watch row by row. For a longer one, do not loop faster: send a batch.
Follow-up steps
A follow-up is written from the email it follows. When a campaign's second step goes out, each row needs the first email, or the message reads as a first touch. Add three columns to recipients.csv:
earlier_email: the body of the email this one follows, as it went out.earlier_sent_at: when it went out, as an ISO time such as2026-11-18T15:02:00Z.stage:coldwhile the recipient has not replied (the default),engagedafter a reply.
body_for sends them in context: thread (the earlier email), prior_touches (one touch, with the date and the email cut to 500 characters) and stage. Change the rule to say it is a follow-up, for example RULES = ["A short follow-up to the email in the thread.", "Ask for a 20-minute call next week."]. Keep the same sender company as the first step.
For more than one earlier email, or a reply from the recipient, build thread with every message, oldest first, each with direction (sent or received), sent_at and body. Where your workspace does not read thread yet, ignored_params names it, and prior_touches still carries the history. Every field is in Follow-ups and replies.
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. Apartly_measuredcode in thenotescolumn means a line had nothing to check against and was not measured.context_hint: each line names a field the call left out, such asrecipientor thethreadof a follow-up. Add that column torecipients.csv, delete those rows frommessages.csv, and run the script again.incomplete: a value here means the message breaks at least one rule, and the value lists itsfailed_rulescodes. Do not use that message. Read itsomittedrows, add the fact or change the rule they name, and run that row again. Treat a row whoseomittedquotes one of your rules (Your rule ...) the same way, even withincomplete: false.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 Outbound runs 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
- A list: ask your agent. It sends the whole list in one call with
outbound_message_batch(up to 500) and reads the results withget_message_batch. A chat agent that loops over a list one message at a time is slow and hits the workspace's limits. To find the recipients and write a first sample, paste the setup prompt into Claude, ChatGPT, Codex or Claude Code. 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 console's Outbound page.
Next: Run Outbound before you send puts the same call in front of every message your code sends.