Detect loops in streamed thinking, text and tool call arguments in `DetectLoops`

Merged
MP
18d ago
+1972-73

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):

  • DetectLoops fields: stream_detector (default RepetitionDetector(), None turns it off), stream_channels (('thinking', 'text', 'tool_args')), stream_check_every (256), repeated_parallel_call_threshold (5).
  • New LoopPattern values: repeated_thinking, repeated_stream_text, repeated_tool_args, repeated_parallel_call. New field DetectedLoop.passage, defaulting to None.
  • LoopDetector, the pluggable ABC: async detect(ctx, sample: StreamSample) -> Repetition | None, plus StreamSample, Repetition and StreamChannel.
  • RepetitionDetector, the default heuristic. It reports text that ends in the same passage repeated back to back: min_period=20 to max_period=2000 characters using at least min_distinct_chars=8 different characters, at least min_repeats=8 times, covering at least min_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 every every characters if set. If the judge fails or times out, the heuristic's answer is used and a loop judge failed span is emitted. A judge built from model= 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-tagged SystemPromptPart, request-scoped this time because the response that looped is dropped, then raises ModelRetry from wrap_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 raises LoopDetectedError.
  • 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. DetectLoops never forces streaming (has_wrap_run_event_stream is False).
  • Under Temporal, DBOS and Prefect, each response is checked whole in workflow code, and LoopJudge never 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 -

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 -

2026-11-02 · pre-push review 1 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -

2026-11-02 · pre-push review 2 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -

2026-11-02 · pre-push review 2 of 3 at be7b898057407683da3a93f9534ecaed97aa0fbe · iter -

2026-11-02 · pre-push review 3 of 3 at 43e248c96d · iter -

2026-11-02 · pre-push review 3 of 3 at 43e248c96d · iter -

2026-11-02 · stricter RepetitionDetector defaults · iter -

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 DetectLoops row and main's new RefineOutput row; moved the LoopPattern API 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 ValueError for unknown stream_channels (7e84c0a35c); kept LoopJudge and RepetitionDetector submodule-only
  • Why: matches the class's other eager validation; the top level exports only capabilities, and DetectedLoop/LoopDetectedError are 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 -

2026-11-03 · douwebot round on f2fc1bddf0 · iter -

  • Decision: LoopJudge rejects a judge agent with output validators, like TrajectoryJudge; docs say a LoopDetector instance is shared across runs (b1a3493592). Left test_the_nudge_reaches_only_the_retried_request unmarked
  • 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_prefix exemption 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 eager ask_user/detect_loops/planning imports) and main's tests.conftest import in test_dbos.py, keeping this PR's message and LoopJudge imports
  • Why: #12450 removed register_tag's late-registration warning, so the eager imports are no longer needed; main dropped detach_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.