Skip to content

Latest commit

 

History

History
94 lines (65 loc) · 3.08 KB

resource-optimization.md

File metadata and controls

94 lines (65 loc) · 3.08 KB

Cut model cost

The problem

An insurance broker gets letters all day. Each one needs a desk and a level of urgency. The rules are in a long handbook.

The first try is the safe choice. The strong model reads the whole handbook for each letter. It works, and it costs a lot. Most letters are easy, and the handbook never changes.

How it works

Cut model cost by routing letters.

Two ideas cut the bill: model routing and prompt caching.

  1. The handbook is marked for caching, so it is cheap to read again.
  2. The small model gives structured output: desk, urgency, and if it is hard.
  3. Code sends only the hard ones to the strong model.

For example, a letter about a double payment is easy. A letter with a broken door and a double charge is hard. Only the second one is passed up.

The flow

sequenceDiagram
    participant Code as Your code
    participant Small as Small model
    participant Strong as Strong model
    Code->>Small: handbook and letter
    Small-->>Code: desk, urgency, hard or not
    alt the letter is hard
        Code->>Strong: handbook and letter
        Strong-->>Code: desk and urgency
    else the letter is easy
        Code->>Code: file it now
    end
Loading

Concepts

Run it

uv run lab resource-optimization naive
uv run lab resource-optimization

The run shows who filed each letter and how many tokens came from the cache. Try --case 2 and --case 3.

Prove it

There are three trays of five letters. For each tray, code divides the cost by the letters filed right. It adds the three results. A cheap wrong answer makes the number worse.

The unit is a millionth of a dollar. The cost is an estimate from token counts, not a bill.

Version Cost for each right letter
Strong model every time 24695
Routing and caching 4244

Now break it. Open the pattern file and find needs_strong. Make it always return False. Then run the test:

uv run pytest tests/promises/test_resource_optimization.py

The test fails, because a hard letter now stays with the small model.

Stuck points

  • A short block is not cached. If the cache count stays at zero, the block may be too small.
  • The cache fades after a quiet spell. The first call after that pays full price.

What to watch for

The small model judges how hard a letter is. It can be sure and wrong. Check a sample of easy letters by hand.

The numbers move from run to run, since they depend on how many letters are passed up. The estimate also leaves out the small extra fee for writing to the cache.

Where to go next

Go to Trace every call. It shows what each call really did.