ll7098ll commited on
Commit
6283c2d
·
verified ·
1 Parent(s): b1f70de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -37
app.py CHANGED
@@ -1,9 +1,11 @@
1
  import os
 
 
2
  import streamlit as st
 
3
  from streamlit_chat import message
4
- import google.generativeai as genai
5
 
6
- # Gemini API 설정
7
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
8
 
9
  # 모델 설정
@@ -14,43 +16,90 @@ generation_config = {
14
  "max_output_tokens": 8192,
15
  "response_mime_type": "text/plain",
16
  }
 
 
 
 
 
 
17
 
18
- model = genai.GenerativeModel(
19
- model_name="learnlm-1.5-pro-experimental",
20
- generation_config=generation_config,
21
- system_instruction="""교사가 학습 목표를 입력하면, 학생들이 학습 목표에 도달할 수 있게 질문을 계속 해줘,
 
 
 
 
 
 
 
22
  학생들은 네 질문에 답을 할 것이야. 그러면 바로 답을 제시하지 말고 질문형태로 피드백을 해줘.
23
- 질문을 통해서 학생들이 스스로 학습 목표를 도달할 수 있도록 도와줘.""",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  )
25
 
26
- # Streamlit 세션 상태 초기화
 
 
 
 
27
  if "chat_session" not in st.session_state:
28
- st.session_state.chat_session = model.start_chat(history=[])
29
- if "messages" not in st.session_state:
30
- st.session_state.messages = []
31
-
32
- # 웹앱 설정
33
- st.title("AI 학습 튜터")
34
-
35
- # 학습 목표 입력
36
- if "learning_goal" not in st.session_state:
37
- st.session_state.learning_goal = st.text_input("학습 목표를 입력해주세요:")
38
- if st.session_state.learning_goal:
39
- st.session_state.chat_session.send_message(st.session_state.learning_goal)
40
- response = st.session_state.chat_session.last
41
- st.session_state.messages.append({"role": "ai", "content": response.text})
42
-
43
- # 채팅 메시지 표시
44
- if st.session_state.learning_goal:
45
- for i, msg in enumerate(st.session_state.messages):
46
- message(msg["content"], is_user=msg["role"] == "user", key=str(i))
47
-
48
- # 사용자 입력
49
- if prompt := st.chat_input("질문을 입력해주세요:"):
50
- st.session_state.messages.append({"role": "user", "content": prompt})
51
- message(prompt, is_user=True, key=str(len(st.session_state.messages)))
52
-
53
- # Gemini API를 통해 답변 생성
54
- response = st.session_state.chat_session.send_message(prompt)
55
- st.session_state.messages.append({"role": "ai", "content": response.text})
56
- message(response.text, is_user=False, key=str(len(st.session_state.messages)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import time
3
+ import google.generativeai as genai
4
  import streamlit as st
5
+ import re
6
  from streamlit_chat import message
 
7
 
8
+ # Google Generative AI API 설정
9
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
10
 
11
  # 모델 설정
 
16
  "max_output_tokens": 8192,
17
  "response_mime_type": "text/plain",
18
  }
19
+ safety_settings = [
20
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
21
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
22
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
23
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
24
+ ]
25
 
26
+ # 전역 변수로 chat_session 초기화
27
+ chat_session = None
28
+
29
+ def start_new_chat_session():
30
+ global chat_session
31
+ chat_session = genai.GenerativeModel(
32
+ model_name="learnlm-1.5-pro-experimental",
33
+ safety_settings=safety_settings,
34
+ generation_config=generation_config,
35
+ system_instruction="""
36
+ 교사가 학습 목표를 입력하면, 학생들이 학습 목표에 도달할 수 있게 질문을 계속 해줘,
37
  학생들은 네 질문에 답을 할 것이야. 그러면 바로 답을 제시하지 말고 질문형태로 피드백을 해줘.
38
+ 질문을 통해서 학생들이 스스로 학습 목표를 도달할 수 있도록 도와줘.
39
+ """,
40
+ ).start_chat(history=[])
41
+
42
+ # 초기 세션 시작
43
+ start_new_chat_session()
44
+
45
+ # Streamlit 앱 설정
46
+ st.set_page_config(page_title="질문하는 AI 선생님", layout="centered")
47
+
48
+ st.markdown(
49
+ """
50
+ <div style='font-size: 30px; font-weight: bold; text-align: center;'>질문하는 AI 선생님</div>
51
+ <div style='text-align: center; margin-bottom: 20px;'>학습주제를 입력하면, AI가 끊임 없는 질문을 통해 스스로 학습하게 도와줍니다.</div>
52
+ """,
53
+ unsafe_allow_html=True
54
  )
55
 
56
+ # 채팅 히스토리 관리
57
+ if "history" not in st.session_state:
58
+ st.session_state.history = []
59
+
60
+ # 채팅 세션 초기화
61
  if "chat_session" not in st.session_state:
62
+ st.session_state.chat_session = chat_session
63
+
64
+ # 사용자 입력 받기
65
+ user_input = st.text_input(
66
+ "입력", key="user_input", placeholder="여기에 학습 표나 질문을 입력하세요...",
67
+ help="학습 목표를 입력하거나 학습하고자 하는 주제에 대한 질문을 입력하세요."
68
+ )
69
+
70
+ def respond(user_input):
71
+ st.session_state.history.append({"user": user_input, "ai": ""})
72
+ try:
73
+ response = st.session_state.chat_session.send_message(user_input, stream=True)
74
+ full_text = ""
75
+
76
+ # 스트리밍 응답 처리
77
+ for chunk in response:
78
+ chunk_text = chunk.text
79
+
80
+ # 단어 단위로 분리하여 실시간 출력
81
+ for word in chunk_text.split():
82
+ full_text += word + " "
83
+
84
+ # 히스토리 최신 항목 업데이트
85
+ st.session_state.history[-1]["ai"] = full_text
86
+ time.sleep(0.05) # 출력 속도 조절
87
+
88
+ except Exception as e:
89
+ st.session_state.history[-1]["ai"] = f"에러 발생: {str(e)}"
90
+
91
+ # 응답 생성 및 출력
92
+ if user_input:
93
+ respond(user_input)
94
+
95
+ # 채팅 메시지 출력
96
+ for chat in st.session_state.history:
97
+ if "user" in chat:
98
+ message(chat["user"], is_user=True, key=f"user_{chat['user']}")
99
+ if "ai" in chat:
100
+ message(chat["ai"], is_user=False, key=f"ai_{chat['ai']}")
101
+
102
+ # 초기화 버튼 클릭 시
103
+ if st.button("초기화"):
104
+ start_new_chat_session()
105
+ st.session_state.history = []