ll7098ll commited on
Commit
e90cb1f
·
verified ·
1 Parent(s): c8be43f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -36
app.py CHANGED
@@ -1,49 +1,69 @@
1
- # -*- coding: utf-8 -*-
2
- """Untitled1.ipynb
3
- Automatically generated by Colab.
4
- Original file is located at
5
- https://colab.research.google.com/drive/1huUmrgIbG1wwEKxs3zsCdRNir_IY5ICf
6
- """
7
-
8
  import os
9
-
10
- from openai import OpenAI
11
  import openai
 
 
12
 
 
13
  openai_api_key = os.getenv("OPENAI_API_KEY")
14
-
15
- client = openai.OpenAI(api_key = openai_api_key)
16
 
17
  def openai_chat(text):
18
- from openai import OpenAI
19
-
20
- completion = client.chat.completions.create(
21
- model="gpt-4o",
22
- messages=[
23
- {"role": "system", "content": "초등학교 6학년 수준 범위 내에서 학생의 질문에 친절하게 답하는 교사 역할, 설명은 구체적인 예시를 들어서, 어려운 단어는 별도로 설명해줘. 설명글의 분량은 1000~2000자 정도로 해줘."},
24
- {"role": "user", "content": text}
25
- ],
26
- temperature=1,
27
- max_tokens=2000,
28
- top_p=0.9,
29
- frequency_penalty=0,
30
- presence_penalty=0
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  )
32
 
33
- return completion.choices[0].message.content
 
 
34
 
35
- openai_chat("한글은 누가 만들었어?")
 
 
 
 
36
 
37
- import gradio as gr
 
 
 
 
38
 
39
- with gr.Blocks() as demo:
40
- gr.Markdown("<div style='font-size: 30px; font-weight: bold;'>친절한 AI 선생님(GPT-4o)</div>")
41
- gr.Markdown("궁금한 것은 무엇이든 물어보세요. AI 선생님이 친절하게 알려줄 거예요!")
42
-
43
- Q = gr.Textbox(label="질문", placeholder="질문을 넣어주세요.")
44
- btn = gr.Button("질문하기")
45
- A = gr.TextArea(label="AI 선생님의 설명", placeholder="AI 선생님이 답변 중 입니다.")
46
 
47
- btn.click(openai_chat, inputs=Q, outputs=A)
 
 
 
 
 
48
 
49
- demo.launch()
 
 
 
 
 
 
 
 
 
 
1
  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-4",
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
  )
39
 
40
+ # 채팅 히스토리 관리
41
+ if "history" not in st.session_state:
42
+ st.session_state.history = []
43
 
44
+ # 사용자 입력 받기
45
+ user_input = st.text_input(
46
+ "질문", key="user_input", placeholder="질문을 넣어주세요.",
47
+ help="AI 선생님에게 궁금한 것을 물어보세요."
48
+ )
49
 
50
+ def respond(user_input):
51
+ if user_input:
52
+ st.session_state.history.append({"user": user_input, "ai": ""})
53
+ response = openai_chat(user_input)
54
+ st.session_state.history[-1]["ai"] = response
55
 
56
+ # 응답 생성 및 출력
57
+ if user_input:
58
+ respond(user_input)
 
 
 
 
59
 
60
+ # 채팅 메시지 출력
61
+ for chat in st.session_state.history:
62
+ if "user" in chat:
63
+ message(chat["user"], is_user=True, key=f"user_{chat['user']}")
64
+ if "ai" in chat:
65
+ message(chat["ai"], is_user=False, key=f"ai_{chat['ai']}")
66
 
67
+ # 초기화 버튼 클릭 시
68
+ if st.button("초기화"):
69
+ st.session_state.history = []