Core Fundamentals ⏱ 9 min read 📁 examples/03_structured_output.mjs

Lesson 03: Structured Data Extraction

Compare five distinct structured extraction strategies: JSON schema response format, a Zod schema, parallel tool calls, closing summary tools, and forced tool output fallback.

1. Why This Feature Exists

Extracting reliable JSON from LLMs across heterogeneous providers is challenging: some providers support native JSON Schema (OpenAI, Gemini), while others or local models degrade or reject response_format. Merci SDK provides multi-strategy extraction with automatic fallback.

2. Key Symbols and Exports

session.asJson().withSchema(schema)
Strict native JSON Schema enforcement via provider response_format.
session.asJson().withSchema(zodSchema)
The same path with a Zod schema — Zod validates the reply locally, and the builder converts it to plain JSON Schema at the wire boundary.
session.withTools([extractorTool])
Parallel tool calls where the model invokes a extraction tool per discovered item.
session.asJsonSchema().asTool()
Converts a JSON schema into a synthetic forced tool for providers lacking native schema modes.
extractAndParseJson()
Robust JSON extractor supporting markdown code fence unwrapping and error healing, accepting JSON Schema or a Zod schema.

3. Implementation Walkthrough

import {
    createUserMessage,
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel
} from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

const MeetingNotesSchema = {
    type: 'object',
    properties: {
        action_items: {
            type: 'array',
            items: {
                type: 'object',
                properties: {
                    task: { type: 'string' },
                    assignee: { type: 'string' },
                    priority: { type: 'string', enum: ['high', 'medium', 'low'] }
                },
                required: ['task', 'assignee', 'priority']
            }
        }
    },
    required: ['action_items']
};

// Approach A: Native JSON Schema
const session = client.session(getDefaultModel({ provider: PROVIDER }))
    .asJson()
    .withSchema(MeetingNotesSchema);

const result = await session.run('Meeting notes: Bob will deploy v2 by Friday (high priority). Alice to review PRs.');
console.log(JSON.parse(result));

4. Wire and Telemetry Mechanics

Under OpenAI and Gemini, response_format is set with json_schema. Under providers that do not support response_format (like OpenCode or older local models), the SDK transparently converts the schema into a forced tool call, parses the arguments, and returns validated structured data.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/03_structured_output.mjs

Read the full example: examples/03_structured_output.mjs →

Expected Output: Runs 4 extraction benchmarks side-by-side on meeting notes text and outputs an items/tokens/time comparison matrix.