Search and contents

Merging paginated call results

This guide shows how to reconcile a split BudgetPlan's several CallOutcomes into one final answer, using the optional merge callback of InferenceClient.run_plan (engine/inference.py).

Token Budget (engine/token_budget.py) decides whether a call's content fits one Ollama call or must paginate across several. A caller's job never knows, or needs to know, which happened until it looks at the result.

  • run_plan executes every batch and returns a PaginatedResult.
  • Without a merge callback, that is just the raw list of per-batch outcomes.
  • merge turns N per-batch outcomes into a single PaginatedResult.merged outcome, for a use case that needs one coherent answer rather than N separate ones.

1. Decide whether you need this at all

Not every paginated caller does. If each batch's output is already a complete, disjoint piece of the final result, there is nothing to reconcile. Examples are a document split into non-overlapping sections, or per-theme scores keyed by a theme that never repeats across batches. The caller can consume result.outcomes directly and skip merge entirely.

Reach for merge only when a genuinely single answer is needed and there is a real chance that no one batch's output already is that answer. The concrete case in this codebase is run_plan("SYS", plan, build_prompt)'s pagination on an oversized set of retrieved chunks, where the caller wants one synthesized answer to a question, not one partial answer per chunk batch.

2. Pick the merge shape: structural, or reduce

Structural

The batches' outputs recombine mechanically, with no further model call:

def concat_merge(outcomes: list[CallOutcome]) -> CallOutcome:
    return CallOutcome(
        success=all(o.success for o in outcomes),
        text="\n---\n".join(o.text for o in outcomes),
        attempts=sum(o.attempts for o in outcomes),
        duration_ms=sum(o.duration_ms for o in outcomes),
    )

Use this when the split boundary was chosen so each batch's output is already complete and non-overlapping: positional concatenation for disjoint sections, dict-union for disjoint per-key results. It is a pure function. Test it with plain deterministic unit tests (order preserved, nothing dropped or duplicated).

Reduce

The batches' outputs are partial answers to the same question and genuinely need reconciling, not just recombining. This is a closure over InferenceClient, making one further call:

def reduce_merge(outcomes: list[CallOutcome]) -> CallOutcome:
    partials = "\n".join(o.text for o in outcomes if o.success)
    return client.call(f"Reconcile these partial answers into one:\n{partials}")

client is whatever InferenceClient the caller already has in scope. merge doesn't get one injected, the same way build_prompt doesn't get anything injected beyond fixed_overhead and the batch.

This is the shape point-of-use SOP answer synthesis needs. A question whose retrieved Playbook chunks didn't fit one call gets a per-chunk-batch partial answer each. merge is the one further call that turns those into the single answer a human actually reads.

3. Wire it into run_plan

result = client.run_plan(fixed_overhead, plan, build_prompt, merge=reduce_merge)
answer = result.merged  # CallOutcome | None

result.merged is None when merge was never supplied, or when the plan has no batches (so there are no outcomes to merge). If you passed one and there is at least one batch, you always get a CallOutcome back, including for a plan that never actually split.

merge is never invoked for a single-batch plan, even when supplied. That batch's own outcome is used directly as merged, since reconciling a list of one spends a call for no reason. Don't write a merge function that assumes it always runs against 2+ outcomes. Guard len(outcomes) == 1 yourself only if merge does something batch-count-sensitive beyond simple reconciliation, which it usually doesn't need to.

4. Test it

  • Structural merges: plain deterministic assertions against merge's own output (order preserved, nothing dropped or duplicated). See test_run_plan_merge_reconciles_a_structural_split in tests/test_inference.py.
  • Reduce-style merges: test_run_plan_merge_can_make_a_reduce_style_second_call in tests/test_inference.py shows the shape, a merge closure making a second mocked call. That is only a wiring test. It proves the second call happens and its result lands in merged, not that the reconciled answer is actually correct.
    • There are no golden-set fact-grounding tests (a known input's exact figures must survive synthesis) for a real reduce-style merge.
    • There are no structural safety-net properties (every batch traceable, no verbatim duplication).
    • Both need a real answer-synthesis prompt to test against.
    • An LLM-judged Gate mode is the suitable monitoring-only layer for subjective coherence, not a hard CI gate.

Pitfalls

  • A reduce-style merge costs a real, additional model call, but only when the plan actually splits. Budget for it the same way any other call is budgeted (Token Budget, retry schedule). It is not free just because it's "only a merge."
  • Failed batches are passed to merge too. run_plan never filters outcomes before handing them to merge. A batch that exhausted its retries and came back success=False is still in the list, with whatever (likely empty or low-quality) text it landed on. Reconciling that is merge's own policy to make (skip it, flag the whole answer as partial, and so on), the same way a failed batch aborting nothing is call's policy, not run_plan's.
  • A single-batch plan silently skips merge. If you're testing a merge function in isolation and it never seems to fire, check plan.is_split before suspecting the callback itself.

Release: v0.11.0