Skip to content

Commit 62f20c5

Browse files
Create Dash-Langchain-app2.py
1 parent 11dfc81 commit 62f20c5

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Blog/Dash-Langchain-app2.py

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
from dash import Dash, dcc, html, callback, Input, Output, State, no_update
2+
from operator import itemgetter
3+
4+
from langchain.prompts import ChatPromptTemplate
5+
from langchain.chat_models import ChatOpenAI
6+
from langchain.embeddings import OpenAIEmbeddings
7+
from langchain.schema.output_parser import StrOutputParser
8+
from langchain.schema.runnable import RunnablePassthrough, RunnableLambda
9+
from langchain.vectorstores import FAISS
10+
11+
api_key = "my-api-key" # https://platform.openai.com/account/api-keys
12+
app = Dash()
13+
14+
app.layout = html.Div([
15+
html.H1("Summarize Earnings Reports"),
16+
html.Label("Select earnings report:"),
17+
dcc.Dropdown(value='tesla-earning-report.txt',
18+
id='reports',
19+
clearable=False,
20+
style={'width':'120px'},
21+
options=[
22+
{'label':'Tesla', 'value':'tesla-earning-report.txt'},
23+
{'label':'Microsoft', 'value':'microsoft-earning-report.txt'}]
24+
),
25+
dcc.Input(id='question',
26+
type='text',
27+
placeholder='type your question...',
28+
debounce=True,
29+
style={'width':'500px', 'height':'30px', 'margin-top':20},
30+
maxLength=100),
31+
dcc.Loading(id="loading", children=html.Div(id='answer', children=None, style={'margin-bottom':20})),
32+
html.Hr(),
33+
html.Div(id='report-content', children=[])
34+
])
35+
36+
37+
@callback(
38+
Output('answer', 'children'),
39+
Output('report-content', 'children'),
40+
Input('question','value'),
41+
State('reports', 'value'),
42+
prevent_initial_call=True
43+
)
44+
def update_layout(question_asked, file):
45+
if question_asked:
46+
with open(file, encoding="utf8") as f:
47+
lines = f.readlines()
48+
49+
vectorstore = FAISS.from_texts(lines, embedding=OpenAIEmbeddings(openai_api_key=api_key))
50+
retriever = vectorstore.as_retriever()
51+
52+
template = """Answer the question based only on the following context:
53+
{context}
54+
55+
Question: {question}
56+
"""
57+
58+
prompt = ChatPromptTemplate.from_template(template)
59+
60+
model = ChatOpenAI(openai_api_key=api_key)
61+
62+
chain = (
63+
{"context": retriever, "question": RunnablePassthrough()}
64+
| prompt
65+
| model
66+
| StrOutputParser()
67+
)
68+
display_answer = chain.invoke(question_asked)
69+
70+
view_selected_report = [
71+
html.H3("Complete earnings report chosen:"),
72+
dcc.Markdown(children=lines)
73+
74+
]
75+
76+
return display_answer, view_selected_report
77+
78+
else:
79+
return no_update
80+
81+
82+
if __name__ == "__main__":
83+
app.run_server(debug=True)

0 commit comments

Comments
 (0)