Thesebanana commited on
Commit
6335064
Β·
1 Parent(s): 93499bc

initial commit work

Browse files
Files changed (2) hide show
  1. app.py +169 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ model_id="mistralai/Mistral-7B-Instruct-v0.3"
8
+
9
+ # Function to get a language model for HuggingFace inference
10
+ def get_llm_hf_inference(model_id=model_id, max_new_tokens=128, temperature=0.1):
11
+ """
12
+ Returns a language model for HuggingFace inference.
13
+
14
+ Parameters:
15
+ - model_id (str): The ID of the HuggingFace model repository.
16
+ - max_new_tokens (int): The maximum number of new tokens to generate.
17
+ - temperature (float): The temperature for sampling from the model.
18
+
19
+ Returns:
20
+ - llm (HuggingFaceEndpoint): The language model for HuggingFace inference.
21
+ """
22
+ llm = HuggingFaceEndpoint(
23
+ repo_id=model_id,
24
+ max_new_tokens=max_new_tokens,
25
+ temperature=temperature,
26
+ token = os.getenv("HF_TOKEN")
27
+ )
28
+ return llm
29
+
30
+ # Configure the Streamlit app
31
+ st.set_page_config(page_title="HuggingFace ChatBot", page_icon="πŸ€—")
32
+ st.title("Personal HuggingFace ChatBot")
33
+ st.markdown(f"*This is a simple chatbot that uses the HuggingFace transformers library to generate responses to your text input. It uses the {model_id}.*")
34
+
35
+ # Initialize session state for avatars
36
+ if "avatars" not in st.session_state:
37
+ st.session_state.avatars = {'user': None, 'assistant': None}
38
+
39
+ # Initialize session state for user text input
40
+ if 'user_text' not in st.session_state:
41
+ st.session_state.user_text = None
42
+
43
+ # Initialize session state for model parameters
44
+ if "max_response_length" not in st.session_state:
45
+ st.session_state.max_response_length = 256
46
+
47
+ if "system_message" not in st.session_state:
48
+ st.session_state.system_message = "friendly AI conversing with a human user"
49
+
50
+ if "starter_message" not in st.session_state:
51
+ st.session_state.starter_message = "Hello, there! How can I help you today?"
52
+
53
+
54
+ # Sidebar for settings
55
+ with st.sidebar:
56
+ st.header("System Settings")
57
+
58
+ # AI Settings
59
+ st.session_state.system_message = st.text_area(
60
+ "System Message", value="You are a friendly AI conversing with a human user."
61
+ )
62
+ st.session_state.starter_message = st.text_area(
63
+ 'First AI Message', value="Hello, there! How can I help you today?"
64
+ )
65
+
66
+ # Model Settings
67
+ st.session_state.max_response_length = st.number_input(
68
+ "Max Response Length", value=128
69
+ )
70
+
71
+ # Avatar Selection
72
+ st.markdown("*Select Avatars:*")
73
+ col1, col2 = st.columns(2)
74
+ with col1:
75
+ st.session_state.avatars['assistant'] = st.selectbox(
76
+ "AI Avatar", options=["πŸ€—", "πŸ’¬", "πŸ€–"], index=0
77
+ )
78
+ with col2:
79
+ st.session_state.avatars['user'] = st.selectbox(
80
+ "User Avatar", options=["πŸ‘€", "πŸ‘±β€β™‚οΈ", "πŸ‘¨πŸΎ", "πŸ‘©", "πŸ‘§πŸΎ"], index=0
81
+ )
82
+ # Reset Chat History
83
+ reset_history = st.button("Reset Chat History")
84
+
85
+ # Initialize or reset chat history
86
+ if "chat_history" not in st.session_state or reset_history:
87
+ st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]
88
+
89
+ def get_response(system_message, chat_history, user_text,
90
+ eos_token_id=['User'], max_new_tokens=256, get_llm_hf_kws={}):
91
+ """
92
+ Generates a response from the chatbot model.
93
+
94
+ Args:
95
+ system_message (str): The system message for the conversation.
96
+ chat_history (list): The list of previous chat messages.
97
+ user_text (str): The user's input text.
98
+ model_id (str, optional): The ID of the HuggingFace model to use.
99
+ eos_token_id (list, optional): The list of end-of-sentence token IDs.
100
+ max_new_tokens (int, optional): The maximum number of new tokens to generate.
101
+ get_llm_hf_kws (dict, optional): Additional keyword arguments for the get_llm_hf function.
102
+
103
+ Returns:
104
+ tuple: A tuple containing the generated response and the updated chat history.
105
+ """
106
+ # Set up the model
107
+ hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.1)
108
+
109
+ # Create the prompt template
110
+ prompt = PromptTemplate.from_template(
111
+ (
112
+ "[INST] {system_message}"
113
+ "\nCurrent Conversation:\n{chat_history}\n\n"
114
+ "\nUser: {user_text}.\n [/INST]"
115
+ "\nAI:"
116
+ )
117
+ )
118
+ # Make the chain and bind the prompt
119
+ chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
120
+
121
+ # Generate the response
122
+ response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
123
+ response = response.split("AI:")[-1]
124
+
125
+ # Update the chat history
126
+ chat_history.append({'role': 'user', 'content': user_text})
127
+ chat_history.append({'role': 'assistant', 'content': response})
128
+ return response, chat_history
129
+
130
+ # Chat interface
131
+ chat_interface = st.container(border=True)
132
+ with chat_interface:
133
+ output_container = st.container()
134
+ st.session_state.user_text = st.chat_input(placeholder="Enter your text here.")
135
+
136
+ # Display chat messages
137
+ with output_container:
138
+ # For every message in the history
139
+ for message in st.session_state.chat_history:
140
+ # Skip the system message
141
+ if message['role'] == 'system':
142
+ continue
143
+
144
+ # Display the chat message using the correct avatar
145
+ with st.chat_message(message['role'],
146
+ avatar=st.session_state['avatars'][message['role']]):
147
+ st.markdown(message['content'])
148
+
149
+ # When the user enter new text:
150
+ if st.session_state.user_text:
151
+
152
+ # Display the user's new message immediately
153
+ with st.chat_message("user",
154
+ avatar=st.session_state.avatars['user']):
155
+ st.markdown(st.session_state.user_text)
156
+
157
+ # Display a spinner status bar while waiting for the response
158
+ with st.chat_message("assistant",
159
+ avatar=st.session_state.avatars['assistant']):
160
+
161
+ with st.spinner("Thinking..."):
162
+ # Call the Inference API with the system_prompt, user text, and history
163
+ response, st.session_state.chat_history = get_response(
164
+ system_message=st.session_state.system_message,
165
+ user_text=st.session_state.user_text,
166
+ chat_history=st.session_state.chat_history,
167
+ max_new_tokens=st.session_state.max_response_length,
168
+ )
169
+ st.markdown(response)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ huggingface_hub
3
+ streamlit
4
+ langchain_core
5
+ langchain_community
6
+ langchain_huggingface
7
+ langchain_text_splitters
8
+ accelerate
9
+ watchdog
10
+ tqdm