Skip to content
Amazon Ergo on Bedrock: Build a Self-Testing Code Agent — ContentBuffer guide

Amazon Ergo on Bedrock: Build a Self-Testing Code Agent

K
Kodetra Technologies··12 min read Intermediate

Summary

Call Amazon's open-weights Ergo 1.0 on Bedrock and wrap it in a loop that runs its own tests.

On December 1, at re:Invent, Amazon released Ergo: a 1.1 trillion parameter mixture-of-experts model with open weights, a 1M-token context window, and Bedrock pricing of $1 per million input tokens and $3 per million output. It went straight to the top of Hugging Face's trending list, and most of the conversation since has been about one question: is a model that cheap good enough to hand real coding work?

Amazon's own model card gives a candid answer. Under limitations it says first-attempt accuracy trails the strongest closed models, and recommends "letting the agent test and verify its own changes" for long-running work. That sentence is the design brief for this guide.

You'll call Ergo 1.0 through Bedrock's OpenAI-compatible endpoint, then build a small coding agent in about 150 lines of Python. The agent can read files, write files and run pytest, and the harness refuses to accept "done" until the tests are green. You'll also meter every run in dollars and test the whole loop offline before spending a token.

What Ergo is, in numbers

Everything below comes from the Hugging Face model card and the Bedrock model card. The benchmark figures are Amazon's own runs.

PropertyValue
ArchitectureMoE transformer, 256 routed experts per layer (8 active) plus 1 shared
Parameters1.1T total, 55B active per token
Context / max output1M tokens / 128K tokens
ModalitiesText in, text out. No images in this release
ReasoningAlways on. It cannot be disabled
Bedrock price (global profile)$1.00 input, $0.03 cache read, $3.00 output per 1M tokens
Coding benchmarks74.2% DeepSWE, 31.5 FrontierSWE v2, 46.2% Terminal-Bench 4.0
WeightsAmazon-FMR/Ergo (MXFP4, 626 GB), Ergo-mxfp8 (1.17 TB), Ergo-bf16 (2.22 TB)
LicenseAmazon Ergo Open-Weights License (commercial use allowed, with an acceptable use policy)

One thing to keep in perspective: on the same card, Kimi K3.1 Pro beats Ergo on DeepSWE (77.9) and by a wide margin on Terminal-Bench 4.0 (63.3). Ergo's pitch is price and speed (over 400 output tokens per second on Bedrock) with open weights from a US vendor. It is a strong model that still gets things wrong on the first try, which is why the verify loop matters.

Prerequisites

  • An AWS account with Amazon Bedrock access in a supported Region (the examples use us-west-2)
  • A Bedrock API key. In the Bedrock console, open API keys and create a long-term key, or generate a short-term one with aws-bedrock-token-generator
  • Python 3.10+ with pip install -U openai pytest
  • Basic familiarity with OpenAI-style tool calling
export AWS_BEARER_TOKEN_BEDROCK="your-bedrock-api-key"
export AWS_REGION="us-west-2"

Step 1: Make a first call

Bedrock exposes Ergo through four APIs: Responses, Chat Completions, Converse and InvokeModel. The first two live under an OpenAI-compatible base URL, so the stock openai SDK works. This is the Chat Completions call from the AWS model card, trimmed:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1",
    api_key=os.environ["AWS_BEARER_TOKEN_BEDROCK"],
)

resp = client.chat.completions.create(
    model="global.amazon.ergo-1.0",      # or us.amazon.ergo-1.0
    messages=[
        {"role": "system", "content": "You are a helpful coding assistant."},
        {"role": "user", "content": "Write a Python function that reverses a string."},
    ],
    reasoning_effort="medium",           # low | medium | high | xhigh | max
    max_completion_tokens=8192,          # reasoning spends part of this
)
print(resp.choices[0].message.content)
print(resp.usage)

Three details in that snippet trip people up on day one:

  • The model ID is an inference profile. The base ID amazon.ergo-1.0 can't be invoked directly. Use global.amazon.ergo-1.0 or us.amazon.ergo-1.0, or you get a 400 saying in-region invocation isn't supported.
  • Reasoning can't be turned off. reasoning_effort="none" returns HTTP 400. The lowest setting is low.
  • Keep the output cap at 8,192 or more. Reasoning tokens come out of max_completion_tokens. Set it too low and you get an empty answer with finish_reason: "length".

If you'd rather stay on boto3, the same model works through client.converse(modelId='global.amazon.ergo-1.0', ...). The agent below uses Chat Completions because its tool-calling format is the one most frameworks already speak.

Step 2: Give the agent a sandboxed repo

Everything from here to Step 4 goes in one file, ergo_agent.py. It starts with the imports and endpoint settings:

"""Self-testing coding agent for Amazon Ergo 1.0 on Bedrock (Chat Completions API)."""
import json
import os
import subprocess
import sys
from pathlib import Path

from openai import OpenAI

REGION = os.environ.get("AWS_REGION", "us-west-2")
MODEL = os.environ.get("ERGO_MODEL", "global.amazon.ergo-1.0")
BASE_URL = os.environ.get(
    "ERGO_BASE_URL", f"https://bedrock-runtime.{REGION}.amazonaws.com/openai/v1"
)

The agent gets four tools: list files, read a file, write a file, run the tests. All of them go through one Repo class that enforces two rules the model can't talk its way around. Paths must stay inside the repo, and test files are read-only. The second rule matters more than it looks. The cheapest way for any coding model to make a failing test pass is to edit the test.

class Repo:
    def __init__(self, root):
        self.root = Path(root).resolve()

    def _safe(self, rel):
        p = (self.root / rel).resolve()
        if p != self.root and self.root not in p.parents:
            raise ValueError(f"path escapes the repository: {rel}")
        return p

    def list_files(self):
        return "\n".join(sorted(
            str(p.relative_to(self.root)) for p in self.root.rglob("*.py")
            if "__pycache__" not in p.parts))

    def read_file(self, path):
        return self._safe(path).read_text()

    def write_file(self, path, content):
        p = self._safe(path)
        if p.name.startswith("test_"):
            raise ValueError("test files are read-only")
        p.write_text(content)
        return f"wrote {len(content)} chars to {path}"

    def run_tests(self):
        r = subprocess.run(
            [sys.executable, "-m", "pytest", "-q", "-x", "--no-header", "-p", "no:cacheprovider"],
            cwd=self.root, capture_output=True, text=True, timeout=120)
        return f"exit_code={r.returncode}\n{(r.stdout + r.stderr)[-3000:]}"

Note what run_tests returns: the exit code on the first line, then the tail of pytest's output. The harness parses that first line itself in Step 4, so "did the tests pass" is decided by a process exit code and never by the model's summary.

The tool schemas are plain OpenAI function definitions:

TOOLS = [
    {"type": "function", "function": {
        "name": "list_files",
        "description": "List the files in the repository.",
        "parameters": {"type": "object", "properties": {}, "required": []}}},
    {"type": "function", "function": {
        "name": "read_file",
        "description": "Read a UTF-8 text file from the repository.",
        "parameters": {"type": "object",
                       "properties": {"path": {"type": "string"}},
                       "required": ["path"]}}},
    {"type": "function", "function": {
        "name": "write_file",
        "description": "Overwrite a file with new content. Test files are read-only.",
        "parameters": {"type": "object",
                       "properties": {"path": {"type": "string"},
                                      "content": {"type": "string"}},
                       "required": ["path", "content"]}}},
    {"type": "function", "function": {
        "name": "run_tests",
        "description": "Run pytest in the repository and return the output.",
        "parameters": {"type": "object", "properties": {}, "required": []}}},
]

Step 3: Meter every run in dollars

A 1M-token window at $1 per million sounds like nothing until an agent re-sends a growing transcript twelve times. Track cost per run from the usage block on each response. Bedrock supports implicit prompt caching for Ergo, and cache reads cost $0.03 per million on the global profile, so the meter separates cached input from fresh input when the response reports it.

# USD per 1M tokens, Standard tier (Bedrock model card, Dec 2026)
PRICES = {
    "global.amazon.ergo-1.0": {"in": 1.00, "cached": 0.03, "out": 3.00},
    "us.amazon.ergo-1.0": {"in": 1.10, "cached": 0.033, "out": 3.30},
}

class Meter:
    def __init__(self, model):
        self.p = PRICES.get(model, PRICES["global.amazon.ergo-1.0"])
        self.inp = self.cached = self.out = 0

    def add(self, usage):
        if usage is None:
            return
        details = getattr(usage, "prompt_tokens_details", None)
        cached = (getattr(details, "cached_tokens", 0) or 0) if details else 0
        self.inp += usage.prompt_tokens - cached
        self.cached += cached
        self.out += usage.completion_tokens

    @property
    def usd(self):
        return (self.inp * self.p["in"] + self.cached * self.p["cached"]
                + self.out * self.p["out"]) / 1_000_000

The US profile costs 10% more than global ($1.10 / $3.30). Pick it only if you need inference to stay in US Regions.

Step 4: The loop that won't take "done" for an answer

This is the core. Each turn sends the transcript plus tools, executes whatever tool calls come back, and appends the results. Two pieces of harness state do the verifying:

  • last_test_exit holds the exit code of the most recent pytest run. Any write_file resets it to None, because an edit makes the previous result stale.
  • When the model replies without tool calls (its way of saying it's finished), the harness checks that value. Anything other than 0 gets a pushback message and the loop continues.
MAX_TURNS = 12
MAX_OUTPUT_TOKENS = 8192   # Ergo always reasons; lower values can return empty answers
BUDGET_USD = 0.50

SYSTEM = """You are a coding agent working in a small Python repository.
Rules:
1. Run the tests before you change anything.
2. Read a file before you edit it. Write whole files, not diffs.
3. After every edit, run the tests again.
4. Never edit test files.
5. Stop only when the tests pass, then summarize the change in two sentences."""

def run_agent(task, repo_dir, effort="medium"):
    client = OpenAI(base_url=BASE_URL, api_key=os.environ["AWS_BEARER_TOKEN_BEDROCK"])
    repo, meter = Repo(repo_dir), Meter(MODEL)
    messages = [{"role": "system", "content": SYSTEM},
                {"role": "user", "content": task}]
    last_test_exit = None

    for turn in range(1, MAX_TURNS + 1):
        resp = client.chat.completions.create(
            model=MODEL, messages=messages, tools=TOOLS,
            reasoning_effort=effort, max_completion_tokens=MAX_OUTPUT_TOKENS)
        meter.add(resp.usage)
        choice = resp.choices[0]
        msg = choice.message

        if choice.finish_reason == "length":
            raise RuntimeError("hit max_completion_tokens mid-turn; raise MAX_OUTPUT_TOKENS")
        if meter.usd > BUDGET_USD:
            raise RuntimeError(f"budget exceeded: ${meter.usd:.4f}")

        if not msg.tool_calls:
            if last_test_exit != 0:
                # The model says it is done, but the last test run did not pass.
                messages.append({"role": "assistant", "content": msg.content or ""})
                messages.append({"role": "user", "content":
                                 "The tests have not passed yet. Run them and keep going."})
                print(f"[turn {turn}] claimed done without green tests; pushed back")
                continue
            print(f"[turn {turn}] done")
            return {"answer": msg.content, "turns": turn, "cost_usd": round(meter.usd, 4),
                    "tokens": {"input": meter.inp, "cached": meter.cached, "output": meter.out}}

        messages.append(msg.model_dump(exclude_none=True))
        for call in msg.tool_calls:
            name = call.function.name
            try:
                args = json.loads(call.function.arguments or "{}")
                result = getattr(repo, name)(**args)
            except Exception as e:  # report the failure to the model instead of crashing
                result = f"ERROR: {type(e).__name__}: {e}"
            if name == "run_tests" and result.startswith("exit_code="):
                last_test_exit = int(result.split("\n", 1)[0].split("=")[1])
            if name == "write_file":
                last_test_exit = None   # any edit invalidates the last test result
            print(f"[turn {turn}] {name}({', '.join(args) if isinstance(args, dict) else ''})"
                  f" -> {result.splitlines()[0][:70]}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})

    raise RuntimeError(f"no passing result after {MAX_TURNS} turns (${meter.usd:.4f} spent)")


if __name__ == "__main__":
    out = run_agent("The test suite in this repo is failing. Find the bug and fix it.",
                    sys.argv[1] if len(sys.argv) > 1 else "demo_repo")
    print(json.dumps(out, indent=2))

Tool errors are returned to the model as text instead of raised. A model that tries to write to a test file sees ERROR: ValueError: test files are read-only and can change course. A turn cap and a dollar budget bound the worst case.

Step 5: A worked example

Here's a small repo with a real bug. merge_intervals is supposed to merge overlapping or touching ranges, and it has two defects: a strict < where it needs <=, and it overwrites the end of the merged range instead of taking the max.

# demo_repo/intervals.py
def merge_intervals(intervals):
    """Merge overlapping or touching [start, end] intervals."""
    if not intervals:
        return []
    ordered = sorted(intervals)
    merged = [list(ordered[0])]
    for start, end in ordered[1:]:
        last = merged[-1]
        if start < last[1]:
            last[1] = end
        else:
            merged.append([start, end])
    return merged
# demo_repo/test_intervals.py
from intervals import merge_intervals


def test_overlap():
    assert merge_intervals([[1, 4], [2, 6]]) == [[1, 6]]


def test_touching():
    assert merge_intervals([[1, 3], [3, 5]]) == [[1, 5]]


def test_contained():
    assert merge_intervals([[1, 10], [2, 3]]) == [[1, 10]]


def test_unsorted():
    assert merge_intervals([[8, 9], [1, 2]]) == [[1, 2], [8, 9]]

Running pytest by hand confirms the starting point:

FAILED test_intervals.py::test_touching - assert [[1, 3], [3, 5]] == [[1, 5]]
FAILED test_intervals.py::test_contained - assert [[1, 3]] == [[1, 10]]
2 failed, 2 passed in 0.02s

Now point the agent at it:

python ergo_agent.py demo_repo

Step 6: Test the harness before you trust it

Before pointing this at Bedrock, check that the guardrails hold. The harness reads ERGO_BASE_URL, so you can aim it at a tiny local server that speaks the Chat Completions format and replays a scripted list of tool calls. No model is involved, which is the point: you're testing your code, and the script can misbehave on purpose.

I ran the harness against two scripts. The first is a well-behaved agent: run tests, read the file, write the fix, run tests, summarize.

[turn 1] run_tests() -> exit_code=1
[turn 2] read_file(path) -> def merge_intervals(intervals):
[turn 3] write_file(path, content) -> wrote 402 chars to intervals.py
[turn 4] run_tests() -> exit_code=0
[turn 5] done

The second script cheats. It tries to overwrite the test file, tries to read outside the repo, then announces success without a passing run:

[turn 1] run_tests() -> exit_code=1
[turn 2] write_file(path, content) -> ERROR: ValueError: test files are read-only
[turn 3] read_file(path) -> ERROR: ValueError: path escapes the repository: ../../etc/passwd
[turn 4] claimed done without green tests; pushed back
[turn 5] read_file(path) -> def merge_intervals(intervals):
[turn 6] write_file(path, content) -> wrote 402 chars to intervals.py
[turn 7] run_tests() -> exit_code=0
[turn 8] done

All three guardrails fired, and the run still ended on a real exit_code=0. Those transcripts are from the scripted stub, so they show what the harness does, not how Ergo behaves. Against the live model you'll see the same line format with Ergo choosing the calls, followed by the result dictionary:

{
  "answer": "<the model's two-sentence summary>",
  "turns": 5,
  "cost_usd": ...,
  "tokens": {"input": ..., "cached": ..., "output": ...}
}

For a sense of scale: a five-turn run that totals 20,000 fresh input tokens and 6,000 output tokens costs 20,000 × $1/1M + 6,000 × $3/1M = $0.038 on the global profile. Because Ergo always reasons, expect output tokens to be a larger share of the bill than you're used to on small tasks.

Pitfalls and gotchas

  • Quota is reserved up front. AWS notes that each request reserves its full output limit against your quota. Setting max_completion_tokens to 128K "just in case" will throttle parallel agents with 429s. Size it to the task.
  • No cross-check on tokens. Bedrock's count-tokens feature isn't supported for Ergo, so you can't pre-count a prompt. Budget from the usage you get back, as the meter does.
  • Text only. Ergo can't read screenshots or diagrams. If your agent workflow passes images of a UI, they need to become text first.
  • Server-side web search is murky. The Bedrock feature table lists web search as supported, while the same docs tell Codex users to disable it because built-in server-side tools aren't supported on the OpenAI-compatible path. Treat it as unavailable there and supply your own search tool.
  • Knowledge cutoff differs by source. The Hugging Face card says June 2026 and the Bedrock card says May 2026. Either way, don't rely on it for library versions released this autumn.
  • Cache writes aren't free. Explicit cache writes cost $1.25 per million (30-minute TTL) against $0.03 for reads. Caching pays off on long transcripts that get re-sent many times, which describes agents well, and poorly describes one-shot calls.
  • Self-hosting is a cluster project. The smallest checkpoint (MXFP4) is a 626 GB download. vLLM and SGLang both have day-one recipes, and Transformers users need the 2.22 TB BF16 repo. For most teams Bedrock is the practical way to try it.
  • Read the license before you resell it. The weights are free to run, fine-tune and ship in commercial products under an acceptable use policy, but it's a custom license, so have someone read the full text if you plan to offer Ergo as a hosted service.
  • pytest in a subprocess is not a sandbox. The path jail stops the file tools from leaving the repo. It doesn't stop code the model wrote from doing anything your user account can do once the tests import it. Run the agent in a container or a throwaway VM for anything beyond a demo.

Quick reference

WhatValue
Model IDsglobal.amazon.ergo-1.0, us.amazon.ergo-1.0
Base URLhttps://bedrock-runtime.<region>.amazonaws.com/openai/v1
AuthAWS_BEARER_TOKEN_BEDROCK (Bedrock API key)
APIsResponses, Chat Completions, Converse, InvokeModel
Reasoning effortlow, medium, high, xhigh, max (none returns 400)
Minimum sensible output cap8,192 tokens
Global price per 1M$1.00 in, $0.03 cache read, $1.25 cache write, $3.00 out
US price per 1M$1.10 in, $0.033 cache read, $1.375 cache write, $3.30 out
IAM actionsbedrock:InvokeModel, bedrock:InvokeModelWithResponseStream
Empty answer, finish_reason "length"Raise max_completion_tokens
400 in-region not supportedUse the global. or us. profile ID

Next steps

  • Sweep reasoning effort. Run the same failing repo at low, medium and high and compare turns and cost from the result dictionary. The cheapest setting that still goes green is your default.
  • Add a diff tool. Whole-file writes are simple and fine for small files. For larger ones, add a search-and-replace tool so output tokens don't scale with file size.
  • Use it from a coding CLI. AWS documents configs for OpenCode and Codex CLI against the same endpoint, and a LiteLLM proxy setup for Claude Code.
  • Compare against your current model. Keep the harness and swap ERGO_MODEL and ERGO_BASE_URL. Same repo, same guardrails, and the meter tells you what each green run cost.

Sources

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,617 newsletter subscribers.

Also get