Skip to content

Loop gate

$0.001 per callUSDC via x402POST /api/loop-gate

Decides whether an agent loop should run another iteration.

Category: AI & computeTags: ai agent loop judgment budget stopAlso found as: should-continue loop-check iteration-gate

Try in playground →

Details

Returns decision (continue, stop or escalate), reason, confidence (0 to 1), the checks behind it and nextStep (iterate, change_approach, narrow_scope, verify_result, hand_off). Send the goal, lastOutput and iteration, and optionally maxIterations, a budget { spentUsd, maxUsd }, history (up to 20 of { iteration, summary }) and constraints. The budget and iteration checks run in code before anything else: when either trips the answer is stop, no model is consulted and goalMet and model are null, at the same price. Repeating and stuck outputs are found lexically. Otherwise a typed judgment model (the /v1/judge backends) answers; model names which served. Model-backed, not deterministic, except the budget and iteration checks.

Parameters

NameTypeRequiredDescription
goalstringyesWhat the loop is trying to accomplish. Up to 600 characters. Up to 600 characters.
lastOutputstring | objectyesWhat the iteration that just finished produced, or a digest of it. Up to 3000 characters. Up to 3000 characters.
iterationinteger (1-)yesThe number of iterations completed so far (the one that produced lastOutput). At least 1. The example sends 4.
maxIterationsinteger (1-)noOptional. At iteration >= maxIterations the answer is stop, decided in code. At least 1. The example sends 6.
budgetobjectnoOptional { spentUsd, maxUsd }. At spentUsd >= maxUsd the answer is stop, decided in code.
historyarray of objectnoOptional, up to 20 earlier iterations as { iteration, summary }, oldest first; each summary up to 400 characters. Pass the same kind of text you pass as lastOutput so repeats compare like with like. The model reads the newest 5; all are compared lexically.
constraintsarray of stringnoOptional, up to 8 rules the output must respect, each up to 160 characters. With constraints the model also answers constraintBreached; a breach escalates.

Example request

curl -i -X POST https://agent402.tools/api/loop-gate \
  -H "Content-Type: application/json" \
  -d '{"goal":"Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.","lastOutput":"Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.","iteration":4,"maxIterations":6,"budget":{"spentUsd":0.52,"maxUsd":0.5},"history":[{"iteration":2,"summary":"One study found (Nature Neuroscience 2021)."},{"iteration":3,"summary":"Second study found (Sleep 2023); PubMed search for a third in progress."}]}'

Watch a call get paid

RequestPOST /api/loop-gate
402$0.001 USDC
SignPAYMENT-SIGNATURE
Settleon 14 chains
Answer200 OK
ReceiptAgent402-ReceiptEd25519

Example response

{
  "decision": "stop",
  "reason": "Budget exhausted: spent 0.52 USD of 0.5 USD. No model was consulted.",
  "confidence": 1,
  "checks": {
    "goalMet": null,
    "budgetExceeded": true,
    "iterationsExhausted": false,
    "repeating": false,
    "stuck": false,
    "constraintBreached": false
  },
  "model": null,
  "aiGenerated": true
}
FieldTypeAlways presentIn the example
decisionstringyesstop
reasonstringyesBudget exhausted: spent 0.52 USD of 0.5 USD. No model was consulted.
confidencenumberyes1
checksobjectyes6 fields: goalMet, budgetExceeded, iterationsExhausted, repeating and 2 more
modelnullnonull
aiGeneratedbooleanyestrue

From an MCP client

catalog.call {
  "slug": "loop-gate",
  "params": {
    "goal": "Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.",
    "lastOutput": "Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.",
    "iteration": 4,
    "maxIterations": 6,
    "budget": {
      "spentUsd": 0.52,
      "maxUsd": 0.5
    },
    "history": [
      {
        "iteration": 2,
        "summary": "One study found (Nature Neuroscience 2021)."
      },
      {
        "iteration": 3,
        "summary": "Second study found (Sleep 2023); PubMed search for a third in progress."
      }
    ]
  }
}

Hosted connector (https://agent402.tools/mcp): paid in the call. Stdio package (npx -y agent402-mcp@0.20.0): pays from a wallet or AGENT402_CREDITS_KEY.

Errors and behavior

Paid call (JavaScript agent)

import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const client = new x402Client();
client.setSpendControls?.({ maxAmountPerPayment: "$0.001" }); // refuse any quote above this tool's price
registerExactEvmScheme(client, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
const payFetch = wrapFetchWithPayment(fetch, client);

const res = await payFetch("https://agent402.tools/api/loop-gate", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    "goal": "Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.",
    "lastOutput": "Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.",
    "iteration": 4,
    "maxIterations": 6,
    "budget": {
      "spentUsd": 0.52,
      "maxUsd": 0.5
    },
    "history": [
      {
        "iteration": 2,
        "summary": "One study found (Nature Neuroscience 2021)."
      },
      {
        "iteration": 3,
        "summary": "Second study found (Sleep 2023); PubMed search for a third in progress."
      }
    ]
  }),
});

Get a wallet or run npx -y agent402-mcp@0.20.0 wallet new.

The quote (Python)

import base64, json, urllib.error, urllib.request

req = urllib.request.Request("https://agent402.tools/api/loop-gate", method="POST", data="{\"goal\":\"Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.\",\"lastOutput\":\"Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.\",\"iteration\":4,\"maxIterations\":6,\"budget\":{\"spentUsd\":0.52,\"maxUsd\":0.5},\"history\":[{\"iteration\":2,\"summary\":\"One study found (Nature Neuroscience 2021).\"},{\"iteration\":3,\"summary\":\"Second study found (Sleep 2023); PubMed search for a third in progress.\"}]}".encode(), headers={"Content-Type": "application/json"})
try:
    urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
    quote = json.loads(base64.b64decode(e.headers["PAYMENT-REQUIRED"]))
    print(e.code, [(a["network"], a["amount"]) for a in quote["accepts"]])  # the price, per chain, in base units

Related tools