First, this article is written by a Japanese man who is studying English now, so I think it may use incorrect English grammar and phrases. I would appreciate your kind understanding.
This article summarize that how to use Google Gemini API.
Let’s get down to the main topic.
Use Gemini API
The steps required to use Gemini API are as follows.
- Get API Key
- Installing the required libraries
- Coding and Excute the code
Step1. Get API Key
Obtain an API key by referring to the official Google Cloud page.
https://cloud.google.com/docs/authentication/api-keys
Step2. Installing the required libraries
Build an environment to use Gemini API. I used Flask to use Gemini API.
But you don’t need to use Flask. Create a virtual environment using venv and then you create main.py and .env and then install google-generativeai.
Create a virtual environment.
python -m venv env
source env/Scripts/activate
Create main.py and .env.
touch main.py
touch .env
Install google-generativeai and python-dotenv. Installing python-dotenv is optional.
pip install google-generativeai python-dotenv
Coding and Excute the code
Write main.py following code.
import os
from dotenv import load_dotenv
import google.generativeai as genai
# Loading .env file
load_dotenv()
# Setting API Key
GOOGLE_API_KEY=os.getenv('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)
gemini_pro = genai.GenerativeModel("gemini-pro")
prompt = "Hello World!"
res = gemini_pro.generate_content(prompt)
print(res.text)
Write the API key in .env.
GOOGLE_API_KEY=[your API Key]
Then run the below command.
python main.py
Error setting environment variables
An error occurred when setting the environment variable “GOOGLE_APPLICATION_CREDENTIALS” when using GCP.
The solution for this error is as follows:
1. Create a GCP service account key(json)
How to create service account key
2. Set GOOGLE_APPLICATION_CREDENTIALS in .env file
GOOGLE_APPLICATION_CREDENTIALS=[your GCP service account key’s path]
self-made app using Gemini API
Lastly, I would like to introduce a self-made application using Gemini API.
https://github.com/kkoch5t2/auto-article-create
It’s a simple application using flask. If you’d like, check this app’s source code and please tell me your feedback.