跳到正文
DEV Community· Belal Shafiq·· 2 小時前AI 評分51

如何使用 AgentTrafficCop SDK 1.2.0 以雜湊偵測 AI 智能體循環,避免傳送原始操作內容

How to Detect AI Agent Loops Without Sending Sensitive Payloads

AI 導讀

AgentTrafficCop SDK 1.2.0 可透過 hash_only=True 在本地計算操作內容的 SHA-256 雜湊值,偵測完全重複的工具呼叫及重複序列,而不向服務傳送原始操作內容。

正文

Your agent keeps calling the same tool with the same arguments. Every request succeeds, so retries are not the problem. You want to reject the next repeated action—but you do not want to send customer records, internal documents, or private prompts to another service.

For exact repeats and repeating sequences, you can compare locally calculated hashes instead of transmitting raw action contents. AgentTrafficCop SDK 1.2.0 provides this through hash_only=True. Your code still has to place the check before the action and stop on rejection.

This guide gets you to a working test first, then explains what this approach cannot protect. It is not semantic loop detection, automatic instrumentation, or a guarantee of anonymous processing.

Disclosure: I’m building AgentTrafficCop, the tool used in this example.

Quick start: reject repeated tool calls in Python

Install or upgrade the SDK, then set your API key in the environment.

Use a test key: the example makes real guard requests, consumes approved-message quota, and may add the two named agents to your tracked-agent allowance. It does not call a model or execute a tool.

python -m pip install --upgrade 'agenttrafficcop==1.2.0'
export ATC_API_KEY="your-api-key"
import os
import uuid

from agenttrafficcop import AgentTrafficCopError, GuardSync


def main():
    run_id = uuid.uuid4().hex
    action = {
        "tool": "search_docs",
        "arguments": {"query": "refund policy"},
    }

    with GuardSync(
        url="https://api.agenttrafficcop.com",
        api_key=os.environ["ATC_API_KEY"],
        dry_run=False,
    ) as guard:
        for attempt in range(1, 4):
            try:
                result = guard.check(
                    session_id=run_id,
                    sender="planner",
                    recipient="researcher",
                    intent="tool_call",
                    payload=action,
                    hash_only=True,
                )
            except AgentTrafficCopError as exc:
                print("Action not executed:", exc.error_code)
                break

            if not result.approved:
                break

            # Replace this print with the protected tool invocation.
            print("Approved attempt", attempt)


if __name__ == "__main__":
    main()

With the default repeat threshold of three, a fresh session, and no other blocking policy, the first two checks are approved and the third is rejected with REPEATED_PAYLOAD_LOOP. Custom thresholds can change that result.

Expected console output under those defaults:

Approved attempt 1
Approved attempt 2
Action not executed: REPEATED_PAYLOAD_LOOP

A different error is not a successful loop test. Authentication, exhausted quota, agent limits, or an unavailable service can prevent the example from reaching its third check. Diagnose that response rather than treating every rejection as loop detection.

Replace the approval print with your actual protected operation. Keep the guard before execution, preserve failures, and use one stable session ID throughout the run.

The service cannot stop an operation that bypasses the check or undo work already completed.

Where the guard belongs in a real agent loop

Put it after the application has selected a tool and its arguments, but before invoking that tool.

Hash the action you are about to execute—not an unrelated status message. Only invoke the tool after approval. If an exception escapes the example, do not catch it higher up and execute the tool anyway.

A check before a tool does not protect the earlier model call used to choose that tool. If you also need to guard repeated model requests, add a check at that boundary.

There is no automatic protection for work outside the paths you guard.

Should you use hash-only checks?

  • Use them when your trusted application needs exact-repeat, sequence, or step checks and wants to avoid transmitting raw action contents.
  • Keep raw mode when you need the service to inspect and validate the original payload representation. In hash-only mode, it can validate the envelope and hash format, not the underlying contents.
  • Do not rely on them alone when agents rephrase the same request, repeated actions are legitimately required, or untrusted code controls the submitted hashes.
  • Do not add another service just for hashing. A local counter or framework termination rule may be enough for a simple single-process loop. A hosted guard is useful when you want centralized decisions and recorded evidence across guarded integrations; it still introduces a network dependency.

What leaves your application?

In ordinary mode, the application submits a payload and the server calculates its hash.

In hash-only mode, the SDK calculates the SHA-256 digest locally and sends that digest instead. The action payload is omitted from the outgoing request.

Session IDs, sender and recipient names, intent, and the digest still leave your application. Keep sensitive information out of those identifiers. The SDK rejects metadata in hash-only mode rather than transmitting it alongside the hash.

Hash-only means less raw data transmitted. It does not mean anonymous, encrypted, or zero-data processing.

Why a hash is enough for some loop checks

Two identical canonical payloads produce the same digest. A sequence such as A → B → A → B also produces a repeating digest sequence.

The detector can compare those values without reading the original action.

  • Consecutive repeats: count identical adjacent digests.
  • Repeating cycles: inspect recurring digest sequences within configured bounds.
  • Step limits: count approved checks, independent of payload contents.
  • Schema changes: use a separately submitted schema hash on eligible plans.

This is deterministic comparison, not semantic understanding. Two differently worded requests can mean the same thing without producing the same digest.

A repeated action can also be intentional; a detector decision is evidence to investigate, not proof of a software defect.

Choose a payload that represents the action

The SDK uses sorted JSON keys, compact separators, unescaped Unicode, and UTF-8 encoding before SHA-256. This avoids a different hash solely because object keys were inserted in a different order.

It is not a universal cross-language canonicalization standard.

Timestamps, random IDs, and other changing values are not automatically removed. If every submitted payload includes a new random identifier, exact-repeat detection may miss repeated work.

On the other hand, stripping meaningful arguments can make distinct actions appear identical. Decide which fields define the action before relying on its digest.

The SDK rejects unsupported JSON values and non-finite numbers in hash-only mode. It never automatically falls back to raw transmission if an older backend rejects the request format.

Start with shadow mode when repetition may be legitimate

Add mode="shadow" to the check to observe supported detector warnings without rejecting actions for those detections.

Inspect result.would_block and result.shadow_decision before deciding to enable enforcement.

Shadow mode still enforces:

  • Authentication
  • Input validation
  • Quotas
  • Rate limits
  • Spending blocks

It consumes normal approved-message quota. It is not the legacy dry_run option; keep that option disabled for server-side evaluation.

Shadow and enforcement histories are separate. Switching to enforcement does not replay the shadow history.

Changing only between raw and hash-only representations does not reset detector history when their digests match within the same mode, key, and run.

What this will not fix

The server cannot validate the original action contents or verify that the submitted digest corresponds to the action actually executed.

Hash-only checks rely on a trusted application supplying consistent hashes. An untrusted caller can change a digest, just as it can misrepresent an action.

Hashes reveal equality, and predictable inputs can be guessed by hashing candidate values. Identical action payloads also hash identically even when the surrounding world has changed; intentional polling or retrying may need a different workflow policy.

Do not treat SHA-256 as a substitute for access controls or as a guarantee of anonymization. Existing raw requests are not made private retroactively.

Run budgets and rolling spend limits still apply, but hashing does not measure costs. Spending controls need an authorized cost-reporting integration, and delayed reports or in-flight actions can cause overshoot.

They are not provider-side hard spending caps.

What to verify in your integration

  1. Inspect a test request and confirm that neither raw payload nor metadata is sent.
  2. Test repeated and genuinely different actions with fresh run IDs.
  3. Verify that a rejected check prevents your tool or model call.
  4. Review shadow warnings before choosing enforcement thresholds.
  5. Check which execution paths your framework adapter actually covers. Adapters do not automatically opt into hash-only mode.

Hash-only checks are useful when deterministic repetition signals are enough and raw payload exposure is a concern.

They complement framework termination rules, action validation, and spending controls; they do not replace them.

Start with one repeated action before changing production. Use a test key, inspect the third-check result, and verify your code stops.

來源:DEV Community · dev.to