### TuningExample Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos.md A single example for tuning. ```APIDOC ## class TuningExample A single example for tuning. ``` -------------------------------- ### Install and Run Tests with pytest Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/CONTRIBUTING.md Installs the pytest library and then runs all tests in the 'tests' directory using pytest. ```bash pip install pytest ``` ```bash pytest tests ``` ```bash pytest ``` -------------------------------- ### Install google-generativeai SDK Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/README.md Use pip to install the google-generativeai Python SDK. This command installs version 0.x.x. ```bash pip install google-generativeai ``` -------------------------------- ### Basic generate_content Example Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Demonstrates a basic usage of the generate_content method to get a text response from the model. ```python model = genai.GenerativeModel('models/gemini-1.5-flash') response = model.generate_content('Tell me a story about a magic backpack') response.text ``` -------------------------------- ### Basic GenerativeModel Setup Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md Instantiate a GenerativeModel with a specified model name. This is the most basic configuration. ```python model = genai.GenerativeModel('models/gemini-1.5-flash') ``` -------------------------------- ### Install Google Generative AI SDK Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/ais-templates/aistudio_gemini_prompt_freeform.ipynb Installs the necessary Google Generative AI SDK. Ensure you are using a version greater than or equal to 0.8.2. ```python # @title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` ```python !pip install -U -q "google-generativeai>=0.8.2" ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/CONTRIBUTING.md Installs the library in editable mode with development requirements, allowing for direct source code edits without reinstallation. ```bash pip install -e .[dev] ``` -------------------------------- ### Streaming generate_content Example Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Illustrates how to use the stream=True option with generate_content to receive response chunks as they become available. ```python response = model.generate_content('Tell me a story about a magic backpack', stream=True) for chunk in response: print(chunk.text) ``` -------------------------------- ### Install Generative AI SDK Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/ais-templates/aistudio_gemini_prompt_freeform_nofiles.ipynb Installs the necessary Google Generative AI Python SDK. Ensure you have version 0.8.2 or higher. ```python !pip install -U -q "google-generativeai>=0.8.2" ``` -------------------------------- ### Verify Configuration and Initialize Model Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md After configuring the SDK, you can initialize a GenerativeModel to start making requests. This snippet verifies that the configuration was successful. ```python import google.generativeai as genai # Verify configuration model = genai.GenerativeModel('models/gemini-1.5-flash') ``` -------------------------------- ### Setup and Configuration Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/ais-templates/aistudio_gemini_prompt_freeform_nofiles.ipynb Imports required libraries, sets up the API key (from Colab secrets), and defines model parameters. It handles potential Colab environment differences. ```python # import necessary modules. import google.generativeai as genai import base64 import json try: # Mount google drive from google.colab import drive drive.mount("/gdrive") # The SDK will automatically read it from the GOOGLE_API_KEY environment variable. # In Colab get the key from Colab-secrets ("🔑" in the left panel). import os from google.colab import userdata os.environ["GOOGLE_API_KEY"] = userdata.get("GOOGLE_API_KEY") except ImportError: pass # Parse the arguments model = "gemini-1.5-flash" # @param {isTemplate: true} contents_b64 = b'W3sicGFydHMiOiBbeyJ0ZXh0IjogIkhlbGxvIn1dfV0=' generation_config_b64 = "e30=" # @param {isTemplate: true} safety_settings_b64 = "e30=" # @param {isTemplate: true} contents = json.loads(base64.b64decode(contents_b64)) generation_config = json.loads(base64.b64decode(generation_config_b64)) safety_settings = json.loads(base64.b64decode(safety_settings_b64)) stream = False print(json.dumps(contents, indent=4)) ``` -------------------------------- ### Initialize and Use ChatSession Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/ChatSession.md Demonstrates how to start a chat session, send messages, and retrieve responses. This is the primary way to interact with the model for conversational purposes. ```python >>> model = genai.GenerativeModel('models/gemini-1.5-flash') >>> chat = model.start_chat() >>> response = chat.send_message("Hello") >>> print(response.text) >>> response = chat.send_message("Hello again") >>> print(response.text) >>> response = chat.send_message(...) ``` -------------------------------- ### TuningExamples Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos.md A set of tuning examples. Can be training or validation data. ```APIDOC ## class TuningExamples A set of tuning examples. Can be training or validation data. ``` -------------------------------- ### GenerativeModel.start_chat Example Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Initiates a chat session with the model. You can optionally provide initial chat history to continue a previous conversation. The chat session supports automatic function calling. ```python model = genai.GenerativeModel() chat = model.start_chat(history=[...]) response = chat.send_message("Hello?") ``` -------------------------------- ### Dataset Attributes Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos/Dataset.md The Dataset object has an optional attribute 'examples' which can store inline tuning examples. ```APIDOC ## Dataset Dataset for training or validation. ### Attributes - **examples** (google.ai.generativelanguage.TuningExamples) - Optional. Inline examples. This field is a member of `oneof`_ ``dataset``. ``` -------------------------------- ### google.generativeai.protos.Example Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos/Example.md Represents an input/output example for instructing a generative model. It consists of a user's input message and the expected model output message. ```APIDOC ## google.generativeai.protos.Example ### Description An input/output example used to instruct the Model. It demonstrates how the model should respond or format its response. ### Attributes - **input** (google.ai.generativelanguage.Message) - Required. An example of an input `Message` from the user. - **output** (google.ai.generativelanguage.Message) - Required. An example of what the model should output given the input. ``` -------------------------------- ### Format Code with black Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/CONTRIBUTING.md Installs the black code formatter and applies it to the entire project directory. ```bash pip install black ``` ```bash black . ``` -------------------------------- ### List, Get, and Delete Files Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md Manage files within the SDK by listing all uploaded files, retrieving details of a specific file by its ID, and deleting files. Ensure the 'genai' library is imported. ```python # List files for file in genai.list_files(): print(f"{file.display_name} ({file.mime_type}) - Expires: {file.expiration_time}") # Get specific file file = genai.get_file('files/abc123') print(f"Size: {file.size_bytes} bytes") # Delete file genai.delete_file('files/abc123') ``` -------------------------------- ### Multi-turn Chat with generate_content Example Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Shows how to manage multi-turn conversations manually by sending the entire conversation history with each generate_content request. ```python messages = [{'role':'user', 'parts': ['hello']}] response = model.generate_content(messages) # "Hello, how can I help" messages.append(response.candidates[0].content) messages.append({'role':'user', 'parts': ['How does quantum physics work?']}) response = model.generate_content(messages) ``` -------------------------------- ### Start a Chat Session and Send Messages Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/INDEX.md Initiate a chat session to maintain conversation history and send follow-up messages. The SDK automatically handles context. ```python chat = model.start_chat() response = chat.send_message('First message') response = chat.send_message('Follow-up') # Maintains history ``` -------------------------------- ### Debug Tests with nose2 Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/CONTRIBUTING.md Installs the nose2 library and runs tests with the debugger enabled. ```bash pip install nose2 ``` ```bash nose2 --debugger ``` -------------------------------- ### start_chat() Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Start a multi-turn conversation session with the model. Initializes a chat session with optional history and function calling configuration. ```APIDOC ## start_chat() ### Description Start a multi-turn conversation session with the model. Initializes a chat session with optional history and function calling configuration. ### Method `def start_chat( self, *, history: Iterable[content_types.StrictContentType] | None = None, enable_automatic_function_calling: bool = False, ) -> ChatSession` ### Parameters #### Query Parameters - **history** (Iterable[StrictContentType]) - Optional - Previous conversation messages to initialize with. - **enable_automatic_function_calling** (bool) - Optional - If True, automatically call functions when model returns tool calls. Defaults to False. ### Returns `ChatSession` — Stateful conversation object. ### Raises - `ValueError` — If generation_config has `candidate_count > 1`. ### Example ```python model = genai.GenerativeModel('models/gemini-1.5-flash') chat = model.start_chat() response = chat.send_message('What is AI?') print(response.text) response = chat.send_message('Explain machine learning.') print(response.text) ``` ``` -------------------------------- ### ChatSession send_message Examples Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Demonstrates sending a single message, receiving a streaming response, and checking the chat history length. ```python chat = model.start_chat() response = chat.send_message('Hello!') print(response.text) # Streaming response = chat.send_message('Tell me a story', stream=True) for chunk in response: print(chunk.text, end='') # Chat history is automatically maintained print(f"Messages in history: {len(chat.history)}") ``` -------------------------------- ### GenerativeModel with System Instruction Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md Set a system-level instruction for the GenerativeModel to prepend to all requests. This guides the model's behavior and persona. ```python model = genai.GenerativeModel( 'models/gemini-1.5-flash', system_instruction='You are a helpful assistant. Be concise and accurate.' ) ``` -------------------------------- ### Instantiate and Use GenerationConfig Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Example of creating a GenerationConfig object and passing it to a GenerativeModel. This configures the model's generation behavior, including output format and sampling parameters. ```python import google.generativeai as genai config = genai.GenerationConfig( max_output_tokens=500, temperature=0.7, top_p=0.95, stop_sequences=['\n\n'], response_mime_type='application/json' ) model = genai.GenerativeModel( 'models/gemini-1.5-flash', generation_config=config ) response = model.generate_content('Generate JSON data') ``` -------------------------------- ### Start a Multi-turn Conversation Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Initiate a chat session using `start_chat()` to engage in multi-turn conversations. Send messages using `chat.send_message()` and receive responses. ```python >>> chat = model.start_chat() >>> response = chat.send_message("Hi, I have some questions for you.") >>> response.text "Sure, I'll do my best to answer your questions..." ``` -------------------------------- ### Fetch a Base Model Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Retrieve metadata for a base model by its name. Ensure the name starts with 'models/'. ```python def get_base_model( name: model_types.BaseModelNameOptions, *, client=None, request_options: helper_types.RequestOptionsType | None = None, ) -> model_types.Model ``` -------------------------------- ### TuningExample Attributes Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos/TuningExample.md This snippet details the attributes of the TuningExample protocol buffer message, which is used for providing examples during model tuning. ```APIDOC ## TuningExample ### Description A single example for tuning. ### Attributes - **text_input** (str) - Optional. Text model input. This field is a member of `oneof`_ ``model_input``. - **output** (str) - Required. The expected model output. ``` -------------------------------- ### Perform Type Checking with pytype Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/CONTRIBUTING.md Installs pytype and performs static type checking on the codebase. Requires creating and removing a temporary __init__.py file due to a known issue. ```bash pip install pytype ``` ```bash touch google/__init__.py # https://github.com/google/pytype/issues/464 ``` ```bash pytype ``` ```bash rm google/__init__.py ``` -------------------------------- ### start_chat Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Initializes and returns a ChatSession object attached to this model, allowing for conversational interactions. The chat can be started with an optional initial history. ```APIDOC ## start_chat ### Description Returns a `genai.ChatSession` attached to this model. The chat can be initialized with an optional history. ### Method Signature start_chat( *, history: (Iterable[content_types.StrictContentType] | None) = None, enable_automatic_function_calling: bool = False ) -> ChatSession ### Parameters * `history`: An iterable of `protos.Content` objects, or equivalents to initialize the session. * `enable_automatic_function_calling`: If True, enables automatic function calling. ### Example ```python >>> model = genai.GenerativeModel() >>> chat = model.start_chat(history=[...]) >>> response = chat.send_message("Hello?") ``` ``` -------------------------------- ### Get a specific model Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/get_model.md This example demonstrates how to call the `get_model` function to retrieve details about a specific generative AI model. ```APIDOC ## google.generativeai.get_model ### Description Calls the API to fetch a model by name. ### Method Signature google.generativeai.get_model(name: model_types.AnyModelNameOptions, *, client=None, request_options: (helper_types.RequestOptionsType | None) = None) -> (model_types.Model | model_types.TunedModel) ### Parameters #### Args - **name** (model_types.AnyModelNameOptions) - Required - The name of the model to fetch. Should start with `models/` - **client** (any) - Optional - The client to use. - **request_options** (helper_types.RequestOptionsType | None) - Optional - Options for the request. ### Returns - **Model** (model_types.Model | model_types.TunedModel) - A `types.Model` object representing the fetched model. ### Example ```python import pprint import google.generativeai as genai model = genai.get_model('models/gemini-1.5-flash') pprint.pprint(model) ``` ``` -------------------------------- ### Get a tuned model by name Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/get_tuned_model.md Use this function to retrieve a specific tuned model. Ensure the model name starts with 'tunedModels/'. ```python import pprint import google.generativeai as genai model = genai.get_tuned_model('tunedModels/gemini-1.0-pro-001') pprint.pprint(model) ``` -------------------------------- ### Get a base model by name Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/get_base_model.md Use this function to retrieve a specific base model by its name. Ensure you have the `google-generativeai` library installed and imported. ```python import pprint import google.generativeai as genai model = genai.get_base_model('models/chat-bison-001') pprint.pprint(model) ``` -------------------------------- ### GenerativeModel Usage Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai.md Demonstrates how to set up the SDK, configure API keys, instantiate a GenerativeModel, and generate content. ```APIDOC ## Setup ```posix-terminal pip install google-generativeai ``` ## GenerativeModel Use `genai.GenerativeModel` to access the API: ```python import google.generativeai as genai import os genai.configure(api_key=os.environ['API_KEY']) model = genai.GenerativeModel(model_name='gemini-1.5-flash') response = model.generate_content('Teach me about how an LLM works') print(response.text) ``` See the [python quickstart](https://ai.google.dev/tutorials/python_quickstart) for more details. ``` -------------------------------- ### Get a model by name Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/get_model.md Use this function to fetch a model. Ensure the model name starts with `models/`. Requires the `google.generativeai` library to be imported. ```python import pprint import google.generativeai as genai model = genai.get_model('models/gemini-1.5-flash') pprint.pprint(model) ``` -------------------------------- ### Start Chat Session Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Initiates a multi-turn conversation. Use `history` to provide previous messages and `enable_automatic_function_calling` to automatically invoke functions when the model returns tool calls. Raises `ValueError` if `candidate_count` is greater than 1 in `generation_config`. ```python model = genai.GenerativeModel('models/gemini-1.5-flash') chat = model.start_chat() response = chat.send_message('What is AI?') print(response.text) response = chat.send_message('Explain machine learning.') print(response.text) ``` -------------------------------- ### Client Initialization Flow Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/module-structure.md Illustrates the sequence of calls from user code to the underlying client for model instantiation. ```text User Code ↓ genai.configure() ↓ _ClientManager.configure() ↓ [Stores config] ↓ User requests genai.GenerativeModel() ↓ GenerativeModel._client = get_default_generative_client() ↓ _ClientManager.get_default_client('generative') ↓ gl.GenerativeServiceClient (from google-ai-generativelanguage) ``` -------------------------------- ### Configure Client with Service Account Credentials Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md Configure the client using credentials from a service account JSON file. This is useful for authenticating in environments where a user account is not available. ```python from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file( 'key.json' ) genai.configure(credentials=credentials) ``` -------------------------------- ### get Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/caching/CachedContent.md Fetches a specific CachedContent resource by its name. ```APIDOC ## get ### Description Fetches required `CachedContent` resource. ### Method GET (or equivalent SDK method) ### Endpoint (Not explicitly defined, SDK method signature provided) ### Parameters #### Path Parameters * **name** (string) - Required - The resource name referring to the cached content. #### Query Parameters None #### Request Body None ### Request Example ```python # Example using Python SDK # cached_content = CachedContent.get(name="cached_content_name") ``` ### Response #### Success Response * **CachedContent** - `CachedContent` resource with the specified `name`. ``` -------------------------------- ### Generate API Reference Documentation Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/CONTRIBUTING.md Builds the API reference documentation using the provided script. ```bash python docs/build_docs.py ``` -------------------------------- ### Configure with API Key (Direct Parameter) Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/README.md Configure the SDK by passing the API key directly as a parameter to genai.configure(). This is suitable for testing or when environment variables are not preferred. ```python import google.generativeai as genai # Method 2: Direct parameter genai.configure(api_key='your-api-key') ``` -------------------------------- ### Basic Usage of Generative AI SDK Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/README.md Configure the SDK with your API key, initialize a generative model, and generate text content. The response text is then printed. ```python import google.generativeai as genai genai.configure(api_key='YOUR_API_KEY') model = genai.GenerativeModel('models/gemini-1.5-flash') response = model.generate_content('What is AI?') print(response.text) ``` -------------------------------- ### BatchEmbedTextRequest Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos.md Batch request to get a text embedding from the model. ```APIDOC ## Class BatchEmbedTextRequest ### Description Batch request to get a text embedding from the model. ### Usage This class is part of the protobuf definitions for the Google Generative AI API. ``` -------------------------------- ### BatchEmbedContentsRequest Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos.md Batch request to get embeddings from the model for a list of prompts. ```APIDOC ## Class BatchEmbedContentsRequest ### Description Batch request to get embeddings from the model for a list of prompts. ### Usage This class is part of the protobuf definitions for the Google Generative AI API. ``` -------------------------------- ### get Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/RequestOptions.md Returns the value for a given key, or a default value if the key is not found. ```APIDOC ## get ### Description Returns the value for a given key, or a default value if the key is not found. ### Method `get(key, default=None)` ### Parameters - **key**: The key to look up. - **default**: The default value to return if the key is not found (defaults to None). ``` -------------------------------- ### get_base_model() Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Fetches a base model by its name. The name must start with 'models/'. ```APIDOC ## get_base_model() ### Description Fetch a base model by name. ### Method Signature ```python def get_base_model( name: model_types.BaseModelNameOptions, *, client=None, request_options: helper_types.RequestOptionsType | None = None, ) -> model_types.Model ``` ### Parameters #### Path Parameters - **name** (str) - Required - Base model name (must start with `models/`). #### Keyword Arguments - **client** (ModelServiceClient) - Optional - Default: None - Custom client. - **request_options** (dict) - Optional - Default: None - Additional request options. ### Returns `Model` - Base model metadata. ``` -------------------------------- ### Get a Specific Permission (Async) Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Permissions.md Asynchronous version for retrieving information about a specific permission. ```python get_async( name ) ``` -------------------------------- ### Upload and Generate Content from PDF File Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md This snippet demonstrates how to upload a PDF file using the SDK, use it in a content generation prompt for summarization, and then clean up by deleting the uploaded file. Ensure the 'genai' library is imported. ```python # Upload file file = genai.upload_file('large-document.pdf') print(f"Uploaded: {file.name}") # Use in generation response = model.generate_content([ 'Summarize this document:', file ]) print(response.text) # Cleanup genai.delete_file(file.name) ``` -------------------------------- ### Configure API Key and Generate Content Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/INDEX.md Configure the SDK with your API key and generate a text response from a model. Ensure you replace 'YOUR_KEY' with your actual API key. ```python import google.generativeai as genai genai.configure(api_key='YOUR_KEY') model = genai.GenerativeModel('models/gemini-1.5-flash') response = model.generate_content('Your question') print(response.text) ``` -------------------------------- ### Configure with API Key (Environment Variable) Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/README.md Configure the SDK using an API key stored in the GEMINI_API_KEY environment variable. Ensure the environment variable is set before calling genai.configure(). ```python import os import google.generativeai as genai # Method 1: Environment variable os.environ['GEMINI_API_KEY'] = 'your-api-key' genai.configure() ``` -------------------------------- ### Get Permission Information Asynchronously Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Permission.md Asynchronously retrieves information about a specific permission. This is the non-blocking version of `Permission.get`. ```python get_async( name, client=None ) ``` -------------------------------- ### Fetch a Tuned Model Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Retrieve metadata for a tuned model by its name. Ensure the name starts with 'tunedModels/'. ```python def get_tuned_model( name: model_types.TunedModelNameOptions, *, client=None, request_options: helper_types.RequestOptionsType | None = None, ) -> model_types.TunedModel ``` -------------------------------- ### configure Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai.md Captures default client configuration for the Generative AI SDK. ```APIDOC ## configure(...) ### Description Captures default client configuration. ### Parameters (No specific parameters documented in the source) ``` -------------------------------- ### Model Initialization Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Model.md Instantiate a Model object with its various properties. ```APIDOC ## google.generativeai.types.Model ### `__init__` ```python google.generativeai.types.Model( name: str, base_model_id: str, version: str, display_name: str, description: str, input_token_limit: int, output_token_limit: int, supported_generation_methods: list[str], temperature: (float | None) = None, max_temperature: (float | None) = None, top_p: (float | None) = None, top_k: (int | None) = None ) ``` **Parameters:** * `name` (str): The resource name of the `Model`. * `base_model_id` (str): The base name of the model. * `version` (str): The major version number of the model. * `display_name` (str): The human-readable name of the model. * `description` (str): A short description of the model. * `input_token_limit` (int): Maximum number of input tokens allowed for this model. * `output_token_limit` (int): Maximum number of output tokens available for this model. * `supported_generation_methods` (list[str]): Lists which methods are supported by the model. * `temperature` (float | None, optional): Controls randomness. Defaults to None. * `max_temperature` (float | None, optional): The maximum temperature allowed. Defaults to None. * `top_p` (float | None, optional): Controls diversity via nucleus sampling. Defaults to None. * `top_k` (int | None, optional): Controls diversity via top-k sampling. Defaults to None. ``` -------------------------------- ### Configure with Service Account Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/README.md Authenticate using a service account by providing the path to your key file. This method is recommended for server-side applications. ```python from google.oauth2 import service_account import google.generativeai as genai credentials = service_account.Credentials.from_service_account_file( 'key.json' ) genai.configure(credentials=credentials) ``` -------------------------------- ### Get a Specific Permission Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Permissions.md Retrieve information about a specific permission using its name. Returns the permission as a Permission object. ```python @classmethod get( name: str ) -> Permission ``` -------------------------------- ### Get Permission Information Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Permission.md Retrieves information about a specific permission by its name. Requires the permission's name as input. ```python @classmethod get( name: str, client: (glm.PermissionServiceClient | None) = None ) -> Permission ``` -------------------------------- ### Configure Client with Combined Options Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md Configure the client using a `ClientOptions` object that includes both a custom endpoint and an API key. This provides a consolidated way to set multiple client configurations. ```python options = client_options_lib.ClientOptions( api_endpoint='https://custom.endpoint.com', api_key='key-value', # Alternative to separate api_key param ) genai.configure(client_options=options) ``` -------------------------------- ### Initialize GenerativeModel and generate content Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai.md Configure the API key and initialize the GenerativeModel to generate content. Ensure your API key is set as an environment variable. ```python import google.generativeai as genai import os genai.configure(api_key=os.environ['API_KEY']) model = genai.GenerativeModel(model_name='gemini-1.5-flash') response = model.generate_content('Teach me about how an LLM works') print(response.text) ``` -------------------------------- ### Text Generation with Configuration Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md Customize generation parameters like temperature and max output tokens when instantiating the model for text generation. ```python config = genai.GenerationConfig( temperature=0.7, max_output_tokens=500, ) model = genai.GenerativeModel( 'models/gemini-1.5-flash', generation_config=config ) response = model.generate_content('Explain quantum computing') print(response.text) ``` -------------------------------- ### Send Message and Get Response Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/ChatSession.md Sends a message to the model and appends the request/response to the chat history. Use this for standard, non-streaming interactions. ```python model = genai.GenerativeModel('models/gemini-1.5-flash') chat = model.start_chat() response = chat.send_message("Hello") print(response.text) print(len(chat.history)) ``` -------------------------------- ### Configure API Key Authentication (Parameter) Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md Use this method to directly provide your API key when configuring the SDK. Ensure the key is valid. ```python import google.generativeai as genai # From parameter genai.configure(api_key='AIzaSyD...') ``` -------------------------------- ### Multi-Turn Conversation with Initial History Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md Start a multi-turn conversation with pre-existing history, allowing the model to consider past interactions from the beginning. ```python history = [ {'role': 'user', 'parts': ['Hi, I am Alice']}, {'role': 'model', 'parts': ['Hi Alice, nice to meet you!']}, ] chat = model.start_chat(history=history) response = chat.send_message('What did I just tell you?') ``` -------------------------------- ### Import Libraries and Configure API Key Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/ais-templates/aistudio_gemini_prompt_freeform.ipynb Imports essential libraries and sets up the Google API key. It attempts to retrieve the key from Colab secrets if available, otherwise it relies on the GOOGLE_API_KEY environment variable. ```python # import necessary modules. import base64 import copy import json import pathlib import requests import PIL.Image import IPython.display from IPython.display import Markdown try: # The SDK will automatically read it from the GOOGLE_API_KEY environment variable. # In Colab get the key from Colab-secrets ("🔑" in the left panel). import os from google.colab import userdata os.environ["GOOGLE_API_KEY"] = userdata.get("GOOGLE_API_KEY") except ImportError: pass import google.generativeai as genai # Parse the arguments model = "gemini-1.5-flash" # @param {isTemplate: true} contents_b64 = "W3sicGFydHMiOiBbeyJ0ZXh0IjogIldoYXQncyBpbiB0aGlzIHBpY3R1cmU/In0sIHsiZmlsZV9kYXRhIjogeyJ1cmwiOiAiaHR0cHM6Ly9zdG9yYWdlLmdvb2dsZWFwaXMuY29tL2dlbmVyYXRpdmVhaS1kb3dubG9hZHMvaW1hZ2VzL3Njb25lcy5qcGciLCAibWltZV90eXBlIjogImltYWdlL2pwZWcifX1dfV0=" # @param {isTemplate: true} generation_config_b64 = "e30=" # @param {isTemplate: true} safety_settings_b64 = "e30=" # @param {isTemplate: true} gais_contents = json.loads(base64.b64decode(contents_b64)) generation_config = json.loads(base64.b64decode(generation_config_b64)) safety_settings = json.loads(base64.b64decode(safety_settings_b64)) stream = False # Convert and upload the files tempfiles = pathlib.Path(f"tempfiles") tempfiles.mkdir(parents=True, exist_ok=True) drive = None def upload_file_data(file_data, index): """Upload files to the Files API. For each file, Google AI Studio either sent: - a Google Drive ID, - a URL, - a file path, or - The raw bytes (`inline_data`). The API only understands `inline_data` or it's Files API. This code, uploads files to the files API where the API can access them. """ mime_type = file_data["mime_type"] if drive_id := file_data.pop("drive_id", None): if drive is None: from google.colab import drive drive.mount("/gdrive") path = next( pathlib.Path(f"/gdrive/.shortcut-targets-by-id/{drive_id}").glob("*" ) ) print("Uploading:", str(path)) file_info = genai.upload_file(path=path, mime_type=mime_type) file_data["file_uri"] = file_info.uri return if url := file_data.pop("url", None): response = requests.get(url) data = response.content name = url.split("/")[-1] path = tempfiles / str(index) path.write_bytes(data) print("Uploading:", url) file_info = genai.upload_file(path, display_name=name, mime_type=mime_type) file_data["file_uri"] = file_info.uri return if name := file_data.get("filename", None): if not pathlib.Path(name).exists(): raise IOError( f"local file: `{name}` does not exist. You can upload files " 'to Colab using the file manager ("📁 Files" in the left ' "toolbar)" ) file_info = genai.upload_file(path, display_name=name, mime_type=mime_type) file_data["file_uri"] = file_info.uri return if "inline_data" in file_data: return raise ValueError("Either `drive_id`, `url` or `inline_data` must be provided.") contents = copy.deepcopy(gais_contents) index = 0 for content in contents: for n, part in enumerate(content["parts"]): if file_data := part.get("file_data", None): upload_file_data(file_data, index) index += 1 import json print(json.dumps(contents, indent=4)) ``` -------------------------------- ### Basic Text Generation with Simple Query Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md Configure the API key and instantiate a model to generate text for a simple query. ```python import google.generativeai as genai genai.configure(api_key='YOUR_API_KEY') model = genai.GenerativeModel('models/gemini-1.5-flash') response = model.generate_content('What is quantum computing?') print(response.text) ``` -------------------------------- ### GenerativeModel.start_chat Signature Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Defines the signature for starting a chat session. It allows initializing the session with history and enabling automatic function calling. ```python start_chat( *, history: (Iterable[content_types.StrictContentType] | None) = None, enable_automatic_function_calling: bool = False ) -> ChatSession ``` -------------------------------- ### MessagePrompt Attributes Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos/MessagePrompt.md The MessagePrompt object has the following attributes: context, examples, and messages. Each attribute has a specific type and purpose within the prompt structure. ```APIDOC ## MessagePrompt ### Description A `MessagePrompt` contains a structured set of fields that provide context for the conversation, examples of user input/model output message pairs that prime the model to respond in different ways, and the conversation history or list of messages representing the alternating turns of the conversation between the user and the model. ### Attributes * **context** (`str`): Optional. Text that should be provided to the model first to ground the response. If not empty, this `context` will be given to the model first before the `examples` and `messages`. When using a `context` be sure to provide it with every request to maintain continuity. This field can be a description of your prompt to the model to help provide context and guide the responses. Examples: "Translate the phrase from English to French." or "Given a statement, classify the sentiment as happy, sad or neutral.". Anything included in this field will take precedence over message history if the total input size exceeds the model's `input_token_limit` and the input request is truncated. * **examples** (`MutableSequence[google.ai.generativelanguage.Example]`): Optional. Examples of what the model should generate. This includes both user input and the response that the model should emulate. These `examples` are treated identically to conversation messages except that they take precedence over the history in `messages`: If the total input size exceeds the model's `input_token_limit` the input will be truncated. Items will be dropped from `messages` before `examples`. * **messages** (`MutableSequence[google.ai.generativelanguage.Message]`): Required. A snapshot of the recent conversation history sorted chronologically. Turns alternate between two authors. If the total input size exceeds the model's `input_token_limit` the input will be truncated: The oldest items will be dropped from `messages`. ``` -------------------------------- ### Initialize GenerativeModel Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Instantiate a GenerativeModel with a specified model name. Configure safety settings, generation parameters, tools, and system instructions as needed. ```python import google.generativeai as genai import PIL.Image genai.configure(api_key='YOUR_API_KEY') model = genai.GenerativeModel('models/gemini-1.5-flash') ``` -------------------------------- ### Upload File and Generate Content Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/INDEX.md Upload a local file (e.g., a PDF) for the model to analyze and then generate content based on it. Remember to delete the file after use. ```python file = genai.upload_file('document.pdf') response = model.generate_content(['Summarize:', file]) genai.delete_file(file.name) ``` -------------------------------- ### Get Function Declaration Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/FunctionLibrary.md Retrieves a FunctionDeclaration object based on its name or a FunctionCall object. This allows for looking up function definitions within the library. ```python __getitem__(name: (str | protos.FunctionCall)) -> (FunctionDeclaration | protos.FunctionDeclaration) ``` -------------------------------- ### Initiate Model Tuning and Generate Text Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/create_tuned_model.md Initiates a model tuning process with a specified ID, source model, and training data. It then waits for the tuning to complete and demonstrates how to use the tuned model for text generation. ```python my_id = "my-tuned-model-id" operation = palm.create_tuned_model( id = my_id, source_model="models/text-bison-001", training_data=[{'text_input': 'example input', 'output': 'example output'},...]) tuned_model=operation.result() # Wait for tuning to finish palm.generate_text(f"tunedModels/{my_id}", prompt="...") ``` -------------------------------- ### Handle Missing Credentials Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/errors.md Catch DefaultCredentialsError when no API key or ADC is found, guiding the user to set environment variables or configure manually. ```python import google.auth.exceptions try: genai.configure() model = genai.GenerativeModel('models/gemini-1.5-flash') except google.auth.exceptions.DefaultCredentialsError: print('No credentials found. Set GOOGLE_API_KEY or use service account.') ``` -------------------------------- ### Generate Content with Text Input Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/GenerativeModel.md Use the `generate_content` method to get a text-based response from the model. Ensure the model is initialized with a valid model name. ```python >>> result = model.generate_content('Tell me a story about a magic backpack') >>> result.text "In the quaint little town of Lakeside, there lived a young girl named Lily..." ``` -------------------------------- ### Generate Content with Gemini Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/ais-templates/aistudio_gemini_prompt_freeform_nofiles.ipynb Initializes the Gemini model and calls the `generate_content` method with the configured parameters. The response is then displayed as Markdown. ```python from IPython.display import display from IPython.display import Markdown # Call the model and print the response. gemini = genai.GenerativeModel(model_name=model) response = gemini.generate_content( contents, generation_config=generation_config, safety_settings=safety_settings, stream=stream, ) display(Markdown(response.text)) ``` -------------------------------- ### Tool Constructor Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Tool.md Initializes a Tool object with optional function declarations, Google Search retrieval configurations, or code execution settings. ```APIDOC ## google.generativeai.types.Tool ### Description A wrapper for protos.Tool, Contains a collection of related `FunctionDeclaration` objects, protos.CodeExecution object, and protos.GoogleSearchRetrieval object. ### Signature google.generativeai.types.Tool( *, function_declarations: (Iterable[FunctionDeclarationType] | None) = None, google_search_retrieval: (GoogleSearchRetrievalType | None) = None, code_execution: (protos.CodeExecution | None) = None ) ### Attributes - `code_execution` (protos.CodeExecution | None) - Configuration for code execution. - `function_declarations` (Iterable[FunctionDeclarationType] | None) - A collection of function declarations. - `google_search_retrieval` (GoogleSearchRetrievalType | None) - Configuration for Google Search retrieval. ``` -------------------------------- ### Multi-Turn Conversation with ChatSession Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md Manage multi-turn conversations using ChatSession, which maintains context across multiple messages. Start a chat and send messages sequentially. ```python model = genai.GenerativeModel('models/gemini-1.5-flash') chat = model.start_chat() # First turn response = chat.send_message('What is AI?') print(f"Bot: {response.text}\n") # Second turn (context maintained) response = chat.send_message('How does machine learning relate to it?') print(f"Bot: {response.text}\n") # Third turn response = chat.send_message('Give me an example of a machine learning application') print(f"Bot: {response.text}\n") # Access history print(f"Total messages in history: {len(chat.history)}") ``` -------------------------------- ### Instantiate Permissions Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Permissions.md Instantiate the Permissions class with a parent resource. ```python google.generativeai.types.Permissions( parent ) ``` -------------------------------- ### Handle ValueError for Invalid Model Name Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/errors.md Catch `ValueError` when an invalid model name format is used. Model names must start with 'models/' or 'tunedModels/'. ```python get_model('invalid-name') ``` -------------------------------- ### Instantiate RequestOptions with Retry and Timeout Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/RequestOptions.md Demonstrates how to create a RequestOptions object with custom retry and timeout configurations. This is useful for controlling request behavior under specific network conditions or for time-sensitive operations. ```python import google.generativeai as genai from google.generativeai.types import RequestOptions from google.api_core import retry model = genai.GenerativeModel() response = model.generate_content('Hello', request_options=RequestOptions( retry=retry.Retry(initial=10, multiplier=2, maximum=60, timeout=300))) response = model.generate_content('Hello', request_options=RequestOptions(timeout=600))) ``` -------------------------------- ### Initialize FunctionLibrary Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/FunctionLibrary.md Instantiate a FunctionLibrary with a collection of Tool objects. This is used to manage the lookup and execution of functions defined within these tools. ```python google.generativeai.types.FunctionLibrary( tools: Iterable[ToolType] ) ``` -------------------------------- ### Configure API Key Authentication (Environment Variable) Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md The SDK automatically uses the `GEMINI_API_KEY` or `GOOGLE_API_KEY` environment variables if no API key is passed to `configure()`. This is useful for managing keys outside of your code. ```python import google.generativeai as genai # From environment (GEMINI_API_KEY or GOOGLE_API_KEY) genai.configure() ``` -------------------------------- ### FunctionLibrary Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/FunctionLibrary.md Initializes a FunctionLibrary with a collection of Tool objects. ```APIDOC ## FunctionLibrary ### Description Initializes a FunctionLibrary with a collection of Tool objects. ### Parameters #### Path Parameters - **tools** (Iterable[ToolType]) - Description: A collection of Tool objects to be managed by the FunctionLibrary. ``` -------------------------------- ### Enable Automatic Function Calling Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md Start a chat session with automatic function calling enabled. The model will automatically invoke defined tools when appropriate based on the conversation. ```python def get_weather(location: str, unit: str = 'celsius') -> str: # Implementation here return f"Weather in {location}: 20°{unit[0].upper()}" chat = model.start_chat(enable_automatic_function_calling=True) response = chat.send_message('What is the weather in Paris?') # Model automatically calls get_weather and includes response ``` -------------------------------- ### Check Model Capabilities Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/usage-patterns.md Retrieves a specific model and displays its supported generation methods, token limits, and generation configuration parameters like temperature, top_p, and top_k. Use this to understand a model's specific features and constraints. ```python model = genai.get_model('models/gemini-1.5-flash') print(f"Model: {model.display_name}") print(f"Methods: {', '.join(model.supported_generation_methods)}") print(f"Input limit: {model.input_token_limit} tokens") print(f"Output limit: {model.output_token_limit} tokens") print(f"Temperature range: {model.temperature} (default)") print(f"Top P: {model.top_p}") print(f"Top K: {model.top_k}") ``` -------------------------------- ### Configure Generative AI Client Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Configure default client credentials and settings. Use this to set your API key or authentication credentials. It can also load credentials from environment variables. ```python import google.generativeai as genai genai.configure(api_key='your-api-key') # or from environment genai.configure() # with custom metadata genai.configure( api_key='key', default_metadata=[('custom-header', 'value')] ) ``` -------------------------------- ### to_proto Method Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Tool.md Converts the Tool object to its protocol buffer representation. ```APIDOC ## to_proto ### Description Converts the Tool object to its protocol buffer representation. ### Signature to_proto() ``` -------------------------------- ### Convert response to dict Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/AsyncGenerateContentResponse.md Use `to_dict()` to get a JSON-compatible dictionary representation of the response. Note that this method captures only the accumulated `GenerateContentResponse` fields and does not capture the iterator state when streaming. ```python import json response = model.generate_content('Hello?') json.dumps(response.to_dict()) ``` -------------------------------- ### Generate Content with GenerativeModel Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/api-reference.md Use `generate_content` to get a response from the model. Supports text, streaming, and multimodal inputs. Configure generation parameters, safety settings, and tools for specific requests. ```python import google.generativeai as genai genai.configure(api_key='your-api-key') model = genai.GenerativeModel('models/gemini-1.5-flash') # Text generation response = model.generate_content('Explain quantum computing') print(response.text) # Streaming response = model.generate_content('Tell a story', stream=True) for chunk in response: print(chunk.text, end='') # Multimodal import PIL.Image response = model.generate_content([ 'Describe this image:', PIL.Image.open('photo.jpg') ]) ``` -------------------------------- ### Tool Constructor Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/types/Tool.md Initializes a Tool object with optional function declarations, Google Search retrieval, or code execution configurations. ```python google.generativeai.types.Tool( *, function_declarations: (Iterable[FunctionDeclarationType] | None) = None, google_search_retrieval: (GoogleSearchRetrievalType | None) = None, code_execution: (protos.CodeExecution | None) = None ) ``` -------------------------------- ### Override Safety Settings for a Specific Request Source: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/_autodocs/configuration.md You can override the model's default safety settings for individual content generation requests. This example disables blocking for sexual content for one specific call. ```python model = genai.GenerativeModel('models/gemini-1.5-flash') response = model.generate_content( 'Generate adult content', safety_settings={ 'HARM_CATEGORY_SEXUAL': 'BLOCK_NONE', } ) ```