### Google GenAI SDK - Installation and Client Setup Source: https://context7.com/cnemri/google-genai-skills/llms.txt Instructions on how to install the `google-genai` SDK and initialize the client for accessing Gemini API and Vertex AI. Supports standard, API key, and Vertex AI initialization. ```APIDOC ## Google GenAI SDK - Installation and Client Setup ### Description Install the `google-genai` SDK and initialize the client to start making API calls for text generation, multimodal processing, and media generation. Supports standard initialization (using environment variables), explicit API key initialization, and Vertex AI initialization for enterprise features. ### Method N/A (Installation and Client Setup) ### Endpoint N/A ### Parameters #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Install the SDK # pip install google-genai from google import genai from google.genai import types # Standard initialization (uses GEMINI_API_KEY or GOOGLE_API_KEY env var) client = genai.Client() # Explicit API key initialization client = genai.Client(api_key='YOUR_API_KEY') # Vertex AI initialization (for enterprise features) client = genai.Client( vertexai=True, project='your-project-id', location='us-central1' ) ``` ### Response #### Success Response (200) N/A (Client initialization does not return a direct response in this context) #### Response Example N/A ``` -------------------------------- ### Install google-genai SDK Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-genai-sdk-python/references/setup.md Installs the official google-genai Python SDK using pip. This is the recommended package for interacting with Google's generative AI models. ```bash pip install google-genai ``` -------------------------------- ### Quick Start Setup for Google GenAI SDK Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/SKILL.md Initializes the Google GenAI client and imports necessary libraries for image generation and manipulation. This setup is crucial before interacting with any Gemini image models. ```python from google import genai from google.genai import types from PIL import Image import io client = genai.Client() ``` -------------------------------- ### Generate High-Resolution Product Mockups with Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Produce high-resolution, commercial-quality product photographs using Gemini 2.5 Flash. This example details a specific setup for a ceramic coffee mug, including lighting, camera angle, and focus. ```python response = client.models.generate_content( model="gemini-2.5-flash-image", contents="A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.", ) ``` -------------------------------- ### Install and Initialize Google GenAI SDK Source: https://context7.com/cnemri/google-genai-skills/llms.txt Installs the `google-genai` SDK and demonstrates different ways to initialize the client for accessing Gemini API and Vertex AI. Requires API keys or project configuration for authentication. ```python # Install the SDK # pip install google-genai from google import genai from google.genai import types # Standard initialization (uses GEMINI_API_KEY or GOOGLE_API_KEY env var) client = genai.Client() # Explicit API key initialization client = genai.Client(api_key='YOUR_API_KEY') # Vertex AI initialization (for enterprise features) client = genai.Client( vertexai=True, project='your-project-id', location='us-central1' ) ``` -------------------------------- ### Python: Before Agent Callback Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/callbacks.md Provides an example of a callback that runs before an agent starts its execution. This can be used for setting up agent context or logging initial parameters. ```python from genai.callback import CallbackHandler class BeforeAgentCallbackHandler(CallbackHandler): def on_agent_start(self, agent_input: dict) -> None: print(f"Agent starting with input: {agent_input}") # Example usage: # callback_handler = BeforeAgentCallbackHandler() # agent.run(..., callbacks=[callback_handler]) ``` -------------------------------- ### Virtual Try-On with Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Place a garment onto a model in an image using the Gemini API. This example assumes you have URIs for both the model image and the garment image stored in Google Cloud Storage. ```python response = client.models.generate_content( model='gemini-2.5-flash-image', contents=[ types.Part.from_uri(file_uri="gs://.../model.jpg", mime_type="image/jpeg"), types.Part.from_uri(file_uri="gs://.../dress.jpg", mime_type="image/jpeg"), "Realistically place the dress from the second image onto the person in the first image." ] ) ``` -------------------------------- ### Python Pub/Sub Integration Example Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/advanced-tools.md Provides a Python example for integrating with Google Cloud Pub/Sub. This snippet illustrates how to publish messages to a topic or subscribe to messages from a subscription. It's useful for building event-driven architectures and asynchronous communication patterns. ```python from google.cloud import pubsub_v1 def publish_message(project_id, topic_id, message): """Publishes a message to a Pub/Sub topic. (Producer)""" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) # Data must be a bytestring data = message.encode("utf-8") # When you publish a message, the client returns a future. future = publisher.publish(topic_path, data) print(f"Published message ID: {future.result()}") def receive_messages(project_id, subscription_id): """Receives messages from a Pub/Sub subscription. (Consumer)""" subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message): print(f"Received message: {message.data.decode('utf-8')}") message.ack() # Acknowledge the message streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f"Listening for messages on {subscription_path}...") # Keep the main thread alive to process messages try: streaming_pull_future.result() except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown streaming_pull_future.join() # Wait for the shutdown to complete ``` -------------------------------- ### Quick Start Setup for Speech Skill Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/speech-build/SKILL.md Initializes the Google GenAI client for speech-related operations. This setup is a prerequisite for using TTS and STT functionalities. ```python from google import genai from google.genai import types # For STT: from google.cloud import speech_v2 client = genai.Client() ``` -------------------------------- ### Install Specific Skill using npx Source: https://github.com/cnemri/google-genai-skills/blob/main/README.md This command installs a specific skill from the 'cnemri/google-genai-skills' repository using the 'npx' package runner. It's a convenient way to add individual skills to your agent's environment. ```bash npx skills add cnemri/google-genai-skills --skill google-adk-python ``` -------------------------------- ### Initialize google-genai Client Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-genai-sdk-python/references/setup.md Demonstrates various ways to initialize the google-genai client. It covers standard initialization using environment variables, explicit API key usage (discouraged for production), and Vertex AI integration. ```python from google import genai from google.genai import types # Standard initialization client = genai.Client() ``` ```python from google import genai # Explicit API key (avoid hardcoding in production) client = genai.Client(api_key='YOUR_API_KEY') ``` ```python from google import genai # Vertex AI Initialization client = genai.Client( vertexai=True, project='your-project-id', location='us-central1' ) ``` -------------------------------- ### Create Minimalist Backgrounds for Text Overlays using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Design minimalist compositions with ample negative space, ideal for text overlays. This example generates an image with a single red maple leaf on an off-white background, specifying lighting and composition. ```python response = client.models.generate_content( model="gemini-2.5-flash-image", contents="A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.", ) ``` -------------------------------- ### Grounding Image Generation with Google Search using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Generate images based on real-time data by integrating Google Search with Gemini 3 Pro. This example creates a graphic related to a specific sports event, specifying aspect ratio and utilizing the search tool. ```python response = client.models.generate_content( model="gemini-3-pro-image-preview", contents="Make a simple but stylish graphic of last night's Arsenal game in the Champion's League", config=types.GenerateContentConfig( tools=[types.Tool(google_search=types.GoogleSearch())], image_config=types.ImageConfig(aspect_ratio="16:9") ) ) ``` -------------------------------- ### Modern Logo Design with Text Rendering using Python (Gemini 3 Pro) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Create modern, minimalist logos with accurate text rendering, specifically utilizing Gemini 3 Pro. This example demonstrates logo generation for a coffee shop, specifying font style, color scheme, and incorporating a coffee bean element. ```python response = client.models.generate_content( model="gemini-3-pro-image-preview", contents="Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.", config=types.GenerateContentConfig( image_config=types.ImageConfig(aspect_ratio="1:1") ) ) ``` -------------------------------- ### Product Recontextualization with Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Place a product image into a new scene or context using the Gemini API. This is useful for generating product mockups or visualizing products in different environments. ```python response = client.models.generate_content( model='gemini-2.5-flash-image', contents=[ types.Part.from_uri(file_uri="gs://.../product.png", mime_type="image/png"), "Place this product on a marble countertop in a luxury kitchen." ] ) ``` -------------------------------- ### Control Aspect Ratio with Blank Canvas using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Force a specific aspect ratio for image generation by providing a blank image of the desired dimensions. This example uses the Pillow library to create a blank PNG image and then sends it to the Gemini API. ```python from PIL import Image import io def create_canvas(width=1280, height=720): img = Image.new("RGB", (width, height), "white") buf = io.BytesIO() img.save(buf, format="PNG") return types.Part.from_bytes(data=buf.getvalue(), mime_type="image/png") response = client.models.generate_content( model='gemini-2.5-flash-image', contents=[ create_canvas(1280, 720), "A cinematic wide shot of a desert planet." ] ) ``` -------------------------------- ### Setup Google GenAI Client for Veo Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-build/SKILL.md Initializes the google-genai library and an authenticated client with Vertex AI enabled. This is a prerequisite for all Veo operations. It requires setting the GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_REGION environment variables. ```python from google import genai from google.genai import types import os PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT") LOCATION = os.environ.get("GOOGLE_CLOUD_REGION", "us-central1") client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION) ``` -------------------------------- ### Create Stylized Stickers with Transparent Backgrounds using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Generate stylized stickers with clean outlines and simple shading, suitable for various applications. This example focuses on a 'kawaii' style and specifies a white background, implying transparency can be handled post-generation if needed. ```python response = client.models.generate_content( model="gemini-2.5-flash-image", contents="A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.", ) ``` -------------------------------- ### Sequential Art (Comics) Generation with Character References using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Create multi-panel comic storytelling using character references with Gemini 3 Pro. This example generates a 3-panel comic in a noir style, incorporating a character reference image. ```python response = client.models.generate_content( model="gemini-3-pro-image-preview", contents=[ "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humorous scene.", types.Part.from_uri(file_uri="gs://.../character.jpg", mime_type="image/jpeg") ], ) ``` -------------------------------- ### Generate Video from Image using Veo Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-use/SKILL.md Generates a video starting from a static image. This function takes a text prompt to guide the video's content and an input image file. The output is saved to a specified MP4 file. ```bash uv run skills/veo-use/scripts/image_to_video.py "Zoom out from the flower" --image start.png --output flower.mp4 ``` -------------------------------- ### Python Spanner Integration Example Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/advanced-tools.md Features a Python example for interacting with Google Cloud Spanner. This snippet likely demonstrates how to establish a connection, execute DML statements (INSERT, UPDATE, DELETE), and query data from Spanner tables. It's valuable for developers working with globally distributed, strongly consistent databases. ```python from google.cloud import spanner def sample_update_data(instance_id, database_id): """Updates data in a Spanner database. (Producer)""" spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) database = instance.database(database_id) def update_data(transaction): transaction.insert( "Singers", [ { "SingerId": "10", "FirstName": "Marc", "LastName": "Richards", } ], ) database.run_in_transaction(update_data) print("Added Singer.") def sample_query_data(instance_id, database_id): """Queries data from a Spanner database. (Consumer)""" spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) database = instance.database(database_id) with database.snapshot() as snapshot: results = snapshot.execute_sql( "SELECT SingerId, FirstName, LastName FROM Singers WHERE SingerId = 10" ) for row in results: print(f"SingerId: {row[0]}, FirstName: {row[1]}, LastName: {row[2]}") ``` -------------------------------- ### Python: Basic Callback Example Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/callbacks.md Demonstrates a basic implementation of a callback function in Python. Callbacks are functions passed as arguments to other functions, to be executed later. ```python from genai.callback import CallbackHandler class MyCallbackHandler(CallbackHandler): def __init__(self): super().__init__() def on_tool_start(self, tool_name: str, input_data: dict) -> None: print(f"Tool '{tool_name}' started with input: {input_data}") def on_tool_end(self, tool_name: str, output_data: dict) -> None: print(f"Tool '{tool_name}' ended with output: {output_data}") # Example usage (assuming you have a tool runner setup): # callback_handler = MyCallbackHandler() # tool_runner.run(..., callbacks=[callback_handler]) ``` -------------------------------- ### Generate Video with Reference Image using Veo Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-use/SKILL.md Guides video generation using specific asset images, such as subjects or products. This script requires a text prompt, a reference image, and an output file name. ```bash uv run skills/veo-use/scripts/reference_to_video.py "A man walking on the moon" --reference-image man.png --output moon_walk.mp4 ``` -------------------------------- ### Generate Polished Image from Sketch (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Converts a rough drawing into a polished image using the Gemini API. This function takes a sketch image URI and a text prompt to guide the image generation. It requires the 'google-generativeai' library and an initialized client. ```python response = client.models.generate_content( model="gemini-3-pro-image-preview", contents=[ types.Part.from_uri(file_uri="gs://.../car_sketch.png", mime_type="image/png"), "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting." ], ) ``` -------------------------------- ### Maintain Character Consistency Across Scenes with Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Ensure a character's appearance remains consistent across multiple generated images. This example uses a reference image of the character and a prompt to generate a new scene featuring them. ```python response = client.models.generate_content( model='gemini-2.5-flash-image', contents=[ types.Part.from_uri(file_uri="gs://.../character_ref.png", mime_type="image/png"), "Generate an image of this character eating an apple in a park." ] ) ``` -------------------------------- ### Python Bigtable Integration Example Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/advanced-tools.md Demonstrates how to integrate with Google Cloud Bigtable using Python. This snippet likely involves setting up a connection, performing read/write operations, and handling data within a Python environment. It serves as a practical example for developers looking to leverage Bigtable with their applications. ```python from google.cloud import bigtable def sample_simple_mutation(project_id, instance_id, table_id): """Performs a simple mutation on a row. (Producer)""" client = bigtable.Client(project=project_id, admin=True) instance = client.instance(instance_id) table = instance.table(table_id) row_key = b"simple-row-key" row = table.direct_row(row_key) # Set a value for a specific column column_name = "test-column" row.set_cell("test-family", column_name, "test-value") # Commit the mutation row.commit() print("Mutated row {}".format(row_key.decode('utf-8'))) ``` -------------------------------- ### Clone Google GenAI Skills Repository Source: https://github.com/cnemri/google-genai-skills/blob/main/README.md This command clones the entire 'google-genai-skills' repository from GitHub to a specified local directory. This is useful for manual installation or if you need access to all skills and their source code. ```bash git clone https://github.com/cnemri/google-genai-skills.git ~/.gemini/skills/google-genai-skills ``` -------------------------------- ### Compose Image from Multiple References (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/recipes.md Combines up to 14 reference images to create a new composition using the Gemini API. This advanced feature allows for detailed control over aspect ratio and image size. It requires the 'google-generativeai' library and an initialized client. ```python response = client.models.generate_content( model="gemini-3-pro-image-preview", contents=[ "An office group photo of these people, they are making funny faces.", types.Part.from_uri(file_uri="gs://.../person1.png", mime_type="image/png"), types.Part.from_uri(file_uri="gs://.../person2.png", mime_type="image/png"), types.Part.from_uri(file_uri="gs://.../person3.png", mime_type="image/png"), # ... up to 14 images total ], config=types.GenerateContentConfig( image_config=types.ImageConfig(aspect_ratio="5:4", image_size="2K") ) ) ``` -------------------------------- ### Apply Style Transfer Between Images (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/references/image_editing.md Transfer the visual style from one image to the content of another. This example uses the 'gemini-2.5-flash-image' model, taking a style reference image and a prompt to generate a new image with the specified aesthetic. ```python response = client.models.generate_content( model='gemini-2.5-flash-image', contents=[ types.Part.from_uri(file_uri="gs://.../style_ref.png", mime_type="image/png"), "Using the concepts and colors from this image, generate a kitchen with the same aesthetic." ], config=types.GenerateContentConfig(response_modalities=["IMAGE"]) ) ``` -------------------------------- ### Multimodal Inputs - Images, Audio, Video Source: https://context7.com/cnemri/google-genai-skills/llms.txt Process multimodal inputs including images, audio, and video using Gemini's capabilities. Examples show image handling via PIL and bytes, and using the Files API for larger media files. ```APIDOC ## Multimodal Inputs - Images, Audio, Video ### Description Process images, audio, video, and documents with Gemini's multimodal capabilities. This endpoint allows for rich input types beyond plain text, enabling more sophisticated AI applications. ### Method POST ### Endpoint `/models/generateContent` (handles multimodal content) `/files/upload` (for uploading large media files) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **model** (string) - Required - The name of the model to use. - **contents** (list) - Required - A list containing media parts and text prompts. - **Part** (object) - Represents a part of the content. Can be text, bytes, a file URI, or a Part object with media resolution control. - **from_bytes** (bytes) - Image/Audio/Video data. - **mime_type** (string) - MIME type of the data (e.g., 'image/jpeg', 'video/mp4'). - **file_uri** (string) - URI of a file uploaded via the Files API. - **media_resolution** (object) - Controls media resolution for vision detail vs. token usage. - **level** (enum) - `MEDIA_RESOLUTION_LOW` or `MEDIA_RESOLUTION_HIGH`. ### Request Example ```python from google import genai from google.genai import types from PIL import Image client = genai.Client() # Image input with PIL img = Image.open('image.jpg') response = client.models.generate_content( model='gemini-3-flash-preview', contents=[img, 'Describe this image.'] ) print(response.text) # Image from bytes with open('image.jpg', 'rb') as f: img_bytes = f.read() response = client.models.generate_content( model='gemini-3-flash-preview', contents=[ types.Part.from_bytes(img_bytes, mime_type='image/jpeg'), 'What objects are in this image?' ] ) # Video/Audio via Files API (for large files) video_file = client.files.upload(file='video.mp4') response = client.models.generate_content( model='gemini-3-flash-preview', contents=[video_file, 'What happens in this video?'] ) print(response.text) client.files.delete(name=video_file.name) # Cleanup # Control media resolution for vision detail vs. token usage part = types.Part.from_uri( file_uri='gs://bucket/image.jpg', mime_type='image/jpeg', media_resolution=types.PartMediaResolution( level=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW ) ) ``` ### Response #### Success Response (200) - **text** (string) - The model's description or analysis of the multimodal input. #### Response Example ```json { "text": "This image contains a cat sitting on a windowsill, looking outside." } ``` ``` -------------------------------- ### Python Vertex AI RAG Engine Integration Example Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/advanced-tools.md Illustrates how to use the Vertex AI Retrieval Augmented Generation (RAG) Engine with Python. This snippet likely shows how to configure the RAG engine, provide a query, and retrieve relevant documents or data to augment the generation process. It's key for building more informed and context-aware AI applications. ```python from google.cloud import aiplatform from google.cloud.aiplatform.matching_engine import MatchingEngineIndexEndpoint def sample_vertex_ai_rag_engine( project: str, location: str, index_endpoint_id: str, deployed_index_id: str, query_text: str, ): """Uses the Vertex AI RAG Engine to retrieve documents for a query. (Consumer)""" aiplatform.init(project=project, location=location) index_endpoint = MatchingEngineIndexEndpoint( index_endpoint_id=index_endpoint_id, deployed_index_id=deployed_index_id, ) # The `get_nearest_neighbors` method is used to retrieve relevant documents. # The number of neighbors to retrieve can be specified using `num_neighbors`. response = index_endpoint.get_nearest_neighbors( deployed_index_id=deployed_index_id, queries=[ { "datapoint": { "numeric": {}, "sparse_vector": { "indices": [], "values": [], }, }, "neighbor_count": 3, } ], filter_value=query_text, # Example of using a filter based on query text ) print("Retrieved documents:") for neighbor in response.nearest_neighbors: print(f" - ID: {neighbor.datapoint.match_id}, Distance: {neighbor.distance}") ``` -------------------------------- ### Initialize Chat with Custom History (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-genai-sdk-python/references/chat.md Illustrates how to start a new chat session pre-populated with a custom conversation history. This is useful for resuming conversations or providing initial context. It uses the 'types.Content' and 'types.Part' objects to define the history. Assumes 'client' is an initialized Google GenAI client. ```python 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) ``` -------------------------------- ### Text Generation - Basic and Streaming Source: https://context7.com/cnemri/google-genai-skills/llms.txt Demonstrates how to generate text responses using Gemini models. Covers basic text generation, streaming for reduced latency, and advanced configuration with system instructions and hyperparameters. ```APIDOC ## Text Generation - Basic and Streaming ### Description Generate text responses using Gemini models with support for streaming, system instructions, and hyperparameter configuration. This endpoint allows for both standard text generation and real-time streaming of responses. ### Method POST ### Endpoint `/models/generateContent` (for basic generation) `/models/generateContentStream` (for streaming generation) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **model** (string) - Required - The name of the model to use (e.g., 'gemini-3-flash-preview'). - **contents** (string or list) - Required - The input prompt or content for generation. - **config** (object) - Optional - Configuration for generation, including `system_instruction`, `temperature`, `max_output_tokens`, `top_p`. - **system_instruction** (string) - Optional - Instructions for the model's persona or behavior. - **temperature** (number) - Optional - Controls randomness. Higher values mean more random output. - **max_output_tokens** (integer) - Optional - The maximum number of tokens to generate. - **top_p** (number) - Optional - Nucleus sampling parameter. ### Request Example ```python from google import genai from google.genai import types client = genai.Client() # Basic text generation response = client.models.generate_content( model='gemini-3-flash-preview', contents='Why is the sky blue?' ) print(response.text) # Streaming for reduced 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='') # With system instructions and configuration response = client.models.generate_content( model='gemini-3-flash-preview', contents='Tell me about yourself', config=types.GenerateContentConfig( system_instruction='You are a pirate. Speak like one.', temperature=1.0, max_output_tokens=500, top_p=0.95, ) ) print(response.text) ``` ### Response #### Success Response (200) - **text** (string) - The generated text response from the model. #### Response Example ```json { "text": "The sky appears blue due to a phenomenon called Rayleigh scattering..." } ``` ``` -------------------------------- ### Fast Image Generation with Gemini 2.5 Flash Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-build/SKILL.md Demonstrates how to generate an image from a text prompt using the `gemini-2.5-flash-image` model. This is suitable for quick, high-quality image creation. ```python response = client.models.generate_content( model='gemini-2.5-flash-image', contents='A cute robot eating a banana', config=types.GenerateContentConfig( response_modalities=['IMAGE'] ) ) ``` -------------------------------- ### Transcribe Audio using Chirp 3 Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/speech-build/SKILL.md Transcribes audio content using the Chirp 3 model via the google-cloud-speech SDK. This snippet requires the google-cloud-speech library to be installed and configured. ```python # Requires google-cloud-speech from google.cloud import speech_v2 # ... (See stt.md for full setup) response = speech_client.recognize(...) ``` -------------------------------- ### Multimodal Content Processing with Gemini Source: https://context7.com/cnemri/google-genai-skills/llms.txt Illustrates how to use Gemini's multimodal capabilities to process images, audio, and video. Shows image input using PIL and bytes, handling large media files via the Files API, and controlling media resolution for detailed analysis or token efficiency. ```python from google import genai from google.genai import types from PIL import Image client = genai.Client() # Image input with PIL img = Image.open('image.jpg') response = client.models.generate_content( model='gemini-3-flash-preview', contents=[img, 'Describe this image.'] ) print(response.text) # Image from bytes with open('image.jpg', 'rb') as f: img_bytes = f.read() response = client.models.generate_content( model='gemini-3-flash-preview', contents=[ types.Part.from_bytes(img_bytes, mime_type='image/jpeg'), 'What objects are in this image?' ] ) # Video/Audio via Files API (for large files) video_file = client.files.upload(file='video.mp4') response = client.models.generate_content( model='gemini-3-flash-preview', contents=[video_file, 'What happens in this video?'] ) print(response.text) client.files.delete(name=video_file.name) # Cleanup # Control media resolution for vision detail vs. token usage part = types.Part.from_uri( file_uri='gs://bucket/image.jpg', mime_type='image/jpeg', media_resolution=types.PartMediaResolution( level=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW ) ) ``` -------------------------------- ### Handle Image Inputs with PIL and Bytes in Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-genai-sdk-python/references/multimodal_inputs.md Demonstrates how to load images using PIL and read them as bytes for input to the Gemini API. It shows the process of opening an image file and preparing it, along with the byte representation, to be sent as content to the model. ```python # 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.' ] ) ``` -------------------------------- ### Generate Video from Text using Veo Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-use/SKILL.md Creates a video from a text description using the Veo model. Requires a text prompt and an output file path. The script utilizes Python and is executed via 'uv run'. ```bash uv run skills/veo-use/scripts/text_to_video.py "A cinematic drone shot of a futuristic city" --output city.mp4 ``` -------------------------------- ### Extend Video Duration using Veo Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-use/SKILL.md Extends the duration of an existing video clip. This script requires the input video file, a prompt to guide the extension, the desired duration in seconds, and an output file path. ```bash uv run skills/veo-use/scripts/extend_video.py --video clip.mp4 --prompt "The car flies away into the sunset" --duration 6 --output extended.mp4 ``` -------------------------------- ### Basic and Streaming Text Generation with Gemini Source: https://context7.com/cnemri/google-genai-skills/llms.txt Shows how to generate text responses using Gemini models, including basic generation, streaming for faster initial responses, and configuring system instructions and generation parameters like temperature and max output tokens. ```python from google import genai from google.genai import types client = genai.Client() # Basic text generation response = client.models.generate_content( model='gemini-3-flash-preview', contents='Why is the sky blue?', ) print(response.text) # Streaming for reduced 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='') # With system instructions and configuration response = client.models.generate_content( model='gemini-3-flash-preview', contents='Tell me about yourself', config=types.GenerateContentConfig( system_instruction='You are a pirate. Speak like one.', temperature=1.0, max_output_tokens=500, top_p=0.95, ) ) print(response.text) ``` -------------------------------- ### Configure System Instructions for AI Generation (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-genai-sdk-python/references/text_generation.md Illustrates how to set system instructions for the AI model using `types.GenerateContentConfig`. This allows defining the AI's persona or behavior. It requires the `google.generativeai.types` module. ```python from google.generativeai import types config = types.GenerateContentConfig( system_instruction='You are a pirate. Speak like one.', ) ``` -------------------------------- ### Reasoning and Thinking Configuration (Python) Source: https://context7.com/cnemri/google-genai-skills/llms.txt Configures reasoning depth for complex tasks using thinking models. For Gemini 3 Series, `thinking_level` (MINIMAL, LOW, MEDIUM, HIGH) is used. For Gemini 2.5 Series, `thinking_budget` (token count) is used. `include_thoughts=True` returns the model's reasoning process. ```python from google import genai from google.genai import types client = genai.Client() # Gemini 3 Series - Use thinking_level # Levels: MINIMAL, LOW, MEDIUM, HIGH (default) response = client.models.generate_content( model='gemini-3-flash-preview', contents='Solve this complex math problem: What is the integral of x^2 * e^x?', config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig( thinking_level=types.ThinkingLevel.HIGH, include_thoughts=True # Returns thoughts in response ) ) ) # Access thoughts and response for part in response.candidates[0].content.parts: if part.thought: print(f"Thought: {part.text}") else: print(f"Response: {part.text}") # Gemini 2.5 Series - Use thinking_budget (token count) config = types.GenerateContentConfig( thinking_config=types.ThinkingConfig( thinking_budget=1024, # 0 = OFF, 1024 = specific budget include_thoughts=True ) ) ``` -------------------------------- ### Edit Image with Nano Banana (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/nano-banana-use/SKILL.md Edits an existing image based on a text prompt using Gemini Nano Banana models. Requires Python and authentication setup. Takes an input image, a prompt, and outputs the edited image. ```bash uv run skills/nano-banana-use/scripts/edit_image.py original.png "Make the sky purple" --output edited.png ``` -------------------------------- ### Batch Get Google Developer Documents (Bash) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-developer-knowledge/SKILL.md Retrieves up to 20 documents in a single API call by providing a space-separated list of document names. The results can be saved to a specified directory using the `--output` option. This script requires `curl` and the `DEVELOPERKNOWLEDGE_API_KEY` environment variable. ```bash ./skills/google-developer-knowledge/scripts/batch_get_documents.sh \ "documents/ai.google.dev/gemini-api/docs/get-started/python" \ "documents/ai.google.dev/gemini-api/docs/models" ``` -------------------------------- ### Python: Before Tool Callback Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/callbacks.md Illustrates a callback that runs before a tool is invoked. This allows for validation of tool inputs or preparation for tool execution. ```python from genai.callback import CallbackHandler class BeforeToolCallbackHandler(CallbackHandler): def on_tool_start(self, tool_name: str, input_data: dict) -> None: print(f"Tool '{tool_name}' is about to start with input: {input_data}") # Example usage: # callback_handler = BeforeToolCallbackHandler() # tool_runner.run(..., callbacks=[callback_handler]) ``` -------------------------------- ### Get Single Google Developer Document (Bash) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-developer-knowledge/SKILL.md Retrieves the full content of a specific document using its name, typically obtained from search results. The content can be displayed directly or saved to a JSON file using the `--output` option. This script relies on `curl` and the `DEVELOPERKNOWLEDGE_API_KEY` environment variable. ```bash ./skills/google-developer-knowledge/scripts/get_document.sh "documents/ai.google.dev/gemini-api/docs/get-started/python" ``` ```bash ./skills/google-developer-knowledge/scripts/get_document.sh "documents/ai.google.dev/..." --output doc.json ``` -------------------------------- ### Image-to-Video Generation using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-build/references/generation.md Generates a video by animating a static image based on a text prompt using the Veo 3 model. Requires the google.genai library and an image file. It takes a text prompt, an image input, and configuration options as input, outputting a video operation. ```python operation = client.models.generate_videos( model="veo-3.1-generate-001", prompt="zoom out of the flower field, play whimsical music", image=types.Image.from_file(location="path/to/image.png"), config=types.GenerateVideosConfig( aspect_ratio="16:9", duration_seconds=6, resolution="1080p", generate_audio=True, ), ) ``` -------------------------------- ### Text-to-Video Generation using Python Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-build/references/generation.md Generates a video from a text prompt using the Veo 3 model. Requires the google.genai library. It takes a text prompt and configuration options like aspect ratio, resolution, and duration as input, and outputs a video operation. ```python from google import genai from google.genai import types client = genai.Client(vertexai=True, project="YOUR_PROJECT", location="us-central1") operation = client.models.generate_videos( model="veo-3.1-generate-001", prompt="a cinematic wide shot of a detective interrogating a rubber duck in a dark room", config=types.GenerateVideosConfig( aspect_ratio="16:9", # "16:9" or "9:16" resolution="1080p", # "720p", "1080p", or "4k" (4k adds latency) duration_seconds=6, # 4, 6, or 8 number_of_videos=1, # 1 or 2 person_generation="allow_adult", # "allow_adult" or "dont_allow" enhance_prompt=True, # Let the model rewrite/improve your prompt generate_audio=True, # Generate synchronized audio output_gcs_uri="gs://your-bucket/output.mp4" # Optional: Save directly to GCS ), ) ``` -------------------------------- ### Generate Video with Asset Reference Images using Veo 3 Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/veo-build/references/advanced.md Guides video generation by using up to three specific reference images (assets) to maintain the identity of subjects, objects, or scenes. This method requires loading reference images and providing them in a list within the configuration, along with a prompt and other generation parameters like aspect ratio and duration. ```python # Load images from GCS or local files ref_image_1 = types.VideoGenerationReferenceImage( image=types.Image.from_file(location="man.png"), reference_type="asset", ) ref_image_2 = types.VideoGenerationReferenceImage( image=types.Image.from_file(location="woman.png"), reference_type="asset", ) operation = client.models.generate_videos( model="veo-3.1-generate-preview", # or veo-3.1-fast-generate-preview prompt="a woman and a man drinking a cup of coffee in a cafe", config=types.GenerateVideosConfig( reference_images=[ref_image_1, ref_image_2], # List of up to 3 references aspect_ratio="16:9", duration_seconds=8, person_generation="allow_adult", generate_audio=True, ), ) ``` -------------------------------- ### Run Basic Research Task (Bash) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/deep-research/SKILL.md Initiates a deep research task using the 'research.py' script. This command takes a research query as an argument and streams the results to the console. It requires the 'GOOGLE_API_KEY' environment variable and the 'google-genai' SDK. ```bash uv run skills/deep-research/scripts/research.py "Research the history of RISC-V architecture." ``` -------------------------------- ### Basic Chat with Gemini-3-Flash-Preview (Python) Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-genai-sdk-python/references/chat.md Demonstrates how to initiate a basic multi-turn conversation using the 'gemini-3-flash-preview' model. It sends an initial message and then a follow-up question to test context retention. Assumes 'client' is an initialized Google GenAI client. ```python 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) ``` -------------------------------- ### Python: Before Model Callback Source: https://github.com/cnemri/google-genai-skills/blob/main/skills/google-adk-python/references/callbacks.md Shows how to implement a callback that executes before a language model generates a response. Useful for pre-processing inputs or setting model configurations. ```python from genai.callback import CallbackHandler class BeforeModelCallbackHandler(CallbackHandler): def on_model_start(self, model_input: dict) -> None: print(f"Model about to generate with input: {model_input}") # Example usage: # callback_handler = BeforeModelCallbackHandler() # model.generate(..., callbacks=[callback_handler]) ```