Detect loops in streamed thinking, text and tool call arguments in `DetectLoops`
Mike asked for this directly; there is no issue.
Why: DetectLoops only compared finished responses between requests. A model that loops inside one response (thinking that keeps repeating a passage, text that degenerates, a write_file body repeating a block, or the same tool call made many times at once) uses up its output budget before any check can see it. Now each response is also checked on its own as it streams, and when it loops the stream is stopped and the request made again with the usual nudge.
[!WARNING]
Compatibility impact: LoopPattern gains repeated_thinking, repeated_stream_text, repeated_tool_args and repeated_parallel_call, so a LoopHandler, code reading LoopDetectedError.loop, or code reading a nudge's metadata['pattern'] can now be handed them. An exhaustive match ending in assert_never fails type checking. The in-response checks are on by default, so a response that repeats a passage, or makes the same call 5 times, is now stopped and retried.
Why this can ship in a minor release: Pydantic AI Harness is on 0.x releases, where the API may change between minor releases, and runs whose responses don't loop behave as before.
Migration: handle the new patterns wherever you match on pattern. To keep only the checks between requests, pass stream_detector=None, repeated_parallel_call_threshold=None.
New public surface (pydantic_ai_harness.detect_loops):
DetectLoopsfields:stream_detector(defaultRepetitionDetector(),Noneturns it off),stream_channels(('thinking', 'text', 'tool_args')),stream_check_every(256),repeated_parallel_call_threshold(5).- New
LoopPatternvalues:repeated_thinking,repeated_stream_text,repeated_tool_args,repeated_parallel_call. New fieldDetectedLoop.passage, defaulting toNone. LoopDetector, the pluggable ABC:async detect(ctx, sample: StreamSample) -> Repetition | None, plusStreamSample,RepetitionandStreamChannel.RepetitionDetector, the default heuristic. It reports text that ends in the same passage repeated back to back:min_period=20tomax_period=2000characters using at leastmin_distinct_chars=8different characters, at leastmin_repeats=8times, covering at leastmin_chars=2000. Runs of a shorter or plainer unit, like divider lines, rows of zeros or table rules, are skipped. Grids, markdown tables and a few dozen identical rows are not reported. It compares characters exactly, so it is deterministic.LoopJudge(model=... | agent=..., heuristic=..., every=None, max_chars=4000, timeout=5.0), an optional model judge. It is asked when the heuristic suspects a loop (to confirm or overrule it), and everyeverycharacters if set. If the judge fails or times out, the heuristic's answer is used and aloop judge failedspan is emitted. A judge built frommodel=is not instrumented, like the other harness judges, and its usage is added to the run's usage. The docs tell users to pick a small, fast "System 1" model, not a reasoning model.
Behavior:
'nudge': enqueues the usual origin-taggedSystemPromptPart, request-scoped this time because the response that looped is dropped, then raisesModelRetryfromwrap_model_request. That goes through core's existing stream-abandonment path: the stream stops and the request is retried. The retry counts against output retries.'error': stops the stream and raisesLoopDetectedError.- Handler: if it returns, the response continues. If it raises
ModelRetry, the stream stops and the request is retried. - Responses that aren't streamed get the same checks at the same offsets when they arrive.
DetectLoopsnever forces streaming (has_wrap_run_event_streamisFalse). - Under Temporal, DBOS and Prefect, each response is checked whole in workflow code, and
LoopJudgenever calls its model there. - Known limits, documented:
run_stream()can't retry once its output has started streaming. A stopped stream's tokens aren't added to the run's usage (core's abandonment path doesn't record them).
Verification: tests/harness/detect_loops/test_in_stream.py covers each channel, repeated parallel calls, the heuristic's negative cases, every action, non-streamed responses, run_stream, cancellation and task leaks, telemetry, and the judge paths: confirm, overrule, detect on cadence, failure, timeout, a custom agent, agent name. The durable path is tested with Prefect, DBOS and Temporal, including replay. Ran ruff (whole repo), pyright on the changed packages, the detect_loops tests on 3.13 and 3.14 with 100% coverage of the source, and the detect-loops docs examples. The full tests/harness run had 14 failures in other capabilities, caused by my local environment: sandbox exit 126 instead of 127, and Temporal RPC flakes under xdist.
What changes for existing users: the new checks are on by default. A response that repeats a passage at least 8 times in a row (2000+ characters), or makes the same call 5 times, is now stopped and retried, or rejected and retried if it wasn't streamed. Everything else behaves as before.
PR decisions
2026-11-02 · in-response nudge stops the stream via ModelRetry · iter -
- Decision: A loop within a response enqueues the usual origin-tagged SystemPromptPart nudge and raises ModelRetry from wrap_model_request, which abandons the stream through core's existing path and retries the request
- Why: Core has no other supported way to restart a streamed request; RetryModelRequest is rejected once a stream reached the consumer. Mike asked for nudge semantics/origin consistent with the existing nudge
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · DetectLoops never forces streaming · iter -
- Decision: has_wrap_run_event_stream returns False; a response that isn't streamed is checked whole when it arrives, at the same offsets
- Why: Forcing streaming would change behavior for every plain agent.run() user (precedent: CodeMode gates the same property)
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · LoopJudge is skipped in durable workflow code · iter -
- Decision: Under Temporal/DBOS/Prefect the response is checked whole in workflow code with the heuristic only; the judge model is never called there
- Why: A model call in workflow code is not checkpointed and could repeat on replay; a judge failure must never break the run, so skipping beats TrajectoryJudge's UserError
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · pre-push review 1 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -
- Decision: reserved
- Why: tree 41b9c076dc4b24e7e6b9e887f369615e0eb455f6; full branch vs merge-base 129c94ef29
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · pre-push review 1 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -
- Decision: no review: reviewer could not read the bundle outside the project root
- Why: tree 41b9c076dc4b24e7e6b9e887f369615e0eb455f6; bundle moved under the ignored .pydantic-ai-harness/review/
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · pre-push review 2 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -
- Decision: reserved
- Why: tree 41b9c076dc4b24e7e6b9e887f369615e0eb455f6; full branch vs merge-base 129c94ef29
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · pre-push review 2 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -
- Decision: remediated: 12 findings (double count, run_stream/UsageLimits docs, judge count, dict args, waiter, judge name, durable docs, Temporal/DBOS tests, heuristic wording, error.type, unused helper)
- Why: tree 41b9c076dc4b24e7e6b9e887f369615e0eb455f6 reviewed; full branch vs 129c94ef29
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · pre-push review 3 of 3 at 43e248c96d · iter -
- Decision: reserved
- Why: follow-up scope be7b898..43e248c96d plus prior findings
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · pre-push review 3 of 3 at 43e248c96d · iter -
- Decision: remediated: durable judge tests made falsifiable, judge agent named detect_loops, skill reference rewrapped; budget exhausted
- Why: follow-up scope be7b898..43e248c96d (tree a7fdc24e); remediation verified locally on 3.13 and 3.14
- Source: https://github.com/pydantic/pydantic-ai/tree/agent/detect-loops-streaming
2026-11-02 · stricter RepetitionDetector defaults · iter -
- Decision: Mike chose: keep all channels on; min_repeats=8, min_chars=2000, new min_distinct_chars=8
- Why: douwebot showed grids, table rules and identical rows tripping the 4x/400-char defaults; Mike picked the stricter-all-channels option
- Source: https://github.com/pydantic/pydantic-ai/pull/12222#discussion_r4444425329
2026-11-02 · in-response nudge is request-scoped · iter -
- Decision: Mike chose: keep the origin-tagged SystemPromptPart for loops within a response, with scope='request', plus the short ModelRetry feedback
- Why: The response that looped is dropped, so a conversation-scoped nudge would turn a one-off glitch into permanent context (douwebot)
- Source: https://github.com/pydantic/pydantic-ai/pull/12222
2026-11-02 · keep stream_* naming; rename DetectedLoop.repeated_text to passage · iter -
- Decision: Mike chose to keep stream_detector/stream_channels/stream_check_every/StreamSample/StreamChannel/'repeated_stream_text'; the field becomes passage
- Why: Matches Mike's request vocabulary; the field name collided with the 'repeated_text' pattern (douwebot)
- Source: https://github.com/pydantic/pydantic-ai/pull/12222
2026-11-03 · merge origin/main at a7911615df · iter -
- Decision: resolved the one conflict (skill table in CONTROL-AND-SAFETY.md) by keeping this PR's
DetectLoopsrow and main's newRefineOutputrow; moved theLoopPatternAPI waiver to the v2.68.0 baseline the API check now uses - Why: union of two adjacent docs rows plus a mechanical waiver bump changes no code, so no local pre-push review was dispatched (budget already exhausted); douwebot re-reviews the new head
- Source: https://github.com/pydantic/pydantic-ai/pull/12222
2026-11-03 · douwebot round on a7911615df · iter -
- Decision: added eager
ValueErrorfor unknownstream_channels(7e84c0a35c); keptLoopJudgeandRepetitionDetectorsubmodule-only - Why: matches the class's other eager validation; the top level exports only capabilities, and
DetectedLoop/LoopDetectedErrorare already submodule-only. Pre-push review budget was exhausted, so the fix was verified locally (targeted tests, pyright) and pushed - Source: https://github.com/pydantic/pydantic-ai/pull/12222#discussion_r4564461145
2026-11-03 · douwebot round on 7e84c0a35c · iter -
- Decision:
test_channels_can_be_turned_offstreams 40 chunks so it fails if the channel filter is ignored;LoopJudgerejectsmax_chars < 1(f2fc1bddf0) - Why: both verified (the test passed with the filter disabled;
[-0:]slices the whole sample). Pre-push budget exhausted, so verified locally and pushed - Source: https://github.com/pydantic/pydantic-ai/pull/12222#discussion_r4564733175
2026-11-03 · douwebot round on f2fc1bddf0 · iter -
- Decision:
LoopJudgerejects a judgeagentwith output validators, likeTrajectoryJudge; docs say aLoopDetectorinstance is shared across runs (b1a3493592). Lefttest_the_nudge_reaches_only_the_retried_requestunmarked - Why: the validator check turns a silent heuristic fallback into a construction error. The prefix checker ran on that test and found no violation, so a
moves_cache_prefixexemption would only hide a future one - Source: https://github.com/pydantic/pydantic-ai/pull/12222#discussion_r4565548235
2026-11-04 · merge origin/main at e635129ba2 · iter -
- Decision: took main's
tests/harness/conftest.py(dropping the eagerask_user/detect_loops/planningimports) and main'stests.conftestimport intest_dbos.py, keeping this PR's message andLoopJudgeimports - Why: #12450 removed
register_tag's late-registration warning, so the eager imports are no longer needed; main droppeddetach_dbos_logging/without_admin_server - Source: https://github.com/pydantic/pydantic-ai/pull/12222
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.