AIAI Club
← Back to articles
ENGLISH GUIDE

A Modern Usage Example for the Official Python SDK: From Environment Setup to Multi-Turn Conversation History Management

Build a chatbot with memory in Python! Use minimal hands-on code based on the official google-generativeai library, with a visual explanation of the chat = model.start_chat() history management technique.

1. Environment Installation and Initialization

Run the following in your terminal: pip install google-generativeai

2. Concise Python Code with Full Conversation History Memory

import os
import google.generativeai as genai

genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-flash")

chat = model.start_chat(history=[])
while True:
user_input = input("User: ")
if user_input.lower() == "exit":
break
response = chat.send_message(user_input)
print(f"Gemini: {response.text}")
With the start_chat object, all back-and-forth question history is automatically maintained in the background, so developers do not need to manually assemble complex JSON message arrays!

This English translation is based on a Chinese source article. Prices are approximate where stated and conditions should be confirmed with the official provider or seller.