anth-core-workflow-a
Build Claude tool use (function calling) workflows with the Messages API. Use when implementing tool use, function calling, agent loops, or building AI assistants that interact with external systems. Trigger with phrases like "claude tool use", "anthropic function calling", "claude tools", "agent loop anthropic", "tool_use blocks".
What this skill does
# Anthropic Core Workflow A — Tool Use (Function Calling)
## Overview
Implement Claude's tool use capability where the model can call functions you define. Claude returns `tool_use` content blocks with structured JSON inputs; your code executes the function and returns `tool_result` blocks. This is the foundation for building AI agents.
## Prerequisites
- Completed `anth-install-auth` setup
- Understanding of the Messages API request/response cycle
- Functions or APIs you want Claude to call
## Instructions
### Step 1: Define Tools
```python
import anthropic
client = anthropic.Anthropic()
tools = [
{
"name": "get_weather",
"description": "Get current weather for a city. Use when the user asks about weather conditions.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g. 'San Francisco, CA'"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature units"
}
},
"required": ["city"]
}
},
{
"name": "search_database",
"description": "Search product database by query string. Returns matching products.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"max_results": {"type": "integer", "default": 10}
},
"required": ["query"]
}
}
]
```
### Step 2: Send Request with Tools
```python
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)
# Claude responds with stop_reason="tool_use"
# message.content contains both text and tool_use blocks:
# [
# {"type": "text", "text": "I'll check the weather for you."},
# {"type": "tool_use", "id": "toolu_01A...", "name": "get_weather",
# "input": {"city": "Tokyo", "units": "celsius"}}
# ]
```
### Step 3: Execute Tool and Return Result
```python
def execute_tool(name: str, input_data: dict) -> str:
"""Route tool calls to actual implementations."""
if name == "get_weather":
# Call your weather API
return '{"temp": 22, "condition": "partly cloudy", "humidity": 65}'
elif name == "search_database":
return '{"results": [{"name": "Widget A", "price": 29.99}]}'
raise ValueError(f"Unknown tool: {name}")
# Extract tool_use blocks and execute
tool_results = []
for block in message.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id, # Must match the tool_use block id
"content": result
})
# Continue conversation with tool results
follow_up = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"},
{"role": "assistant", "content": message.content},
{"role": "user", "content": tool_results}
]
)
print(follow_up.content[0].text)
# "The current weather in Tokyo is 22°C and partly cloudy with 65% humidity."
```
### Step 4: Agentic Loop (Multiple Tool Calls)
```python
def run_agent(user_message: str, tools: list, max_turns: int = 10) -> str:
"""Run an agentic loop that handles multiple sequential tool calls."""
messages = [{"role": "user", "content": user_message}]
for _ in range(max_turns):
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=tools,
messages=messages
)
# If Claude is done (no more tool calls), return final text
if response.stop_reason == "end_turn":
return next(
(b.text for b in response.content if b.type == "text"), ""
)
# Process tool calls
messages.append({"role": "assistant", "content": response.content})
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})
messages.append({"role": "user", "content": tool_results})
return "Max turns reached"
```
## Output
- Tool definitions with JSON Schema input validation
- Agent loop handling sequential tool calls
- Proper `tool_use` / `tool_result` message threading
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `invalid_request_error`: tool schema invalid | Malformed `input_schema` | Validate against JSON Schema spec |
| `tool_use_id` mismatch | Result ID doesn't match tool_use ID | Copy `block.id` exactly |
| Claude ignores tools | Description too vague | Add clear "Use when..." descriptions |
| Infinite loop | Claude keeps calling tools | Add `max_turns` guard + `tool_choice: {"type": "auto"}` |
## Tool Choice Options
```python
# Let Claude decide (default)
tool_choice={"type": "auto"}
# Force Claude to use a specific tool
tool_choice={"type": "tool", "name": "get_weather"}
# Force Claude to use any tool (must call at least one)
tool_choice={"type": "any"}
```
## Resources
- [Tool Use Guide](https://docs.anthropic.com/en/docs/build-with-claude/tool-use)
- [Tool Use API Reference](https://docs.anthropic.com/en/api/messages)
- [Tool Use Examples](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/examples)
## Next Steps
For streaming with tools, see `anth-core-workflow-b`.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.