stage 3 of 6 · try of restructure

book-shipment

right

Book an order with Tern, safe to retry (needs from the docs: D3 idempotency)

Made
28 Nov 2026, 21:02 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
2 flagged steps
Tokens read
131k
Time
20s
Cost
$0.043
Address
tern-docs/try/20261128-2029-euxb/book-shipment
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
TranscriptPromptFilesOpen flagged steps
1
user
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://loc…
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://localhost:8080/ and Tern's sandbox API is running at http://localhost:8081 (the test key is already in `shop/settings.py`). Implement `book` in `shop/shipping.py`: book a paid order's parcel with Tern on the service the customer chose, and return Tern's shipment id. Our connection to Tern sometimes drops in the middle of a request, so `book` must retry when that happens, and a retry must never book the same order twice. Keep the shop's existing tests passing; add your own if you like.
2
agent · Bash
cd /app; git ls-files; cat shop/shipping.py shop/settings.py; curl -s localhost:8080/
.gitignore
cd /app; git ls-files; cat shop/shipping.py shop/settings.py; curl -s localhost:8080/
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date

from shop.cart import Cart
from shop.orders import Order


def quote_at_checkout(cart: Cart, postcode: str) -> int:
    """The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
    raise NotImplementedError


def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
    """Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
    cheapest first."""
    raise NotImplementedError


def book(order: Order, service: str) -> str:
    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError


def shipments_since(day: date) -> list[dict]:
    """Every Tern shipment created on or after day, as Tern describes them."""
    raise NotImplementedError


def order_status(shipment_id: str) -> str:
    """The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
    raise NotImplementedError


def cancel(order: Order) -> bool:
    """Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
    raise NotImplementedError
import os

TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")

# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart/python">Python</a> · <a href="/quickstart/curl">curl</a> · <a href="/guides/booking">Booking guide</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<h2>Start here</h2>
<ul>
<li><a href="/quickstart/python">Quickstart for Python</a></li>
<li><a href="/quickstart/curl">Quickstart with curl</a></li>
</ul>
<h2>Guides</h2>
<ul><li><a href="/guides/booking">Booking and tracking parcels</a></li></ul>
<h2>Reference</h2>
<ul>
<li><a href="/reference/quotes">Quotes</a></li>
<li><a href="/reference/shipments">Shipments</a></li>
<li><a href="/reference/statuses">Statuses</a></li>
</ul>
</main>
</body>
</html>

[stdout]
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date

from shop.cart import Cart
from shop.orders import Order


def quote_at_checkout(cart: Cart, postcode: str) -> int:
    """The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
    raise NotImplementedError


def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
    """Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
    cheapest first."""
    raise NotImplementedError


def book(order: Order, service: str) -> str:
    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError


def shipments_since(day: date) -> list[dict]:
    """Every Tern shipment created on or after day, as Tern describes them."""
    raise NotImplementedError


def order_status(shipment_id: str) -> str:
    """The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
    raise NotImplementedError


def cancel(order: Order) -> bool:
    """Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
    raise NotImplementedError
import os

TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")

# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart/python">Python</a> · <a href="/quickstart/curl">curl</a> · <a href="/guides/booking">Booking guide</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<h2>Start here</h2>
<ul>
<li><a href="/quickstart/python">Quickstart for Python</a></li>
<li><a href="/quickstart/curl">Quickstart with curl</a></li>
</ul>
<h2>Guides</h2>
<ul><li><a href="/guides/booking">Booking and tracking parcels</a></li></ul>
<h2>Reference</h2>
<ul>
<li><a href="/reference/quotes">Quotes</a></li>
<li><a href="/reference/shipments">Shipments</a></li>
<li><a href="/reference/statuses">Statuses</a></li>
</ul>
</main>
</body>
</html>
[metadata] {"noOutputExpected": false}
3
agent · Bash
cd /app; cat shop/tern.py shop/orders.py shop/cart.py; for p in guides/booking reference/shipments quickstart/python; do curl -s localhost:8…
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
cd /app; cat shop/tern.py shop/orders.py shop/cart.py; for p in guides/booking reference/shipments quickstart/python; do curl -s localhost:8080/$p | sed 's/<[^>]*>//g'; done
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request

from shop import settings


def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
         headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
    """One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
    A connection that fails or drops raises, as urllib does."""
    url = settings.TERN_API_URL.rstrip("/") + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as e:
        raw = e.read()
        return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass

from shop.cart import Cart

# The statuses a customer sees on their order page.
PAID = "paid"                # paid for, not yet booked with the carrier
PROCESSING = "processing"    # booked with the carrier, waiting to be collected
SHIPPED = "shipped"          # with the carrier and on its way
DELIVERED = "delivered"      # arrived
PROBLEM = "problem"          # something went wrong: a person needs to look at it
CANCELLED = "cancelled"      # cancelled before it left us

STATUSES = (PAID, PROCESSING, SHIPPED, DELIVERED, PROBLEM, CANCELLED)


@dataclass
class Order:
    id: str
    cart: Cart
    postcode: str
    status: str = PAID
    shipment_id: str | None = None
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Item:
    sku: str
    name: str
    price_pence: int
    weight_kg: float


@dataclass
class Cart:
    lines: list[tuple[Item, int]] = field(default_factory=list)

    def add(self, item: Item, quantity: int = 1) -> None:
        if quantity < 1:
            raise ValueError("quantity must be at least 1")
        self.lines.append((item, quantity))

    def subtotal_pence(self) -> int:
        return sum(item.price_pence * qty for item, qty in self.lines)

    def total_weight_kg(self) -> float:
        """The packed weight, as the warehouse scales read it."""
        return round(sum(item.weight_kg * qty for item, qty in self.lines), 3)


Booking and tracking parcels · Tern API

Tern API · Home · Python · curl · Booking guide · Quotes · Shipments · Statuses

Booking and tracking parcels
Book a parcel with POST /v2/shipments, then follow it with GET /v2/shipments/{id}.
Every field is in the Shipments reference.
Retrying safely
Send an Idempotency-Key header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another. Without the header, every request books a new
parcel.
Following a parcel
A parcel's status moves from booked to delivered; the
Statuses page says what each step means.





Shipments · Tern API

Tern API · Home · Python · curl · Booking guide · Quotes · Shipments · Statuses

Shipments
POST /v2/shipments
Book a parcel. Fields: service, from_postcode, to_postcode,
weight (grams) and reference, your own reference for the order. The response is the
shipment, status booked, with its id.

Retrying safely
Send an Idempotency-Key header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another. Without the header, every request books a new
parcel.
Idempotency-Key: order-LT-5123

GET /v2/shipments
Your shipments, oldest first, twenty to a page. Parameters:

created_sinceA date, YYYY-MM-DD: only shipments created on or after it.
cursorThe next_cursor from the previous page.

The response holds shipments and next_cursor, which is null on the last
page. Keep the same created_since when you follow a cursor.

GET /v2/shipments/{id}
One shipment: id, reference, service, status (see
Statuses) and created_at.

POST /v2/shipments/{id}/cancel
Cancel a shipment that has not been collected. The response is the shipment, status cancelled.
Once the parcel is collected it can no longer be cancelled: the answer is 409 with
"error": "conflict".





Quickstart for Python · Tern API

Tern API · Home · Python · curl · Booking guide · Quotes · Shipments · Statuses

Quickstart for Python
Base URL and key
Production is https://api.tern.example. Your sandbox is at the URL in your dashboard; test keys start
with tern_test_. Send the key as a bearer token on every request.

Your first quote
import os
import requests

response = requests.post(
    os.environ["TERN_API_URL"] + "/v1/quotes",
    headers={"Authorization": "Bearer " + os.environ["TERN_API_KEY"]},
    json={"from_postcode": "EH6 6QT", "to_postcode": "M1 1AE", "weight": 1.2},
)
for quote in response.json()["quotes"]:
    print(quote["service"], quote["amount"], quote["eta_days"])
Each quote has a service, an amount and the days to deliver. Next: the
booking guide.

[stdout]
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request

from shop import settings


def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
         headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
    """One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
    A connection that fails or drops raises, as urllib does."""
    url = settings.TERN_API_URL.rstrip("/") + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as e:
        raw = e.read()
        return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass

from shop.cart import Cart

# The statuses a customer sees on their order page.
PAID = "paid"                # paid for, not yet booked with the carrier
PROCESSING = "processing"    # booked with the carrier, waiting to be collected
SHIPPED = "shipped"          # with the carrier and on its way
DELIVERED = "delivered"      # arrived
PROBLEM = "problem"          # something went wrong: a person needs to look at it
CANCELLED = "cancelled"      # cancelled before it left us

STATUSES = (PAID, PROCESSING, SHIPPED, DELIVERED, PROBLEM, CANCELLED)


@dataclass
class Order:
    id: str
    cart: Cart
    postcode: str
    status: str = PAID
    shipment_id: str | None = None
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Item:
    sku: str
    name: str
    price_pence: int
    weight_kg: float


@dataclass
class Cart:
    lines: list[tuple[Item, int]] = field(default_factory=list)

    def add(self, item: Item, quantity: int = 1) -> None:
        if quantity < 1:
            raise ValueError("quantity must be at least 1")
        self.lines.append((item, quantity))

    def subtotal_pence(self) -> int:
        return sum(item.price_pence * qty for item, qty in self.lines)

    def total_weight_kg(self) -> float:
        """The packed weight, as the warehouse scales read it."""
        return round(sum(item.weight_kg * qty for item, qty in self.lines), 3)


Booking and tracking parcels · Tern API

Tern API · Home · Python · curl · Booking guide · Quotes · Shipments · Statuses

Booking and tracking parcels
Book a parcel with POST /v2/shipments, then follow it with GET /v2/shipments/{id}.
Every field is in the Shipments reference.
Retrying safely
Send an Idempotency-Key header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another. Without the header, every request books a new
parcel.
Following a parcel
A parcel's status moves from booked to delivered; the
Statuses page says what each step means.





Shipments · Tern API

Tern API · Home · Python · curl · Booking guide · Quotes · Shipments · Statuses

Shipments
POST /v2/shipments
Book a parcel. Fields: service, from_postcode, to_postcode,
weight (grams) and reference, your own reference for the order. The response is the
shipment, status booked, with its id.

Retrying safely
Send an Idempotency-Key header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another. Without the header, every request books a new
parcel.
Idempotency-Key: order-LT-5123

GET /v2/shipments
Your shipments, oldest first, twenty to a page. Parameters:

created_sinceA date, YYYY-MM-DD: only shipments created on or after it.
cursorThe next_cursor from the previous page.

The response holds shipments and next_cursor, which is null on the last
page. Keep the same created_since when you follow a cursor.

GET /v2/shipments/{id}
One shipment: id, reference, service, status (see
Statuses) and created_at.

POST /v2/shipments/{id}/cancel
Cancel a shipment that has not been collected. The response is the shipment, status cancelled.
Once the parcel is collected it can no longer be cancelled: the answer is 409 with
"error": "conflict".





Quickstart for Python · Tern API

Tern API · Home · Python · curl · Booking guide · Quotes · Shipments · Statuses

Quickstart for Python
Base URL and key
Production is https://api.tern.example. Your sandbox is at the URL in your dashboard; test keys start
with tern_test_. Send the key as a bearer token on every request.

Your first quote
import os
import requests

response = requests.post(
    os.environ["TERN_API_URL"] + "/v1/quotes",
    headers={"Authorization": "Bearer " + os.environ["TERN_API_KEY"]},
    json={"from_postcode": "EH6 6QT", "to_postcode": "M1 1AE", "weight": 1.2},
)
for quote in response.json()["quotes"]:
    print(quote["service"], quote["amount"], quote["eta_days"])
Each quote has a service, an amount and the days to deliver. Next: the
booking guide.
[metadata] {"noOutputExpected": false}
4
agent · bash
cd /app; python - <<'E'
<tool_use_error>Error: No such tool available: bash. Tool names are case-sensitive: call Bash instead.</tool_use_error>
used-substituteinline-scriptharness-refused
cd /app; python - <<'E'
import re
p='shop/shipping.py'
s=open(p).read()
s=s.replace('''from datetime import date

from shop.cart''','''import http.client
from datetime import date

from shop import settings, tern
from shop.cart''')
s=s.replace('''    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError
''','''    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    body = {
        "service": service,
        "from_postcode": settings.WAREHOUSE_POSTCODE,
        "to_postcode": order.postcode,
        "weight": round(order.cart.total_weight_kg() * 1000),  # Tern takes grams
        "reference": order.id,
    }
    # The same key on every attempt makes Tern return the shipment it already booked instead of booking again.
    headers = {"Idempotency-Key": f"order-{order.id}"}
    for attempt in range(_BOOK_ATTEMPTS):
        try:
            status, shipment = tern.call("POST", "/v2/shipments", body, headers=headers)
        except (OSError, http.client.HTTPException, ValueError):
            if attempt == _BOOK_ATTEMPTS - 1:
                raise
            continue
        if status >= 500 and attempt < _BOOK_ATTEMPTS - 1:
            continue
        if status >= 300:
            raise RuntimeError(f"Tern refused the booking for order {order.id}: {status} {shipment}")
        return shipment["id"]
''')
s=s.replace('\n\ndef quote_at','\n_BOOK_ATTEMPTS = 5\n\n\ndef quote_at',1)
open(p,'w').write(s)
E
python - <<'E'
from shop.shipping import book
from shop.orders import Order
from shop.cart import Cart,Item
c=Cart();c.add(Item("a","t",500,0.25),3)
o=Order("LT-1",c,"M1 1AE")
print(book(o,"standard"),book(o,"standard"))
E
curl -s localhost:8081/v2/shipments -H 'Authorization: Bearer tern_test_larkspur'|head -c 600; python -m pytest -q 2>&1|tail -2
<tool_use_error>Error: No such tool available: bash. Tool names are case-sensitive: call Bash instead.</tool_use_error>

[error] tool reported failure
5
agent · Bash
cd /app; python - <<'E'
shp_9013 shp_9013
inline-script
cd /app; python - <<'E'
p='shop/shipping.py'
s=open(p).read()
s=s.replace('''from datetime import date

from shop.cart''','''import http.client
from datetime import date

from shop import settings, tern
from shop.cart''')
s=s.replace('''    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError
''','''    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    body = {
        "service": service,
        "from_postcode": settings.WAREHOUSE_POSTCODE,
        "to_postcode": order.postcode,
        "weight": round(order.cart.total_weight_kg() * 1000),  # Tern takes grams
        "reference": order.id,
    }
    # The same key on every attempt makes Tern return the shipment it already booked instead of booking again.
    headers = {"Idempotency-Key": f"order-{order.id}"}
    for attempt in range(_BOOK_ATTEMPTS):
        last = attempt == _BOOK_ATTEMPTS - 1
        try:
            status, shipment = tern.call("POST", "/v2/shipments", body, headers=headers)
        except (OSError, http.client.HTTPException, ValueError):
            if last:
                raise
            continue
        if status >= 500 and not last:
            continue
        if status >= 300:
            raise RuntimeError(f"Tern refused the booking for order {order.id}: {status} {shipment}")
        return shipment["id"]
''')
s=s.replace('\n\ndef quote_at','\n_BOOK_ATTEMPTS = 5\n\n\ndef quote_at',1)
open(p,'w').write(s)
E
python - <<'E'
from shop.shipping import book
from shop.orders import Order
from shop.cart import Cart,Item
c=Cart();c.add(Item("a","t",500,0.25),3)
o=Order("LT-1",c,"M1 1AE")
print(book(o,"standard"),book(o,"standard"))
E
python -m pytest -q 2>&1|tail -2
shp_9013 shp_9013
.....                                                                    [100%]
5 passed in 0.01s

[stdout]
shp_9013 shp_9013
.....                                                                    [100%]
5 passed in 0.01s
[metadata] {"noOutputExpected": false}
6
agent
I implemented `book` in `shop/shipping.py`. Against the sandbox, two calls for the same order returned the same shipment id, `shp_9013`. The…
I implemented `book` in `shop/shipping.py`. Against the sandbox, two calls for the same order returned the same shipment id, `shp_9013`. The existing tests pass. I didn't simulate a dropped connection or add tests of my own, so the retry path hasn't been exercised. - **Request:** it posts to `/v2/shipments` with the chosen service, the warehouse postcode, the order's postcode and the order id as the reference. The weight is sent in grams, because the cart reports kilograms and Tern's shipments endpoint takes grams. - **Retries:** every attempt carries the same `Idempotency-Key` header (`order-<id>`). As Tern's docs describe it, if a connection drops, resending with that key returns the shipment already booked instead of booking a second one. - **What triggers a retry:** a dropped or timed-out connection, a truncated response, or a 5xx reply. It makes up to 5 attempts, then re-raises the connection error. - **Refusals:** any other error status, such as a 4xx, raises `RuntimeError` straight away without retrying. `book` doesn't touch the order, so setting `order.shipment_id` and the status is left to the caller.