Kims12 commited on
Commit
2c72380
·
verified ·
1 Parent(s): 5fd94b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -51
app.py CHANGED
@@ -1,6 +1,8 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import openai
 
 
4
 
5
  #############################
6
  # [기본코드] - 수정/삭제 불가
@@ -237,7 +239,7 @@ with gr.Blocks() as demo:
237
  )
238
 
239
  # --- Tab: ChatGPT ---
240
- with gr.Tab("gpt-4o-mini"):
241
  chatgpt_system_message = gr.Textbox(
242
  value="""반드시 한글로 답변할 것.
243
  너는 ChatGPT, OpenAI에서 개발한 언어 모델이다.
@@ -269,72 +271,109 @@ with gr.Blocks() as demo:
269
  )
270
 
271
  #################################################
272
- # [클로드 플레이그라운드] - [참조코드] 일부 발췌
273
  #################################################
274
- with gr.Tab("claude-3-haiku"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  gr.Markdown("클로드 모델과의 간단한 플레이그라운드입니다.")
276
 
277
- # Claude용 토큰
278
  claude_token_box = gr.Textbox(
279
  label="Claude 토큰 (비공개)",
280
  type="password",
281
- placeholder="Claude API 토큰을 입력하세요..."
 
282
  )
283
 
284
  claude_system_message = gr.Textbox(
285
  label="System Message",
286
- value="반드시 한글로 답변할 것.\n너는 Anthropic에서 개발한 클로드이다.\n최대한 정확하고 친절하게 답변하라.\n",
 
 
287
  lines=3
288
  )
289
 
290
- claude_max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max Tokens")
291
- claude_temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature")
292
- claude_top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
- claude_question_input = gr.Textbox(label="질문을 입력하세요")
295
- claude_answer_output = gr.Textbox(label="답변", interactive=False)
 
 
 
 
 
 
 
 
 
 
296
  claude_submit_button = gr.Button("전송")
297
 
298
- # Claude 응답 함수 (최소 기능만 사용)
299
- def respond_claude_qna(
300
- question: str,
301
- system_message: str,
302
- max_tokens: int,
303
- temperature: float,
304
- top_p: float,
305
- claude_api_key: str
306
- ):
307
- """
308
- [참조코드]에서 최소한의 클로드 호출 ���분만 발췌한 함수.
309
- 플레이그라운드 형태로 한 번의 질문에 대한 답변을 반환.
310
- """
311
- import anthropic
312
-
313
- # 토큰이 없으면 에러
314
- if not claude_api_key:
315
- return "Claude API 토큰이 필요합니다."
316
-
317
- try:
318
- claude_client = anthropic.Anthropic(api_key=claude_api_key)
319
- # 클로드에게 보낼 프롬프트 구성
320
- # Anthropic 공식 예시를 참고하여 HUMAN_PROMPT / AI_PROMPT 사용
321
- prompt = (
322
- f"{anthropic.HUMAN_PROMPT}\n"
323
- f"{system_message}\n\n"
324
- f"질문: {question}\n"
325
- f"{anthropic.AI_PROMPT}"
326
- )
327
- response = claude_client.completions.create(
328
- model="claude-3-haiku-20240307",
329
- max_tokens_to_sample=max_tokens,
330
- temperature=temperature,
331
- top_p=top_p,
332
- prompt=prompt
333
- )
334
- return response.completion.strip()
335
- except Exception as e:
336
- return f"오류가 발생했습니다: {str(e)}"
337
-
338
  claude_submit_button.click(
339
  fn=respond_claude_qna,
340
  inputs=[
@@ -353,3 +392,4 @@ with gr.Blocks() as demo:
353
  #############################
354
  if __name__ == "__main__":
355
  demo.launch()
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import openai
4
+ import anthropic
5
+ from typing import Optional
6
 
7
  #############################
8
  # [기본코드] - 수정/삭제 불가
 
239
  )
240
 
241
  # --- Tab: ChatGPT ---
242
+ with gr.Tab("ChatGPT"):
243
  chatgpt_system_message = gr.Textbox(
244
  value="""반드시 한글로 답변할 것.
245
  너는 ChatGPT, OpenAI에서 개발한 언어 모델이다.
 
271
  )
272
 
273
  #################################################
274
+ # [클로드 플레이그라운드] - 개선된 코드
275
  #################################################
276
+
277
+ def validate_claude_token(token: str) -> bool:
278
+ """Claude API 토큰 검증"""
279
+ return bool(token and len(token.strip()) >= 10)
280
+
281
+ def respond_claude_qna(
282
+ question: str,
283
+ system_message: str,
284
+ max_tokens: int,
285
+ temperature: float,
286
+ top_p: float,
287
+ claude_api_key: str
288
+ ) -> str:
289
+ """
290
+ Claude API를 사용한 개선된 응답 생성 함수
291
+ """
292
+ if not validate_claude_token(claude_api_key):
293
+ return "유효한 Claude API 토큰이 필요합니다."
294
+
295
+ try:
296
+ client = anthropic.Anthropic(api_key=claude_api_key)
297
+
298
+ # 메시지 생성
299
+ message = client.messages.create(
300
+ model="claude-3-haiku-20240307",
301
+ max_tokens=max_tokens,
302
+ temperature=temperature,
303
+ system=system_message,
304
+ messages=[
305
+ {
306
+ "role": "user",
307
+ "content": question
308
+ }
309
+ ]
310
+ )
311
+
312
+ return message.content[0].text
313
+
314
+ except anthropic.APIError as ae:
315
+ return f"Claude API 오류: {str(ae)}"
316
+ except anthropic.RateLimitError:
317
+ return "요청 한도를 초과했습니다. 잠시 후 다시 시도해주세요."
318
+ except Exception as e:
319
+ return f"예상치 못한 오류가 발생했습니다: {str(e)}"
320
+
321
+ with gr.Tab("클로드 플레이그라운드"):
322
  gr.Markdown("클로드 모델과의 간단한 플레이그라운드입니다.")
323
 
 
324
  claude_token_box = gr.Textbox(
325
  label="Claude 토큰 (비공개)",
326
  type="password",
327
+ placeholder="Claude API 토큰을 입력하세요...",
328
+ show_copy_button=False
329
  )
330
 
331
  claude_system_message = gr.Textbox(
332
  label="System Message",
333
+ value="""반드시 한글로 답변할 것.
334
+ 너는 Anthropic에서 개발한 클로드이다.
335
+ 최대한 정확하고 친절하게 답변하라.""",
336
  lines=3
337
  )
338
 
339
+ claude_max_tokens = gr.Slider(
340
+ minimum=1,
341
+ maximum=4096,
342
+ value=512,
343
+ step=1,
344
+ label="Max Tokens"
345
+ )
346
+
347
+ claude_temperature = gr.Slider(
348
+ minimum=0.1,
349
+ maximum=2.0,
350
+ value=0.7,
351
+ step=0.05,
352
+ label="Temperature"
353
+ )
354
+
355
+ claude_top_p = gr.Slider(
356
+ minimum=0.1,
357
+ maximum=1.0,
358
+ value=0.95,
359
+ step=0.05,
360
+ label="Top-p"
361
+ )
362
 
363
+ claude_question_input = gr.Textbox(
364
+ label="질문을 입력하세요",
365
+ lines=3,
366
+ placeholder="질문을 입력하세요..."
367
+ )
368
+
369
+ claude_answer_output = gr.Textbox(
370
+ label="답변",
371
+ interactive=False,
372
+ lines=10
373
+ )
374
+
375
  claude_submit_button = gr.Button("전송")
376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  claude_submit_button.click(
378
  fn=respond_claude_qna,
379
  inputs=[
 
392
  #############################
393
  if __name__ == "__main__":
394
  demo.launch()
395
+