function-calling
БесплатноБез исполняемых скриптовНе проверенFunction calling (tool use) lets an LLM request calls to your own functions while your code runs them and returns the results in a loop. Covers the OpenAI…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Function Calling
Overview
Function calling (also called tool use) lets an LLM ask your code to run functions. The model never executes anything itself: it returns a tool call (name plus JSON arguments), your code runs it, and you send the result back so the model can continue. Both big providers work this way; only the message shapes differ.
The flow is always:
- Define tools with JSON schemas.
- Send the conversation plus the tool definitions.
- If the response contains tool calls, execute each one.
- Append the model's turn and all the results to the conversation, call again.
- Stop when the response has no tool calls (the final text answer).
OpenAI now recommends the Responses API (client.responses.create) for new code; Chat Completions is still supported and its older shape (tools=[{"type":"function","function":{...}}], role: "tool" messages) appears in many tutorials. Model ids change often: read them from the provider's model list and keep them in configuration, not in code.
Instructions
Shared: tool implementations
# tools.py
import json
def get_weather(city: str, unit: str | None = "celsius") -> dict:
# Replace with a real weather API call. Strict schemas send null for omitted optionals.
unit = unit or "celsius"
return {"city": city, "temperature": 22 if unit == "celsius" else 72,
"unit": unit, "conditions": "Partly cloudy"}
def send_email(to: str, subject: str, body: str) -> dict:
# Replace with your mail provider; keep side effects behind a confirmation in real use.
return {"success": True, "message_id": "msg_8f3a21"}
def search_database(query: str, limit: int = 5) -> dict:
# Replace with a real product search.
products = [{"name": "Ceramic mug 350 ml", "sku": "MUG-350", "price_usd": 14.5}]
return {"results": products[:limit]}
TOOL_MAP = {"get_weather": get_weather, "send_email": send_email,
"search_database": search_database}
def execute_tool(name: str, arguments: dict) -> str:
"""Always returns a string; errors become data the model can react to."""
if name not in TOOL_MAP:
return json.dumps({"error": f"Unknown tool: {name}"})
try:
return json.dumps(TOOL_MAP[name](**arguments))
except Exception as e:
return json.dumps({"error": str(e)})
OpenAI (Responses API)
Tools are flat objects. With strict: true the arguments always match the schema; strict mode needs additionalProperties: false and every property listed in required (make optional fields nullable with ["string", "null"]).
# openai_agent.py
import json, os
from openai import OpenAI
from tools import execute_tool
client = OpenAI()
MODEL = os.environ["OPENAI_MODEL"] # a current tool-capable model from the OpenAI model list
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get current weather for a city. Use when the user asks about weather or temperature.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. 'Tokyo, Japan'"},
"unit": {"type": ["string", "null"], "enum": ["celsius", "fahrenheit", None]},
},
"required": ["city", "unit"],
"additionalProperties": False,
},
"strict": True,
},
{
"type": "function",
"name": "send_email",
"description": "Send an email to one recipient. Only call after the user asked for an email.",
"parameters": {
"type": "object",
"properties": {
"to": {"type": "string", "description": "Recipient email address"},
"subject": {"type": "string"},
"body": {"type": "string"},
},
"required": ["to", "subject", "body"],
"additionalProperties": False,
},
"strict": True,
},
]
def run_agent(user_message: str, max_iterations: int = 10) -> str:
input_items = [{"role": "user", "content": user_message}]
for _ in range(max_iterations):
response = client.responses.create(model=MODEL, input=input_items, tools=tools)
input_items += response.output # keep the model's items, including reasoning
calls = [item for item in response.output if item.type == "function_call"]
if not calls:
return response.output_text
for call in calls: # may be several in one turn
result = execute_tool(call.name, json.loads(call.arguments))
input_items.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": result, # a string
})
return "Max iterations reached"
print(run_agent("What's the weather in Tokyo? If it's over 20 C, email [email protected] a trip tip."))
Chat Completions equ
Установить function-calling в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл function-calling?
Function calling (tool use) lets an LLM request calls to your own functions while your code runs them and returns the results in a loop. Covers the OpenAI Responses API, the Anthropic Messages API, parallel calls, tool_choice, strict schemas and error handling. Use when building AI agents with tools, letting LLMs query APIs or databases, or creating agentic workflows.
Как установить скилл function-calling?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл function-calling запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic