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.
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
)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
max_calls_per_run | int | No | None | Maximum 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.
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
)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
detect_loops | bool | No | False | Enable loop detection. |
loop_threshold | int | No | 3 | Consecutive 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.
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.