Anthropic::StructuredOutput
Structured output helper for extracting typed JSON from tool-use responses.
Uses the tool-use pattern to get structured data from Claude: define a tool with a JSON schema, force the model to use it, then extract and parse the tool's input as your structured data.
Usage
schema = JSON.parse(%({"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}))
tool = Anthropic::StructuredOutput.tool("extract_data", schema, description: "Extract structured data")
choice = Anthropic::StructuredOutput.tool_choice("extract_data")
response = client.messages.create(
model: Anthropic::Model.sonnet,
messages: [Anthropic::Message.user("My name is Alice")],
max_tokens: 1024,
tools: [tool],
tool_choice: choice,
)
result = Anthropic::StructuredOutput.extract(response)
result["name"].as_s # => "Alice"
Constants
Default tool name used for structured output extraction.
Class methods
Extracts the structured output from a response.
Looks for a tool_use block matching the given tool name and returns its input as JSON::Any. Returns nil if no matching block is found.
Extracts the structured output, raising if not found.
Raises ExtractionError if no matching tool_use block is found.
Extracts and deserializes structured output to a typed struct.
Type T must include JSON::Serializable or have a .from_json method. Returns nil if no matching tool_use block is found.
Check if a response contains structured output from the named tool.
Creates a tool definition for structured output extraction.
The tool's input_schema defines the shape of the structured data the model should return.