AI Agents by HandAll problemsAbout

All problems › Agent problem · medium · ~20 min

Halve the input-token cost

token cost context size chunking

Solve it in your browser →

Cut the token bill (~20 min)

cut_token_cost.py is a support agent with one tool, search_kb, over a 10-article knowledge base. It answers correctly but it's expensive:

python -m cut_token_cost

The prompt asks whether a laptop delivered 20 days ago can be returned and what the return shipping costs (the answer is $12.50, spread over two articles). Every search_kb call dumps five full articles into the conversation, and that bulk is re-sent on every later model call.

Goal: the same correct answer for at most half the baseline input cost, in at most 3 model calls. Cost is input tokens, weighted by price (cache writes count 1.25x, cache reads 0.1x); it's the input_cost of the counting client in tests/conftest.py. Measure the baseline first: count calls and print response.usage for each one.

Constraints:

  • Raw SDK only, and run_agent(prompt, client=None, max_turns=10) -> str keeps its signature.
  • You can change the tools, their schemas, the system prompt, the request parameters and the loop, but search_kb must keep working under that name (add tools rather than replacing it).
  • A failing tool must still come back to the model as an is_error result rather than crash the agent.
  • Don't give up correctness for cost: the model still needs enough information to quote the right numbers.

Before you change anything, work out where the tokens are going. Then be ready to explain each lever you pulled (what it saves, what it costs in answer quality or latency, how you'd check it didn't regress) and which levers you rejected and why. For example: would prompt caching help here? When would it?

Running the module with a key prints a trace of every model call to stderr: tool calls with their ids and inputs, the results sent back, and token counts (ABH_TRACE=0 turns it off).

Check it: pytest tests/test_cut_token_cost.py. The offline tests check the loop, that search_kb still works, and how big the conversation is after one search. The cost and correctness goals are checked by the live test, which needs an API key (see Settings).

Starter code and hidden tests open in the editor. Nothing to install.