Gemini is Google's most capable AI model family, offering multimodal capabilities that can understand and process text, images, audio, video, and code. The Gemini API allows developers to integrate these powerful AI capabilities into their applications, including chatbots.
pip install google-generativeai
import google.generativeai as genai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure the API key
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
Here's a basic implementation of a chatbot using the Gemini API:
import google.generativeai as genai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure the API key
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Set up the model
model = genai.GenerativeModel('gemini-1.5-pro')
# Initialize a chat session
chat = model.start_chat(history=[])
def get_response(user_input):
response = chat.send_message(user_input)
return response.text
# Example chat loop
def chat_loop():
print("Chatbot: Hello! How can I help you today? (Type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Goodbye!")
break
response = get_response(user_input)
print(f"Chatbot: {response}")
if __name__ == "__main__":
chat_loop()
System instructions help define the behavior, capabilities, and limitations of your chatbot:
# Adding system instructions
chat = model.start_chat(history=[])
chat.send_message("""
System: You are a helpful assistant for a programming course.
You should provide concise explanations about Python concepts
and offer code examples when appropriate. Be friendly and encouraging.
""")
For a more interactive experience, you can stream responses as they're generated: