Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.prompts.prompt import PromptTemplate
|
2 |
+
from langchain.llms import OpenAI
|
3 |
+
from langchain.chains import ChatVectorDBChain
|
4 |
+
import os
|
5 |
+
from typing import Optional, Tuple
|
6 |
+
import gradio as gr
|
7 |
+
import pickle
|
8 |
+
from threading import Lock
|
9 |
+
|
10 |
+
with open("vanguard_vectorstore.pkl", "rb") as f:
|
11 |
+
vectorstore = pickle.load(f)
|
12 |
+
|
13 |
+
_template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.
|
14 |
+
You can assume the question about investing and the investment management industry.
|
15 |
+
Chat History:
|
16 |
+
{chat_history}
|
17 |
+
Follow Up Input: {question}
|
18 |
+
Standalone question:"""
|
19 |
+
CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
|
20 |
+
|
21 |
+
template = """You are an AI assistant for answering questions about investing and the investment management industry.
|
22 |
+
You are given the following extracted parts of a long document and a question. Provide a conversational answer.
|
23 |
+
If you don't know the answer, just say "Hmm, I'm not sure." Don't try to make up an answer.
|
24 |
+
If the question is not about investing, politely inform them that you are tuned to only answer questions about investing and the investment management industry.
|
25 |
+
Question: {question}
|
26 |
+
=========
|
27 |
+
{context}
|
28 |
+
=========
|
29 |
+
Answer in Markdown:"""
|
30 |
+
QA_PROMPT = PromptTemplate(template=template, input_variables=["question", "context"])
|
31 |
+
|
32 |
+
|
33 |
+
def get_chain(vectorstore):
|
34 |
+
llm = OpenAI(temperature=0)
|
35 |
+
qa_chain = ChatVectorDBChain.from_llm(
|
36 |
+
llm,
|
37 |
+
vectorstore,
|
38 |
+
qa_prompt=QA_PROMPT,
|
39 |
+
condense_question_prompt=CONDENSE_QUESTION_PROMPT,
|
40 |
+
)
|
41 |
+
return qa_chain
|
42 |
+
|
43 |
+
def set_openai_api_key(api_key: str):
|
44 |
+
"""Set the api key and return chain.
|
45 |
+
If no api_key, then None is returned.
|
46 |
+
"""
|
47 |
+
if api_key:
|
48 |
+
# os.environ["OPENAI_API_KEY"] = api_key
|
49 |
+
chain = get_chain(vectorstore)
|
50 |
+
# os.environ["OPENAI_API_KEY"] = ""
|
51 |
+
return chain
|
52 |
+
|
53 |
+
class ChatWrapper:
|
54 |
+
|
55 |
+
def __init__(self):
|
56 |
+
self.lock = Lock()
|
57 |
+
def __call__(
|
58 |
+
self, api_key: str, inp: str, history: Optional[Tuple[str, str]], chain
|
59 |
+
):
|
60 |
+
"""Execute the chat functionality."""
|
61 |
+
self.lock.acquire()
|
62 |
+
try:
|
63 |
+
history = history or []
|
64 |
+
# If chain is None, that is because no API key was provided.
|
65 |
+
if chain is None:
|
66 |
+
history.append((inp, "Please paste your OpenAI key to use"))
|
67 |
+
return history, history
|
68 |
+
# Set OpenAI key
|
69 |
+
import openai
|
70 |
+
openai.api_key = api_key
|
71 |
+
# Run chain and append input.
|
72 |
+
output = chain({"question": inp, "chat_history": history})["answer"]
|
73 |
+
history.append((inp, output))
|
74 |
+
except Exception as e:
|
75 |
+
raise e
|
76 |
+
finally:
|
77 |
+
self.lock.release()
|
78 |
+
return history, history
|
79 |
+
|
80 |
+
chat = ChatWrapper()
|
81 |
+
|
82 |
+
block = gr.Blocks(css=".gradio-container {background-color: lightgray}")
|
83 |
+
|
84 |
+
with block:
|
85 |
+
with gr.Row():
|
86 |
+
gr.Markdown("<h3><center>Chat-Your-Data (Vanguard Investments Australia)</center></h3>")
|
87 |
+
|
88 |
+
openai_api_key_textbox = gr.Textbox(
|
89 |
+
placeholder="Paste your OpenAI API key (sk-...)",
|
90 |
+
show_label=False,
|
91 |
+
lines=1,
|
92 |
+
type="password",
|
93 |
+
)
|
94 |
+
|
95 |
+
chatbot = gr.Chatbot()
|
96 |
+
|
97 |
+
with gr.Row():
|
98 |
+
message = gr.Textbox(
|
99 |
+
label="What's your question?",
|
100 |
+
placeholder="Ask questions about Investing with Vanguard",
|
101 |
+
lines=1,
|
102 |
+
)
|
103 |
+
submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
|
104 |
+
|
105 |
+
gr.Examples(
|
106 |
+
examples=[
|
107 |
+
"What are the benefits of investing in ETFs?",
|
108 |
+
"What is the average cost of investing in a managed fund?",
|
109 |
+
"At what age can I start investing?",
|
110 |
+
"Do you offer investment accounts for kids?"
|
111 |
+
],
|
112 |
+
inputs=message,
|
113 |
+
)
|
114 |
+
|
115 |
+
gr.HTML("Demo application of a LangChain chain.")
|
116 |
+
|
117 |
+
gr.HTML(
|
118 |
+
"<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain π¦οΈπ</a></center>"
|
119 |
+
)
|
120 |
+
|
121 |
+
state = gr.State()
|
122 |
+
agent_state = gr.State()
|
123 |
+
|
124 |
+
submit.click(chat, inputs=[openai_api_key_textbox, message, state, agent_state], outputs=[chatbot, state])
|
125 |
+
message.submit(chat, inputs=[openai_api_key_textbox, message, state, agent_state], outputs=[chatbot, state])
|
126 |
+
|
127 |
+
openai_api_key_textbox.change(
|
128 |
+
set_openai_api_key,
|
129 |
+
inputs=[openai_api_key_textbox],
|
130 |
+
outputs=[agent_state],
|
131 |
+
)
|
132 |
+
|
133 |
+
block.launch(debug=True)
|