import openai import gradio as gr import os # Set OpenAI API key from environment variable openai.api_key = os.getenv("OPENAI_API_KEY") # Define a function to interact with OpenAI's ChatGPT def chat_with_openai(input_text): try: response = openai.Completion.create( engine="gpt-4", # Use the model you want (e.g., 'gpt-3.5-turbo', 'gpt-4') prompt=input_text, max_tokens=150, n=1, stop=None, temperature=0.7, ) answer = response.choices[0].text.strip() return answer except Exception as e: return str(e) # Define the Gradio interface with gr.Blocks() as ui: gr.Markdown("# Chatbot with OpenAI API") chatbot = gr.Chatbot(label="OpenAI Chatbot") msg = gr.Textbox(label="Enter your message here:") submit_btn = gr.Button("Submit") def on_submit(message, chat_history): response = chat_with_openai(message) chat_history.append((message, response)) return chat_history, "" submit_btn.click(on_submit, inputs=[msg, chatbot], outputs=[chatbot, msg]) # Launch the Gradio app ui.launch()