Skip to main content

Getting Started with Google Gemini API

If you're just getting started with Generative AI and want to use Google's Gemini models for free, you're in the right place. In this tutorial, I’ll walk you through everything you need to know to build your first Gemini-powered application using Python, including how to get a free API key, install necessary libraries, and write code that interacts with Gemini’s generate_content() function.

How to Get a Free Gemini API Key

You’ll need a Google account for this.

  1. Go to the official Google AI Studio.
  2. Sign in with your Google account.
  3. In the top-right corner, click on your profile and select "Get API Key".
  4. You’ll be redirected to Google Cloud's API Console.
  5. Create a new API key or use the existing one.
  6. Copy this key and keep it safe! You'll use it in your Python code.

**Important: Google provides free quota to use Gemini API. Make sure you check the quota limits for the free tier.

Setting Up Your Python Environment

Before writing any code, install the required libraries:

pip install google-generativeai python-dotenv

Also, create a .env file in your project folder and add your API key like this:

'.env' file should contain following information.

GOOGLE_API_KEY=your_api_key_here

This helps keep your secret key private and secure.

Full Example Code + Explanation

Here is the complete code with detailed comments to help you understand how to interact with the Gemini API using Python:

# Import necessary Python modules
import os                              # Helps interact with environment variables
from dotenv import load_dotenv         # Loads variables from .env file
from google import genai               # Google's Generative AI SDK
from google.genai import types         # Contains types for model configuration

# Load environment variables (API key)
load_dotenv(".env")                    # Loads the .env file from current directory
api_key = os.getenv("GOOGLE_API_KEY")  # Retrieves the API key from the environment

# Initialize the GenAI client
gClient = genai.Client(api_key=api_key)  # Authenticates you to use the Gemini models

# ---------------------------------------------
# EXAMPLE 1: Simple usage
# Ask the model a question
response = gClient.models.generate_content(
    model='gemini-2.0-flash',           # Free-tier optimized model
    contents="Explain what generate_content function do in genai.Client.models."
)
print(response.text)

# ---------------------------------------------
# EXAMPLE 2: With generation configuration
# Translate a sentence with custom behavior
response = gClient.models.generate_content(
    model="gemini-2.0-flash",
    contents='Translate good morning in Korean',
    
    # Optional configuration for generation behavior
    config=types.GenerateContentConfig(
        temperature=1,                 # Controls creativity: 0 = more predictable, 1 = more diverse
        top_p=0.99,                    # Limits the token selection to a cumulative probability
        top_k=0,                       # Limits token selection to top k tokens (0 = disabled)
        max_output_tokens=4096         # Max tokens in the output (adjust based on response length)
    ),
)
print(response.text)

Understanding Key Parameters

generate_content()

This function sends a prompt to the selected Gemini model and receives a generated response.

temperature

Controls randomness:

  • 0: Most deterministic
  • 1: Most creative/random

top_p

Uses nucleus sampling. The model selects tokens from the top cumulative probability mass. Values closer to 1 allow more variety.

top_k

Model picks from the top k most likely tokens. Set to 0 to disable.

max_output_tokens

Limits the response length (like word count, but for tokens). Typical values: 256, 1024, 4096.

More Sample Use Cases

1. Summarize a Paragraph

response = gClient.models.generate_content(
    model="gemini-2.0-flash",
    contents="Summarize this: Artificial Intelligence is transforming industries across the globe..."
)
print(response.text)

2. Translate Multiple Languages

response = gClient.models.generate_content(
    model="gemini-2.0-flash",
    contents="Translate 'thank you' into French, Spanish, and Japanese."
)
print(response.text)

3. Generate a Poem

response = gClient.models.generate_content(
    model="gemini-2.0-flash",
    contents="Write a haiku about spring."
)
print(response.text)

4. Coding Help

response = gClient.models.generate_content(
    model="gemini-2.0-flash",
    contents="Explain what a Python decorator is with an example."
)
print(response.text)

2025.04.22 - [AI] - How to use Gemini API via LangChain

Helpful Resources

Comments

Popular

How to Fine-Tune LLaMA 3.2-1B-Instruct for Korean Instruction Tasks with LoRA and Hugging Face

LLaMA 3.2-1B-Instruct is a lightweight instruction-tuned language model released by Meta. It is designed to handle a wide range of instruction-based tasks with relatively low computational resources. Although the model was trained with multilingual capabilities, its performance on languages not included in its training set—such as Korean—is limited. This tutorial demonstrates how to fine-tune this open-source model on a Korean dataset using Hugging Face Transformers and PEFT (specifically LoRA), enabling it to better respond to Korean instructions. 1. Prerequisites Before running the example code below, ensure you have the following libraries installed: pip install torch transformers datasets peft accelerate mlflow huggingface_hub To use the LLaMA model or KoAlpaca datasets, you'll need a Hugging Face token. Additionally, you may need to handle potential CUDA Out-Of-Memory (OOM) errors. The following code takes care of both: from huggingface_hub import login login("y...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...