File size: 17,973 Bytes
b34f0d5
7dcc8af
9bab38e
5900591
7dcc8af
b34f0d5
8144da3
7dcc8af
 
 
 
 
 
 
5900591
 
7dcc8af
b34f0d5
8144da3
c65ce97
 
f1d1009
 
 
 
 
7dcc8af
f1d1009
 
c65ce97
 
 
 
 
 
7dcc8af
b34f0d5
7dcc8af
 
 
 
 
b34f0d5
7dcc8af
 
f1d1009
b34f0d5
7dcc8af
f1d1009
7dcc8af
 
 
b34f0d5
7dcc8af
 
 
 
 
b34f0d5
7dcc8af
c65ce97
8144da3
7dcc8af
 
 
 
 
 
 
 
c65ce97
7dcc8af
8144da3
7dcc8af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23d8e09
7dcc8af
 
 
092cc1c
 
 
 
 
 
 
f1d1009
092cc1c
 
 
f1d1009
092cc1c
 
 
 
8144da3
092cc1c
 
 
 
 
 
 
 
 
8144da3
092cc1c
 
 
 
 
 
 
 
 
 
 
 
 
 
9bab38e
 
 
 
 
 
 
f1d1009
9bab38e
f1d1009
 
 
 
 
9bab38e
 
f1d1009
 
9bab38e
 
 
 
 
 
 
 
8144da3
9bab38e
 
 
 
 
 
 
 
 
 
 
 
 
5900591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1d1009
7dcc8af
 
b34f0d5
 
7dcc8af
 
f1d1009
 
 
 
2c0bbf8
f1d1009
 
 
 
2c0bbf8
f1d1009
 
 
5900591
2c0bbf8
5900591
 
 
 
2c0bbf8
5900591
 
 
f1d1009
23d8e09
 
 
 
 
 
 
 
2c0bbf8
23d8e09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1d1009
 
 
 
 
 
 
 
 
 
 
 
 
23d8e09
8144da3
23d8e09
 
 
7dcc8af
 
 
 
 
 
b34f0d5
2c0bbf8
 
23d8e09
 
 
 
 
 
 
8144da3
23d8e09
 
 
 
 
 
f1d1009
 
 
 
 
 
 
 
 
 
 
 
23d8e09
8144da3
9bab38e
 
 
 
 
 
 
 
 
 
2c0bbf8
9bab38e
 
 
 
 
 
 
 
8144da3
9bab38e
 
 
 
 
 
f1d1009
 
 
 
 
 
 
 
 
 
 
 
9bab38e
6d1479a
5900591
 
 
 
 
 
 
 
 
 
2c0bbf8
5900591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c0bbf8
5900591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b34f0d5
5900591
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import gradio as gr
from huggingface_hub import InferenceClient
import openai
import anthropic
import os

# 제거할 모델들을 MODELS 사전에서 제외
MODELS = {
    "Zephyr 7B Beta": "HuggingFaceH4/zephyr-7b-beta",
    "Meta Llama 3.1 8B": "meta-llama/Meta-Llama-3.1-8B-Instruct",
    "Meta-Llama 3.1 70B-Instruct": "meta-llama/Meta-Llama-3.1-70B-Instruct",
    "Microsoft": "microsoft/Phi-3-mini-4k-instruct",
    "Mixtral 8x7B": "mistralai/Mistral-7B-Instruct-v0.3",
    "Mixtral Nous-Hermes": "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
    "Aya-23-35B": "CohereForAI/aya-23-35B",
    "DeepSeek-V3": "deepseek/deepseek-chat"
}

# Cohere Command R+ 모델 ID 정의
COHERE_MODEL = "CohereForAI/c4ai-command-r-plus-08-2024"

def get_client(model_name, hf_token):
    """
    모델 이름에 맞춰 InferenceClient 생성.
    hf_token을 UI에서 입력받은 값으로 사용하도록 변경.
    """
    if not hf_token:
        raise ValueError("HuggingFace API 토큰이 필요합니다.")

    if model_name in MODELS:
        model_id = MODELS[model_name]
    elif model_name == "Cohere Command R+":
        model_id = COHERE_MODEL
    else:
        raise ValueError("유효하지 않은 모델 이름입니다.")
    return InferenceClient(model_id, token=hf_token)

def respond(
    message,
    chat_history,
    model_name,
    max_tokens,
    temperature,
    top_p,
    system_message,
    hf_token,       # HF 토큰을 추가로 받음
):
    try:
        client = get_client(model_name, hf_token)
    except ValueError as e:
        chat_history.append((message, str(e)))
        return chat_history

    messages = [{"role": "system", "content": system_message}]
    for human, assistant in chat_history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})
    messages.append({"role": "user", "content": message})

    try:
        if model_name == "Cohere Command R+":
            # Cohere Command R+ 모델을 위한 비스트리밍 처리
            response = client.chat_completion(
                messages,
                max_tokens=max_tokens,
                temperature=temperature,
                top_p=top_p,
            )
            assistant_message = response.choices[0].message.content
            chat_history.append((message, assistant_message))
            return chat_history
        else:
            # 다른 모델들을 위한 스트리밍 처리
            stream = client.chat_completion(
                messages,
                max_tokens=max_tokens,
                temperature=temperature,
                top_p=top_p,
                stream=True,
            )
            partial_message = ""
            for response in stream:
                if response.choices[0].delta.content is not None:
                    partial_message += response.choices[0].delta.content
                    if len(chat_history) > 0 and chat_history[-1][0] == message:
                        chat_history[-1] = (message, partial_message)
                    else:
                        chat_history.append((message, partial_message))
                    yield chat_history
    except Exception as e:
        error_message = f"오류가 발생했습니다: {str(e)}"
        chat_history.append((message, error_message))
        yield chat_history

def cohere_respond(
    message,
    chat_history,
    system_message,
    max_tokens,
    temperature,
    top_p,
    hf_token,   # HF 토큰 추가
):
    model_name = "Cohere Command R+"
    try:
        client = get_client(model_name, hf_token)
    except ValueError as e:
        chat_history.append((message, str(e)))
        return chat_history

    messages = [{"role": "system", "content": system_message}]
    for human, assistant in chat_history:
        if human:
            messages.append({"role": "user", "content": human})
        if assistant:
            messages.append({"role": "assistant", "content": assistant})

    messages.append({"role": "user", "content": message})

    try:
        # Cohere Command R+ 모델을 위한 비스트리밍 처리
        response_full = client.chat_completion(
            messages,
            max_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
        )
        assistant_message = response_full.choices[0].message.content
        chat_history.append((message, assistant_message))
        return chat_history
    except Exception as e:
        error_message = f"오류가 발생했습니다: {str(e)}"
        chat_history.append((message, error_message))
        return chat_history

def chatgpt_respond(
    message,
    chat_history,
    system_message,
    max_tokens,
    temperature,
    top_p,
    openai_token,  # openai 토큰 추가
):
    """
    chatgpt용 응답. openai_token을 UI에서 입력받아 사용하도록 변경.
    """
    if not openai_token:
        chat_history.append((message, "OpenAI API 토큰이 필요합니다."))
        return chat_history

    openai.api_key = openai_token  # UI에서 받은 토큰 사용

    messages = [{"role": "system", "content": system_message}]
    for human, assistant in chat_history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})
    messages.append({"role": "user", "content": message})

    try:
        response = openai.ChatCompletion.create(
            model="gpt-4o-mini",  # 또는 다른 모델 ID 사용
            messages=messages,
            max_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
        )
        assistant_message = response.choices[0].message['content']
        chat_history.append((message, assistant_message))
        return chat_history
    except Exception as e:
        error_message = f"오류가 발생했습니다: {str(e)}"
        chat_history.append((message, error_message))
        return chat_history

def claude_respond(
    message,
    chat_history,
    system_message,
    max_tokens,
    temperature,
    top_p,
    claude_token,  # Claude 토큰 추가
):
    """
    Claude용 응답. claude_token을 UI에서 입력받아 사용하도록 변경.
    """
    if not claude_token:
        chat_history.append((message, "Claude API 토큰이 필요합니다."))
        return chat_history

    try:
        client = anthropic.Anthropic(api_key=claude_token)
        
        # 메시지 생성
        response = client.messages.create(
            model="claude-3-haiku-20240307",
            max_tokens=max_tokens,
            temperature=temperature,
            system=system_message,
            messages=[
                {
                    "role": "user",
                    "content": message
                }
            ]
        )
        
        assistant_message = response.content[0].text
        chat_history.append((message, assistant_message))
        return chat_history
    except Exception as e:
        error_message = f"오류가 발생했습니다: {str(e)}"
        chat_history.append((message, error_message))
        return chat_history

def deepseek_respond(
    message,
    chat_history,
    system_message,
    max_tokens,
    temperature,
    top_p,
    deepseek_token,  # DeepSeek 토큰 추가
):
    """
    DeepSeek용 응답. deepseek_token을 UI에서 입력받아 사용하도록 변경.
    """
    if not deepseek_token:
        chat_history.append((message, "DeepSeek API 토큰이 필요합니다."))
        return chat_history

    openai.api_key = deepseek_token
    openai.api_base = "https://api.deepseek.com/v1"

    messages = [{"role": "system", "content": system_message}]
    for human, assistant in chat_history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})
    messages.append({"role": "user", "content": message})

    try:
        response = openai.ChatCompletion.create(
            model="deepseek-chat",
            messages=messages,
            max_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
        )
        assistant_message = response.choices[0].message['content']
        chat_history.append((message, assistant_message))
        return chat_history
    except Exception as e:
        error_message = f"오류가 발생했습니다: {str(e)}"
        chat_history.append((message, error_message))
        return chat_history

def clear_conversation():
    return []

with gr.Blocks() as demo:
    gr.Markdown("# Prompting AI Chatbot")
    gr.Markdown("언어모델별 프롬프트 테스트 챗봇입니다.")

    # --- 토큰 입력 UI 추가 ---
    with gr.Row():
        hf_token_box = gr.Textbox(
            label="HuggingFace 토큰",
            type="password",
            placeholder="HuggingFace API 토큰을 입력하세요..."
        )
        openai_token_box = gr.Textbox(
            label="OpenAI 토큰",
            type="password",
            placeholder="OpenAI API 토큰을 입력하세요..."
        )
        claude_token_box = gr.Textbox(
            label="Claude 토큰",
            type="password",
            placeholder="Claude API 토큰을 입력하세요..."
        )
        deepseek_token_box = gr.Textbox(
            label="DeepSeek 토큰",
            type="password",
            placeholder="DeepSeek API 토큰을 입력하세요..."
        )

    with gr.Tab("일반 모델"):
        with gr.Row():
            with gr.Column(scale=1):
                model_name = gr.Radio(
                    choices=list(MODELS.keys()),
                    label="Language Model",
                    value="Zephyr 7B Beta"
                )
                max_tokens = gr.Slider(minimum=100, maximum=8000, value=2000, step=100, label="Max Tokens")
                temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature")
                top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
                system_message = gr.Textbox(
                    value="""반드시 한글로 답변할 것.
너는 최고의 비서이다.
내가 요구하는것들을 최대한 자세하고 정확하게 답변하라.
""",
                    label="System Message",
                    lines=3
                )
    
            with gr.Column(scale=2):
                chatbot = gr.Chatbot()
                msg = gr.Textbox(label="메세지를 입력하세요")
                with gr.Row():
                    submit_button = gr.Button("전송")
                    clear_button = gr.Button("대화 내역 지우기")
    
        # respond 함수에 hf_token 인자를 전달하도록 수정
        inputs_for_normal = [
            msg, 
            chatbot, 
            model_name, 
            max_tokens, 
            temperature, 
            top_p, 
            system_message,
            hf_token_box
        ]
        msg.submit(respond, inputs_for_normal, chatbot)
        submit_button.click(respond, inputs_for_normal, chatbot)
        clear_button.click(clear_conversation, outputs=chatbot, queue=False)
    
    with gr.Tab("Cohere Command R+"):
        with gr.Row():
            cohere_system_message = gr.Textbox(
                value="""반드시 한글로 답변할 것.
너는 최고의 비서이다.
내가 요구하는것들을 최대한 자세하고 정확하게 답변하라.
""",
                label="System Message",
                lines=3
            )
            cohere_max_tokens = gr.Slider(minimum=100, maximum=8000, value=2000, step=100, label="Max new tokens")
            cohere_temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature")
            cohere_top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-P",
            )
        
        cohere_chatbot = gr.Chatbot(height=600)
        cohere_msg = gr.Textbox(label="메세지를 입력하세요")
        with gr.Row():
            cohere_submit_button = gr.Button("전송")
            cohere_clear_button = gr.Button("대화 내역 지우기")
        
        # cohere_respond 함수에 hf_token 인자를 전달하도록 수정
        inputs_for_cohere = [
            cohere_msg, 
            cohere_chatbot, 
            cohere_system_message, 
            cohere_max_tokens, 
            cohere_temperature, 
            cohere_top_p,
            hf_token_box
        ]
        cohere_msg.submit(cohere_respond, inputs_for_cohere, cohere_chatbot)
        cohere_submit_button.click(cohere_respond, inputs_for_cohere, cohere_chatbot)
        cohere_clear_button.click(clear_conversation, outputs=cohere_chatbot, queue=False)
    
    with gr.Tab("ChatGPT"):
        with gr.Row():
            chatgpt_system_message = gr.Textbox(
                value="""반드시 한글로 답변할 것.
너는 ChatGPT, OpenAI에서 개발한 언어 모델이다.
내가 요구하는 것을 최대한 자세하고 정확하게 답변하라.
""",
                label="System Message",
                lines=3
            )
            chatgpt_max_tokens = gr.Slider(minimum=100, maximum=5000, value=2000, step=100, label="Max Tokens")
            chatgpt_temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature")
            chatgpt_top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-P",
            )
        
        chatgpt_chatbot = gr.Chatbot(height=600)
        chatgpt_msg = gr.Textbox(label="메세지를 입력하세요")
        with gr.Row():
            chatgpt_submit_button = gr.Button("전송")
            chatgpt_clear_button = gr.Button("대화 내역 지우기")
        
        # chatgpt_respond 함수에 openai_token 인자를 전달하도록 수정
        inputs_for_chatgpt = [
            chatgpt_msg, 
            chatgpt_chatbot, 
            chatgpt_system_message, 
            chatgpt_max_tokens, 
            chatgpt_temperature, 
            chatgpt_top_p,
            openai_token_box
        ]
        chatgpt_msg.submit(chatgpt_respond, inputs_for_chatgpt, chatgpt_chatbot)
        chatgpt_submit_button.click(chatgpt_respond, inputs_for_chatgpt, chatgpt_chatbot)
        chatgpt_clear_button.click(clear_conversation, outputs=chatgpt_chatbot, queue=False)

    with gr.Tab("Claude"):
        with gr.Row():
            claude_system_message = gr.Textbox(
                value="""반드시 한글로 답변할 것.
너는 Anthropic에서 개발한 클로드이다.
최대한 정확하고 친절하게 답변하라.
""",
                label="System Message",
                lines=3
            )
            claude_max_tokens = gr.Slider(minimum=100, maximum=8000, value=2000, step=100, label="Max Tokens")
            claude_temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature")
            claude_top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-P",
            )
        
        claude_chatbot = gr.Chatbot(height=600)
        claude_msg = gr.Textbox(label="메세지를 입력하세요")
        with gr.Row():
            claude_submit_button = gr.Button("전송")
            claude_clear_button = gr.Button("대화 내역 지우기")
        
        # claude_respond 함수에 claude_token 인자를 전달하도록 수정
        inputs_for_claude = [
            claude_msg, 
            claude_chatbot, 
            claude_system_message, 
            claude_max_tokens, 
            claude_temperature, 
            claude_top_p,
            claude_token_box
        ]
        claude_msg.submit(claude_respond, inputs_for_claude, claude_chatbot)
        claude_submit_button.click(claude_respond, inputs_for_claude, claude_chatbot)
        claude_clear_button.click(clear_conversation, outputs=claude_chatbot, queue=False)

    with gr.Tab("DeepSeek"):
        with gr.Row():
            deepseek_system_message = gr.Textbox(
                value="""반드시 한글로 답변할 것.
너는 DeepSeek-V3, 최고의 언어 모델이다.
내가 요구하는 것을 최대한 자세하고 정확하게 답변하라.
""",
                label="System Message",
                lines=3
            )
            deepseek_max_tokens = gr.Slider(minimum=100, maximum=8000, value=2000, step=100, label="Max Tokens")
            deepseek_temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature")
            deepseek_top_p = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-P",
            )
        
        deepseek_chatbot = gr.Chatbot(height=600)
        deepseek_msg = gr.Textbox(label="메세지를 입력하세요")
        with gr.Row():
            deepseek_submit_button = gr.Button("전송")
            deepseek_clear_button = gr.Button("대화 내역 지우기")
        
        # deepseek_respond 함수에 deepseek_token 인자를 전달하도록 수정
        inputs_for_deepseek = [
            deepseek_msg, 
            deepseek_chatbot, 
            deepseek_system_message, 
            deepseek_max_tokens, 
            deepseek_temperature, 
            deepseek_top_p,
            deepseek_token_box
        ]
        deepseek_msg.submit(deepseek_respond, inputs_for_deepseek, deepseek_chatbot)
        deepseek_submit_button.click(deepseek_respond, inputs_for_deepseek, deepseek_chatbot)
        deepseek_clear_button.click(clear_conversation, outputs=deepseek_chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()