Getting Started with the Gemini API
The Gemini API provides access to Google's powerful language models. This tutorial will guide you through authentication, making requests, and interpreting responses.
1. Obtain an API Key
Visit the Google AI Platform console, create a project, enable the Generative Language API, and generate an API key.
2. Set Up Your Environment
Install the required package:
pip install google-generativeai
Set the API key as an environment variable:
import os
os.environ["GOOGLE_API_KEY"] = "YOUR_API_KEY"
3. Initialize the Client
import google.generativeai as genai
model = genai.GenModel("gemini-1.5-pro")
4. Make a Request
Create a prompt and generate text:
prompt = "Explain quantum computing in simple terms."
response = model.generate(prompt)
print(response.text)
5. Understand the Response
The response object includes:
-
text: The generated output. -
usage: Token usage and cost details.
6. Manage Costs
The API is billed per million tokens. Monitor usage to stay within budget. The free tier often covers small projects.
7. Error Handling
Wrap calls in try/except to handle network issues:
try:
response = model.generate(prompt)
except Exception as e:
print(f"Error: {e}")
8. Next Steps
- Try different models like
gemini-1.5-ultrafor higher quality. - Use the API for chat, embeddings, or batch requests.
- Integrate into web apps, bots, or data pipelines.
Conclusion
The Gemini API is easy to use. Follow these steps to start building AI-powered applications.
Top comments (0)