generated from streamlit/app-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_app_test.py
88 lines (70 loc) · 3.84 KB
/
streamlit_app_test.py
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
78
79
80
81
82
83
84
85
86
87
import streamlit as st
import replicate
import os
import logging
# App title
st.set_page_config(page_title="🦙💬 Llama 2 Chatbot")
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Create a Logger instance
logger = logging.getLogger(__name__)
# Replicate credentials
with st.sidebar:
st.title("🦙💬 Llama 2 Chatbot")
if 'REPLICATE_API_TOKEN' in st.secrets:
st.success('API key already provided' ,icon='✅')
replicate_api = st.secrets['REPLICATE_API_TOKEN']
else:
replicate_api = st.text_input('Enter Replicate API Token:', type='password')
if not (replicate_api.startswith('r8_') and len(replicate_api) == 40):
st.warning('Please enter your credentials!', icon='⚠️')
else:
st.success('Proceed to entering your prompt message!' , icon ='👉')
temperature = st.sidebar.slider('temperature', min_value=0.01, max_value=5.0, value=0.1, step=0.01)
top_p = st.sidebar.slider('top_p', min_value=0.01, max_value=1.0, value=0.9, step=0.01)
max_length = st.sidebar.slider('max_length', min_value=64, max_value=4096, value=512, step=8)
st.markdown('📖 If you enjoyed this show some love at my [Linkedin Profile](https://www.linkedin.com/in/wolfsbane9513/) ')
os.environ['REPLICATE_API_TOKEN'] = replicate_api
# Store the LLM Generated response
if "messages" not in st.session_state.keys():
st.session_state.messages = [{"role":"assistant","content": "How may I assist you today?"}]
# Display or clear chat message
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
def clear_chat_history():
st.session_state.messages = [{"role":"assistant","content": "How may I assist you today?"}]
st.sidebar.button('Clear Chat History',on_click=clear_chat_history)
# Function for generating LLaMA2 response
# Refactored from <https://github.com/a16z-infra/llama2-chatbot>
def generate_llama2_response(prompt_input):
#string_dialogue = "You are a helpful assistant.You do not respond as 'User' or pretend to be a 'User'. You only respond once as 'Assistant'."
string_dialogue = "You are a helpful assistant. You do not respond as 'User' or pretend to be a 'User'. You only respond once as 'Assistant'."
for dict_message in st.session_state.messages:
if dict_message["role"] == "user":
string_dialogue += "User" + dict_message["content"] + "\\n\\n"
else:
string_dialogue += "Assistant" + dict_message["content"] + "\\n\\n"
logger.info(f"string dialogue{string_dialogue} - {prompt_input}")
output = replicate.run('a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5',
input = {"prompt": f"{string_dialogue}{prompt_input} Assistant: ",
"temperature":temperature, "top_p":top_p, "max_length":max_length, "repetition_penalty":1})
return output
# User provided prompt
if prompt := st.chat_input(disabled= not replicate_api):
st.session_state.messages.append({"role":"user","content":prompt})
with st.chat_message("user"):
st.write(prompt)
# Generate a new response if last message is not from assistant
if st.session_state.messages[-1]["role"] != "assistant":
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = generate_llama2_response(prompt)
placeholder = st.empty()
full_response = ''
for item in response:
full_response += item
placeholder.markdown(full_response)
placeholder.markdown(full_response)
logger.info(f"user prompt and api response {prompt},{full_response}")
message = {"role":"assistant","content": full_response}
st.session_state.messages.append(message)