#!/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}")
