Number the retrieved chunks so the model can cite them, and stop adding chunks before the prompt gets too long.
AI · intermediate · 7 min · 33 steps · free
def count_tokens(text):
return len(text.split())
def build_prompt(question, chunks, budget):
parts = []
used = count_tokens(question)
for i, chunk in enumerate(chunks, start=1):
cost = count_tokens(chunk)
if used + cost > budget:
break
parts.append(f'[{i}] {chunk}')
used += cost
context = '\n'.join(parts)
return f'Answer only from these sources and cite them.\n{context}\nQuestion: {question}', used
chunks = ['refunds are free for 30 days', 'keep the receipt', 'shipping to india takes 5 days']
prompt, used = build_prompt('are refunds free', chunks, 12)
print(used)
print(prompt)count_tokens(). Its body does not run yet: it runs each time the function is called.build_prompt(). Its body does not run yet: it runs each time the function is called.chunks is created and points to a new list: ['refunds are free for 30 days', 'keep the receipt', 'shipping to india takes 5 days'].build_prompt(), with question = 'are refunds free', chunks = ['refunds are free for 30 days', 'keep the receipt', 'shipping to india takes 5 days'] and budget = 12. It gets its own names.parts is created and points to a new list: [].count_tokens(), with text = 'are refunds free'. It gets its own names.len(text.split()).i is created with the value 1. chunk is created with the value 'refunds are free for 30 days'.count_tokens(), with text = 'refunds are free for 30 days'. It gets its own names.len(text.split()).count_tokens() has finished, so its names are gone. The value it returned, 6, is stored in cost.used + cost > budget is false, so the block under it is skipped.used changes from 3 to 9.i changes from 1 to 2. chunk changes from 'refunds are free for 30 days' to 'keep the receipt'.count_tokens(), with text = 'keep the receipt'. It gets its own names.len(text.split()).count_tokens() has finished, so its names are gone. The value it returned, 3, is stored in cost.used + cost > budget is false, so the block under it is skipped.parts points to.used changes from 9 to 12.i changes from 2 to 3. chunk changes from 'keep the receipt' to 'shipping to india takes 5 days'.count_tokens(), with text = 'shipping to india takes 5 days'. It gets its own names.len(text.split()).count_tokens() has finished, so its names are gone. The value it returned, 6, is stored in cost.break.f'Answer only from these sources and cite them.\n{context}\nQuestion: {question}', used.build_prompt() has finished, so its names are gone. The value it returned, 'Answer only from these sources and cite them.\n[1] refunds are free for 30 days\n[2] keep the receipt\nQuestion: are refunds free', is stored in prompt. used is created with the value 12.12.Answer: So the answer can cite [1], [2]
Answer: Bury the useful part and cost more
← Keyword vs Meaning: Hybrid Search · Grounded Answers and "I Don't Know" →