Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line1111121131141151161171181191201211221231242 unmodified lines127128129130131import streamlit as stfrom functools import lru_cacheimport requests# Cache model loading to optimize performance@lru_cache(maxsize=3)def load_hf_model(model_name):# Use the Hugging Face Inference API directlyapi_url = f"https://api-inference.huggingface.co/models/deepseek-ai/{model_name}"return api_url# Load all models at startupMODELS = {"DeepSeek-R1-Distill-Qwen-32B": load_hf_model("DeepSeek-R1-Distill-Qwen-32B"),"DeepSeek-R1": load_hf_model("DeepSeek-R1"),"DeepSeek-R1-Zero": load_hf_model("DeepSeek-R1-Zero")}# --- Chatbot function ---def chatbot(input_text, history, model_choice, system_message, max_new_tokens, temperature, top_p):history = history or []# Get the selected model API URLapi_url = MODELS[model_choice]# Create payload for the modelpayload = {"inputs": {"messages": [{"role": "user", "content": input_text}],"system": system_message,"max_tokens": max_new_tokens,"temperature": temperature,"top_p": top_p}}# Run inference using the selected modeltry:headers = {"Authorization": f"Bearer {st.secrets['HUGGINGFACE_TOKEN']}"}response = requests.post(api_url, headers=headers, json=payload).json()# Handle the response formatif isinstance(response, list) and len(response) > 0:# Assuming the response is a list of generated textassistant_response = response[0].get("generated_text", "No response generated.")elif isinstance(response, dict) and "generated_text" in response:# If the response is a dictionary with generated_textassistant_response = response["generated_text"]else:assistant_response = "Unexpected model response format."except Exception as e:1 unmodified line# Append user and assistant messages to historyhistory.append((input_text, assistant_response))return history# --- Streamlit App ---st.set_page_config(page_title="DeepSeek Chatbot", page_icon="🤖", layout="wide")# Title and descriptionst.title("DeepSeek Chatbot")st.markdown("""Created by [ruslanmv.com](https://ruslanmv.com/)This is a demo of different DeepSeek models. Select a model, type your message, and click "Submit".You can also adjust optional parameters like system message, max new tokens, temperature, and top-p.""")# Sidebar for model selection and parameterswith st.sidebar:st.header("Options")model_choice = st.radio("Choose a Model",options=list(MODELS.keys()),index=0)st.header("Optional Parameters")system_message = st.text_area("System Message",value="You are a friendly Chatbot created by ruslanmv.com",height=100)max_new_tokens = st.slider("Max New Tokens",min_value=1,max_value=4000,value=200)temperature = st.slider("Temperature",min_value=0.10,max_value=4.00,value=0.70)top_p = st.slider("Top-p (nucleus sampling)",min_value=0.10,max_value=1.00,value=0.90)# Initialize chat historyif "chat_history" not in st.session_state:st.session_state.chat_history = []# Display chat historyfor user_msg, assistant_msg in st.session_state.chat_history:with st.chat_message("user"):1 unmodified linewith st.chat_message("assistant"):st.write(assistant_msg)# Input box for user messageuser_input = st.chat_input("Type your message here...")# Handle user inputif user_input:# Add user message to chat historyst.session_state.chat_history = chatbot(user_input,st.session_state.chat_history,model_choice,system_message,2 unmodified linestop_p)# Rerun to update the chat displayst.rerun()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970711 unmodified line7374757677787980818283848586871 unmodified line89909192939495969798991001011022 unmodified lines105106107108109import streamlit as stfrom models import demo # Import the demo object from models.py# --- Streamlit App Configuration ---st.set_page_config(page_title="DeepSeek Chatbot",page_icon="🤖",layout="wide")# --- App Title and Description ---st.title("DeepSeek Chatbot")st.markdown("""Created by [ruslanmv.com](https://ruslanmv.com/)This is a demo of different DeepSeek models. Select a model, type your message, and click "Submit".You can also adjust optional parameters like system message, max new tokens, temperature, and top-p.""")# --- Sidebar for Model Selection and Parameters ---with st.sidebar:st.header("Options")model_choice = st.radio("Choose a Model",options=["DeepSeek-R1-Distill-Qwen-32B", "DeepSeek-R1", "DeepSeek-R1-Zero"],index=1 # Default to "DeepSeek-R1")with st.expander("Optional Parameters", expanded=False):system_message = st.text_area("System Message",value="You are a friendly Chatbot created by ruslanmv.com",height=100)max_new_tokens = st.slider("Max New Tokens",min_value=1,max_value=4000,value=200)temperature = st.slider("Temperature",min_value=0.10,max_value=4.00,value=0.70)top_p = st.slider("Top-p (nucleus sampling)",min_value=0.10,max_value=1.00,value=0.90)# --- Chatbot Function ---def chatbot(input_text, history, model_choice, system_message, max_new_tokens, temperature, top_p):# Create payload for the modelpayload = {"messages": [{"role": "user", "content": input_text}],"system": system_message,"max_tokens": max_new_tokens,"temperature": temperature,"top_p": top_p}# Run inference using the selected modeltry:response = demo(payload) # Use the demo object directlyif isinstance(response, dict) and "choices" in response:assistant_response = response["choices"][0]["message"]["content"]else:assistant_response = "Unexpected model response format."except Exception as e:1 unmodified line# Append user and assistant messages to historyhistory.append((input_text, assistant_response))return history# --- Chat History Management ---if "chat_history" not in st.session_state:st.session_state.chat_history = []# --- Chat Interface ---st.header("Chat with DeepSeek")# Display chat historyfor user_msg, assistant_msg in st.session_state.chat_history:with st.chat_message("user"):1 unmodified linewith st.chat_message("assistant"):st.write(assistant_msg)# Input for new messageinput_text = st.chat_input("Type your message here...")# Handle new message submissionif input_text:# Update chat historyst.session_state.chat_history = chatbot(input_text,st.session_state.chat_history,model_choice,system_message,2 unmodified linestop_p)# Rerun the app to display the updated chat historyst.rerun()
app.py+68-90