File size: 8,798 Bytes
ee35bb2
 
 
 
57018ea
58b6e69
ee35bb2
57018ea
 
 
 
 
 
ee35bb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
from openai import OpenAI
import sys
import io
import json
from dotenv import load_dotenv
import os


load_dotenv()

api_key = os.getenv("OPENAI_API_KEY")

client = OpenAI(api_key=api_key)
SYS_PROMPT_example="""You are given a Python programming topic and an example related to that topic. Based on this information, generate another example that is clear, concise, and easy to understand for someone learning the topic. The new example should reinforce the key concepts of the topic and be similar in structure and difficulty to the original example provided.

Instructions:
    Understand the Topic: Start by identifying the key concept of the Python topic provided.
    Analyze the Example: Review the provided example to understand the teaching approach, level of complexity, and the specific Python syntax or function being used.
    Create a New Example: Develop a new example that mirrors the original example's style but with different variables, context, or problem. Ensure the new example is equally understandable and appropriate for the same learning level.
    Output Only the Example: Return only the new example in the format of a Python code snippet. Do not include explanations or descriptions"""

SYS_PROMPT_chat="""You are given a Python programming topic, a specific example related to that topic, and a user query about the topic. Your task is to provide a response that addresses the user’s query by explaining or clarifying the concept related to the topic. Ensure your response is clear and helps the user understand the topic better.

Instructions:

Understand the Topic: Identify the key concept of the Python topic provided.
Analyze the Example: Review the provided example to understand how it illustrates the concept.
Address the Query: Based on the user query, provide a clear, concise, and accurate response. Explain the concept in the context of the example if necessary.
Format Your Response: Your response should be focused on answering the query and providing relevant explanations or additional examples if needed.
Note: if the user user query is not related to previous example then you can provide the answer based on the topic, leave it example.
"""
SYS_PROMPT_code=""" You are given a piece of Python code from the user. Your task is to execute the code and provide the output of the program. If the code contains errors, return the exact error message clearly. Do not provide explanations or any corrections to the code.
Instructions:
    Execute the Code: Run the provided Python code to determine its output or to identify any errors.
    Provide Output: If the code executes successfully, return only the output of the program.
    Return Error: If the code contains errors, return only the exact error message generated by the Python interpreter.
    Format Your Response: Ensure that the response is limited to the output or error message only, without any additional explanation or correction."""

SYS_PROMPT_example = """
You are an AI tutor designed to help users learn programming concepts in Python. Your task is to provide detailed explanations for subtopics within a broader topic, including descriptions and examples. The subtopics should be related to the current topic and give practical, easy-to-understand examples that can help learners understand the concept better. 

For example, if the current topic is 'Control Structures', you might provide subtopics like 'if statements', 'if-else statements', 'elif statements', and loops. Each subtopic should include:
1. A clear description of the subtopic.
2. A Python code example that demonstrates the subtopic.
3. Output of the example.
4. An explanation of how the code works.

Please provide content based on the topic passed to you. Respond only with the content, not any other text.

For example, if the topic is 'Control Flow', you might provide:
1. 'If Statements'
2. 'If-Else Statements'
3. 'Loops'
"""




#write me system prompt for 5 quize
SYS_PROMPT_quize="""You are given a Python programming topic. Your task is to generate a set of five quiz questions related to the topic. Each question should be clear, concise, and designed to test the user's understanding of the key concepts covered in the topic. For each question, provide four multiple-choice options (A, B, C, D) ."""

questions = [
    {
        "question": "What is the purpose of control structures in Python?",
        "options": ["To control the flow of a program", "To define the structure of data", "To store variables", "To perform mathematical calculations"]
    }
]
def generate_content(topic):
    # Prepare the chat messages to send to the model
    chat_msgs = [
        {"role": "system", "content": SYS_PROMPT_example},  # System prompt to guide the model
        {"role": "user", "content": f"This is Topic: {topic}. Please generate subtopics, their descriptions, and examples."},
    ]

    # Call OpenAI's chat completions API to get a response
    chat_completion = client.chat.completions.create(
        model='gpt-3.5-turbo',  # You can change this to another model if needed
        messages=chat_msgs,
                )

    # Extract the response content from the API
    response = chat_completion.choices[0].message.content



    return response



def get_new_example(topic, current_example):
    chat_msgs = [
        {"role": "system", "content":f'{SYS_PROMPT_example}'},
        {"role": "user", "content": f"This is Topic : {topic}. and current example : {current_example}. you have return only another example and output of this example " }
    ]

    chat_completion = client.chat.completions.create(
        model = 'gpt-3.5-turbo',
        messages=chat_msgs,
        logprobs=True
    )

    response = chat_completion.choices[0].message.content

    return response

def chatbot_response(query, topic, current_code=None, last_output=None):
    # Construct the system message
    context_info = f"This is Topic: {topic}. This is user query: {query}."
    
    # Add context from current code and last output if available
    if current_code:
        context_info += f" Current code being practiced: {current_code}."
    if last_output:
        context_info += f" Last code output: {last_output}."

    # Define chat messages with the context information
    chat_msgs = [
        {"role": "system", "content": SYS_PROMPT_chat},
        {"role": "user", "content": context_info}
    ]

    # Mocking API call to client (replace `client` with your actual OpenAI client object)
    chat_completion = client.chat.completions.create(
        model='gpt-3.5-turbo',
        messages=chat_msgs,
        logprobs=True
    )

    response = chat_completion.choices[0].message.content
    return response

def run_code_with_openai(code):
    chat_msgs = [
        {"role": "system", "content":f'{SYS_PROMPT_code}'},
        {"role": "user", "content": f"This is user code : {code}.  " }
    ]

    chat_completion = client.chat.completions.create(
    model = 'gpt-4o',
    messages=chat_msgs,
    )

    response = chat_completion.choices[0].message.content
    print(response)
    return response

def get_quize(topic):
    # Define system prompt and example response format
    SYS_PROMPT_quize = "You are a helpful assistant that provides quiz questions."

    # Define the message structure and prompt the model for JSON response
    chat_msgs = [
        {"role": "system", "content": f'{SYS_PROMPT_quize}'},
        {"role": "user", "content": (
            f"This is Topic: {topic}. Please return 1 quiz questions, each with 4 options, "
            "and format the response as JSON like this: "
            '{"questions": [{"question": "Question 1 text", "options": ["Option A", "Option B", "Option C", "Option D"]}, '
        )}
    ]

    chat_completion = client.chat.completions.create(
        model='gpt-3.5-turbo',
        messages=chat_msgs
    )

    response_text = chat_completion.choices[0].message.content
    print("Model Response:", response_text)  # For debugging

    # Attempt to parse JSON response
    try:
        response = json.loads(response_text)  # Convert JSON string to Python dictionary
    except json.JSONDecodeError:
        # Handle the case where JSON decoding fails
        print("Error: Invalid JSON response from model.")
        response = {"questions": []}  # Return an empty structure as fallback

    return response

def run_code_locally(code):
    # Capture the output for local code execution
    old_stdout = sys.stdout
    sys.stdout = io.StringIO()

    try:
        exec(code)  # Execute the code
        output = sys.stdout.getvalue()  # Capture the output
    except Exception as e:
        output = f"Error: {str(e)}"  # Capture any errors
    finally:
        sys.stdout = old_stdout  # Restore original stdout

    return output