Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | 1x 18x 18x 18x 6x 1x 1x 6x 5x 5x 5x 5x 15x 10x 10x 15x 5x 18x 2x 2x 2x 2x 2x 2x 12x 6x 5x 5x 5x 5x 5x 10x 4x 3x 3x 3x 3x 4x 17x 17x 6x 6x 6x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x | /**
* AgentKits — Structured Output
*
* JSON Schema constrained output for LLM responses.
* Forces models to return valid JSON matching your schema.
*
* Usage:
* import { createStructured } from 'agentkits/structured';
* const extract = createStructured({
* provider: 'gemini',
* apiKey: '...',
* schema: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' } }, required: ['name'] }
* });
* const result = await extract.parse('John is 30 years old');
* // { name: 'John', age: 30 }
*/
import { createChat, type ChatConfig, type ChatMessage } from '../llm/index.js';
// ── Types ──────────────────────────────────────────────────────────
export interface JSONSchema {
type: string;
properties?: Record<string, JSONSchema>;
items?: JSONSchema;
required?: string[];
enum?: any[];
description?: string;
default?: any;
minimum?: number;
maximum?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
additionalProperties?: boolean | JSONSchema;
}
export interface StructuredConfig extends ChatConfig {
/** JSON Schema the output must conform to */
schema: JSONSchema;
/** Number of retries on parse failure (default: 2) */
retries?: number;
/** Custom system prompt prefix */
systemPrefix?: string;
}
export interface StructuredClient {
/** Parse unstructured text into structured JSON */
parse(input: string): Promise<any>;
/** Parse with message history context */
parseWithContext(messages: ChatMessage[], input: string): Promise<any>;
/** Validate JSON against schema */
validate(data: any): ValidationResult;
/** Current config */
readonly config: Readonly<StructuredConfig>;
}
export interface ValidationResult {
valid: boolean;
errors: string[];
}
// ── Schema Validation ─────────────────────────────────────────────
function validateAgainstSchema(data: any, schema: JSONSchema, path = ''): string[] {
const errors: string[] = [];
if (schema.type === 'object') {
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
return [`${path || 'root'}: expected object, got ${typeof data}`];
}
for (const req of schema.required ?? []) {
if (!(req in data)) errors.push(`${path}.${req}: required field missing`);
}
if (schema.properties) {
for (const [key, subSchema] of Object.entries(schema.properties)) {
if (key in data) {
errors.push(...validateAgainstSchema(data[key], subSchema, `${path}.${key}`));
}
}
}
} else if (schema.type === 'array') {
if (!Array.isArray(data)) {
return [`${path || 'root'}: expected array, got ${typeof data}`];
}
if (schema.items) {
data.forEach((item: any, i: number) => {
errors.push(...validateAgainstSchema(item, schema.items!, `${path}[${i}]`));
});
}
} else if (schema.type === 'string') {
if (typeof data !== 'string') errors.push(`${path}: expected string, got ${typeof data}`);
else {
if (schema.minLength != null && data.length < schema.minLength) errors.push(`${path}: too short (min ${schema.minLength})`);
if (schema.maxLength != null && data.length > schema.maxLength) errors.push(`${path}: too long (max ${schema.maxLength})`);
if (schema.enum && !schema.enum.includes(data)) errors.push(`${path}: must be one of ${schema.enum.join(', ')}`);
}
} else if (schema.type === 'number' || schema.type === 'integer') {
if (typeof data !== 'number') errors.push(`${path}: expected number, got ${typeof data}`);
else {
if (schema.minimum != null && data < schema.minimum) errors.push(`${path}: below minimum ${schema.minimum}`);
if (schema.maximum != null && data > schema.maximum) errors.push(`${path}: above maximum ${schema.maximum}`);
}
} else if (schema.type === 'boolean') {
if (typeof data !== 'boolean') errors.push(`${path}: expected boolean, got ${typeof data}`);
}
return errors;
}
function schemaToPrompt(schema: JSONSchema): string {
return JSON.stringify(schema, null, 2);
}
// ── Main ──────────────────────────────────────────────────────────
export function createStructured(config: StructuredConfig): StructuredClient {
const { schema, retries = 2, systemPrefix = '', ...chatConfig } = config;
const chat = createChat(chatConfig);
const systemPrompt = `${systemPrefix}You are a structured data extraction assistant. Extract information from the user's input and return ONLY valid JSON matching this schema:
\`\`\`json
${schemaToPrompt(schema)}
\`\`\`
Rules:
- Return ONLY the JSON object, no markdown fences, no explanation
- All required fields must be present
- Use null for missing optional fields
- Numbers must be actual numbers, not strings
- Follow the exact schema structure`;
async function tryParse(text: string): Promise<any> {
// Try to extract JSON from response
let json = text.trim();
// Remove markdown code fences if present
json = json.replace(/^```(?:json)?\s*\n?/i, '').replace(/\n?```\s*$/i, '');
json = json.trim();
// Try to find JSON object/array
const objMatch = json.match(/(\{[\s\S]*\})/);
const arrMatch = json.match(/(\[[\s\S]*\])/);
if (objMatch && schema.type === 'object') json = objMatch[1];
else if (arrMatch && schema.type === 'array') json = arrMatch[1];
return JSON.parse(json);
}
const client: StructuredClient = {
async parse(input) {
let lastError: Error | null = null;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const prompt = attempt === 0
? input
: `${input}\n\nPrevious attempt had errors: ${lastError?.message}. Please fix and return valid JSON.`;
const response = await chat.complete(prompt, { system: systemPrompt });
const data = await tryParse(response);
const validation = validateAgainstSchema(data, schema);
if (validation.length === 0) return data;
lastError = new Error(`Schema validation: ${validation.join('; ')}`);
} catch (e: any) {
lastError = e;
}
}
throw new Error(`Failed to get valid structured output after ${retries + 1} attempts: ${lastError?.message}`);
},
async parseWithContext(messages, input) {
const allMessages: ChatMessage[] = [
{ role: 'system', content: systemPrompt },
...messages,
{ role: 'user', content: input },
];
let lastError: Error | null = null;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const msgs = attempt === 0
? allMessages
: [...allMessages, { role: 'user' as const, content: `Previous attempt had errors: ${lastError?.message}. Fix and return valid JSON.` }];
const response = await chat.chat(msgs);
const data = await tryParse(response.content);
const validation = validateAgainstSchema(data, schema);
if (validation.length === 0) return data;
lastError = new Error(`Schema validation: ${validation.join('; ')}`);
} catch (e: any) {
lastError = e;
}
}
throw new Error(`Failed after ${retries + 1} attempts: ${lastError?.message}`);
},
validate(data) {
const errors = validateAgainstSchema(data, schema);
return { valid: errors.length === 0, errors };
},
get config() { return config; },
};
return client;
}
|