Sub topic 9
Refine: carry a running summary forward
Prerequisites and scope
This chapter assumes you can read basic Python and have sent prompts to an LLM through an API. It also assumes you know what a token is. It builds on the chunking chapter: you already have a list of chunks that stay under a token budget and split along paragraph boundaries. Here you will summarise that list with the refine strategy, see where it breaks, and decide when to use it instead of map-reduce.
The idea
Refine is an iterative strategy. You read the document in order, one chunk at a time, and keep a single running summary.
- Summarise the first chunk.
- For each later chunk, give the model the current summary and the new chunk. Ask it to produce an updated summary.
- After the last chunk, the running summary is the result.
The summary acts as the model's memory. Each call sees only two things: what you have written so far and the next piece of the source. The model never sees the whole document at once, and it never sees earlier chunks again.
The implementation
The code below processes chunks in order and rewrites the running summary with each new chunk. call_llm is any function that takes a prompt string and returns the model's text.
def refine_summary(chunks, call_llm):
summary = ''
for chunk in chunks:
if not summary:
prompt = 'Summarise this text:\n\n' + chunk
else:
prompt = (
'Here is the summary so far:\n' + summary +
'\n\nUpdate it using the next part of the document. Keep it under 200 words.\n\n' + chunk
)
summary = call_llm(prompt)
return summaryThree details matter here.
- The loop is sequential. Call N needs the output of call N-1, so you cannot run the calls in parallel.
- The summary replaces itself each time. Nothing from earlier chunks survives unless the model chose to keep it in the summary.
- The length cap ("under 200 words") is what keeps the prompt size stable. Without it, the summary grows and eventually competes with the chunk for space in the context window.
To run it end to end, combine it with the chunker from the previous chapter:
def chunk_paragraphs(text, max_tokens, count_tokens):
chunks, current, size = [], [], 0
for para in text.split('\n\n'):
n = count_tokens(para)
if current and size + n > max_tokens:
chunks.append('\n\n'.join(current))
current, size = [], 0
current.append(para)
size += n
if current:
chunks.append('\n\n'.join(current))
return chunks
def refine_summary(chunks, call_llm):
summary = ''
for chunk in chunks:
if not summary:
prompt = 'Summarise this text:\n\n' + chunk
else:
prompt = (
'Here is the summary so far:\n' + summary +
'\n\nUpdate it using the next part of the document. Keep it under 200 words.\n\n' + chunk
)
summary = call_llm(prompt)
return summary
def fake_count(text):
return len(text.split())
def fake_llm(prompt):
# Stand-in for a real model: returns the first 20 words of the last paragraph.
last = prompt.split('\n\n')[-1]
return ' '.join(last.split()[:20])
doc = '\n\n'.join(f'Paragraph {i} ' + 'word ' * 50 for i in range(10))
chunks = chunk_paragraphs(doc, 120, fake_count)
print(len(chunks), 'chunks')
print(refine_summary(chunks, fake_llm))Replace fake_llm with a function that calls your provider's API to use it for real. The stand-in lets you check the control flow and the number of calls without spending tokens.
Token budget per call
Each refine call has to fit the running summary, the instructions, the new chunk and the model's output in the context window. A rough budget looks like this:
| Part of the call | Typical size |
|---|---|
| Instructions | 50 to 100 tokens |
| Running summary | Up to your length cap, for example 300 tokens |
| New chunk | Your chunk budget |
| Output | About the same as the length cap |
So the chunk budget you chose for map-reduce is not automatically right for refine. Leave room for the summary and the output. If the cap is 300 tokens and the instructions are 100, reduce the chunk budget by about 700 tokens to stay safe: the summary and the instructions in the prompt, plus the output reserved for the reply.
What refine does well
- Document order is preserved. The summary is built in the sequence the author wrote. This suits narratives, meeting transcripts, legal sequences and any text where later parts depend on earlier ones.
- Context carries across chunk boundaries. If a name is introduced in chunk 2 and used in chunk 5, the summary can hold the link. In map-reduce, chunk 5 is summarised alone and may not know who the name refers to.
- The output has one voice. There is no combine step that stitches separate summaries together, so you avoid repetition and awkward transitions.
- The prompt size is predictable. Every call is about the same size, so memory and token use per call are stable.
Where refine fails
Early details fade
Every update rewrites the summary under a fixed length cap. When the new chunk contains something important, the model must drop something to make room. It usually drops the oldest material, because the summary is the only record of it. After 30 updates, a detail from chunk 1 has survived 30 rewrites. Each rewrite is a chance to lose it.
This is the main reason refine is less suitable for documents where all parts matter equally, such as a survey of many independent items.
Recency bias
The model sees the new chunk in full detail and the older material only in compressed form. It tends to give the new chunk more weight. The final summary can end up describing the last third of the document well and the first third in one sentence.
Errors compound
If the model misstates something at step 4, step 5 sees that misstatement as fact. It has no way to check the claim against the source, because the source chunk is gone. A wrong claim can persist or get worse across the remaining updates. In map-reduce, a bad partial summary affects only one branch.
Latency grows linearly
With N chunks you make N sequential calls. If each takes 4 seconds, 50 chunks take about 200 seconds. Map-reduce can run the map step in parallel, so its wall-clock time is closer to one map call plus the reduce calls.
One failure stops everything
Because each step depends on the last, a failed call in the middle means you either retry that step or restart. Save the running summary and the chunk index after each call so you can resume.
import json
def refine_with_checkpoint(chunks, call_llm, path='refine_state.json'):
try:
with open(path) as f:
state = json.load(f)
except FileNotFoundError:
state = {'next': 0, 'summary': ''}
for i in range(state['next'], len(chunks)):
chunk = chunks[i]
if not state['summary']:
prompt = 'Summarise this text:\n\n' + chunk
else:
prompt = (
'Here is the summary so far:\n' + state['summary'] +
'\n\nUpdate it using the next part of the document. Keep it under 200 words.\n\n' + chunk
)
state['summary'] = call_llm(prompt)
state['next'] = i + 1
with open(path, 'w') as f:
json.dump(state, f)
return state['summary']Improving the refine prompt
The simple prompt in the first listing works for short documents. For longer ones, add constraints to the update instruction.
- Tell the model what to keep. For example: "Keep every named person, date and decision already in the summary unless the new text contradicts it."
- Tell the model what to add. For example: "Add only information that appears in the new text."
- Forbid outside knowledge. For example: "Use only the summary and the new text."
- Use a structure instead of free prose. A list of fixed sections (people, decisions, open questions) is harder to overwrite than a paragraph, because the model updates items instead of rewording a whole text.
- Allow the length to grow in a controlled way. A cap of 200 words may be too tight for 50 chunks. Scale the cap with the document, for example 150 words plus 10 words per chunk.
Choosing refine
| Question | Favours refine | Favours map-reduce |
|---|---|---|
| Does order matter? | Yes, narrative or chronological | No, independent sections |
| Do later parts depend on earlier parts? | Yes | No |
| Do all parts matter equally? | No | Yes |
| Is latency important? | No | Yes |
| Is the document very long (hundreds of chunks)? | Usually not | Often, with a hierarchical reduce |
| Do you need to retry cheaply? | Needs checkpoints | Retry one chunk |
A reasonable default is map-reduce for most documents, and refine when order and cross-chunk context matter more than speed and even coverage. Some systems combine them: summarise sections with map-reduce, then refine across the section summaries in order.
Cost
Refine costs more input tokens per chunk than map-reduce, because every call repeats the running summary. Over N chunks, the extra input is roughly N times the summary length. With a 300-token summary and 40 chunks, that is about 12,000 extra input tokens. This is small compared with the chunk text itself, which is why the main cost of refine is time, not money. Map-reduce adds a reduce step instead, so the totals are usually in the same range. Later chapters compare the strategies in detail.
Checking a refine result
After a refine run, check for the failures described above.
- Pick five facts from the first third of the document. Check whether each appears in the final summary.
- Pick five facts from the last third and do the same. A large gap between the two counts points to fading or recency bias.
- Pick two claims from the summary and trace each to the source passage. A claim you cannot trace is a hallucination, and it may have entered at any step.
- Log the intermediate summaries. Reading them in order shows exactly which update dropped a detail.
Exercise
You summarise a 60-chunk interview transcript with refine and a fixed 150-word cap. The final summary describes the closing chunks well, but it hardly mentions the opening topic. Name the two causes and give two changes that would reduce the problem.
Show answer
The causes are fading of early details (each rewrite under a fixed cap drops the oldest material to make room) and recency bias (the model sees the new chunk in full but older material only in compressed form). Possible changes: raise the cap so it scales with the number of chunks; tell the model in the update prompt to keep all items already in the summary unless contradicted; use a structured summary with fixed sections so items are updated and not reworded; or summarise sections with map-reduce first and refine across the section summaries.
Exercise
A refine run over 50 chunks takes 4 seconds per call. How long does it take, and why can you not shorten it by sending the calls in parallel?
Show answer
About 200 seconds (50 x 4). Each call needs the summary produced by the previous call, so the calls form a chain and cannot run at the same time. Map-reduce can run its map calls in parallel because each chunk is summarised independently.