-
Notifications
You must be signed in to change notification settings - Fork 11
/
chapter_03.py
42 lines (34 loc) · 1.36 KB
/
chapter_03.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
import streamlit as st
from langchain.chat_models import ChatOpenAI
from langchain.schema import (SystemMessage, HumanMessage, AIMessage)
def main():
llm = ChatOpenAI(temperature=0)
st.set_page_config(
page_title="My Great ChatGPT",
page_icon="🤗"
)
st.header("My Great ChatGPT 🤗")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = [
SystemMessage(content="You are a helpful assistant.")
]
# Monitor user input
if user_input := st.chat_input("Input your question here:"):
st.session_state.messages.append(HumanMessage(content=user_input))
with st.spinner("ChatGPT is typing ..."):
response = llm(st.session_state.messages)
st.session_state.messages.append(AIMessage(content=response.content))
# Display chat history
messages = st.session_state.get('messages', [])
for message in messages:
if isinstance(message, AIMessage):
with st.chat_message('assistant'):
st.markdown(message.content)
elif isinstance(message, HumanMessage):
with st.chat_message('user'):
st.markdown(message.content)
else: # isinstance(message, SystemMessage):
st.write(f"System message: {message.content}")
if __name__ == '__main__':
main()