File size: 1,700 Bytes
7fe0df9
1dacd0d
28668a9
 
3e5f6ae
28668a9
 
c365981
28668a9
 
c365981
 
28668a9
 
c365981
 
28668a9
 
 
 
 
c365981
 
 
 
28668a9
 
c365981
28668a9
 
 
3e5f6ae
7fe0df9
c263170
da5015b
7740cf7
7fe0df9
 
 
 
7740cf7
c263170
 
 
7fe0df9
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
# app.py
import gradio as gr
import openai
import os

# 1️⃣ Thiết lập OpenAI API key (đặt biến môi trường OPENAI_API_KEY trước khi chạy)
openai.api_key = os.getenv("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")

def respond(message, history, system_message, max_tokens, temperature, top_p):
    # 2.1 — Gom system + lịch sử chat vào messages list
    messages = [{"role": "system", "content": system_message}]
    for u, b in history:
        messages.append({"role": "user",      "content": u})
        messages.append({"role": "assistant", "content": b})
    messages.append({"role": "user", "content": message})

    # 2.2 — Gọi OpenAI ChatCompletion
    resp = openai.ChatCompletion.create(
        model="gpt-4.1-nano",
        messages=messages,
        max_tokens=max_tokens,
        temperature=temperature,
        top_p=top_p,
    )

    # 2.3 — Trích nội dung assistant reply
    reply = resp.choices[0].message.content.strip()

    # 2.4 — Cập nhật history và trả về
    history.append((message, reply))
    return history

# 3️⃣ Giao diện Gradio
demo = gr.ChatInterface(
    respond, #câu phản hồi
    additional_inputs=[
        gr.Textbox("Bạn là một chatbot tiếng Việt thân thiện.", label="System message"),
        gr.Slider(1, 2048, value=512, step=1, label="Max new tokens"),
        gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature"),
        gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
    ],
)

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