Chat History using Gemini AI

Bisha bhandari
2 min readJun 5, 2024

The Gemini API gives you access to the latest generative AI models from Google. The Gemini tutorials will help you get started with Gemini using a programming language of your choice.

To use the Gemini API, you’ll need an API key. If you don’t already have one, create a key in Google AI Studio.

Lets start with coding:

At first install all necessary packages that we gonna use in this:

pip install -q -U google-generativeai
pip install python-decouple

Then importing all the necessary libraries/packages:

import google.generativeai as genai
from decouple import config

Now, Setup Gemini API keys as in environment variables . Below are the step to set it .

#Create .env file where you wil create python fle 

gemini_api_key= "your_gemini-api-keys"

After setting environment variables in .env , link .env file with main python files . for instance:

GOOGLE_API_KEY=config("gemini_api_key")

genai.configure(api_key=GOOGLE_API_KEY)

Initialization of Generative Model

#Initialization of the Generative Model:
model = genai.GenerativeModel('gemini-1.5-flash')

Loop for user interactions:

#Loop for user interactions-you can send many message according to the range value determination.
x = range(2)
for n in x:
prompt=input("User:")
response = chat.send_message(prompt)
print(response.text)
print("chat-history:",chat.history)

you can check token-count for your Chat history:

token=model.count_tokens(chat.history)
print(token)

After completing the above process , you can run the code in terminal & will get below reference:

Conclusion:

1. Install Necessary Packages:
— Use `pip install -q -U google-generativeai` and `pip install decouple` to install required packages.

2. Import Libraries:
— Import `google.generativeai` as `genai`.
— Import `config` from `decouple`.

3. Set Up API Keys:
— Create a `.env` file to store your API keys.
— Link the `.env` file with the main Python file using `GOOGLE_API_KEY=config(“gemini_api_key”)`.

4. Configure API Key:
— Configure the Gemini API with `genai.configure(api_key=GOOGLE_API_KEY)`.

5. Initialize Generative Model:
— Initialize the generative model with `model = genai.GenerativeModel(‘gemini-1.5-flash’)`.

6. User Interaction Loop:
— Create a loop for user interactions where prompts are taken as input and responses are generated using `chat.send_message(prompt)`.

7. Check Chat History and Token Count:
— Print chat history using `print(“chat-history:”, chat.history)`.
— Check the token count with `token=model.count_tokens(chat.history)` and print it.

8. Run the Code:
— Run the code in the terminal to execute the above steps and interact with the generative AI model.

--

--