-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot2.py
49 lines (41 loc) · 1.61 KB
/
chatbot2.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
import streamlit as st
from langchain_openai import ChatOpenAI
import os
# Streamlit UI 설정
st.set_page_config(page_title="ChatOpenAI Demo", page_icon=":robot:")
st.header("영주의 챗봇")
with st.sidebar:
openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
if openai_api_key:
os.environ["OPENAI_API_KEY"] = openai_api_key
else:
st.info("Please add your OpenAI API key to continue.")
st.stop()
# ChatOpenAI 모델 초기화
chat = ChatOpenAI(temperature=0)
# 세션 상태 초기화
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "system", "content": "You are a helpful assistant."}
]
# 대화 히스토리 표시
for message in st.session_state.messages:
if message["role"] != "system":
with st.chat_message(message["role"]):
st.markdown(message["content"])
# 사용자 입력 처리
prompt = st.chat_input("무엇을 도와드릴까요?")
if prompt:
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
message_placeholder = st.empty()
full_response = ""
for response in chat.stream(st.session_state.messages):
full_response += (response.content or "")
message_placeholder.markdown(full_response + "▌")
message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})
# 스크롤을 최하단으로 이동
st.empty()