Learning resourcesReviewed · Pydantic

Pydantic AI Harness: Detect Loops

This guide teaches Python developers to detect loops in Pydantic AI agents, but its default corrective prompt cannot guarantee that an agent stops. It documents DetectLoops, configurable repetition checks, streamed-response interruption, stopping errors and an optional model judge.

Researched 24 Nov 2026

In short.

This guide helps Python developers add loop detection to Pydantic AI agents, but its default reminder does not guarantee a stop. DetectLoops identifies repeated tool activity and repeated passages within model responses. Developers can request a change of approach, end the run with an error or supply a custom handler. The default checks require no second model; an optional LoopJudge adds model calls and latency. Intentional polling and repetitive file content need careful configuration. The page supplies detailed behavior and examples, but detection accuracy, runtime overhead, actual costs and compatibility with a specific installed release remain unassessed.

Researched and written by an AI model and checked by a second AI model. How it works

Covers the complete documentation page at [https://pydantic.dev/docs/ai/harness/detect-loops/index.md], including usage, detection rules, examples, API reference and the 0.x compatibility warning. Linked pages, the documentation index, repository source, package metadata and provider documentation are excluded. Installation, example execution, detection accuracy, runtime overhead, durable replay behavior and provider compatibility remain untested.

The overview

Identity

Detect Loops is a documentation guide for the DetectLoops capability in Pydantic AI Harness. Its original address is [https://pydantic.dev/docs/ai/harness/detect-loops/index.md]. It explains how to recognize repetitive agent behavior and intervene before more requests or output are consumed.

The resource combines a usage guide with an inline API reference. The implementation it describes comes from the pydantic-ai-harness Python package and attaches to a Pydantic AI Agent through its capabilities argument.

Assessment

The guide is useful for developers whose agents repeatedly call an unsuccessful tool, alternate between the same actions or generate the same passage indefinitely. It explains comparison rules, default thresholds, intervention choices and interactions with streaming, compaction and durable execution.

Its central limit is that repetition is only one sign of stalled work. The default checks recognize specific patterns; they do not establish whether an agent is making useful progress overall. The page provides no measured detection accuracy, false-positive rate or performance benchmark.

Users

The intended readers are Python developers building autonomous Pydantic AI agents that take many steps. It also covers agents stuck in output-validation retries, where several responses repeat the same text without calling tools.

Beginners need familiarity with an Agent and function tools, meaning application functions the model can call. Experienced developers get details about canonical argument matching, custom detectors, tracing, concurrent runs and workflow replay. The documented integration assumes Pydantic AI; applicability to other agent frameworks is not established.

Capabilities

Across a run, the defaults detect the same tool call five times within the latest ten tool calls; three identical results from successive occurrences of the same call within that window; three alternating A-B cycles; or three consecutive responses with no tool calls and matching text after ignoring case and whitespace.

Within a response, checks cover repeated thinking, output text and tool arguments. A separate rule detects five identical tool calls in one response before those calls execute. Responses received without streaming undergo the same repetition checks after they arrive.

An intervention can add corrective guidance, raise LoopDetectedError or invoke a custom handler. When instrumentation is enabled, detections also emit trace spans identifying the pattern, action, count, window and involved tools.

Using it

Requirements

The examples require a Python application using Pydantic AI and the pydantic-ai-harness package. A model-backed agent also needs access to its configured model. The page does not establish supported Python versions, exact dependency versions, hardware requirements or provider setup details.

The optional LoopJudge requires a judge model or a supplied judge agent. Custom LoopDetector implementations must be stateless or keep state associated with the RunContext because one detector instance can serve concurrent runs. Under durable execution, custom detectors and handlers must be deterministic and avoid direct input/output operations.

Mechanism

DetectLoops records responses and tool results, then checks the run before the next model request. Tool arguments are compared as canonical JSON with sorted keys. Result comparison includes the outcome, structured content and returned file identifiers. Repeated ModelRetry messages can therefore count as repeated results. Recording happens before other capabilities rewrite messages, so later compaction does not change the recorded comparisons.

At most one cross-response loop is reported per request, in the order repeated_result, alternating_calls, repeated_call and repeated_text. The responses forming a reported loop are then excluded from subsequent counts. Each run starts fresh, including a run supplied with earlier message_history.

The default RepetitionDetector checks each response part every 256 characters and at its end. It requires an exactly repeated passage of 20 to 2,000 characters, at least eight distinct characters, at least eight repetitions and at least 2,000 repeated characters overall. LoopJudge can confirm suspected repetition or check periodically for less exact loops. Its default timeout is five seconds, after which the heuristic result is used; exceeding usage limits instead ends the run.

Setup

The documented installation commands are pip install pydantic-ai-harness and, alternatively, uv add pydantic-ai-harness. Import Agent from pydantic_ai and DetectLoops from pydantic_ai_harness, then include DetectLoops() in the Agent constructor's capabilities list.

Choose action='error' when detection should end the run, or provide a handler for application-specific behavior. Set individual call or text thresholds to None to disable those checks. window must be at least 2, and each enabled cross-response threshold must be at least 2. repeated_call_threshold and repeated_result_threshold must not exceed window; twice alternating_calls_threshold must not exceed window. repeated_text_threshold does not have to fit within the call window. Invalid configurations raise ValueError.

For passage detection, stream_detector=None disables the text heuristic, while stream_channels selects thinking, text and tool arguments. DetectLoops does not itself make an agent stream.

Example

The page includes a deterministic FunctionModel example that always requests read_file with path missing.txt. The tool always returns the same file-not-found message. With DetectLoops(action='error'), the documented expected exception identifies repeated_result, tool read_file and count three.

A practical complication is intentional polling. An unchanged status returned three times can trigger repeated_result, and unchanged call arguments can trigger repeated_call after five occurrences within the default window. Adding elapsed time to the result changes result matching, but repeated_call still ignores the result and may need separate adjustment.

Assessment & evidence

Limitations

Exact matching misses repetition that changes slightly on each pass. Legitimate polling or large repetitive fixtures can trigger detection. Cross-response call comparison covers function tools, excluding provider-run native tools. Within-response argument checks cover function and output tools, also excluding native tools.

A default nudge can be ignored. Within-response nudges stop and retry the response, consuming output retries, but run_stream() cannot retry once output has started streaming. A loop detected after that point ends with UnexpectedModelBehavior. The guide recommends agent.run() with an event_stream_handler or agent.iter() when output loops must also be retried.

Under durable execution, response checks happen after the complete response reaches workflow code, so they cannot stop generation early. LoopJudge uses only its deterministic heuristic there. DetectLoops also does not resolve repeated context-window overflow, truncate history, restart a run or roll back actions.

Practical reasoning

The intervention should match the consequence of continued repetition. A corrective prompt gives the model an opportunity to recover. An error provides a defined stopping behavior for detected patterns. A custom handler can apply application-specific guidance, but for a loop within a response, merely returning from that handler allows streaming to continue.

The page supports using multiple DetectLoops capabilities independently, such as a lower threshold that nudges and a higher threshold that ends the run. This provides a documented escalation approach. Budget limits remain useful alongside it because repetitive work can evade the configured patterns, and interrupted streams have the accounting limitation described above.

Alternatives and complements

The page describes System Reminders as a way to reintroduce guidance on a cadence or condition, and Trajectory Judge as a second model that assesses whether a run is on track. These address guidance and broader progress assessment. Their linked documentation, costs and effectiveness are not established by this page.

Within DetectLoops, alternatives include the default deterministic heuristic, LoopJudge and a custom LoopDetector. For context-window problems, the page points to compaction and application handlers. It supplies no comparative evaluation of competing libraries.

Evidence

The evidence consists of the complete maintainer-hosted Detect Loops page, including installation instructions, explanatory examples, default settings, operational caveats and an API reference. It gives detailed descriptions of intended behavior.

The page supplies no empirical accuracy study, workload benchmark, latency measurement or demonstrated cost saving. Its example outputs are documentation expectations. Installation, examples and runtime behavior were not executed or tested.

Access & freshness

Costs

Package charges, model prices, detector overhead and achievable savings are unknown from this page. The default heuristic uses no second model. Corrective retries can still require further model requests.

LoopJudge adds model usage to the run and makes the stream wait for each judgment. Its requests operate within UsageLimits, with the pending main request reserved. A judge request that would exceed those limits raises UsageLimitExceeded rather than falling back to the heuristic.

The page states that an interrupted streamed response contributes no request or tokens to the run's usage accounting. It does not establish whether a provider bills for that interrupted generation, so reported run usage alone cannot establish total monetary cost.

Rights and data handling

The page links to implementation source at [https://github.com/pydantic/pydantic-ai/tree/main/src/pydantic_ai_harness/pydantic_ai_harness/detect_loops/]. It supplies no licence text establishing commercial-use or redistribution permissions for the package or documentation. Those permissions remain unknown from this evidence.

LoopJudge receives the latest portion of the response part, up to 4,000 characters by default. Provider retention and data-use terms are not described. Trace spans omit arguments, results, response text and fingerprints unless trace_include_content is enabled. The page warns that short values can be recovered from fingerprints by hashing candidate values; a supplied judge agent also retains its own instrumentation settings.

Freshness

The supplied page was captured on 24 November 2026 at 01:39:16 UTC. Its publication date, last modification date and exact corresponding package release are not established.

The page warns that Pydantic AI Harness APIs may change between minor releases while on 0.x versions, with deprecation warnings and migration guidance described as the upgrade mechanism. Compatibility with a particular installed release or model provider remains unknown.

Suggested next steps

Identify which repeated actions are legitimate in your application, particularly polling, retries and repetitive file generation. Choose thresholds and enabled channels around those behaviors, then decide whether each detection should prompt recovery or end the run.

Before deployment, evaluate unsuccessful tool calls, alternating actions, repeated output, intended repetition and the streaming interface you actually use. Measure detection behavior, added latency and provider spend on that workload. Verify package compatibility and licence terms separately.

If using LoopJudge, establish whether response text and tool arguments may be sent to its model. For durable workflows, account for whole-response detection and keep custom workflow handlers deterministic.

Evidence for this report

selected-page.txtselected · checked 2026-11-24