Upload 2 files
Browse files- chatbot/conversation.py +61 -0
- chatbot/database.py +40 -0
chatbot/conversation.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from langchain_community.chat_message_histories import SQLChatMessageHistory
|
| 3 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 4 |
+
from langchain_core.runnables.history import RunnableWithMessageHistory
|
| 5 |
+
from langchain_google_genai import GoogleGenerativeAI # Update based on your model
|
| 6 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 7 |
+
from config import DB_PATH # Import database path
|
| 8 |
+
import config
|
| 9 |
+
|
| 10 |
+
# Generate a unique session ID
|
| 11 |
+
def generate_session_id():
|
| 12 |
+
return str(uuid.uuid4())
|
| 13 |
+
|
| 14 |
+
# Fetch session message history from the database
|
| 15 |
+
def get_session_message_history_from_db(session_id):
|
| 16 |
+
chat_message_history = SQLChatMessageHistory(session_id=session_id, connection=f"sqlite:///{DB_PATH}")
|
| 17 |
+
return chat_message_history
|
| 18 |
+
|
| 19 |
+
# Define a chat template
|
| 20 |
+
chat_template = ChatPromptTemplate(
|
| 21 |
+
messages=[
|
| 22 |
+
("system", """You are a helpful AI assistant. Provide clear, concise, and accurate responses.
|
| 23 |
+
Maintain a friendly and professional tone.
|
| 24 |
+
For technical queries, give step-by-step explanations and examples.
|
| 25 |
+
If a question is unclear, ask for clarification.
|
| 26 |
+
Keep responses engaging and contextually relevant.
|
| 27 |
+
If unsure, admit it rather than guessing."""),
|
| 28 |
+
MessagesPlaceholder(variable_name="history"),
|
| 29 |
+
("human", "{human_input}")
|
| 30 |
+
]
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Define the AI model (Update based on your API key and provider)
|
| 34 |
+
model = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=config.GOOGLE_API_KEY)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Define output parser
|
| 38 |
+
output_parser = StrOutputParser()
|
| 39 |
+
|
| 40 |
+
# Create the conversation chain
|
| 41 |
+
chain = chat_template | model | output_parser
|
| 42 |
+
|
| 43 |
+
# Use RunnableWithMessageHistory to manage chat history
|
| 44 |
+
conversation_chain = RunnableWithMessageHistory(
|
| 45 |
+
chain,
|
| 46 |
+
get_session_message_history_from_db,
|
| 47 |
+
input_messages_key="human_input",
|
| 48 |
+
history_messages_key="history"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Function to interact with the chatbot
|
| 52 |
+
def chat_bot(prompt, session_id=None):
|
| 53 |
+
if session_id is None:
|
| 54 |
+
session_id = generate_session_id() # Generate a new session ID if not provided
|
| 55 |
+
|
| 56 |
+
config = {"configurable": {"session_id": session_id}}
|
| 57 |
+
input_prompt = {"human_input": prompt}
|
| 58 |
+
|
| 59 |
+
response = conversation_chain.invoke(input_prompt, config=config)
|
| 60 |
+
|
| 61 |
+
return response, session_id # Return both response and session ID
|
chatbot/database.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
from config import DB_PATH # Import database path from config.py
|
| 3 |
+
|
| 4 |
+
def create_table():
|
| 5 |
+
"""Creates the chat history table if it doesn't exist."""
|
| 6 |
+
conn = sqlite3.connect(DB_PATH)
|
| 7 |
+
cursor = conn.cursor()
|
| 8 |
+
cursor.execute("""
|
| 9 |
+
CREATE TABLE IF NOT EXISTS chat_history (
|
| 10 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 11 |
+
session_id TEXT,
|
| 12 |
+
user_message TEXT,
|
| 13 |
+
bot_response TEXT,
|
| 14 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
| 15 |
+
)
|
| 16 |
+
""")
|
| 17 |
+
conn.commit()
|
| 18 |
+
conn.close()
|
| 19 |
+
|
| 20 |
+
def get_chat_history(session_id):
|
| 21 |
+
"""Fetches chat history for a given session."""
|
| 22 |
+
conn = sqlite3.connect(DB_PATH)
|
| 23 |
+
cursor = conn.cursor()
|
| 24 |
+
cursor.execute("SELECT user_message, bot_response FROM chat_history WHERE session_id=? ORDER BY timestamp",
|
| 25 |
+
(session_id,))
|
| 26 |
+
history = cursor.fetchall()
|
| 27 |
+
conn.close()
|
| 28 |
+
return history
|
| 29 |
+
|
| 30 |
+
def save_chat(session_id, user_message, bot_response):
|
| 31 |
+
"""Stores a chat message in the database."""
|
| 32 |
+
conn = sqlite3.connect(DB_PATH)
|
| 33 |
+
cursor = conn.cursor()
|
| 34 |
+
cursor.execute("INSERT INTO chat_history (session_id, user_message, bot_response) VALUES (?, ?, ?)",
|
| 35 |
+
(session_id, user_message, bot_response))
|
| 36 |
+
conn.commit()
|
| 37 |
+
conn.close()
|
| 38 |
+
|
| 39 |
+
# Initialize the database
|
| 40 |
+
create_table()
|