Strict Structured JSON Outputs in Gemini: Schema Enforcement using Python
When integrating Large Language Models (LLMs) into production codebases, parsing free-text outputs is a major point of failure. If your code expects a structured JSON object but the model returns conversational text alongside it, your code will throw runtime errors.
Using Google's Gemini 1.5 Pro or Flash, developers can set a response_schema directly in the API configurations. This forces the model to respond strictly in a JSON format that adheres to a predefined data structure, guaranteeing zero parsing exceptions in your agent loops.
Defining Your Data Structure with Pydantic
The most robust way to enforce a schema in Python is by defining a Pydantic model. Pydantic handles type validation and automatically exports the required OpenAPI-compatible JSON schema that the Gemini API expects.
Let's define a system diagnostics schema for an AI node inspector:
500 italic"># Defining the diagnostic data structure
"text-brand-cyan font-bold">from pydantic "text-brand-cyan font-bold">import BaseModel, Field
"text-brand-cyan font-bold">from typing "text-brand-cyan font-bold">import List, Optional
"text-brand-cyan font-bold">class PortConfig(BaseModel):
port: int = Field(description="Internal port number")
status: str = Field(description="Status of the port: ACTIVE, INACTIVE, or BLOCKED")
"text-brand-cyan font-bold">class SystemDiagnostics(BaseModel):
config_name: str = Field(description="Name of the configuration preset")
status: str = Field(description="Health state of the system node")
endpoint: str = Field(description="API version endpoint identifier")
data_active: bool = Field(description="Whether the data loop is active")
ports: List[PortConfig] = Field(description="List of port status configurations")Dispatching the Schema-Enforced API Request
Once you have your Pydantic model, you pass it to the Gemini client setup. The SDK will translate your class definition into the required schema parameter.
Here is the exact setup to dispatch a strict request:

System Prompt
Notice that the model is locked into returning the exact structure defined in our parameters. Here is the full execution script using the Google GenAI SDK:
500 italic"># Dispatching request "text-brand-cyan font-bold">with strict JSON schema enforcement
"text-brand-cyan font-bold">import google.generativeai "text-brand-cyan font-bold">as genai
"text-brand-cyan font-bold">import json
500 italic"># Configure API key
genai.configure(api_key="GEMINI_API_KEY")
500 italic"># Initialize model "text-brand-cyan font-bold">with schema enforcement parameters
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config={
"response_mime_type": "application/json",
"response_schema": SystemDiagnostics,
}
)
500 italic"># Request extraction "text-brand-cyan font-bold">from unstructured text
raw_log = "Error log: SRV_741 port 8080 state is ACTIVE. System load 45.2%, health is OK."
response = model.generate_content(
f"Analyze these diagnostics and populate the schema: {raw_log}"
)
500 italic"># Parse response "text-brand-cyan font-bold">with complete confidence
parsed_data = json.loads(response.text)
"text-brand-cyan font-bold">print("Validated JSON Object:", parsed_data)By specifying the response_schema, the API guarantees that response.text will always be a valid string conforming to the SystemDiagnostics model. This structure makes it ideal for agentic pipelines, letting your agents communicate data structures reliably without manual string cleanup regex rules.
Related AI Workflows
Agentic WorkflowsAgentic RAG Orchestration: Multi-Agent Gemini & Antigravity SDK
Design production-grade Retrieval-Augmented Generation (RAG) systems utilizing multi-agent orchestration frameworks and the Gemini API.
Agentic WorkflowsThe Best Vector Databases for Gemini API Agentic Loops: 2026 Comparison
Discover the best vector databases to store and query text embeddings generated by the Gemini API, comparing Pinecone, Supabase, and Qdrant.