Team Ai
Apppublic

decodingdatascience/python3jan

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py94 linesDownload Raw Back to root
1# Import necessary libraries
2import openai
3import gradio as gr
4from dotenv import load_dotenv
5import os
6
7# Load environment variables from the .env file
8load_dotenv()
9
10# Retrieve the OpenAI API key
11api_key = os.getenv("OPENAI_API_KEY")
12
13# Check if the API key is loaded properly
14if not api_key:
15    raise ValueError(   
16        "OpenAI API key is not set. Please make sure your .env file contains the line 'OPENAI_API_KEY=<your-api-key>'"
17    )
18
19# Set the API key for OpenAI
20openai.api_key = api_key
21
22# Define the system prompt
23system_prompt = {
24    "role": "system",
25    "content": (
26        "You are a Python master bot designed to answer questions specifically "
27        "related to Python programming. Provide explanations in a way that a 7th grader "
28        "can understand, using clear language and examples. If a non-Python-related question "
29        "is asked, politely decline and redirect the conversation back to Python topics.\n\n"
30        "# Steps\n\n"
31        "1. Identify the Python-related question from the user.\n"
32        "2. Simplify the explanation to ensure a 7th grader can understand it.\n"
33        "3. Provide a relevant example with a brief explanation.\n"
34        "4. If the question is not about Python, politely decline and suggest focusing on Python topics.\n\n"
35        "# Output Format\n\n"
36        "Respond in simple language with explanations, examples, and polite declinations if necessary.\n\n"
37        "# Examples\n\n"
38        "**Example 1:**\n\n"
39        "*Input:* \"How do I create a variable in Python?\"\n\n"
40        "*Output:*\n"
41        "\"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"
42        "```python\nage = 12\n```\nHere, 'age' is the variable name and '12' is the value it's holding.\"\n\n"
43        "**Example 2:**\n\n"
44        "*Input:* \"Can you tell me about the history of the Internet?\"\n\n"
45        "*Output:*\n"
46        "\"I'm here to help with Python programming questions. If you have questions about Python, feel free to ask!\"\n\n"
47        "# Notes\n\n"
48        "- Always ensure the response includes an explanation suitable for a 7th grader.\n"
49        "- Use at least one code example in the explanation when applicable.\n"
50        "- Maintain a friendly and encouraging tone."
51    ),
52}
53
54# Define the chatbot function
55def chatbot(user_input):
56    try:
57        # Create the message structure
58        messages = [
59            system_prompt,
60            {"role": "user", "content": user_input},
61        ]
62
63        # Get the response from OpenAI
64        response = openai.ChatCompletion.create(
65            model="gpt-4",
66            messages=messages,
67            temperature=0,
68            max_tokens=1024,
69            top_p=0.1,
70            frequency_penalty=0,
71            presence_penalty=0,
72        )
73
74        # Return the assistant's reply
75        return response["choices"][0]["message"]["content"]
76    except openai.error.AuthenticationError as e:
77        return (
78            "Authentication Error: Please check if your API key is correctly set in the .env file."
79        )
80    except Exception as e:
81        return f"An error occurred: {str(e)}"
82
83# Create the Gradio interface
84interface = gr.Interface(
85    fn=chatbot,
86    inputs="text",
87    outputs="text",
88    title="Python Master Bot",
89    description="Ask me any Python programming question, and I will answer in a way a 7th grader can understand.",
90)
91
92# Launch the interface
93interface.launch(share=True)
94