Connecting Agents to Tool Calling: From Function Description to Error Fallback

For stable Agent tool calling, first fix the tool contract, then write the scheduling loop: function name, parameter Schema, return structure, error codes, and timeout limits are fixed first; the model only selects tools and fills parameters within the contract. This article provides a modifiable Python skeleton, function description patterns, parameter validation and least privilege, error classification and retry fallback, and a pre-launch acceptance checklist. All addresses and keys in examples are marked as placeholder values.

Agent tool-call flow: function description registration, parameter validation, scheduling loop, tool execution, result return, and error fallback

Key takeaways

  • 1. Fix contract before loop: tool name, parameter Schema, return structure, error codes, and timeout limits are fixed; the model only chooses within the contract.
  • 2. Write function descriptions as 'when to use + when not to use + parameter scope'; keep no more than 8 tools and group them.
  • 3. Validate parameters at the tool gateway; treat model output as untrusted input; require idempotency keys for writes and a human review switch.
  • 4. Classify errors into retry, refill parameters, fail immediately, or human review; do not retry parameter validation or business validation failures.
  • 5. Log task ID, round, tool name, parameter summary, status, input and output Token, duration, and fallback flag to verify gates.
Audience
Backend engineers, platform engineers, and SREs adding internal tools or third-party APIs to Agents in production
Estimated time
About 90 minutes to complete contract definition, scheduling skeleton, and acceptance tests (example estimate; depends on existing gateway and logging systems)
Prerequisites
Available model credentials, tool gateway or service wrappers, structured logs, and the ability to query usage by task

How to implement Agent tool calling: define the contract first, then write the scheduling loop

For Agent tool calling to land reliably, first lock down the tool contract, then write the scheduling loop: function names, parameter JSON Schema, return-value structures, error codes, and timeout limits must be fixed first; the model is only responsible for selecting tools and filling parameters within the contract. Conversely, writing the loop first and adding descriptions later can cause parameter hallucination, duplicate write operations, and failures that cannot be attributed. The scope of this article is as of December 3, 2026; addresses and keys in example code are placeholder values; model capabilities are based on AGTCloud Model Library real-time display.

Treat the contract as an interface definition between services, not part of the prompt: it should be enforced by the gateway, and model output should always be treated as untrusted input. This way, even if the model or prompt changes, validation rules, idempotency keys, and usage limits remain stable.

Contract fieldDefined byMust includeTypical consequence if missing
Tool nameServer sideVerb + object, globally unique across the siteSimilar tools may be mixed up
Parameter SchemaServer sideTypes, required fields, enums, and value rangesParameter hallucination and type errors
Return structureServer sideSuccess fields, error codes, and retryable flagThe model cannot determine the next step
Timeout and usage limitsGateway30-second-level timeout and single-output limitLoop does not converge and usage amplifies
Side-effect descriptionServer sideRead-only / write, and whether an idempotency key is requiredDuplicate submission of business data
Non-applicable conditionsServer sideExplicitly list scenarios where it should not be calledFalse triggering and polling irrelevant tools

The boundary between function descriptions and business descriptions in Agent tool calling

Function descriptions for Agent tool calling are written for the model, while business descriptions are written for humans; the two must not be mixed into one paragraph. A function description should only answer “when to call, how to fill parameters, and when not to call”; business rules, approval criteria, and compliance notes belong to server-side logic and must be validated by code. Putting approval rules into the description effectively downgrades a hard constraint to a sentence the model may ignore.

In practice, keep descriptions to 3–5 sentences and provide each tool with 1 positive example and 1 negative example. Overly long descriptions crowd out context and blur the boundaries between similar tools.

How to write function descriptions for Agent tool calling without false triggering

Function descriptions for Agent tool calling should be written as decidable conditional statements, not capability advertisements. The following is a tool declaration example that can be directly adapted; field meanings are consistent with the comparison table below. The order number and address in the example are placeholder data.

{
  "name": "query_order_status",
  "description": "按订单号查询已受理订单的当前状态。仅当用户提供了完整订单号且问题是状态时调用;查询物流轨迹、退款进度或历史订单列表时不要调用本工具。",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {"type": "string", "pattern": "^ORD-[0-9]{8}$"},
      "include_history": {"type": "boolean", "default": false}
    },
    "required": ["order_id"],
    "additionalProperties": false
  },
  "returns": {"status": "CREATED|PAID|SHIPPED|CLOSED", "updated_at": "ISO-8601"},
  "side_effect": "read_only",
  "timeout_seconds": 30
}
Description styleFalse-trigger riskBasis for judgmentRecommendation
“Query order information”High: status, logistics, and refunds may all matchNo mutually exclusive conditionsAdd non-applicable conditions
“Universal query tool”High: any question may be selectedCapability boundary is too broadSplit into multiple tools by business object
State parameter format and value rangeLow: parameter errors are blocked at the gatewaySchema can validateRecommended
State read-only or write side effectsLow: write operations are separately controlledThe gateway can add idempotency keys accordinglyRecommended
Put approval rules into the descriptionMedium-high: the model may ignore themNo code validationMove to server-side rule nodes
Similar tools share the same descriptionHigh: selection becomes randomizedMissing mutually exclusive statementsEach includes a “when not to use” sentence

The total number of tools should also be constrained: keep visible tools per task to 8 or fewer, and mount them by business domain groups when exceeded. The more selectable tools there are, the higher the probability of wrong selection, while descriptions in each prompt turn also linearly crowd out context space.

Parameter validation and least privilege for Agent tool calling

Parameter validation for Agent tool calling must be placed at the tool gateway; it cannot rely only on the model’s self-constraint. The gateway validates types, required fields, enums, and value ranges according to the Schema. On validation failure, it returns the original error to the model for refilling rather than silently correcting it or continuing execution. Write operations must additionally enforce idempotency keys, and the manual-review switch should be placed on the server side.

Tool levelTypical operationsWhat the gateway must doWhether automatic retry is allowed
Read-only queryCheck status, check configuration, and retrieve documentsParameter validation + result count limitRetryable, limited to 2 times
Read-only external callThird-party API queries30-second timeout + result cachingRetryable with backoff
Internal writeCreate tickets and update statusIdempotency key + permission validation + audit trailNo automatic retry
High-impact writeRefunds, batch changes, and outbound sendingManual review + secondary confirmationNo automatic retry
  1. First classify: label each tool as read-only / write / high-impact write; the level determines gateway policy rather than being decided by the model at runtime.

  2. Then validate: parameter Schema, value ranges, and business-key formats are implemented uniformly at the gateway; the error return structure is fixed to three fields: code + message + retryable.

  3. Then authorize: issue the minimum visible tool set according to task identity; unauthorized tools do not appear in the prompt and are rejected from the gateway side.

  4. Keep evidence: record task ID, round, tool name, parameter summary, and idempotency key for each call, for retrospectives and usage reconciliation.

Scheduling loop example for Agent tool calling: a runnable Python skeleton

The scheduling loop for Agent tool calling must simultaneously handle three things: return tool results to the model, check hard constraints before each round, and enforce validation and idempotency at the tool gateway. The following Python skeleton includes a local tool registry and can be run directly for self-testing; the model-call part is represented by placeholder functions and can be replaced with your own client. Addresses and keys in the example are placeholder values.

import json
import time

BASE_URL = "https://api.example.com/v1"   # 占位地址,替换为你自己的服务
API_KEY = "YOUR_API_KEY"                  # 占位密钥,不要写进代码库

TOOLS = {
    "query_order_status": {
        "side_effect": "read_only",
        "schema": lambda a: isinstance(a.get("order_id"), str)
                           and a["order_id"].startswith("ORD-"),
    },
}

def call_model(messages, tools):
    """占位:替换为实际的模型客户端,返回 {'tool': name, 'args': dict} 或 {'final': str}"""
    raise NotImplementedError("接入你使用的模型客户端")

def run_tool(name, args, seen_keys):
    spec = TOOLS.get(name)
    if not spec:
        return {"code": "UNKNOWN_TOOL", "retryable": False}
    if not spec["schema"](args):
        return {"code": "SCHEMA_INVALID", "retryable": False,
                "message": "order_id 必须是 ORD- 开头的字符串"}
    if spec["side_effect"] != "read_only":
        key = args.get("idempotency_key")
        if not key or key in seen_keys:
            return {"code": "DUPLICATE_WRITE", "retryable": False}
        seen_keys.add(key)
    return {"code": "OK", "data": {"status": "PAID"}}

def run_agent(goal, max_rounds=6, timeout_seconds=30, max_output_tokens=800):
    messages = [{"role": "user", "content": goal}]
    seen_keys = set()
    started = time.time()
    for rnd in range(1, max_rounds + 1):
        if time.time() - started > timeout_seconds * max_rounds:
            return {"final": "", "degraded": "budget_exceeded", "rounds": rnd - 1}
        decision = call_model(messages, list(TOOLS))
        if "final" in decision:
            return {"final": decision["final"], "rounds": rnd}
        result = run_tool(decision["tool"], decision.get("args", {}), seen_keys)
        messages.append({"role": "tool", "content": json.dumps(result, ensure_ascii=False)})
        print(f"round={rnd} tool={decision['tool']} code={result['code']}")
    return {"final": "", "degraded": "max_rounds", "rounds": max_rounds}

if __name__ == "__main__":
    print(run_tool("query_order_status", {"order_id": "ORD-00000001"}, set()))
    print(run_tool("query_order_status", {"order_id": "BAD"}, set()))

This skeleton puts three hard constraints in code rather than prompts: round limit, parameter Schema validation, and write-operation idempotency key. `run_tool` is directly runnable; two self-test cases demonstrate valid and invalid parameters respectively. After replacing `call_model` with a real client, the rest of the logic needs no changes. The 6 rounds, 30 seconds, and 800 Token in the example are example assumed values and should be adjusted according to canary logs.

Call-count example under Agent tool-calling assumptions

Capacity estimation for Agent tool calling can align expectations with pure arithmetic: assume a single-task round limit of 6 rounds, at most 3 tool calls per round, and retryable errors limited to 2 attempts; in the worst case, one task produces 6 × 3 × 2 = 36 tool requests. If the per-round limit is reduced to 2, the worst-case value drops to 24. Further assume that 20% of an average of 2,000 daily tasks trigger retries; the additional requests caused by retries are about 2,000 × 20% × 2 = 800. All of the above are example assumptions, used to show how parameters enter the estimation formula, and do not represent business measured values or any quote.

The key point of the example is that amplification comes from three configurable multipliers: rounds, calls per round, and retries. All three are on the engineering side; tuning them first is easier to validate than switching models first, and does not trigger effect regression testing.

Error classification and retry fallback for Agent tool calling

Error fallback for Agent tool calling should route by error type rather than uniformly 'try again'. The gateway returns a fixed structure with three fields: code, message, and retryable. The scheduler uses it to decide whether to retry, refill parameters, fail immediately, or escalate to manual handling. The model receives only the structured raw error, not a vague 'call failed'.

Example error codesCategoryScheduler actionAttempt limit
TIMEOUT / 429 / 5XXRetryableRetry with exponential backoff after 1 second → 2 seconds → 4 seconds2 attempts
SCHEMA_INVALIDRefill parametersReturn the raw message to the model to refill parameters2 attempts
BUSINESS_VALIDATION_FAILEDFail immediatelyReturn the business error and do not retry1 attempt
PERMISSION_DENIEDFail immediatelyEscalate to the manual authorization process1 attempt
DUPLICATE_WRITEEscalate to manual handlingAlert and send to the review queue1 attempt
MAX_ROUNDS / BUDGET_EXCEEDEDDegradeReturn the results already obtained and mark them as degradedDo not retry
RETRYABLE = {"TIMEOUT", "429", "5XX"}
REFILLABLE = {"SCHEMA_INVALID"}

def handle(result, attempt):
    code = result.get("code")
    if code == "OK":
        return "continue"
    if code in RETRYABLE and attempt < 2:
        return "retry_with_backoff"
    if code in REFILLABLE and attempt < 2:
        return "refill_args"          # 把 result['message'] 原文回传给模型
    if code in {"DUPLICATE_WRITE", "MAX_ROUNDS", "BUDGET_EXCEEDED"}:
        return "human_review"
    return "fail_fast"                # 业务校验失败、权限不足一律立即返回

# 说明:2 次尝试与退避间隔是示例假设值;关键是类别白名单显式可测,
# 而不是把「是否重试」交给模型自行判断。

Writing categories as sets instead of scattering if-else branches through business code makes it easy to validate with paired cases: a retryable error should trigger backoff, and a business validation error should return immediately. '0 blocked' in validation logic does not mean it is effective; you must see both 'what should be blocked is blocked' and 'what should pass is passed'.

Determining retryable and non-retryable errors in Agent tool calling

Agent tool calling distinguishes retryable from non-retryable by asking whether one retry could change the result. Timeouts, rate limiting, and 5xx are temporary external states, so retrying is meaningful. Parameter format errors, business validation failures, and insufficient permissions are deterministic outcomes; retrying any number of times produces the same result, only duplicating billing and amplifying log noise. The decision should be provided by the gateway in the retryable field; the model does not participate.

A case easily misclassified is 'the tool returns an empty result': it may be due to incorrect query conditions, or the data may genuinely not exist. A safer approach is to classify it as a refill-parameters case, limit it to 2 attempts, and return the raw empty result, rather than putting it in the retryable category and repeatedly requesting.

Timeout, idempotency, and usage gates for Agent tool calling

The three gates for Agent tool calling should be centrally managed in the same configuration file: single-call timeout, write-operation idempotency key, and task-level usage limit. Central configuration makes it possible to change only one place during canary releases and lets monitoring read it directly; limits scattered across prompts and business code are often found to have no effect only during load testing.

# 示例配置(示例假设值,非生产默认值)
tools:
  timeout_seconds: 30
  max_calls_per_round: 3
  require_idempotency_key_for_write: true
  auto_retry_write: false
agent:
  max_rounds: 6
  max_output_tokens: 800
retry:
  max_attempts: 2
  backoff: [1s, 2s, 4s]
  never_retry: [SCHEMA_INVALID, BUSINESS_VALIDATION_FAILED, PERMISSION_DENIED]
budget:
  max_input_tokens_per_task: 4000
  max_total_tokens_per_task: 8000
  on_exceeded: return_partial_with_degraded_flag
observability:
  per_round_fields: [task_id, round, tool, args_digest, code, retryable, in_tokens, out_tokens, elapsed_ms]

The max_total_tokens_per_task in the configuration must be rechecked before each round, not only once at the task entry point: during timeout retries, output already generated from the previous attempt may still count toward usage. Match actual usage by task ID with AGTCloud console time-period data for cross-checking, to confirm the counter has not missed records.

Observability for Agent tool calling: locating issues with one log table

The most time-consuming part of troubleshooting Agent tool calling is not fixing bugs but reconstructing the scene. Persisting 9 fixed fields per round can separate five classes of issues—wrong tool selected by the model, parameter hallucination, abnormal tool return, non-converging loops, and usage amplification—without replaying the entire conversation.

FieldWhat is recordedProblems that can be locatedVerification method
task_idUnique task IDChain failed calls across servicesAlign with the main state of the workflow engine
roundCurrent round numberNon-converging loops, round-limit failureCompute the proportion of tasks that hit the limit
toolTool name selected in this roundTool misselection, ambiguous description boundariesAggregate misselection rate by tool
args_digestParameter digest (masked)Parameter hallucination, format errorsCompare with Schema validation logs
code / retryableGateway return code and whether it is retryableWhether error classification takes effectValidation with paired cases
in_tokens / out_tokensThis round's input and output tokensUsage amplification and context expansionCross-check with console usage
elapsed_msThis round's elapsed timeTimeouts and serial latencyView long tail by percentile
degradedWhether degradation is triggeredWhether degradation is hidden in success rateCount the proportion of degraded tasks
idempotency_keyIdempotency key for write operationsWhether duplicate submissions are blockedDuplicate-check hit count

Parameter summaries should be masked, retaining only field names and schema validation conclusions, and not storing business plaintext. This meets troubleshooting needs while avoiding writing user data into general logging systems.

Acceptance checklist before launching Agent tool calling

Before Agent tool calling enters canary release, use an acceptance table to record evidence item by item. If any item lacks evidence, restrict to read-only canary scope and do not enable write operations. The 7 items below correspond one-to-one to the earlier contracts, permissions, error classification, gates, and logs, making it easy to copy into the release ticket.

No.Acceptance itemPass criteriaEvidence format
1Tool contract completeAll 6 contract fields are definedTool registry snippet
2Parameter validation at the gatewayInvalid parameters are intercepted and return SCHEMA_INVALIDPaired test cases
3Write operation idempotencyThe second request with the same idempotency key is blocked by DUPLICATE_WRITEGateway interception logs
4No-retry list effectiveBusiness validation errors are attempted only onceError classification cases
5Round and usage gates effectiveTasks that hit the cap return a degraded markerLoad test logs
6All 9 log fields are presentA failed trace can be fully reconstructedLog sample
7No hard-coded unit prices or parametersBoth the article and code read definitions from the model libraryCode review record
  1. Run normal cases first: valid parameters pass in one attempt, and check whether log fields are complete.

  2. Run parameter cases next: invalid parameters are intercepted by the gateway, and parameter re-entry stops after at most 2 attempts.

  3. Run timeout cases next: after consecutive timeouts, cumulative call count is capped, and usage does not exceed 2 times the single-call cap.

  4. Run budget cases last: when budget is exhausted, return partial results with a degraded marker instead of failing silently.

How to continue validating Agent tool calling on AGTCloud

Post-launch validation of Agent tool calling is recommended in three steps: in the AGTCloud model library verify candidate models' context length and capability definitions, and judge whether tool descriptions and multi-turn results will crowd out output space; in the AGTCloud console use a sample request to confirm that input and output tokens are recorded separately; then integrate the 9 log fields and acceptance table from this article into canary retrospectives, comparing actual usage with counter readings by task ID.

Parameter tuning order should also start from the engineering side: first reduce the per-round tool call cap from 3 to 2, add parameter validation errors to the no-retry list, and add idempotency keys to write operations; these changes can be canary-released, rolled back, and measured. Model switching changes both effectiveness and cost, so it should be done last, and after re-checking definitions in the AGTCloud model library run regression tests.

The division of labor in AGTCloud can be summarized in one sentence: articles and code are responsible for stable contracts, formulas, and decision frameworks, while the model library is responsible for changing capability and pricing data. When the two are not mixed, tool calling implementations can withstand load testing and will not become outdated after price adjustments or model upgrades.

Docs ↗

Frequently asked questions

Describe four items: what it does, when to use it, when not to use it, and parameter scope. Write differences between easily confused tools as one mutually exclusive condition. For example, order status and logistics tracking should specify returned fields and time-range scope, not both say 'query order information'. Adjectives and examples cannot replace clear applicable and non-applicable boundaries.

Source

C

Chen Yizhou

API Engineering

AGTCloud technical column author for API development, focusing on large-model API access, interface compatibility, SDK integration, and application development. Content covers Python API calls, OpenAI-compatible interfaces, streaming output, error handling, concurrency optimization, and development practices, helping developers reduce model access and migration costs.