| import gradio as gr |
| from openai import OpenAI |
| import os |
|
|
| |
| os.environ["OPENAI_API_KEY"] = "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" |
|
|
| client = OpenAI() |
|
|
| |
| history = [] |
|
|
| |
| def chat_with_gpt(message, history_list): |
| history_list = history_list or [] |
| |
| |
| messages = [{"role": "system", "content": "You are a helpful assistant."}] |
| for human, bot in history_list: |
| messages.append({"role": "user", "content": human}) |
| messages.append({"role": "assistant", "content": bot}) |
| messages.append({"role": "user", "content": message}) |
|
|
| |
| response = client.chat.completions.create( |
| model="gpt-4o-mini", |
| messages=messages, |
| temperature=0.7 |
| ) |
|
|
| reply = response.choices[0].message.content |
| history_list.append((message, reply)) |
| return history_list, history_list |
|
|
| |
| with gr.Blocks(title="ChatGPT via OpenAI API") as demo: |
| gr.Markdown("### π€ ChatGPT (API-Powered) β No Pro Needed") |
| chatbot = gr.Chatbot(height=400) |
| msg = gr.Textbox(label="Your Message") |
| clear = gr.Button("Clear Chat") |
|
|
| msg.submit(chat_with_gpt, [msg, chatbot], [chatbot, chatbot]) |
| clear.click(lambda: None, None, chatbot) |
|
|
| demo.launch() |
|
|