-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
62 lines (49 loc) · 1.85 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import streamlit as st
import ollama
import time
def askllm(message, model='llama3.2'):
try:
response = ollama.chat(model=model, messages=[{'role': 'user', 'content': message}])
return response['message']['content']
except Exception as e:
error_message = str(e).lower()
return f"An error occurred with model '{model}': {str(e)}"
def stream_response(messages):
lines = messages.split('\n')
for line in lines:
words = line.split()
for word in words:
yield word + " "
time.sleep(0.1)
yield "\n"
def show_messages():
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
def main():
st.set_page_config(
page_title="AI Chatbot",
page_icon="favicon.png",
initial_sidebar_state="collapsed",
menu_items=None
)
st.header(":blue[AI Chatbot]")
user_input = st.chat_input("Enter your prompt here", key="1")
if 'messages' not in st.session_state:
intro_line = f"""Greetings! Chat securely with your local AI assistant. How can I help you today?"""
st.caption(intro_line)
st.session_state['messages'] = []
show_messages()
if user_input:
with st.chat_message("user"):
st.write(user_input)
st.session_state.messages.append({"role": "user", "content": user_input})
messages = "\n".join(msg["content"] for msg in st.session_state.messages)
response = askllm(messages)
st.session_state.messages.append({"role": "assistant", "content": response})
with st.chat_message("assistant"):
st.write_stream(stream_response(response))
elif st.session_state['messages'] is None:
st.info("Enter a prompt to start the conversation")
if __name__ == "__main__":
main()