ciaochris commited on
Commit
690a5d7
·
verified ·
1 Parent(s): df27d2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -70
app.py CHANGED
@@ -1,87 +1,52 @@
1
  import gradio as gr
2
  from groq import Groq
3
  import os
4
- from functools import lru_cache
5
 
6
- # Initialize Groq client with error handling
7
- if "GROQ_API_KEY" not in os.environ:
8
- raise ValueError("GROQ_API_KEY not found in environment variables.")
9
  client = Groq(api_key=os.environ["GROQ_API_KEY"])
10
 
11
- class EducationalAgent:
12
- def __init__(self, subject, specialization):
13
- self.subject = subject
14
- self.specialization = specialization
15
-
16
- @lru_cache(maxsize=100) # Simple caching mechanism for repeated queries
17
- def generate_response(self, prompt, grade_level):
18
- try:
19
- completion = client.chat.completions.create(
20
- messages=[
21
- {
22
- "role": "system",
23
- "content": f"You are an AI tutor specialized in {self.subject}. Your focus is on {self.specialization}. Adjust your explanations for a {grade_level} level. Provide your response in the following format:\n\nLesson: [Your lesson content here]\n\nQuestion: [A comprehension question related to the lesson]\n\nFeedback: [General feedback or tips related to the topic]",
24
- },
25
- {"role": "user", "content": prompt},
26
- ],
27
- model="llama3-groq-8b-8192-tool-use-preview",
28
- max_tokens=4000,
29
- temperature=0.7,
30
- )
31
- return completion.choices[0].message.content
32
- except Exception as e:
33
- return f"An error occurred: {str(e)}"
34
-
35
- # Create educational agent instances
36
- math_agent = EducationalAgent("Mathematics", "algebra, geometry, and calculus")
37
- science_agent = EducationalAgent("Science", "physics, chemistry, and biology")
38
- literature_agent = EducationalAgent("Literature", "literary analysis and writing skills")
39
- history_agent = EducationalAgent("History", "world history and historical analysis")
40
-
41
- def process_query(query, subject, grade_level):
42
- if len(query.strip()) == 0:
43
- return "Please enter a question.", "", ""
44
- if len(query) > 500:
45
- return "Please limit your question to 500 characters.", "", ""
46
 
47
- # Choose the correct agent based on subject
48
- if subject == "Mathematics":
49
- response = math_agent.generate_response(query, grade_level)
50
- elif subject == "Science":
51
- response = science_agent.generate_response(query, grade_level)
52
- elif subject == "Literature":
53
- response = literature_agent.generate_response(query, grade_level)
54
- elif subject == "History":
55
- response = history_agent.generate_response(query, grade_level)
56
- else:
57
- return "Invalid subject selected.", "", ""
58
 
59
- # Parse the response
60
- lesson, question, feedback = "No lesson available", "No question available", "No feedback available"
61
- parts = response.split("\n\n")
62
- for part in parts:
63
- if part.startswith("Lesson:"):
64
- lesson = part.replace("Lesson:", "").strip()
65
- elif part.startswith("Question:"):
66
- question = part.replace("Question:", "").strip()
67
- elif part.startswith("Feedback:"):
68
- feedback = part.replace("Feedback:", "").strip()
69
-
70
- return lesson, question, feedback
 
 
 
 
 
 
 
71
 
72
- # Create Gradio interface
73
  with gr.Blocks() as demo:
74
  gr.Markdown("# 🎓 Vers3Dynamics Tutor: Your Personal Learning Companion")
75
-
76
  with gr.Row():
77
  with gr.Column(scale=2):
78
  subject = gr.Dropdown(
79
- ["Mathematics", "Science", "History", "Literature"],
80
  label="Subject",
81
  info="Choose the subject of your lesson"
82
  )
83
  difficulty = gr.Radio(
84
- ["Elementary", "Middle School", "High School", "College"],
85
  label="Difficulty Level",
86
  info="Select your proficiency level"
87
  )
@@ -96,7 +61,7 @@ with gr.Blocks() as demo:
96
  lesson_output = gr.Markdown(label="Lesson")
97
  question_output = gr.Markdown(label="Comprehension Question")
98
  feedback_output = gr.Markdown(label="Feedback")
99
-
100
  gr.Markdown("""
101
  ### How to Use
102
  1. Select a subject from the dropdown.
@@ -106,10 +71,17 @@ with gr.Blocks() as demo:
106
  5. Review the AI-generated content to enhance your learning.
107
  6. Feel free to ask follow-up questions or explore new topics!
108
  """)
109
-
 
 
 
 
 
 
 
110
  submit_button.click(
111
- fn=process_query,
112
- inputs=[student_input, subject, difficulty],
113
  outputs=[lesson_output, question_output, feedback_output]
114
  )
115
 
 
1
  import gradio as gr
2
  from groq import Groq
3
  import os
 
4
 
5
+ # Initialize Groq client
 
 
6
  client = Groq(api_key=os.environ["GROQ_API_KEY"])
7
 
8
+ def generate_tutor_output(subject, difficulty, student_input):
9
+ prompt = f"""
10
+ You are an expert tutor in {subject} at the {difficulty} level.
11
+ The student has provided the following input: "{student_input}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ Please generate:
14
+ 1. A brief, engaging lesson on the topic (2-3 paragraphs)
15
+ 2. A thought-provoking examples with answers to check understanding
16
+ 3. Give real world problems that can be solved with the lesson
 
 
 
 
 
 
 
17
 
18
+ Format your response as a JSON object with keys: "lesson", "question", "feedback"
19
+ """
20
+
21
+ completion = client.chat.completions.create(
22
+ messages=[
23
+ {
24
+ "role": "system",
25
+ "content": "You are the world's best AI tutor, renowned for your ability to explain complex concepts in an engaging, clear, and memorable way and giving math examples. Your expertise in {subject} is unparalleled, and you're adept at tailoring your teaching to {difficulty} level students. Your goal is to not just impart knowledge, but to inspire a love for learning and critical thinking.",
26
+ },
27
+ {
28
+ "role": "user",
29
+ "content": prompt,
30
+ }
31
+ ],
32
+ model="llama3-groq-8b-8192-tool-use-preview",
33
+ max_tokens=1000,
34
+ )
35
+
36
+ return completion.choices[0].message.content
37
 
 
38
  with gr.Blocks() as demo:
39
  gr.Markdown("# 🎓 Vers3Dynamics Tutor: Your Personal Learning Companion")
40
+
41
  with gr.Row():
42
  with gr.Column(scale=2):
43
  subject = gr.Dropdown(
44
+ ["Math", "Science", "History", "Literature"],
45
  label="Subject",
46
  info="Choose the subject of your lesson"
47
  )
48
  difficulty = gr.Radio(
49
+ ["Beginner", "Intermediate", "Advanced"],
50
  label="Difficulty Level",
51
  info="Select your proficiency level"
52
  )
 
61
  lesson_output = gr.Markdown(label="Lesson")
62
  question_output = gr.Markdown(label="Comprehension Question")
63
  feedback_output = gr.Markdown(label="Feedback")
64
+
65
  gr.Markdown("""
66
  ### How to Use
67
  1. Select a subject from the dropdown.
 
71
  5. Review the AI-generated content to enhance your learning.
72
  6. Feel free to ask follow-up questions or explore new topics!
73
  """)
74
+
75
+ def process_output(output):
76
+ try:
77
+ parsed = eval(output)
78
+ return parsed["lesson"], parsed["question"], parsed["feedback"]
79
+ except:
80
+ return "Error parsing output", "No question available", "No feedback available"
81
+
82
  submit_button.click(
83
+ fn=lambda s, d, i: process_output(generate_tutor_output(s, d, i)),
84
+ inputs=[subject, difficulty, student_input],
85
  outputs=[lesson_output, question_output, feedback_output]
86
  )
87