Optimize before you send
Put Amdahl between the code that knows who the recipient is and the queue that sends the message, so each message is optimized before it ships, with no data connected: what context to pass, the fallback when it cannot answer, what to store, and what never to do with the result.
Level: production. Call: messages.optimize. You need: a Customer agent key kept server-side (amdahl keys create --preset agent, see CLI; rotate it before it expires), and code that queues outbound messages. No connected data.
If your outbound comes out of code (an AI SDR, a job that reads a CRM and calls a model, an integration that queues sequencer steps), Amdahl belongs in one place: after your code knows who the recipient is and what it knows about them, and before the message is queued. Amdahl writes the message from that context. A draft is optional. A draft sent in message is the starting point, and what it states is taken as the sender's own word. So pass it what your code knows, not what your code wrote.
Where the call goes
Gather the context
Who the recipient is, a reason to write now, what you offer, and the ask, as facts and rules.
your code
Write
One call per recipient, in a background job. Usually 1 to 2 minutes.
messages.optimize
Queue
The returned message, or your fallback whenever the call could not answer.
your sequencer
Three rules make it safe:
- Never block a send on it. Run it in a background job or a step of your workflow engine, with a timeout of 310 seconds. A call can take up to 300 before it gives up.
- Always have a fallback. When
okisfalse, or the call times out, there is no message. Queue a fallback your own code wrote, or hold the send, and log why. Keep the fallback on your side. Sent inmessage, it would become the starting point of the message. - Use
messageas returned. It is the version that kept your rules, names and numbers exact and passed Amdahl's re-evaluation. Do not run it through another model to polish it, and do not merge it with your own text. That throws away the work that kept your facts exact. If it needs to change, send the change as a rule or a fact and run it again (see Steering it).
The call, with its fallback
TypeScript (Node 18 or later):
const API = 'https://app.amdahl.ai/api/platform/v1/messages/optimize'
/** What to queue, and why. */
export interface Optimized {
text: string | null
outcome: 'rewritten' | 'fallback'
runId?: string
reason?: string
/** What the message left out because the facts could not back it. */
omitted?: Array<{ what: string; why: string }>
}
/** Write one message from what you know. Never throws: on any failure it returns the fallback. */
export async function optimizeBeforeSend(
facts: string[],
rules: string[],
fallback: string | null,
channel?: 'email' | 'linkedin',
): Promise<Optimized> {
try {
const res = await fetch(API, {
method: 'POST',
headers: {
'X-API-Key': process.env.AMDAHL_KEY ?? '',
'Content-Type': 'application/json',
},
body: JSON.stringify({ context: { facts, rules }, ...(channel ? { channel } : {}) }),
signal: AbortSignal.timeout(310_000),
})
const body = await res.json().catch(() => ({}))
const data = body.data ?? body
if (!res.ok || !data.ok) {
return { text: fallback, outcome: 'fallback', reason: data.reason ?? data.error?.code ?? `http_${res.status}` }
}
return { text: data.message, outcome: 'rewritten', runId: data.run_id, omitted: data.omitted }
} catch (err) {
return { text: fallback, outcome: 'fallback', reason: err instanceof Error ? err.name : 'unknown' }
}
}Python (3.9 or later, standard library only):
import json, os, urllib.error, urllib.request
API = "https://app.amdahl.ai/api/platform/v1/messages/optimize"
def optimize_before_send(facts, rules, fallback=None, channel=None):
"""Write one message from what you know. Never raises: on any failure it returns the fallback."""
body = {"context": {"facts": facts, "rules": rules}, **({"channel": channel} if channel else {})}
req = urllib.request.Request(
API, data=json.dumps(body).encode("utf-8"), method="POST",
headers={"X-API-Key": os.environ["AMDAHL_KEY"], "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=310) as res:
data = json.load(res)["data"]
except urllib.error.HTTPError as err:
return {"text": fallback, "outcome": "fallback", "reason": f"http_{err.code}"}
except (OSError, ValueError, KeyError) as err: # timeout, network, or an unreadable body
return {"text": fallback, "outcome": "fallback", "reason": type(err).__name__}
if not data.get("ok"):
return {"text": fallback, "outcome": "fallback", "reason": data.get("reason")}
return {"text": data["message"], "outcome": "rewritten", "run_id": data.get("run_id"),
"omitted": data.get("omitted")}Call it with what your code already knows about the recipient:
result = optimize_before_send(
facts=[
"The recipient is Sam Ortiz, Head of RevOps at Brightpath.",
"Brightpath posted three SDR roles last week.",
"We sell Rampwise, which gives every new sales rep a guided first 30 days.",
],
rules=["Ask for a 20-minute call next week."],
channel="email",
)Both return the text to queue and an outcome to log. Neither retries: every attempt is a fresh run that counts toward the monthly cap. If a recipient is worth a second try, enqueue it once more on your side and remember that you did.
Neither sends on_missing_input, so both run best_effort, the default: a success always carries a message. What your facts could not back is left out of it, never made up, and listed in omitted as {what, why}. Log it: a row there names a fact your code could add next time. on_missing_input: "ask" returns questions instead of a message, which a send queue has nobody to answer.
What to store
For each message, keep enough to answer "what went out, and why" later:
| Store | From | Why |
|---|---|---|
| The facts and rules you sent, and the text you queued | your code, message | What the message was written from, and what went out. |
outcome | the response | How often a message is written or falls back. A rising fallback rate is your signal to look. |
context | the response | How many facts and rules arrived. A message written from one fact is a thin message. |
run_id | the response | Quote it to Amdahl support about any one message. |
summary | the response | One line a person can read in a review queue. |
omitted | the response | What the message left out because your facts could not back it, each {what, why}. A repeated what names a fact your code should gather. |
notes[].code | the response | Facts about the run, such as style_pass_only. Branch on code, never on the wording of says. Show a person in the review queue only the notes whose audience is sender, and keep the developer ones in your logs. A draft_improved_no_context note means your code sent a message with no facts, no rules and no recipient, so the draft was improved instead. |
A person in the loop, then without one
Start with a person approving each message: show the facts and message side by side in whatever review queue you already have, and queue the version they approve. A review screen may also send "include_tries": true to show every version the run scored on the way (see Reading tries); leave it out of the send path, which only needs message. Once a campaign's messages are going out unedited, let that campaign queue message on its own and keep reviewing a sample.
Three things to know before you take the person out:
- The message is only as good as the facts. Every specific line comes from a fact your code sent, or from evidence Amdahl read. If your code sends one fact per recipient, every message will be generic. See Context.
- Without your data, it evaluates how the message reads. With no data connected, Amdahl evaluates how a message reads and how clearly it asks. It does not evaluate claims against your customers' own conversations, so a wrong fact is still wrong in the message. Every response says so in a
style_pass_onlynote. If your facts make claims about customers or results, connect your conversations and read Evaluate claims against your customers first. - Say the ask in a rule. Without one, Amdahl may close on a one-line question about whether the problem is real for the reader rather than a meeting request.
Steering it
Send the sender's rules and voice with the facts:
{
"channel": "email",
"context": {
"facts": ["The recipient is Morgan Lee, new Head of RevOps at Corvid.", "Morgan started at Corvid in September."],
"rules": ["Never mention pricing.", "End by asking for a 15-minute call."],
"voice_examples": ["Hey Morgan, congrats on the new role. Most RevOps leads I talk to spend their first month untangling the CRM. Free for 15 minutes Tuesday?"]
}
}rules bind the message: one that breaks a rule is never returned. voice_examples are matched, not copied. Load both once per sender or campaign rather than writing them per send, and build facts per recipient. The details are in Keep your voice, rules and facts.
Volume and the cap
- 1,000 a month per workspace for calls made with an API key or a connected agent, counted only when a result comes back. Past it the call returns
429withquota_exceededuntil the month rolls, and your fallback takes over. Ask Amdahl to raise it before a launch that will need more. - One recipient per call. For a backlog, send a batch; see Optimize a campaign.
- Watch the cap.
GET /setup/statusreturnsoptimize.quota(limit,used,remaining,resets_at) andoptimize.allowed. Call it from a health check or a deploy step, not on every send, and alert beforeremainingreaches zero. See Check your setup. - 30 optimize calls a minute per key, inside 300 requests a minute per client IP. A send pipeline that runs one optimize at a time rarely gets near it, since each takes 1 to 2 minutes; a pipeline that runs many in parallel can. See Rate limits.
If your writer is an agent
When the messages come from an agent over MCP rather than from your code, the same rules apply through the optimize_message tool. Tell the agent, in its instructions, to gather what it knows about the recipient, send it as context, and queue the tool's message exactly as returned. An agent that writes its own draft and sends that gets it ignored. An agent that paraphrases the result undoes the evaluation that produced it. If the result needs to change, the agent re-runs the tool with the change as a rule or a fact in context.
Every field the response can carry is on Optimize a message.