Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import gradio as grfrom huggingface_hub import InferenceClient"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")def respond(message,history: list[tuple[str, str]],system_message,max_tokens,temperature,top_p,):messages = [{"role": "system", "content": system_message}]for val in history:if val[0]:messages.append({"role": "user", "content": val[0]})if val[1]:messages.append({"role": "assistant", "content": val[1]})messages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):token = message.choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""demo = gr.ChatInterface(respond,additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1,maximum=1.0,value=0.95,step=0.05,label="Top-p (nucleus sampling)",),],)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168import osfrom langchain_huggingface import HuggingFaceEndpointimport streamlit as stfrom langchain_core.prompts import PromptTemplatefrom langchain_core.output_parsers import StrOutputParsermodel_id="mistralai/Mistral-7B-Instruct-v0.3"def get_llm_hf_inference(model_id=model_id, max_new_tokens=128, temperature=0.1):"""Returns a language model for HuggingFace inference.Parameters:- model_id (str): The ID of the HuggingFace model repository.- max_new_tokens (int): The maximum number of new tokens to generate.- temperature (float): The temperature for sampling from the model.Returns:- llm (HuggingFaceEndpoint): The language model for HuggingFace inference."""llm = HuggingFaceEndpoint(repo_id=model_id,max_new_tokens=max_new_tokens,temperature=temperature,token = os.getenv("HF_TOKEN"))return llm# Configure the Streamlit appst.set_page_config(page_title="HuggingFace ChatBot", page_icon="🤗")st.title("Personal HuggingFace ChatBot")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}.*")# Initialize session state for avatarsif "avatars" not in st.session_state:st.session_state.avatars = {'user': None, 'assistant': None}# Initialize session state for user text inputif 'user_text' not in st.session_state:st.session_state.user_text = None# Initialize session state for model parametersif "max_response_length" not in st.session_state:st.session_state.max_response_length = 256if "system_message" not in st.session_state:st.session_state.system_message = "friendly AI conversing with a human user"if "starter_message" not in st.session_state:st.session_state.starter_message = "Hello, there! How can I help you today?"# Sidebar for settingswith st.sidebar:st.header("System Settings")# AI Settingsst.session_state.system_message = st.text_area("System Message", value="You are a friendly AI conversing with a human user.")st.session_state.starter_message = st.text_area('First AI Message', value="Hello, there! How can I help you today?")# Model Settingsst.session_state.max_response_length = st.number_input("Max Response Length", value=128)# Avatar Selectionst.markdown("*Select Avatars:*")col1, col2 = st.columns(2)with col1:st.session_state.avatars['assistant'] = st.selectbox("AI Avatar", options=["🤗", "💬", "🤖"], index=0)with col2:st.session_state.avatars['user'] = st.selectbox("User Avatar", options=["👤", "👱♂️", "👨🏾", "👩", "👧🏾"], index=0)# Reset Chat Historyreset_history = st.button("Reset Chat History")# Initialize or reset chat historyif "chat_history" not in st.session_state or reset_history:st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]def get_response(system_message, chat_history, user_text,eos_token_id=['User'], max_new_tokens=256, get_llm_hf_kws={}):"""Generates a response from the chatbot model.Args:system_message (str): The system message for the conversation.chat_history (list): The list of previous chat messages.user_text (str): The user's input text.model_id (str, optional): The ID of the HuggingFace model to use.eos_token_id (list, optional): The list of end-of-sentence token IDs.max_new_tokens (int, optional): The maximum number of new tokens to generate.get_llm_hf_kws (dict, optional): Additional keyword arguments for the get_llm_hf function.Returns:tuple: A tuple containing the generated response and the updated chat history."""# Set up the modelhf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.1)# Create the prompt templateprompt = PromptTemplate.from_template(("[INST] {system_message}""\nCurrent Conversation:\n{chat_history}\n\n""\nUser: {user_text}.\n [/INST]""\nAI:"))# Make the chain and bind the promptchat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')# Generate the responseresponse = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))response = response.split("AI:")[-1]# Update the chat historychat_history.append({'role': 'user', 'content': user_text})chat_history.append({'role': 'assistant', 'content': response})return response, chat_history# Chat interfacechat_interface = st.container(border=True)with chat_interface:output_container = st.container()st.session_state.user_text = st.chat_input(placeholder="Enter your text here.")# Display chat messageswith output_container:# For every message in the historyfor message in st.session_state.chat_history:# Skip the system messageif message['role'] == 'system':continue# Display the chat message using the correct avatarwith st.chat_message(message['role'],avatar=st.session_state['avatars'][message['role']]):st.markdown(message['content'])# When the user enter new text:if st.session_state.user_text:# Display the user's new message immediatelywith st.chat_message("user",avatar=st.session_state.avatars['user']):st.markdown(st.session_state.user_text)# Display a spinner status bar while waiting for the responsewith st.chat_message("assistant",avatar=st.session_state.avatars['assistant']):with st.spinner("Thinking..."):# Call the Inference API with the system_prompt, user text, and historyresponse, st.session_state.chat_history = get_response(system_message=st.session_state.system_message,user_text=st.session_state.user_text,chat_history=st.session_state.chat_history,max_new_tokens=st.session_state.max_response_length,)st.markdown(response)
app.py+167-63