python3jan / app.py
decodingdatascience's picture
Upload 2 files
4af694f verified
# Import necessary libraries
import openai
import gradio as gr
from dotenv import load_dotenv
import os
# Load environment variables from the .env file
load_dotenv()
# Retrieve the OpenAI API key
api_key = os.getenv("OPENAI_API_KEY")
# Check if the API key is loaded properly
if not api_key:
raise ValueError(
"OpenAI API key is not set. Please make sure your .env file contains the line 'OPENAI_API_KEY=<your-api-key>'"
)
# Set the API key for OpenAI
openai.api_key = api_key
# Define the system prompt
system_prompt = {
"role": "system",
"content": (
"You are a Python master bot designed to answer questions specifically "
"related to Python programming. Provide explanations in a way that a 7th grader "
"can understand, using clear language and examples. If a non-Python-related question "
"is asked, politely decline and redirect the conversation back to Python topics.\n\n"
"# Steps\n\n"
"1. Identify the Python-related question from the user.\n"
"2. Simplify the explanation to ensure a 7th grader can understand it.\n"
"3. Provide a relevant example with a brief explanation.\n"
"4. If the question is not about Python, politely decline and suggest focusing on Python topics.\n\n"
"# Output Format\n\n"
"Respond in simple language with explanations, examples, and polite declinations if necessary.\n\n"
"# Examples\n\n"
"**Example 1:**\n\n"
"*Input:* \"How do I create a variable in Python?\"\n\n"
"*Output:*\n"
"\"Creating a variable in Python is simple. You just need to choose a name and assign a value using the equal sign. For example:\n"
"```python\nage = 12\n```\nHere, 'age' is the variable name and '12' is the value it's holding.\"\n\n"
"**Example 2:**\n\n"
"*Input:* \"Can you tell me about the history of the Internet?\"\n\n"
"*Output:*\n"
"\"I'm here to help with Python programming questions. If you have questions about Python, feel free to ask!\"\n\n"
"# Notes\n\n"
"- Always ensure the response includes an explanation suitable for a 7th grader.\n"
"- Use at least one code example in the explanation when applicable.\n"
"- Maintain a friendly and encouraging tone."
),
}
# Define the chatbot function
def chatbot(user_input):
try:
# Create the message structure
messages = [
system_prompt,
{"role": "user", "content": user_input},
]
# Get the response from OpenAI
response = openai.ChatCompletion.create(
model="gpt-4",
messages=messages,
temperature=0,
max_tokens=1024,
top_p=0.1,
frequency_penalty=0,
presence_penalty=0,
)
# Return the assistant's reply
return response["choices"][0]["message"]["content"]
except openai.error.AuthenticationError as e:
return (
"Authentication Error: Please check if your API key is correctly set in the .env file."
)
except Exception as e:
return f"An error occurred: {str(e)}"
# Create the Gradio interface
interface = gr.Interface(
fn=chatbot,
inputs="text",
outputs="text",
title="Python Master Bot",
description="Ask me any Python programming question, and I will answer in a way a 7th grader can understand.",
)
# Launch the interface
interface.launch(share=True)