DP-CE commited on
Commit
7782f61
Β·
verified Β·
1 Parent(s): 0a38d05

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +157 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,159 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_huggingface import HuggingFaceEndpoint
 
3
  import streamlit as st
4
+ from langchain_core.prompts import PromptTemplate
5
+ from langchain_core.output_parsers import StrOutputParser
6
 
7
+ def get_llm_hf_inference(model_id="mistralai/Mistral-7B-Instruct-v0.3", max_new_tokens=128, temperature=0.1):
8
+ token = os.getenv("HF_TOKEN") # Hugging Face Spaces injects this automatically
9
+
10
+ if not token:
11
+ raise ValueError("Missing Hugging Face API token. Please set 'HF_TOKEN' as a secret in your Space.")
12
+
13
+ return HuggingFaceEndpoint(
14
+ repo_id=model_id,
15
+ max_new_tokens=max_new_tokens,
16
+ temperature=temperature,
17
+ token=token
18
+ )
19
+
20
+ # Configure the Streamlit app
21
+ st.set_page_config(page_title="HuggingFace ChatBot", page_icon="πŸ€—")
22
+ st.title("Personal HuggingFace ChatBot")
23
+ st.markdown(f"*This is a simple chatbot that uses the HuggingFace transformers library to generate responses to your text input.*")
24
+
25
+ # Initialize session state for avatars
26
+ if "avatars" not in st.session_state:
27
+ st.session_state.avatars = {'user': None, 'assistant': None}
28
+
29
+ # Initialize session state for user text input
30
+ if 'user_text' not in st.session_state:
31
+ st.session_state.user_text = None
32
+
33
+ # Initialize session state for model parameters
34
+ if "max_response_length" not in st.session_state:
35
+ st.session_state.max_response_length = 256
36
+
37
+ if "system_message" not in st.session_state:
38
+ st.session_state.system_message = "friendly AI conversing with a human user"
39
+
40
+ if "starter_message" not in st.session_state:
41
+ st.session_state.starter_message = "Hello, there! How can I help you today?"
42
+
43
+
44
+ # Sidebar for settings
45
+ with st.sidebar:
46
+ st.header("System Settings")
47
+
48
+ # AI Settings
49
+ st.session_state.system_message = st.text_area(
50
+ "System Message", value="You are a friendly AI conversing with a human user."
51
+ )
52
+ st.session_state.starter_message = st.text_area(
53
+ 'First AI Message', value="Hello, there! How can I help you today?"
54
+ )
55
+
56
+ # Model Settings
57
+ st.session_state.max_response_length = st.number_input(
58
+ "Max Response Length", value=128
59
+ )
60
+
61
+ # Avatar Selection
62
+ st.markdown("*Select Avatars:*")
63
+ col1, col2 = st.columns(2)
64
+ with col1:
65
+ st.session_state.avatars['assistant'] = st.selectbox(
66
+ "AI Avatar", options=["πŸ€—", "πŸ’¬", "πŸ€–"], index=0
67
+ )
68
+ with col2:
69
+ st.session_state.avatars['user'] = st.selectbox(
70
+ "User Avatar", options=["πŸ‘€", "πŸ‘±β€β™‚οΈ", "πŸ‘¨πŸΎ", "πŸ‘©", "πŸ‘§πŸΎ"], index=0
71
+ )
72
+ # Reset Chat History
73
+ reset_history = st.button("Reset Chat History")
74
+
75
+ # Initialize or reset chat history
76
+ if "chat_history" not in st.session_state or reset_history:
77
+ st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]
78
+
79
+ def get_response(system_message, chat_history, user_text,
80
+ eos_token_id=['User'], max_new_tokens=256, get_llm_hf_kws={}):
81
+ """
82
+ Generates a response from the chatbot model.
83
+
84
+ Args:
85
+ system_message (str): The system message for the conversation.
86
+ chat_history (list): The list of previous chat messages.
87
+ user_text (str): The user's input text.
88
+ model_id (str, optional): The ID of the HuggingFace model to use.
89
+ eos_token_id (list, optional): The list of end-of-sentence token IDs.
90
+ max_new_tokens (int, optional): The maximum number of new tokens to generate.
91
+ get_llm_hf_kws (dict, optional): Additional keyword arguments for the get_llm_hf function.
92
+
93
+ Returns:
94
+ tuple: A tuple containing the generated response and the updated chat history.
95
+ """
96
+ # Set up the model
97
+ hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.1)
98
+
99
+ # Create the prompt template
100
+ prompt = PromptTemplate.from_template(
101
+ (
102
+ "[INST] {system_message}"
103
+ "\nCurrent Conversation:\n{chat_history}\n\n"
104
+ "\nUser: {user_text}.\n [/INST]"
105
+ "\nAI:"
106
+ )
107
+ )
108
+ # Make the chain and bind the prompt
109
+ chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
110
+
111
+ # Generate the response
112
+ response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
113
+ response = response.split("AI:")[-1]
114
+
115
+ # Update the chat history
116
+ chat_history.append({'role': 'user', 'content': user_text})
117
+ chat_history.append({'role': 'assistant', 'content': response})
118
+ return response, chat_history
119
+
120
+ # Chat interface
121
+ chat_interface = st.container(border=True)
122
+ with chat_interface:
123
+ output_container = st.container()
124
+ st.session_state.user_text = st.chat_input(placeholder="Enter your text here.")
125
+
126
+ # Display chat messages
127
+ with output_container:
128
+ # For every message in the history
129
+ for message in st.session_state.chat_history:
130
+ # Skip the system message
131
+ if message['role'] == 'system':
132
+ continue
133
+
134
+ # Display the chat message using the correct avatar
135
+ with st.chat_message(message['role'],
136
+ avatar=st.session_state['avatars'][message['role']]):
137
+ st.markdown(message['content'])
138
+
139
+ # When the user enter new text:
140
+ if st.session_state.user_text:
141
+
142
+ # Display the user's new message immediately
143
+ with st.chat_message("user",
144
+ avatar=st.session_state.avatars['user']):
145
+ st.markdown(st.session_state.user_text)
146
+
147
+ # Display a spinner status bar while waiting for the response
148
+ with st.chat_message("assistant",
149
+ avatar=st.session_state.avatars['assistant']):
150
+
151
+ with st.spinner("Thinking..."):
152
+ # Call the Inference API with the system_prompt, user text, and history
153
+ response, st.session_state.chat_history = get_response(
154
+ system_message=st.session_state.system_message,
155
+ user_text=st.session_state.user_text,
156
+ chat_history=st.session_state.chat_history,
157
+ max_new_tokens=st.session_state.max_response_length,
158
+ )
159
+ st.markdown(response)