Logo vun Tool Calling Principles

Tool Calling Principles

Communautéit
j4flmao
tool-calling-principles

Use this skill when the user says 'tool calling', 'function calling', 'tool schema', 'JSON schema for tools', 'agent picks wrong tool', 'tool error handling', 'structured outputs', 'tool_use / tool_result'. Designs tool interfaces for LLM agents: naming, descriptions, strict schemas, error contracts, idempotency, output shaping, and permission levels. Do NOT use for: building MCP servers specifically (ai/mcp-patterns and .claude/rules/mcp-server-design.md), the agent loop (ai/ai-agents/core-architectures), or general REST API design (backend/universal/api-design).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummtool-calling-principles
Stären
41
Forks
6
Matgeliwwert Fichieren
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Tool Calling Principles an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/ai-agents/tool-calling-principles
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/ai-agents/tool-calling-principles .claude/skills/tool-calling-principles
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Tool Calling Principles an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Tool Calling Principles automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Tool Calling Principles net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Tool-Calling Principles

Purpose

Tools are the agent's only way to read or change the world, and the model chooses and fills them using nothing but names, descriptions, and schemas. Good tools are few, coarse-grained, strictly typed, safe to retry, and return compact results with actionable errors. This skill gives the rules and templates for designing them.

Agent Protocol

Trigger

"tool calling", "function calling", "tool schema", "tool description", "wrong tool selected", "tool errors", "strict mode", "structured output".

Input Context

  • The operations the agent needs and the underlying APIs.
  • Side effects of each operation (read, reversible write, irreversible).
  • Provider (Anthropic, OpenAI, other) and whether strict schema mode is available.
  • Observed failure transcripts if debugging.

Output Artifact

Tool definitions (JSON Schema), handler skeletons with validation and error contract, permission matrix.

Response Format

Tool: {verb_noun}  Side effect: {read|write-reversible|write-irreversible}  Approval: {none|human}
Description: {what, when to use, when NOT to use, output shape, limits}
Schema: {required fields, enums, formats}
Errors: {code: hint}
Idempotency: {key or natural}

Completion Criteria

  • Small, cohesive tool set; overlapping tools merged or removed.
  • Descriptions say when to use and when not to use.
  • Schemas use enums/formats/required fields; strict mode on where supported.
  • Errors return code + message + corrective hint.
  • Write tools idempotent; irreversible tools gated.

Design Rules

  1. Name by intent: search_orders, refund_order, not api_call or execute.
  2. Coarse over chatty: one get_customer_summary beats five getters the model must chain.
  3. Descriptions are prompts: purpose, when to use, when not to, input semantics, output shape, limits (e.g. "returns at most 20 rows").
  4. Constrain inputs: enum for categorical values, format/pattern for ids and dates, minimum/maximum for numbers, required for everything mandatory, additionalProperties: false.
  5. Flat, primitive arguments: nested objects raise error rates; prefer start_date, end_date over {range: {...}}.
  6. Compact outputs: return only fields the model needs; paginate with a cursor; cap size. Return the new state after a write ("refund R-91 created, status=pending"), not just true.
  7. Errors that teach: {"error": "ORDER_NOT_FOUND", "message": "...", "hint": "use search_orders with the customer's email first"}.
  8. Idempotency: write tools accept an idempotency key or are naturally idempotent (set, not increment).
  9. Least privilege: separate read and write tools so read-only agents never see writes.
  10. Never trust arguments: validate server-side; the schema is guidance to the model, not a security boundary.

Provider Formats

Anthropic Messages API:

json
{
  "name": "refund_order",
  "description": "Refund a delivered order fully or partially. Use only after confirming the order id with search_orders. Not for cancellations of undelivered orders (use cancel_order). Returns refund id and status.",
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": {"type": "string", "pattern": "^ORD-[0-9]{6}$"},
      "amount_cents": {"type": "integer", "minimum": 1},
      "reason": {"type": "string", "enum": ["damaged", "late", "wrong_item", "other"]},
      "idempotency_key": {"type": "string"}
    },
    "required": ["order_id", "amount_cents", "reason", "idempotency_key"],
    "additionalProperties": false
  }
}

The model replies with tool_use blocks (id, name, input); you answer in the next user message with tool_result blocks (tool_use_id, content, optional is_error: true).

OpenAI Chat Completions / Responses: {"type": "function", "function": {"name", "description", "parameters", "strict": true}}. Strict mode requires every property listed in required and additionalProperties: false; model optional fields as nullable types instead.

Handler Template

python
from __future__ import annotations

import json
import logging
from typing import Any

from pydantic import BaseModel, Field, ValidationError

log = logging.getLogger("tools")


class RefundArgs(BaseModel):
    model_config = {"extra": "forbid"}
    order_id: str = Field(pattern=r"^ORD-[0-9]{6}$")
    amount_cents: int = Field(ge=1)
    reason: str = Field(pattern=r"^(damaged|late|wrong_item|other)$")
    idempotency_key: str


def tool_error(code: str, message: str, hint: str) -> str:
    return json.dumps({"error": code, "message": message, "hint": hint})


def handle_refund(raw_args: dict[str, Any], user_id: str) -> tuple[str, bool]:
    """Returns (content, is_error) for a tool_result block."""
    try:
        args = RefundArgs.model_validate(raw_args)
    except ValidationError as exc:
        return tool_error("INVALID_ARGS", str(exc.errors()[:3]), "fix the listed fields and retry"), True

    order = orders_repo.get(args.order_id, owner=user_id)          # authorization in code
    if order is None:
        return tool_error("ORDER_NOT_FOUND", args.order_id, "call search_orders first"), True
    if args.amount_cents > order.total_cents - order.refunded_cents:
        return tool_error("AMOUNT_TOO_HIGH", f"max {order.total_cents - order.refunded_cents}",
                          "refund at most the remaining amount"), True
    try:
        refund = payments.refund(order, args.amount_cents, idempotency_key=args.idempotency_key)
    except payments.TransientError as exc:
        log.warning("refund transient failure order=%s err=%s", args.order_id, exc)
        return tool_error("UPSTREAM_UNAVAILABLE", str(exc), "retry once with the same idempotency_key"), True
    return json.dumps({"refund_id": refund.id, "status": refund.status,
                       "remaining_cents": order.total_cents - order.refunded_cents - args.amount_cents}), False

orders_repo and payments are your application services; the handler owns validation, authorization, and error mapping.

Permission Levels

LevelExamplesControl
Readsearch, get, listRate limit, result caps
Reversible writedraft email, create branchLog + idempotency
Irreversible / externalsend email, pay, delete, deployHuman approval or dry-run + confirm

Debugging Wrong Tool Use

SymptomLikely causeFix
Picks wrong toolOverlapping descriptionsAdd "use X instead when..." lines; merge tools
Invents argumentsMissing lookup tool or vague schemaAdd search tool; enums/patterns
Loops on errorsErrors without hintsAdd corrective hints
Huge contextVerbose tool outputsField selection, pagination, truncation
Never calls toolDescription doesn't match user phrasingInclude trigger examples in description

Checklist

  • Tool inventory cohesive and non-overlapping (split agents past ~10-15 tools or on eval evidence).
  • Descriptions include when-not-to-use and output limits.
  • Strict schemas (required, enums, additionalProperties: false).
  • Server-side validation and authorization.
  • Structured errors with hints; is_error set.
  • Idempotency keys on writes; approval on irreversible actions.
  • Tool-selection eval: prompts mapped to expected tool + args.

References

  • Anthropic docs: Tool use (tool_use / tool_result, is_error).
  • OpenAI docs: Function calling and Structured Outputs (strict: true).
  • Repo rule: .claude/rules/mcp-server-design.md for MCP-exposed tools.

Shared References

Additional reference material for this skill, stored outside its own references/ folder.

  • ../../../harness-engineering/tool-orchestration/references/idempotency-patterns.md — Idempotency Patterns
  • ../../../harness-engineering/tool-orchestration/references/tool-error-handling.md — Tool Error Handling in Agent Harnesses
  • ../../../harness-engineering/tool-orchestration/references/tool-version-compatibility.md — Tool Versioning and Compatibility in Agent Harnesses

Heefeg gestallte Froen

Wat mécht de KI-Skill Tool Calling Principles?

Use this skill when the user says 'tool calling', 'function calling', 'tool schema', 'JSON schema for tools', 'agent picks wrong tool', 'tool error handling', 'structured outputs', 'tool_use / tool_result'. Designs tool interfaces for LLM agents: naming, descriptions, strict schemas, error contracts, idempotency, output shaping, and permission levels. Do NOT use for: building MCP servers specifically (ai/mcp-patterns and .claude/rules/mcp-server-design.md), the agent loop (ai/ai-agents/core-architectures), or general REST API design (backend/universal/api-design).

Firwat Tool Calling Principles op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Tool Calling Principles besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Tool Calling Principles an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/ai/ai-agents/tool-calling-principles an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Tool Calling Principles benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Tool Calling Principles benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Tool Calling Principles domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Tool Calling Principles gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇