Anvia
Agents

Turn Limits and Cancellation

Bound agent runs and stop work safely.

Turn limits keep model-tool loops bounded. Cancellation lets hooks stop a run before unsafe or unwanted work continues.

Set a Default Turn Limit

const agent = new AgentBuilder("support", model)
  .tool(lookupOrder)
  .defaultMaxTurns(3)
  .build();

For a simple tool flow, 3 is usually enough:

  1. model decides to call a tool
  2. Anvia returns the tool result
  3. model writes the final answer

Override Per Prompt

const response = await agent
  .prompt("Where is order A-100?")
  .maxTurns(2)
  .send();

Use request-level limits when a specific workflow should be stricter than the agent default.

Handle Max Turns

If the model keeps calling tools past the limit, Anvia throws MaxTurnsError.

import { MaxTurnsError } from "@anvia/core";

try {
  await agent.prompt(userInput).send();
} catch (error) {
  if (error instanceof MaxTurnsError) {
    logger.warn({ messages: error.messages }, "agent exceeded max turns");
  }

  throw error;
}

Keep the stored messages from the error only if your product wants to preserve incomplete runs.

Cancel With Hooks

import { PromptCancelledError, cancelPrompt, createHook } from "@anvia/core";

const hook = createHook({
  onCompletionCall({ prompt }) {
    if (containsSensitiveData(prompt)) {
      return cancelPrompt("Sensitive data is not allowed in this workflow.");
    }
  },
});

try {
  await agent.prompt(userInput).withHook(hook).send();
} catch (error) {
  if (error instanceof PromptCancelledError) {
    return {
      message: "This request cannot be processed.",
    };
  }

  throw error;
}

Cancellation stops the run and prevents the next model or tool action.

Skip Instead of Cancel

Use skipTool(...) when only one tool call should be blocked and the model can still continue.

const hook = createHook({
  onToolCall({ toolName }) {
    if (toolName === "refund_order" && !currentUser.canRefund) {
      return skipTool("Current user cannot create refunds.");
    }
  },
});

Use cancellation when the whole prompt should stop. Use skip when the run can continue with a safe tool result.