Guardrails

Guardrails stop an agent on behavioral conditions rather than on a budget dimension. Two guardrails are available:

  • Call count. Terminate the agent after a fixed number of LLM calls.
  • Loop detection. Terminate the agent when it repeats the same call pattern, which signals it is stuck.

Guardrails are enforced independently of budgets and of each other. To cap cost, token count, or runtime, see Budgets.

Call count #

Set max_calls_per_run to limit the number of LLM calls an agent may make. When the limit is reached, AgentKavach terminates the agent and raises CallLimitError. The count is tracked for the lifetime of the AgentKavach instance.

python
from agentkavach import AgentKavach, Budget
from agentkavach.exceptions import CallLimitError

guard = AgentKavach(
    provider="openai",
    api_key="ak_prod_...",
    llm_key="sk-...",
    budget=Budget.daily(50),
    max_calls_per_run=20,   # terminate the agent after 20 calls
)
ParameterTypeRequiredDefaultDescription
max_calls_per_runintNoNoneMaximum number of LLM calls before the agent is terminated. None disables the limit.

Loop detection #

Set detect_loops=True to detect repetitive call patterns that indicate an agent stuck in a loop. When the same pattern repeats loop_threshold consecutive times, AgentKavach terminates the agent and raises LoopDetectedError. Loop detection is off by default.

python
from agentkavach import AgentKavach, Budget
from agentkavach.exceptions import LoopDetectedError

guard = AgentKavach(
    provider="openai",
    api_key="ak_prod_...",
    llm_key="sk-...",
    budget=Budget.daily(50),
    detect_loops=True,
    loop_threshold=5,   # 5 consecutive identical patterns trips the detector
)
ParameterTypeRequiredDefaultDescription
detect_loopsboolNoFalseEnable loop detection.
loop_thresholdintNo3Consecutive identical call patterns before LoopDetectedError is raised.

Combining guardrails and budgets #

Guardrails and budget dimensions can be configured together on one agent. Each is enforced independently, and the first condition to trip terminates the agent.

python
guard = AgentKavach(
    provider="openai",
    api_key="ak_prod_...",
    llm_key="sk-...",
    budget=Budget.daily(100),   # cost dimension
    max_tokens_per_run=500_000, # token-count dimension
    max_runtime_seconds=600,    # duration dimension
    max_calls_per_run=100,      # call-count guardrail
    detect_loops=True,          # loop-detection guardrail
)

ℹ️ First condition wins

With several limits configured, whichever one is reached first terminates the agent. The others stop being evaluated once the agent is terminated. See SDK Reference for the exception each limit raises.