bot / app.py
latterworks's picture
Update app.py
61f65e4 verified
raw
history blame
2.11 kB
import gradio as gr
import os
import openai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Initialize OpenAI client
openai.api_key = OPENAI_API_KEY
openai.api_base = "https://api.aimlapi.com/"
# Greeting function for Gradio
def greet(name):
return f"Hello {name}!"
# OpenAI Chat Completion Function
def get_openai_response(user_content, model="o1-preview", max_tokens=500):
try:
chat_completion = openai.ChatCompletion.create(
model=model,
messages=[
{"role": "user", "content": user_content}
],
max_tokens=max_tokens
)
response = chat_completion.choices[0].message['content']
return response
except Exception as e:
return f"An error occurred: {e}"
# Gradio interface
def openai_chat_interface(user_content, model, max_tokens):
return get_openai_response(user_content, model, max_tokens)
# Define Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# OpenAI Chat Completion & Greeting Interface")
# Greeting section
with gr.Row():
gr.Markdown("### Greeting Section")
greet_input = gr.Textbox(label="Enter your name")
greet_output = gr.Textbox(label="Greeting Output")
greet_button = gr.Button("Greet")
greet_button.click(greet, inputs=greet_input, outputs=greet_output)
# OpenAI Chat Completion Section
with gr.Row():
gr.Markdown("### OpenAI Chat Completion")
user_input = gr.Textbox(label="Enter your message")
model_input = gr.Radio(["o1-preview", "o1-mini"], label="Model Selection", value="o1-preview")
max_tokens_input = gr.Slider(1, 7000, value=500, label="Max Tokens")
openai_response = gr.Textbox(label="OpenAI Response")
chat_button = gr.Button("Get OpenAI Response")
chat_button.click(openai_chat_interface,
inputs=[user_input, model_input, max_tokens_input],
outputs=openai_response)
# Launch Gradio app
demo.launch()