-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathChat_Bot.py
More file actions
77 lines (61 loc) · 2.39 KB
/
Chat_Bot.py
File metadata and controls
77 lines (61 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from dotenv import load_dotenv
import time
import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_groq import ChatGroq
from langchain.memory import ConversationBufferMemory
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.chains import LLMChain
load_dotenv()
class LanguageModelProcessor:
def __init__(self):
groq_api_key = os.getenv("GROQ_API_KEY")
if groq_api_key:
self.llm = ChatGroq(temperature=0, model_name="llama3-8b-8192", groq_api_key=groq_api_key)
else:
raise ValueError("GROQ_API_KEY not found in environment variables. Please set one.")
self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
# Load Bot prompt
try:
with open('Bot_prompt.txt', 'r') as file:
Bot_prompt = file.read().strip()
except FileNotFoundError:
raise FileNotFoundError("Bot prompt file 'Bot_prompt.txt' not found. Please ensure it exists in the current directory.")
self.prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(Bot_prompt),
MessagesPlaceholder(variable_name="chat_history"),
HumanMessagePromptTemplate.from_template("{text}")
])
self.conversation = LLMChain(
llm=self.llm,
prompt=self.prompt,
memory=self.memory
)
def process(self, text):
response = self.conversation.invoke({"text": text})
return response['text']
class ConversationManager:
def __init__(self):
self.llm_processor = LanguageModelProcessor()
print()
print("Chatbot initialized. Type 'goodbye' to end.")
print()
def main(self):
while True:
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() in ["exit", "quit", "goodbye"]:
print("Bot: Goodbye!")
break
llm_response = self.llm_processor.process(user_input)
print(f"🤖 : {llm_response}")
print()
if __name__ == "__main__":
manager = ConversationManager()
manager.main()