Spaces:
Sleeping
Sleeping
# 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() | |