
Google Genai Sdk Python
- 94 installs
- 124 repo stars
- Updated February 6, 2026
- cnemri/google-genai-skills
Guides writing idiomatic Python with the official google-genai SDK for Gemini and Vertex AI: text, chat, reasoning, structured output, multimodal, and tools.
About
Provides reference guidance for building with the google-genai Python SDK across text, chat, reasoning, tools, and media. A developer uses it when writing Gemini or Vertex AI code in Python.
- Covers client setup, streaming, structured output, and function calling
- Stateless client.models vs stateful client.chats patterns
Google Genai Sdk Python by the numbers
- 94 all-time installs (skills.sh)
- Ranked #4,644 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/cnemri/google-genai-skills --skill google-genai-sdk-pythonAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 94 |
|---|---|
| repo stars | ★ 124 |
| Last updated | February 6, 2026 |
| Repository | cnemri/google-genai-skills ↗ |
What it does
Guides writing idiomatic Python with the official google-genai SDK for Gemini and Vertex AI: text, chat, reasoning, structured output, multimodal, and tools.
Files
Google GenAI Python SDK Skill
Use this skill to write high-quality, idiomatic Python code for the Gemini API.
Reference Materials
Identify the user's task and refer to the relevant file:
- [Setup & Client](references/setup.md): Installation, auth, client initialization.
- [Models](references/models.md): Recommended models (Flash, Pro, Lite, Imagen, Veo).
- [Text Generation](references/text_generation.md): Basic inference, streaming, system instructions, safety.
- [Chat](references/chat.md): Multi-turn conversations and history.
- [Reasoning](references/reasoning.md): Thinking config (
thinking_level/thinking_budget), thought signatures. - [Structured Output](references/structured_output.md): JSON schemas, Pydantic models, Enums.
- [Multimodal Inputs](references/multimodal_inputs.md): Images, audio, video, PDFs, media resolution.
- [Tools](references/tools.md): Function calling, code execution, Google Search grounding.
- [Media Generation](references/media_generation.md): Image generation/editing (Imagen), video generation (Veo).
- [Source Code](references/source_code.md): Raw SDK source code for deep inspection.
Core Principles
1. Unified SDK: Always use google-genai. 2. Stateless Models: Use client.models for single requests. 3. Stateful Chats: Use client.chats for conversations. 4. Types: Import from google.genai.types.
Chat
For multi-turn conversations, use the chats service. It manages history automatically.
Basic Chat
chat = client.chats.create(model='gemini-3-flash-preview')
response = chat.send_message('Hello, I am a developer.')
print(response.text)
response = chat.send_message('What did I just say I am?')
print(response.text)History Access
for message in chat.get_history():
print(f'{message.role}: {message.parts[0].text}')Custom History
Initialize a chat with existing history.
history = [
types.Content(role='user', parts=[types.Part.from_text(text='Hi')]),
types.Content(role='model', parts=[types.Part.from_text(text='Hello')])
]
chat = client.chats.create(model='gemini-3-flash-preview', history=history)Media Generation
Image Generation (Imagen)
Use gemini-2.5-flash-image (Nano Banana) or gemini-3-pro-image-preview (Nano Banana Pro).
response = client.models.generate_content(
model='gemini-2.5-flash-image',
contents='A futuristic city',
config=types.GenerateContentConfig(
image_config=types.ImageConfig(number_of_images=1)
)
)
for part in response.parts:
part.as_image().save('image.png')Image Editing
Use chats for editing workflows.
chat = client.chats.create(model='gemini-2.5-flash-image')
response = chat.send_message(['Change the sky to purple', image])Video Generation (Veo)
Use veo-3.0-generate-001 or veo-3.0-fast-generate-001.
operation = client.models.generate_videos(
model='veo-3.0-fast-generate-001',
prompt='A cat driving a car',
)
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
# Download
for video in operation.response.generated_videos:
video.video.save('video.mp4')Models
Recommended Models (2025)
Always prefer the latest models for the best performance and cost-efficiency.
| Capability | Model Name | Description |
|---|---|---|
| General & Multimodal | gemini-3-flash-preview | Best for most text/multimodal tasks. High speed, low cost. |
| Reasoning & Coding | gemini-3-pro-preview | Best for complex logic, math, and heavy coding tasks. |
| Low Latency | gemini-2.5-flash-lite | Optimized for high-volume, low-latency tasks. |
| Image Generation | gemini-2.5-flash-image | "Nano Banana". Fast image generation. |
| High-Quality Images | gemini-3-pro-image-preview | "Nano Banana Pro". High-fidelity image generation. |
| Video Generation | veo-3.0-generate-001 | High-quality video generation. |
| Fast Video | veo-3.0-fast-generate-001 | Faster video generation. |
Deprecated Models
Do not use:
gemini-1.5-*gemini-progemini-ultra
Model Capabilities
- Gemini 3 Series: Native reasoning (
thinking_level), high-precision tool use. - Gemini 2.5 Series: Reasoning via
thinking_budget. - Veo: Video generation from text or image prompts.
Multimodal Inputs
Gemini supports Text, Images, Audio, Video, and PDF documents.
Images (PIL & Bytes)
# PIL
from PIL import Image
img = Image.open('image.jpg')
# Bytes
with open('image.jpg', 'rb') as f:
img_bytes = f.read()
response = client.models.generate_content(
model='gemini-3-flash-preview',
contents=[
img, # Or types.Part.from_bytes(img_bytes, mime_type='image/jpeg')
'Describe this.'
]
)Audio & Video (File API)
For large files (video, long audio), use the Files API.
# Upload
video_file = client.files.upload(file='video.mp4')
# Generate
response = client.models.generate_content(
model='gemini-3-flash-preview',
contents=[video_file, 'What happens in this video?']
)
# Cleanup
client.files.delete(name=video_file.name)Media Resolution
Control vision detail vs. token usage. Levels: LOW, MEDIUM, HIGH, ULTRA_HIGH.
# Per-part configuration
part = types.Part.from_uri(
file_uri='...',
mime_type='image/jpeg',
media_resolution=types.PartMediaResolution(
level=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW
)
)Reasoning (Thinking)
Reasoning models generate "thoughts" before the final response to improve accuracy on complex tasks.
Configuration
Gemini 3 Series
Use thinking_level to control reasoning depth.
-
MINIMAL: Minimal reasoning, lowest latency. -
LOW: Simple tasks. -
MEDIUM: Balanced. -
HIGH: Maximum depth (default).
config = types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=types.ThinkingLevel.HIGH,
include_thoughts=True # Returns thoughts in response
)
)Gemini 2.5 Series
Use thinking_budget (token count).
-
0: Thinking OFF. -
1024: Specific token budget.
config = types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_budget=1024,
include_thoughts=True
)
)Accessing Thoughts
If include_thoughts=True, thoughts are returned as parts.
for part in response.candidates[0].content.parts:
if part.thought:
print(f"Thought: {part.text}")
else:
print(f"Response: {part.text}")Thought Signatures
When using tools with reasoning models, the API returns an encrypted thought_signature.
- Automatic: The SDK handles this automatically when using
chatsor preserving the fullresponseobject in history. - Manual: If manually constructing history, you must include the
thought_signaturefrom the model's turn in the next request to avoid errors.
Setup and Initialization
Installation
Golden Rule: Always use the google-genai SDK. Do not use legacy google-generativeai.
pip install google-genaiInitialization
The SDK requires a client object. It implicitly uses the GEMINI_API_KEY (or GOOGLE_API_KEY) environment variable.
from google import genai
from google.genai import types
# Standard initialization
client = genai.Client()
# Explicit API key (avoid hardcoding in production)
# client = genai.Client(api_key='YOUR_API_KEY')
# Vertex AI Initialization
# client = genai.Client(
# vertexai=True,
# project='your-project-id',
# location='us-central1'
# )Best Practices
- Imports: Use
from google import genaiandfrom google.genai import types. - Statelessness: The client is predominantly stateless. Access methods via
client.models,client.chats, etc.
Google GenAI SDK Source Code
Use web_fetch to retrieve raw code for deep inspection of SDK internals.
Base URL: https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/
Core
- Client:
client.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/client.py - Config & Types:
types.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/types.py
Features
- Text/Multimodal:
models.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/models.py - Chat:
chats.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/chats.py - Files:
files.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/files.py - Live API:
live.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/live.py - Tuning:
tunings.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/tunings.py - Batch:
batches.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/batches.py
Internal
- Transformers:
_transformers.py-https://raw.githubusercontent.com/googleapis/python-genai/main/google/genai/_transformers.py
Structured Output
Enforce specific response structures using response_schema.
Pydantic Models (Recommended)
from pydantic import BaseModel
class Recipe(BaseModel):
name: str
ingredients: list[str]
response = client.models.generate_content(
model='gemini-3-flash-preview',
contents='Cookie recipe',
config=types.GenerateContentConfig(
response_mime_type='application/json',
response_schema=Recipe,
),
)
# Access parsed object directly
print(response.parsed)JSON Schema (Dict)
schema = {
"type": "OBJECT",
"properties": {
"name": {"type": "STRING"},
"age": {"type": "INTEGER"}
}
}
response = client.models.generate_content(
...,
config=types.GenerateContentConfig(
response_mime_type='application/json',
response_schema=schema
)
)Enums
You can also restrict output to a specific enum.
import enum
class Grade(enum.Enum):
A = "A"
B = "B"
config=types.GenerateContentConfig(
response_mime_type='text/x.enum',
response_schema=Grade
)Text Generation & Configuration
Basic Generation
response = client.models.generate_content(
model='gemini-3-flash-preview',
contents='Why is the sky blue?',
)
print(response.text)Streaming
Reduces time-to-first-token.
response = client.models.generate_content_stream(
model='gemini-3-flash-preview',
contents='Write a long story about a space pirate.'
)
for chunk in response:
print(chunk.text, end='')Configuration (GenerateContentConfig)
Control generation parameters, system instructions, and safety.
System Instructions
config = types.GenerateContentConfig(
system_instruction='You are a pirate. Speak like one.',
)Hyperparameters
Note: For Gemini 3 models, keep temperature at 1.0 (default) for optimal reasoning.
config = types.GenerateContentConfig(
temperature=1.0,
max_output_tokens=500,
top_p=0.95,
)Safety Settings
Avoid setting these unless explicitly requested.
config = types.GenerateContentConfig(
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
),
]
)Content & Part Hierarchy
For complex requests (e.g., specific roles), use Content and Part objects explicitly.
contents=[
types.Content(
role='user',
parts=[types.Part.from_text(text='Hello')]
)
]Tools & Grounding
Grounding (Google Search)
Enable the model to access real-time information.
tools = [types.Tool(google_search=types.GoogleSearch())]
response = client.models.generate_content(..., config=types.GenerateContentConfig(tools=tools))Code Execution
Enable Python code generation and execution.
tools = [types.Tool(code_execution=types.ToolCodeExecution())]Function Calling
Pass Python functions to the model.
Definition
def get_weather(city: str) -> str:
"""Returns weather for a city."""
return "Sunny"
tools = [get_weather]Configuration
config = types.GenerateContentConfig(
tools=tools,
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode=types.FunctionCallingConfigMode.AUTO, # or ANY, NONE
stream_function_call_arguments=True # For streaming args
)
)
)Handling (Automatic)
Use client.chats or preserve history, and the SDK handles execution automatically.
Handling (Manual)
Check response.function_calls, execute, and return types.Part.from_function_response.