shoaib-28838 commited on
Commit
7b34ba5
·
verified ·
1 Parent(s): d80de2b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -0
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import gradio as gr
4
+ from langchain_openai import ChatOpenAI
5
+ from langchain.prompts import (
6
+ ChatPromptTemplate,
7
+ MessagesPlaceholder,
8
+ SystemMessagePromptTemplate,
9
+ HumanMessagePromptTemplate,
10
+ )
11
+ from langchain_core.output_parsers import StrOutputParser
12
+ from langchain.chains import LLMChain
13
+ from langchain.memory import ConversationBufferMemory
14
+
15
+ # Load environment variables
16
+ load_dotenv()
17
+ OPENAI_SECRET_KEY = os.getenv("OPENAI_API_KEY")
18
+
19
+ def initialize_chatbot():
20
+ """Initialize the chatbot components."""
21
+ if not OPENAI_SECRET_KEY:
22
+ raise ValueError("OpenAI API Key not found in environment variables.")
23
+
24
+ # Initialize the chatbot components
25
+ llm = ChatOpenAI(api_key=OPENAI_SECRET_KEY)
26
+ prompt = ChatPromptTemplate(
27
+ messages=[
28
+ SystemMessagePromptTemplate.from_template(
29
+ "You are a nice chatbot having a conversation with a human."
30
+ ),
31
+ MessagesPlaceholder(variable_name="chat_history"),
32
+ HumanMessagePromptTemplate.from_template("{question}")
33
+ ]
34
+ )
35
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
36
+ conversation = LLMChain(
37
+ llm=llm,
38
+ prompt=prompt,
39
+ verbose=True,
40
+ memory=memory
41
+ )
42
+
43
+ output_parser = StrOutputParser()
44
+ chain = conversation
45
+ return chain
46
+
47
+ # Initialize the chatbot outside of the function to make it accessible
48
+ chain = initialize_chatbot()
49
+
50
+ def chat_response(message, history):
51
+ """Generate response for the given message."""
52
+ response = chain.invoke({"question": message})
53
+ return response
54
+
55
+ if __name__ == "__main__":
56
+ # Launch the chat interface
57
+ gr.ChatInterface(
58
+ chat_response,
59
+ chatbot=gr.Chatbot(height=500),
60
+ textbox=gr.Textbox(placeholder="", container=False, scale=7),
61
+ title="ChatBot",
62
+ description="Ask any question",
63
+ theme="soft",
64
+ examples=["Hello", "Am I cool?", "What is GenAI?"],
65
+ cache_examples=True,
66
+ retry_btn=None,
67
+ undo_btn="Delete Previous",
68
+ clear_btn="Clear",
69
+ ).launch()