File size: 35,457 Bytes
94ecb74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d85aba
 
 
 
 
 
 
94ecb74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
"""
πŸŽ“ Simplified CourseCrafter Agent - Core Functionality Only

Focuses on web search, lesson creation, flashcards, and quizzes without complex MCP dependencies.
"""

import json
from typing import Dict, List, Any, Optional, AsyncGenerator, Callable
from datetime import datetime

from .llm_client import LlmClient, Message
from ..types import (
    GenerationOptions, ProgressUpdate, StreamChunk
)
from ..utils.config import config
from ..utils.helpers import smart_json_loads

from ..tools.web_research import research_topic
from ..tools.image_generation import (
    generate_educational_image,
    extract_image_placeholders,
    replace_image_placeholders
)

class SimpleCourseAgent:
    """
    Main agent for course generation:
    - Web search for research
    - Lesson generation
    - Flashcard creation
    - Quiz generation
    - Image generation
    """

    def __init__(self):
        self.llm_client = LlmClient()
        self.system_prompt = self._get_system_prompt()
        self.default_provider = config.get_default_llm_provider()
        print(f"πŸŽ“ SimpleCourseAgent initialized with default provider: {self.default_provider}")

    def _get_system_prompt(self) -> str:
        """Get the system prompt for course generation"""
        return """You are Course Creator AI, an expert educational content creator and course designer. Your goal is to create high-quality educational content that is comprehensive, well-structured, engaging, and tailored to the needs of lerners. Create detailed lessons, generate flashcards, quizzes, and educational images.

## Your Capabilities:
- Research topics thoroughly using web search and content analysis
- Generate engaging, structured lesson content with clear explanations and objectives
- Generate interactive flashcards for key concepts for repetition learning
- Create multiple-choice quizzes to reinforce learning
- Generate educational images and visual aids
- Ensure content quality and educational effectiveness

## Quality Standards:
- Content must be accurate, well-researched, and up-to-date
- Lessons should build upon each other logically
- Include practical examples and real-world applications
- Maintain appropriate difficulty level for target audience
- Ensure content is engaging and interactive
- Provide clear learning objectives and outcomes

## RESPONSE FORMAT:
- Always respond with valid JSON only. No markdown, no explanations, just pure JSON.
- Follow the format below for each type of content:

For course planning, return:
{
  "title": "Course title",
  "description": "Brief description",
  "learning_objectives": ["objective1", "objective2"],
  "lesson_titles": ["Lesson 1 title", "Lesson 2 title"],
  "estimated_duration": 60
}

For lessons, return:
{
  "title": "Lesson title",
  "duration": 15,
  "objectives": ["Learn X", "Understand Y"],
  "content": "Detailed lesson content in markdown",
  "key_takeaways": ["Key point 1", "Key point 2"],
  "examples": ["Example 1", "Example 2"]
}

For flashcards, return:
[
  {
    "question": "What is X?",
    "answer": "X is...",
    "category": "Category name"
  }
]

For quizzes, return:
{
  "title": "Quiz title",
  "instructions": "Instructions text",
  "questions": [
    {
      "question": "Question text?",
      "options": ["A) Option 1", "B) Option 2", "C) Option 3", "D) Option 4"],
      "correct_answer": "A",
      "explanation": "Why A is correct"
    }
  ]
}

Always strive to create courses that are not just informative, but are easy to understand, engaging, learning experiences."""

    def update_provider_config(self, provider: str, api_key: str = None, **kwargs):
        """Update provider configuration and reinitialize client"""
        success = self.llm_client.update_provider_config(provider, api_key, **kwargs)
        if success:
            self.default_provider = provider
        return success

    async def generate_course(
        self,
        topic: str,
        options: GenerationOptions,
        provider: Optional[str] = None,
        progress_callback: Optional[Callable[[ProgressUpdate], None]] = None
    ) -> AsyncGenerator[StreamChunk, None]:
        """Generate a complete course on the given topic"""
        
        # Use provided provider or fall back to default
        if provider is None:
            provider = self.default_provider

        print(f"πŸš€ Starting course generation for: {topic}")
        print(f"πŸ“‹ Options: {options.lesson_count} lessons, {options.difficulty.value} difficulty")
        print(f"🧠 Using LLM provider: {provider}")

        try:
            # Step 1: Research the topic
            if progress_callback:
                progress_callback(ProgressUpdate(
                    stage="research",
                    progress=0.1,
                    message="Researching topic..."
                ))

            print("πŸ” Step 1: Researching topic...")
            research_data = await self._research_topic(topic, provider)
            # Store research data for use in lesson generation
            self._current_research = research_data
            yield StreamChunk(type="progress", content="βœ… Research completed")

            # Step 2: Generate course structure
            if progress_callback:
                progress_callback(ProgressUpdate(
                    stage="planning",
                    progress=0.3,
                    message="Planning course structure..."
                ))

            print("πŸ“‹ Step 2: Planning course structure...")
            course_plan = await self._plan_course(topic, options, provider)
            print(f"βœ… Course plan created: {course_plan.get('title', 'Unknown')}")
            yield StreamChunk(type="progress", content="βœ… Course structure planned")

            # Step 3: Generate lessons
            if progress_callback:
                progress_callback(ProgressUpdate(
                    stage="lessons",
                    progress=0.5,
                    message="Creating lessons..."
                ))

            print("πŸ“š Step 3: Generating lessons...")
            lessons = await self._generate_lessons(course_plan, options, provider)
            print(f"βœ… Generated {len(lessons)} lessons")
            yield StreamChunk(type="progress", content="βœ… Lessons created")

            # Step 4: Generate flashcards
            if progress_callback and options.include_flashcards:
                progress_callback(ProgressUpdate(
                    stage="flashcards",
                    progress=0.7,
                    message="Creating flashcards..."
                ))

            flashcards = []
            if options.include_flashcards:
                print("πŸƒ Step 4: Generating flashcards...")
                flashcards = await self._generate_flashcards(lessons, provider, options.difficulty.value)
                print(f"βœ… Generated {len(flashcards)} flashcards")
                yield StreamChunk(type="progress", content="βœ… Flashcards created")

            # Step 5: Generate quiz
            if progress_callback and options.include_quizzes:
                progress_callback(ProgressUpdate(
                    stage="quiz",
                    progress=0.8,
                    message="Creating quiz..."
                ))

            quiz = None
            if options.include_quizzes:
                print("πŸ“ Step 5: Generating quiz...")
                quiz = await self._generate_quiz(lessons, provider, options.difficulty.value)
                print(f"βœ… Generated quiz with {len(quiz.get('questions', []))} questions")
                yield StreamChunk(type="progress", content="βœ… Quiz created")

            # Step 6: Generate images (if requested)
            images = []
            if options.include_images:
                if progress_callback:
                    progress_callback(ProgressUpdate(
                        stage="images",
                        progress=0.9,
                        message="Generating images..."
                    ))

                print("πŸ–ΌοΈ Step 6: Generating images...")
                try:
                    images = await self._generate_images(lessons)
                    print(f"βœ… Generated {len(images)} images")
                    yield StreamChunk(type="progress", content="βœ… Images generated")

                    # Attach images to lessons
                    for i, lesson in enumerate(lessons):
                        if i < len(images):
                            lesson["images"] = [images[i]]
                    
                    print(f"πŸ“Ž Attached images to {min(len(lessons), len(images))} lessons")
                    
                except Exception as e:
                    print(f"⚠️ Image generation failed: {e}")
                    # Continue without images
                    images = []
                    yield StreamChunk(type="progress", content="⚠️ Images skipped (generation failed)")
            else:
                print("πŸ–ΌοΈ Image generation skipped (not requested)")
                yield StreamChunk(type="progress", content="⏭️ Images skipped")

            # Final assembly
            if progress_callback:
                progress_callback(ProgressUpdate(
                    stage="completion",
                    progress=1.0,
                    message="Course generation complete!"
                ))

            print("πŸ”„ Assembling final course data...")
            yield StreamChunk(type="progress", content="βœ… Finalizing course")

            # Yield the complete course
            course_data = {
                "course_info": course_plan,
                "lessons": lessons,
                "flashcards": flashcards,
                "quiz": quiz,
                "images": images,
                "generated_at": datetime.now().isoformat()
            }

            print("πŸŽ‰ Course generation completed successfully!")
            print(f"πŸ“Š Final course data: {len(lessons)} lessons, {len(flashcards)} flashcards, {len(quiz.get('questions', []) if quiz else [])} quiz questions")

            yield StreamChunk(type="course_complete", content=json.dumps(course_data, indent=2))

        except Exception as e:
            error_msg = f"Error generating course: {str(e)}"
            print(f"❌ {error_msg}")
            import traceback
            traceback.print_exc()
            yield StreamChunk(type="error", content=error_msg)

    async def _research_topic(self, topic: str, provider: str = None) -> Dict[str, Any]:
        """Research the topic using web search and content extraction"""
        print(f"πŸ” Researching topic: {topic}")

        # Use the provided provider or fall back to default
        research_provider = provider or self.default_provider
        print(f"🧠 Using LLM provider for research: {research_provider}")

        try:
            # Use the new web research tools with the specified provider
            research_results = await research_topic(topic, llm_provider=research_provider)

            if research_results and research_results.get("success"):
                print(f"βœ… Web research successful: {research_results.get('successful_sources', 0)} sources")
                return research_results
            else:
                print(f"⚠️ Web research failed or returned no results")

        except Exception as e:
            print(f"⚠️ Web research failed: {e}")

        # Fallback to enhanced simulated research
        print("πŸ”„ Using fallback research data")
        return {
            "topic": topic,
            "key_concepts": [
                f"Fundamental concepts of {topic}",
                f"Practical applications of {topic}",
                f"Tools and resources for {topic}",
                f"Best practices in {topic}",
                f"Common challenges in {topic}"
            ],
            "sources": [
                f"Educational resources for {topic}",
                f"Documentation and tutorials for {topic}",
                f"Community forums and discussions about {topic}",
                f"Official guides and specifications for {topic}"
            ],
            "research_summary": f"Comprehensive research on {topic} covering fundamental concepts, practical applications, available tools and resources, best practices, and common challenges. This research would typically include web search results, documentation extraction, and content analysis from multiple authoritative sources.",
            "success": True,
            "fallback": True
        }

    async def _plan_course(
        self,
        topic: str,
        options: GenerationOptions,
        provider: str
    ) -> Dict[str, Any]:
        """Plan the overall course structure"""

        print(f"πŸ“‹ Planning course for {topic} with {options.lesson_count} lessons")

        prompt = f"""Create a course plan for: "{topic}"

Requirements:
- {options.lesson_count} lessons
- {options.difficulty.value} difficulty level
- {options.max_lesson_duration} minutes per lesson

Return ONLY a JSON object with:
- title: Course title
- description: Brief description
- learning_objectives: Array of 3-5 objectives
- lesson_titles: Array of lesson titles
- estimated_duration: Total course duration

Focus on practical, engaging content. Return only valid JSON, no other text. Do not wrap the JSON in markdown code blocks or backticks."""

        messages = [
            Message(role="system", content=self.system_prompt),
            Message(role="user", content=prompt)
        ]

        try:
            response_text = await self._get_llm_response(provider, messages)
            print(f"πŸ“‹ LLM response for course plan: {response_text[:200]}...")

            # Try to parse JSON with smart parser
            course_plan = smart_json_loads(response_text)
            if course_plan is not None:
                print(f"βœ… Successfully parsed course plan JSON")
                return course_plan
            else:
                raise ValueError("Failed to extract valid JSON from response")

        except Exception as e:
            print(f"❌ JSON parsing failed for course plan: {e}")
            print(f"Raw response: {response_text}")
            # Fallback if JSON parsing fails
            return {
                "title": f"Course: {topic}",
                "description": f"A comprehensive introduction to {topic}",
                "learning_objectives": [
                    f"Understand the fundamentals of {topic}",
                    f"Apply key concepts of {topic}",
                    f"Analyze real-world applications of {topic}"
                ],
                "lesson_titles": [f"Lesson {i+1}: {topic} Fundamentals" for i in range(options.lesson_count)],
                "estimated_duration": options.lesson_count * options.max_lesson_duration
            }
        except Exception as e:
            print(f"❌ Error in course planning: {e}")
            # Return fallback
            return {
                "title": f"Course: {topic}",
                "description": f"A comprehensive introduction to {topic}",
                "learning_objectives": [
                    f"Understand the fundamentals of {topic}",
                    f"Apply key concepts of {topic}",
                    f"Analyze real-world applications of {topic}"
                ],
                "lesson_titles": [f"Lesson {i+1}: {topic} Basics" for i in range(options.lesson_count)],
                "estimated_duration": options.lesson_count * options.max_lesson_duration
            }

    async def _generate_lessons(
        self,
        course_plan: Dict[str, Any],
        options: GenerationOptions,
        provider: str
    ) -> List[Dict[str, Any]]:
        """Generate detailed lesson content"""

        lessons = []
        lesson_titles = course_plan.get("lesson_titles", [])
        print(f"πŸ“š Generating {len(lesson_titles)} lessons")

        for i, title in enumerate(lesson_titles):
            print(f"πŸ“– Generating lesson {i+1}: {title}")

            # Include research data in the prompt
            research_context = ""
            if hasattr(self, '_current_research') and self._current_research:
                research_context = f"""
Research Context:
{self._current_research.get('research_summary', '')}

Key Concepts: {', '.join(self._current_research.get('key_concepts', [])[:3])}
"""

            # Create difficulty-specific guidelines
            difficulty_guidelines = {
                "beginner": """
- Use simple, clear language and avoid technical jargon
- Explain every concept from the ground up with no assumed prior knowledge
- Include step-by-step instructions with detailed explanations for each step
- Use basic, relatable examples that anyone can understand
- Focus on fundamental concepts and practical applications
- Include plenty of context and background information
- Break down complex ideas into smaller, digestible parts""",
                "intermediate": """
- Use some technical terminology but explain it when first introduced
- Assume basic familiarity with the subject area
- Include moderately complex examples that build on fundamental knowledge
- Focus on practical applications and real-world scenarios
- Introduce some advanced concepts but explain them thoroughly
- Include best practices and common patterns
- Balance theory with hands-on practice""",
                "advanced": """
- Use technical language and industry-standard terminology
- Assume solid foundational knowledge in the subject area
- Include complex, real-world examples and edge cases
- Focus on advanced techniques, optimization, and expert-level practices
- Discuss trade-offs, limitations, and alternative approaches
- Include cutting-edge developments and research
- Emphasize problem-solving and critical thinking"""
            }

            prompt = f"""Create comprehensive, detailed educational content for: "{title}"

This is lesson {i+1} of {len(lesson_titles)} in a course about "{course_plan.get('title', '')}"

{research_context}

Requirements:
- Duration: {options.max_lesson_duration} minutes
- Difficulty Level: {options.difficulty.value.upper()}

DIFFICULTY-SPECIFIC GUIDELINES for {options.difficulty.value.upper()} level:
{difficulty_guidelines.get(options.difficulty.value, difficulty_guidelines["intermediate"])}

Content Requirements:
- Create EXTENSIVE, thorough content that truly teaches the topic (aim for 2000+ words)
- Include multiple practical examples with code/step-by-step instructions
- Provide detailed explanations that help students understand complex concepts
- Include real-world applications and use cases
- Add troubleshooting tips and common pitfalls
- Make content comprehensive enough to actually learn from
- Include image placeholders where visual aids would be helpful

IMPORTANT: When you want to include an educational image, use this format:
{{{{IMAGE_PLACEHOLDER:{title}:Description of the image needed}}}}

LIMIT: Use a MAXIMUM of 3 image placeholders per lesson. Choose the most important visual aids.

For example:
{{{{IMAGE_PLACEHOLDER:{title}:Diagram showing the main components}}}}
{{{{IMAGE_PLACEHOLDER:{title}:Screenshot of the user interface}}}}
{{{{IMAGE_PLACEHOLDER:{title}:Flowchart of the process}}}}

The content should be substantial and educational. Include sections like:
- Introduction with context and importance
- Core concepts with detailed explanations
- Multiple practical examples with code/instructions
- Step-by-step tutorials
- Best practices and tips
- Common mistakes to avoid
- Real-world applications
- Further resources and next steps

Return ONLY a JSON object with:
- title: Lesson title
- duration: Estimated duration
- objectives: Learning objectives for this lesson (3-5 specific objectives)
- content: EXTENSIVE lesson content in markdown format (2000+ words, with image placeholders)
- key_takeaways: Array of 5-7 key points
- examples: Array of 3-5 detailed practical examples with explanations

Return only valid JSON, no other text. Do not wrap the JSON in markdown code blocks or backticks."""

            messages = [
                Message(role="system", content=self.system_prompt),
                Message(role="user", content=prompt)
            ]

            try:
                response_text = await self._get_llm_response(provider, messages)
                print(f"πŸ“– LLM response for lesson {i+1}: {response_text[:100]}...")

                lesson_data = smart_json_loads(response_text)
                if lesson_data is not None:
                    lessons.append(lesson_data)
                    print(f"βœ… Successfully generated lesson {i+1}")
                else:
                    raise ValueError("Failed to extract valid JSON from response")

            except Exception as e:
                print(f"❌ JSON parsing failed for lesson {i+1}: {e}")
                # Fallback lesson structure
                lessons.append({
                    "title": title,
                    "duration": options.max_lesson_duration,
                    "objectives": [f"Learn about {title}"],
                    "content": f"# {title}\n\nThis lesson covers the fundamentals of {title}.\n\n## Key Concepts\n\n- Important concept 1\n- Important concept 2\n- Important concept 3\n\n## Examples\n\nHere are some practical examples related to {title}...",
                    "key_takeaways": [f"Key concept from {title}", f"Important principle of {title}"],
                    "examples": [f"Example 1 related to {title}", f"Example 2 related to {title}"]
                })
            except Exception as e:
                print(f"❌ Error generating lesson {i+1}: {e}")
                # Fallback lesson structure
                lessons.append({
                    "title": title,
                    "duration": options.max_lesson_duration,
                    "objectives": [f"Learn about {title}"],
                    "content": f"# {title}\n\nDetailed content about {title}...",
                    "key_takeaways": [f"Key concept from {title}"],
                    "examples": [f"Example related to {title}"]
                })

        return lessons

    async def _generate_flashcards(
        self,
        lessons: List[Dict[str, Any]],
        provider: str,
        difficulty: str = "intermediate"
    ) -> List[Dict[str, Any]]:
        """Generate flashcards from lesson content with difficulty-appropriate complexity"""

        print(f"πŸƒ Generating {difficulty} level flashcards from lesson content")

        # Combine all lesson content
        all_content = "\n\n".join([
            lesson.get("content", "") + "\n" +
            "\n".join(lesson.get("key_takeaways", []))
            for lesson in lessons
        ])

        # Create difficulty-specific flashcard guidelines
        flashcard_guidelines = {
            "beginner": """
- Focus on basic definitions and simple facts
- Use clear, simple language in both questions and answers
- Test fundamental concepts and terminology
- Include basic examples and straightforward explanations
- Avoid complex relationships or multi-step reasoning
- Keep answers concise and direct""",
            "intermediate": """
- Include concepts, relationships, and applications
- Test understanding of how concepts connect
- Use moderate complexity in questions and explanations
- Include practical examples and use cases
- Test both knowledge and basic application
- Balance definitions with conceptual understanding""",
            "advanced": """
- Focus on complex principles, applications, and analysis
- Test deep understanding and critical thinking
- Include challenging scenarios and edge cases
- Test ability to synthesize and evaluate information
- Include questions about trade-offs and best practices
- Emphasize expert-level insights and nuanced understanding"""
        }

        prompt = f"""Create flashcards based on this lesson content:

{all_content[:2000]}...

DIFFICULTY LEVEL: {difficulty.upper()}

FLASHCARD GUIDELINES for {difficulty.upper()} level:
{flashcard_guidelines.get(difficulty, flashcard_guidelines["intermediate"])}

Generate 10-15 flashcards covering the most important concepts at the {difficulty} level.

Return ONLY a JSON array where each flashcard has:
- question: The question/prompt
- answer: The answer/explanation
- category: Which lesson/topic this relates to

Ensure flashcards match the {difficulty} difficulty level. Return only valid JSON, no other text. Do not wrap the JSON in markdown code blocks or backticks."""

        messages = [
            Message(role="system", content=self.system_prompt),
            Message(role="user", content=prompt)
        ]

        try:
            response_text = await self._get_llm_response(provider, messages)
            print(f"πŸƒ LLM response for flashcards: {response_text[:100]}...")

            flashcards = smart_json_loads(response_text)
            if flashcards is not None:
                print(f"βœ… Successfully generated {len(flashcards)} flashcards")
                return flashcards
            else:
                raise ValueError("Failed to extract valid JSON from response")

        except Exception as e:
            print(f"❌ JSON parsing failed for flashcards: {e}")
            # Fallback flashcards
            return [
                {
                    "question": f"What is the main concept in {lesson.get('title', 'this lesson')}?",
                    "answer": f"The main concept is related to {lesson.get('title', 'the lesson topic')}",
                    "category": lesson.get('title', 'General')
                }
                for lesson in lessons[:5]  # Limit to 5 fallback cards
            ]
        except Exception as e:
            print(f"❌ Error generating flashcards: {e}")
            return []

    async def _generate_quiz(
        self,
        lessons: List[Dict[str, Any]],
        provider: str,
        difficulty: str = "intermediate"
    ) -> Dict[str, Any]:
        """Generate a multiple-choice quiz with difficulty-appropriate questions"""

        print(f"πŸ“ Generating {difficulty} level quiz from lesson content")

        # Combine lesson content
        all_content = "\n\n".join([
            lesson.get("content", "") + "\n" +
            "\n".join(lesson.get("key_takeaways", []))
            for lesson in lessons
        ])

        # Create difficulty-specific quiz guidelines
        quiz_guidelines = {
            "beginner": """
- Focus on basic recall and recognition questions
- Test fundamental concepts and definitions
- Use simple, clear language in questions
- Include straightforward examples
- Avoid trick questions or complex scenarios
- Test one concept per question""",
            "intermediate": """
- Include application and analysis questions
- Test understanding of relationships between concepts
- Use moderate complexity in scenarios
- Include some problem-solving questions
- Test ability to apply knowledge to new situations
- Mix recall with application questions""",
            "advanced": """
- Focus on analysis, synthesis, and evaluation questions
- Test complex problem-solving abilities
- Include multi-step reasoning questions
- Use challenging real-world scenarios
- Test ability to compare and contrast approaches
- Include questions about trade-offs and limitations"""
        }

        prompt = f"""Create a 10-question multiple-choice quiz based on this content:

{all_content[:2000]}...

DIFFICULTY LEVEL: {difficulty.upper()}

QUIZ GUIDELINES for {difficulty.upper()} level:
{quiz_guidelines.get(difficulty, quiz_guidelines["intermediate"])}

Return ONLY a JSON object with:
- title: Quiz title
- instructions: Brief instructions
- questions: Array of question objects

Each question should have:
- question: The question text
- options: Array of 4 multiple choice options (A, B, C, D)
- correct_answer: The letter of the correct answer
- explanation: Why this answer is correct

Ensure questions match the {difficulty} difficulty level. Return only valid JSON, no other text. Do not wrap the JSON in markdown code blocks or backticks."""

        messages = [
            Message(role="system", content=self.system_prompt),
            Message(role="user", content=prompt)
        ]

        try:
            response_text = await self._get_llm_response(provider, messages)
            print(f"πŸ“ LLM response for quiz: {response_text[:100]}...")

            quiz = smart_json_loads(response_text)
            if quiz is not None:
                print(f"βœ… Successfully generated quiz with {len(quiz.get('questions', []))} questions")
                return quiz
            else:
                raise ValueError("Failed to extract valid JSON from response")

        except Exception as e:
            print(f"❌ JSON parsing failed for quiz: {e}")
            # Fallback quiz
            return {
                "title": "Course Quiz",
                "instructions": "Choose the best answer for each question.",
                "questions": [
                    {
                        "question": f"What is a key concept from {lesson.get('title', 'this lesson')}?",
                        "options": ["A) Option A", "B) Option B", "C) Option C", "D) Option D"],
                        "correct_answer": "A",
                        "explanation": "This is the correct answer based on the lesson content."
                    }
                    for lesson in lessons[:3]  # Limit to 3 fallback questions
                ]
            }
        except Exception as e:
            print(f"❌ Error generating quiz: {e}")
            return {
                "title": "Course Quiz",
                "instructions": "Choose the best answer for each question.",
                "questions": []
            }

    async def _generate_images(self, lessons: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """Generate educational images for lessons using Pollinations API"""

        print("πŸ–ΌοΈ Generating actual images for lessons using Pollinations API")

        images = []

        # Process each lesson separately to avoid duplication
        for lesson in lessons:
            lesson_title = lesson.get("title", "")
            content = lesson.get("content", "")

            print(f"πŸ“š Processing images for lesson: {lesson_title}")

            # Extract placeholders for this specific lesson
            placeholders = extract_image_placeholders(content)

            if not placeholders:
                print(f"πŸ“ No image placeholders found for {lesson_title}, generating 1 default image")
                # Generate one default image for the lesson
                topic = lesson_title.split(":")[0] if ":" in lesson_title else lesson_title

                try:
                    image_data = await generate_educational_image(lesson_title, topic, "educational")
                    if image_data:
                        images.append(image_data)
                        print(f"βœ… Generated default image for: {lesson_title}")
                    else:
                        print(f"⚠️ Failed to generate default image for: {lesson_title}")
                except Exception as e:
                    print(f"❌ Error generating default image for {lesson_title}: {e}")
            else:
                # Generate images for ALL placeholders to avoid unreplaced ones
                print(f"🎨 Found {len(placeholders)} placeholders for {lesson_title}, generating images for ALL of them")

                for i, placeholder in enumerate(placeholders):
                    placeholder_lesson_title = placeholder["lesson_title"]
                    description = placeholder["description"]

                    try:
                        # Create educational prompt from placeholder description
                        topic = description
                        image_data = await generate_educational_image(placeholder_lesson_title, topic, "educational")

                        if image_data:
                            # Store the specific placeholder description for matching
                            image_data["placeholder_description"] = description
                            image_data["placeholder_full"] = placeholder["placeholder"]
                            images.append(image_data)
                            print(f"βœ… Generated image {i+1}/{len(placeholders)} for {lesson_title}: {description[:50]}...")
                        else:
                            print(f"⚠️ Failed to generate image {i+1} for {lesson_title}: {description[:50]}...")

                    except Exception as e:
                        print(f"❌ Error generating image {i+1} for {lesson_title}: {e}")

        # Replace placeholders in lesson content with actual images
        for lesson in lessons:
            if images:
                lesson["content"] = replace_image_placeholders(lesson["content"], images)

        print(f"βœ… Generated {len(images)} total images and updated lesson content")
        return images

    async def _get_llm_response(self, provider: str, messages: List[Message]) -> str:
        """Get a complete response from the LLM by collecting all streaming chunks"""

        print(f"🧠 Getting LLM response from {provider}")

        response_text = ""

        try:
            async for chunk in self.llm_client.generate_stream(
                provider=provider,
                messages=messages
            ):
                if chunk.type == "text":
                    response_text += chunk.content
                elif chunk.type == "error":
                    raise Exception(f"LLM error: {chunk.content}")

            print(f"βœ… Got LLM response ({len(response_text)} characters)")
            return response_text.strip()

        except Exception as e:
            print(f"❌ Error getting LLM response: {e}")
            raise

    async def refine_course(
        self,
        course_data: Dict[str, Any],
        user_request: str,
        provider: Optional[str] = None
    ) -> Dict[str, Any]:
        """Refine or add to existing course based on user feedback"""
        
        # Use provided provider or fall back to default
        if provider is None:
            provider = self.default_provider

        prompt = f"""The user wants to modify this course:

Current course: {json.dumps(course_data, indent=2)[:1000]}...

User request: "{user_request}"

Please modify the course accordingly. If they want more information about a specific topic, research it and add detailed content. Return the updated course data in the same JSON format."""

        messages = [
            Message(role="system", content=self.system_prompt),
            Message(role="user", content=prompt)
        ]

        try:
            response_text = await self._get_llm_response(provider, messages)
            refined_course = smart_json_loads(response_text)
            if refined_course is not None:
                return refined_course
            else:
                return course_data  # Return original if parsing fails
        except:
            return course_data  # Return original if parsing fails

    def get_available_providers(self) -> List[str]:
        """Get list of available LLM providers"""
        return self.llm_client.get_available_providers()