ai-structured-output
БесплатноБез исполняемых скриптовНе проверенGenerate type-safe AI content using Gemini structured output with Zod validation and Code Execution Tool. Use when building AI generation functions that need…
от majiayu000★ 31 звезда на GitHubОб этом скилле
AI Structured Output Patterns
This skill documents patterns for generating type-safe, validated AI content using Google Gemini with Vercel AI SDK.
When to Use This Skill
- Generating structured content (blog posts, reports, summaries) with guaranteed format
- Need type-safe LLM output with TypeScript inference
- Preventing hallucinations in data analysis through code execution
- Creating reusable AI generation functions for workflows
- Building multi-step AI pipelines with separate analysis and generation phases
Architecture Overview
The recommended architecture uses a 2-step generation flow:
Step 1: Analysis (Accuracy) Step 2: Structured Output (Presentation)
┌─────────────────────────────┐ ┌─────────────────────────────┐
│ generateText() │ │ generateObject() │
│ + Code Execution Tool │ ──▶ │ + Zod Schema │
│ + Extended Thinking │ │ + Field Descriptions │
│ = Accurate calculations │ │ = Type-safe output │
└─────────────────────────────┘ └─────────────────────────────┘
Why 2 steps?
- Step 1 focuses on accuracy: Code execution prevents calculation errors
- Step 2 focuses on format: Zod schema ensures consistent structure
- Separation allows optimisation: extended thinking only where needed
2-Step Generation Implementation
Complete Example
import { google } from "@ai-sdk/google";
import { generateText, generateObject } from "ai";
import { z } from "zod";
// Define output schema with field descriptions
const outputSchema = z.object({
title: z.string().max(100).describe("SEO-optimised title, max 60 chars preferred"),
excerpt: z.string().max(500).describe("2-3 sentence summary for meta description"),
content: z.string().describe("Full markdown content without H1 title"),
tags: z.array(z.string()).min(1).max(10).describe("3-5 category tags in Title Case"),
highlights: z.array(z.object({
value: z.string().describe('Metric value, e.g. "52.60%", "$125,000"'),
label: z.string().describe('Short label, e.g. "Electric Vehicles Lead"'),
detail: z.string().describe('Context, e.g. "2,081 units registered"'),
})).min(3).max(10).describe("3-6 key statistics for visual display"),
});
type GeneratedOutput = z.infer<typeof outputSchema>;
export async function generate2Step(data: string): Promise<GeneratedOutput> {
// STEP 1: Analysis with Code Execution
const analysisResult = await generateText({
model: google("gemini-2.5-flash"),
system: ANALYSIS_INSTRUCTIONS,
tools: { code_execution: google.tools.codeExecution({}) },
prompt: `Analyse this data:\n${data}\n\nProvide detailed analysis with accurate calculations.`,
providerOptions: {
google: {
thinkingConfig: {
thinkingBudget: -1, // Unlimited thinking for complex analysis
},
},
},
});
// STEP 2: Structured Output Generation
const { object } = await generateObject({
model: google("gemini-2.5-flash"),
schema: outputSchema,
system: GENERATION_INSTRUCTIONS,
prompt: `Based on this analysis:\n\n${analysisResult.text}\n\nGenerate the structured output.`,
});
return object; // Fully typed!
}
Code Execution Tool
The Code Execution Tool is critical for preventing hallucinations in data analysis.
Configuration
tools: { code_execution: google.tools.codeExecution({}) }
Why It Matters
| Without Code Execution | With Code Execution |
|---|---|
| LLM guesses calculations | Python executes actual math |
| Plausible but wrong numbers | Verified accurate results |
| Cannot validate data | Can parse and validate input |
| Unreliable for financial data | Safe for market analysis |
When to Use
- Always use for: calculations, aggregations, percentages, comparisons
- Skip for: creative writing, summaries, opinion pieces
- Use in Step 1 only: Code execution is for analysis, not generation
Example: Data Analysis with Code Execution
const analysisResult = await generateText({
model: google("gemini-2.5-flash"),
tools: { code_execution: google.tools.codeExecution({}) },
system: `You are a data analyst. Use Python code execution for ALL calculations.
Never estimate or guess numbers. Execute code to:
- Parse the input data
- Calculate totals and percentages
- Compare values and trends
- Validate data consistency`,
prompt: `Analyse this sales data:\n${pipeDelimitedData}`,
});
Extended Thinking Configuration
Extended thinking improves analysis quality but increases latency. Use selectively.
Configuration
providerOptions: {
google: {
thinkingConfig: {
thinkingBudget: -1, // -1 = unlimited, or set specific token budget
},
},
}
When to Use
| Step | Extended Thinking | Reason |
|---|---|---|
| Analysis (Step 1) | YES | Complex |
Установить ai-structured-output в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadEditWriteGrepGlobВложенные файлы
FAQ
Что делает скилл ai-structured-output?
Generate type-safe AI content using Gemini structured output with Zod validation and Code Execution Tool. Use when building AI generation functions that need guaranteed output format.
Как установить скилл ai-structured-output?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ai-structured-output запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic