File size: 1,154 Bytes
f27ce24
 
5024470
f27ce24
5024470
dcbfe42
5024470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()