POC script
Open the first script, copy it, paste it into a file and run it. Its header says what it needs. The others are supporting code.
Versions needed
| Tool | Version | Note | Get that exact version |
|---|---|---|---|
| boto3 | 1.44.17 or later | Tested with 1.44.17. An older release may reject the reasoning effort field. | boto3 1.44.17 on PyPI |
| AWS CLI | 2.37.0 or later | Only for quickstart.sh. Tested with 2.37.0. | macOS, Linux, Windows |
poc/quickstart.py 56 lines
#!/usr/bin/env python3
"""Amazon Ergo on Amazon Bedrock: one streamed request, with measured speed and cost.
Needs: boto3 1.44.17 or later. Tested with 1.44.17: pip install boto3==1.44.17
(that exact release: https://pypi.org/project/boto3/1.44.17/). An older boto3 may
reject the outputConfig field that sets the reasoning effort.
AWS credentials with bedrock:InvokeModelWithResponseStream on the Ergo inference
profile, and a Region where the global profile is callable.
The same call from the AWS CLI is in quickstart.sh (AWS CLI 2.37.0 or later).
Run: python3 quickstart.py
python3 quickstart.py "Write a Go function that merges two sorted slices." high
"""
import sys
import time
import boto3
TESTED_BOTO3 = "1.44.17" # https://pypi.org/project/boto3/1.44.17/
if tuple(int(part) for part in boto3.__version__.split(".")[:3]) < (1, 44, 17):
print(f"warning: boto3 {boto3.__version__} is older than the tested {TESTED_BOTO3}; "
f"if a call is rejected, run: pip install boto3=={TESTED_BOTO3}", file=sys.stderr)
MODEL_ID = "global.amazon.ergo-1.0" # the base ID amazon.ergo-1.0 cannot be called directly
PRICE_IN, PRICE_OUT = 1.00, 3.00 # USD per 1M tokens, Global cross-Region, read 2026-12-01
prompt = sys.argv[1] if len(sys.argv) > 1 else "Write a Python LRU cache class with O(1) get and put, and pytest tests."
effort = sys.argv[2] if len(sys.argv) > 2 else "medium" # low | medium | high | xhigh | max
client = boto3.client("bedrock-runtime", region_name="us-east-1")
started = time.time()
response = client.converse_stream(
modelId=MODEL_ID,
messages=[{"role": "user", "content": [{"text": prompt}]}],
inferenceConfig={"maxTokens": 16384}, # Ergo needs at least 8,192
outputConfig={"effort": effort}, # Ergo always reasons; this sets how hard
)
first_token = None
usage = {}
for event in response["stream"]:
text = event.get("contentBlockDelta", {}).get("delta", {}).get("text")
if text:
first_token = first_token or time.time()
print(text, end="", flush=True)
elif "metadata" in event:
usage = event["metadata"]["usage"]
total = time.time() - started
# Reasoning is billed as output tokens but is not streamed, so it shows up as the wait for the first token.
cost = (usage["inputTokens"] * PRICE_IN + usage["outputTokens"] * PRICE_OUT) / 1_000_000
print(f"\n\n--- {MODEL_ID}, effort {effort}")
print(f"first token {first_token - started:.1f} s")
print(f"total time {total:.1f} s")
print(f"tokens {usage['inputTokens']} in, {usage['outputTokens']} out (output includes reasoning)")
print(f"output speed {usage['outputTokens'] / total:.0f} tokens/s (all output tokens over total time)")
print(f"cost ${cost:.5f}")
poc/quickstart.sh 24 lines
#!/usr/bin/env bash
# Amazon Ergo on Amazon Bedrock from the AWS CLI: one request, then the answer and token usage.
#
# Needs: AWS CLI 2.37.0 or later (aws --version). Tested with 2.37.0.
# Installers for that exact version:
# macOS https://awscli.amazonaws.com/AWSCLIV2-2.37.0.pkg
# Linux https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.37.0.zip
# Windows https://awscli.amazonaws.com/AWSCLIV2-2.37.0.msi
# Credentials with bedrock:InvokeModel on the Ergo inference profile.
#
# Run: ./quickstart.sh
# ./quickstart.sh "Write a Go function that merges two sorted slices." high
set -euo pipefail
PROMPT="${1:-Write a Python function that checks whether a string is a palindrome. Code only.}"
EFFORT="${2:-low}" # low | medium | high | xhigh | max
aws bedrock-runtime converse \
--region us-east-1 \
--model-id global.amazon.ergo-1.0 \
--messages "$(jq -n --arg p "$PROMPT" '[{role: "user", content: [{text: $p}]}]')" \
--inference-config maxTokens=16384 \
--output-config effort="$EFFORT" \
--query '{answer: output.message.content[?text].text | [0], usage: usage, latencyMs: metrics.latencyMs}' \
--output json
poc/lambda/index.mjs 147 lines
// Amazon Ergo playground backend: one Bedrock ConverseStream call, streamed to the caller as
// newline-delimited JSON events:
// {"type":"reasoning","text":...} reasoning summary deltas, when the model emits them
// {"type":"text","text":...} answer deltas
// {"type":"done","stop_reason":...,"usage":{...},"metrics":{...}}
// {"type":"error","message":...}
// Lambda runs `handler`; local mode (poc/local.mjs) and poc/verify.sh import `chat`, so every path
// makes the same Bedrock call.
import { BedrockRuntimeClient, ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
export const MODEL_ID = process.env.MODEL_ID || "global.amazon.ergo-1.0";
export const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
export const MAX_PROMPT_CHARS = 20000;
// Ergo reasons inside the output limit and each request reserves the full limit against the account
// quota, so the limit is fixed here and never taken from the caller.
export const MAX_OUTPUT_TOKENS = 16384;
const SYSTEM = "You are a senior software engineer. Answer with working code first, then a short explanation.";
const client = new BedrockRuntimeClient({});
// Returns { prompt, effort } or { error } for a request body string.
export function parseRequest(raw) {
let body;
try {
body = JSON.parse(raw || "{}");
} catch {
return { error: "body must be JSON" };
}
const prompt = typeof body.prompt === "string" ? body.prompt.trim() : "";
const effort = body.effort ?? "medium";
if (!prompt) return { error: "prompt is required" };
if (prompt.length > MAX_PROMPT_CHARS) return { error: `prompt is longer than ${MAX_PROMPT_CHARS} characters` };
if (!EFFORTS.includes(effort)) return { error: `effort must be one of ${EFFORTS.join(", ")}` };
return { prompt, effort };
}
// Calls Ergo and passes each event object to emit. Resolves with the final "done" event.
// A failure before the first delta throws; a failure mid-stream throws after partial output.
export async function chat({ prompt, effort }, emit) {
const started = performance.now();
const response = await client.send(new ConverseStreamCommand({
modelId: MODEL_ID,
system: [{ text: SYSTEM }],
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: MAX_OUTPUT_TOKENS },
outputConfig: { effort },
}));
let firstToken, stopReason, usage = {}, latencyMs;
for await (const event of response.stream) {
const delta = event.contentBlockDelta?.delta;
if (delta) {
const reasoning = delta.reasoningContent?.text;
if (delta.text || reasoning) firstToken ??= performance.now();
if (reasoning) emit({ type: "reasoning", text: reasoning });
if (delta.text) emit({ type: "text", text: delta.text });
} else if (event.messageStop) {
stopReason = event.messageStop.stopReason;
} else if (event.metadata) {
usage = event.metadata.usage ?? {};
latencyMs = event.metadata.metrics?.latencyMs;
} else {
const failure = Object.entries(event).find(([name]) => name.endsWith("Exception"));
if (failure) throw Object.assign(new Error(failure[1]?.message || failure[0]), { name: failure[0] });
}
}
const ended = performance.now();
const outputTokens = usage.outputTokens ?? 0;
const done = {
type: "done",
model_id: MODEL_ID,
effort,
max_output_tokens: MAX_OUTPUT_TOKENS,
stop_reason: stopReason,
usage: {
input_tokens: usage.inputTokens ?? 0,
output_tokens: outputTokens,
cache_read_tokens: usage.cacheReadInputTokens ?? 0,
cache_write_tokens: usage.cacheWriteInputTokens ?? 0,
},
// Timed around the Bedrock call. Ergo bills its reasoning as output tokens but does not stream it,
// so the reasoning happens during the wait for the first token. tokens_per_second therefore
// divides all output tokens by the whole request time.
metrics: {
ttft_ms: firstToken === undefined ? null : Math.round(firstToken - started),
total_ms: Math.round(ended - started),
bedrock_latency_ms: latencyMs ?? null,
tokens_per_second: round1(outputTokens / ((ended - started) / 1000)),
},
};
emit(done);
return done;
}
const round1 = (n) => Math.round(n * 10) / 10;
// HTTP status and a caller-safe message for a Bedrock failure. Details stay in the function log.
export function describeError(err) {
const name = err?.name || "Error";
if (name === "ThrottlingException") return { status: 429, message: "Bedrock throttled the request (account quota). Retry in a moment." };
if (name === "ValidationException") return { status: 400, message: `Bedrock rejected the request: ${err.message}` };
if (name === "AccessDeniedException") return { status: 502, message: "The backend is not allowed to invoke the model." };
return { status: 502, message: `Model call failed (${name}).` };
}
const cors = {
"Access-Control-Allow-Origin": process.env.ALLOWED_ORIGIN || "",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
};
// API Gateway proxy integration in STREAM mode: HttpResponseStream.from writes the status and
// headers, then everything written to the stream reaches the browser as it is produced.
export const handler = globalThis.awslambda?.streamifyResponse?.(async (event, responseStream) => {
const open = (statusCode, contentType) => globalThis.awslambda.HttpResponseStream.from(responseStream, {
statusCode,
headers: { ...cors, "Content-Type": contentType, "Cache-Control": "no-store" },
});
const fail = (statusCode, message) => {
const out = open(statusCode, "application/json");
out.write(JSON.stringify({ message }));
out.end();
};
const raw = event.isBase64Encoded ? Buffer.from(event.body || "", "base64").toString("utf8") : event.body;
const request = parseRequest(raw);
if (request.error) return fail(400, request.error);
// The response status is committed with the first event, so a failure before any output
// (throttling, access denied) still returns a real HTTP error.
let out;
const emit = (e) => {
out ??= open(200, "application/x-ndjson");
out.write(JSON.stringify(e) + "\n");
};
try {
const done = await chat(request, emit);
console.log(JSON.stringify({ effort: done.effort, stop_reason: done.stop_reason, usage: done.usage, metrics: done.metrics }));
} catch (err) {
console.error(err);
const { status, message } = describeError(err);
if (!out) return fail(status, message);
emit({ type: "error", message });
}
out.end();
});