ll7098ll commited on
Commit
beb811e
·
verified ·
1 Parent(s): 1e16f85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -51
app.py CHANGED
@@ -2,37 +2,20 @@ import os
2
  import time
3
  import openai
4
  import streamlit as st
 
5
  from streamlit_chat import message
6
 
7
  # OpenAI API 설정
8
  openai_api_key = os.getenv("OPENAI_API_KEY")
9
  openai.api_key = openai_api_key
10
 
11
- def openai_chat(text):
12
- try:
13
- response = openai.ChatCompletion.create(
14
- model="gpt-4o",
15
- messages=[
16
- {"role": "system", "content": "초등학교 6학년 수준 범위 내에서 학생의 질문에 친절하게 답하는 교사 역할, 설명은 구체적인 예시를 들어서, 어려운 단어는 별도로 설명해줘. 설명글의 분량은 1000~2000자 정도로 해줘."},
17
- {"role": "user", "content": text}
18
- ],
19
- temperature=1,
20
- max_tokens=2000,
21
- top_p=0.9,
22
- frequency_penalty=0,
23
- presence_penalty=0
24
- )
25
- return response.choices[0].message["content"]
26
- except Exception as e:
27
- return f"에러 발생: {str(e)}"
28
-
29
  # Streamlit 앱 설정
30
- st.set_page_config(page_title="친절한 AI 선생님(GPT-4)", layout="centered")
31
 
32
  st.markdown(
33
  """
34
- <div style='font-size: 30px; font-weight: bold; text-align: center;'>친절한 AI 선생님(GPT-4)</div>
35
- <div style='text-align: center; margin-bottom: 20px;'>궁금한 것은 무엇이든 물어보세요. AI 선생님이 친절하게 알려줄 거예요!</div>
36
  """,
37
  unsafe_allow_html=True
38
  )
@@ -41,45 +24,57 @@ st.markdown(
41
  if "history" not in st.session_state:
42
  st.session_state.history = []
43
 
44
- # 채팅 메시지 출력 영역
45
  chat_container = st.container()
 
46
 
47
- def respond(user_input):
48
- if user_input:
49
- st.session_state.history.append({"user": user_input, "ai": ""})
50
- response = openai_chat(user_input)
51
- st.session_state.history[-1]["ai"] = response
52
-
53
- # 사용자 입력 처리 및 응답 생성
54
- with st.container():
55
- # 채팅창 출력
56
- with chat_container:
57
- chat_scrollable = st.empty()
58
- chat_content = ""
59
- for chat in st.session_state.history:
60
- if "user" in chat:
61
- chat_content += f"<div style='text-align: right; margin: 5px 0;'><b>사용자:</b> {chat['user']}</div>"
62
- if "ai" in chat:
63
- chat_content += f"<div style='text-align: left; margin: 5px 0;'><b>AI:</b> {chat['ai']}</div>"
64
- chat_scrollable.markdown(
65
- f"""
66
- <div style='height: 400px; overflow-y: auto; padding: 10px; border: 1px solid #ccc;'>{chat_content}</div>
67
- """,
68
- unsafe_allow_html=True
69
- )
70
 
71
- # 사용자 입력 받기
 
 
72
  user_input = st.text_input(
73
  "질문", key="user_input", placeholder="질문을 넣어주세요.",
74
  help="AI 선생님에게 궁금한 것을 물어보세요."
75
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- # 응답 생성 및 출력
78
- if user_input:
79
- respond(user_input)
80
- st.experimental_rerun()
81
 
82
  # 초기화 버튼 클릭 시
83
- if st.button("초기화"):
84
  st.session_state.history = []
85
  st.experimental_rerun()
 
2
  import time
3
  import openai
4
  import streamlit as st
5
+ import re
6
  from streamlit_chat import message
7
 
8
  # OpenAI API 설정
9
  openai_api_key = os.getenv("OPENAI_API_KEY")
10
  openai.api_key = openai_api_key
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  # Streamlit 앱 설정
13
+ st.set_page_config(page_title="친절한 AI 선생님(GPT-4)", layout="wide")
14
 
15
  st.markdown(
16
  """
17
+ <div style='font-size: 30px; font-weight: bold; text-align: center; margin-bottom: 10px;'>친절한 AI 선생님(GPT-4)</div>
18
+ <div style='text-align: center; margin-bottom: 20px; color: #6c757d;'>궁금한 것은 무엇이든 물어보세요. AI 선생님이 친절하게 알려줄 거예요!</div>
19
  """,
20
  unsafe_allow_html=True
21
  )
 
24
  if "history" not in st.session_state:
25
  st.session_state.history = []
26
 
27
+ # 채팅 메시지 출력 - 채팅창이 위에 있도록 설정
28
  chat_container = st.container()
29
+ input_container = st.container()
30
 
31
+ with chat_container:
32
+ st.markdown("""<div style='height: 400px; overflow-y: auto; border: 1px solid #e1e1e1; padding: 10px; border-radius: 10px; background-color: #f9f9f9;'>""", unsafe_allow_html=True)
33
+ for chat in st.session_state.history:
34
+ if "user" in chat:
35
+ message(chat["user"], is_user=True, key=f"user_{chat['user']}")
36
+ if "ai" in chat:
37
+ message(chat["ai"], is_user=False, key=f"ai_{chat['ai']}")
38
+ st.markdown("""</div>""", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # 사용자 입력 받기 - 입력창이 아래에 있도록 설정
41
+ with input_container:
42
+ st.markdown("""<div style='margin-top: 20px;'>""", unsafe_allow_html=True)
43
  user_input = st.text_input(
44
  "질문", key="user_input", placeholder="질문을 넣어주세요.",
45
  help="AI 선생님에게 궁금한 것을 물어보세요."
46
  )
47
+ st.markdown("""</div>""", unsafe_allow_html=True)
48
+
49
+ def openai_chat(text):
50
+ try:
51
+ response = openai.ChatCompletion.create(
52
+ model="gpt-4o",
53
+ messages=[
54
+ {"role": "system", "content": "초등학교 6학년 수준 범위 내에서 학생의 질문에 친절하게 답하는 교사 역할, 설명은 구체적인 예시를 들어서, 어려운 단어는 별도로 설명해줘. 설명글의 분량은 1000~2000자 정도로 해줘."},
55
+ {"role": "user", "content": text}
56
+ ],
57
+ temperature=1,
58
+ max_tokens=2000,
59
+ top_p=0.9,
60
+ frequency_penalty=0,
61
+ presence_penalty=0
62
+ )
63
+ return response.choices[0].message["content"]
64
+ except Exception as e:
65
+ return f"에러 발생: {str(e)}"
66
+
67
+ def respond(user_input):
68
+ st.session_state.history.append({"user": user_input, "ai": ""})
69
+ response = openai_chat(user_input)
70
+ st.session_state.history[-1]["ai"] = response
71
 
72
+ # 응답 생성 및 출력
73
+ if user_input:
74
+ respond(user_input)
75
+ st.experimental_rerun()
76
 
77
  # 초기화 버튼 클릭 시
78
+ if st.button("초기화", type="primary", use_container_width=True):
79
  st.session_state.history = []
80
  st.experimental_rerun()