Structured Output & Auto-Repair
Structured Output in Kikoyu SDK allows you to enforce strongly typed Zod response schemas on AI Agents.
When a response schema is attached, Kikoyu SDK automatically formats the model’s output into a validated JSON object and executes automated multi-step repair prompts if the LLM produces malformed or non-compliant output.
Why Structured Output Matters
By default, LLMs return unstructured natural language strings. In production APIs, backend systems require strict JSON objects matching specific field shapes (e.g. { sentiment: 'positive', score: 0.95 }).
Kikoyu SDK guarantees:
- 100% Type Safety: Inferred TypeScript types directly from your Zod schema.
- Auto-Repair Loop: If the LLM generates bad JSON or misses a field, Kikoyu catches the Zod error and automatically sends a corrective repair prompt back to the model.
Step-by-Step Implementation Guide
Step 1: Define Zod Response Schema
typescript
Step 2: Attach Schema to Agent via .withResponseSchema()
typescript
Step 3: Execute Agent & Access Inferred result.structuredOutput
typescript
How Auto-Repair Works Under the Hood
plaintext
- JSON Schema Generation: Kikoyu converts your Zod schema into a JSON Schema definition automatically.
- Runtime Validation: When the model finishes generating text, Kikoyu parses the JSON string and validates it against your Zod schema.
- Auto-Repair Execution: If JSON parsing fails or required Zod fields are missing, Kikoyu issues an immediate repair prompt (
The response failed JSON schema validation with error: ... Please fix and return valid JSON matching schema) up tomaxRetriesattempts.
Best Practices
- Provide Clear Field Descriptions: Use
.describe()on Zod properties so the LLM understands expected field definitions. - Set Sensible Range Constraints: Use
.min(),.max(), and.enum()to restrict value boundaries tightly.