| | from openai import OpenAI |
| | import gradio as gr |
| | import os |
| |
|
| | api_key = os.getenv("OPENAI_API_KEY") |
| | client = OpenAI(api_key=api_key) |
| |
|
| | def predict(message, history=""): |
| | if history: |
| | history_list = eval(history) |
| | else: |
| | history_list = [] |
| |
|
| | |
| | history_list.append(("user", message)) |
| |
|
| | |
| | messages = [{"role": "user" if role == "user" else "assistant", "content": content} for role, content in history_list] |
| |
|
| | |
| | response = client.chat.completions.create( |
| | model='gpt-3.5-turbo', |
| | messages=messages, |
| | max_tokens=150, |
| | temperature=0.5 |
| | ) |
| |
|
| | |
| | answer = response.choices[0].message['content'] |
| | history_list.append(("assistant", answer)) |
| | |
| | |
| | history_text = str(history_list) |
| |
|
| | return history_text, answer |
| |
|
| | with gr.Blocks() as app: |
| | with gr.Row(): |
| | with gr.Column(): |
| | message_input = gr.Textbox(label="Your Message") |
| | history_input = gr.Textbox(label="History", lines=10, placeholder="Conversation history appears here...") |
| | with gr.Column(): |
| | history_output = gr.Textbox(label="Updated History", lines=10) |
| | response_output = gr.Textbox(label="Assistant's Response") |
| | predict_button = gr.Button("Predict") |
| | predict_button.click(predict, inputs=[message_input, history_input], outputs=[history_output, response_output]) |
| |
|
| | app.launch() |