Introduction
The Gemini API provides access to Google's powerful large language models, enabling developers to integrate advanced AI capabilities into their applications. This tutorial will guide you through the essential steps to start using the Gemini API in a Python script, from obtaining an API key to sending a request and handling the response.
Prerequisites
- Python 3.8+ installed on your machine.
- Requests library (
pip install requests) for HTTP calls. - API Key from Google AI Platform. Visit the Google Cloud Console, enable the Gemini API, and create an API key.
Setting Up Authentication
import requests API_KEY = "YOUR_API_KEY_HERE" BASE_URL = "https://generativelanguage.googleapis.com/v1beta1/models/gemini-pro:generateText" Replace YOUR_API_KEY_HERE with your actual key. The endpoint uses HTTP POST and expects a JSON payload.
Making a Request
The request body follows the format required by Gemini:
payload = { "prompt": "Write a short poem about sunrise.", "generation_config": { "max_output_tokens": 150, "temperature": 0.7, "top_p": 0.9, "top_k": 50, "stop_sequences": ["\"\"\""] } } response = requests.post(BASE_URL, json=payload, headers={"Authorization": f"Bearer {API_KEY}"}) Handling the Response
If the request succeeds (HTTP 200), the response contains the generated text:
if response.status_code == 200: data = response.json() generated_text = data.get("generated_text", "") print(generated_text) else: print(f"Error: {response.status_code} - {response.text}") Full Example
import requests API_KEY = "YOUR_API_KEY_HERE" BASE_URL = "https://generativelanguage.googleapis.com/v1beta1/models/gemini-pro:generateText" def generate_text(prompt, max_tokens=150, temperature=0.7): payload = { "prompt": prompt, "generation_config": { "max_output_tokens": max_tokens, "temperature": temperature, "top_p": 0.9, "top_k": 50, "stop_sequences": ["\"\"\""] } } url = f"{BASE_URL}?key={API_KEY}" response = requests.post(url, json=payload) if response.status_code == 200: return response.json().get("generated_text", "") else: raise Exception(f"Request failed: {response.status_code} - {response.text}") # Example usage if __name__ == "__main__": print(generate_text("Explain quantum computing in simple terms.")) Conclusion
Integrating the Gemini API is straightforward once you have the correct endpoint and payload. Experiment with different prompts and generation parameters to tailor outputs for your use case. Remember to respect usage limits and billing policies on your Google Cloud account. Happy coding!
