Create langchain_app.py
Browse files- langchain_app.py +51 -0
langchain_app.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from langchain.chains import ConversationChain
|
3 |
+
from hugchat import hugchat
|
4 |
+
from hugchat.login import Login
|
5 |
+
|
6 |
+
st.set_page_config(page_title="HugChat - An LLM-powered Streamlit app")
|
7 |
+
st.title('🤗💬 HugChat App')
|
8 |
+
|
9 |
+
# Hugging Face Credentials
|
10 |
+
with st.sidebar:
|
11 |
+
st.header('Hugging Face Login')
|
12 |
+
hf_email = st.text_input('Enter E-mail:', type='password')
|
13 |
+
hf_pass = st.text_input('Enter password:', type='password')
|
14 |
+
|
15 |
+
# Store AI generated responses
|
16 |
+
if "messages" not in st.session_state.keys():
|
17 |
+
st.session_state.messages = [{"role": "assistant", "content": "I'm HugChat, How may I help you?"}]
|
18 |
+
|
19 |
+
# Display existing chat messages
|
20 |
+
for message in st.session_state.messages:
|
21 |
+
with st.chat_message(message["role"]):
|
22 |
+
st.write(message["content"])
|
23 |
+
|
24 |
+
# Function for generating LLM response
|
25 |
+
def generate_response(prompt, email, passwd):
|
26 |
+
# Hugging Face Login
|
27 |
+
sign = Login(email, passwd)
|
28 |
+
cookies = sign.login()
|
29 |
+
sign.saveCookies()
|
30 |
+
# Create ChatBot
|
31 |
+
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
|
32 |
+
chain = ConversationChain(llm=chatbot)
|
33 |
+
response = chain.run(input=prompt)
|
34 |
+
return response
|
35 |
+
|
36 |
+
# Prompt for user input and save
|
37 |
+
if prompt := st.chat_input():
|
38 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
39 |
+
with st.chat_message("user"):
|
40 |
+
st.write(prompt)
|
41 |
+
|
42 |
+
# If last message is not from assistant, we need to generate a new response
|
43 |
+
if st.session_state.messages[-1]["role"] != "assistant":
|
44 |
+
# Call LLM
|
45 |
+
with st.chat_message("assistant"):
|
46 |
+
with st.spinner("Thinking..."):
|
47 |
+
response = generate_response(prompt, hf_email, hf_pass)
|
48 |
+
st.write(response)
|
49 |
+
|
50 |
+
message = {"role": "assistant", "content": response}
|
51 |
+
st.session_state.messages.append(message)
|