Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Function Calling

ASecurity

Implement robust LLM function/tool calling: schemas, multi-call handling, validation, error recovery, and structured execution. Use for agent tool use.

2 stars
0 votes
0 copies
0 views
Added 9/29/2026
ai-agentspythongobashrailsdebuggingapi

Works with

cliapi

Security Analysis

A96/100
mediumInstalls packages at runtime which could introduce malicious dependencies

Pro scans all 2 files and shows the line behind each finding

Scanned 9/29/2026

$npx -y skills add ssrjkk/claude-skills --skill function-calling --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Function Calling?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Function Calling
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/ssrjkk-function-calling/badge)](https://www.skillsdirectory.com/skills/ssrjkk-function-calling)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: function-calling
description: "Implement robust LLM function/tool calling: schemas, multi-call handling, validation, error recovery, and structured execution. Use for agent tool use."
category: ai
tags: [function-calling, tool-use, llm, structured-output, agents, json-schema]
models: [sonnet, opus, gpt-5, gemini-2.5, glm-4.6]
version: 1.0.0
created: 2026-09-25
updated: 2026-09-28
author: ssrjkk
---
# Function Calling

> Wiring LLMs to real functions with robust tool calling.

## Quick Start
```bash
pip install openai
# declare tools, let the model call them, execute, and loop
```

## When to Use
- Letting the model query data, compute, or take actions
- Structured extraction into defined function inputs
- Agentic workflows that alternate reasoning and tool calls
- Reducing hallucination by constraining output to schemas

## Best Practices

### Tool Schemas
- Write clear, complete JSON schemas per function
- Use `description` on every param to guide the model
- Enforce `required` and sensible `enum`/`pattern`
- Keep parameter names self-explanatory

### Calling Loop
- Detect tool_calls; execute them; append results as `tool` messages
- Support multiple tool calls in one response
- Include the `tool_call_id` on every result
- Cap iterations to avoid runaway loops

### Validation & Recovery
- Validate arguments before execution
- Return structured errors that the model can read
- Never auto-execute dangerous tools without approval
- Log the full call trace for debugging

### Prompting
- Give the model context on when to call each tool
- Ask it to use tools instead of guessing answers
- Provide examples of tool usage in the system prompt
- Keep tool descriptions aligned with actual behavior

## Dependencies
```bash
pip install openai pydantic
# optional: instructor for schema-guided calls
```

## Examples
```python
import openai

client = openai.OpenAI()

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }
]

resp = client.chat.completions.create(
    model="gpt-5",
    messages=[{"role": "user", "content": "Weather in Tokyo?"}],
    tools=TOOLS,
)
call = resp.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)
```
```python
# Execute the call and feed the result back
import json

def dispatch(name: str, args: dict) -> str:
    if name == "get_weather":
        return weather_api(args["city"])
    return json.dumps({"error": f"unknown tool: {name}"})

result = dispatch(call.function.name, json.loads(call.function.arguments))
messages = [
    {"role": "user", "content": "Weather in Tokyo?"},
    resp.choices[0].message,
    {"role": "tool", "tool_call_id": call.id, "content": result},
]
final = client.chat.completions.create(model="gpt-5", messages=messages, tools=TOOLS)
print(final.choices[0].message.content)
```
```python
# Multi-call handling
def run_tools(message) -> list[dict]:
    results = []
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        results.append(
            {"role": "tool", "tool_call_id": call.id, "content": dispatch(call.function.name, args)}
        )
    return results
```
```python
# Validation with pydantic before execution
from pydantic import BaseModel, ValidationError

class WeatherArgs(BaseModel):
    city: str
    units: str = "metric"

def safe_dispatch(name: str, args: dict) -> str:
    try:
        if name == "get_weather":
            w = WeatherArgs(**args)
            return weather_api(w.city, w.units)
        return f'{{"error": "unknown tool {name}"}}'
    except ValidationError as e:
        return f'{{"error": "invalid args: {e}"}}'
```

## Step-by-Step
1. Write the tool functions you want the model to call.
2. Define JSON schemas with descriptions and required fields.
3. Send the first request with `tools` and user intent.
4. Execute returned `tool_calls` and append results with IDs.
5. Loop until the model returns a final text answer.
6. Validate args; return structured errors the model can use.
7. Add guardrails for dangerous actions.
8. Log traces; test with edge cases and malformed args.

## Validation
1. Model emits valid, schema-conforming calls for the test set
2. Multi-call responses are executed in order
3. Errors are surfaced back to the model for recovery
4. Loop terminates within the iteration cap
5. Dangerous tools require explicit approval

## Troubleshooting
- Model skips tools: add tool usage examples to the system prompt.
- Invalid JSON args: loosen schemas or use guided generation.
- Loops: cap iterations and detect repeated identical calls.

Attribution

ssrjkkssrjkk
View sourceSee grades on GitHubMore from ssrjkk →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Terse caveman voice: answer first, fluff gone, every technical fact kept. Use for /caveman, "caveman mode", "talk like caveman", "be brief", "less tokens". Stays on until "stop caveman" or "normal mode".

1100021 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

698431 votes

Writing Skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dep...

3931 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3421 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Amp, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Grok Build, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

741 votes
View all in ai-agents →