davidfearne commited on
Commit
a42d4ec
·
verified ·
1 Parent(s): 250bf87

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -131
app.py CHANGED
@@ -1,131 +1,130 @@
1
- import streamlit as st
2
- from langchain.chat_models import ChatOpenAI
3
- from langchain_openai import AzureChatOpenAI
4
- from langchain.schema import AIMessage, HumanMessage, SystemMessage
5
- from langchain.callbacks.base import BaseCallbackHandler
6
- from typing import Any
7
- from prompts import dental_system_message, welcome_message, update
8
-
9
- OPENAI_API_KEY = "86b631a9c0294e9698e327c59ff5ac2c"
10
- OPENAI_API_TYPE = "azure"
11
- OPENAI_API_BASE = "https://davidfearn-gpt4.openai.azure.com"
12
- OPENAI_API_VERSION = "2024-08-01-preview"
13
- OPENAI_MODEL = "gpt-4o"
14
-
15
-
16
- # --- Page Config ---
17
- st.set_page_config(page_title="Home Dental Expert", page_icon="🦷")
18
- st.subheader("🦷 Home Dental Expert")
19
-
20
- haleon_system_message = SystemMessage(content=dental_system_message)
21
-
22
- from langchain.schema import BaseMessage
23
-
24
- def get_llm_response_with_context(messages: list[BaseMessage], stream_container):
25
-
26
-
27
- llm = AzureChatOpenAI(
28
-
29
- openai_api_version=OPENAI_API_VERSION,
30
- openai_api_key=OPENAI_API_KEY,
31
- azure_endpoint=OPENAI_API_BASE,
32
- openai_api_type=OPENAI_API_TYPE,
33
- deployment_name=OPENAI_MODEL,
34
- temperature=0.7,
35
- streaming=True,
36
- callbacks=[StreamlitCallbackHandler(stream_container)],
37
- )
38
-
39
- full_convo = [haleon_system_message] + messages
40
- assert all(isinstance(m, BaseMessage) for m in full_convo), "One or more messages is not a BaseMessage type"
41
- return llm(full_convo)
42
-
43
- # --- Streaming Output Handler ---
44
- class StreamlitCallbackHandler(BaseCallbackHandler):
45
- def __init__(self, container):
46
- self.container = container
47
- self.text = ""
48
-
49
- def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
50
- self.text += token
51
- self.container.markdown(self.text + "▌")
52
-
53
- # --- Session State Init ---
54
- if "messages" not in st.session_state:
55
- st.session_state.messages = []
56
-
57
- if "greeted" not in st.session_state:
58
- st.session_state.greeted = False
59
-
60
- if "welcome_response" not in st.session_state:
61
- st.session_state.welcome_response = None
62
-
63
- # --- Display welcome message at top if it exists ---
64
- if st.session_state.welcome_response:
65
- with st.chat_message("assistant"):
66
- st.markdown(st.session_state.welcome_response)
67
-
68
- from datetime import datetime
69
-
70
- def get_time_of_day():
71
- """Returns 'morning' if before 12pm, 'evening' if after 5pm, otherwise 'afternoon'."""
72
- now = datetime.now().hour
73
- if now < 12:
74
- return "morning"
75
- elif now < 17:
76
- return "afternoon"
77
- else:
78
- return "evening"
79
-
80
-
81
-
82
- # --- Stream the welcome message only once ---
83
- if not st.session_state.greeted:
84
- with st.chat_message("assistant"):
85
- stream_container = st.empty()
86
-
87
- time_of_day = get_time_of_day()
88
- latest_update = update
89
-
90
- llm = AzureChatOpenAI(
91
- openai_api_version=OPENAI_API_VERSION,
92
- openai_api_key=OPENAI_API_KEY,
93
- azure_endpoint=OPENAI_API_BASE,
94
- openai_api_type=OPENAI_API_TYPE,
95
- deployment_name=OPENAI_MODEL,
96
- temperature=0.7,
97
- streaming=True,
98
- callbacks=[StreamlitCallbackHandler(stream_container)]
99
- )
100
-
101
- messages = [
102
- haleon_system_message,
103
- HumanMessage(content=f"Give a warm, friendly greeting specific to the time of day being the {time_of_day} as if the user just opened the daily dental journaling app. They have used this app before, so you can assume they are familiar with it. This app is designed to be specically before or after they brush their teeth. Also comment on the latest update as this will be the focus for todays discussion: {latest_update}. Ask a follow up question. DON'T USE #Hash #Tags. Feel free to use emojis."),
104
- ]
105
-
106
- response = llm(messages)
107
-
108
- # Save it to show above later
109
- st.session_state.welcome_response = response.content
110
- st.session_state.greeted = True
111
-
112
- # --- Chat History Display ---
113
- for msg in st.session_state.messages:
114
- with st.chat_message("user" if isinstance(msg, HumanMessage) else "assistant"):
115
- st.markdown(msg.content)
116
-
117
- # --- Chat Input ---
118
- user_input = st.chat_input("Type your message...")
119
-
120
- # --- On User Message ---
121
- if user_input:
122
- st.chat_message("user").markdown(user_input)
123
- st.session_state.messages.append(HumanMessage(content=user_input))
124
-
125
- with st.chat_message("assistant"):
126
- stream_container = st.empty()
127
-
128
- response = get_llm_response_with_context(st.session_state.messages, stream_container)
129
-
130
- st.session_state.messages.append(AIMessage(content=response.content))
131
- stream_container.markdown(response.content)
 
1
+ import streamlit as st
2
+ from langchain_openai import AzureChatOpenAI
3
+ from langchain.schema import AIMessage, HumanMessage, SystemMessage
4
+ from langchain.callbacks.base import BaseCallbackHandler
5
+ from typing import Any
6
+ from prompts import dental_system_message, welcome_message, update
7
+
8
+ OPENAI_API_KEY = "86b631a9c0294e9698e327c59ff5ac2c"
9
+ OPENAI_API_TYPE = "azure"
10
+ OPENAI_API_BASE = "https://davidfearn-gpt4.openai.azure.com"
11
+ OPENAI_API_VERSION = "2024-08-01-preview"
12
+ OPENAI_MODEL = "gpt-4o"
13
+
14
+
15
+ # --- Page Config ---
16
+ st.set_page_config(page_title="Home Dental Expert", page_icon="🦷")
17
+ st.subheader("🦷 Home Dental Expert")
18
+
19
+ haleon_system_message = SystemMessage(content=dental_system_message)
20
+
21
+ from langchain.schema import BaseMessage
22
+
23
+ def get_llm_response_with_context(messages: list[BaseMessage], stream_container):
24
+
25
+
26
+ llm = AzureChatOpenAI(
27
+
28
+ openai_api_version=OPENAI_API_VERSION,
29
+ openai_api_key=OPENAI_API_KEY,
30
+ azure_endpoint=OPENAI_API_BASE,
31
+ openai_api_type=OPENAI_API_TYPE,
32
+ deployment_name=OPENAI_MODEL,
33
+ temperature=0.7,
34
+ streaming=True,
35
+ callbacks=[StreamlitCallbackHandler(stream_container)],
36
+ )
37
+
38
+ full_convo = [haleon_system_message] + messages
39
+ assert all(isinstance(m, BaseMessage) for m in full_convo), "One or more messages is not a BaseMessage type"
40
+ return llm(full_convo)
41
+
42
+ # --- Streaming Output Handler ---
43
+ class StreamlitCallbackHandler(BaseCallbackHandler):
44
+ def __init__(self, container):
45
+ self.container = container
46
+ self.text = ""
47
+
48
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
49
+ self.text += token
50
+ self.container.markdown(self.text + "▌")
51
+
52
+ # --- Session State Init ---
53
+ if "messages" not in st.session_state:
54
+ st.session_state.messages = []
55
+
56
+ if "greeted" not in st.session_state:
57
+ st.session_state.greeted = False
58
+
59
+ if "welcome_response" not in st.session_state:
60
+ st.session_state.welcome_response = None
61
+
62
+ # --- Display welcome message at top if it exists ---
63
+ if st.session_state.welcome_response:
64
+ with st.chat_message("assistant"):
65
+ st.markdown(st.session_state.welcome_response)
66
+
67
+ from datetime import datetime
68
+
69
+ def get_time_of_day():
70
+ """Returns 'morning' if before 12pm, 'evening' if after 5pm, otherwise 'afternoon'."""
71
+ now = datetime.now().hour
72
+ if now < 12:
73
+ return "morning"
74
+ elif now < 17:
75
+ return "afternoon"
76
+ else:
77
+ return "evening"
78
+
79
+
80
+
81
+ # --- Stream the welcome message only once ---
82
+ if not st.session_state.greeted:
83
+ with st.chat_message("assistant"):
84
+ stream_container = st.empty()
85
+
86
+ time_of_day = get_time_of_day()
87
+ latest_update = update
88
+
89
+ llm = AzureChatOpenAI(
90
+ openai_api_version=OPENAI_API_VERSION,
91
+ openai_api_key=OPENAI_API_KEY,
92
+ azure_endpoint=OPENAI_API_BASE,
93
+ openai_api_type=OPENAI_API_TYPE,
94
+ deployment_name=OPENAI_MODEL,
95
+ temperature=0.7,
96
+ streaming=True,
97
+ callbacks=[StreamlitCallbackHandler(stream_container)]
98
+ )
99
+
100
+ messages = [
101
+ haleon_system_message,
102
+ HumanMessage(content=f"Give a warm, friendly greeting specific to the time of day being the {time_of_day} as if the user just opened the daily dental journaling app. They have used this app before, so you can assume they are familiar with it. This app is designed to be specically before or after they brush their teeth. Also comment on the latest update as this will be the focus for todays discussion: {latest_update}. Ask a follow up question. DON'T USE #Hash #Tags. Feel free to use emojis."),
103
+ ]
104
+
105
+ response = llm(messages)
106
+
107
+ # Save it to show above later
108
+ st.session_state.welcome_response = response.content
109
+ st.session_state.greeted = True
110
+
111
+ # --- Chat History Display ---
112
+ for msg in st.session_state.messages:
113
+ with st.chat_message("user" if isinstance(msg, HumanMessage) else "assistant"):
114
+ st.markdown(msg.content)
115
+
116
+ # --- Chat Input ---
117
+ user_input = st.chat_input("Type your message...")
118
+
119
+ # --- On User Message ---
120
+ if user_input:
121
+ st.chat_message("user").markdown(user_input)
122
+ st.session_state.messages.append(HumanMessage(content=user_input))
123
+
124
+ with st.chat_message("assistant"):
125
+ stream_container = st.empty()
126
+
127
+ response = get_llm_response_with_context(st.session_state.messages, stream_container)
128
+
129
+ st.session_state.messages.append(AIMessage(content=response.content))
130
+ stream_container.markdown(response.content)