extrait 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thibault Terrasson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,247 @@
1
+ # extrait
2
+
3
+ Structured JSON extraction from LLMs with validation, repair, and streaming.
4
+
5
+ Features:
6
+ - Multi-candidate JSON extraction from LLM responses
7
+ - Automatic repair with jsonrepair
8
+ - Zod schema validation and coercion
9
+ - Optional self-healing for validation failures
10
+ - Streaming support
11
+ - MCP tools
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ bun install
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```typescript
22
+ import { createLLM, prompt, s } from "extrait";
23
+ import { z } from "zod";
24
+
25
+ const llm = createLLM({
26
+ provider: "openai-compatible",
27
+ model: "gpt-5-nano",
28
+ transport: { apiKey: process.env.LLM_API_KEY },
29
+ });
30
+
31
+ const SummarySchema = s.schema(
32
+ "Summary",
33
+ z.object({
34
+ summary: s.string().min(1).describe("One-sentence summary"),
35
+ tags: s.array(s.string()).default([]).describe("Keywords"),
36
+ })
37
+ );
38
+
39
+ const result = await llm.structured(
40
+ SummarySchema,
41
+ prompt`Summarize this: """${text}"""`
42
+ );
43
+
44
+ console.log(result.data);
45
+ ```
46
+
47
+ ## API Reference
48
+
49
+ ### Creating an LLM Client
50
+
51
+ ```typescript
52
+ const llm = createLLM({
53
+ provider: "openai-compatible" | "anthropic-compatible",
54
+ model: "gpt-5-nano",
55
+ transport: {
56
+ baseURL: "https://api.openai.com", // optional
57
+ apiKey: process.env.LLM_API_KEY, // optional
58
+ },
59
+ defaults: {
60
+ mode: "loose" | "strict", // loose allows repair
61
+ selfHeal: 0 | 1 | 2, // retry attempts
62
+ debug: false, // show repair logs
63
+ },
64
+ });
65
+ ```
66
+
67
+ ### Defining Schemas
68
+
69
+ Use the `s` wrapper around Zod for enhanced schema building:
70
+
71
+ ```typescript
72
+ import { s } from "extrait";
73
+ import { z } from "zod";
74
+
75
+ const Schema = s.schema(
76
+ "SchemaName",
77
+ z.object({
78
+ // String fields
79
+ text: s.string().min(1).describe("Field description"),
80
+ optional: s.string().optional(),
81
+ withDefault: s.string().default("value"),
82
+
83
+ // Numbers
84
+ count: s.number().int().min(0).max(100),
85
+ score: s.number().min(0).max(1),
86
+
87
+ // Arrays
88
+ items: s.array(s.string()).min(1).max(10),
89
+
90
+ // Nested objects
91
+ nested: z.object({
92
+ field: s.string(),
93
+ }),
94
+
95
+ // Enums (use native Zod)
96
+ category: z.enum(["a", "b", "c"]),
97
+
98
+ // Booleans
99
+ flag: s.boolean(),
100
+ })
101
+ );
102
+ ```
103
+
104
+ ### Making Structured Calls
105
+
106
+ ```typescript
107
+ // Simple prompt
108
+ const result = await llm.structured(
109
+ Schema,
110
+ prompt`Your prompt with ${variables}`
111
+ );
112
+
113
+ // Multi-part prompt
114
+ const result = await llm.structured(
115
+ Schema,
116
+ prompt()
117
+ .system`You are an expert assistant.`
118
+ .user`Analyze: """${input}"""`
119
+ );
120
+
121
+ // With options
122
+ const result = await llm.structured(
123
+ Schema,
124
+ prompt`Your prompt`,
125
+ {
126
+ mode: "loose",
127
+ selfHeal: 1,
128
+ debug: true,
129
+ stream: {
130
+ to: "stdout",
131
+ onData: (event) => {
132
+ console.log("Partial data:", event.data);
133
+ if (event.done) {
134
+ console.log("Streaming done.");
135
+ }
136
+ },
137
+ },
138
+ }
139
+ );
140
+ ```
141
+
142
+ ### Result Object
143
+
144
+ ```typescript
145
+ {
146
+ data: T, // Validated data matching schema
147
+ raw: string, // Raw LLM response
148
+ thinkBlocks: ThinkBlock[], // Extracted <think> blocks
149
+ json: unknown | null, // Parsed JSON before validation
150
+ attempts: AttemptTrace[], // Self-heal attempts
151
+ usage?: {
152
+ inputTokens?: number,
153
+ outputTokens?: number,
154
+ totalTokens?: number,
155
+ cost?: number,
156
+ },
157
+ finishReason?: string, // e.g., "stop"
158
+ }
159
+ ```
160
+
161
+ ### Error Handling
162
+
163
+ ```typescript
164
+ import { StructuredParseError } from "extrait";
165
+
166
+ try {
167
+ const result = await llm.structured(Schema, prompt`...`);
168
+ } catch (error) {
169
+ if (error instanceof StructuredParseError) {
170
+ console.error("Validation failed");
171
+ console.error("Attempt:", error.attempt);
172
+ console.error("Zod issues:", error.zodIssues);
173
+ console.error("Repair log:", error.repairLog);
174
+ console.error("Candidates:", error.candidates);
175
+ }
176
+ }
177
+ ```
178
+
179
+ ### MCP Tools
180
+
181
+ ```typescript
182
+ import { createMCPClient } from "extrait";
183
+
184
+ const mcpClient = await createMCPClient({
185
+ id: "calculator",
186
+ transport: {
187
+ type: "stdio",
188
+ command: "bun",
189
+ args: ["run", "examples/calculator-mcp-server.ts"],
190
+ },
191
+ });
192
+
193
+ const result = await llm.structured(
194
+ Schema,
195
+ prompt`Calculate 14 + 8`,
196
+ {
197
+ request: {
198
+ mcpClients: [mcpClient],
199
+ maxToolRounds: 5,
200
+ toolDebug: {
201
+ enabled: true,
202
+ includeRequest: true,
203
+ includeResult: true,
204
+ },
205
+ onToolExecution: (execution) => {
206
+ console.log(execution.name, execution.durationMs);
207
+ },
208
+ },
209
+ }
210
+ );
211
+
212
+ await mcpClient.close?.();
213
+ ```
214
+
215
+ ## Examples
216
+
217
+ Run examples with: `bun run dev <example-name>`
218
+
219
+ Available examples:
220
+ - `streaming` - Real LLM streaming + snapshot self-check ([streaming.ts](examples/streaming.ts))
221
+ - `simple` - Basic structured output with streaming ([simple.ts](examples/simple.ts))
222
+ - `sentiment-analysis` - Enum validation, strict mode ([sentiment-analysis.ts](examples/sentiment-analysis.ts))
223
+ - `data-extraction` - Complex nested schemas, self-healing ([data-extraction.ts](examples/data-extraction.ts))
224
+ - `multi-step-reasoning` - Chained structured calls ([multi-step-reasoning.ts](examples/multi-step-reasoning.ts))
225
+ - `calculator-tool` - MCP tool integration ([calculator-tool.ts](examples/calculator-tool.ts))
226
+
227
+ Pass arguments after the example name:
228
+ ```bash
229
+ bun run dev streaming
230
+ bun run dev simple "Bun.js runtime"
231
+ bun run dev sentiment-analysis "I love this product."
232
+ bun run dev multi-step-reasoning "Why is the sky blue?"
233
+ ```
234
+
235
+ ## Environment Variables
236
+
237
+ - `LLM_PROVIDER` - `openai-compatible` or `anthropic-compatible`
238
+ - `LLM_BASE_URL` - API endpoint (optional)
239
+ - `LLM_MODEL` - Model name (default: `gpt-5-nano`)
240
+ - `LLM_API_KEY` - API key for the provider
241
+ - `STRUCTURED_DEBUG=1` - Enable debug output
242
+
243
+ ## Testing
244
+
245
+ ```bash
246
+ bun test
247
+ ```
@@ -0,0 +1,3 @@
1
+ import type { ExtractJsonCandidatesOptions, ExtractionCandidate, ExtractionHeuristicsOptions } from "./types";
2
+ export declare const DEFAULT_EXTRACTION_HEURISTICS: ExtractionHeuristicsOptions;
3
+ export declare function extractJsonCandidates(input: string, options?: ExtractJsonCandidatesOptions): ExtractionCandidate[];
@@ -0,0 +1,8 @@
1
+ import type { z } from "zod";
2
+ export interface WithFormatOptions {
3
+ schemaInstruction?: string;
4
+ }
5
+ export declare const DEFAULT_SCHEMA_INSTRUCTION = "Strictly follow this schema:";
6
+ export declare function withFormat(schema: z.ZodTypeAny, options?: WithFormatOptions): string;
7
+ export declare function formatPrompt(schema: z.ZodTypeAny, task: string, options?: WithFormatOptions): string;
8
+ export declare function resolveSchemaInstruction(instruction: string | undefined): string;