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 Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

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 ...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...