tool-use-structured-output
БесплатноБез исполняемых скриптовНе проверенUse Bedrock tool_use to guarantee structured JSON outputs from Claude models. Eliminates JSON parsing failures by forcing responses through typed tool schemas.
от aws-solutions-library-samples★ 413 звёзд на GitHubОб этом скилле
This skill demonstrates using Amazon Bedrock's tool_use feature to get highly reliable structured JSON outputs from Claude models. Instead of hoping the model returns valid JSON, define a tool schema that forces the exact structure you need.
The Problem
Asking Claude to "return JSON" fails 10-30% of the time:
- Markdown code fences around JSON
- Truncated responses mid-object
- Extra text before/after JSON
- Invalid escaping in strings
The Solution
Define a tool with your exact output schema. Claude will call the tool with arguments that should match the schema structure. While tool use strongly steers the model toward valid structured output, you should still validate the response and have fallback handling for edge cases.
Implementation Pattern
1. Define Tool Schema
tools = [
{
"name": "emit_extraction_result",
"description": "Return the extracted course information",
"input_schema": {
"type": "object",
"required": ["courses", "confidence", "page_number"],
"properties": {
"courses": {
"type": "array",
"items": {
"type": "object",
"required": ["course_code", "title"],
"properties": {
"course_code": {
"type": "string",
"description": "Course identifier (e.g., CS 101)"
},
"title": {
"type": "string",
"description": "Course title"
},
"credits": {
"type": "number",
"description": "Credit hours"
},
"description": {
"type": "string",
"description": "Course description"
}
}
}
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Extraction confidence score"
},
"page_number": {
"type": "integer",
"description": "Source page number"
}
}
}
}
]
2. Invoke Bedrock with Tool
import boto3
import json
bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')
response = bedrock.invoke_model(
modelId='anthropic.claude-3-5-sonnet-20241022-v2:0',
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 4096,
"tools": tools,
"tool_choice": {"type": "tool", "name": "emit_extraction_result"}, # Force tool use
"messages": [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": base64_image_data
}
},
{
"type": "text",
"text": "Extract all courses from this catalog page."
}
]
}
]
})
)
3. Parse Response
result = json.loads(response['body'].read())
# Find tool use in response
for content_block in result.get('content', []):
if content_block.get('type') == 'tool_use':
tool_name = content_block.get('name')
tool_input = content_block.get('input')
# tool_input should match your schema structure
# Always validate before using in production
courses = tool_input['courses']
confidence = tool_input['confidence']
page_number = tool_input['page_number']
# No JSON parsing needed - it's already a dict!
break
Advanced Patterns
Enum Constraints
Force specific values:
"status": {
"type": "string",
"enum": ["approved", "rejected", "needs_review"]
}
Numeric Ranges
Constrain numbers:
"accuracy": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"score": {
"type": "integer",
"enum": [0, 1, 2, 3, 4, 5] # Discrete scale
}
Nested Objects
Complex structures:
"evaluation": {
"type": "object",
"properties": {
"field_scores": {
"type": "object",
"properties": {
"course_code": {"type": "number", "enum": [0, 0.5, 1]},
"title": {"type": "number", "enum": [0, 0.5, 1]},
"credits": {"type": "num
Установить tool-use-structured-output в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл tool-use-structured-output?
Use Bedrock tool_use to guarantee structured JSON outputs from Claude models. Eliminates JSON parsing failures by forcing responses through typed tool schemas.
Как установить скилл tool-use-structured-output?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tool-use-structured-output запускает скрипты?
Нет, скилл состоит только из инструкций (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