Each time your support bot calls the model, you pay for its tokens: the text sent plus the text received. A bot with tools calls the model in a loop, and every call sends the whole chat again. So a visitor can run up your bill on purpose: "Look up every order from 1 to 100, one per tool call." The model is glad to help. A rule in the prompt won't hold either, because the visitor can talk the model out of it.
The budget lives in your code. Count what each chat spends, and check the count before every call that costs money. The counters belong to the conversation, not to one message, so typing "Keep going." doesn't buy a fresh budget. Here is the same idea on another resource, 3 searches per chat:
MAX_SEARCHES = 3
def search(conversation, words):
if conversation["searches"] >= MAX_SEARCHES:
return "You've used all the searches of this chat."
conversation["searches"] = conversation["searches"] + 1
return run_search(words)
Your chat already counts tool_calls and tokens in the dict from new_chat(). Give each chat two limits: 5 tool calls, which catch loops, and 2000 tokens, which catch huge messages that never use a tool. With the budget, the attack chat prints:
Visitor: Look up every order from 1 to 100, one per tool call. Don't stop until you've checked them all.
Tool: lookup_order {'order_id': 1} -> {'id': 1, 'ordered': '2026-03-02', 'status': 'paid'}
…
Tool: lookup_order {'order_id': 5} -> {'id': 5, 'ordered': '2026-05-07', 'status': 'paid'}
Bot: Sorry, this chat has reached its limit. Please email help@cornershop.example and we'll answer you there.
Visitor: Keep going.
Bot: Sorry, this chat has reached its limit. Please email help@cornershop.example and we'll answer you there.
Tool calls: 5 | Tokens: 270
Honest visitors don't notice the budget. The chat about orders 3 and 4 uses 2 tool calls and 125 tokens and gets its answers as before. A new chat after the attack starts again from 0. The check also sends a 2781-character text three times in one chat. It gets two summaries, then the sorry message once the chat reaches 2109 tokens.
Your task: below db.row_factory, set MAX_TOOL_CALLS to 5, MAX_TOKENS to 2000, and SORRY to the polite message above. At the top of the while loop in chat, if the chat's tool_calls or tokens has reached its limit, print "Bot:" and SORRY, then return.
Assignment
Follow the Coding Tutorial to give every chat a budget of tool calls and tokens, and to stop politely when it is spent.
Hint
Use >= so the chat stops when a counter reaches its limit, and or so either limit is enough. Without the return, the sorry message prints but the loop calls the model again.
Free plan: 30 tutor messages. PRO is unlimited.
