JUNGU commited on
Commit
7af9de2
·
verified ·
1 Parent(s): d034f8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -19
app.py CHANGED
@@ -12,7 +12,6 @@ logger = logging.getLogger(__name__)
12
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
13
  if GEMINI_API_KEY:
14
  logger.info("API 키가 환경변수에서 감지되었습니다.")
15
- # 키의 일부만 표시 (보안을 위해)
16
  logger.info(f"API 키 미리보기: {GEMINI_API_KEY[:8]}...")
17
  else:
18
  logger.warning("GEMINI_API_KEY가 환경변수에서 감지되지 않았습니다.")
@@ -22,14 +21,12 @@ else:
22
  with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
23
  gr.Markdown(
24
  """
25
- # ♊️ Gemini API 챗봇 (Secrets 사용)
26
  Google Gemini API를 사용하는 챗봇입니다.
27
 
28
  **중요**: Hugging Face Spaces의 **Settings → Repository secrets**에 `GEMINI_API_KEY`가 설정되어 있어야 합니다.
29
 
30
  [API 키 발급받기](https://aistudio.google.com/app/apikey)
31
-
32
- **디버깅 정보**:
33
  """
34
  )
35
 
@@ -41,8 +38,12 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
41
  interactive=False
42
  )
43
 
44
- # Gradio 챗봇 UI 컴포넌트
45
- chatbot = gr.Chatbot(label="Gemini 챗봇", height=600)
 
 
 
 
46
 
47
  with gr.Row():
48
  # 사용자 메시지 입력란
@@ -50,6 +51,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
50
  label="메시지 입력",
51
  placeholder="무엇이든 물어보세요...",
52
  scale=7,
 
53
  )
54
  # 전송 버튼
55
  submit_button = gr.Button("전송", variant="primary", scale=1)
@@ -57,15 +59,25 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
57
  with gr.Accordion("고급 설정", open=False):
58
  # LLM의 역할을 정의하는 시스템 메시지
59
  system_message = gr.Textbox(
60
- value="You are a helpful and friendly chatbot.", label="시스템 메시지"
 
 
61
  )
62
  # 모델의 창의성을 조절하는 슬라이더
63
  temperature = gr.Slider(
64
- minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Temperature"
 
 
 
 
65
  )
66
  # 생성할 최대 토큰 수를 조절하는 슬라이더
67
  max_tokens = gr.Slider(
68
- minimum=1, maximum=4096, value=1024, step=1, label="Max new tokens"
 
 
 
 
69
  )
70
 
71
  # 환경변수 새로고침 버튼
@@ -116,8 +128,9 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
116
 
117
  # 사용할 모델과 시스템 프롬프트를 설정합니다.
118
  try:
 
119
  model = genai.GenerativeModel(
120
- model_name='gemini-2.0-flash-exp', # 또는 'gemini-1.5-flash'
121
  system_instruction=system_prompt
122
  )
123
  except Exception as e:
@@ -126,11 +139,23 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
126
 
127
  # Gradio의 대화 기록을 Gemini API가 이해할 수 있는 형식으로 변환합니다.
128
  gemini_history = []
129
- for user_msg, model_msg in chat_history:
130
- if user_msg:
131
- gemini_history.append({"role": "user", "parts": [user_msg]})
132
- if model_msg:
133
- gemini_history.append({"role": "model", "parts": [model_msg]})
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  # 이전 대화 기록을 바탕으로 채팅 세션을 시작합니다.
136
  chat = model.start_chat(history=gemini_history)
@@ -170,14 +195,26 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
170
  def on_submit(message, chat_history, system_prompt, temp, max_output_tokens):
171
  if not message.strip():
172
  return "", chat_history
173
-
174
- chat_history.append((message, None))
175
- bot_response_stream = respond(message, chat_history, system_prompt, temp, max_output_tokens)
 
 
 
 
 
 
176
 
177
  for partial_response in bot_response_stream:
178
- chat_history[-1] = (message, partial_response)
 
 
 
 
 
179
  yield "", chat_history
180
 
 
181
  msg.submit(
182
  on_submit,
183
  [msg, chatbot, system_message, temperature, max_tokens],
@@ -189,6 +226,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
189
  [msg, chatbot]
190
  )
191
 
 
192
  if __name__ == "__main__":
193
  # 디버깅 모드로 실행
194
  demo.launch(debug=True)
 
12
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
13
  if GEMINI_API_KEY:
14
  logger.info("API 키가 환경변수에서 감지되었습니다.")
 
15
  logger.info(f"API 키 미리보기: {GEMINI_API_KEY[:8]}...")
16
  else:
17
  logger.warning("GEMINI_API_KEY가 환경변수에서 감지되지 않았습니다.")
 
21
  with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
22
  gr.Markdown(
23
  """
24
+ # ♊️ Gemini API 챗봇
25
  Google Gemini API를 사용하는 챗봇입니다.
26
 
27
  **중요**: Hugging Face Spaces의 **Settings → Repository secrets**에 `GEMINI_API_KEY`가 설정되어 있어야 합니다.
28
 
29
  [API 키 발급받기](https://aistudio.google.com/app/apikey)
 
 
30
  """
31
  )
32
 
 
38
  interactive=False
39
  )
40
 
41
+ # Gradio 챗봇 UI 컴포넌트 - type 파라미터 추가
42
+ chatbot = gr.Chatbot(
43
+ label="Gemini 챗봇",
44
+ height=600,
45
+ type="messages" # 이 파라미터를 추가하여 경고 해결
46
+ )
47
 
48
  with gr.Row():
49
  # 사용자 메시지 입력란
 
51
  label="메시지 입력",
52
  placeholder="무엇이든 물어보세요...",
53
  scale=7,
54
+ lines=1
55
  )
56
  # 전송 버튼
57
  submit_button = gr.Button("전송", variant="primary", scale=1)
 
59
  with gr.Accordion("고급 설정", open=False):
60
  # LLM의 역할을 정의하는 시스템 메시지
61
  system_message = gr.Textbox(
62
+ value="You are a helpful and friendly chatbot.",
63
+ label="시스템 메시지",
64
+ lines=2
65
  )
66
  # 모델의 창의성을 조절하는 슬라이더
67
  temperature = gr.Slider(
68
+ minimum=0.0,
69
+ maximum=1.0,
70
+ value=0.7,
71
+ step=0.1,
72
+ label="Temperature"
73
  )
74
  # 생성할 최대 토큰 수를 조절하는 슬라이더
75
  max_tokens = gr.Slider(
76
+ minimum=1,
77
+ maximum=4096,
78
+ value=1024,
79
+ step=1,
80
+ label="Max new tokens"
81
  )
82
 
83
  # 환경변수 새로고침 버튼
 
128
 
129
  # 사용할 모델과 시스템 프롬프트를 설정합니다.
130
  try:
131
+ # 사용 가능한 모델로 변경
132
  model = genai.GenerativeModel(
133
+ model_name='gemini-2.0-flash', # 안정적인 모델 사용
134
  system_instruction=system_prompt
135
  )
136
  except Exception as e:
 
139
 
140
  # Gradio의 대화 기록을 Gemini API가 이해할 수 있는 형식으로 변환합니다.
141
  gemini_history = []
142
+
143
+ # type="messages" 형식에 맞게 처리
144
+ if isinstance(chat_history, list) and len(chat_history) > 0:
145
+ # 새로운 메시지 형식 처리
146
+ if isinstance(chat_history[0], dict):
147
+ for msg in chat_history:
148
+ if msg.get("role") == "user":
149
+ gemini_history.append({"role": "user", "parts": [msg.get("content", "")]})
150
+ elif msg.get("role") == "assistant":
151
+ gemini_history.append({"role": "model", "parts": [msg.get("content", "")]})
152
+ # 이전 튜플 형식도 지원
153
+ else:
154
+ for user_msg, model_msg in chat_history:
155
+ if user_msg:
156
+ gemini_history.append({"role": "user", "parts": [user_msg]})
157
+ if model_msg:
158
+ gemini_history.append({"role": "model", "parts": [model_msg]})
159
 
160
  # 이전 대화 기록을 바탕으로 채팅 세션을 시작합니다.
161
  chat = model.start_chat(history=gemini_history)
 
195
  def on_submit(message, chat_history, system_prompt, temp, max_output_tokens):
196
  if not message.strip():
197
  return "", chat_history
198
+
199
+ # 새로운 메시지 형식 사용
200
+ chat_history = chat_history or []
201
+
202
+ # 사용자 메시지 추가
203
+ chat_history.append({"role": "user", "content": message})
204
+
205
+ # 봇 응답 스트리밍
206
+ bot_response_stream = respond(message, chat_history[:-1], system_prompt, temp, max_output_tokens)
207
 
208
  for partial_response in bot_response_stream:
209
+ # 마지막 메시지가 사용자 메시지인 경우에만 봇 응답 추가
210
+ if chat_history and chat_history[-1]["role"] == "user":
211
+ chat_history.append({"role": "assistant", "content": partial_response})
212
+ else:
213
+ # 봇 응답 업데이트
214
+ chat_history[-1]["content"] = partial_response
215
  yield "", chat_history
216
 
217
+ # 이벤트 핸들러 연결
218
  msg.submit(
219
  on_submit,
220
  [msg, chatbot, system_message, temperature, max_tokens],
 
226
  [msg, chatbot]
227
  )
228
 
229
+ # 메인 실행 부분
230
  if __name__ == "__main__":
231
  # 디버깅 모드로 실행
232
  demo.launch(debug=True)