Akshayram1 commited on
Commit
d37162c
·
verified ·
1 Parent(s): e8d616f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -47
app.py CHANGED
@@ -8,7 +8,7 @@ import json
8
  from pydantic import BaseModel, Field
9
  from typing import List, Optional, Dict
10
  from enum import Enum
11
- from langchain_google_genai import ChatGoogleGenerativeAI
12
 
13
  # Page configuration
14
  st.set_page_config(
@@ -181,7 +181,7 @@ class MaterialCollection(BaseModel):
181
  class QuizQuestion(BaseModel):
182
  question: str
183
  options: List[str]
184
- correct_answer: int # Index of correct option (0-based)
185
  explanation: str
186
 
187
  class Quiz(BaseModel):
@@ -200,18 +200,48 @@ class Projects(BaseModel):
200
 
201
  # Initialize LLM and search tool
202
  def initialize_services():
203
- # Initialize Gemini model
204
- gemini_llm = ChatGoogleGenerativeAI(
205
- model="gemini-2.0-flash-lite",
206
- google_api_key=os.getenv("GOOGLE_API_KEY"),
207
- temperature=0.7,
208
- convert_system_message_to_human=True
209
- )
210
 
211
- # Initialize search tool
212
- search_tool = SerperDevTool(serper_api_key=os.getenv("SERPER_API_KEY"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
- return gemini_llm, search_tool
 
 
 
 
 
 
 
 
 
215
 
216
  def create_agents_and_tasks(topics, expertise_level, llm):
217
  # Create agents
@@ -343,7 +373,7 @@ def display_learning_materials(materials):
343
  </div>
344
  """, unsafe_allow_html=True)
345
  except json.JSONDecodeError as e:
346
- st.error("Error parsing learning materials")
347
  st.write(materials) # Fallback to display raw output
348
 
349
  def display_quiz(quiz):
@@ -381,7 +411,7 @@ def display_quiz(quiz):
381
  st.write(question['explanation'])
382
 
383
  except json.JSONDecodeError as e:
384
- st.error("Error parsing quiz")
385
  st.write(quiz) # Fallback to display raw output
386
 
387
  def display_projects(projects):
@@ -502,16 +532,39 @@ def main():
502
  help="Choose your current level of expertise"
503
  )
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  generate_btn = st.button("🚀 Generate Learning Path", use_container_width=True, type="primary")
506
 
507
  st.markdown("---")
508
  st.markdown("""
509
  <div style="font-size: 0.8rem; color: #666;">
510
- Powered by CrewAI and Gemini 2.0<br>
511
  © 2025 Learning Path Generator
512
  </div>
513
  """, unsafe_allow_html=True)
514
 
 
 
 
 
515
  # Main content area
516
  if not st.session_state.generation_complete and not generate_btn:
517
  render_welcome_screen()
@@ -530,44 +583,55 @@ def main():
530
  <div class='progress-bar'>
531
  <div class='progress'></div>
532
  </div>
533
- <p>Our AI experts are crafting the perfect resources for you using Google's Gemini 2.0.<br>This may take a minute or two.</p>
534
  </div>
535
  """, unsafe_allow_html=True)
536
 
537
  try:
538
- # Initialize Gemini LLM and tools
539
- gemini_llm, search_tool = initialize_services()
540
-
541
- # Create agents and tasks with Gemini
542
- agents, tasks = create_agents_and_tasks(topics, expertise_level, gemini_llm)
543
-
544
- # Create and run crew
545
- crew = Crew(
546
- agents=agents,
547
- tasks=tasks,
548
- process=Process.sequential
549
- )
550
-
551
- result = crew.kickoff({"topics": topic_list, "expertise_level": ExpertiseLevel(expertise_level)})
552
-
553
- # Store results in session state
554
- st.session_state.results = {
555
- "materials": tasks[0].output.raw,
556
- "quiz": tasks[1].output.raw,
557
- "projects": result.pydantic
558
- }
559
- st.session_state.generation_complete = True
560
-
561
- # Rerun to display results
562
- st.rerun()
563
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
  except Exception as e:
565
  st.error(f"🚨 An error occurred: {str(e)}")
566
- # Add more specific error handling for Gemini API issues
567
- if "google_api_key" in str(e).lower():
568
- st.error("There seems to be an issue with the Google API key. Please check your environment variables.")
569
- elif "quota" in str(e).lower():
570
- st.error("API quota exceeded. Please try again later.")
571
 
572
  # Display results if generation is complete
573
  if st.session_state.generation_complete and st.session_state.results:
 
8
  from pydantic import BaseModel, Field
9
  from typing import List, Optional, Dict
10
  from enum import Enum
11
+ from langchain.llms import GoogleGenerativeAI
12
 
13
  # Page configuration
14
  st.set_page_config(
 
181
  class QuizQuestion(BaseModel):
182
  question: str
183
  options: List[str]
184
+ correct_answer: int
185
  explanation: str
186
 
187
  class Quiz(BaseModel):
 
200
 
201
  # Initialize LLM and search tool
202
  def initialize_services():
203
+ # Get API keys
204
+ google_api_key = os.getenv("GOOGLE_API_KEY")
205
+ serper_api_key = os.getenv("SERPER_API_KEY")
206
+
207
+ if not google_api_key:
208
+ st.error("Google API Key not found in environment variables. Please set the GOOGLE_API_KEY.")
209
+ st.stop()
210
 
211
+ if not serper_api_key:
212
+ st.warning("Serper API Key not found. Search functionality may be limited.")
213
+
214
+ try:
215
+ # Initialize Gemini model
216
+ from langchain_google_genai import ChatGoogleGenerativeAI
217
+
218
+ gemini_llm = ChatGoogleGenerativeAI(
219
+ model="gemini-2.0-flash-lite",
220
+ google_api_key=google_api_key,
221
+ temperature=0.7,
222
+ convert_system_message_to_human=True
223
+ )
224
+
225
+ # Test the model connection
226
+ _ = gemini_llm.invoke("Test connection")
227
+
228
+ # Initialize search tool if API key is available
229
+ search_tool = None
230
+ if serper_api_key:
231
+ search_tool = SerperDevTool(serper_api_key=serper_api_key)
232
+
233
+ return gemini_llm, search_tool
234
 
235
+ except ImportError:
236
+ st.error("Required packages not installed. Please install langchain-google-genai.")
237
+ st.stop()
238
+ except Exception as e:
239
+ st.error(f"Error initializing Gemini model: {str(e)}")
240
+ # Fallback to a default model from CrewAI
241
+ from crewai import LLM
242
+ default_llm = LLM(name="openai", model="gpt-3.5-turbo")
243
+ st.warning("Falling back to default model (OpenAI GPT-3.5).")
244
+ return default_llm, None
245
 
246
  def create_agents_and_tasks(topics, expertise_level, llm):
247
  # Create agents
 
373
  </div>
374
  """, unsafe_allow_html=True)
375
  except json.JSONDecodeError as e:
376
+ st.error(f"Error parsing learning materials: {e}")
377
  st.write(materials) # Fallback to display raw output
378
 
379
  def display_quiz(quiz):
 
411
  st.write(question['explanation'])
412
 
413
  except json.JSONDecodeError as e:
414
+ st.error(f"Error parsing quiz: {e}")
415
  st.write(quiz) # Fallback to display raw output
416
 
417
  def display_projects(projects):
 
532
  help="Choose your current level of expertise"
533
  )
534
 
535
+ # Add model selection dropdown
536
+ model_options = [
537
+ "gemini-2.0-flash-lite",
538
+ "gemini-2.0-pro",
539
+ "gpt-3.5-turbo" # Fallback option
540
+ ]
541
+ selected_model = st.selectbox(
542
+ "AI Model",
543
+ options=model_options,
544
+ index=0,
545
+ help="Select the AI model to use"
546
+ )
547
+
548
+ # Store the selected model in session state
549
+ if 'selected_model' not in st.session_state:
550
+ st.session_state.selected_model = selected_model
551
+ elif st.session_state.selected_model != selected_model:
552
+ st.session_state.selected_model = selected_model
553
+
554
  generate_btn = st.button("🚀 Generate Learning Path", use_container_width=True, type="primary")
555
 
556
  st.markdown("---")
557
  st.markdown("""
558
  <div style="font-size: 0.8rem; color: #666;">
559
+ Powered by CrewAI and Google Gemini<br>
560
  © 2025 Learning Path Generator
561
  </div>
562
  """, unsafe_allow_html=True)
563
 
564
+ # Check for API keys
565
+ if not os.getenv("GOOGLE_API_KEY") and st.session_state.selected_model.startswith("gemini"):
566
+ st.warning("⚠️ Google API Key not found. Please add it to your environment variables.", icon="⚠️")
567
+
568
  # Main content area
569
  if not st.session_state.generation_complete and not generate_btn:
570
  render_welcome_screen()
 
583
  <div class='progress-bar'>
584
  <div class='progress'></div>
585
  </div>
586
+ <p>Our AI experts are crafting the perfect resources for you.<br>This may take a minute or two.</p>
587
  </div>
588
  """, unsafe_allow_html=True)
589
 
590
  try:
591
+ # Try-except for better error handling
592
+ try:
593
+ # Initialize Gemini LLM and tools
594
+ llm, search_tool = initialize_services()
595
+
596
+ # Create agents and tasks with Gemini
597
+ agents, tasks = create_agents_and_tasks(topics, expertise_level, llm)
598
+
599
+ # Create and run crew
600
+ crew = Crew(
601
+ agents=agents,
602
+ tasks=tasks,
603
+ process=Process.sequential
604
+ )
605
+
606
+ result = crew.kickoff({"topics": topic_list, "expertise_level": ExpertiseLevel(expertise_level)})
607
+
608
+ # Store results in session state
609
+ st.session_state.results = {
610
+ "materials": tasks[0].output.raw,
611
+ "quiz": tasks[1].output.raw,
612
+ "projects": result.pydantic
613
+ }
614
+ st.session_state.generation_complete = True
615
+
616
+ # Rerun to display results
617
+ st.rerun()
618
+
619
+ except ImportError as ie:
620
+ st.error(f"Missing package: {str(ie)}")
621
+ st.info("Try installing required packages with: `pip install langchain-google-genai crewai pydantic`")
622
+
623
+ except AttributeError as ae:
624
+ st.error(f"Configuration issue: {str(ae)}")
625
+ st.info("This might be a compatibility issue between CrewAI and the LLM integration.")
626
+
627
+ except ValueError as ve:
628
+ st.error(f"Value error: {str(ve)}")
629
+ if "api_key" in str(ve).lower():
630
+ st.info("There seems to be an issue with your API key. Please check if it's correctly set in the .env file.")
631
+
632
  except Exception as e:
633
  st.error(f"🚨 An error occurred: {str(e)}")
634
+ st.info("If the issue persists, try switching to a different AI model in the sidebar.")
 
 
 
 
635
 
636
  # Display results if generation is complete
637
  if st.session_state.generation_complete and st.session_state.results: