stage 2 of 6 · try of restructure

quote-options

right

Every Tern service for a cart, cheapest first (needs from the docs: D1 grams, D2 current endpoint)

Made
28 Nov 2026, 20:57 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
2 flagged steps
Tokens read
130k
Time
15s
Cost
$0.045
Address
tern-docs/try/20261128-2029-b08p/quote-options
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 `quote_options` in `shop/shipping.py`: the customer picks a delivery speed at checkout, so we need every service Tern offers for the cart and postcode, with its price in pence and the days it takes, cheapest first. Keep the shop's existing tests passing; add your own if you like.
2
agent · Bash
cd /app; cat shop/shipping.py shop/settings.py; ls . shop tests 2>/dev/null; curl -s localhost:8080/
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
cd /app; cat shop/shipping.py shop/settings.py; ls . shop tests 2>/dev/null; curl -s localhost:8080/
"""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"
.:
README.md
pytest.ini
shop
tests

shop:
__init__.py
cart.py
orders.py
settings.py
shipping.py
tern.py

tests:
__init__.py
test_cart.py
test_orders.py
<!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]
"""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"
.:
README.md
pytest.ini
shop
tests

shop:
__init__.py
cart.py
orders.py
settings.py
shipping.py
tern.py

tests:
__init__.py
test_cart.py
test_orders.py
<!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/cart.py README.md; curl -s localhost:8080/reference/quotes; curl -s localhost:8080/quickstart/python
"""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/cart.py README.md; curl -s localhost:8080/reference/quotes; curl -s localhost:8080/quickstart/python
"""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, 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)
# Larkspur Tea: shop backend

The order and checkout logic behind Larkspur Tea's online shop. Plain Python 3.13, no framework, no dependencies
beyond pytest for the tests.

- `shop/cart.py`: carts and items. Prices are in pence; weights are in kilograms, as the warehouse weighs them.
- `shop/orders.py`: orders and the order statuses the shop shows customers.
- `shop/shipping.py`: everything to do with our carrier, Tern. Mostly still to write.
- `shop/tern.py`: a thin client for Tern's API (authentication, JSON in and out).
- `shop/settings.py`: configuration, from the environment with defaults for development.

## Shipping

We ship everything with Tern. In development, `TERN_API_URL` points at Tern's sandbox and `TERN_API_KEY` holds a
test key; both default to what the sandbox expects.

## Tests

```
python -m pytest
```
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Quotes · 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>Quotes</h1>
<h2>POST /v2/quotes</h2>
<p>Prices for one parcel on every service Tern offers between two postcodes.</p>
<table>
<tr><th>Field</th><th>Type</th><th></th></tr>
<tr><td><code>from_postcode</code></td><td>string</td><td>Where the parcel is collected.</td></tr>
<tr><td><code>to_postcode</code></td><td>string</td><td>Where it is delivered.</td></tr>
<tr><td><code>weight</code></td><td>integer</td><td>The packed weight <strong>in grams</strong>. Up to 20,000.</td></tr>
</table>
<p>The response holds <code>quotes</code>, one per service (<code>economy</code>, <code>standard</code>,
<code>express</code>), each with an <code>id</code>, its <code>amount</code> <strong>in pence</strong>, the
<code>currency</code> and <code>eta_days</code>. They are in no particular order. A parcel over 20 kg is a
<code>422</code> with <code>"error": "too_heavy"</code>.</p>
</main>
</body>
</html>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Quickstart for Python · 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>Quickstart for Python</h1>
<h2>Base URL and key</h2>
<p>Production is <code>https://api.tern.example</code>. Your sandbox is at the URL in your dashboard; test keys start
with <code>tern_test_</code>. Send the key as a bearer token on every request.</p>

<h2>Your first quote</h2>
<pre>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"])</pre>
<p>Each quote has a <code>service</code>, an <code>amount</code> and the days to deliver. Next: the
<a href="/guides/booking">booking guide</a>.</p>
</main>
</body>
</html>

[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, 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)
# Larkspur Tea: shop backend

The order and checkout logic behind Larkspur Tea's online shop. Plain Python 3.13, no framework, no dependencies
beyond pytest for the tests.

- `shop/cart.py`: carts and items. Prices are in pence; weights are in kilograms, as the warehouse weighs them.
- `shop/orders.py`: orders and the order statuses the shop shows customers.
- `shop/shipping.py`: everything to do with our carrier, Tern. Mostly still to write.
- `shop/tern.py`: a thin client for Tern's API (authentication, JSON in and out).
- `shop/settings.py`: configuration, from the environment with defaults for development.

## Shipping

We ship everything with Tern. In development, `TERN_API_URL` points at Tern's sandbox and `TERN_API_KEY` holds a
test key; both default to what the sandbox expects.

## Tests

```
python -m pytest
```
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Quotes · 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>Quotes</h1>
<h2>POST /v2/quotes</h2>
<p>Prices for one parcel on every service Tern offers between two postcodes.</p>
<table>
<tr><th>Field</th><th>Type</th><th></th></tr>
<tr><td><code>from_postcode</code></td><td>string</td><td>Where the parcel is collected.</td></tr>
<tr><td><code>to_postcode</code></td><td>string</td><td>Where it is delivered.</td></tr>
<tr><td><code>weight</code></td><td>integer</td><td>The packed weight <strong>in grams</strong>. Up to 20,000.</td></tr>
</table>
<p>The response holds <code>quotes</code>, one per service (<code>economy</code>, <code>standard</code>,
<code>express</code>), each with an <code>id</code>, its <code>amount</code> <strong>in pence</strong>, the
<code>currency</code> and <code>eta_days</code>. They are in no particular order. A parcel over 20 kg is a
<code>422</code> with <code>"error": "too_heavy"</code>.</p>
</main>
</body>
</html>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Quickstart for Python · 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>Quickstart for Python</h1>
<h2>Base URL and key</h2>
<p>Production is <code>https://api.tern.example</code>. Your sandbox is at the URL in your dashboard; test keys start
with <code>tern_test_</code>. Send the key as a bearer token on every request.</p>

<h2>Your first quote</h2>
<pre>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"])</pre>
<p>Each quote has a <code>service</code>, an <code>amount</code> and the days to deliver. Next: the
<a href="/guides/booking">booking guide</a>.</p>
</main>
</body>
</html>
[metadata] {"noOutputExpected": false}
4
agent · Bash
cd /app; curl -s -XPOST localhost:8081/v2/quotes -H 'Authorization: Bearer tern_test_larkspur' -H 'Content-Type: application/json' -d '{"fro…
{"quotes": [{"id": "qt_7", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_8", "service": "standard", "a…
used-substitute
cd /app; curl -s -XPOST localhost:8081/v2/quotes -H 'Authorization: Bearer tern_test_larkspur' -H 'Content-Type: application/json' -d '{"from_postcode":"EH6 6QT","to_postcode":"M1 1AE","weight":1200}'; echo; curl -s -XPOST localhost:8081/v2/quotes -H 'Authorization: Bearer tern_test_larkspur' -d '{"from_postcode":"EH6 6QT","to_postcode":"M1 1AE","weight":20001}'
{"quotes": [{"id": "qt_7", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_8", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_9", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
{"error": "too_heavy"}

[stdout]
{"quotes": [{"id": "qt_7", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_8", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_9", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
{"error": "too_heavy"}
[metadata] {"noOutputExpected": false}
5
agent · Bash
cd /app; python - <<'E'
....... [100%]
inline-script
cd /app; python - <<'E'
p='shop/shipping.py'
s=open(p).read()
s=s.replace('''    cheapest first."""
    raise NotImplementedError''','''    cheapest first."""
    status, body = tern.call("POST", "/v2/quotes", {
        "from_postcode": settings.WAREHOUSE_POSTCODE,
        "to_postcode": postcode,
        "weight": round(cart.total_weight_kg() * 1000),  # Tern wants grams
    })
    if status != 200:
        raise RuntimeError(f"Tern quote failed ({status}): {body.get('error', body)}")
    options = [(q["service"], q["amount"], q["eta_days"]) for q in body["quotes"]]
    return sorted(options, key=lambda option: (option[1], option[2]))''',1)
s=s.replace("from shop.cart import Cart","from shop import settings, tern\nfrom shop.cart import Cart",1)
open(p,'w').write(s)
E
cat > tests/test_shipping.py <<'E'
from unittest.mock import patch

import pytest

from shop import shipping
from shop.cart import Cart, Item


def _cart():
    cart = Cart()
    cart.add(Item("T1", "Tea", 500, 0.4), 3)
    return cart


def test_quote_options_sorted_and_in_grams():
    quotes = [{"service": "express", "amount": 1295, "eta_days": 1},
              {"service": "economy", "amount": 495, "eta_days": 5},
              {"service": "standard", "amount": 695, "eta_days": 3}]
    with patch("shop.tern.call", return_value=(200, {"quotes": quotes})) as call:
        result = shipping.quote_options(_cart(), "M1 1AE")
    assert result == [("economy", 495, 5), ("standard", 695, 3), ("express", 1295, 1)]
    assert call.call_args.args[2]["weight"] == 1200


def test_quote_options_error():
    with patch("shop.tern.call", return_value=(422, {"error": "too_heavy"})):
        with pytest.raises(RuntimeError):
            shipping.quote_options(_cart(), "M1 1AE")
E
python -m pytest -q 2>&1|tail -3
python -c "
from shop import shipping
from shop.cart import *
c=Cart();c.add(Item('a','a',1,0.4),3);print(shipping.quote_options(c,'M1 1AE'))"
.......                                                                  [100%]
7 passed in 0.18s
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]

[stdout]
.......                                                                  [100%]
7 passed in 0.18s
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
[metadata] {"noOutputExpected": false}
6
agent
I've implemented `quote_options` in `shop/shipping.py`. Against the sandbox, a 1.2 kg cart to M1 1AE returns `[('economy', 495, 5), ('standa…
I've implemented `quote_options` in `shop/shipping.py`. Against the sandbox, a 1.2 kg cart to M1 1AE returns `[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]`. The full suite passes, including two new tests in `tests/test_shipping.py`. - **Request:** it calls `POST /v2/quotes` from the warehouse postcode, sending the cart weight in grams. - **Result:** it returns every service as `(service, price in pence, eta_days)`, sorted by price. Ties are broken by fewer days. - **Errors:** any non-200 response raises `RuntimeError` with Tern's error message, such as `too_heavy` for parcels over 20 kg. If you'd rather show the customer a friendly message for that case, say so and I'll add a specific exception. - **Docs mismatch:** Tern's Python quickstart is out of date. It shows `/v1/quotes` with the weight in kilograms, while the Quotes reference and the sandbox use `/v2/quotes` with grams. I followed the reference, and the sandbox confirmed it. The new tests mock Tern. They check the sorting, that 1.2 kg is sent as 1200 grams, and that an error status raises.