import os | |
from dotenv import load_dotenv | |
from openai import Client | |
import gradio as gr | |
# Load environment variables from .env file | |
load_dotenv() | |
# Get the value of the environment variable | |
api_key = os.getenv('OPENAI_API_KEY') | |
if not api_key: | |
raise ValueError("API key not found. Please set your OPENAI_API_KEY in the environment.") | |
# Initialize the OpenAI client | |
client = Client(api_key=api_key) | |
def chatbot(input): | |
"""Chatbot function using the OpenAI API""" | |
if input: | |
messages = [ | |
{"role": "system", "content": "You are a helpful and kind AI Assistant."}, | |
{"role": "user", "content": input}, | |
] | |
response = client.chat.complete( | |
engine="text-davinci-003", | |
messages=messages, | |
max_tokens=150, | |
n=1, | |
stop=None, | |
temperature=0.7, | |
) | |
reply = response.choices[0].text | |
return reply | |
input_text = gr.Textbox(lines=7, label="Chat with AI") | |
output_text = gr.Textbox(label="Reply") | |
interface = gr.Interface(fn=chatbot, inputs=input_text, outputs=output_text, title="AI Chatbot", | |
description="Ask anything you want", theme="compact") | |
interface.launch(share=True) | |