DEV Community

Phil IPS
Phil IPS

Posted on

Getting Started with the Gemini API: A 500-Word Tutorial

Getting Started with the Gemini API

The Gemini API gives you access to Google's cutting-edge large language models. This tutorial will walk you through the essential steps to start using the API in your own projects.

1. Getting an API Key

  1. Visit the Google AI Platform console.
  2. Create a new project or select an existing one.
  3. Enable the Generative Language API.
  4. Generate an API key and keep it secret.

2. Setting Up Your Environment

You can use any language that supports HTTP requests, but Python makes it easiest.

pip install google-generativeai
Enter fullscreen mode Exit fullscreen mode

Set the API key as an environment variable:

import os
os.environ["GOOGLE_API_KEY"] = "YOUR_API_KEY_HERE"
Enter fullscreen mode Exit fullscreen mode

3. Initializing the Client

import google.generativeai as genai

# Choose a model; gemini-1.5-pro is a good starting point.
model = genai.GenModel("gemini-1.5-pro")
Enter fullscreen mode Exit fullscreen mode

4. Making a Completion Request

Create a prompt and send it to the model:

prompt = "Write a short poem about the ocean."
completion = model.generate(prompt)
print(completion.text)
Enter fullscreen mode Exit fullscreen mode

The generate method returns a Generation object. The primary attribute is text, which contains the model's response.

5. Understanding the Response

The response includes:

  • text: The generated content.
  • usage: Information about token usage and cost.
  • model: The model that generated the text.

You can access these via completion.text, completion.usage, etc.

6. Managing Costs

The Gemini API is billed per million tokens. Keep an eye on your usage to stay within budget. For small projects, the free tier often suffices.

7. Error Handling

Network errors or invalid requests will raise exceptions. Wrap calls in try/except blocks:

try:
    response = model.generate(prompt)
except Exception as e:
    print(f"Error: {e}")
Enter fullscreen mode Exit fullscreen mode

8. Next Steps

  • Explore different models like gemini-1.5-ultra for higher quality.
  • Use the API for chat completions, embeddings, or batch requests.
  • Integrate the API into web apps, bots, or data pipelines.

Conclusion

With minimal setup, the Gemini API lets you harness powerful language capabilities. Follow these steps to start building AI-powered applications today.

Top comments (0)