A multi-agent pipeline rarely blows up because of one large call. It blows up in the loop: the planner sees the goal, the worker sees the goal plus the plan, the critic sees the goal plus the plan plus both drafts, and the final writer sees everything again. By the fourth hop you are paying to re-read context you already paid to generate.
Two levers fix this. The first is which model tier each hop points at. The second — the one most teams skip — is how much text moves between hops. Tier choice is a one-line change. Context discipline is an architecture decision, and in our experience it saves more.
Rule 1: Route by task difficulty, not by agent rank
The usual pattern is to give the "important" agent the pro model and everything else the fast one, by instinct. That instinct is often wrong: a planner producing five bullet steps is a narrow, well-specified job, while a critic scanning a whole transcript for omissions is genuinely harder.
Classify the task, then pick the tier. The router itself runs on the cheap tier, so the decision costs almost nothing:
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
)
ROUTER = (
'Classify the task. Reply JSON only: {"difficulty": "easy"} or {"difficulty": "hard"}. '
'Use "hard" for multi-step math, ambiguous specs, or code debugging. Otherwise "easy".'
)
def route(task: str) -> str:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": ROUTER},
{"role": "user", "content": task},
],
temperature=0,
max_tokens=50,
)
raw = resp.choices[0].message.content.strip().strip("`").removeprefix("json").strip()
try:
difficulty = json.loads(raw).get("difficulty", "easy")
except (json.JSONDecodeError, AttributeError):
difficulty = "easy" # never pay pro rates for a parse failure
return "deepseek-v4-pro" if difficulty == "hard" else "deepseek-v4-flash"
if __name__ == "__main__":
print(route("Extract invoice numbers from this PDF text"))
print(route("Find the off-by-one bug across these three functions"))
Log the routing decision alongside the run. After a few hundred tasks you will usually find the "hard" bucket is much smaller than you assumed — often the final synthesis and the reviewer, nothing else. That single observation is where most of the savings live.
Most multi-agent cost overruns are not pricing problems. They are context-plumbing problems.
Rule 2: Keep handoffs compact and structured
Pass a rolling digest, not the full transcript. Each worker should receive a truncated, labelled summary of what earlier steps concluded — never the raw message history. Cap that digest in characters, not vibes, and let the oldest detail fall off first.
The pipeline below does three things at once: flash for planning and execution, pro only for the review pass, and a hard token budget that raises instead of quietly draining your balance.
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
)
class TokenBudget:
def __init__(self, limit: int):
self.limit, self.used = limit, 0
def charge(self, usage) -> None:
self.used += getattr(usage, "total_tokens", 0) or 0
if self.used > self.limit:
raise RuntimeError(f"Token budget exceeded: {self.used}/{self.limit}")
def call(model: str, system: str, user: str, budget: TokenBudget, max_tokens: int = 500) -> str:
resp = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user},
],
temperature=0.2,
max_tokens=max_tokens,
)
budget.charge(resp.usage)
return resp.choices[0].message.content.strip()
def parse_json(text: str) -> dict:
cleaned = text.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip()
return json.loads(cleaned)
PLANNER = 'Break the goal into 3-5 concrete subtasks. Reply JSON only: {"steps": ["...", "..."]}'
WORKER = (
"Complete the subtask in under 120 words. You only see the digest of earlier steps "
"below; do not ask for more context."
)
REVIEWER = (
"Review this multi-agent run. Give exactly 3 bullet critiques and one closing line "
"starting with VERDICT:. Flag only real gaps, not stylistic preferences."
)
def run_workflow(goal: str, digest_budget: int = 1500, token_limit: int = 30000) -> dict:
budget = TokenBudget(token_limit)
steps = parse_json(
call("deepseek-v4-flash", PLANNER, goal, budget, max_tokens=300)
)["steps"]
digest = ""
for i, step in enumerate(steps, 1):
out = call(
"deepseek-v4-flash",
WORKER,
f"Subtask: {step}\n\nDigest:\n{digest}",
budget,
)
digest = (digest + f"\n[{i}] {step} -> {out}")[-digest_budget:]
review = call(
"deepseek-v4-pro", REVIEWER, f"Goal: {goal}\n\nDigest:\n{digest}", budget, max_tokens=400
)
return {"steps": steps, "digest": digest, "review": review, "tokens_used": budget.used}
if __name__ == "__main__":
result = run_workflow("Draft a 5-bullet launch checklist for a public API beta.")
print(result["review"])
print("tokens used:", result["tokens_used"])
Rule 3: Put a token ledger inside the loop
The TokenBudget class above is deliberately a token counter rather than a currency counter. Token counts are stable and returned by every response, while rates change. For actual rates, check aicreditsapi.com/pricing and convert at the edge of your own code if you need a hard currency cap.
A budget that raises an exception is more useful than one that logs a warning. Runaway agent loops are silent by nature — each individual call looks reasonable, and only the aggregate is absurd.
Set the cap per run, not per process, so one bad task cannot poison an entire evening's batch.
Always set max_tokens. The default ceiling is usually far above what a short subtask needs.
Log tokens per agent role. The hog is almost always the agent that receives unstructured history, not the one calling the expensive model.
Retry a failed step once on the cheap tier before escalating. Many "hard" failures are just under-specified prompts.
Cap the step count in the orchestrator too — a budget alone still lets a 40-step loop crawl to the limit.
Where the cheap tier actually breaks
deepseek-v4-flash handles extraction, formatting, classification, short summaries, and most tool-call argument generation well. It starts to wobble on long-horizon planning with many interacting constraints, debugging where several invariants must hold at once, and polished prose a customer will read. Those are exactly the places to spend on deepseek-v4-pro, which costs more than flash — so put it where one call produces the visible output.
| Role | Model | Why |
|---|---|---|
| Router / classifier | deepseek-v4-flash | Single-label output, low ambiguity |
| Planner (3-5 steps) | deepseek-v4-flash | Short output; structure matters more than depth |
| Worker / extractor | deepseek-v4-flash | Narrow, well-specified subtask |
| Reviewer / critic | deepseek-v4-pro | Must spot omissions across the whole digest |
| Final synthesis | deepseek-v4-pro | User-visible quality, one call per run |
| Bulk summarization | deepseek-v4-flash | Volume dominates; per-call quality matters less |
Timing and caching: the quiet multipliers
Off-peak requests cost less than peak ones, so move batched, non-urgent work — nightly evals, backfills, document re-indexing — into the off-peak window. Cache hits also cost less than fresh tokens, and multi-agent systems are unusually good candidates because the planner's instruction block is identical on every run.
That only works if the prefix actually matches. Byte-identical system prompts get cached; prompts with a timestamp or a random run ID at the top do not.
Put long, stable instructions first and variable data (the goal, retrieved docs) last.
Keep the system prompt byte-identical between runs — no injected dates, no shuffled examples.
Put few-shot examples before user content, never interleaved with it.
Reuse one client object across agents so connection setup is not repeated per call.
Access and wiring
Everything above runs against the OpenAI SDK with base_url="https://api.aicreditsapi.com/v1", so switching tiers is a string change and nothing else. AiCredits sells DeepSeek credits to developers outside China and accepts card or PayPal — no Chinese phone number or bank account needed, which is the usual blocker for international teams. The same account also covers the code-linting tools, useful if you want a second pair of eyes on the orchestrator before it starts spending.
FAQ
For many pipelines, yes — routing, extraction, short summaries and tool argument generation all hold up. Escalate to deepseek-v4-pro for the reviewer and the final user-facing synthesis. That typically leaves one or two pro calls per run, which is where the cost predictability comes from.
Three guards together: a per-run token budget that raises, a max_tokens value on every single call, and a maximum step count in the orchestrator. Add per-role token logging so you can see which hop is consuming the budget.
Not automatically. Most agent subtasks are narrow and well-specified, which is where cheap tiers are strongest. Quality drops on long-context reasoning, multi-constraint planning and polished prose — so keep the expensive tier for exactly those.
Not with AiCredits. You pay by card or PayPal, and the base URL stays https://api.aicreditsapi.com/v1 so the code samples in this post run unchanged.