Building a Simple Chatbot with Google Generative AI
In this blog post, we'll walk through the steps to create a basic chatbot using Google's Generative AI (Gemini) that can remember user-provided information and retrieve it later.
Step 1: Setting Up Google Generative AI
First, we need to set up the Google Generative AI (genai) with an API key:
```python
import google.generativeai as genai
import json
import os
# Set up Google Generative AI
genai.configure(api_key="API_KEY") # Replace with your actual API key
```
# Step 2: Memory Management with JSON
The chatbot will store and retrieve user data using a JSON file (`memory.json`).
# Loading Memory
```python
MEMORY_FILE = "memory.json"
# Load memory from JSON file
def load_memory():
if os.path.exists(MEMORY_FILE):
with open(MEMORY_FILE, "r") as file:
return json.load(file)
return {}
```
# Saving Memory
```python
# Save memory to JSON file
def save_memory(memory):
with open(MEMORY_FILE, "w") as file:
json.dump(memory, file, indent=4)
```
# Storing User Data
```python
# Store user data in memory
def remember_info(key, value):
memory = load_memory()
memory[key.lower()] = value # Convert key to lowercase for consistency
save_memory(memory)
```
# Retrieving Stored Data
```python
# Retrieve stored data
def recall_info(key):
memory = load_memory()
return memory.get(key.lower(), "I do not remember.")
```
# Step 3: Generating Responses with Google Gemini API
The chatbot will use Google's `gemini-pro` model to generate responses.
```python
# Generate response using Google Gemini API
def chat_with_genai(prompt, context):
try:
model = genai.GenerativeModel("gemini-pro")
response = model.generate_content(f"{context}\n{prompt}")
return response.text.strip()
except Exception as e:
print(f"Google Gemini API Error: {e}")
return "An error occurred. Please try again later."
```
# Step 4: Running the Chatbot
The chatbot will run in a loop, allowing users to interact, store, and retrieve information.
```python
print("Chatbot: Hello! How can I assist you today? [Type 'quit' to exit]")
while True:
user_input = input("You: ").strip().lower()
if user_input in ["quit", "exit", "bye"]:
print("Chatbot: Goodbye!")
break
# Check if the user wants to remember something
if "remember" in user_input:
parts = user_input.split("remember", 1)
if len(parts) > 1:
details = parts[1].strip().split(" as ", 1)
if len(details) == 2:
key, value = details[0].strip(), details[1].strip()
remember_info(key, value)
print(f"Chatbot: Got it! I'll remember that {key} is {value}.")
else:
print("Chatbot: Please use the format 'Remember [key] as [value]'.")
else:
print("Chatbot: Please provide information to remember, e.g., 'Remember my name as Avinash Kumar'.")
continue
# Check if the user is asking for remembered information
if "what is" in user_input or "who is" in user_input or "where is" in user_input:
key = user_input.replace("what is", "").replace("who is", "").replace("where is", "").strip()
remembered_value = recall_info(key)
print(f"Chatbot: {remembered_value}")
continue
# Pass context from memory to API for better responses
memory = load_memory()
context = "\n".join([f"{key}: {value}" for key, value in memory.items()])
response = chat_with_genai(user_input, context)
print("Chatbot:", response)
```
# Conclusion
This simple chatbot shows how to:
1. Store and retrieve user data using a JSON file.
2. Generate responses using Google's Gemini API.
3. Handle user interactions for remembering and recalling information.
Full code
import google.generativeai as genai
import json
import os
# Configure Google Generative AI
genai.configure(api_key="API_KEY") # Replace with your actual API key
MEMORY_FILE = "memory.json"
# Load memory from JSON file
def load_memory():
if os.path.exists(MEMORY_FILE):
with open(MEMORY_FILE, "r") as file:
return json.load(file)
return {}
# Save memory to JSON file
def save_memory(memory):
with open(MEMORY_FILE, "w") as file:
json.dump(memory, file, indent=4)
# Store user data in memory
def remember_info(key, value):
memory = load_memory()
memory[key.lower()] = value # Convert key to lowercase for consistency
save_memory(memory)
# Retrieve stored data
def recall_info(key):
memory = load_memory() https://unhealthyirreparable.com/cit2c8ca?key=7566cfdb82de49ba4912160b26b7621f
return memory.get(key.lower(), "I do not remember.")
# Generate response using Google Gemini API
def chat_with_genai(prompt, context):
try:
model = genai.GenerativeModel("gemini-pro")
response = model.generate_content(f"{context}\n{prompt}")
return response.text.strip()
except Exception as e:
print(f"Google Gemini API Error: {e}")
return "An error occurred. Please try again later."
# Main Chatbot Loop
print("Chatbot: Hello! How can I assist you today? [Type 'quit' to exit]")
while True:
user_input = input("You: ").strip().lower()
if user_input in ["quit", "exit", "bye"]:
print("Chatbot: Goodbye!")
break
https://unhealthyirreparable.com/cit2c8ca?key=7566cfdb82de49ba4912160b26b7621f # Check if the user wants to remember something
if "remember" in user_input:
parts = user_input.split("remember", 1)
if len(parts) > 1:
details = parts[1].strip().split(" as ", 1)
if len(details) == 2:
key, value = details[0].strip(), details[1].strip()
remember_info(key, value)
print(f"Chatbot: Got it! I'll remember that {key} is {value}.")
else:
print("Chatbot: Please use the format 'Remember [key] as [value]'.")
else:
print("Chatbot: Please provide information to remember, e.g., 'Remember my name as Avinash Kumar'.")
continue
# Check if the user is asking for remembered information
if "what is" in user_input or "who is" in user_input or "where is" in user_input:
key = user_input.replace("what is", "").replace("who is", "").replace("where is", "").strip()
remembered_value = recall_info(key)
print(f"Chatbot: {remembered_value}")
continue
# Pass context from memory to API for better responses
memory = load_memory()
context = "\n".join([f"{key}: {value}" for key, value in memory.items()])
response = chat_with_genai(user_input, context)
print("Chatbot:", response)

Comments
Post a Comment