"A large language model is a language model trained with self-supervised machine learning on a vast amount of text, designed for natural language processing tasks, especially language generation."
— Wikipedia
import requests
import json
# Setup API credentials
API_KEY = "YOUR_API_KEY_HERE"
API_URL = "https://generativelanguage.googleapis.com/..."
def ask_gemini(prompt: str):
"""Sends a prompt to the Gemini API"""
Import necessary libraries and configure API credentials to connect with Google's Gemini model.
# Construct the request payload
payload = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
]
}
# Set up headers with the API key
headers = {
"Content-Type": "application/json"
}
Structure the request with the user's prompt formatted according to Gemini API specifications.
# Complete URL including the API key parameter
full_url = f"{API_URL}?key={API_KEY}"
try:
# Make the POST request
response = requests.post(
full_url,
headers=headers,
data=json.dumps(payload)
)
response.raise_for_status()
# Parse the JSON response
result = response.json()
Send the HTTP POST request to the Gemini API and handle the response.
# Safely extract the generated text
generated_text = result.get('candidates', [{}])[0]\
.get('content', {})\
.get('parts', [{}])[0]\
.get('text', 'No response text found.')
print("--- Gemini Response ---")
print(generated_text)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
Extract the generated text from the API response and implement error handling.
if __name__ == "__main__":
# Define your question here
my_question = "What are the three most
interesting facts about
the ocean?"
# Call the function with your question
ask_gemini(my_question)
Execute the program by calling the ask_gemini() function.
--- Gemini Response ---
## The Three Most Interesting Facts About the Ocean
### 1. The Majority of Life and Terrain is Unknown (The 95% Mystery)
Despite centuries of exploration, humanity has explored and mapped less than 5%
of the global ocean. This means that approximately 95% of the deep-sea
environment and the life within it remains a complete mystery.
### 2. The Ocean is the World's Largest Museum (The Deep Cold Storage)
The deep sea acts as an immense, cold, dark, and low-oxygen preservative
environment, making it the perfect repository for history, geology, and even
atmospheric changes.
### 3. The Ocean Powers Our Weather and Produces Half Our Oxygen
The ocean is the primary engine driving global climate and sustaining life on
Earth through fundamental chemical and physical processes.
The model returns detailed, structured responses based on the prompt.