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
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.mjsRead the full example: examples/03_structured_output.mjs →