Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import streamlit as stfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadimport torch# App Configurationst.set_page_config(page_title="Klove AI ChatBox", page_icon="⚡")# 1. Load Qwen3 (Cached for efficiency)@st.cache_resourcedef load_qwen3():model_id = "Qwen/Qwen3-1.7B"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id,torch_dtype="auto",device_map="auto")return tokenizer, modeltokenizer, model = load_qwen3()# 2. System Prompt Selection (Main UI, No Sidebar)st.title("⚡ Klove AI ChatBox")system_options = {"General Assistant": "You are a helpful and concise assistant.","Python Expert": "You are an expert Python developer. Provide clean, efficient code with brief explanations.","Creative Storyteller": "You are a creative writer. Use vivid imagery and engaging narrative styles."}# Horizontal layout for the selector and a clear buttoncol1, col2 = st.columns([3, 1])with col1:selected_role = st.selectbox("Choose AI Personality:", list(system_options.keys()))with col2:if st.button("Clear History", use_container_width=True):st.session_state.messages = []st.rerun()system_prompt = system_options[selected_role]# 3. Setup Session Stateif "messages" not in st.session_state:st.session_state.messages = []# Display Chat Historyfor message in st.session_state.messages:if message["role"] != "system": # Hide system prompt from UIwith st.chat_message(message["role"]):st.markdown(message["content"])# 4. Chat Input & Streamingif prompt := st.chat_input("Message Qwen3..."):# Insert system prompt if history is emptyif len(st.session_state.messages) == 0:st.session_state.messages.append({"role": "system", "content": system_prompt})# Add User Messagest.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)# Generate Assistant Responsewith st.chat_message("assistant"):# Prepare input with chat templateinput_ids = tokenizer.apply_chat_template(st.session_state.messages,tokenize=True,add_generation_prompt=True,return_tensors="pt").to(model.device)streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)generation_kwargs = dict(input_ids=input_ids,streamer=streamer,max_new_tokens=1024,temperature=0.7)# Threaded generation for real-time streamingthread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()# Stream the outputfull_response = st.write_stream(streamer)st.session_state.messages.append({"role": "assistant", "content": full_response})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import streamlit as stfrom llama_cpp import Llamaimport os# Page configurationst.set_page_config(page_title="Qwen3 GGUF Chat", page_icon="🤖")st.title("🤖 Qwen3-1.7B (8-bit GGUF)")# 1. Load Model (Cached to prevent reloading on every interaction)@st.cache_resourcedef load_qwen_gguf():# repo_id and filename as per your requestrepo_id = "Qwen/Qwen3-1.7B-GGUF"filename = "Qwen3-1.7B-Q8_0.gguf"# from_pretrained automatically downloads and caches the .gguf filereturn Llama.from_pretrained(repo_id=repo_id,filename=filename,n_ctx=4096, # Context window (Qwen3 supports up to 32k, but 4k is safer for free RAM)n_threads=2, # Match the 2 vCPUs on HF Free Tierverbose=False # Reduces log clutter)llm = load_qwen_gguf()# 2. Chat History Initializationif "messages" not in st.session_state:st.session_state.messages = [{"role": "system", "content": "You are a helpful AI assistant. Answer concisely and accurately."}]# Display existing chat messagesfor message in st.session_state.messages:if message["role"] != "system":with st.chat_message(message["role"]):st.markdown(message["content"])# 3. Chat Logic & Streamingif prompt := st.chat_input("Ask Qwen3..."):# Add user message to historyst.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)# Generate assistant responsewith st.chat_message("assistant"):# Use create_chat_completion for OpenAI-style streamingstream = llm.create_chat_completion(messages=st.session_state.messages,stream=True,max_tokens=1024,temperature=0.7,top_p=0.8,repeat_penalty=1.1)# Generator for Streamlit streamingdef stream_response():for chunk in stream:delta = chunk['choices'][0]['delta']if 'content' in delta:yield delta['content']# write_stream handles the "typewriter" effect automaticallyfull_response = st.write_stream(stream_response())# Save the assistant's final answerst.session_state.messages.append({"role": "assistant", "content": full_response})
app.py+47-68