Google GenAI Python SDK for the Gemini API
Reference guide and advanced configuration for the new unified google-genai SDK of the Gemini API in Portelcore.
Part 1: Fundamental Concepts and Initial Configuration
Sección titulada «Parte 1: Conceptos Fundamentales y Configuración Inicial»This section sets the context for the new SDK, addressing the main user confusion regarding the library change, and provides a robust guide to starting correctly, covering installation and the two critical authentication paths.
1.1. The New Standard: Migrating from google-generativeai to google-genai
Sección titulada «1.1. El Nuevo Estándar: Migrando de google-generativeai a google-genai»The development ecosystem for Google's generative AI models has evolved. The google-genai library is now the official, unified, and recommended Python SDK for interacting with the Gemini API and other Google generative AI models. It reached General Availability (GA) in May 2025 and replaces the legacy library, google-generativeai.
The previous library, google-generativeai, has been marked as “Inactive” on the Python Package Index (PyPI) and is on a path to obsolescence. Support for this package, including critical bug fixes, will cease at the end of September 2025, although some sources indicate a slightly earlier support end date, August 31, 2025. Developers are advised to aim for the earlier date to ensure a seamless transition.
This change is not simply a rename, but a strategic unification driven by developer feedback. The goal was to create a single SDK that simplifies access to the entire range of Google generative AI models (Gemini, Veo, Imagen, etc.) and offers a clearer and more consistent development path. One of the most significant design decisions of the new google-genai SDK is that it acts as a single interface for two distinct backend services: the easy-to-access Gemini developer API, and the enterprise-grade Vertex AI platform.
This unified architecture provides a smooth ramp-up for developers. They can quickly get started, often with a free tier, using an API key for the Gemini developer API. As their applications mature and require greater scalability, governance, and integration with other Google Cloud services, they can switch to the Vertex AI backend with minimal code changes, primarily in the client initialization. The google-genai SDK works as a bridge, reducing the barrier to entry while providing a clear path to production in Google Cloud. Therefore, all users of the legacy library are urged to migrate to ensure access to the latest features (such as Live API and Veo), performance improvements, and continuous support.
1.2. Installation and Environment
Sección titulada «1.2. Instalación y Entorno»Before installing the SDK, it is a best practice to set up a Python virtual environment. This isolates project dependencies, avoiding conflicts with other projects or system packages.
To create and activate a virtual environment using venv:
# En macOS/Linuxpython3 -m venv gemini-envsource gemini-env/bin/activate
# En Windowspy -m venv gemini-env.\gemini-env\Scripts\activateOnce the virtual environment is active, you can install the latest version of the Google Gen AI SDK using pip. Using the --upgrade flag ensures that the most recent version is obtained.
pip install --upgrade google-genaiIt is essential to keep the Python version requirements in mind. The google-genai SDK requires Python 3.9 or higher. Using an unsupported version may cause unexpected errors during installation or runtime.
For applications requiring high-performance asynchronous execution, the SDK offers an option to use aiohttp as the HTTP transport backend instead of the default httpx. This can be installed as an extra:
pip install google-genai[aiohttp]1.3. Authentication: Your Key to the Gemini API
Sección titulada «1.3. Autenticación: Su Clave para la API de Gemini»Authentication is the most critical configuration step, and the method differs depending on the intended backend service: the Gemini Developer API or the Gemini API on Vertex AI.
1.3.1. The Gemini Developer API Route (Recommended for Prototypes and Free Tier)
Sección titulada «1.3.1. La Vía de la API de Desarrollador de Gemini (Recomendada para Prototipos y Nivel Gratuito)»This is the fastest way to start building with Gemini. It requires an API key that can be obtained for free from Google AI Studio.
The process to obtain an API key is as follows:
- Navigate to (https://ai.google.dev/) and sign in with a Google account.
- Click on “Get API key”.
- Choose to create the API key in a new or existing Google Cloud project.
- The API key will be generated automatically.
API keys are sensitive credentials and must be treated like passwords. They must be stored securely and should never be exposed in client-side code or committed to public version control systems.
The most secure and recommended method to use the key is to set it as an environment variable. The SDK is designed to automatically detect and use the environment variables GOOGLE_API_KEY or GEMINI_API_KEY. If both are configured, GOOGLE_API_KEY takes priority.
To configure the environment variable:
-
On Linux/macOS (bash):
Ventana de terminal export GOOGLE_API_KEY='SU_CLAVE_DE_API_AQUI'# Agregue esta línea a su archivo ~/.bashrc o ~/.zshrc para que sea permanente -
On Windows: Use the “Environment Variables” graphical interface in the system settings to add a new user or system variable named
GOOGLE_API_KEYwith your key as the value.
1.3.2. The Vertex AI Way (Recommended for Production and Google Cloud Integration)
Sección titulada «1.3.2. La Vía de Vertex AI (Recomendada para Producción e Integración con Google Cloud)»For production-scale applications that require Google Cloud's enterprise features, it is recommended to use the Gemini API through Vertex AI. This approach requires a Google Cloud project with billing enabled.
Initial setup steps include:
- Select or create a Google Cloud project.
- Ensure that billing is enabled for the project.
- Enable the Vertex AI API (
aiplatform.googleapis.com) for the project.
Authentication for Vertex AI can be done in two ways:
-
Application Default Credentials (ADC) (Recommended for production): This is the preferred method for most production scenarios. ADC automatically finds credentials based on the environment. In a local development environment, this can be configured by running a gcloud CLI command:
Ventana de terminal gcloud auth application-default loginWhen running in a Google Cloud environment (e.g., Cloud Run, Google Kubernetes Engine, Cloud Functions), ADC automatically uses the service account attached to that resource, eliminating the need to manage keys.
-
API Keys (for testing in Vertex): It is possible to use an API key to authenticate to the Vertex AI endpoint, but the process is more complex than with the developer API. It requires organization-level permissions to enable service account API key creation, create a service account with an appropriate role (e.g.,
Vertex AI User), and then create an API key restricted to that service account. Due to its complexity, this method is generally used for specific testing scenarios rather than general application development.
1.4. Client Initialization: Connecting to the Model
Sección titulada «1.4. Inicialización del Cliente: Conectándose al Modelo»Once authentication is configured, the next step is to instantiate the genai.Client object. The unified SDK simplifies this by providing a single client that can be configured for either of the two backends.
The following are the four main scenarios for client initialization.
-
Scenario 1: Gemini Developer API (Explicit Key) This method is convenient for notebooks or quick scripts where you do not want to configure environment variables. The API key is passed directly as an argument.
from google import genaiclient = genai.Client(api_key="SU_CLAVE_DE_API_AQUI") -
Scenario 2: Gemini Developer API (Environment Variable) This is the cleanest and most recommended approach for application code, as it decouples credentials from the code. The client automatically finds and uses the
GOOGLE_API_KEYenvironment variable.# Asegúrese de que la variable de entorno GOOGLE_API_KEY esté configuradafrom google import genaiclient = genai.Client() -
Scenario 3: Vertex AI API (Explicit Parameters) To connect to Vertex AI, the flag
vertexaiis set toTrueand the project ID and location are provided. This method will automatically use Application Default Credentials (ADC) for authentication.from google import genaiclient = genai.Client(vertexai=True, project="su-id-de-proyecto-gcp", location="us-central1") -
Scenario 4: Vertex AI API (Environment Variables) As an alternative for Vertex AI, configuration can be externalized to environment variables. The client will detect these variables and will be configured to use the Vertex AI backend.
Ventana de terminal export GOOGLE_GENAI_USE_VERTEXAI=trueexport GOOGLE_CLOUD_PROJECT='su-id-de-proyecto-gcp'export GOOGLE_CLOUD_LOCATION='us-central1'# El cliente se configurará automáticamente para Vertex AIfrom google import genaiclient = genai.Client()
The following table summarizes these methods for quick reference.
Table 1: Client Initialization Quick Reference
| Use Case | Python Code | Required Environment Variables | Notes |
|---|---|---|---|
| Developer API with Explicit Key | client = genai.Client(api_key="SU_CLAVE...") | None | Useful for notebooks and quick testing. Avoid in production code. |
| Developer API with Env Var | client = genai.Client() | GOOGLE_API_KEY or GEMINI_API_KEY | Preferred method for clean and secure application code. |
| Vertex AI with Explicit Parameters | client = genai.Client(vertexai=True, project="...", location="...") | None (uses ADC) | Explicit method to point to Vertex AI. Requires ADC authentication (gcloud auth...). |
| Vertex AI with Env Var | client = genai.Client() | GOOGLE_GENAI_USE_VERTEXAI=true, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION | Configures the client for Vertex AI without parameters in the code. Requires ADC authentication. |
Part 2: Core Capabilities: Text and Chat
Sección titulada «Parte 2: Capacidades Principales: Texto y Chat»This part dives into the most common use cases: generating text and building conversational agents. It details the main methods and objects involved.
2.1. Generating Content: The generate_content Method
Sección titulada «2.1. Generando Contenido: El Método generate_content»The primary method for all single-turn generation tasks is client.models.generate_content(). This versatile method is the foundation for interacting with Gemini models.
A basic use involves providing a simple text string as contents and specifying the name of the model to use, such as gemini-2.5-flash.
import google.genai as genai
# Asumiendo que 'client' ha sido inicializado como se describió anteriormenteresponse = client.models.generate_content( model="gemini-2.5-flash", contents="Explica brevemente por qué el cielo es azul.")
print(response.text)While passing a simple string is convenient, it is fundamental to understand the underlying data structure that the SDK uses. Internally, the SDK converts all inputs into a standardized structure consisting of types.Content and types.Part objects. Understanding this structure is key to unlocking the SDK's advanced capabilities, such as multimodal prompts and function calling.
types.Content: Represents a single message or turn in a conversation. It has two main attributes: arole(usually ‘user’ for input or ‘model’ for output) and a list ofparts.types.Part: Represents a piece of data within aContentobject. A part can be text, image data, a file reference, a function call, etc.
The SDK intelligently handles various input types for the contents argument, converting them into the appropriate Content/Part format:
- A single string:
contents='¿Por qué el cielo es azul?'is converted into aUserContentwith a single textPart. - A list of strings:
contents=['Pregunta 1', 'Pregunta 2']is converted into a singleUserContentcontaining two textParts. - A
types.Partobject: Allows for more detailed control, such as specifying image data. - A fully formed
types.Contentobject: Provides maximum control over the message role and content.
To access the generated response, the response.text convenience accessor is the simplest method. However, it is important to know that this accessor only works for simple responses consisting of a single text part. If the response is blocked by safety filters, contains multiple candidates, or includes non-textual data types, accessing response.text will generate an error. The most robust and secure method for production is to access the candidate and its parts directly:
try: # Método robusto para acceder al texto text_response = response.candidates.content.parts.text print(text_response)except (IndexError, AttributeError): # Manejar el caso en que no hay respuesta de texto válida print("No se pudo obtener una respuesta de texto válida.") # Se puede inspeccionar response.prompt_feedback para ver si fue bloqueado print(f"Razón del bloqueo del prompt: {response.prompt_feedback.block_reason}")2.2. Streaming Responses for Real-Time Feedback
Sección titulada «2.2. Respuestas en Streaming para Retroalimentación en Tiempo Real»For interactive applications such as chatbots, streaming the model response drastically improves the user experience. Instead of waiting for the entire response to be generated, text chunks are displayed as they arrive, providing immediate feedback.
This functionality is achieved with the generate_content_stream() method. This method returns an iterator that yields response chunks as they are generated by the model.
import google.genai as genai
# Asumiendo que 'client' ha sido inicializadoresponse_stream = client.models.generate_content_stream( model="gemini-2.0-flash", contents="Escribe un poema largo sobre el océano y sus misterios.")
print("Respuesta del modelo:")for chunk in response_stream: print(chunk.text, end="")print() # Para una nueva línea al final2.3. Mastering Conversational AI: The Chat Interface
Sección titulada «2.3. Dominando la IA Conversacional: La Interfaz de Chat»The SDK provides two main mechanisms for managing multi-turn conversations. One approach is to manually manage the conversation history by building a list of Content objects representing each turn and passing it to generate_content() in each call. While flexible, this method can be cumbersome.
The recommended and most convenient approach for creating chatbots is to use the stateful chat interface provided by client.chats. This high-level object abstracts history management, significantly simplifying application code. This is a deliberate design decision in the SDK: providing a high-level, stateful abstraction (client.chats) for a common use case (chat), which greatly simplifies development compared to the low-level, stateless generate_content method.
The workflow for using the chat interface is as follows:
- Initialize a chat session:
client.chats.create()is used to start a new conversation. You can specify the model and, optionally, provide an initial history to contextualize the conversation. - Sending messages: The
chat.send_message()method is used to send the following user message. The SDK automatically manages the state, adding the user message and the subsequent model response to the conversation history. - Accessing history: At any time, the full conversation history can be retrieved using
chat.get_history().
A complete example of a multi-turn conversation is shown below:
import google.genai as genai
# Asumiendo que 'client' ha sido inicializado# 1. Crear una nueva sesión de chatchat_session = client.chats.create( model="gemini-2.0-flash")
# 2. Enviar el primer mensajeprint("Usuario: Hola, ¿puedes ayudarme a planificar un viaje a la luna?")response = chat_session.send_message("Hola, ¿puedes ayudarme a planificar un viaje a la luna?")print(f"Modelo: {response.text}\n")
# 3. Enviar un segundo mensaje de seguimientoprint("Usuario: ¿Qué tres cosas debería empacar?")response = chat_session.send_message("¿Qué tres cosas debería empacar?")print(f"Modelo: {response.text}\n")
# 4. Mostrar el historial completo de la conversaciónprint("--- Historial de la Conversación ---")for message in chat_session.get_history(): # El rol y el texto están en message.role y message.parts.text role = "Usuario" if message.role == "user" else "Modelo" print(f"{role}: {message.parts.text}")2.4. Advanced Generation Control
Sección titulada «2.4. Control Avanzado de la Generación»To fine-tune the model's behavior, the generate_content method accepts a config parameter, which takes a types.GenerateContentConfig object. This object allows developers to control various aspects of the generation process.
One of the most useful configurations is system_instruction. A system instruction provides high-level guidance or establishes a personality for the model that persists throughout the entire conversation. For example, the model can be instructed to act as a specific character or to follow certain rules in its responses.
from google.genai import types
# Asumiendo que 'client' ha sido inicializadoresponse = client.models.generate_content( model='gemini-2.0-flash', contents='¡Ah del barco! Cuéntame un chiste sobre un loro.', config=types.GenerateContentConfig( system_instruction='Hablas como un pirata malhumorado y conciso.' ))print(response.text)In addition to system instructions, there are several other parameters that can be adjusted to control the creativity and structure of the model's output. The following table details the most important ones.
Table 2: Key Generation Configuration Parameters
| Parameter | Description | Range | Effect on Output |
|---|---|---|---|
temperature | Controls the randomness of token selection. | 0.0 - 1.0 | Lower values (e.g., 0.2) make the output more deterministic and less creative. Higher values (e.g., 0.9) increase randomness and creativity. |
top_p | Nucleus sampling. Considers the smallest set of tokens whose cumulative probability is greater than top_p. | 0.0 - 1.0 | A value like 0.95 means that only the tokens comprising the top 95% of the probability mass are considered. This helps avoid highly improbable tokens. |
top_k | Considers only the k most probable tokens at each step of the generation. | Integer | A top_k of 1 is greedy decoding. A value like 40 restricts the selection to the 40 most probable tokens. |
candidate_count | The number of candidate responses to generate. | Integer (e.g., 1-8) | Generates multiple possible responses for the same prompt. Useful for providing options to the user. |
max_output_tokens | The maximum number of tokens that can be generated in the response. | Integer | Limits the output length. Essential for controlling costs and latency. |
stop_sequences | A list of strings that, when generated, will stop the output. | List of strings | Useful for stopping generation at a specific point, such as an end-of-sentence marker or a particular format. |
seed | Random seed for generation. | Integer | Providing a seed makes the output deterministic and reproducible (as long as temperature is not 0). |
Part 3: Advanced Interactions: Multimodality and Function Calling
Sección titulada «Parte 3: Interacciones Avanzadas: Multimodalidad y Llamada a Funciones»This part shows the true power of Gemini models by explaining how to work with non-textual inputs and connect the model to external tools.
3.1. Beyond Text: Understanding Multimodal Inputs
Sección titulada «3.1. Más Allá del Texto: Comprendiendo las Entradas Multimodales»One of the defining characteristics of the Gemini model family is its inherent multimodal capability. This means it can process and reason about different types of data, or “modalities,” such as text, images, audio, and video, within a single prompt request.
This capability is enabled by constructing the contents argument as a list containing multiple Part objects, where each Part can contain a different type of data. For example, a single request can include an image and a text question about that image.
3.2. Working with Images
Sección titulada «3.2. Trabajando con Imágenes»The SDK provides two strategically distinct methods for handling image data. The choice between them depends on the specific requirements of the use case, such as file size and reuse.
This duality of methods is not a redundancy, but a deliberate design that addresses different operational needs. The inline method is simple and excellent for one-off analyses and development convenience. The File API, while involving an additional upload step, is essential for production scenarios where efficiency, scalability, and large file handling are paramount.
Method 1: Inline Image Data
Sección titulada «Método 1: Datos de Imagen en Línea (Inline)»This method is ideal for smaller image files (the total request, including prompts and bytes, must be less than 20 MB) and for simplicity in development. The image data is passed directly in the generate_content call.
-
From a local file: The image file is read in binary mode (
'rb') and passed totypes.Part.from_bytes(), specifying the correct MIME type.import google.genai as genaifrom google.genai import types# Asumiendo que 'client' ha sido inicializadowith open('imagen_scones.jpg', 'rb') as f:image_bytes = f.read()image_part = types.Part.from_bytes(data=image_bytes,mime_type='image/jpeg')prompt_part = "Describe lo que ves en esta imagen."# Combinar imagen y texto en una sola solicitudresponse = client.models.generate_content(model='gemini-2.5-flash', # O un modelo de visión como gemini-pro-visioncontents=[prompt_part, image_part])print(response.text) -
From a URL: You can use a library like
requeststo get the image bytes from a URL and then pass them in the same way.
Method 2: The Files API
Sección titulada «Método 2: La API de Archivos (Files API)»This method is recommended for large image files (larger than 20 MB) or for scenarios where the same file will be reused in multiple prompt requests. Using the Files API avoids the need to reload the same bytes with each call.
The workflow consists of two steps:
- Upload:
client.files.upload()is used to upload the file to Google's servers. This method returns a file object that acts as a reference. - Prompt: The returned file object is passed directly into the
contentslist of agenerate_contentcall. The SDK handles resolving the reference to the uploaded file.
import google.genai as genai
# Asumiendo que 'client' ha sido inicializado
# 1. Cargar el archivo usando la API de Archivosprint("Cargando archivo...")sample_file = client.files.upload( file_path="imagen_grande.png", display_name="Mi Imagen de Muestra")print(f"Archivo cargado: {sample_file.uri}")
# 2. Usar el archivo cargado en una indicaciónprompt = "Analiza esta imagen y describe los objetos principales y su disposición espacial."response = client.models.generate_content( model='gemini-2.5-flash', contents=[prompt, sample_file] # Pasar el objeto de archivo directamente)
print(response.text)
# Opcional: Eliminar el archivo después de su usoclient.files.delete(name=sample_file.name)print(f"Archivo eliminado: {sample_file.name}")Files uploaded via the Files API are stored temporarily for 48 hours before being automatically deleted. The API also provides methods to manage these files, such as get(), list(), and delete().
3.3. Audio and Video Interaction
Sección titulada «3.3. Interacción con Audio y Vídeo»Image handling concepts extend directly to other modalities such as audio and video. Because these files tend to be large, the Files API is the primary method for working with them.
The process is identical to that of large images:
- Use
client.files.upload()to upload the audio file (e.g., MP3, WAV) or video file (e.g., MP4). - Include the returned file object in the prompt to
generate_content.
The following example shows how to upload an audio file and ask the model to transcribe it.
import google.genai as genaiimport time
# Asumiendo que 'client' ha sido inicializado
# 1. Cargar un archivo de audioprint("Cargando archivo de audio...")audio_file = client.files.upload( file_path="discurso_muestra.mp3", display_name="Discurso de Muestra")
# El procesamiento del archivo puede llevar tiempo, se espera a que esté ACTIVOwhile audio_file.state.name == "PROCESSING": print("Procesando archivo... esperando.") time.sleep(10) audio_file = client.files.get(name=audio_file.name)
if audio_file.state.name == "FAILED": raise ValueError(audio_file.state.name)
# 2. Usar el archivo de audio en una indicaciónprompt = "Transcribe el discurso en este archivo de audio."response = client.models.generate_content( model='gemini-2.5-flash', contents=[prompt, audio_file])print("\n--- Transcripción ---")print(response.text)3.4. Function Calling: Expanding Model Capabilities
Sección titulada «3.4. Llamada a Funciones: Ampliando las Capacidades del Modelo»Function calling, also known as tool use, is a powerful technique that allows the language model to interact with external systems. It allows the model to answer questions or perform actions that go beyond its inherent knowledge, such as fetching real-time data from an API, querying a database, or controlling a device.
The general workflow is as follows:
- Define Tools: A set of tools (Python functions) that the model can call is defined. This definition includes the function name, a description of what it does, and the schema of its parameters.
- Pass Tools to the Model: The list of defined tools is passed to the model in the
generate_contentcall. - The Model Decides to Call: The model analyzes the user's prompt and, if it determines that one of the provided tools can help answer, instead of generating text, its response will contain a
Partobject of typefunction_call. This object specifies the name of the function to call and the arguments with which to call it. - Execute the Function: The application code detects this
function_call, executes the corresponding Python function with the provided arguments, and obtains a result. - Return the Result to the Model: A second call is made to
generate_content, providing the conversation history plus the result of the function execution (wrapped in atypes.Part.from_function_response()). - Final Response: The model uses the function result to generate a final natural language response for the user.
Although the research snippets do not provide an end-to-end function calling code example, the structure of the Part objects for function_call and function_response is the basis for implementing this advanced pattern.
Part 4: Production Readiness: Error Handling, Security, and Management
Sección titulada «Parte 4: Preparación para Producción: Manejo de Errores, Seguridad y Gestión»This final part provides the critical information needed to build robust, reliable, and responsible applications.
4.1. Robust Error Handling
Sección titulada «4.1. Manejo Robusto de Errores»In a production environment, robust error handling is non-negotiable. API calls can fail for various reasons, such as invalid credentials, network issues, quota exhaustion, or malformed inputs.
The SDK uses Python's standard exception system. Most API-related errors can be caught using a try...except block that looks for exceptions from the google.api_core.exceptions module or, if available, a more specific class like errors.APIError.
from google.api_core import exceptions as core_exceptionsimport google.genai as genai
# Asumiendo que 'client' ha sido inicializadotry: response = client.models.generate_content( model="nombre-de-modelo-invalido", contents="¿Cuál es tu nombre?" ) print(response.text)except core_exceptions.GoogleAPICallError as e: # 'e' es una superclase para muchos errores de API print(f"Ha ocurrido un error en la API: {e}") # En muchos casos, 'e' tendrá atributos como 'code' y 'message' # aunque esto puede variar. Se recomienda inspeccionar el objeto de excepción.
except core_exceptions.NotFound as e: # Un error más específico si se sabe qué buscar print(f"Error: Recurso no encontrado. ¿Es correcto el nombre del modelo? - {e.message}")
except core_exceptions.ResourceExhausted as e: # Específico para errores de cuota print(f"Error: Se ha excedido la cuota de la API. - {e.message}")When catching an exception, the exception object often contains valuable information for logging and debugging, such as a status code and a descriptive message.
It is important to consider that error messages, while useful for developers, can be a double-edged sword. They can leak internal implementation details that could be exploited in adversarial attacks. For example, analyzing security validation error messages could reveal internal thresholds or defense mechanisms, helping a malicious actor bypass protections. Therefore, while errors should be logged extensively in the backend, the information presented to end users must be carefully controlled. It is often safer to show a generic message such as "An error occurred while processing your request" instead of exposing the raw API error message.
The following table summarizes the most common API error codes and how to resolve them.
Table 3: Common API Error Codes and Resolutions
| HTTP Code | Status | Probable Cause | Recommended Action in Python |
|---|---|---|---|
| 400 | INVALID_ARGUMENT | The request body is malformed (e.g., a parameter with an incorrect type, a missing required field). | Verify that the parameters in GenerateContentConfig and the format of contents are correct. Ensure that the model is compatible with the requested features. |
| 403 | PERMISSION_DENIED | The API key is incorrect, does not have the necessary permissions, or you are attempting to access a restricted resource (e.g., a fine-tuned model). | Verify that the API key (or ADC authentication for Vertex) is correctly configured and has the necessary permissions. |
| 429 | RESOURCE_EXHAUSTED | The API rate limit has been exceeded (requests per minute). | Implement exponential backoff in your retry logic. Consider requesting a quota increase if necessary for your application. |
| 500 | INTERNAL | An unexpected error occurred on Google's side. This can sometimes be caused by a very long input context. | Reduce the prompt length. Try the request again after a short wait. If the problem persists, consider switching to a different model temporarily. |
| 503 | UNAVAILABLE | The service is temporarily overloaded or unavailable. | Try the request again after a short wait using an exponential backoff strategy. If the problem persists, report the issue. |
4.2. Content Safety Management
Sección titulada «4.2. Gestión de la Seguridad del Contenido»The Gemini API includes built-in safety features to filter potentially harmful content. These features are designed to help developers build safer and more responsible applications.
The API classifies content into four main harm categories:
- Harassment (
HARM_CATEGORY_HARASSMENT) - Hate speech (
HARM_CATEGORY_HATE_SPEECH) - Sexually explicit content (
HARM_CATEGORY_SEXUALLY_EXPLICIT) - Dangerous content (
HARM_CATEGORY_DANGEROUS_CONTENT)
For each category, the model assigns a probability that the content is unsafe. By default, the API blocks prompts and responses that have a probability of MEDIUM or HIGH of being unsafe in any of these categories.
Developers can override this default setting per request by passing a list of SafetySetting objects to the safety_settings parameter. This allows granular control over the blocking threshold for each category.
from google.genai import types
# Asumiendo que 'client' ha sido inicializado
# Ejemplo: Relajar el umbral para el acoso, pero mantener el predeterminado para otros.# ¡Use esta configuración con precaución y solo si es necesario para su caso de uso!safety_config =
try: response = client.models.generate_content( model='gemini-2.0-flash', contents="Escribe un diálogo entre dos personajes que están discutiendo acaloradamente.", safety_settings=safety_config ) print(response.text)except ValueError: # A menudo, una respuesta bloqueada puede generar un ValueError al intentar acceder a.text print("La respuesta fue bloqueada o está vacía.") # Inspeccionar la retroalimentación de seguridad para depurar print(f"Razón del bloqueo del prompt: {response.prompt_feedback.block_reason}") if response.candidates: print(f"Calificaciones de seguridad del candidato: {response.candidates.safety_ratings}")When a response appears empty or an error occurs, it is crucial to inspect the safety feedback. The response object contains prompt_feedback (for the input prompt) and candidates.safety_ratings (for the generated response). These attributes will reveal if the content was blocked and why, which is essential for debugging.
The following table clarifies the meaning of the different blocking thresholds.
Table 4: Safety Configuration Thresholds
| API Constant | Setting in Google AI Studio | Description |
|---|---|---|
HARM_BLOCK_THRESHOLD_UNSPECIFIED | N/A | The threshold is not specified; the model's default threshold is used. |
BLOCK_NONE | Block none | Never block content, regardless of the probability that it is unsafe. Should be used with extreme caution. |
BLOCK_ONLY_HIGH | Block few | Block only when the probability of unsafe content is HIGH. |
BLOCK_MEDIUM_AND_ABOVE | Block some | (Default for most models) Block when the probability of unsafe content is MEDIUM or HIGH. |
BLOCK_LOW_AND_ABOVE | Block most | Block when the probability of unsafe content is LOW, MEDIUM, or HIGH. |
4.3. Model Management
Sección titulada «4.3. Gestión de Modelos»The SDK provides a programmatic way to discover available models and their capabilities. This is useful for building applications that can adapt to different models or for verifying a model's capabilities before using it.
The client.models.list() method returns an iterator over the available models.
Python
import google.genai as genai
# Asumiendo que 'client' ha sido inicializadoprint("Modelos disponibles:")for model in client.models.list(): # El objeto 'model' contiene metadatos detallados print(f" - Nombre: {model.name}") print(f" - Nombre para mostrar: {model.display_name}") print(f" - Métodos soportados: {model.supported_generation_methods}") # Verificar si el modelo soporta chat (create_chat) if 'create_chat' in model.supported_generation_methods: print(" - ¡Este modelo soporta chat!") print("-" * 20)This functionality can also be used to specifically list models that have been fine-tuned by the user, by setting query_base=False in the list request configuration. This allows applications to dynamically discover and use custom models.
Part 5: Environment Validation and Technical Checklist
Sección titulada «Parte 5: Validación del Entorno y Checklist Técnica»To finalize the provisioning of integrations based on the unified google-genai SDK in the Portelcore tenant, validate compliance with the following technical milestones:
- I have migrated all tenant scripts from the legacy
google-generativeailibrary to the newgoogle-genaistandard. ✓ - API keys are managed exclusively through the
GOOGLE_API_KEYenvironment variable or obfuscated in the Google Cloud Secret Manager instead of being written in plaintext. ✓ - A robust exception handler (
google.api_core.exceptions) is implemented to capture 429 (Resource Exhausted) status codes using exponential backoff policies. ✓ - Temperature and security thresholds (
safety_settings) are formally parameterized according to theportelcore.comdomain use case. ✓

