structured-output
Structured data extraction using Pydantic schemas, strict JSON output formats, and schema validation.
- License 许可
- MIT
- 最近更新
- 2026-06-05
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- structured-output
- license
- MIT license
- metadata
- { "skill-author": "Lord1Egypt" }
- description
- Structured data extraction using Pydantic schemas, strict JSON output formats, and schema validation.
- allowed-tools
- Read Write Edit Bash
03 SKILL.md 正文
Gemini Structured Output & Schema Validation Skill
Overview
This skill provides guidelines and code patterns for enforcing structured, type-safe output formats (specifically JSON) from Gemini models. By declaring a Pydantic model or defining a JSON Schema, developers guarantee that the model's response adheres strictly to the schema structure, avoiding parsing failures at runtime.
When to Use This Skill
- Extracting entities, metrics, or relationships from unstructured text.
- Generating forms, configurations, or structured databases.
- Creating API payloads or feeding downstream programming workflows.
- Classifying inputs into predefined categories.
Quick Start (with runnable code examples)
from typing import List, Optional
from pydantic import BaseModel, Field
from google import genai
# Initialize the Gemini GenAI Client
client = genai.Client()
# Define the target structure using Pydantic
class EntityExtraction(BaseModel):
name: str = Field(description="Name of the person, company, or concept")
category: str = Field(description="Type of entity (e.g., Person, Organization, Location, Technology)")
relevance_score: float = Field(description="Relevance score from 0.0 to 1.0")
context_snippet: Optional[str] = Field(None, description="A snippet from the text showing where this was found")
class TextAnalysisReport(BaseModel):
summary: str = Field(description="A concise summary of the analyzed text")
sentiment: str = Field(description="Sentiment classification: POSITIVE, NEGATIVE, or NEUTRAL")
entities: List[EntityExtraction] = Field(default=[], description="List of extracted entities")
def extract_structured_data(text: str):
print("Sending text to Gemini for structured analysis...")
# Generate content using gemini-2.5-flash with a schema configuration
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=f"Analyze the following text and extract details:\n\n{text}",
config=dict(
# Force JSON mime type output
response_mime_type="application/json",
# Pass the Pydantic class to define the target schema structure
response_schema=TextAnalysisReport
)
)
# Parse the response text directly as a Pydantic model instance
try:
report = TextAnalysisReport.model_validate_json(response.text)
print("\n--- Successfully Extracted Pydantic Object ---")
print(f"Sentiment: {report.sentiment}")
print(f"Summary: {report.summary}")
print("\nEntities Found:")
for entity in report.entities:
print(f" - [{entity.category}] {entity.name} (Relevance: {entity.relevance_score})")
except Exception as e:
print(f"Failed to validate JSON output: {e}")
print(response.text)
if __name__ == "__main__":
sample_text = (
"Yesterday, Google announced the release of Gemini 2.5 on their official blog in California. "
"Sundar Pichai expressed great excitement about the natively multimodal architecture, which shows "
"unprecedented speed improvements for developers worldwide."
)
extract_structured_data(sample_text)
Advanced Usage
Raw Dict / JSON Schema Fallback
If you are not using Pydantic, you can pass a raw dictionary containing a standard OpenAPI 3.0 schema:
raw_schema = {
"type": "OBJECT",
"properties": {
"items": {
"type": "ARRAY",
"items": {"type": "STRING"}
}
},
"required": ["items"]
}
response = client.models.generate_content(
model='gemini-2.5-flash',
contents="List five colors",
config=dict(
response_mime_type="application/json",
response_schema=raw_schema
)
)
Key References
- Google GenAI Structured Output documentation
- Pydantic v2 Documentation
Dependencies
google-genai>=0.1.1pydantic>=2.0
04 同仓库更多 Skills
zarr-python
Chunked N-D arrays for cloud storage. Compressed arrays, parallel I/O, S3/GCS integration, NumPy/Dask/Xarray compatible, for large-scale scientific computing pipelines.
what-if-oracle
Run structured What-If scenario analysis with multi-branch possibility exploration. Use this skill when the user asks speculative questions like "what if...", "what would happen if...", "what are the possibilities", "explore scenarios", "scenario analysis", "possibility space", "what could go wrong", "best case / worst case", "risk analysis", "contingency planning", "strategic options", or any question about uncertain futures. Also trigger when the user faces a fork-in-the-road decision, wants to stress-test an idea, or needs to think through consequences before committing.
websockets-network
Asynchronous bi-directional WebSocket client and server configuration in Python.
vite-frontend
Initializing, structuring, and bundling client-side Single-Page Applications (SPA) with Vite.
venue-templates
Access comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
vaex
Use this skill for processing and analyzing large tabular datasets (billions of rows) that exceed available RAM. Vaex excels at out-of-core DataFrame operations, lazy evaluation, fast aggregations, efficient visualization of big data, and machine learning on large datasets. Apply when users need to work with large CSV/HDF5/Arrow/Parquet files, perform fast statistics on massive datasets, create visualizations of big data, or build ML pipelines that do not fit in memory.