🔍 About This Code Showcase
This curated code snippet demonstrates how the Science Learning Materials Builder coordinates 4 specialized AI agents to create complete, age-appropriate science lessons for Grade 4 students (ages 9-10).
Full deployment scripts, API keys, and proprietary curriculum algorithms are omitted for security. This showcase highlights the core multi-agent pipeline, reading level optimization, and lesson packaging system.
📖 Core Algorithm: Educational Content Pipeline
The foundation of the Science Learning Materials Builder is its 4-agent pipeline that researches, illustrates, writes, and packages complete science lessons:
import google.generativeai as genai
from tavily import TavilyClient
from typing import Dict, List
import json
from datetime import datetime
class ScienceLessonPipeline:
"""
4-agent educational content generation system for Grade 4 science.
Creates complete lessons with curriculum alignment, age-appropriate
content, quizzes, activities, and visual prompts.
"""
def __init__(self, gemini_api_key: str, tavily_api_key: str):
genai.configure(api_key=gemini_api_key)
self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
self.tavily = TavilyClient(api_key=tavily_api_key)
self.curriculum_standards = {
'life_science': ['photosynthesis', 'food chains', 'adaptations'],
'earth_science': ['water cycle', 'weather', 'erosion'],
'physical_science': ['states of matter', 'energy', 'simple machines'],
'space_science': ['solar system', 'earth rotation', 'seasons']
}
self.reading_level_specs = {
'target_grade': 3,
'max_sentence_length': 15,
'vocabulary_simplicity': 'elementary',
'use_concrete_examples': True
}
async run_science_lesson_pipeline(self, topic: str) -> Dict:
"""
Execute complete 4-agent lesson generation pipeline.
Args:
topic: Science topic (e.g., "Photosynthesis", "Water Cycle")
Returns:
Complete lesson plan with markdown and PDF paths
"""
print(f"🔬 Creating lesson for: {topic}")
research_data = await self._agent_curriculum_research(topic)
if not research_data['age_appropriate']:
return {'error': f'Topic "{topic}" not suitable for Grade 4'}
visual_prompts = await self._agent_visual_illustrator(topic, research_data)
lesson_content = await self._agent_content_writer(topic, research_data)
packaged_lesson = await self._agent_lesson_packager(
topic,
research_data,
visual_prompts,
lesson_content
)
return {
'topic': topic,
'lesson_path': packaged_lesson['markdown_path'],
'pdf_path': packaged_lesson['pdf_path'],
'visual_prompts': visual_prompts,
'metadata': {
'reading_level': 'Grade 3',
'duration': research_data['recommended_duration'],
'ngss_aligned': True,
'quiz_questions': 7
}
}
🔬 Agent 1: Curriculum Research (Web-Powered + NGSS Validation)
The Curriculum Research Agent searches the web for kid-friendly explanations, validates against NGSS standards, and extracts fun facts:
async _agent_curriculum_research(self, topic: str) -> Dict:
"""
Agent 1: Research topic, validate curriculum alignment, extract fun facts.
Tasks:
1. Search web for kid-friendly educational content
2. Validate against NGSS Grade 4 standards
3. Extract 5 amazing fun facts for 9-year-olds
4. Suggest hands-on activities
5. Assess age-appropriateness with reasoning
"""
search_query = f"{topic} for kids grade 4 science lesson"
search_results = self.tavily.search(
query=search_query,
search_depth="advanced",
max_results=5,
include_domains=["nasa.gov", "kids.nationalgeographic.com", "sciencekids.co.nz"]
)
educational_content = "\n\n".join([
f"Source: {r['url']}\n{r['content']}"
for r in search_results['results']
])
research_prompt = f"""
You are a curriculum research agent for Grade 4 science education.
Topic: {topic}
Educational Resources Found:
{educational_content}
Your tasks:
1. NGSS Validation:
- Check if topic aligns with Grade 4 Next Generation Science Standards
- Identify which NGSS standard(s) this covers
- Confirm age-appropriateness for 9-10 year olds
2. Extract Fun Facts (5 items):
- Find 5 amazing, kid-friendly facts that will excite students
- Must be simple, concrete, and relatable to children's experiences
- Examples: "Some trees can live for over 1,000 years!"
3. Learning Objectives (3 items):
- Write 3 clear learning objectives in simple language
- Use action verbs: understand, identify, explain, describe
4. Hands-On Activity Suggestion:
- Propose one simple experiment or activity kids can do
- Must be safe, use common household items
- Should reinforce the main concept
5. Recommended Lesson Duration:
- Estimate total time needed (30-50 minutes typical)
Return JSON with:
{{
"age_appropriate": true/false,
"reasoning": "why it's suitable or not",
"ngss_standard": "specific standard code",
"fun_facts": ["fact 1", "fact 2", ...],
"learning_objectives": ["obj 1", "obj 2", "obj 3"],
"hands_on_activity": {{
"title": "Activity Name",
"materials": ["item 1", "item 2"],
"steps": ["step 1", "step 2", ...]
}},
"recommended_duration": "45 minutes",
"key_vocabulary": ["word1", "word2", ...]
}}
"""
response = self.model.generate_content(research_prompt)
research_data = self._parse_json_response(response.text)
return research_data
🎨 Agent 2: Visual Illustrator (Educational Image Prompts)
The Visual Illustrator Agent generates prompts for 3 types of educational visuals: diagrams, fun illustrations, and process steps:
async _agent_visual_illustrator(self, topic: str, research_data: Dict) -> Dict:
"""
Agent 2: Generate prompts for 3 educational illustrations.
Visual Types:
1. Educational Diagram: Labeled, clear, scientific
2. Fun Illustration: Cartoon-style, colorful, engaging
3. Process Steps: Step-by-step visual guide
"""
illustration_prompt = f"""
You are an educational illustrator for children's science materials.
Topic: {topic}
Key Concepts: {research_data['learning_objectives']}
Create 3 image generation prompts for educational visuals suitable for 9-year-olds:
1. EDUCATIONAL DIAGRAM:
- Purpose: Show main concept with clear labels
- Style: Clean, simple diagram with minimal text
- Labels: Use large, easy-to-read text
- Colors: Bright, distinct colors for different parts
- Example: "Labeled diagram of photosynthesis showing sunlight, chloroplast,
water, CO2, and oxygen with arrows. Bright colors, simple shapes,
large labels suitable for children."
2. FUN ILLUSTRATION:
- Purpose: Make the topic engaging and memorable
- Style: Cartoon-style, friendly characters
- Mood: Cheerful, inviting, not scary
- Details: Show concept in a fun, relatable way
- Example: "Cute cartoon sun smiling down on a happy green plant making
oxygen bubbles. Bright colors, big eyes, friendly expressions."
3. PROCESS STEPS VISUAL:
- Purpose: Show how something works step-by-step
- Style: Sequential panels (1-2-3) showing progression
- Clarity: Each step clearly distinct
- Numbers: Large step numbers (1, 2, 3, etc.)
- Example: "3-panel sequence showing: 1) plant in sunlight, 2) plant
absorbing water and CO2, 3) plant releasing oxygen.
Simple numbered steps, bright colors."
Return JSON:
{{
"diagram_prompt": "detailed prompt...",
"diagram_caption": "kid-friendly caption",
"fun_illustration_prompt": "detailed prompt...",
"fun_illustration_caption": "kid-friendly caption",
"process_steps_prompt": "detailed prompt...",
"process_steps_caption": "kid-friendly caption"
}}
Constraints for ALL prompts:
- Must be appropriate for children (no scary/violent content)
- Bright, cheerful colors
- Simple, clear visuals
- Large text/labels when used
- No complex scientific jargon in visuals
"""
response = self.model.generate_content(illustration_prompt)
visual_prompts = self._parse_json_response(response.text)
self._save_visual_prompts(topic, visual_prompts)
return visual_prompts
✍️ Agent 3: Content Writer (3rd Grade Reading Level)
The Content Writer Agent creates age-appropriate explanations, vocabulary, and quiz questions optimized for 9-year-olds:
async _agent_content_writer(self, topic: str, research_data: Dict) -> Dict:
"""
Agent 3: Write student-facing content at 3rd grade reading level.
Deliverables:
1. Simple Explanation (3-4 paragraphs)
2. Vocabulary (5 words with kid-friendly definitions)
3. Quiz Questions (5 multiple choice + 2 short answer)
4. Fun Challenge Activity
"""
writing_prompt = f"""
You are a children's science writer creating content for 9-year-old students.
Topic: {topic}
Learning Objectives: {research_data['learning_objectives']}
Fun Facts: {research_data['fun_facts']}
CRITICAL WRITING CONSTRAINTS:
- Reading Level: 3rd grade (Flesch-Kincaid Grade 3)
- Sentence Length: Maximum 15 words per sentence
- Vocabulary: Simple, everyday words (avoid technical jargon)
- Tone: Enthusiastic, encouraging, friendly
- Examples: Use concrete, relatable examples from kids' daily life
TASKS:
1. SIMPLE EXPLANATION (3-4 paragraphs):
Write a clear explanation of {topic} that a 9-year-old can understand.
Guidelines:
- Start with a question or exciting statement
- Use "you" to make it personal
- Compare to things kids know (pets, toys, food, home)
- Keep sentences short and simple
- Use transition words (first, next, then, finally)
- End with why it matters to them
Example style:
"Have you ever wondered how plants make their own food? It's amazing!
Plants are like tiny food factories. They use three simple things:
sunlight, water, and air. Let me tell you how it works..."
2. VOCABULARY (5 words):
Select 5 key terms and define them simply.
Format:
- **Word**: Simple definition in one sentence.
- Use analogies kids understand
- Example: "**Chloroplast**: The tiny food factory inside a plant leaf,
like a kitchen where the plant makes its meals."
3. QUIZ QUESTIONS:
A. Multiple Choice (5 questions):
- Clear question
- 4 answer choices (A, B, C, D)
- Only one correct answer
- Distractors should be plausible but clearly wrong
- Keep questions simple and direct
B. Short Answer (2 questions):
- Ask for explanation in their own words
- Provide sample acceptable answer
- Example: "Why do plants need sunlight? (Sample: Plants use sunlight
to make their food, like we need heat to cook.)"
4. FUN CHALLENGE:
Create a take-home activity that reinforces learning.
- Must be simple, safe, and use household items
- Should produce observable results
- Takes 15-30 minutes
Return JSON with all content organized by section.
"""
response = self.model.generate_content(writing_prompt)
lesson_content = self._parse_json_response(response.text)
reading_level = self._check_reading_level(lesson_content['explanation'])
if reading_level > 4.0:
print(f"⚠️ Warning: Reading level is Grade {reading_level:.1f}, targeting Grade 3")
return lesson_content
📦 Agent 4: Lesson Packager (Markdown + PDF Export)
The Lesson Packaging Agent compiles all outputs into a complete lesson plan with teacher guide and answer key:
async _agent_lesson_packager(self, topic: str, research: Dict,
visuals: Dict, content: Dict) -> Dict:
"""
Agent 4: Package complete lesson into markdown and PDF formats.
Lesson Structure:
1. Teacher Guide (objectives, tips, materials)
2. Student Lesson (explanation, visuals, vocab, quiz)
3. Answer Key (all quiz solutions)
"""
lesson_title = f"Science Lesson: {topic} (Grade 4)"
filename = f"science_lesson_{topic.lower().replace(' ', '_')}_grade4_{datetime.now().strftime('%Y%m%d')}"
markdown_content = f"""
# {lesson_title}
**Target Audience:** Grade 4 (Ages 9-10)
**Duration:** {research['recommended_duration']}
**NGSS Standard:** {research['ngss_standard']}
---
## 📘 TEACHER GUIDE
### Learning Objectives
{self._format_list(research['learning_objectives'])}
### Key Concepts to Emphasize
- {topic} is fundamental to understanding {self._get_category(topic)}
- Students should grasp the main process and why it matters
- Encourage hands-on exploration and questions
### Teaching Tips
1. Start with the fun facts to grab attention
2. Use visual aids prominently (show diagrams)
3. Relate concepts to students' everyday experiences
4. Allow time for the hands-on activity
5. Review vocabulary before the quiz
### Materials Needed
{self._format_list(research['hands_on_activity']['materials'])}
---
## 📖 STUDENT LESSON
### What You'll Learn Today
{self._format_list(research['learning_objectives'])}
### Amazing Facts About {topic}!
{self._format_fun_facts(research['fun_facts'])}
---
### Let's Learn About {topic}!
{content['explanation']}
---
### Visual Learning
**Diagram:** {visuals['diagram_caption']}
*[Educational diagram would appear here]*
**Fun Illustration:** {visuals['fun_illustration_caption']}
*[Cartoon illustration would appear here]*
**Process Steps:** {visuals['process_steps_caption']}
*[Step-by-step visual would appear here]*
---
### 📚 Vocabulary Words
{self._format_vocabulary(content['vocabulary'])}
---
### ✅ Check Your Understanding!
#### Multiple Choice Questions
{self._format_multiple_choice(content['quiz_multiple_choice'])}
#### Short Answer Questions
{self._format_short_answer(content['quiz_short_answer'])}
---
### 🎨 Fun Challenge Activity!
**{research['hands_on_activity']['title']}**
**What You'll Need:**
{self._format_list(research['hands_on_activity']['materials'])}
**What To Do:**
{self._format_numbered_steps(research['hands_on_activity']['steps'])}
---
## 🔑 ANSWER KEY (For Teachers)
### Multiple Choice Answers
{self._format_answer_key_mc(content['quiz_multiple_choice'])}
### Short Answer Sample Responses
{self._format_answer_key_sa(content['quiz_short_answer'])}
---
*Lesson created with AI-powered educational content generation*
*Aligned with Next Generation Science Standards (NGSS)*
"""
markdown_path = self._save_markdown(filename, markdown_content)
pdf_path = self._convert_to_pdf(markdown_path)
return {
'markdown_path': markdown_path,
'pdf_path': pdf_path,
'lesson_title': lesson_title,
'word_count': len(markdown_content.split())
}