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
- Visit the Google AI Platform console.
- Create a new project or select an existing one.
- Enable the Generative Language API.
- 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
Set the API key as an environment variable:
import os
os.environ["GOOGLE_API_KEY"] = "YOUR_API_KEY_HERE"
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")
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)
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}")
8. Next Steps
- Explore different models like
gemini-1.5-ultrafor 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)