Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -24,10 +24,15 @@ if not os.path.exists(MODEL_PATH):
|
|
24 |
st.error(f"π¨ Model download failed: {e}")
|
25 |
st.stop()
|
26 |
|
27 |
-
# β
Load model
|
28 |
try:
|
29 |
if "model" not in st.session_state:
|
30 |
-
st.session_state["model"] = Llama(
|
|
|
|
|
|
|
|
|
|
|
31 |
st.write("β
Model loaded successfully!")
|
32 |
except Exception as e:
|
33 |
st.error(f"π¨ Error loading model: {e}")
|
@@ -55,30 +60,32 @@ if st.button("Send") and user_input:
|
|
55 |
# Add user input to chat history
|
56 |
st.session_state["messages"].append(("user", user_input))
|
57 |
st.chat_message("user").write(user_input)
|
58 |
-
|
59 |
# β
Format messages using Phi-3 chat template
|
60 |
formatted_messages = [
|
61 |
{"role": "system", "content": "You are an AI assistant. Provide clear and concise answers."},
|
62 |
{"role": "user", "content": user_input}
|
63 |
]
|
64 |
-
|
65 |
-
#
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
82 |
|
83 |
|
84 |
|
|
|
24 |
st.error(f"π¨ Model download failed: {e}")
|
25 |
st.stop()
|
26 |
|
27 |
+
# β
Load optimized model
|
28 |
try:
|
29 |
if "model" not in st.session_state:
|
30 |
+
st.session_state["model"] = Llama(
|
31 |
+
model_path=MODEL_PATH,
|
32 |
+
n_ctx=1024, # Reduce context window for faster inference
|
33 |
+
n_threads=2, # Match available CPU cores (2 vCPUs)
|
34 |
+
numa=True # Enable NUMA optimization
|
35 |
+
)
|
36 |
st.write("β
Model loaded successfully!")
|
37 |
except Exception as e:
|
38 |
st.error(f"π¨ Error loading model: {e}")
|
|
|
60 |
# Add user input to chat history
|
61 |
st.session_state["messages"].append(("user", user_input))
|
62 |
st.chat_message("user").write(user_input)
|
63 |
+
|
64 |
# β
Format messages using Phi-3 chat template
|
65 |
formatted_messages = [
|
66 |
{"role": "system", "content": "You are an AI assistant. Provide clear and concise answers."},
|
67 |
{"role": "user", "content": user_input}
|
68 |
]
|
69 |
+
|
70 |
+
# β
Streamed response for faster user experience
|
71 |
+
response_data = st.session_state["model"].create_chat_completion(
|
72 |
+
messages=formatted_messages,
|
73 |
+
max_tokens=256, temperature=0.7, top_p=0.9,
|
74 |
+
stream=True # β
Enables real-time streaming
|
75 |
+
)
|
76 |
+
|
77 |
+
response_text = ""
|
78 |
+
response_container = st.empty() # Placeholder for live updates
|
79 |
+
|
80 |
+
for chunk in response_data:
|
81 |
+
if "choices" in chunk and len(chunk["choices"]) > 0:
|
82 |
+
choice = chunk["choices"][0]
|
83 |
+
if "message" in choice:
|
84 |
+
response_text += choice["message"]["content"]
|
85 |
+
response_container.markdown(f"**AI:** {response_text}")
|
86 |
+
if choice.get("finish_reason") == "stop":
|
87 |
+
break
|
88 |
+
|
89 |
|
90 |
|
91 |
|